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
|
---|---|---|---|---|
Mastering-Machine-Learning-for-Penetration-Testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import ReachTooltip from '@reach/tooltip';
import tooltipStyles from './Tooltip.css';
import useThemeStyles from '../../useThemeStyles';
const Tooltip = ({
children,
className = '',
...props
}: {
children: React$Node,
className: string,
...
}): React.Node => {
const style = useThemeStyles();
return (
// $FlowFixMe[cannot-spread-inexact] unsafe spread
<ReachTooltip
className={`${tooltipStyles.Tooltip} ${className}`}
style={style}
{...props}>
{children}
</ReachTooltip>
);
};
export default Tooltip;
| 20.486486 | 66 | 0.651134 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const [count, setCount] = (0, _react.useState)(0);
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 5
}
}, /*#__PURE__*/_react.default.createElement("p", {
__source: {
fileName: _jsxFileName,
lineNumber: 17,
columnNumber: 7
}
}, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", {
onClick: () => setCount(count + 1),
__source: {
fileName: _jsxFileName,
lineNumber: 18,
columnNumber: 7
}
}, "Click me"));
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkV4YW1wbGUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJzZXRDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVBLFNBQUFBLFNBQUEsR0FBQTtBQUNBLFFBQUEsQ0FBQUMsS0FBQSxFQUFBQyxRQUFBLElBQUEscUJBQUEsQ0FBQSxDQUFBO0FBRUEsc0JBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEscUJBQUFELEtBQUEsV0FEQSxlQUVBO0FBQUEsSUFBQSxPQUFBLEVBQUEsTUFBQUMsUUFBQSxDQUFBRCxLQUFBLEdBQUEsQ0FBQSxDQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUZBLENBREE7QUFNQSIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QsIHt1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBbY291bnQsIHNldENvdW50XSA9IHVzZVN0YXRlKDApO1xuXG4gIHJldHVybiAoXG4gICAgPGRpdj5cbiAgICAgIDxwPllvdSBjbGlja2VkIHtjb3VudH0gdGltZXM8L3A+XG4gICAgICA8YnV0dG9uIG9uQ2xpY2s9eygpID0+IHNldENvdW50KGNvdW50ICsgMSl9PkNsaWNrIG1lPC9idXR0b24+XG4gICAgPC9kaXY+XG4gICk7XG59XG4iXX0= | 76.205128 | 1,252 | 0.786047 |
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.
*
*/
'use strict';
const babelRegister = require('@babel/register');
babelRegister({
ignore: [/[\\\/](build|server\/server|node_modules)[\\\/]/],
presets: [['react-app', {runtime: 'automatic'}]],
plugins: ['@babel/transform-modules-commonjs'],
});
const express = require('express');
const compress = require('compression');
const {readFileSync} = require('fs');
const path = require('path');
const renderToString = require('./render-to-string');
const renderToStream = require('./render-to-stream');
const renderToBuffer = require('./render-to-buffer');
const {JS_BUNDLE_DELAY} = require('./delays');
const PORT = process.env.PORT || 4000;
const app = express();
app.use(compress());
app.get(
'/',
handleErrors(async function (req, res) {
await waitForWebpack();
renderToStream(req.url, res);
})
);
app.get(
'/string',
handleErrors(async function (req, res) {
await waitForWebpack();
renderToString(req.url, res);
})
);
app.get(
'/stream',
handleErrors(async function (req, res) {
await waitForWebpack();
renderToStream(req.url, res);
})
);
app.get(
'/buffer',
handleErrors(async function (req, res) {
await waitForWebpack();
renderToBuffer(req.url, res);
})
);
app.use(express.static('build'));
app.use(express.static('public'));
app
.listen(PORT, () => {
console.log(`Listening at ${PORT}...`);
})
.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error;
}
const isPipe = portOrPipe => Number.isNaN(portOrPipe);
const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
});
function handleErrors(fn) {
return async function (req, res, next) {
try {
return await fn(req, res);
} catch (x) {
next(x);
}
};
}
async function waitForWebpack() {
while (true) {
try {
readFileSync(path.resolve(__dirname, '../build/main.js'));
return;
} catch (err) {
console.log(
'Could not find webpack build output. Will retry in a second...'
);
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
| 22.862385 | 72 | 0.613846 |
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 {Fragment, useCallback, useState} from 'react';
export function ListItem({item, removeItem, toggleItem}) {
const handleDelete = useCallback(() => {
removeItem(item);
}, [item, removeItem]);
const handleToggle = useCallback(() => {
toggleItem(item);
}, [item, toggleItem]);
return (
<li>
<button onClick={handleDelete}>Delete</button>
<label>
<input
checked={item.isComplete}
onChange={handleToggle}
type="checkbox"
/>{' '}
{item.text}
</label>
</li>
);
}
export function List(props) {
const [newItemText, setNewItemText] = useState('');
const [items, setItems] = useState([
{id: 1, isComplete: true, text: 'First'},
{id: 2, isComplete: true, text: 'Second'},
{id: 3, isComplete: false, text: 'Third'},
]);
const [uid, setUID] = useState(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 => {
if (event.key === 'Enter') {
handleClick();
}
},
[handleClick],
);
const handleChange = useCallback(
event => {
setNewItemText(event.currentTarget.value);
},
[setNewItemText],
);
const removeItem = useCallback(
itemToRemove => setItems(items.filter(item => item !== itemToRemove)),
[items],
);
const toggleItem = useCallback(
itemToToggle => {
// Dont use indexOf()
// because editing props in DevTools creates a new Object.
const index = items.findIndex(item => item.id === itemToToggle.id);
setItems(
items
.slice(0, index)
.concat({
...itemToToggle,
isComplete: !itemToToggle.isComplete,
})
.concat(items.slice(index + 1)),
);
},
[items],
);
return (
<Fragment>
<h1>List</h1>
<input
type="text"
placeholder="New list item..."
value={newItemText}
onChange={handleChange}
onKeyPress={handleKeyPress}
/>
<button disabled={newItemText === ''} onClick={handleClick}>
<span role="img" aria-label="Add item">
Add
</span>
</button>
<ul>
{items.map(item => (
<ListItem
key={item.id}
item={item}
removeItem={removeItem}
toggleItem={toggleItem}
/>
))}
</ul>
</Fragment>
);
}
| 21.674419 | 74 | 0.540356 |
owtf | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
// Used in next.config.js to remove the process transitive dependency.
module.exports = {
env: {},
cwd() {},
};
| 16.7 | 70 | 0.636364 |
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, itThrowsWhenRendering} =
ReactDOMServerIntegrationUtils(initModules);
describe('ReactDOMServerIntegrationSelect', () => {
let options;
beforeEach(() => {
resetModules();
options = [
<option key={1} value="foo" id="foo">
Foo
</option>,
<option key={2} value="bar" id="bar">
Bar
</option>,
<option key={3} value="baz" id="baz">
Baz
</option>,
];
});
// a helper function to test the selected value of a <select> element.
// takes in a <select> DOM element (element) and a value or array of
// values that should be selected (selected).
const expectSelectValue = (element, selected) => {
if (!Array.isArray(selected)) {
selected = [selected];
}
// the select DOM element shouldn't ever have a value or defaultValue
// attribute; that is not how select values are expressed in the DOM.
expect(element.getAttribute('value')).toBe(null);
expect(element.getAttribute('defaultValue')).toBe(null);
['foo', 'bar', 'baz'].forEach(value => {
const expectedValue = selected.indexOf(value) !== -1;
const option = element.querySelector(`#${value}`);
expect(option.selected).toBe(expectedValue);
});
};
itRenders('a select with a value and an onChange', async render => {
const e = await render(
<select value="bar" onChange={() => {}}>
{options}
</select>,
);
expectSelectValue(e, 'bar');
});
itRenders('a select with a value and readOnly', async render => {
const e = await render(
<select value="bar" readOnly={true}>
{options}
</select>,
);
expectSelectValue(e, 'bar');
});
itRenders('a select with a multiple values and an onChange', async render => {
const e = await render(
<select value={['bar', 'baz']} multiple={true} onChange={() => {}}>
{options}
</select>,
);
expectSelectValue(e, ['bar', 'baz']);
});
itRenders('a select with a multiple values and readOnly', async render => {
const e = await render(
<select value={['bar', 'baz']} multiple={true} readOnly={true}>
{options}
</select>,
);
expectSelectValue(e, ['bar', 'baz']);
});
itRenders('a select with a value and no onChange/readOnly', async render => {
// this configuration should raise a dev warning that value without
// onChange or readOnly is a mistake.
const e = await render(<select value="bar">{options}</select>, 1);
expectSelectValue(e, 'bar');
});
itRenders('a select with a defaultValue', async render => {
const e = await render(<select defaultValue="bar">{options}</select>);
expectSelectValue(e, 'bar');
});
itRenders('a select value overriding defaultValue', async render => {
const e = await render(
<select value="bar" defaultValue="baz" readOnly={true}>
{options}
</select>,
1,
);
expectSelectValue(e, 'bar');
});
itRenders(
'a select with options that use dangerouslySetInnerHTML',
async render => {
const e = await render(
<select defaultValue="baz" value="bar" readOnly={true}>
<option
id="foo"
value="foo"
dangerouslySetInnerHTML={{
__html: 'Foo',
}}>
{undefined}
</option>
<option
id="bar"
value="bar"
dangerouslySetInnerHTML={{
__html: 'Bar',
}}>
{null}
</option>
<option
id="baz"
dangerouslySetInnerHTML={{
__html: 'Baz', // This warns because no value prop is passed.
}}
/>
</select>,
2,
);
expectSelectValue(e, 'bar');
},
);
itThrowsWhenRendering(
'a select with option that uses dangerouslySetInnerHTML and 0 as child',
async render => {
await render(
<select defaultValue="baz" value="foo" readOnly={true}>
<option
id="foo"
value="foo"
dangerouslySetInnerHTML={{
__html: 'Foo',
}}>
{0}
</option>
</select>,
1,
);
},
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
);
itThrowsWhenRendering(
'a select with option that uses dangerouslySetInnerHTML and empty string as child',
async render => {
await render(
<select defaultValue="baz" value="foo" readOnly={true}>
<option
id="foo"
value="foo"
dangerouslySetInnerHTML={{
__html: 'Foo',
}}>
{''}
</option>
</select>,
1,
);
},
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.',
);
itRenders(
'a select value overriding defaultValue no matter the prop order',
async render => {
const e = await render(
<select defaultValue="baz" value="bar" readOnly={true}>
{options}
</select>,
1,
);
expectSelectValue(e, 'bar');
},
);
itRenders('a select option with flattened children', async render => {
const e = await render(
<select value="bar" readOnly={true}>
<option value="bar">A {'B'}</option>
</select>,
);
const option = e.options[0];
expect(option.textContent).toBe('A B');
expect(option.value).toBe('bar');
expect(option.selected).toBe(true);
});
itRenders(
'a select option with flattened children no value',
async render => {
const e = await render(
<select value="A B" readOnly={true}>
<option>A {'B'}</option>
</select>,
);
const option = e.options[0];
expect(option.textContent).toBe('A B');
expect(option.value).toBe('A B');
expect(option.selected).toBe(true);
},
);
itRenders(
'a boolean true select value match the string "true"',
async render => {
const e = await render(
<select value={true} readOnly={true}>
<option value="first">First</option>
<option value="true">True</option>
</select>,
1,
);
expect(e.firstChild.selected).toBe(false);
expect(e.lastChild.selected).toBe(true);
},
);
itRenders(
'a missing select value does not match the string "undefined"',
async render => {
const e = await render(
<select readOnly={true}>
<option value="first">First</option>
<option value="undefined">Undefined</option>
</select>,
1,
);
expect(e.firstChild.selected).toBe(true);
expect(e.lastChild.selected).toBe(false);
},
);
});
| 26.384892 | 93 | 0.574619 |
owtf | import React, {PureComponent} from 'react';
import {
VictoryArea,
VictoryAxis,
VictoryChart,
VictoryBar,
VictoryTheme,
VictoryScatter,
VictoryStack,
} from 'victory';
const colors = ['#fff489', '#fa57c1', '#b166cc', '#7572ff', '#69a6f9'];
export default class Charts extends PureComponent {
render() {
const streamData = this.props.data;
return (
<div>
<div style={{display: 'flex'}}>
<VictoryChart
theme={VictoryTheme.material}
width={400}
height={400}
style={{
parent: {
backgroundColor: '#222',
},
}}>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
/>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
dependentAxis
/>
<VictoryScatter
data={streamData[0]}
size={6}
style={{
data: {
fill: d => colors[d.x % 5],
},
}}
/>
</VictoryChart>
<VictoryChart
theme={VictoryTheme.material}
width={400}
height={400}
style={{
parent: {
backgroundColor: '#222',
},
}}
domainPadding={[20, 20]}>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
/>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
dependentAxis
/>
<VictoryBar
data={streamData[0]}
style={{
data: {
fill: d => colors[d.x % 5],
stroke: 'none',
padding: 5,
},
}}
/>
</VictoryChart>
</div>
<div
style={{
display: 'flex',
position: 'relative',
top: '-50px',
}}>
<VictoryChart
theme={VictoryTheme.material}
width={800}
height={350}
style={{
parent: {
backgroundColor: '#222',
},
}}>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
/>
<VictoryAxis
style={{
axis: {stroke: 'white'},
tickLabels: {fill: 'white'},
}}
dependentAxis
/>
<VictoryStack>
{streamData.map((data, i) => (
<VictoryArea key={i} data={data} colorScale={colors} />
))}
</VictoryStack>
</VictoryChart>
</div>
</div>
);
}
}
| 24.212598 | 71 | 0.367073 |
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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZS5qcyJdLCJuYW1lcyI6WyJBIiwiQiIsIkNvbXBvbmVudCIsImEiLCJiIiwiYyIsImQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7QUFUQTs7Ozs7Ozs7QUFXQSxNQUFNQSxDQUFDLGdCQUFHLDBCQUFjLENBQWQsQ0FBVjtBQUNBLE1BQU1DLENBQUMsZ0JBQUcsMEJBQWMsQ0FBZCxDQUFWOztBQUVPLFNBQVNDLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsQ0FBQyxHQUFHLHVCQUFXSCxDQUFYLENBQVY7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdILENBQVgsQ0FBVixDQUYwQixDQUkxQjs7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBVjtBQUFBLFFBQXlCTSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBN0IsQ0FMMEIsQ0FLa0I7O0FBRTVDLFNBQU9FLENBQUMsR0FBR0MsQ0FBSixHQUFRQyxDQUFSLEdBQVlDLENBQW5CO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0fSBmcm9tICdyZWFjdCc7XG5cbmNvbnN0IEEgPSBjcmVhdGVDb250ZXh0KDEpO1xuY29uc3QgQiA9IGNyZWF0ZUNvbnRleHQoMik7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IGEgPSB1c2VDb250ZXh0KEEpO1xuICBjb25zdCBiID0gdXNlQ29udGV4dChCKTtcblxuICAvLyBwcmV0dGllci1pZ25vcmVcbiAgY29uc3QgYyA9IHVzZUNvbnRleHQoQSksIGQgPSB1c2VDb250ZXh0KEIpOyAvLyBlc2xpbnQtZGlzYWJsZS1saW5lIG9uZS12YXJcblxuICByZXR1cm4gYSArIGIgKyBjICsgZDtcbn1cbiJdfQ== | 71.366667 | 1,464 | 0.873272 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SyntheticEvent', () => {
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should be able to `preventDefault`', () => {
let expectedCount = 0;
const eventHandler = syntheticEvent => {
expect(syntheticEvent.isDefaultPrevented()).toBe(false);
syntheticEvent.preventDefault();
expect(syntheticEvent.isDefaultPrevented()).toBe(true);
expect(syntheticEvent.defaultPrevented).toBe(true);
expectedCount++;
};
const node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(expectedCount).toBe(1);
});
it('should be prevented if nativeEvent is prevented', () => {
let expectedCount = 0;
const eventHandler = syntheticEvent => {
expect(syntheticEvent.isDefaultPrevented()).toBe(true);
expectedCount++;
};
const node = ReactDOM.render(<div onClick={eventHandler} />, container);
let event;
event = document.createEvent('Event');
event.initEvent('click', true, true);
event.preventDefault();
node.dispatchEvent(event);
event = document.createEvent('Event');
event.initEvent('click', true, true);
// Emulate IE8
Object.defineProperty(event, 'defaultPrevented', {
get() {},
});
Object.defineProperty(event, 'returnValue', {
get() {
return false;
},
});
node.dispatchEvent(event);
expect(expectedCount).toBe(2);
});
it('should be able to `stopPropagation`', () => {
let expectedCount = 0;
const eventHandler = syntheticEvent => {
expect(syntheticEvent.isPropagationStopped()).toBe(false);
syntheticEvent.stopPropagation();
expect(syntheticEvent.isPropagationStopped()).toBe(true);
expectedCount++;
};
const node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(expectedCount).toBe(1);
});
});
| 24.558824 | 76 | 0.649655 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @flow
*/
import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
import type {Props} from '../client/ReactFiberConfigDOM';
import {getFiberCurrentPropsFromNode} from '../client/ReactDOMComponentTree';
function isInteractive(tag: string): boolean {
return (
tag === 'button' ||
tag === 'input' ||
tag === 'select' ||
tag === 'textarea'
);
}
function shouldPreventMouseEvent(
name: string,
type: string,
props: Props,
): boolean {
switch (name) {
case 'onClick':
case 'onClickCapture':
case 'onDoubleClick':
case 'onDoubleClickCapture':
case 'onMouseDown':
case 'onMouseDownCapture':
case 'onMouseMove':
case 'onMouseMoveCapture':
case 'onMouseUp':
case 'onMouseUpCapture':
case 'onMouseEnter':
return !!(props.disabled && isInteractive(type));
default:
return false;
}
}
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
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 (shouldPreventMouseEvent(registrationName, inst.type, props)) {
return null;
}
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;
}
| 24.653846 | 120 | 0.666 |
owtf | import React from 'react';
import {useContext, useMemo, useRef, useState, useLayoutEffect} from 'react';
import {__RouterContext} from 'react-router';
import {ReactReduxContext} from 'react-redux';
import ThemeContext from './shared/ThemeContext';
let rendererModule = {
status: 'pending',
promise: null,
result: null,
};
export default function lazyLegacyRoot(getLegacyComponent) {
let componentModule = {
status: 'pending',
promise: null,
result: null,
};
return function Wrapper(props) {
const createLegacyRoot = readModule(
rendererModule,
() => import('../legacy/createLegacyRoot')
).default;
const Component = readModule(componentModule, getLegacyComponent).default;
const containerRef = useRef(null);
const rootRef = useRef(null);
// Populate every contexts we want the legacy subtree to see.
// Then in src/legacy/createLegacyRoot we will apply them.
const theme = useContext(ThemeContext);
const router = useContext(__RouterContext);
const reactRedux = useContext(ReactReduxContext);
const context = useMemo(
() => ({
theme,
router,
reactRedux,
}),
[theme, router, reactRedux]
);
// Create/unmount.
useLayoutEffect(() => {
if (!rootRef.current) {
rootRef.current = createLegacyRoot(containerRef.current);
}
const root = rootRef.current;
return () => {
root.unmount();
};
}, [createLegacyRoot]);
// Mount/update.
useLayoutEffect(() => {
if (rootRef.current) {
rootRef.current.render(Component, props, context);
}
}, [Component, props, context]);
return <div style={{display: 'contents'}} ref={containerRef} />;
};
}
// This is similar to React.lazy, but implemented manually.
// We use this to Suspend rendering of this component until
// we fetch the component and the legacy React to render it.
function readModule(record, createPromise) {
if (record.status === 'fulfilled') {
return record.result;
}
if (record.status === 'rejected') {
throw record.result;
}
if (!record.promise) {
record.promise = createPromise().then(
value => {
if (record.status === 'pending') {
record.status = 'fulfilled';
record.promise = null;
record.result = value;
}
},
error => {
if (record.status === 'pending') {
record.status = 'rejected';
record.promise = null;
record.result = error;
}
}
);
}
throw record.promise;
}
| 25.96875 | 78 | 0.620943 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export type Destination = {
buffer: string,
done: boolean,
fatal: boolean,
error: mixed,
};
export opaque type PrecomputedChunk = string;
export opaque type Chunk = string;
export opaque type BinaryChunk = string;
export function flushBuffered(destination: Destination) {}
export const supportsRequestStorage = false;
export const requestStorage: AsyncLocalStorage<Request> = (null: any);
export function beginWriting(destination: Destination) {}
export function writeChunk(
destination: Destination,
chunk: Chunk | PrecomputedChunk | BinaryChunk,
): void {
destination.buffer += chunk;
}
export function writeChunkAndReturn(
destination: Destination,
chunk: Chunk | PrecomputedChunk | BinaryChunk,
): boolean {
destination.buffer += chunk;
return true;
}
export function completeWriting(destination: Destination) {}
export function close(destination: Destination) {
destination.done = true;
}
export function stringToChunk(content: string): Chunk {
return content;
}
export function stringToPrecomputedChunk(content: string): PrecomputedChunk {
return content;
}
export function typedArrayToBinaryChunk(
content: $ArrayBufferView,
): BinaryChunk {
throw new Error('Not implemented.');
}
export function clonePrecomputedChunk(
chunk: PrecomputedChunk,
): PrecomputedChunk {
return chunk;
}
export function byteLengthOfChunk(chunk: Chunk | PrecomputedChunk): number {
throw new Error('Not implemented.');
}
export function byteLengthOfBinaryChunk(chunk: BinaryChunk): number {
throw new Error('Not implemented.');
}
export function closeWithError(destination: Destination, error: mixed): void {
destination.done = true;
destination.fatal = true;
destination.error = error;
}
export {createFastHashJS as createFastHash} from './createFastHashJS';
| 22.952381 | 78 | 0.756837 |
Penetration-Testing-Study-Notes | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
const {MessageChannel} = require('node:worker_threads');
export default function enqueueTask(task: () => void): void {
const channel = new MessageChannel();
channel.port1.onmessage = () => {
channel.port1.close();
task();
};
channel.port2.postMessage(undefined);
}
| 23.35 | 66 | 0.679012 |
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-primitive-constructors');
const {RuleTester} = require('eslint');
const ruleTester = new RuleTester();
ruleTester.run('eslint-rules/no-primitive-constructors', rule, {
valid: ['!!obj', '+string'],
invalid: [
{
code: 'Boolean(obj)',
errors: [
{
message:
'Do not use the Boolean constructor. To cast a value to a boolean, use double negation: !!value',
},
],
},
{
code: 'new String(obj)',
errors: [
{
message:
"Do not use `new String()`. Use String() without new (or '' + value for perf-sensitive code).",
},
],
},
{
code: 'Number(string)',
errors: [
{
message:
'Do not use the Number constructor. To cast a value to a number, use the plus operator: +value',
},
],
},
],
});
| 22.604167 | 109 | 0.547703 |
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 {useContext} from 'react';
import {ProfilerContext} from '../Profiler/ProfilerContext';
import {StoreContext} from '../context';
import styles from './WhatChanged.css';
function hookIndicesToString(indices: Array<number>): string {
// This is debatable but I think 1-based might ake for a nicer UX.
const numbers = indices.map(value => value + 1);
switch (numbers.length) {
case 0:
return 'No hooks changed';
case 1:
return `Hook ${numbers[0]} changed`;
case 2:
return `Hooks ${numbers[0]} and ${numbers[1]} changed`;
default:
return `Hooks ${numbers.slice(0, numbers.length - 1).join(', ')} and ${
numbers[numbers.length - 1]
} changed`;
}
}
type Props = {
fiberID: number,
};
export default function WhatChanged({fiberID}: Props): React.Node {
const {profilerStore} = useContext(StoreContext);
const {rootID, selectedCommitIndex} = useContext(ProfilerContext);
// TRICKY
// Handle edge case where no commit is selected because of a min-duration filter update.
// If the commit index is null, suspending for data below would throw an error.
// TODO (ProfilerContext) This check should not be necessary.
if (selectedCommitIndex === null) {
return null;
}
const {changeDescriptions} = profilerStore.getCommitData(
((rootID: any): number),
selectedCommitIndex,
);
if (changeDescriptions === null) {
return null;
}
const changeDescription = changeDescriptions.get(fiberID);
if (changeDescription == null) {
return null;
}
const {context, didHooksChange, hooks, isFirstMount, props, state} =
changeDescription;
if (isFirstMount) {
return (
<div className={styles.Component}>
<label className={styles.Label}>Why did this render?</label>
<div className={styles.Item}>
This is the first time the component rendered.
</div>
</div>
);
}
const changes = [];
if (context === true) {
changes.push(
<div key="context" className={styles.Item}>
• Context changed
</div>,
);
} else if (
typeof context === 'object' &&
context !== null &&
context.length !== 0
) {
changes.push(
<div key="context" className={styles.Item}>
• Context changed:
{context.map(key => (
<span key={key} className={styles.Key}>
{key}
</span>
))}
</div>,
);
}
if (didHooksChange) {
if (Array.isArray(hooks)) {
changes.push(
<div key="hooks" className={styles.Item}>
• {hookIndicesToString(hooks)}
</div>,
);
} else {
changes.push(
<div key="hooks" className={styles.Item}>
• Hooks changed
</div>,
);
}
}
if (props !== null && props.length !== 0) {
changes.push(
<div key="props" className={styles.Item}>
• Props changed:
{props.map(key => (
<span key={key} className={styles.Key}>
{key}
</span>
))}
</div>,
);
}
if (state !== null && state.length !== 0) {
changes.push(
<div key="state" className={styles.Item}>
• State changed:
{state.map(key => (
<span key={key} className={styles.Key}>
{key}
</span>
))}
</div>,
);
}
if (changes.length === 0) {
changes.push(
<div key="nothing" className={styles.Item}>
The parent component rendered.
</div>,
);
}
return (
<div className={styles.Component}>
<label className={styles.Label}>Why did this render?</label>
{changes}
</div>
);
}
| 23.273292 | 90 | 0.582288 |
null | #!/usr/bin/env node
'use strict';
const {logPromise, updateVersionsForNext} = require('../utils');
const theme = require('../theme');
module.exports = async ({reactVersion, tempDirectory, version}) => {
return logPromise(
updateVersionsForNext(tempDirectory, reactVersion, version),
theme`Updating version numbers ({version ${version}})`
);
};
| 24.714286 | 68 | 0.70195 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export * from 'react-client/src/ReactFlightClientConfigBrowser';
export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerTurbopack';
export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigBundlerTurbopackServer';
export * from 'react-server-dom-turbopack/src/ReactFlightClientConfigTargetTurbopackServer';
export * from 'react-dom-bindings/src/shared/ReactFlightClientConfigDOM';
export const usedWithSSR = true;
| 39.75 | 93 | 0.794163 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
import type {
DispatchConfig,
ReactSyntheticEvent,
} from './ReactSyntheticEventType';
import type {TopLevelType} from './TopLevelEventTypes';
export type EventTypes = {[key: string]: DispatchConfig};
export type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | TouchEvent;
export type PluginName = string;
export type EventSystemFlags = number;
export type LegacyPluginModule<NativeEvent> = {
eventTypes: EventTypes,
extractEvents: (
topLevelType: TopLevelType,
targetInst: null | Fiber,
nativeTarget: NativeEvent,
nativeEventTarget: null | EventTarget,
eventSystemFlags?: number,
container?: null | EventTarget,
) => ?ReactSyntheticEvent,
tapMoveThreshold?: number,
};
| 25.756757 | 77 | 0.737108 |
Ethical-Hacking-Scripts | import * as React from 'react';
export default function UseMemoCache(): React.Node {
React.unstable_useMemoCache(1);
return null;
}
| 16.375 | 52 | 0.724638 |
owtf | 'use strict';
// This is a server to host data-local resources like databases and RSC
const path = require('path');
const url = require('url');
if (typeof fetch === 'undefined') {
// Patch fetch for earlier Node versions.
global.fetch = require('undici').fetch;
}
const express = require('express');
const bodyParser = require('body-parser');
const busboy = require('busboy');
const app = express();
const compress = require('compression');
const {Readable} = require('node:stream');
app.use(compress());
// Application
const {readFile} = require('fs').promises;
const React = require('react');
const moduleBasePath = new URL('../src', url.pathToFileURL(__filename)).href;
async function renderApp(res, returnValue) {
const {renderToPipeableStream} = await import('react-server-dom-esm/server');
const m = await import('../src/App.js');
const App = m.default;
const root = React.createElement(App);
// For client-invoked server actions we refresh the tree and return a return value.
const payload = returnValue ? {returnValue, root} : root;
const {pipe} = renderToPipeableStream(payload, moduleBasePath);
pipe(res);
}
app.get('/', async function (req, res) {
await renderApp(res, null);
});
app.post('/', bodyParser.text(), async function (req, res) {
const {
renderToPipeableStream,
decodeReply,
decodeReplyFromBusboy,
decodeAction,
} = await import('react-server-dom-esm/server');
const serverReference = req.get('rsc-action');
if (serverReference) {
// This is the client-side case
const [filepath, name] = serverReference.split('#');
const action = (await import(filepath))[name];
// Validate that this is actually a function we intended to expose and
// not the client trying to invoke arbitrary functions. In a real app,
// you'd have a manifest verifying this before even importing it.
if (action.$$typeof !== Symbol.for('react.server.reference')) {
throw new Error('Invalid action');
}
let args;
if (req.is('multipart/form-data')) {
// Use busboy to streamingly parse the reply from form-data.
const bb = busboy({headers: req.headers});
const reply = decodeReplyFromBusboy(bb, moduleBasePath);
req.pipe(bb);
args = await reply;
} else {
args = await decodeReply(req.body, moduleBasePath);
}
const result = action.apply(null, args);
try {
// Wait for any mutations
await result;
} catch (x) {
// We handle the error on the client
}
// Refresh the client and return the value
renderApp(res, result);
} else {
// This is the progressive enhancement case
const UndiciRequest = require('undici').Request;
const fakeRequest = new UndiciRequest('http://localhost', {
method: 'POST',
headers: {'Content-Type': req.headers['content-type']},
body: Readable.toWeb(req),
duplex: 'half',
});
const formData = await fakeRequest.formData();
const action = await decodeAction(formData, moduleBasePath);
try {
// Wait for any mutations
await action();
} catch (x) {
const {setServerState} = await import('../src/ServerState.js');
setServerState('Error: ' + x.message);
}
renderApp(res, null);
}
});
app.get('/todos', function (req, res) {
res.json([
{
id: 1,
text: 'Shave yaks',
},
{
id: 2,
text: 'Eat kale',
},
]);
});
app.listen(3001, () => {
console.log('Regional Flight Server listening on port 3001...');
});
app.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error;
}
switch (error.code) {
case 'EACCES':
console.error('port 3001 requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error('Port 3001 is already in use');
process.exit(1);
break;
default:
throw error;
}
});
| 26.836879 | 85 | 0.640163 |
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 ignoreStrings(
methodName: string,
stringsToIgnore: Array<string>,
): void {
// $FlowFixMe[prop-missing] index access only allowed for objects with index keys
console[methodName] = (...args: $ReadOnlyArray<mixed>) => {
const maybeString = args[0];
if (typeof maybeString === 'string') {
for (let i = 0; i < stringsToIgnore.length; i++) {
if (maybeString.startsWith(stringsToIgnore[i])) {
return;
}
}
}
// HACKY In the test harness, DevTools overrides the parent window's console.
// Our test app code uses the iframe's console though.
// To simulate a more accurate end-to-end environment,
// the shell's console patching should pass through to the parent override methods.
window.parent.console[methodName](...args);
};
}
export function ignoreErrors(errorsToIgnore: Array<string>): void {
ignoreStrings('error', errorsToIgnore);
}
export function ignoreWarnings(warningsToIgnore: Array<string>): void {
ignoreStrings('warn', warningsToIgnore);
}
export function ignoreLogs(logsToIgnore: Array<string>): void {
ignoreStrings('log', logsToIgnore);
}
| 29.772727 | 87 | 0.691057 |
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 JSON5 from 'json5';
import type {Element} from 'react-devtools-shared/src/frontend/types';
import type {StateContext} from './views/Components/TreeContext';
import type Store from './store';
export function printElement(
element: Element,
includeWeight: boolean = false,
): string {
let prefix = ' ';
if (element.children.length > 0) {
prefix = element.isCollapsed ? '▸' : '▾';
}
let key = '';
if (element.key !== null) {
key = ` key="${element.key}"`;
}
let hocDisplayNames = null;
if (element.hocDisplayNames !== null) {
hocDisplayNames = [...element.hocDisplayNames];
}
const hocs =
hocDisplayNames === null ? '' : ` [${hocDisplayNames.join('][')}]`;
let suffix = '';
if (includeWeight) {
suffix = ` (${element.isCollapsed ? 1 : element.weight})`;
}
return `${' '.repeat(element.depth + 1)}${prefix} <${
element.displayName || 'null'
}${key}>${hocs}${suffix}`;
}
export function printOwnersList(
elements: Array<Element>,
includeWeight: boolean = false,
): string {
return elements
.map(element => printElement(element, includeWeight))
.join('\n');
}
export function printStore(
store: Store,
includeWeight: boolean = false,
state: StateContext | null = null,
): string {
const snapshotLines = [];
let rootWeight = 0;
function printSelectedMarker(index: number): string {
if (state === null) {
return '';
}
return state.selectedElementIndex === index ? `→` : ' ';
}
function printErrorsAndWarnings(element: Element): string {
const {errorCount, warningCount} =
store.getErrorAndWarningCountForElementID(element.id);
if (errorCount === 0 && warningCount === 0) {
return '';
}
return ` ${errorCount > 0 ? '✕' : ''}${warningCount > 0 ? '⚠' : ''}`;
}
const ownerFlatTree = state !== null ? state.ownerFlatTree : null;
if (ownerFlatTree !== null) {
snapshotLines.push(
'[owners]' + (includeWeight ? ` (${ownerFlatTree.length})` : ''),
);
ownerFlatTree.forEach((element, index) => {
const printedSelectedMarker = printSelectedMarker(index);
const printedElement = printElement(element, false);
const printedErrorsAndWarnings = printErrorsAndWarnings(element);
snapshotLines.push(
`${printedSelectedMarker}${printedElement}${printedErrorsAndWarnings}`,
);
});
} else {
const errorsAndWarnings = store._errorsAndWarnings;
if (errorsAndWarnings.size > 0) {
let errorCount = 0;
let warningCount = 0;
errorsAndWarnings.forEach(entry => {
errorCount += entry.errorCount;
warningCount += entry.warningCount;
});
snapshotLines.push(`✕ ${errorCount}, ⚠ ${warningCount}`);
}
store.roots.forEach(rootID => {
const {weight} = ((store.getElementByID(rootID): any): Element);
const maybeWeightLabel = includeWeight ? ` (${weight})` : '';
// Store does not (yet) expose a way to get errors/warnings per root.
snapshotLines.push(`[root]${maybeWeightLabel}`);
for (let i = rootWeight; i < rootWeight + weight; i++) {
const element = store.getElementAtIndex(i);
if (element == null) {
throw Error(`Could not find element at index "${i}"`);
}
const printedSelectedMarker = printSelectedMarker(i);
const printedElement = printElement(element, includeWeight);
const printedErrorsAndWarnings = printErrorsAndWarnings(element);
snapshotLines.push(
`${printedSelectedMarker}${printedElement}${printedErrorsAndWarnings}`,
);
}
rootWeight += weight;
});
// Make sure the pretty-printed test align with the Store's reported number of total rows.
if (rootWeight !== store.numElements) {
throw Error(
`Inconsistent Store state. Individual root weights ("${rootWeight}") do not match total weight ("${store.numElements}")`,
);
}
// If roots have been unmounted, verify that they've been removed from maps.
// This helps ensure the Store doesn't leak memory.
store.assertExpectedRootMapSizes();
}
return snapshotLines.join('\n');
}
// We use JSON.parse to parse string values
// e.g. 'foo' is not valid JSON but it is a valid string
// so this method replaces e.g. 'foo' with "foo"
export function sanitizeForParse(value: any): any | string {
if (typeof value === 'string') {
if (
value.length >= 2 &&
value.charAt(0) === "'" &&
value.charAt(value.length - 1) === "'"
) {
return '"' + value.slice(1, value.length - 1) + '"';
}
}
return value;
}
export function smartParse(value: any): any | void | number {
switch (value) {
case 'Infinity':
return Infinity;
case 'NaN':
return NaN;
case 'undefined':
return undefined;
default:
return JSON5.parse(sanitizeForParse(value));
}
}
export function smartStringify(value: any): string {
if (typeof value === 'number') {
if (Number.isNaN(value)) {
return 'NaN';
} else if (!Number.isFinite(value)) {
return 'Infinity';
}
} else if (value === undefined) {
return 'undefined';
}
return JSON.stringify(value);
}
// [url, row, column]
export type Stack = [string, number, number];
const STACK_DELIMETER = /\n\s+at /;
const STACK_SOURCE_LOCATION = /([^\s]+) \((.+):(.+):(.+)\)/;
export function stackToComponentSources(
stack: string,
): Array<[string, ?Stack]> {
const out: Array<[string, ?Stack]> = [];
stack
.split(STACK_DELIMETER)
.slice(1)
.forEach(entry => {
const match = STACK_SOURCE_LOCATION.exec(entry);
if (match) {
const [, component, url, row, column] = match;
out.push([component, [url, parseInt(row, 10), parseInt(column, 10)]]);
} else {
out.push([entry, null]);
}
});
return out;
}
| 27.27907 | 129 | 0.621813 |
PenetrationTestingScripts | /* global chrome */
import type {BrowserTheme} from 'react-devtools-shared/src/devtools/views/DevTools';
export function getBrowserTheme(): BrowserTheme {
if (__IS_CHROME__) {
// chrome.devtools.panels added in Chrome 18.
// chrome.devtools.panels.themeName added in Chrome 54.
return chrome.devtools.panels.themeName === 'dark' ? 'dark' : 'light';
} else {
// chrome.devtools.panels.themeName added in Firefox 55.
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/devtools.panels/themeName
if (chrome.devtools && chrome.devtools.panels) {
switch (chrome.devtools.panels.themeName) {
case 'dark':
return 'dark';
default:
return 'light';
}
}
}
}
export const COMPACT_VERSION_NAME = 'compact';
export const EXTENSION_CONTAINED_VERSIONS = [COMPACT_VERSION_NAME];
| 32.115385 | 94 | 0.673256 |
PenetrationTestingScripts | #!/usr/bin/env node
'use strict';
const {exec} = require('child-process-promise');
const {Finder} = require('firefox-profile');
const {resolve} = require('path');
const {argv} = require('yargs');
const EXTENSION_PATH = resolve('./firefox/build/unpacked');
const START_URL = argv.url || 'https://react.dev/';
const firefoxVersion = process.env.WEB_EXT_FIREFOX;
const getFirefoxProfileName = () => {
// Keys are pulled from https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#--firefox
// and profile names from https://searchfox.org/mozilla-central/source/toolkit/profile/xpcshell/head.js#96
switch (firefoxVersion) {
case 'firefox':
return 'default-release';
case 'beta':
return 'default-beta';
case 'nightly':
return 'default-nightly';
case 'firefoxdeveloperedition':
return 'dev-edition-default';
default:
// Fall back to using the default Firefox profile for testing purposes.
// This prevents users from having to re-login-to sites before testing.
return 'default';
}
};
const main = async () => {
const finder = new Finder();
const findPathPromise = new Promise((resolvePromise, rejectPromise) => {
finder.getPath(getFirefoxProfileName(), (error, profile) => {
if (error) {
rejectPromise(error);
} else {
resolvePromise(profile);
}
});
});
const options = [
`--source-dir=${EXTENSION_PATH}`,
`--start-url=${START_URL}`,
'--browser-console',
];
try {
const path = await findPathPromise;
const trimmedPath = path.replace(' ', '\\ ');
options.push(`--firefox-profile=${trimmedPath}`);
} catch (err) {
console.warn('Could not find default profile, using temporary profile.');
}
try {
await exec(`web-ext run ${options.join(' ')}`);
} catch (err) {
console.error('`web-ext run` failed', err.stdout, err.stderr);
}
};
main();
| 27.028986 | 114 | 0.645111 |
Nojle | /**
* 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;
global.TextDecoder = require('util').TextDecoder;
// let serverExports;
let turbopackServerMap;
let ReactServerDOMServer;
let ReactServerDOMClient;
describe('ReactFlightDOMReply', () => {
beforeEach(() => {
jest.resetModules();
// Simulate the condition resolution
jest.mock('react', () => require('react/react.shared-subset'));
jest.mock('react-server-dom-turbopack/server', () =>
require('react-server-dom-turbopack/server.browser'),
);
const TurbopackMock = require('./utils/TurbopackMock');
// serverExports = TurbopackMock.serverExports;
turbopackServerMap = TurbopackMock.turbopackServerMap;
ReactServerDOMServer = require('react-server-dom-turbopack/server.browser');
jest.resetModules();
ReactServerDOMClient = require('react-server-dom-turbopack/client');
});
it('can encode a reply', async () => {
const body = await ReactServerDOMClient.encodeReply({some: 'object'});
const decoded = await ReactServerDOMServer.decodeReply(
body,
turbopackServerMap,
);
expect(decoded).toEqual({some: 'object'});
});
});
| 29.795918 | 80 | 0.706897 |
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
*/
// This list should be kept updated to reflect additions to 'shared/ReactSymbols'.
// DevTools can't import symbols from 'shared/ReactSymbols' directly for two reasons:
// 1. DevTools requires symbols which may have been deleted in more recent versions (e.g. concurrent mode)
// 2. DevTools must support both Symbol and numeric forms of each symbol;
// Since e.g. standalone DevTools runs in a separate process, it can't rely on its own ES capabilities.
export const CONCURRENT_MODE_NUMBER = 0xeacf;
export const CONCURRENT_MODE_SYMBOL_STRING = 'Symbol(react.concurrent_mode)';
export const CONTEXT_NUMBER = 0xeace;
export const CONTEXT_SYMBOL_STRING = 'Symbol(react.context)';
export const SERVER_CONTEXT_SYMBOL_STRING = 'Symbol(react.server_context)';
export const DEPRECATED_ASYNC_MODE_SYMBOL_STRING = 'Symbol(react.async_mode)';
export const ELEMENT_NUMBER = 0xeac7;
export const ELEMENT_SYMBOL_STRING = 'Symbol(react.element)';
export const DEBUG_TRACING_MODE_NUMBER = 0xeae1;
export const DEBUG_TRACING_MODE_SYMBOL_STRING =
'Symbol(react.debug_trace_mode)';
export const FORWARD_REF_NUMBER = 0xead0;
export const FORWARD_REF_SYMBOL_STRING = 'Symbol(react.forward_ref)';
export const FRAGMENT_NUMBER = 0xeacb;
export const FRAGMENT_SYMBOL_STRING = 'Symbol(react.fragment)';
export const LAZY_NUMBER = 0xead4;
export const LAZY_SYMBOL_STRING = 'Symbol(react.lazy)';
export const MEMO_NUMBER = 0xead3;
export const MEMO_SYMBOL_STRING = 'Symbol(react.memo)';
export const PORTAL_NUMBER = 0xeaca;
export const PORTAL_SYMBOL_STRING = 'Symbol(react.portal)';
export const PROFILER_NUMBER = 0xead2;
export const PROFILER_SYMBOL_STRING = 'Symbol(react.profiler)';
export const PROVIDER_NUMBER = 0xeacd;
export const PROVIDER_SYMBOL_STRING = 'Symbol(react.provider)';
export const SCOPE_NUMBER = 0xead7;
export const SCOPE_SYMBOL_STRING = 'Symbol(react.scope)';
export const STRICT_MODE_NUMBER = 0xeacc;
export const STRICT_MODE_SYMBOL_STRING = 'Symbol(react.strict_mode)';
export const SUSPENSE_NUMBER = 0xead1;
export const SUSPENSE_SYMBOL_STRING = 'Symbol(react.suspense)';
export const SUSPENSE_LIST_NUMBER = 0xead8;
export const SUSPENSE_LIST_SYMBOL_STRING = 'Symbol(react.suspense_list)';
export const SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED_SYMBOL_STRING =
'Symbol(react.server_context.defaultValue)';
| 36.279412 | 106 | 0.765983 |
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 {REACT_STRICT_MODE_TYPE} from 'shared/ReactSymbols';
import type {Wakeable, Thenable} from 'shared/ReactTypes';
import type {Fiber, FiberRoot} from './ReactInternalTypes';
import type {Lanes, Lane} from './ReactFiberLane';
import type {SuspenseState} from './ReactFiberSuspenseComponent';
import type {FunctionComponentUpdateQueue} from './ReactFiberHooks';
import type {EventPriority} from './ReactEventPriorities';
import type {
PendingTransitionCallbacks,
PendingBoundaries,
Transition,
TransitionAbort,
} from './ReactFiberTracingMarkerComponent';
import type {OffscreenInstance} from './ReactFiberActivityComponent';
import type {RenderTaskFn} from './ReactFiberRootScheduler';
import {
replayFailedUnitOfWorkWithInvokeGuardedCallback,
enableCreateEventHandleAPI,
enableProfilerTimer,
enableProfilerCommitHooks,
enableProfilerNestedUpdatePhase,
enableProfilerNestedUpdateScheduledHook,
enableDebugTracing,
enableSchedulingProfiler,
disableSchedulerTimeoutInWorkLoop,
enableUpdaterTracking,
enableCache,
enableTransitionTracing,
useModernStrictMode,
disableLegacyContext,
alwaysThrottleRetries,
} from 'shared/ReactFeatureFlags';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import is from 'shared/objectIs';
import {
// Aliased because `act` will override and push to an internal queue
scheduleCallback as Scheduler_scheduleCallback,
shouldYield,
requestPaint,
now,
NormalPriority as NormalSchedulerPriority,
IdlePriority as IdleSchedulerPriority,
} from './Scheduler';
import {
logCommitStarted,
logCommitStopped,
logLayoutEffectsStarted,
logLayoutEffectsStopped,
logPassiveEffectsStarted,
logPassiveEffectsStopped,
logRenderStarted,
logRenderStopped,
} from './DebugTracing';
import {
resetAfterCommit,
scheduleTimeout,
cancelTimeout,
noTimeout,
afterActiveInstanceBlur,
getCurrentEventPriority,
errorHydratingContainer,
startSuspendingCommit,
waitForCommitToBeReady,
preloadInstance,
} from './ReactFiberConfig';
import {
createWorkInProgress,
assignFiberPropertiesInDEV,
resetWorkInProgress,
} from './ReactFiber';
import {isRootDehydrated} from './ReactFiberShellHydration';
import {
getIsHydrating,
didSuspendOrErrorWhileHydratingDEV,
} from './ReactFiberHydrationContext';
import {
NoMode,
ProfileMode,
ConcurrentMode,
StrictLegacyMode,
StrictEffectsMode,
NoStrictPassiveEffectsMode,
} from './ReactTypeOfMode';
import {
HostRoot,
IndeterminateComponent,
ClassComponent,
SuspenseComponent,
SuspenseListComponent,
OffscreenComponent,
FunctionComponent,
ForwardRef,
MemoComponent,
SimpleMemoComponent,
Profiler,
HostComponent,
HostHoistable,
HostSingleton,
} from './ReactWorkTags';
import {ConcurrentRoot, LegacyRoot} from './ReactRootTags';
import type {Flags} from './ReactFiberFlags';
import {
NoFlags,
Incomplete,
StoreConsistency,
HostEffectMask,
ForceClientRender,
BeforeMutationMask,
MutationMask,
LayoutMask,
PassiveMask,
PlacementDEV,
Visibility,
MountPassiveDev,
MountLayoutDev,
DidDefer,
} from './ReactFiberFlags';
import {
NoLanes,
NoLane,
SyncLane,
claimNextRetryLane,
includesSyncLane,
isSubsetOfLanes,
mergeLanes,
removeLanes,
pickArbitraryLane,
includesNonIdleWork,
includesOnlyRetries,
includesOnlyTransitions,
includesBlockingLane,
includesExpiredLane,
getNextLanes,
getEntangledLanes,
getLanesToRetrySynchronouslyOnError,
markRootUpdated,
markRootSuspended as markRootSuspended_dontCallThisOneDirectly,
markRootPinged,
upgradePendingLanesToSync,
markRootFinished,
addFiberToLanesMap,
movePendingFibersToMemoized,
addTransitionToLanesMap,
getTransitionsForLanes,
includesOnlyNonUrgentLanes,
includesSomeLane,
OffscreenLane,
SyncUpdateLanes,
UpdateLanes,
} from './ReactFiberLane';
import {
DiscreteEventPriority,
DefaultEventPriority,
getCurrentUpdatePriority,
setCurrentUpdatePriority,
lowerEventPriority,
lanesToEventPriority,
} from './ReactEventPriorities';
import {requestCurrentTransition, NoTransition} from './ReactFiberTransition';
import {
SelectiveHydrationException,
beginWork as originalBeginWork,
replayFunctionComponent,
} from './ReactFiberBeginWork';
import {completeWork} from './ReactFiberCompleteWork';
import {unwindWork, unwindInterruptedWork} from './ReactFiberUnwindWork';
import {
throwException,
createRootErrorUpdate,
createClassErrorUpdate,
} from './ReactFiberThrow';
import {
commitBeforeMutationEffects,
commitLayoutEffects,
commitMutationEffects,
commitPassiveEffectDurations,
commitPassiveMountEffects,
commitPassiveUnmountEffects,
disappearLayoutEffects,
reconnectPassiveEffects,
reappearLayoutEffects,
disconnectPassiveEffect,
reportUncaughtErrorInDEV,
invokeLayoutEffectMountInDEV,
invokePassiveEffectMountInDEV,
invokeLayoutEffectUnmountInDEV,
invokePassiveEffectUnmountInDEV,
accumulateSuspenseyCommit,
} from './ReactFiberCommitWork';
import {enqueueUpdate} from './ReactFiberClassUpdateQueue';
import {resetContextDependencies} from './ReactFiberNewContext';
import {
resetHooksAfterThrow,
resetHooksOnUnwind,
ContextOnlyDispatcher,
} from './ReactFiberHooks';
import {DefaultCacheDispatcher} from './ReactFiberCache';
import {
createCapturedValueAtFiber,
type CapturedValue,
} from './ReactCapturedValue';
import {
enqueueConcurrentRenderForLane,
finishQueueingConcurrentUpdates,
getConcurrentlyUpdatedLanes,
} from './ReactFiberConcurrentUpdates';
import {
markNestedUpdateScheduled,
recordCommitTime,
resetNestedUpdateFlag,
startProfilerTimer,
stopProfilerTimerIfRunningAndRecordDelta,
syncNestedUpdateFlag,
} from './ReactProfilerTimer';
// DEV stuff
import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber';
import ReactStrictModeWarnings from './ReactStrictModeWarnings';
import {
isRendering as ReactCurrentDebugFiberIsRenderingInDEV,
current as ReactCurrentFiberCurrent,
resetCurrentFiber as resetCurrentDebugFiberInDEV,
setCurrentFiber as setCurrentDebugFiberInDEV,
} from './ReactCurrentFiber';
import {
invokeGuardedCallback,
hasCaughtError,
clearCaughtError,
} from 'shared/ReactErrorUtils';
import {
isDevToolsPresent,
markCommitStarted,
markCommitStopped,
markComponentRenderStopped,
markComponentSuspended,
markComponentErrored,
markLayoutEffectsStarted,
markLayoutEffectsStopped,
markPassiveEffectsStarted,
markPassiveEffectsStopped,
markRenderStarted,
markRenderYielded,
markRenderStopped,
onCommitRoot as onCommitRootDevTools,
onPostCommitRoot as onPostCommitRootDevTools,
} from './ReactFiberDevToolsHook';
import {onCommitRoot as onCommitRootTestSelector} from './ReactTestSelectors';
import {releaseCache} from './ReactFiberCacheComponent';
import {
isLegacyActEnvironment,
isConcurrentActEnvironment,
} from './ReactFiberAct';
import {processTransitionCallbacks} from './ReactFiberTracingMarkerComponent';
import {
SuspenseException,
SuspenseyCommitException,
getSuspendedThenable,
isThenableResolved,
} from './ReactFiberThenable';
import {schedulePostPaintCallback} from './ReactPostPaintCallback';
import {
getSuspenseHandler,
getShellBoundary,
} from './ReactFiberSuspenseContext';
import {resolveDefaultProps} from './ReactFiberLazyComponent';
import {resetChildReconcilerOnUnwind} from './ReactChildFiber';
import {
ensureRootIsScheduled,
flushSyncWorkOnAllRoots,
flushSyncWorkOnLegacyRootsOnly,
getContinuationForRoot,
requestTransitionLane,
} from './ReactFiberRootScheduler';
import {getMaskedContext, getUnmaskedContext} from './ReactFiberContext';
import {peekEntangledActionLane} from './ReactFiberAsyncAction';
const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
const {
ReactCurrentDispatcher,
ReactCurrentCache,
ReactCurrentOwner,
ReactCurrentBatchConfig,
ReactCurrentActQueue,
} = ReactSharedInternals;
type ExecutionContext = number;
export const NoContext = /* */ 0b000;
const BatchedContext = /* */ 0b001;
export const RenderContext = /* */ 0b010;
export const CommitContext = /* */ 0b100;
type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6;
const RootInProgress = 0;
const RootFatalErrored = 1;
const RootErrored = 2;
const RootSuspended = 3;
const RootSuspendedWithDelay = 4;
const RootCompleted = 5;
const RootDidNotComplete = 6;
// Describes where we are in the React execution stack
let executionContext: ExecutionContext = NoContext;
// The root we're working on
let workInProgressRoot: FiberRoot | null = null;
// The fiber we're working on
let workInProgress: Fiber | null = null;
// The lanes we're rendering
let workInProgressRootRenderLanes: Lanes = NoLanes;
opaque type SuspendedReason = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
const NotSuspended: SuspendedReason = 0;
const SuspendedOnError: SuspendedReason = 1;
const SuspendedOnData: SuspendedReason = 2;
const SuspendedOnImmediate: SuspendedReason = 3;
const SuspendedOnInstance: SuspendedReason = 4;
const SuspendedOnInstanceAndReadyToContinue: SuspendedReason = 5;
const SuspendedOnDeprecatedThrowPromise: SuspendedReason = 6;
const SuspendedAndReadyToContinue: SuspendedReason = 7;
const SuspendedOnHydration: SuspendedReason = 8;
// When this is true, the work-in-progress fiber just suspended (or errored) and
// we've yet to unwind the stack. In some cases, we may yield to the main thread
// after this happens. If the fiber is pinged before we resume, we can retry
// immediately instead of unwinding the stack.
let workInProgressSuspendedReason: SuspendedReason = NotSuspended;
let workInProgressThrownValue: mixed = null;
// Whether a ping listener was attached during this render. This is slightly
// different that whether something suspended, because we don't add multiple
// listeners to a promise we've already seen (per root and lane).
let workInProgressRootDidAttachPingListener: boolean = false;
// A contextual version of workInProgressRootRenderLanes. It is a superset of
// the lanes that we started working on at the root. When we enter a subtree
// that is currently hidden, we add the lanes that would have committed if
// the hidden tree hadn't been deferred. This is modified by the
// HiddenContext module.
//
// Most things in the work loop should deal with workInProgressRootRenderLanes.
// Most things in begin/complete phases should deal with entangledRenderLanes.
export let entangledRenderLanes: Lanes = NoLanes;
// Whether to root completed, errored, suspended, etc.
let workInProgressRootExitStatus: RootExitStatus = RootInProgress;
// A fatal error, if one is thrown
let workInProgressRootFatalError: mixed = null;
// The work left over by components that were visited during this render. Only
// includes unprocessed updates, not work in bailed out children.
let workInProgressRootSkippedLanes: Lanes = NoLanes;
// Lanes that were updated (in an interleaved event) during this render.
let workInProgressRootInterleavedUpdatedLanes: Lanes = NoLanes;
// Lanes that were updated during the render phase (*not* an interleaved event).
let workInProgressRootRenderPhaseUpdatedLanes: Lanes = NoLanes;
// Lanes that were pinged (in an interleaved event) during this render.
let workInProgressRootPingedLanes: Lanes = NoLanes;
// If this lane scheduled deferred work, this is the lane of the deferred task.
let workInProgressDeferredLane: Lane = NoLane;
// Errors that are thrown during the render phase.
let workInProgressRootConcurrentErrors: Array<CapturedValue<mixed>> | null =
null;
// These are errors that we recovered from without surfacing them to the UI.
// We will log them once the tree commits.
let workInProgressRootRecoverableErrors: Array<CapturedValue<mixed>> | null =
null;
// The most recent time we either committed a fallback, or when a fallback was
// filled in with the resolved UI. This lets us throttle the appearance of new
// content as it streams in, to minimize jank.
// TODO: Think of a better name for this variable?
let globalMostRecentFallbackTime: number = 0;
const FALLBACK_THROTTLE_MS: number = 300;
// The absolute time for when we should start giving up on rendering
// more and prefer CPU suspense heuristics instead.
let workInProgressRootRenderTargetTime: number = Infinity;
// How long a render is supposed to take before we start following CPU
// suspense heuristics and opt out of rendering more content.
const RENDER_TIMEOUT_MS = 500;
let workInProgressTransitions: Array<Transition> | null = null;
export function getWorkInProgressTransitions(): null | Array<Transition> {
return workInProgressTransitions;
}
let currentPendingTransitionCallbacks: PendingTransitionCallbacks | null = null;
let currentEndTime: number | null = null;
export function addTransitionStartCallbackToPendingTransition(
transition: Transition,
) {
if (enableTransitionTracing) {
if (currentPendingTransitionCallbacks === null) {
currentPendingTransitionCallbacks = {
transitionStart: [],
transitionProgress: null,
transitionComplete: null,
markerProgress: null,
markerIncomplete: null,
markerComplete: null,
};
}
if (currentPendingTransitionCallbacks.transitionStart === null) {
currentPendingTransitionCallbacks.transitionStart =
([]: Array<Transition>);
}
currentPendingTransitionCallbacks.transitionStart.push(transition);
}
}
export function addMarkerProgressCallbackToPendingTransition(
markerName: string,
transitions: Set<Transition>,
pendingBoundaries: PendingBoundaries,
) {
if (enableTransitionTracing) {
if (currentPendingTransitionCallbacks === null) {
currentPendingTransitionCallbacks = ({
transitionStart: null,
transitionProgress: null,
transitionComplete: null,
markerProgress: new Map(),
markerIncomplete: null,
markerComplete: null,
}: PendingTransitionCallbacks);
}
if (currentPendingTransitionCallbacks.markerProgress === null) {
currentPendingTransitionCallbacks.markerProgress = new Map();
}
currentPendingTransitionCallbacks.markerProgress.set(markerName, {
pendingBoundaries,
transitions,
});
}
}
export function addMarkerIncompleteCallbackToPendingTransition(
markerName: string,
transitions: Set<Transition>,
aborts: Array<TransitionAbort>,
) {
if (enableTransitionTracing) {
if (currentPendingTransitionCallbacks === null) {
currentPendingTransitionCallbacks = {
transitionStart: null,
transitionProgress: null,
transitionComplete: null,
markerProgress: null,
markerIncomplete: new Map(),
markerComplete: null,
};
}
if (currentPendingTransitionCallbacks.markerIncomplete === null) {
currentPendingTransitionCallbacks.markerIncomplete = new Map();
}
currentPendingTransitionCallbacks.markerIncomplete.set(markerName, {
transitions,
aborts,
});
}
}
export function addMarkerCompleteCallbackToPendingTransition(
markerName: string,
transitions: Set<Transition>,
) {
if (enableTransitionTracing) {
if (currentPendingTransitionCallbacks === null) {
currentPendingTransitionCallbacks = {
transitionStart: null,
transitionProgress: null,
transitionComplete: null,
markerProgress: null,
markerIncomplete: null,
markerComplete: new Map(),
};
}
if (currentPendingTransitionCallbacks.markerComplete === null) {
currentPendingTransitionCallbacks.markerComplete = new Map();
}
currentPendingTransitionCallbacks.markerComplete.set(
markerName,
transitions,
);
}
}
export function addTransitionProgressCallbackToPendingTransition(
transition: Transition,
boundaries: PendingBoundaries,
) {
if (enableTransitionTracing) {
if (currentPendingTransitionCallbacks === null) {
currentPendingTransitionCallbacks = {
transitionStart: null,
transitionProgress: new Map(),
transitionComplete: null,
markerProgress: null,
markerIncomplete: null,
markerComplete: null,
};
}
if (currentPendingTransitionCallbacks.transitionProgress === null) {
currentPendingTransitionCallbacks.transitionProgress = new Map();
}
currentPendingTransitionCallbacks.transitionProgress.set(
transition,
boundaries,
);
}
}
export function addTransitionCompleteCallbackToPendingTransition(
transition: Transition,
) {
if (enableTransitionTracing) {
if (currentPendingTransitionCallbacks === null) {
currentPendingTransitionCallbacks = {
transitionStart: null,
transitionProgress: null,
transitionComplete: [],
markerProgress: null,
markerIncomplete: null,
markerComplete: null,
};
}
if (currentPendingTransitionCallbacks.transitionComplete === null) {
currentPendingTransitionCallbacks.transitionComplete =
([]: Array<Transition>);
}
currentPendingTransitionCallbacks.transitionComplete.push(transition);
}
}
function resetRenderTimer() {
workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
}
export function getRenderTargetTime(): number {
return workInProgressRootRenderTargetTime;
}
let hasUncaughtError = false;
let firstUncaughtError = null;
let legacyErrorBoundariesThatAlreadyFailed: Set<mixed> | null = null;
// Only used when enableProfilerNestedUpdateScheduledHook is true;
// to track which root is currently committing layout effects.
let rootCommittingMutationOrLayoutEffects: FiberRoot | null = null;
let rootDoesHavePassiveEffects: boolean = false;
let rootWithPendingPassiveEffects: FiberRoot | null = null;
let pendingPassiveEffectsLanes: Lanes = NoLanes;
let pendingPassiveProfilerEffects: Array<Fiber> = [];
let pendingPassiveEffectsRemainingLanes: Lanes = NoLanes;
let pendingPassiveTransitions: Array<Transition> | null = null;
// Use these to prevent an infinite loop of nested updates
const NESTED_UPDATE_LIMIT = 50;
let nestedUpdateCount: number = 0;
let rootWithNestedUpdates: FiberRoot | null = null;
let isFlushingPassiveEffects = false;
let didScheduleUpdateDuringPassiveEffects = false;
const NESTED_PASSIVE_UPDATE_LIMIT = 50;
let nestedPassiveUpdateCount: number = 0;
let rootWithPassiveNestedUpdates: FiberRoot | null = null;
let isRunningInsertionEffect = false;
export function getWorkInProgressRoot(): FiberRoot | null {
return workInProgressRoot;
}
export function getWorkInProgressRootRenderLanes(): Lanes {
return workInProgressRootRenderLanes;
}
export function isWorkLoopSuspendedOnData(): boolean {
return workInProgressSuspendedReason === SuspendedOnData;
}
export function getCurrentTime(): number {
return now();
}
export function requestUpdateLane(fiber: Fiber): Lane {
// Special cases
const mode = fiber.mode;
if ((mode & ConcurrentMode) === NoMode) {
return (SyncLane: Lane);
} else if (
(executionContext & RenderContext) !== NoContext &&
workInProgressRootRenderLanes !== NoLanes
) {
// This is a render phase update. These are not officially supported. The
// old behavior is to give this the same "thread" (lanes) as
// whatever is currently rendering. So if you call `setState` on a component
// that happens later in the same render, it will flush. Ideally, we want to
// remove the special case and treat them as if they came from an
// interleaved event. Regardless, this pattern is not officially supported.
// This behavior is only a fallback. The flag only exists until we can roll
// out the setState warning, since existing code might accidentally rely on
// the current behavior.
return pickArbitraryLane(workInProgressRootRenderLanes);
}
const isTransition = requestCurrentTransition() !== NoTransition;
if (isTransition) {
if (__DEV__ && ReactCurrentBatchConfig.transition !== null) {
const transition = ReactCurrentBatchConfig.transition;
if (!transition._updatedFibers) {
transition._updatedFibers = new Set();
}
transition._updatedFibers.add(fiber);
}
const actionScopeLane = peekEntangledActionLane();
return actionScopeLane !== NoLane
? // We're inside an async action scope. Reuse the same lane.
actionScopeLane
: // We may or may not be inside an async action scope. If we are, this
// is the first update in that scope. Either way, we need to get a
// fresh transition lane.
requestTransitionLane();
}
// Updates originating inside certain React methods, like flushSync, have
// their priority set by tracking it with a context variable.
//
// The opaque type returned by the host config is internally a lane, so we can
// use that directly.
// TODO: Move this type conversion to the event priority module.
const updateLane: Lane = (getCurrentUpdatePriority(): any);
if (updateLane !== NoLane) {
return updateLane;
}
// This update originated outside React. Ask the host environment for an
// appropriate priority, based on the type of event.
//
// The opaque type returned by the host config is internally a lane, so we can
// use that directly.
// TODO: Move this type conversion to the event priority module.
const eventLane: Lane = (getCurrentEventPriority(): any);
return eventLane;
}
function requestRetryLane(fiber: Fiber) {
// This is a fork of `requestUpdateLane` designed specifically for Suspense
// "retries" — a special update that attempts to flip a Suspense boundary
// from its placeholder state to its primary/resolved state.
// Special cases
const mode = fiber.mode;
if ((mode & ConcurrentMode) === NoMode) {
return (SyncLane: Lane);
}
return claimNextRetryLane();
}
export function requestDeferredLane(): Lane {
if (workInProgressDeferredLane === NoLane) {
// If there are multiple useDeferredValue hooks in the same render, the
// tasks that they spawn should all be batched together, so they should all
// receive the same lane.
// Check the priority of the current render to decide the priority of the
// deferred task.
// OffscreenLane is used for prerendering, but we also use OffscreenLane
// for incremental hydration. It's given the lowest priority because the
// initial HTML is the same as the final UI. But useDeferredValue during
// hydration is an exception — we need to upgrade the UI to the final
// value. So if we're currently hydrating, we treat it like a transition.
const isPrerendering =
includesSomeLane(workInProgressRootRenderLanes, OffscreenLane) &&
!getIsHydrating();
if (isPrerendering) {
// There's only one OffscreenLane, so if it contains deferred work, we
// should just reschedule using the same lane.
workInProgressDeferredLane = OffscreenLane;
} else {
// Everything else is spawned as a transition.
workInProgressDeferredLane = requestTransitionLane();
}
}
// Mark the parent Suspense boundary so it knows to spawn the deferred lane.
const suspenseHandler = getSuspenseHandler();
if (suspenseHandler !== null) {
// TODO: As an optimization, we shouldn't entangle the lanes at the root; we
// can entangle them using the baseLanes of the Suspense boundary instead.
// We only need to do something special if there's no Suspense boundary.
suspenseHandler.flags |= DidDefer;
}
return workInProgressDeferredLane;
}
export function peekDeferredLane(): Lane {
return workInProgressDeferredLane;
}
export function scheduleUpdateOnFiber(
root: FiberRoot,
fiber: Fiber,
lane: Lane,
) {
if (__DEV__) {
if (isRunningInsertionEffect) {
console.error('useInsertionEffect must not schedule updates.');
}
}
if (__DEV__) {
if (isFlushingPassiveEffects) {
didScheduleUpdateDuringPassiveEffects = true;
}
}
// Check if the work loop is currently suspended and waiting for data to
// finish loading.
if (
// Suspended render phase
(root === workInProgressRoot &&
workInProgressSuspendedReason === SuspendedOnData) ||
// Suspended commit phase
root.cancelPendingCommit !== null
) {
// The incoming update might unblock the current render. Interrupt the
// current attempt and restart from the top.
prepareFreshStack(root, NoLanes);
markRootSuspended(
root,
workInProgressRootRenderLanes,
workInProgressDeferredLane,
);
}
// Mark that the root has a pending update.
markRootUpdated(root, lane);
if (
(executionContext & RenderContext) !== NoLanes &&
root === workInProgressRoot
) {
// This update was dispatched during the render phase. This is a mistake
// if the update originates from user space (with the exception of local
// hook updates, which are handled differently and don't reach this
// function), but there are some internal React features that use this as
// an implementation detail, like selective hydration.
warnAboutRenderPhaseUpdatesInDEV(fiber);
// Track lanes that were updated during the render phase
workInProgressRootRenderPhaseUpdatedLanes = mergeLanes(
workInProgressRootRenderPhaseUpdatedLanes,
lane,
);
} else {
// This is a normal update, scheduled from outside the render phase. For
// example, during an input event.
if (enableUpdaterTracking) {
if (isDevToolsPresent) {
addFiberToLanesMap(root, fiber, lane);
}
}
warnIfUpdatesNotWrappedWithActDEV(fiber);
if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
if (
(executionContext & CommitContext) !== NoContext &&
root === rootCommittingMutationOrLayoutEffects
) {
if (fiber.mode & ProfileMode) {
let current: null | Fiber = fiber;
while (current !== null) {
if (current.tag === Profiler) {
const {id, onNestedUpdateScheduled} = current.memoizedProps;
if (typeof onNestedUpdateScheduled === 'function') {
onNestedUpdateScheduled(id);
}
}
current = current.return;
}
}
}
}
if (enableTransitionTracing) {
const transition = ReactCurrentBatchConfig.transition;
if (transition !== null && transition.name != null) {
if (transition.startTime === -1) {
transition.startTime = now();
}
addTransitionToLanesMap(root, transition, lane);
}
}
if (root === workInProgressRoot) {
// Received an update to a tree that's in the middle of rendering. Mark
// that there was an interleaved update work on this root.
if ((executionContext & RenderContext) === NoContext) {
workInProgressRootInterleavedUpdatedLanes = mergeLanes(
workInProgressRootInterleavedUpdatedLanes,
lane,
);
}
if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
// The root already suspended with a delay, which means this render
// definitely won't finish. Since we have a new update, let's mark it as
// suspended now, right before marking the incoming update. This has the
// effect of interrupting the current render and switching to the update.
// TODO: Make sure this doesn't override pings that happen while we've
// already started rendering.
markRootSuspended(
root,
workInProgressRootRenderLanes,
workInProgressDeferredLane,
);
}
}
ensureRootIsScheduled(root);
if (
lane === SyncLane &&
executionContext === NoContext &&
(fiber.mode & ConcurrentMode) === NoMode
) {
if (__DEV__ && ReactCurrentActQueue.isBatchingLegacy) {
// Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
} else {
// Flush the synchronous work now, unless we're already working or inside
// a batch. This is intentionally inside scheduleUpdateOnFiber instead of
// scheduleCallbackForFiber to preserve the ability to schedule a callback
// without immediately flushing it. We only do this for user-initiated
// updates, to preserve historical behavior of legacy mode.
resetRenderTimer();
flushSyncWorkOnLegacyRootsOnly();
}
}
}
}
export function scheduleInitialHydrationOnRoot(root: FiberRoot, lane: Lane) {
// This is a special fork of scheduleUpdateOnFiber that is only used to
// schedule the initial hydration of a root that has just been created. Most
// of the stuff in scheduleUpdateOnFiber can be skipped.
//
// The main reason for this separate path, though, is to distinguish the
// initial children from subsequent updates. In fully client-rendered roots
// (createRoot instead of hydrateRoot), all top-level renders are modeled as
// updates, but hydration roots are special because the initial render must
// match what was rendered on the server.
const current = root.current;
current.lanes = lane;
markRootUpdated(root, lane);
ensureRootIsScheduled(root);
}
export function isUnsafeClassRenderPhaseUpdate(fiber: Fiber): boolean {
// Check if this is a render phase update. Only called by class components,
// which special (deprecated) behavior for UNSAFE_componentWillReceive props.
return (executionContext & RenderContext) !== NoContext;
}
// This is the entry point for every concurrent task, i.e. anything that
// goes through Scheduler.
export function performConcurrentWorkOnRoot(
root: FiberRoot,
didTimeout: boolean,
): RenderTaskFn | null {
if (enableProfilerTimer && enableProfilerNestedUpdatePhase) {
resetNestedUpdateFlag();
}
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Should not already be working.');
}
// Flush any pending passive effects before deciding which lanes to work on,
// in case they schedule additional work.
const originalCallbackNode = root.callbackNode;
const didFlushPassiveEffects = flushPassiveEffects();
if (didFlushPassiveEffects) {
// Something in the passive effect phase may have canceled the current task.
// Check if the task node for this root was changed.
if (root.callbackNode !== originalCallbackNode) {
// The current task was canceled. Exit. We don't need to call
// `ensureRootIsScheduled` because the check above implies either that
// there's a new task, or that there's no remaining work on this root.
return null;
} else {
// Current task was not canceled. Continue.
}
}
// Determine the next lanes to work on, using the fields stored
// on the root.
// TODO: This was already computed in the caller. Pass it as an argument.
let lanes = getNextLanes(
root,
root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes,
);
if (lanes === NoLanes) {
// Defensive coding. This is never expected to happen.
return null;
}
// We disable time-slicing in some cases: if the work has been CPU-bound
// for too long ("expired" work, to prevent starvation), or we're in
// sync-updates-by-default mode.
// TODO: We only check `didTimeout` defensively, to account for a Scheduler
// bug we're still investigating. Once the bug in Scheduler is fixed,
// we can remove this, since we track expiration ourselves.
const shouldTimeSlice =
!includesBlockingLane(root, lanes) &&
!includesExpiredLane(root, lanes) &&
(disableSchedulerTimeoutInWorkLoop || !didTimeout);
let exitStatus = shouldTimeSlice
? renderRootConcurrent(root, lanes)
: renderRootSync(root, lanes);
if (exitStatus !== RootInProgress) {
let renderWasConcurrent = shouldTimeSlice;
do {
if (exitStatus === RootDidNotComplete) {
// The render unwound without completing the tree. This happens in special
// cases where need to exit the current render without producing a
// consistent tree or committing.
markRootSuspended(root, lanes, NoLane);
} else {
// The render completed.
// Check if this render may have yielded to a concurrent event, and if so,
// confirm that any newly rendered stores are consistent.
// TODO: It's possible that even a concurrent render may never have yielded
// to the main thread, if it was fast enough, or if it expired. We could
// skip the consistency check in that case, too.
const finishedWork: Fiber = (root.current.alternate: any);
if (
renderWasConcurrent &&
!isRenderConsistentWithExternalStores(finishedWork)
) {
// A store was mutated in an interleaved event. Render again,
// synchronously, to block further mutations.
exitStatus = renderRootSync(root, lanes);
// We assume the tree is now consistent because we didn't yield to any
// concurrent events.
renderWasConcurrent = false;
// Need to check the exit status again.
continue;
}
// Check if something threw
if (exitStatus === RootErrored) {
const originallyAttemptedLanes = lanes;
const errorRetryLanes = getLanesToRetrySynchronouslyOnError(
root,
originallyAttemptedLanes,
);
if (errorRetryLanes !== NoLanes) {
lanes = errorRetryLanes;
exitStatus = recoverFromConcurrentError(
root,
originallyAttemptedLanes,
errorRetryLanes,
);
renderWasConcurrent = false;
}
}
if (exitStatus === RootFatalErrored) {
const fatalError = workInProgressRootFatalError;
prepareFreshStack(root, NoLanes);
markRootSuspended(root, lanes, NoLane);
ensureRootIsScheduled(root);
throw fatalError;
}
// We now have a consistent tree. The next step is either to commit it,
// or, if something suspended, wait to commit it after a timeout.
root.finishedWork = finishedWork;
root.finishedLanes = lanes;
finishConcurrentRender(root, exitStatus, finishedWork, lanes);
}
break;
} while (true);
}
ensureRootIsScheduled(root);
return getContinuationForRoot(root, originalCallbackNode);
}
function recoverFromConcurrentError(
root: FiberRoot,
originallyAttemptedLanes: Lanes,
errorRetryLanes: Lanes,
) {
// If an error occurred during hydration, discard server response and fall
// back to client side render.
// Before rendering again, save the errors from the previous attempt.
const errorsFromFirstAttempt = workInProgressRootConcurrentErrors;
const wasRootDehydrated = isRootDehydrated(root);
if (wasRootDehydrated) {
// The shell failed to hydrate. Set a flag to force a client rendering
// during the next attempt. To do this, we call prepareFreshStack now
// to create the root work-in-progress fiber. This is a bit weird in terms
// of factoring, because it relies on renderRootSync not calling
// prepareFreshStack again in the call below, which happens because the
// root and lanes haven't changed.
//
// TODO: I think what we should do is set ForceClientRender inside
// throwException, like we do for nested Suspense boundaries. The reason
// it's here instead is so we can switch to the synchronous work loop, too.
// Something to consider for a future refactor.
const rootWorkInProgress = prepareFreshStack(root, errorRetryLanes);
rootWorkInProgress.flags |= ForceClientRender;
if (__DEV__) {
errorHydratingContainer(root.containerInfo);
}
}
const exitStatus = renderRootSync(root, errorRetryLanes);
if (exitStatus !== RootErrored) {
// Successfully finished rendering on retry
if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
// During the synchronous render, we attached additional ping listeners.
// This is highly suggestive of an uncached promise (though it's not the
// only reason this would happen). If it was an uncached promise, then
// it may have masked a downstream error from ocurring without actually
// fixing it. Example:
//
// use(Promise.resolve('uncached'))
// throw new Error('Oops!')
//
// When this happens, there's a conflict between blocking potential
// concurrent data races and unwrapping uncached promise values. We
// have to choose one or the other. Because the data race recovery is
// a last ditch effort, we'll disable it.
root.errorRecoveryDisabledLanes = mergeLanes(
root.errorRecoveryDisabledLanes,
originallyAttemptedLanes,
);
// Mark the current render as suspended and force it to restart. Once
// these lanes finish successfully, we'll re-enable the error recovery
// mechanism for subsequent updates.
workInProgressRootInterleavedUpdatedLanes |= originallyAttemptedLanes;
return RootSuspendedWithDelay;
}
// The errors from the failed first attempt have been recovered. Add
// them to the collection of recoverable errors. We'll log them in the
// commit phase.
const errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
workInProgressRootRecoverableErrors = errorsFromFirstAttempt;
// The errors from the second attempt should be queued after the errors
// from the first attempt, to preserve the causal sequence.
if (errorsFromSecondAttempt !== null) {
queueRecoverableErrors(errorsFromSecondAttempt);
}
} else {
// The UI failed to recover.
}
return exitStatus;
}
export function queueRecoverableErrors(errors: Array<CapturedValue<mixed>>) {
if (workInProgressRootRecoverableErrors === null) {
workInProgressRootRecoverableErrors = errors;
} else {
// $FlowFixMe[method-unbinding]
workInProgressRootRecoverableErrors.push.apply(
workInProgressRootRecoverableErrors,
errors,
);
}
}
function finishConcurrentRender(
root: FiberRoot,
exitStatus: RootExitStatus,
finishedWork: Fiber,
lanes: Lanes,
) {
// TODO: The fact that most of these branches are identical suggests that some
// of the exit statuses are not best modeled as exit statuses and should be
// tracked orthogonally.
switch (exitStatus) {
case RootInProgress:
case RootFatalErrored: {
throw new Error('Root did not complete. This is a bug in React.');
}
case RootSuspendedWithDelay: {
if (includesOnlyTransitions(lanes)) {
// This is a transition, so we should exit without committing a
// placeholder and without scheduling a timeout. Delay indefinitely
// until we receive more data.
markRootSuspended(root, lanes, workInProgressDeferredLane);
return;
}
// Commit the placeholder.
break;
}
case RootErrored:
case RootSuspended:
case RootCompleted: {
break;
}
default: {
throw new Error('Unknown root exit status.');
}
}
if (shouldForceFlushFallbacksInDEV()) {
// We're inside an `act` scope. Commit immediately.
commitRoot(
root,
workInProgressRootRecoverableErrors,
workInProgressTransitions,
workInProgressDeferredLane,
);
} else {
if (
includesOnlyRetries(lanes) &&
(alwaysThrottleRetries || exitStatus === RootSuspended)
) {
// This render only included retries, no updates. Throttle committing
// retries so that we don't show too many loading states too quickly.
const msUntilTimeout =
globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now();
// Don't bother with a very short suspense time.
if (msUntilTimeout > 10) {
markRootSuspended(root, lanes, workInProgressDeferredLane);
const nextLanes = getNextLanes(root, NoLanes);
if (nextLanes !== NoLanes) {
// There's additional work we can do on this root. We might as well
// attempt to work on that while we're suspended.
return;
}
// The render is suspended, it hasn't timed out, and there's no
// lower priority work to do. Instead of committing the fallback
// immediately, wait for more data to arrive.
// TODO: Combine retry throttling with Suspensey commits. Right now they
// run one after the other.
root.timeoutHandle = scheduleTimeout(
commitRootWhenReady.bind(
null,
root,
finishedWork,
workInProgressRootRecoverableErrors,
workInProgressTransitions,
lanes,
workInProgressDeferredLane,
),
msUntilTimeout,
);
return;
}
}
commitRootWhenReady(
root,
finishedWork,
workInProgressRootRecoverableErrors,
workInProgressTransitions,
lanes,
workInProgressDeferredLane,
);
}
}
function commitRootWhenReady(
root: FiberRoot,
finishedWork: Fiber,
recoverableErrors: Array<CapturedValue<mixed>> | null,
transitions: Array<Transition> | null,
lanes: Lanes,
spawnedLane: Lane,
) {
// TODO: Combine retry throttling with Suspensey commits. Right now they run
// one after the other.
if (includesOnlyNonUrgentLanes(lanes)) {
// Before committing, ask the renderer whether the host tree is ready.
// If it's not, we'll wait until it notifies us.
startSuspendingCommit();
// This will walk the completed fiber tree and attach listeners to all
// the suspensey resources. The renderer is responsible for accumulating
// all the load events. This all happens in a single synchronous
// transaction, so it track state in its own module scope.
accumulateSuspenseyCommit(finishedWork);
// At the end, ask the renderer if it's ready to commit, or if we should
// suspend. If it's not ready, it will return a callback to subscribe to
// a ready event.
const schedulePendingCommit = waitForCommitToBeReady();
if (schedulePendingCommit !== null) {
// NOTE: waitForCommitToBeReady returns a subscribe function so that we
// only allocate a function if the commit isn't ready yet. The other
// pattern would be to always pass a callback to waitForCommitToBeReady.
// Not yet ready to commit. Delay the commit until the renderer notifies
// us that it's ready. This will be canceled if we start work on the
// root again.
root.cancelPendingCommit = schedulePendingCommit(
commitRoot.bind(null, root, recoverableErrors, transitions),
);
markRootSuspended(root, lanes, spawnedLane);
return;
}
}
// Otherwise, commit immediately.
commitRoot(root, recoverableErrors, transitions, spawnedLane);
}
function isRenderConsistentWithExternalStores(finishedWork: Fiber): boolean {
// Search the rendered tree for external store reads, and check whether the
// stores were mutated in a concurrent event. Intentionally using an iterative
// loop instead of recursion so we can exit early.
let node: Fiber = finishedWork;
while (true) {
if (node.flags & StoreConsistency) {
const updateQueue: FunctionComponentUpdateQueue | null =
(node.updateQueue: any);
if (updateQueue !== null) {
const checks = updateQueue.stores;
if (checks !== null) {
for (let i = 0; i < checks.length; i++) {
const check = checks[i];
const getSnapshot = check.getSnapshot;
const renderedValue = check.value;
try {
if (!is(getSnapshot(), renderedValue)) {
// Found an inconsistent store.
return false;
}
} catch (error) {
// If `getSnapshot` throws, return `false`. This will schedule
// a re-render, and the error will be rethrown during render.
return false;
}
}
}
}
}
const child = node.child;
if (node.subtreeFlags & StoreConsistency && child !== null) {
child.return = node;
node = child;
continue;
}
if (node === finishedWork) {
return true;
}
while (node.sibling === null) {
if (node.return === null || node.return === finishedWork) {
return true;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
// Flow doesn't know this is unreachable, but eslint does
// eslint-disable-next-line no-unreachable
return true;
}
function markRootSuspended(
root: FiberRoot,
suspendedLanes: Lanes,
spawnedLane: Lane,
) {
// When suspending, we should always exclude lanes that were pinged or (more
// rarely, since we try to avoid it) updated during the render phase.
// TODO: Lol maybe there's a better way to factor this besides this
// obnoxiously named function :)
suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
suspendedLanes = removeLanes(
suspendedLanes,
workInProgressRootInterleavedUpdatedLanes,
);
markRootSuspended_dontCallThisOneDirectly(root, suspendedLanes, spawnedLane);
}
// This is the entry point for synchronous tasks that don't go
// through Scheduler
export function performSyncWorkOnRoot(root: FiberRoot, lanes: Lanes): null {
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Should not already be working.');
}
const didFlushPassiveEffects = flushPassiveEffects();
if (didFlushPassiveEffects) {
// If passive effects were flushed, exit to the outer work loop in the root
// scheduler, so we can recompute the priority.
// TODO: We don't actually need this `ensureRootIsScheduled` call because
// this path is only reachable if the root is already part of the schedule.
// I'm including it only for consistency with the other exit points from
// this function. Can address in a subsequent refactor.
ensureRootIsScheduled(root);
return null;
}
if (enableProfilerTimer && enableProfilerNestedUpdatePhase) {
syncNestedUpdateFlag();
}
let exitStatus = renderRootSync(root, lanes);
if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
// If something threw an error, try rendering one more time. We'll render
// synchronously to block concurrent data mutations, and we'll includes
// all pending updates are included. If it still fails after the second
// attempt, we'll give up and commit the resulting tree.
const originallyAttemptedLanes = lanes;
const errorRetryLanes = getLanesToRetrySynchronouslyOnError(
root,
originallyAttemptedLanes,
);
if (errorRetryLanes !== NoLanes) {
lanes = errorRetryLanes;
exitStatus = recoverFromConcurrentError(
root,
originallyAttemptedLanes,
errorRetryLanes,
);
}
}
if (exitStatus === RootFatalErrored) {
const fatalError = workInProgressRootFatalError;
prepareFreshStack(root, NoLanes);
markRootSuspended(root, lanes, NoLane);
ensureRootIsScheduled(root);
throw fatalError;
}
if (exitStatus === RootDidNotComplete) {
// The render unwound without completing the tree. This happens in special
// cases where need to exit the current render without producing a
// consistent tree or committing.
markRootSuspended(root, lanes, workInProgressDeferredLane);
ensureRootIsScheduled(root);
return null;
}
// We now have a consistent tree. Because this is a sync render, we
// will commit it even if something suspended.
const finishedWork: Fiber = (root.current.alternate: any);
root.finishedWork = finishedWork;
root.finishedLanes = lanes;
commitRoot(
root,
workInProgressRootRecoverableErrors,
workInProgressTransitions,
workInProgressDeferredLane,
);
// Before exiting, make sure there's a callback scheduled for the next
// pending level.
ensureRootIsScheduled(root);
return null;
}
export function flushRoot(root: FiberRoot, lanes: Lanes) {
if (lanes !== NoLanes) {
upgradePendingLanesToSync(root, lanes);
ensureRootIsScheduled(root);
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
resetRenderTimer();
// TODO: For historical reasons this flushes all sync work across all
// roots. It shouldn't really matter either way, but we could change this
// to only flush the given root.
flushSyncWorkOnAllRoots();
}
}
}
export function getExecutionContext(): ExecutionContext {
return executionContext;
}
export function deferredUpdates<A>(fn: () => A): A {
const previousPriority = getCurrentUpdatePriority();
const prevTransition = ReactCurrentBatchConfig.transition;
try {
ReactCurrentBatchConfig.transition = null;
setCurrentUpdatePriority(DefaultEventPriority);
return fn();
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
}
}
export function batchedUpdates<A, R>(fn: A => R, a: A): R {
const prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
// If there were legacy sync updates, flush them at the end of the outer
// most batchedUpdates-like method.
if (
executionContext === NoContext &&
// Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
!(__DEV__ && ReactCurrentActQueue.isBatchingLegacy)
) {
resetRenderTimer();
flushSyncWorkOnLegacyRootsOnly();
}
}
}
export function discreteUpdates<A, B, C, D, R>(
fn: (A, B, C, D) => R,
a: A,
b: B,
c: C,
d: D,
): R {
const previousPriority = getCurrentUpdatePriority();
const prevTransition = ReactCurrentBatchConfig.transition;
try {
ReactCurrentBatchConfig.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
return fn(a, b, c, d);
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
if (executionContext === NoContext) {
resetRenderTimer();
}
}
}
// Overload the definition to the two valid signatures.
// Warning, this opts-out of checking the function body.
// eslint-disable-next-line no-unused-vars
declare function flushSync<R>(fn: () => R): R;
// eslint-disable-next-line no-redeclare
declare function flushSync(void): void;
// eslint-disable-next-line no-redeclare
export function flushSync<R>(fn: (() => R) | void): R | void {
// In legacy mode, we flush pending passive effects at the beginning of the
// next event, not at the end of the previous one.
if (
rootWithPendingPassiveEffects !== null &&
rootWithPendingPassiveEffects.tag === LegacyRoot &&
(executionContext & (RenderContext | CommitContext)) === NoContext
) {
flushPassiveEffects();
}
const prevExecutionContext = executionContext;
executionContext |= BatchedContext;
const prevTransition = ReactCurrentBatchConfig.transition;
const previousPriority = getCurrentUpdatePriority();
try {
ReactCurrentBatchConfig.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
if (fn) {
return fn();
} else {
return undefined;
}
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
executionContext = prevExecutionContext;
// Flush the immediate callbacks that were scheduled during this batch.
// Note that this will happen even if batchedUpdates is higher up
// the stack.
if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
flushSyncWorkOnAllRoots();
}
}
}
export function isAlreadyRendering(): boolean {
// Used by the renderer to print a warning if certain APIs are called from
// the wrong context.
return (
__DEV__ &&
(executionContext & (RenderContext | CommitContext)) !== NoContext
);
}
export function isInvalidExecutionContextForEventFunction(): boolean {
// Used to throw if certain APIs are called from the wrong context.
return (executionContext & RenderContext) !== NoContext;
}
// This is called by the HiddenContext module when we enter or leave a
// hidden subtree. The stack logic is managed there because that's the only
// place that ever modifies it. Which module it lives in doesn't matter for
// performance because this function will get inlined regardless
export function setEntangledRenderLanes(newEntangledRenderLanes: Lanes) {
entangledRenderLanes = newEntangledRenderLanes;
}
export function getEntangledRenderLanes(): Lanes {
return entangledRenderLanes;
}
function resetWorkInProgressStack() {
if (workInProgress === null) return;
let interruptedWork;
if (workInProgressSuspendedReason === NotSuspended) {
// Normal case. Work-in-progress hasn't started yet. Unwind all
// its parents.
interruptedWork = workInProgress.return;
} else {
// Work-in-progress is in suspended state. Reset the work loop and unwind
// both the suspended fiber and all its parents.
resetSuspendedWorkLoopOnUnwind(workInProgress);
interruptedWork = workInProgress;
}
while (interruptedWork !== null) {
const current = interruptedWork.alternate;
unwindInterruptedWork(
current,
interruptedWork,
workInProgressRootRenderLanes,
);
interruptedWork = interruptedWork.return;
}
workInProgress = null;
}
function prepareFreshStack(root: FiberRoot, lanes: Lanes): Fiber {
root.finishedWork = null;
root.finishedLanes = NoLanes;
const timeoutHandle = root.timeoutHandle;
if (timeoutHandle !== noTimeout) {
// The root previous suspended and scheduled a timeout to commit a fallback
// state. Now that we have additional work, cancel the timeout.
root.timeoutHandle = noTimeout;
// $FlowFixMe[incompatible-call] Complains noTimeout is not a TimeoutID, despite the check above
cancelTimeout(timeoutHandle);
}
const cancelPendingCommit = root.cancelPendingCommit;
if (cancelPendingCommit !== null) {
root.cancelPendingCommit = null;
cancelPendingCommit();
}
resetWorkInProgressStack();
workInProgressRoot = root;
const rootWorkInProgress = createWorkInProgress(root.current, null);
workInProgress = rootWorkInProgress;
workInProgressRootRenderLanes = lanes;
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
workInProgressRootDidAttachPingListener = false;
workInProgressRootExitStatus = RootInProgress;
workInProgressRootFatalError = null;
workInProgressRootSkippedLanes = NoLanes;
workInProgressRootInterleavedUpdatedLanes = NoLanes;
workInProgressRootRenderPhaseUpdatedLanes = NoLanes;
workInProgressRootPingedLanes = NoLanes;
workInProgressDeferredLane = NoLane;
workInProgressRootConcurrentErrors = null;
workInProgressRootRecoverableErrors = null;
// Get the lanes that are entangled with whatever we're about to render. We
// track these separately so we can distinguish the priority of the render
// task from the priority of the lanes it is entangled with. For example, a
// transition may not be allowed to finish unless it includes the Sync lane,
// which is currently suspended. We should be able to render the Transition
// and Sync lane in the same batch, but at Transition priority, because the
// Sync lane already suspended.
entangledRenderLanes = getEntangledLanes(root, lanes);
finishQueueingConcurrentUpdates();
if (__DEV__) {
ReactStrictModeWarnings.discardPendingWarnings();
}
return rootWorkInProgress;
}
function resetSuspendedWorkLoopOnUnwind(fiber: Fiber) {
// Reset module-level state that was set during the render phase.
resetContextDependencies();
resetHooksOnUnwind(fiber);
resetChildReconcilerOnUnwind();
}
function handleThrow(root: FiberRoot, thrownValue: any): void {
// A component threw an exception. Usually this is because it suspended, but
// it also includes regular program errors.
//
// We're either going to unwind the stack to show a Suspense or error
// boundary, or we're going to replay the component again. Like after a
// promise resolves.
//
// Until we decide whether we're going to unwind or replay, we should preserve
// the current state of the work loop without resetting anything.
//
// If we do decide to unwind the stack, module-level variables will be reset
// in resetSuspendedWorkLoopOnUnwind.
// These should be reset immediately because they're only supposed to be set
// when React is executing user code.
resetHooksAfterThrow();
resetCurrentDebugFiberInDEV();
ReactCurrentOwner.current = null;
if (thrownValue === SuspenseException) {
// This is a special type of exception used for Suspense. For historical
// reasons, the rest of the Suspense implementation expects the thrown value
// to be a thenable, because before `use` existed that was the (unstable)
// API for suspending. This implementation detail can change later, once we
// deprecate the old API in favor of `use`.
thrownValue = getSuspendedThenable();
workInProgressSuspendedReason =
shouldRemainOnPreviousScreen() &&
// Check if there are other pending updates that might possibly unblock this
// component from suspending. This mirrors the check in
// renderDidSuspendDelayIfPossible. We should attempt to unify them somehow.
// TODO: Consider unwinding immediately, using the
// SuspendedOnHydration mechanism.
!includesNonIdleWork(workInProgressRootSkippedLanes) &&
!includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes)
? // Suspend work loop until data resolves
SuspendedOnData
: // Don't suspend work loop, except to check if the data has
// immediately resolved (i.e. in a microtask). Otherwise, trigger the
// nearest Suspense fallback.
SuspendedOnImmediate;
} else if (thrownValue === SuspenseyCommitException) {
thrownValue = getSuspendedThenable();
workInProgressSuspendedReason = SuspendedOnInstance;
} else if (thrownValue === SelectiveHydrationException) {
// An update flowed into a dehydrated boundary. Before we can apply the
// update, we need to finish hydrating. Interrupt the work-in-progress
// render so we can restart at the hydration lane.
//
// The ideal implementation would be able to switch contexts without
// unwinding the current stack.
//
// We could name this something more general but as of now it's the only
// case where we think this should happen.
workInProgressSuspendedReason = SuspendedOnHydration;
} else {
// This is a regular error.
const isWakeable =
thrownValue !== null &&
typeof thrownValue === 'object' &&
typeof thrownValue.then === 'function';
workInProgressSuspendedReason = isWakeable
? // A wakeable object was thrown by a legacy Suspense implementation.
// This has slightly different behavior than suspending with `use`.
SuspendedOnDeprecatedThrowPromise
: // This is a regular error. If something earlier in the component already
// suspended, we must clear the thenable state to unblock the work loop.
SuspendedOnError;
}
workInProgressThrownValue = thrownValue;
const erroredWork = workInProgress;
if (erroredWork === null) {
// This is a fatal error
workInProgressRootExitStatus = RootFatalErrored;
workInProgressRootFatalError = thrownValue;
return;
}
if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
// Record the time spent rendering before an error was thrown. This
// avoids inaccurate Profiler durations in the case of a
// suspended render.
stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
}
if (enableSchedulingProfiler) {
markComponentRenderStopped();
switch (workInProgressSuspendedReason) {
case SuspendedOnError: {
markComponentErrored(
erroredWork,
thrownValue,
workInProgressRootRenderLanes,
);
break;
}
case SuspendedOnData:
case SuspendedOnImmediate:
case SuspendedOnDeprecatedThrowPromise:
case SuspendedAndReadyToContinue: {
const wakeable: Wakeable = (thrownValue: any);
markComponentSuspended(
erroredWork,
wakeable,
workInProgressRootRenderLanes,
);
break;
}
case SuspendedOnInstance: {
// This is conceptually like a suspend, but it's not associated with
// a particular wakeable. It's associated with a host resource (e.g.
// a CSS file or an image) that hasn't loaded yet. DevTools doesn't
// handle this currently.
break;
}
case SuspendedOnHydration: {
// This is conceptually like a suspend, but it's not associated with
// a particular wakeable. DevTools doesn't seem to care about this case,
// currently. It's similar to if the component were interrupted, which
// we don't mark with a special function.
break;
}
}
}
}
export function shouldRemainOnPreviousScreen(): boolean {
// This is asking whether it's better to suspend the transition and remain
// on the previous screen, versus showing a fallback as soon as possible. It
// takes into account both the priority of render and also whether showing a
// fallback would produce a desirable user experience.
const handler = getSuspenseHandler();
if (handler === null) {
// There's no Suspense boundary that can provide a fallback. We have no
// choice but to remain on the previous screen.
// NOTE: We do this even for sync updates, for lack of any better option. In
// the future, we may change how we handle this, like by putting the whole
// root into a "detached" mode.
return true;
}
// TODO: Once `use` has fully replaced the `throw promise` pattern, we should
// be able to remove the equivalent check in finishConcurrentRender, and rely
// just on this one.
if (includesOnlyTransitions(workInProgressRootRenderLanes)) {
if (getShellBoundary() === null) {
// We're rendering inside the "shell" of the app. Activating the nearest
// fallback would cause visible content to disappear. It's better to
// suspend the transition and remain on the previous screen.
return true;
} else {
// We're rendering content that wasn't part of the previous screen.
// Rather than block the transition, it's better to show a fallback as
// soon as possible. The appearance of any nested fallbacks will be
// throttled to avoid jank.
return false;
}
}
if (
includesOnlyRetries(workInProgressRootRenderLanes) ||
// In this context, an OffscreenLane counts as a Retry
// TODO: It's become increasingly clear that Retries and Offscreen are
// deeply connected. They probably can be unified further.
includesSomeLane(workInProgressRootRenderLanes, OffscreenLane)
) {
// During a retry, we can suspend rendering if the nearest Suspense boundary
// is the boundary of the "shell", because we're guaranteed not to block
// any new content from appearing.
//
// The reason we must check if this is a retry is because it guarantees
// that suspending the work loop won't block an actual update, because
// retries don't "update" anything; they fill in fallbacks that were left
// behind by a previous transition.
return handler === getShellBoundary();
}
// For all other Lanes besides Transitions and Retries, we should not wait
// for the data to load.
return false;
}
function pushDispatcher(container: any) {
const prevDispatcher = ReactCurrentDispatcher.current;
ReactCurrentDispatcher.current = ContextOnlyDispatcher;
if (prevDispatcher === null) {
// The React isomorphic package does not include a default dispatcher.
// Instead the first renderer will lazily attach one, in order to give
// nicer error messages.
return ContextOnlyDispatcher;
} else {
return prevDispatcher;
}
}
function popDispatcher(prevDispatcher: any) {
ReactCurrentDispatcher.current = prevDispatcher;
}
function pushCacheDispatcher() {
if (enableCache) {
const prevCacheDispatcher = ReactCurrentCache.current;
ReactCurrentCache.current = DefaultCacheDispatcher;
return prevCacheDispatcher;
} else {
return null;
}
}
function popCacheDispatcher(prevCacheDispatcher: any) {
if (enableCache) {
ReactCurrentCache.current = prevCacheDispatcher;
}
}
export function markCommitTimeOfFallback() {
globalMostRecentFallbackTime = now();
}
export function markSkippedUpdateLanes(lane: Lane | Lanes): void {
workInProgressRootSkippedLanes = mergeLanes(
lane,
workInProgressRootSkippedLanes,
);
}
export function renderDidSuspend(): void {
if (workInProgressRootExitStatus === RootInProgress) {
workInProgressRootExitStatus = RootSuspended;
}
}
export function renderDidSuspendDelayIfPossible(): void {
workInProgressRootExitStatus = RootSuspendedWithDelay;
// Check if there are updates that we skipped tree that might have unblocked
// this render.
if (
(includesNonIdleWork(workInProgressRootSkippedLanes) ||
includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes)) &&
workInProgressRoot !== null
) {
// Mark the current render as suspended so that we switch to working on
// the updates that were skipped. Usually we only suspend at the end of
// the render phase.
// TODO: We should probably always mark the root as suspended immediately
// (inside this function), since by suspending at the end of the render
// phase introduces a potential mistake where we suspend lanes that were
// pinged or updated while we were rendering.
// TODO: Consider unwinding immediately, using the
// SuspendedOnHydration mechanism.
markRootSuspended(
workInProgressRoot,
workInProgressRootRenderLanes,
workInProgressDeferredLane,
);
}
}
export function renderDidError(error: CapturedValue<mixed>) {
if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
workInProgressRootExitStatus = RootErrored;
}
if (workInProgressRootConcurrentErrors === null) {
workInProgressRootConcurrentErrors = [error];
} else {
workInProgressRootConcurrentErrors.push(error);
}
}
// Called during render to determine if anything has suspended.
// Returns false if we're not sure.
export function renderHasNotSuspendedYet(): boolean {
// If something errored or completed, we can't really be sure,
// so those are false.
return workInProgressRootExitStatus === RootInProgress;
}
// TODO: Over time, this function and renderRootConcurrent have become more
// and more similar. Not sure it makes sense to maintain forked paths. Consider
// unifying them again.
function renderRootSync(root: FiberRoot, lanes: Lanes) {
const prevExecutionContext = executionContext;
executionContext |= RenderContext;
const prevDispatcher = pushDispatcher(root.containerInfo);
const prevCacheDispatcher = pushCacheDispatcher();
// If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
if (enableUpdaterTracking) {
if (isDevToolsPresent) {
const memoizedUpdaters = root.memoizedUpdaters;
if (memoizedUpdaters.size > 0) {
restorePendingUpdaters(root, workInProgressRootRenderLanes);
memoizedUpdaters.clear();
}
// At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
// If we bailout on this work, we'll move them back (like above).
// It's important to move them now in case the work spawns more work at the same priority with different updaters.
// That way we can keep the current update and future updates separate.
movePendingFibersToMemoized(root, lanes);
}
}
workInProgressTransitions = getTransitionsForLanes(root, lanes);
prepareFreshStack(root, lanes);
}
if (__DEV__) {
if (enableDebugTracing) {
logRenderStarted(lanes);
}
}
if (enableSchedulingProfiler) {
markRenderStarted(lanes);
}
let didSuspendInShell = false;
outer: do {
try {
if (
workInProgressSuspendedReason !== NotSuspended &&
workInProgress !== null
) {
// The work loop is suspended. During a synchronous render, we don't
// yield to the main thread. Immediately unwind the stack. This will
// trigger either a fallback or an error boundary.
// TODO: For discrete and "default" updates (anything that's not
// flushSync), we want to wait for the microtasks the flush before
// unwinding. Will probably implement this using renderRootConcurrent,
// or merge renderRootSync and renderRootConcurrent into the same
// function and fork the behavior some other way.
const unitOfWork = workInProgress;
const thrownValue = workInProgressThrownValue;
switch (workInProgressSuspendedReason) {
case SuspendedOnHydration: {
// Selective hydration. An update flowed into a dehydrated tree.
// Interrupt the current render so the work loop can switch to the
// hydration lane.
resetWorkInProgressStack();
workInProgressRootExitStatus = RootDidNotComplete;
break outer;
}
case SuspendedOnImmediate:
case SuspendedOnData: {
if (!didSuspendInShell && getSuspenseHandler() === null) {
didSuspendInShell = true;
}
// Intentional fallthrough
}
default: {
// Unwind then continue with the normal work loop.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
throwAndUnwindWorkLoop(unitOfWork, thrownValue);
break;
}
}
}
workLoopSync();
break;
} catch (thrownValue) {
handleThrow(root, thrownValue);
}
} while (true);
// Check if something suspended in the shell. We use this to detect an
// infinite ping loop caused by an uncached promise.
//
// Only increment this counter once per synchronous render attempt across the
// whole tree. Even if there are many sibling components that suspend, this
// counter only gets incremented once.
if (didSuspendInShell) {
root.shellSuspendCounter++;
}
resetContextDependencies();
executionContext = prevExecutionContext;
popDispatcher(prevDispatcher);
popCacheDispatcher(prevCacheDispatcher);
if (workInProgress !== null) {
// This is a sync render, so we should have finished the whole tree.
throw new Error(
'Cannot commit an incomplete root. This error is likely caused by a ' +
'bug in React. Please file an issue.',
);
}
if (__DEV__) {
if (enableDebugTracing) {
logRenderStopped();
}
}
if (enableSchedulingProfiler) {
markRenderStopped();
}
// Set this to null to indicate there's no in-progress render.
workInProgressRoot = null;
workInProgressRootRenderLanes = NoLanes;
// It's safe to process the queue now that the render phase is complete.
finishQueueingConcurrentUpdates();
return workInProgressRootExitStatus;
}
// The work loop is an extremely hot path. Tell Closure not to inline it.
/** @noinline */
function workLoopSync() {
// Perform work without checking if we need to yield between fiber.
while (workInProgress !== null) {
performUnitOfWork(workInProgress);
}
}
function renderRootConcurrent(root: FiberRoot, lanes: Lanes) {
const prevExecutionContext = executionContext;
executionContext |= RenderContext;
const prevDispatcher = pushDispatcher(root.containerInfo);
const prevCacheDispatcher = pushCacheDispatcher();
// If the root or lanes have changed, throw out the existing stack
// and prepare a fresh one. Otherwise we'll continue where we left off.
if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
if (enableUpdaterTracking) {
if (isDevToolsPresent) {
const memoizedUpdaters = root.memoizedUpdaters;
if (memoizedUpdaters.size > 0) {
restorePendingUpdaters(root, workInProgressRootRenderLanes);
memoizedUpdaters.clear();
}
// At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
// If we bailout on this work, we'll move them back (like above).
// It's important to move them now in case the work spawns more work at the same priority with different updaters.
// That way we can keep the current update and future updates separate.
movePendingFibersToMemoized(root, lanes);
}
}
workInProgressTransitions = getTransitionsForLanes(root, lanes);
resetRenderTimer();
prepareFreshStack(root, lanes);
}
if (__DEV__) {
if (enableDebugTracing) {
logRenderStarted(lanes);
}
}
if (enableSchedulingProfiler) {
markRenderStarted(lanes);
}
outer: do {
try {
if (
workInProgressSuspendedReason !== NotSuspended &&
workInProgress !== null
) {
// The work loop is suspended. We need to either unwind the stack or
// replay the suspended component.
const unitOfWork = workInProgress;
const thrownValue = workInProgressThrownValue;
resumeOrUnwind: switch (workInProgressSuspendedReason) {
case SuspendedOnError: {
// Unwind then continue with the normal work loop.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
throwAndUnwindWorkLoop(unitOfWork, thrownValue);
break;
}
case SuspendedOnData: {
const thenable: Thenable<mixed> = (thrownValue: any);
if (isThenableResolved(thenable)) {
// The data resolved. Try rendering the component again.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
replaySuspendedUnitOfWork(unitOfWork);
break;
}
// The work loop is suspended on data. We should wait for it to
// resolve before continuing to render.
// TODO: Handle the case where the promise resolves synchronously.
// Usually this is handled when we instrument the promise to add a
// `status` field, but if the promise already has a status, we won't
// have added a listener until right here.
const onResolution = () => {
// Check if the root is still suspended on this promise.
if (
workInProgressSuspendedReason === SuspendedOnData &&
workInProgressRoot === root
) {
// Mark the root as ready to continue rendering.
workInProgressSuspendedReason = SuspendedAndReadyToContinue;
}
// Ensure the root is scheduled. We should do this even if we're
// currently working on a different root, so that we resume
// rendering later.
ensureRootIsScheduled(root);
};
thenable.then(onResolution, onResolution);
break outer;
}
case SuspendedOnImmediate: {
// If this fiber just suspended, it's possible the data is already
// cached. Yield to the main thread to give it a chance to ping. If
// it does, we can retry immediately without unwinding the stack.
workInProgressSuspendedReason = SuspendedAndReadyToContinue;
break outer;
}
case SuspendedOnInstance: {
workInProgressSuspendedReason =
SuspendedOnInstanceAndReadyToContinue;
break outer;
}
case SuspendedAndReadyToContinue: {
const thenable: Thenable<mixed> = (thrownValue: any);
if (isThenableResolved(thenable)) {
// The data resolved. Try rendering the component again.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
replaySuspendedUnitOfWork(unitOfWork);
} else {
// Otherwise, unwind then continue with the normal work loop.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
throwAndUnwindWorkLoop(unitOfWork, thrownValue);
}
break;
}
case SuspendedOnInstanceAndReadyToContinue: {
switch (workInProgress.tag) {
case HostComponent:
case HostHoistable:
case HostSingleton: {
// Before unwinding the stack, check one more time if the
// instance is ready. It may have loaded when React yielded to
// the main thread.
// Assigning this to a constant so Flow knows the binding won't
// be mutated by `preloadInstance`.
const hostFiber = workInProgress;
const type = hostFiber.type;
const props = hostFiber.pendingProps;
const isReady = preloadInstance(type, props);
if (isReady) {
// The data resolved. Resume the work loop as if nothing
// suspended. Unlike when a user component suspends, we don't
// have to replay anything because the host fiber
// already completed.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
const sibling = hostFiber.sibling;
if (sibling !== null) {
workInProgress = sibling;
} else {
const returnFiber = hostFiber.return;
if (returnFiber !== null) {
workInProgress = returnFiber;
completeUnitOfWork(returnFiber);
} else {
workInProgress = null;
}
}
break resumeOrUnwind;
}
break;
}
default: {
// This will fail gracefully but it's not correct, so log a
// warning in dev.
if (__DEV__) {
console.error(
'Unexpected type of fiber triggered a suspensey commit. ' +
'This is a bug in React.',
);
}
break;
}
}
// Otherwise, unwind then continue with the normal work loop.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
throwAndUnwindWorkLoop(unitOfWork, thrownValue);
break;
}
case SuspendedOnDeprecatedThrowPromise: {
// Suspended by an old implementation that uses the `throw promise`
// pattern. The newer replaying behavior can cause subtle issues
// like infinite ping loops. So we maintain the old behavior and
// always unwind.
workInProgressSuspendedReason = NotSuspended;
workInProgressThrownValue = null;
throwAndUnwindWorkLoop(unitOfWork, thrownValue);
break;
}
case SuspendedOnHydration: {
// Selective hydration. An update flowed into a dehydrated tree.
// Interrupt the current render so the work loop can switch to the
// hydration lane.
resetWorkInProgressStack();
workInProgressRootExitStatus = RootDidNotComplete;
break outer;
}
default: {
throw new Error(
'Unexpected SuspendedReason. This is a bug in React.',
);
}
}
}
if (__DEV__ && ReactCurrentActQueue.current !== null) {
// `act` special case: If we're inside an `act` scope, don't consult
// `shouldYield`. Always keep working until the render is complete.
// This is not just an optimization: in a unit test environment, we
// can't trust the result of `shouldYield`, because the host I/O is
// likely mocked.
workLoopSync();
} else {
workLoopConcurrent();
}
break;
} catch (thrownValue) {
handleThrow(root, thrownValue);
}
} while (true);
resetContextDependencies();
popDispatcher(prevDispatcher);
popCacheDispatcher(prevCacheDispatcher);
executionContext = prevExecutionContext;
if (__DEV__) {
if (enableDebugTracing) {
logRenderStopped();
}
}
// Check if the tree has completed.
if (workInProgress !== null) {
// Still work remaining.
if (enableSchedulingProfiler) {
markRenderYielded();
}
return RootInProgress;
} else {
// Completed the tree.
if (enableSchedulingProfiler) {
markRenderStopped();
}
// Set this to null to indicate there's no in-progress render.
workInProgressRoot = null;
workInProgressRootRenderLanes = NoLanes;
// It's safe to process the queue now that the render phase is complete.
finishQueueingConcurrentUpdates();
// Return the final exit status.
return workInProgressRootExitStatus;
}
}
/** @noinline */
function workLoopConcurrent() {
// Perform work until Scheduler asks us to yield
while (workInProgress !== null && !shouldYield()) {
// $FlowFixMe[incompatible-call] found when upgrading Flow
performUnitOfWork(workInProgress);
}
}
function performUnitOfWork(unitOfWork: Fiber): void {
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
const current = unitOfWork.alternate;
setCurrentDebugFiberInDEV(unitOfWork);
let next;
if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode) {
startProfilerTimer(unitOfWork);
next = beginWork(current, unitOfWork, entangledRenderLanes);
stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
} else {
next = beginWork(current, unitOfWork, entangledRenderLanes);
}
resetCurrentDebugFiberInDEV();
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) {
// If this doesn't spawn new work, complete the current work.
completeUnitOfWork(unitOfWork);
} else {
workInProgress = next;
}
ReactCurrentOwner.current = null;
}
function replaySuspendedUnitOfWork(unitOfWork: Fiber): void {
// This is a fork of performUnitOfWork specifcally for replaying a fiber that
// just suspended.
//
const current = unitOfWork.alternate;
setCurrentDebugFiberInDEV(unitOfWork);
let next;
setCurrentDebugFiberInDEV(unitOfWork);
const isProfilingMode =
enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoMode;
if (isProfilingMode) {
startProfilerTimer(unitOfWork);
}
switch (unitOfWork.tag) {
case IndeterminateComponent: {
// Because it suspended with `use`, we can assume it's a
// function component.
unitOfWork.tag = FunctionComponent;
// Fallthrough to the next branch.
}
case SimpleMemoComponent:
case FunctionComponent: {
// Resolve `defaultProps`. This logic is copied from `beginWork`.
// TODO: Consider moving this switch statement into that module. Also,
// could maybe use this as an opportunity to say `use` doesn't work with
// `defaultProps` :)
const Component = unitOfWork.type;
const unresolvedProps = unitOfWork.pendingProps;
const resolvedProps =
unitOfWork.elementType === Component
? unresolvedProps
: resolveDefaultProps(Component, unresolvedProps);
let context: any;
if (!disableLegacyContext) {
const unmaskedContext = getUnmaskedContext(unitOfWork, Component, true);
context = getMaskedContext(unitOfWork, unmaskedContext);
}
next = replayFunctionComponent(
current,
unitOfWork,
resolvedProps,
Component,
context,
workInProgressRootRenderLanes,
);
break;
}
case ForwardRef: {
// Resolve `defaultProps`. This logic is copied from `beginWork`.
// TODO: Consider moving this switch statement into that module. Also,
// could maybe use this as an opportunity to say `use` doesn't work with
// `defaultProps` :)
const Component = unitOfWork.type.render;
const unresolvedProps = unitOfWork.pendingProps;
const resolvedProps =
unitOfWork.elementType === Component
? unresolvedProps
: resolveDefaultProps(Component, unresolvedProps);
next = replayFunctionComponent(
current,
unitOfWork,
resolvedProps,
Component,
unitOfWork.ref,
workInProgressRootRenderLanes,
);
break;
}
case HostComponent: {
// Some host components are stateful (that's how we implement form
// actions) but we don't bother to reuse the memoized state because it's
// not worth the extra code. The main reason to reuse the previous hooks
// is to reuse uncached promises, but we happen to know that the only
// promises that a host component might suspend on are definitely cached
// because they are controlled by us. So don't bother.
resetHooksOnUnwind(unitOfWork);
// Fallthrough to the next branch.
}
default: {
// Other types besides function components are reset completely before
// being replayed. Currently this only happens when a Usable type is
// reconciled — the reconciler will suspend.
//
// We reset the fiber back to its original state; however, this isn't
// a full "unwind" because we're going to reuse the promises that were
// reconciled previously. So it's intentional that we don't call
// resetSuspendedWorkLoopOnUnwind here.
unwindInterruptedWork(current, unitOfWork, workInProgressRootRenderLanes);
unitOfWork = workInProgress = resetWorkInProgress(
unitOfWork,
entangledRenderLanes,
);
next = beginWork(current, unitOfWork, entangledRenderLanes);
break;
}
}
if (isProfilingMode) {
stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
}
// The begin phase finished successfully without suspending. Return to the
// normal work loop.
resetCurrentDebugFiberInDEV();
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) {
// If this doesn't spawn new work, complete the current work.
completeUnitOfWork(unitOfWork);
} else {
workInProgress = next;
}
ReactCurrentOwner.current = null;
}
function throwAndUnwindWorkLoop(unitOfWork: Fiber, thrownValue: mixed) {
// This is a fork of performUnitOfWork specifcally for unwinding a fiber
// that threw an exception.
//
// Return to the normal work loop. This will unwind the stack, and potentially
// result in showing a fallback.
resetSuspendedWorkLoopOnUnwind(unitOfWork);
const returnFiber = unitOfWork.return;
if (returnFiber === null || workInProgressRoot === null) {
// Expected to be working on a non-root fiber. This is a fatal error
// because there's no ancestor that can handle it; the root is
// supposed to capture all errors that weren't caught by an error
// boundary.
workInProgressRootExitStatus = RootFatalErrored;
workInProgressRootFatalError = thrownValue;
// Set `workInProgress` to null. This represents advancing to the next
// sibling, or the parent if there are no siblings. But since the root
// has no siblings nor a parent, we set it to null. Usually this is
// handled by `completeUnitOfWork` or `unwindWork`, but since we're
// intentionally not calling those, we need set it here.
// TODO: Consider calling `unwindWork` to pop the contexts.
workInProgress = null;
return;
}
try {
// Find and mark the nearest Suspense or error boundary that can handle
// this "exception".
throwException(
workInProgressRoot,
returnFiber,
unitOfWork,
thrownValue,
workInProgressRootRenderLanes,
);
} catch (error) {
// We had trouble processing the error. An example of this happening is
// when accessing the `componentDidCatch` property of an error boundary
// throws an error. A weird edge case. There's a regression test for this.
// To prevent an infinite loop, bubble the error up to the next parent.
workInProgress = returnFiber;
throw error;
}
if (unitOfWork.flags & Incomplete) {
// Unwind the stack until we reach the nearest boundary.
unwindUnitOfWork(unitOfWork);
} else {
// Although the fiber suspended, we're intentionally going to commit it in
// an inconsistent state. We can do this safely in cases where we know the
// inconsistent tree will be hidden.
//
// This currently only applies to Legacy Suspense implementation, but we may
// port a version of this to concurrent roots, too, when performing a
// synchronous render. Because that will allow us to mutate the tree as we
// go instead of buffering mutations until the end. Though it's unclear if
// this particular path is how that would be implemented.
completeUnitOfWork(unitOfWork);
}
}
function completeUnitOfWork(unitOfWork: Fiber): void {
// Attempt to complete the current unit of work, then move to the next
// sibling. If there are no more siblings, return to the parent fiber.
let completedWork: Fiber = unitOfWork;
do {
if (__DEV__) {
if ((completedWork.flags & Incomplete) !== NoFlags) {
// NOTE: If we re-enable sibling prerendering in some cases, this branch
// is where we would switch to the unwinding path.
console.error(
'Internal React error: Expected this fiber to be complete, but ' +
"it isn't. It should have been unwound. This is a bug in React.",
);
}
}
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
const current = completedWork.alternate;
const returnFiber = completedWork.return;
setCurrentDebugFiberInDEV(completedWork);
let next;
if (!enableProfilerTimer || (completedWork.mode & ProfileMode) === NoMode) {
next = completeWork(current, completedWork, entangledRenderLanes);
} else {
startProfilerTimer(completedWork);
next = completeWork(current, completedWork, entangledRenderLanes);
// Update render duration assuming we didn't error.
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
}
resetCurrentDebugFiberInDEV();
if (next !== null) {
// Completing this fiber spawned new work. Work on that next.
workInProgress = next;
return;
}
const siblingFiber = completedWork.sibling;
if (siblingFiber !== null) {
// If there is more work to do in this returnFiber, do that next.
workInProgress = siblingFiber;
return;
}
// Otherwise, return to the parent
// $FlowFixMe[incompatible-type] we bail out when we get a null
completedWork = returnFiber;
// Update the next thing we're working on in case something throws.
workInProgress = completedWork;
} while (completedWork !== null);
// We've reached the root.
if (workInProgressRootExitStatus === RootInProgress) {
workInProgressRootExitStatus = RootCompleted;
}
}
function unwindUnitOfWork(unitOfWork: Fiber): void {
let incompleteWork: Fiber = unitOfWork;
do {
// The current, flushed, state of this fiber is the alternate. Ideally
// nothing should rely on this, but relying on it here means that we don't
// need an additional field on the work in progress.
const current = incompleteWork.alternate;
// This fiber did not complete because something threw. Pop values off
// the stack without entering the complete phase. If this is a boundary,
// capture values if possible.
const next = unwindWork(current, incompleteWork, entangledRenderLanes);
// Because this fiber did not complete, don't reset its lanes.
if (next !== null) {
// Found a boundary that can handle this exception. Re-renter the
// begin phase. This branch will return us to the normal work loop.
//
// Since we're restarting, remove anything that is not a host effect
// from the effect tag.
next.flags &= HostEffectMask;
workInProgress = next;
return;
}
// Keep unwinding until we reach either a boundary or the root.
if (enableProfilerTimer && (incompleteWork.mode & ProfileMode) !== NoMode) {
// Record the render duration for the fiber that errored.
stopProfilerTimerIfRunningAndRecordDelta(incompleteWork, false);
// Include the time spent working on failed children before continuing.
let actualDuration = incompleteWork.actualDuration;
let child = incompleteWork.child;
while (child !== null) {
// $FlowFixMe[unsafe-addition] addition with possible null/undefined value
actualDuration += child.actualDuration;
child = child.sibling;
}
incompleteWork.actualDuration = actualDuration;
}
// TODO: Once we stop prerendering siblings, instead of resetting the parent
// of the node being unwound, we should be able to reset node itself as we
// unwind the stack. Saves an additional null check.
const returnFiber = incompleteWork.return;
if (returnFiber !== null) {
// Mark the parent fiber as incomplete and clear its subtree flags.
// TODO: Once we stop prerendering siblings, we may be able to get rid of
// the Incomplete flag because unwinding to the nearest boundary will
// happen synchronously.
returnFiber.flags |= Incomplete;
returnFiber.subtreeFlags = NoFlags;
returnFiber.deletions = null;
}
// NOTE: If we re-enable sibling prerendering in some cases, here we
// would switch to the normal completion path: check if a sibling
// exists, and if so, begin work on it.
// Otherwise, return to the parent
// $FlowFixMe[incompatible-type] we bail out when we get a null
incompleteWork = returnFiber;
// Update the next thing we're working on in case something throws.
workInProgress = incompleteWork;
} while (incompleteWork !== null);
// We've unwound all the way to the root.
workInProgressRootExitStatus = RootDidNotComplete;
workInProgress = null;
}
function commitRoot(
root: FiberRoot,
recoverableErrors: null | Array<CapturedValue<mixed>>,
transitions: Array<Transition> | null,
spawnedLane: Lane,
) {
// TODO: This no longer makes any sense. We already wrap the mutation and
// layout phases. Should be able to remove.
const previousUpdateLanePriority = getCurrentUpdatePriority();
const prevTransition = ReactCurrentBatchConfig.transition;
try {
ReactCurrentBatchConfig.transition = null;
setCurrentUpdatePriority(DiscreteEventPriority);
commitRootImpl(
root,
recoverableErrors,
transitions,
previousUpdateLanePriority,
spawnedLane,
);
} finally {
ReactCurrentBatchConfig.transition = prevTransition;
setCurrentUpdatePriority(previousUpdateLanePriority);
}
return null;
}
function commitRootImpl(
root: FiberRoot,
recoverableErrors: null | Array<CapturedValue<mixed>>,
transitions: Array<Transition> | null,
renderPriorityLevel: EventPriority,
spawnedLane: Lane,
) {
do {
// `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
// means `flushPassiveEffects` will sometimes result in additional
// passive effects. So we need to keep flushing in a loop until there are
// no more pending effects.
// TODO: Might be better if `flushPassiveEffects` did not automatically
// flush synchronous work at the end, to avoid factoring hazards like this.
flushPassiveEffects();
} while (rootWithPendingPassiveEffects !== null);
flushRenderPhaseStrictModeWarningsInDEV();
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Should not already be working.');
}
const finishedWork = root.finishedWork;
const lanes = root.finishedLanes;
if (__DEV__) {
if (enableDebugTracing) {
logCommitStarted(lanes);
}
}
if (enableSchedulingProfiler) {
markCommitStarted(lanes);
}
if (finishedWork === null) {
if (__DEV__) {
if (enableDebugTracing) {
logCommitStopped();
}
}
if (enableSchedulingProfiler) {
markCommitStopped();
}
return null;
} else {
if (__DEV__) {
if (lanes === NoLanes) {
console.error(
'root.finishedLanes should not be empty during a commit. This is a ' +
'bug in React.',
);
}
}
}
root.finishedWork = null;
root.finishedLanes = NoLanes;
if (finishedWork === root.current) {
throw new Error(
'Cannot commit the same tree as before. This error is likely caused by ' +
'a bug in React. Please file an issue.',
);
}
// commitRoot never returns a continuation; it always finishes synchronously.
// So we can clear these now to allow a new callback to be scheduled.
root.callbackNode = null;
root.callbackPriority = NoLane;
root.cancelPendingCommit = null;
// Check which lanes no longer have any work scheduled on them, and mark
// those as finished.
let remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
// Make sure to account for lanes that were updated by a concurrent event
// during the render phase; don't mark them as finished.
const concurrentlyUpdatedLanes = getConcurrentlyUpdatedLanes();
remainingLanes = mergeLanes(remainingLanes, concurrentlyUpdatedLanes);
markRootFinished(root, remainingLanes, spawnedLane);
if (root === workInProgressRoot) {
// We can reset these now that they are finished.
workInProgressRoot = null;
workInProgress = null;
workInProgressRootRenderLanes = NoLanes;
} else {
// This indicates that the last root we worked on is not the same one that
// we're committing now. This most commonly happens when a suspended root
// times out.
}
// If there are pending passive effects, schedule a callback to process them.
// Do this as early as possible, so it is queued before anything else that
// might get scheduled in the commit phase. (See #16714.)
// TODO: Delete all other places that schedule the passive effect callback
// They're redundant.
if (
(finishedWork.subtreeFlags & PassiveMask) !== NoFlags ||
(finishedWork.flags & PassiveMask) !== NoFlags
) {
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
pendingPassiveEffectsRemainingLanes = remainingLanes;
// workInProgressTransitions might be overwritten, so we want
// to store it in pendingPassiveTransitions until they get processed
// We need to pass this through as an argument to commitRoot
// because workInProgressTransitions might have changed between
// the previous render and commit if we throttle the commit
// with setTimeout
pendingPassiveTransitions = transitions;
scheduleCallback(NormalSchedulerPriority, () => {
flushPassiveEffects();
// This render triggered passive effects: release the root cache pool
// *after* passive effects fire to avoid freeing a cache pool that may
// be referenced by a node in the tree (HostRoot, Cache boundary etc)
return null;
});
}
}
// Check if there are any effects in the whole tree.
// TODO: This is left over from the effect list implementation, where we had
// to check for the existence of `firstEffect` to satisfy Flow. I think the
// only other reason this optimization exists is because it affects profiling.
// Reconsider whether this is necessary.
const subtreeHasEffects =
(finishedWork.subtreeFlags &
(BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !==
NoFlags;
const rootHasEffect =
(finishedWork.flags &
(BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !==
NoFlags;
if (subtreeHasEffects || rootHasEffect) {
const prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = null;
const previousPriority = getCurrentUpdatePriority();
setCurrentUpdatePriority(DiscreteEventPriority);
const prevExecutionContext = executionContext;
executionContext |= CommitContext;
// Reset this to null before calling lifecycles
ReactCurrentOwner.current = null;
// The commit phase is broken into several sub-phases. We do a separate pass
// of the effect list for each phase: all mutation effects come before all
// layout effects, and so on.
// The first phase a "before mutation" phase. We use this phase to read the
// state of the host tree right before we mutate it. This is where
// getSnapshotBeforeUpdate is called.
const shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(
root,
finishedWork,
);
if (enableProfilerTimer) {
// Mark the current commit time to be shared by all Profilers in this
// batch. This enables them to be grouped later.
recordCommitTime();
}
if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
// Track the root here, rather than in commitLayoutEffects(), because of ref setters.
// Updates scheduled during ref detachment should also be flagged.
rootCommittingMutationOrLayoutEffects = root;
}
// The next phase is the mutation phase, where we mutate the host tree.
commitMutationEffects(root, finishedWork, lanes);
if (enableCreateEventHandleAPI) {
if (shouldFireAfterActiveInstanceBlur) {
afterActiveInstanceBlur();
}
}
resetAfterCommit(root.containerInfo);
// The work-in-progress tree is now the current tree. This must come after
// the mutation phase, so that the previous tree is still current during
// componentWillUnmount, but before the layout phase, so that the finished
// work is current during componentDidMount/Update.
root.current = finishedWork;
// The next phase is the layout phase, where we call effects that read
// the host tree after it's been mutated. The idiomatic use case for this is
// layout, but class component lifecycles also fire here for legacy reasons.
if (__DEV__) {
if (enableDebugTracing) {
logLayoutEffectsStarted(lanes);
}
}
if (enableSchedulingProfiler) {
markLayoutEffectsStarted(lanes);
}
commitLayoutEffects(finishedWork, root, lanes);
if (__DEV__) {
if (enableDebugTracing) {
logLayoutEffectsStopped();
}
}
if (enableSchedulingProfiler) {
markLayoutEffectsStopped();
}
if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
rootCommittingMutationOrLayoutEffects = null;
}
// Tell Scheduler to yield at the end of the frame, so the browser has an
// opportunity to paint.
requestPaint();
executionContext = prevExecutionContext;
// Reset the priority to the previous non-sync value.
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
} else {
// No effects.
root.current = finishedWork;
// Measure these anyway so the flamegraph explicitly shows that there were
// no effects.
// TODO: Maybe there's a better way to report this.
if (enableProfilerTimer) {
recordCommitTime();
}
}
const rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
if (rootDoesHavePassiveEffects) {
// This commit has passive effects. Stash a reference to them. But don't
// schedule a callback until after flushing layout work.
rootDoesHavePassiveEffects = false;
rootWithPendingPassiveEffects = root;
pendingPassiveEffectsLanes = lanes;
} else {
// There were no passive effects, so we can immediately release the cache
// pool for this render.
releaseRootPooledCache(root, remainingLanes);
if (__DEV__) {
nestedPassiveUpdateCount = 0;
rootWithPassiveNestedUpdates = null;
}
}
// Read this again, since an effect might have updated it
remainingLanes = root.pendingLanes;
// Check if there's remaining work on this root
// TODO: This is part of the `componentDidCatch` implementation. Its purpose
// is to detect whether something might have called setState inside
// `componentDidCatch`. The mechanism is known to be flawed because `setState`
// inside `componentDidCatch` is itself flawed — that's why we recommend
// `getDerivedStateFromError` instead. However, it could be improved by
// checking if remainingLanes includes Sync work, instead of whether there's
// any work remaining at all (which would also include stuff like Suspense
// retries or transitions). It's been like this for a while, though, so fixing
// it probably isn't that urgent.
if (remainingLanes === NoLanes) {
// If there's no remaining work, we can clear the set of already failed
// error boundaries.
legacyErrorBoundariesThatAlreadyFailed = null;
}
if (__DEV__) {
if (!rootDidHavePassiveEffects) {
commitDoubleInvokeEffectsInDEV(root, false);
}
}
onCommitRootDevTools(finishedWork.stateNode, renderPriorityLevel);
if (enableUpdaterTracking) {
if (isDevToolsPresent) {
root.memoizedUpdaters.clear();
}
}
if (__DEV__) {
onCommitRootTestSelector();
}
// Always call this before exiting `commitRoot`, to ensure that any
// additional work on this root is scheduled.
ensureRootIsScheduled(root);
if (recoverableErrors !== null) {
// There were errors during this render, but recovered from them without
// needing to surface it to the UI. We log them here.
const onRecoverableError = root.onRecoverableError;
for (let i = 0; i < recoverableErrors.length; i++) {
const recoverableError = recoverableErrors[i];
const errorInfo = makeErrorInfo(
recoverableError.digest,
recoverableError.stack,
);
onRecoverableError(recoverableError.value, errorInfo);
}
}
if (hasUncaughtError) {
hasUncaughtError = false;
const error = firstUncaughtError;
firstUncaughtError = null;
throw error;
}
// If the passive effects are the result of a discrete render, flush them
// synchronously at the end of the current task so that the result is
// immediately observable. Otherwise, we assume that they are not
// order-dependent and do not need to be observed by external systems, so we
// can wait until after paint.
// TODO: We can optimize this by not scheduling the callback earlier. Since we
// currently schedule the callback in multiple places, will wait until those
// are consolidated.
if (includesSyncLane(pendingPassiveEffectsLanes) && root.tag !== LegacyRoot) {
flushPassiveEffects();
}
// Read this again, since a passive effect might have updated it
remainingLanes = root.pendingLanes;
// Check if this render scheduled a cascading synchronous update. This is a
// heurstic to detect infinite update loops. We are intentionally excluding
// hydration lanes in this check, because render triggered by selective
// hydration is conceptually not an update.
if (
// Was the finished render the result of an update (not hydration)?
includesSomeLane(lanes, UpdateLanes) &&
// Did it schedule a sync update?
includesSomeLane(remainingLanes, SyncUpdateLanes)
) {
if (enableProfilerTimer && enableProfilerNestedUpdatePhase) {
markNestedUpdateScheduled();
}
// Count the number of times the root synchronously re-renders without
// finishing. If there are too many, it indicates an infinite update loop.
if (root === rootWithNestedUpdates) {
nestedUpdateCount++;
} else {
nestedUpdateCount = 0;
rootWithNestedUpdates = root;
}
} else {
nestedUpdateCount = 0;
}
// If layout work was scheduled, flush it now.
flushSyncWorkOnAllRoots();
if (__DEV__) {
if (enableDebugTracing) {
logCommitStopped();
}
}
if (enableSchedulingProfiler) {
markCommitStopped();
}
if (enableTransitionTracing) {
// We process transitions during passive effects. However, passive effects can be
// processed synchronously during the commit phase as well as asynchronously after
// paint. At the end of the commit phase, we schedule a callback that will be called
// after the next paint. If the transitions have already been processed (passive
// effect phase happened synchronously), we will schedule a callback to process
// the transitions. However, if we don't have any pending transition callbacks, this
// means that the transitions have yet to be processed (passive effects processed after paint)
// so we will store the end time of paint so that we can process the transitions
// and then call the callback via the correct end time.
const prevRootTransitionCallbacks = root.transitionCallbacks;
if (prevRootTransitionCallbacks !== null) {
schedulePostPaintCallback(endTime => {
const prevPendingTransitionCallbacks =
currentPendingTransitionCallbacks;
if (prevPendingTransitionCallbacks !== null) {
currentPendingTransitionCallbacks = null;
scheduleCallback(IdleSchedulerPriority, () => {
processTransitionCallbacks(
prevPendingTransitionCallbacks,
endTime,
prevRootTransitionCallbacks,
);
});
} else {
currentEndTime = endTime;
}
});
}
}
return null;
}
function makeErrorInfo(digest: ?string, componentStack: ?string) {
if (__DEV__) {
const errorInfo = {
componentStack,
digest,
};
Object.defineProperty(errorInfo, 'digest', {
configurable: false,
enumerable: true,
get() {
console.error(
'You are accessing "digest" from the errorInfo object passed to onRecoverableError.' +
' This property is deprecated and will be removed in a future version of React.' +
' To access the digest of an Error look for this property on the Error instance itself.',
);
return digest;
},
});
return errorInfo;
} else {
return {
digest,
componentStack,
};
}
}
function releaseRootPooledCache(root: FiberRoot, remainingLanes: Lanes) {
if (enableCache) {
const pooledCacheLanes = (root.pooledCacheLanes &= remainingLanes);
if (pooledCacheLanes === NoLanes) {
// None of the remaining work relies on the cache pool. Clear it so
// subsequent requests get a new cache
const pooledCache = root.pooledCache;
if (pooledCache != null) {
root.pooledCache = null;
releaseCache(pooledCache);
}
}
}
}
export function flushPassiveEffects(): boolean {
// Returns whether passive effects were flushed.
// TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
// probably just combine the two functions. I believe they were only separate
// in the first place because we used to wrap it with
// `Scheduler.runWithPriority`, which accepts a function. But now we track the
// priority within React itself, so we can mutate the variable directly.
if (rootWithPendingPassiveEffects !== null) {
// Cache the root since rootWithPendingPassiveEffects is cleared in
// flushPassiveEffectsImpl
const root = rootWithPendingPassiveEffects;
// Cache and clear the remaining lanes flag; it must be reset since this
// method can be called from various places, not always from commitRoot
// where the remaining lanes are known
const remainingLanes = pendingPassiveEffectsRemainingLanes;
pendingPassiveEffectsRemainingLanes = NoLanes;
const renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
const priority = lowerEventPriority(DefaultEventPriority, renderPriority);
const prevTransition = ReactCurrentBatchConfig.transition;
const previousPriority = getCurrentUpdatePriority();
try {
ReactCurrentBatchConfig.transition = null;
setCurrentUpdatePriority(priority);
return flushPassiveEffectsImpl();
} finally {
setCurrentUpdatePriority(previousPriority);
ReactCurrentBatchConfig.transition = prevTransition;
// Once passive effects have run for the tree - giving components a
// chance to retain cache instances they use - release the pooled
// cache at the root (if there is one)
releaseRootPooledCache(root, remainingLanes);
}
}
return false;
}
export function enqueuePendingPassiveProfilerEffect(fiber: Fiber): void {
if (enableProfilerTimer && enableProfilerCommitHooks) {
pendingPassiveProfilerEffects.push(fiber);
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalSchedulerPriority, () => {
flushPassiveEffects();
return null;
});
}
}
}
function flushPassiveEffectsImpl() {
if (rootWithPendingPassiveEffects === null) {
return false;
}
// Cache and clear the transitions flag
const transitions = pendingPassiveTransitions;
pendingPassiveTransitions = null;
const root = rootWithPendingPassiveEffects;
const lanes = pendingPassiveEffectsLanes;
rootWithPendingPassiveEffects = null;
// TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
// Figure out why and fix it. It's not causing any known issues (probably
// because it's only used for profiling), but it's a refactor hazard.
pendingPassiveEffectsLanes = NoLanes;
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
throw new Error('Cannot flush passive effects while already rendering.');
}
if (__DEV__) {
isFlushingPassiveEffects = true;
didScheduleUpdateDuringPassiveEffects = false;
if (enableDebugTracing) {
logPassiveEffectsStarted(lanes);
}
}
if (enableSchedulingProfiler) {
markPassiveEffectsStarted(lanes);
}
const prevExecutionContext = executionContext;
executionContext |= CommitContext;
commitPassiveUnmountEffects(root.current);
commitPassiveMountEffects(root, root.current, lanes, transitions);
// TODO: Move to commitPassiveMountEffects
if (enableProfilerTimer && enableProfilerCommitHooks) {
const profilerEffects = pendingPassiveProfilerEffects;
pendingPassiveProfilerEffects = [];
for (let i = 0; i < profilerEffects.length; i++) {
const fiber = ((profilerEffects[i]: any): Fiber);
commitPassiveEffectDurations(root, fiber);
}
}
if (__DEV__) {
if (enableDebugTracing) {
logPassiveEffectsStopped();
}
}
if (enableSchedulingProfiler) {
markPassiveEffectsStopped();
}
if (__DEV__) {
commitDoubleInvokeEffectsInDEV(root, true);
}
executionContext = prevExecutionContext;
flushSyncWorkOnAllRoots();
if (enableTransitionTracing) {
const prevPendingTransitionCallbacks = currentPendingTransitionCallbacks;
const prevRootTransitionCallbacks = root.transitionCallbacks;
const prevEndTime = currentEndTime;
if (
prevPendingTransitionCallbacks !== null &&
prevRootTransitionCallbacks !== null &&
prevEndTime !== null
) {
currentPendingTransitionCallbacks = null;
currentEndTime = null;
scheduleCallback(IdleSchedulerPriority, () => {
processTransitionCallbacks(
prevPendingTransitionCallbacks,
prevEndTime,
prevRootTransitionCallbacks,
);
});
}
}
if (__DEV__) {
// If additional passive effects were scheduled, increment a counter. If this
// exceeds the limit, we'll fire a warning.
if (didScheduleUpdateDuringPassiveEffects) {
if (root === rootWithPassiveNestedUpdates) {
nestedPassiveUpdateCount++;
} else {
nestedPassiveUpdateCount = 0;
rootWithPassiveNestedUpdates = root;
}
} else {
nestedPassiveUpdateCount = 0;
}
isFlushingPassiveEffects = false;
didScheduleUpdateDuringPassiveEffects = false;
}
// TODO: Move to commitPassiveMountEffects
onPostCommitRootDevTools(root);
if (enableProfilerTimer && enableProfilerCommitHooks) {
const stateNode = root.current.stateNode;
stateNode.effectDuration = 0;
stateNode.passiveEffectDuration = 0;
}
return true;
}
export function isAlreadyFailedLegacyErrorBoundary(instance: mixed): boolean {
return (
legacyErrorBoundariesThatAlreadyFailed !== null &&
legacyErrorBoundariesThatAlreadyFailed.has(instance)
);
}
export function markLegacyErrorBoundaryAsFailed(instance: mixed) {
if (legacyErrorBoundariesThatAlreadyFailed === null) {
legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
} else {
legacyErrorBoundariesThatAlreadyFailed.add(instance);
}
}
function prepareToThrowUncaughtError(error: mixed) {
if (!hasUncaughtError) {
hasUncaughtError = true;
firstUncaughtError = error;
}
}
export const onUncaughtError = prepareToThrowUncaughtError;
function captureCommitPhaseErrorOnRoot(
rootFiber: Fiber,
sourceFiber: Fiber,
error: mixed,
) {
const errorInfo = createCapturedValueAtFiber(error, sourceFiber);
const update = createRootErrorUpdate(rootFiber, errorInfo, (SyncLane: Lane));
const root = enqueueUpdate(rootFiber, update, (SyncLane: Lane));
if (root !== null) {
markRootUpdated(root, SyncLane);
ensureRootIsScheduled(root);
}
}
export function captureCommitPhaseError(
sourceFiber: Fiber,
nearestMountedAncestor: Fiber | null,
error: mixed,
) {
if (__DEV__) {
reportUncaughtErrorInDEV(error);
setIsRunningInsertionEffect(false);
}
if (sourceFiber.tag === HostRoot) {
// Error was thrown at the root. There is no parent, so the root
// itself should capture it.
captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
return;
}
let fiber = nearestMountedAncestor;
while (fiber !== null) {
if (fiber.tag === HostRoot) {
captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
return;
} else if (fiber.tag === ClassComponent) {
const ctor = fiber.type;
const instance = fiber.stateNode;
if (
typeof ctor.getDerivedStateFromError === 'function' ||
(typeof instance.componentDidCatch === 'function' &&
!isAlreadyFailedLegacyErrorBoundary(instance))
) {
const errorInfo = createCapturedValueAtFiber(error, sourceFiber);
const update = createClassErrorUpdate(
fiber,
errorInfo,
(SyncLane: Lane),
);
const root = enqueueUpdate(fiber, update, (SyncLane: Lane));
if (root !== null) {
markRootUpdated(root, SyncLane);
ensureRootIsScheduled(root);
}
return;
}
}
fiber = fiber.return;
}
if (__DEV__) {
console.error(
'Internal React error: Attempted to capture a commit phase error ' +
'inside a detached tree. This indicates a bug in React. Potential ' +
'causes include deleting the same fiber more than once, committing an ' +
'already-finished tree, or an inconsistent return pointer.\n\n' +
'Error message:\n\n%s',
error,
);
}
}
export function attachPingListener(
root: FiberRoot,
wakeable: Wakeable,
lanes: Lanes,
) {
// Attach a ping listener
//
// The data might resolve before we have a chance to commit the fallback. Or,
// in the case of a refresh, we'll never commit a fallback. So we need to
// attach a listener now. When it resolves ("pings"), we can decide whether to
// try rendering the tree again.
//
// Only attach a listener if one does not already exist for the lanes
// we're currently rendering (which acts like a "thread ID" here).
//
// We only need to do this in concurrent mode. Legacy Suspense always
// commits fallbacks synchronously, so there are no pings.
let pingCache = root.pingCache;
let threadIDs;
if (pingCache === null) {
pingCache = root.pingCache = new PossiblyWeakMap();
threadIDs = new Set<mixed>();
pingCache.set(wakeable, threadIDs);
} else {
threadIDs = pingCache.get(wakeable);
if (threadIDs === undefined) {
threadIDs = new Set();
pingCache.set(wakeable, threadIDs);
}
}
if (!threadIDs.has(lanes)) {
workInProgressRootDidAttachPingListener = true;
// Memoize using the thread ID to prevent redundant listeners.
threadIDs.add(lanes);
const ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);
if (enableUpdaterTracking) {
if (isDevToolsPresent) {
// If we have pending work still, restore the original updaters
restorePendingUpdaters(root, lanes);
}
}
wakeable.then(ping, ping);
}
}
function pingSuspendedRoot(
root: FiberRoot,
wakeable: Wakeable,
pingedLanes: Lanes,
) {
const pingCache = root.pingCache;
if (pingCache !== null) {
// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
pingCache.delete(wakeable);
}
markRootPinged(root, pingedLanes);
warnIfSuspenseResolutionNotWrappedWithActDEV(root);
if (
workInProgressRoot === root &&
isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)
) {
// Received a ping at the same priority level at which we're currently
// rendering. We might want to restart this render. This should mirror
// the logic of whether or not a root suspends once it completes.
// TODO: If we're rendering sync either due to Sync, Batched or expired,
// we should probably never restart.
// If we're suspended with delay, or if it's a retry, we'll always suspend
// so we can always restart.
if (
workInProgressRootExitStatus === RootSuspendedWithDelay ||
(workInProgressRootExitStatus === RootSuspended &&
includesOnlyRetries(workInProgressRootRenderLanes) &&
now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS)
) {
// Force a restart from the root by unwinding the stack. Unless this is
// being called from the render phase, because that would cause a crash.
if ((executionContext & RenderContext) === NoContext) {
prepareFreshStack(root, NoLanes);
} else {
// TODO: If this does happen during the render phase, we should throw
// the special internal exception that we use to interrupt the stack for
// selective hydration. That was temporarily reverted but we once we add
// it back we can use it here.
}
} else {
// Even though we can't restart right now, we might get an
// opportunity later. So we mark this render as having a ping.
workInProgressRootPingedLanes = mergeLanes(
workInProgressRootPingedLanes,
pingedLanes,
);
}
}
ensureRootIsScheduled(root);
}
function retryTimedOutBoundary(boundaryFiber: Fiber, retryLane: Lane) {
// The boundary fiber (a Suspense component or SuspenseList component)
// previously was rendered in its fallback state. One of the promises that
// suspended it has resolved, which means at least part of the tree was
// likely unblocked. Try rendering again, at a new lanes.
if (retryLane === NoLane) {
// TODO: Assign this to `suspenseState.retryLane`? to avoid
// unnecessary entanglement?
retryLane = requestRetryLane(boundaryFiber);
}
// TODO: Special case idle priority?
const root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
if (root !== null) {
markRootUpdated(root, retryLane);
ensureRootIsScheduled(root);
}
}
export function retryDehydratedSuspenseBoundary(boundaryFiber: Fiber) {
const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;
let retryLane = NoLane;
if (suspenseState !== null) {
retryLane = suspenseState.retryLane;
}
retryTimedOutBoundary(boundaryFiber, retryLane);
}
export function resolveRetryWakeable(boundaryFiber: Fiber, wakeable: Wakeable) {
let retryLane = NoLane; // Default
let retryCache: WeakSet<Wakeable> | Set<Wakeable> | null;
switch (boundaryFiber.tag) {
case SuspenseComponent:
retryCache = boundaryFiber.stateNode;
const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;
if (suspenseState !== null) {
retryLane = suspenseState.retryLane;
}
break;
case SuspenseListComponent:
retryCache = boundaryFiber.stateNode;
break;
case OffscreenComponent: {
const instance: OffscreenInstance = boundaryFiber.stateNode;
retryCache = instance._retryCache;
break;
}
default:
throw new Error(
'Pinged unknown suspense boundary type. ' +
'This is probably a bug in React.',
);
}
if (retryCache !== null) {
// The wakeable resolved, so we no longer need to memoize, because it will
// never be thrown again.
retryCache.delete(wakeable);
}
retryTimedOutBoundary(boundaryFiber, retryLane);
}
export function throwIfInfiniteUpdateLoopDetected() {
if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
nestedUpdateCount = 0;
nestedPassiveUpdateCount = 0;
rootWithNestedUpdates = null;
rootWithPassiveNestedUpdates = null;
throw new Error(
'Maximum update depth exceeded. This can happen when a component ' +
'repeatedly calls setState inside componentWillUpdate or ' +
'componentDidUpdate. React limits the number of nested updates to ' +
'prevent infinite loops.',
);
}
if (__DEV__) {
if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
nestedPassiveUpdateCount = 0;
rootWithPassiveNestedUpdates = null;
console.error(
'Maximum update depth exceeded. This can happen when a component ' +
"calls setState inside useEffect, but useEffect either doesn't " +
'have a dependency array, or one of the dependencies changes on ' +
'every render.',
);
}
}
}
function flushRenderPhaseStrictModeWarningsInDEV() {
if (__DEV__) {
ReactStrictModeWarnings.flushLegacyContextWarning();
ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
}
}
function recursivelyTraverseAndDoubleInvokeEffectsInDEV(
root: FiberRoot,
parentFiber: Fiber,
isInStrictMode: boolean,
) {
if ((parentFiber.subtreeFlags & (PlacementDEV | Visibility)) === NoFlags) {
// Parent's descendants have already had effects double invoked.
// Early exit to avoid unnecessary tree traversal.
return;
}
let child = parentFiber.child;
while (child !== null) {
doubleInvokeEffectsInDEVIfNecessary(root, child, isInStrictMode);
child = child.sibling;
}
}
// Unconditionally disconnects and connects passive and layout effects.
function doubleInvokeEffectsOnFiber(
root: FiberRoot,
fiber: Fiber,
shouldDoubleInvokePassiveEffects: boolean = true,
) {
disappearLayoutEffects(fiber);
if (shouldDoubleInvokePassiveEffects) {
disconnectPassiveEffect(fiber);
}
reappearLayoutEffects(root, fiber.alternate, fiber, false);
if (shouldDoubleInvokePassiveEffects) {
reconnectPassiveEffects(root, fiber, NoLanes, null, false);
}
}
function doubleInvokeEffectsInDEVIfNecessary(
root: FiberRoot,
fiber: Fiber,
parentIsInStrictMode: boolean,
) {
const isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
const isInStrictMode = parentIsInStrictMode || isStrictModeFiber;
// First case: the fiber **is not** of type OffscreenComponent. No
// special rules apply to double invoking effects.
if (fiber.tag !== OffscreenComponent) {
if (fiber.flags & PlacementDEV) {
setCurrentDebugFiberInDEV(fiber);
if (isInStrictMode) {
doubleInvokeEffectsOnFiber(
root,
fiber,
(fiber.mode & NoStrictPassiveEffectsMode) === NoMode,
);
}
resetCurrentDebugFiberInDEV();
} else {
recursivelyTraverseAndDoubleInvokeEffectsInDEV(
root,
fiber,
isInStrictMode,
);
}
return;
}
// Second case: the fiber **is** of type OffscreenComponent.
// This branch contains cases specific to Offscreen.
if (fiber.memoizedState === null) {
// Only consider Offscreen that is visible.
// TODO (Offscreen) Handle manual mode.
setCurrentDebugFiberInDEV(fiber);
if (isInStrictMode && fiber.flags & Visibility) {
// Double invoke effects on Offscreen's subtree only
// if it is visible and its visibility has changed.
doubleInvokeEffectsOnFiber(root, fiber);
} else if (fiber.subtreeFlags & PlacementDEV) {
// Something in the subtree could have been suspended.
// We need to continue traversal and find newly inserted fibers.
recursivelyTraverseAndDoubleInvokeEffectsInDEV(
root,
fiber,
isInStrictMode,
);
}
resetCurrentDebugFiberInDEV();
}
}
function commitDoubleInvokeEffectsInDEV(
root: FiberRoot,
hasPassiveEffects: boolean,
) {
if (__DEV__) {
if (useModernStrictMode) {
let doubleInvokeEffects = true;
if (root.tag === LegacyRoot && !(root.current.mode & StrictLegacyMode)) {
doubleInvokeEffects = false;
}
if (
root.tag === ConcurrentRoot &&
!(root.current.mode & (StrictLegacyMode | StrictEffectsMode))
) {
doubleInvokeEffects = false;
}
recursivelyTraverseAndDoubleInvokeEffectsInDEV(
root,
root.current,
doubleInvokeEffects,
);
} else {
legacyCommitDoubleInvokeEffectsInDEV(root.current, hasPassiveEffects);
}
}
}
function legacyCommitDoubleInvokeEffectsInDEV(
fiber: Fiber,
hasPassiveEffects: boolean,
) {
// TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
// so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
// Maybe not a big deal since this is DEV only behavior.
setCurrentDebugFiberInDEV(fiber);
invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);
if (hasPassiveEffects) {
invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
}
invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);
if (hasPassiveEffects) {
invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
}
resetCurrentDebugFiberInDEV();
}
function invokeEffectsInDev(
firstChild: Fiber,
fiberFlags: Flags,
invokeEffectFn: (fiber: Fiber) => void,
) {
let current: null | Fiber = firstChild;
let subtreeRoot = null;
while (current != null) {
const primarySubtreeFlag = current.subtreeFlags & fiberFlags;
if (
current !== subtreeRoot &&
current.child != null &&
primarySubtreeFlag !== NoFlags
) {
current = current.child;
} else {
if ((current.flags & fiberFlags) !== NoFlags) {
invokeEffectFn(current);
}
if (current.sibling !== null) {
current = current.sibling;
} else {
current = subtreeRoot = current.return;
}
}
}
}
let didWarnStateUpdateForNotYetMountedComponent: Set<string> | null = null;
export function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber: Fiber) {
if (__DEV__) {
if ((executionContext & RenderContext) !== NoContext) {
// We let the other warning about render phase updates deal with this one.
return;
}
if (!(fiber.mode & ConcurrentMode)) {
return;
}
const tag = fiber.tag;
if (
tag !== IndeterminateComponent &&
tag !== HostRoot &&
tag !== ClassComponent &&
tag !== FunctionComponent &&
tag !== ForwardRef &&
tag !== MemoComponent &&
tag !== SimpleMemoComponent
) {
// Only warn for user-defined components, not internal ones like Suspense.
return;
}
// We show the whole stack but dedupe on the top component's name because
// the problematic code almost always lies inside that component.
const componentName = getComponentNameFromFiber(fiber) || 'ReactComponent';
if (didWarnStateUpdateForNotYetMountedComponent !== null) {
if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
return;
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
didWarnStateUpdateForNotYetMountedComponent.add(componentName);
} else {
didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
}
const previousFiber = ReactCurrentFiberCurrent;
try {
setCurrentDebugFiberInDEV(fiber);
console.error(
"Can't perform a React state update on a component that hasn't mounted yet. " +
'This indicates that you have a side-effect in your render function that ' +
'asynchronously later calls tries to update the component. Move this work to ' +
'useEffect instead.',
);
} finally {
if (previousFiber) {
setCurrentDebugFiberInDEV(fiber);
} else {
resetCurrentDebugFiberInDEV();
}
}
}
}
let beginWork;
if (__DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
const dummyFiber = null;
beginWork = (current: null | Fiber, unitOfWork: Fiber, lanes: Lanes) => {
// If a component throws an error, we replay it again in a synchronously
// dispatched event, so that the debugger will treat it as an uncaught
// error See ReactErrorUtils for more information.
// Before entering the begin phase, copy the work-in-progress onto a dummy
// fiber. If beginWork throws, we'll use this to reset the state.
const originalWorkInProgressCopy = assignFiberPropertiesInDEV(
dummyFiber,
unitOfWork,
);
try {
return originalBeginWork(current, unitOfWork, lanes);
} catch (originalError) {
if (
didSuspendOrErrorWhileHydratingDEV() ||
originalError === SuspenseException ||
originalError === SelectiveHydrationException ||
(originalError !== null &&
typeof originalError === 'object' &&
typeof originalError.then === 'function')
) {
// Don't replay promises.
// Don't replay errors if we are hydrating and have already suspended or handled an error
throw originalError;
}
// Don't reset current debug fiber, since we're about to work on the
// same fiber again.
// Unwind the failed stack frame
resetSuspendedWorkLoopOnUnwind(unitOfWork);
unwindInterruptedWork(current, unitOfWork, workInProgressRootRenderLanes);
// Restore the original properties of the fiber.
assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
// Reset the profiler timer.
startProfilerTimer(unitOfWork);
}
// Run beginWork again.
invokeGuardedCallback(
null,
originalBeginWork,
null,
current,
unitOfWork,
lanes,
);
if (hasCaughtError()) {
const replayError = clearCaughtError();
if (
typeof replayError === 'object' &&
replayError !== null &&
replayError._suppressLogging &&
typeof originalError === 'object' &&
originalError !== null &&
!originalError._suppressLogging
) {
// If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
originalError._suppressLogging = true;
}
}
// We always throw the original error in case the second render pass is not idempotent.
// This can happen if a memoized function or CommonJS module doesn't throw after first invocation.
throw originalError;
}
};
} else {
beginWork = originalBeginWork;
}
let didWarnAboutUpdateInRender = false;
let didWarnAboutUpdateInRenderForAnotherComponent;
if (__DEV__) {
didWarnAboutUpdateInRenderForAnotherComponent = new Set<string>();
}
function warnAboutRenderPhaseUpdatesInDEV(fiber: Fiber) {
if (__DEV__) {
if (ReactCurrentDebugFiberIsRenderingInDEV) {
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent: {
const renderingComponentName =
(workInProgress && getComponentNameFromFiber(workInProgress)) ||
'Unknown';
// Dedupe by the rendering component because it's the one that needs to be fixed.
const dedupeKey = renderingComponentName;
if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
const setStateComponentName =
getComponentNameFromFiber(fiber) || 'Unknown';
console.error(
'Cannot update a component (`%s`) while rendering a ' +
'different component (`%s`). To locate the bad setState() call inside `%s`, ' +
'follow the stack trace as described in https://reactjs.org/link/setstate-in-render',
setStateComponentName,
renderingComponentName,
renderingComponentName,
);
}
break;
}
case ClassComponent: {
if (!didWarnAboutUpdateInRender) {
console.error(
'Cannot update during an existing state transition (such as ' +
'within `render`). Render methods should be a pure ' +
'function of props and state.',
);
didWarnAboutUpdateInRender = true;
}
break;
}
}
}
}
}
export function restorePendingUpdaters(root: FiberRoot, lanes: Lanes): void {
if (enableUpdaterTracking) {
if (isDevToolsPresent) {
const memoizedUpdaters = root.memoizedUpdaters;
memoizedUpdaters.forEach(schedulingFiber => {
addFiberToLanesMap(root, schedulingFiber, lanes);
});
// This function intentionally does not clear memoized updaters.
// Those may still be relevant to the current commit
// and a future one (e.g. Suspense).
}
}
}
const fakeActCallbackNode = {};
// $FlowFixMe[missing-local-annot]
function scheduleCallback(priorityLevel: any, callback) {
if (__DEV__) {
// If we're currently inside an `act` scope, bypass Scheduler and push to
// the `act` queue instead.
const actQueue = ReactCurrentActQueue.current;
if (actQueue !== null) {
actQueue.push(callback);
return fakeActCallbackNode;
} else {
return Scheduler_scheduleCallback(priorityLevel, callback);
}
} else {
// In production, always call Scheduler. This function will be stripped out.
return Scheduler_scheduleCallback(priorityLevel, callback);
}
}
function shouldForceFlushFallbacksInDEV() {
// Never force flush in production. This function should get stripped out.
return __DEV__ && ReactCurrentActQueue.current !== null;
}
function warnIfUpdatesNotWrappedWithActDEV(fiber: Fiber): void {
if (__DEV__) {
if (fiber.mode & ConcurrentMode) {
if (!isConcurrentActEnvironment()) {
// Not in an act environment. No need to warn.
return;
}
} else {
// Legacy mode has additional cases where we suppress a warning.
if (!isLegacyActEnvironment(fiber)) {
// Not in an act environment. No need to warn.
return;
}
if (executionContext !== NoContext) {
// Legacy mode doesn't warn if the update is batched, i.e.
// batchedUpdates or flushSync.
return;
}
if (
fiber.tag !== FunctionComponent &&
fiber.tag !== ForwardRef &&
fiber.tag !== SimpleMemoComponent
) {
// For backwards compatibility with pre-hooks code, legacy mode only
// warns for updates that originate from a hook.
return;
}
}
if (ReactCurrentActQueue.current === null) {
const previousFiber = ReactCurrentFiberCurrent;
try {
setCurrentDebugFiberInDEV(fiber);
console.error(
'An update to %s inside a test was not wrapped in act(...).\n\n' +
'When testing, code that causes React state updates should be ' +
'wrapped into act(...):\n\n' +
'act(() => {\n' +
' /* fire events that update state */\n' +
'});\n' +
'/* assert on the output */\n\n' +
"This ensures that you're testing the behavior the user would see " +
'in the browser.' +
' Learn more at https://reactjs.org/link/wrap-tests-with-act',
getComponentNameFromFiber(fiber),
);
} finally {
if (previousFiber) {
setCurrentDebugFiberInDEV(fiber);
} else {
resetCurrentDebugFiberInDEV();
}
}
}
}
}
function warnIfSuspenseResolutionNotWrappedWithActDEV(root: FiberRoot): void {
if (__DEV__) {
if (
root.tag !== LegacyRoot &&
isConcurrentActEnvironment() &&
ReactCurrentActQueue.current === null
) {
console.error(
'A suspended resource finished loading inside a test, but the event ' +
'was not wrapped in act(...).\n\n' +
'When testing, code that resolves suspended data should be wrapped ' +
'into act(...):\n\n' +
'act(() => {\n' +
' /* finish loading suspended data */\n' +
'});\n' +
'/* assert on the output */\n\n' +
"This ensures that you're testing the behavior the user would see " +
'in the browser.' +
' Learn more at https://reactjs.org/link/wrap-tests-with-act',
);
}
}
}
export function setIsRunningInsertionEffect(isRunning: boolean): void {
if (__DEV__) {
isRunningInsertionEffect = isRunning;
}
}
| 34.301938 | 122 | 0.692548 |
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 {createEventTarget, setPointerEvent} from 'dom-event-testing-library';
let React;
let ReactFeatureFlags;
let ReactDOM;
let useFocus;
let act;
function initializeModules(hasPointerEvents) {
setPointerEvent(hasPointerEvents);
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.enableCreateEventHandleAPI = true;
React = require('react');
ReactDOM = require('react-dom');
act = require('internal-test-utils').act;
// TODO: This import throws outside of experimental mode. Figure out better
// strategy for gated imports.
if (__EXPERIMENTAL__ || global.__WWW__) {
useFocus = require('react-interactions/events/focus').useFocus;
}
}
const forcePointerEvents = true;
const table = [[forcePointerEvents], [!forcePointerEvents]];
describe.each(table)(`useFocus hasPointerEvents=%s`, hasPointerEvents => {
let container;
beforeEach(() => {
initializeModules(hasPointerEvents);
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
ReactDOM.render(null, container);
document.body.removeChild(container);
container = null;
});
describe('disabled', () => {
let onBlur, onFocus, ref;
const componentInit = async () => {
onBlur = jest.fn();
onFocus = jest.fn();
ref = React.createRef();
const Component = () => {
useFocus(ref, {
disabled: true,
onBlur,
onFocus,
});
return <div ref={ref} />;
};
await act(() => {
ReactDOM.render(<Component />, container);
});
};
// @gate www
it('does not call callbacks', async () => {
await componentInit();
const target = createEventTarget(ref.current);
target.focus();
target.blur();
expect(onFocus).not.toBeCalled();
expect(onBlur).not.toBeCalled();
});
});
describe('onBlur', () => {
let onBlur, ref;
const componentInit = async () => {
onBlur = jest.fn();
ref = React.createRef();
const Component = () => {
useFocus(ref, {
onBlur,
});
return <div ref={ref} />;
};
await act(() => {
ReactDOM.render(<Component />, container);
});
};
// @gate www
it('is called after "blur" event', async () => {
await componentInit();
const target = createEventTarget(ref.current);
target.focus();
target.blur();
expect(onBlur).toHaveBeenCalledTimes(1);
});
});
describe('onFocus', () => {
let onFocus, ref, innerRef;
const componentInit = async () => {
onFocus = jest.fn();
ref = React.createRef();
innerRef = React.createRef();
const Component = () => {
useFocus(ref, {
onFocus,
});
return (
<div ref={ref}>
<a ref={innerRef} />
</div>
);
};
await act(() => {
ReactDOM.render(<Component />, container);
});
};
// @gate www
it('is called after "focus" event', async () => {
await componentInit();
const target = createEventTarget(ref.current);
target.focus();
expect(onFocus).toHaveBeenCalledTimes(1);
});
// @gate www
it('is not called if descendants of target receive focus', async () => {
await componentInit();
const target = createEventTarget(innerRef.current);
target.focus();
expect(onFocus).not.toBeCalled();
});
});
describe('onFocusChange', () => {
let onFocusChange, ref, innerRef;
const componentInit = async () => {
onFocusChange = jest.fn();
ref = React.createRef();
innerRef = React.createRef();
const Component = () => {
useFocus(ref, {
onFocusChange,
});
return (
<div ref={ref}>
<div ref={innerRef} />
</div>
);
};
await act(() => {
ReactDOM.render(<Component />, container);
});
};
// @gate www
it('is called after "blur" and "focus" events', async () => {
await componentInit();
const target = createEventTarget(ref.current);
target.focus();
expect(onFocusChange).toHaveBeenCalledTimes(1);
expect(onFocusChange).toHaveBeenCalledWith(true);
target.blur();
expect(onFocusChange).toHaveBeenCalledTimes(2);
expect(onFocusChange).toHaveBeenCalledWith(false);
});
// @gate www
it('is not called after "blur" and "focus" events on descendants', async () => {
await componentInit();
const target = createEventTarget(innerRef.current);
target.focus();
expect(onFocusChange).toHaveBeenCalledTimes(0);
target.blur();
expect(onFocusChange).toHaveBeenCalledTimes(0);
});
});
describe('onFocusVisibleChange', () => {
let onFocusVisibleChange, ref, innerRef;
const componentInit = async () => {
onFocusVisibleChange = jest.fn();
ref = React.createRef();
innerRef = React.createRef();
const Component = () => {
useFocus(ref, {
onFocusVisibleChange,
});
return (
<div ref={ref}>
<div ref={innerRef} />
</div>
);
};
await act(() => {
ReactDOM.render(<Component />, container);
});
};
// @gate www
it('is called after "focus" and "blur" if keyboard navigation is active', async () => {
await componentInit();
const target = createEventTarget(ref.current);
const containerTarget = createEventTarget(container);
// use keyboard first
containerTarget.keydown({key: 'Tab'});
target.focus();
expect(onFocusVisibleChange).toHaveBeenCalledTimes(1);
expect(onFocusVisibleChange).toHaveBeenCalledWith(true);
target.blur({relatedTarget: container});
expect(onFocusVisibleChange).toHaveBeenCalledTimes(2);
expect(onFocusVisibleChange).toHaveBeenCalledWith(false);
});
// @gate www
it('is called if non-keyboard event is dispatched on target previously focused with keyboard', async () => {
await componentInit();
const target = createEventTarget(ref.current);
const containerTarget = createEventTarget(container);
// use keyboard first
containerTarget.keydown({key: 'Tab'});
target.focus();
expect(onFocusVisibleChange).toHaveBeenCalledTimes(1);
expect(onFocusVisibleChange).toHaveBeenCalledWith(true);
// then use pointer on the target, focus should no longer be visible
target.pointerdown();
expect(onFocusVisibleChange).toHaveBeenCalledTimes(2);
expect(onFocusVisibleChange).toHaveBeenCalledWith(false);
// onFocusVisibleChange should not be called again
target.blur({relatedTarget: container});
expect(onFocusVisibleChange).toHaveBeenCalledTimes(2);
});
// @gate www
it('is not called after "focus" and "blur" events without keyboard', async () => {
await componentInit();
const target = createEventTarget(ref.current);
const containerTarget = createEventTarget(container);
target.pointerdown();
target.pointerup();
containerTarget.pointerdown();
target.blur({relatedTarget: container});
expect(onFocusVisibleChange).toHaveBeenCalledTimes(0);
});
// @gate www
it('is not called after "blur" and "focus" events on descendants', async () => {
await componentInit();
const innerTarget = createEventTarget(innerRef.current);
const containerTarget = createEventTarget(container);
containerTarget.keydown({key: 'Tab'});
innerTarget.focus();
expect(onFocusVisibleChange).toHaveBeenCalledTimes(0);
innerTarget.blur({relatedTarget: container});
expect(onFocusVisibleChange).toHaveBeenCalledTimes(0);
});
});
describe('nested Focus components', () => {
// @gate www
it('propagates events in the correct order', async () => {
const events = [];
const innerRef = React.createRef();
const outerRef = React.createRef();
const createEventHandler = msg => () => {
events.push(msg);
};
const Inner = () => {
useFocus(innerRef, {
onBlur: createEventHandler('inner: onBlur'),
onFocus: createEventHandler('inner: onFocus'),
onFocusChange: createEventHandler('inner: onFocusChange'),
});
return <div ref={innerRef} />;
};
const Outer = () => {
useFocus(outerRef, {
onBlur: createEventHandler('outer: onBlur'),
onFocus: createEventHandler('outer: onFocus'),
onFocusChange: createEventHandler('outer: onFocusChange'),
});
return (
<div ref={outerRef}>
<Inner />
</div>
);
};
await act(() => {
ReactDOM.render(<Outer />, container);
});
const innerTarget = createEventTarget(innerRef.current);
const outerTarget = createEventTarget(outerRef.current);
outerTarget.focus();
outerTarget.blur();
innerTarget.focus();
innerTarget.blur();
expect(events).toEqual([
'outer: onFocus',
'outer: onFocusChange',
'outer: onBlur',
'outer: onFocusChange',
'inner: onFocus',
'inner: onFocusChange',
'inner: onBlur',
'inner: onFocusChange',
]);
});
});
});
| 28.323263 | 112 | 0.6 |
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';
describe('toErrorDev', () => {
it('does not fail if a warning contains a stack', () => {
expect(() => {
if (__DEV__) {
console.error('Hello\n in div');
}
}).toErrorDev('Hello');
});
it('does not fail if all warnings contain a stack', () => {
expect(() => {
if (__DEV__) {
console.error('Hello\n in div');
console.error('Good day\n in div');
console.error('Bye\n in div');
}
}).toErrorDev(['Hello', 'Good day', 'Bye']);
});
it('does not fail if warnings without stack explicitly opt out', () => {
expect(() => {
if (__DEV__) {
console.error('Hello');
}
}).toErrorDev('Hello', {withoutStack: true});
expect(() => {
if (__DEV__) {
console.error('Hello');
console.error('Good day');
console.error('Bye');
}
}).toErrorDev(['Hello', 'Good day', 'Bye'], {withoutStack: true});
});
it('does not fail when expected stack-less warning number matches the actual one', () => {
expect(() => {
if (__DEV__) {
console.error('Hello\n in div');
console.error('Good day');
console.error('Bye\n in div');
}
}).toErrorDev(['Hello', 'Good day', 'Bye'], {withoutStack: 1});
});
if (__DEV__) {
// Helper methods avoids invalid toWarn().toThrow() nesting
// See no-to-warn-dev-within-to-throw
const expectToWarnAndToThrow = (expectBlock, expectedErrorMessage) => {
let caughtError;
try {
expectBlock();
} catch (error) {
caughtError = error;
}
expect(caughtError).toBeDefined();
expect(caughtError.message).toContain(expectedErrorMessage);
};
it('fails if a warning does not contain a stack', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello');
}).toErrorDev('Hello');
}, 'Received warning unexpectedly does not include a component stack');
});
it('fails if some warnings do not contain a stack', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello\n in div');
console.error('Good day\n in div');
console.error('Bye');
}).toErrorDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello');
console.error('Good day\n in div');
console.error('Bye\n in div');
}).toErrorDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello\n in div');
console.error('Good day');
console.error('Bye\n in div');
}).toErrorDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello');
console.error('Good day');
console.error('Bye');
}).toErrorDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
});
it('fails if warning is expected to not have a stack, but does', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello\n in div');
}).toErrorDev('Hello', {withoutStack: true});
}, 'Received warning unexpectedly includes a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello\n in div');
console.error('Good day');
console.error('Bye\n in div');
}).toErrorDev(['Hello', 'Good day', 'Bye'], {withoutStack: true});
}, 'Received warning unexpectedly includes a component stack');
});
it('fails if expected stack-less warning number does not match the actual one', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hello\n in div');
console.error('Good day');
console.error('Bye\n in div');
}).toErrorDev(['Hello', 'Good day', 'Bye'], {withoutStack: 4});
}, 'Expected 4 warnings without a component stack but received 1');
});
it('fails if withoutStack is invalid', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi');
}).toErrorDev('Hi', {withoutStack: null});
}, 'Instead received object');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi');
}).toErrorDev('Hi', {withoutStack: {}});
}, 'Instead received object');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi');
}).toErrorDev('Hi', {withoutStack: 'haha'});
}, 'Instead received string');
});
it('fails if the argument number does not match', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi %s', 'Sara', 'extra');
}).toErrorDev('Hi', {withoutStack: true});
}, 'Received 2 arguments for a message with 1 placeholders');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi %s');
}).toErrorDev('Hi', {withoutStack: true});
}, 'Received 0 arguments for a message with 1 placeholders');
});
it('fails if stack is passed twice', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi %s%s', '\n in div', '\n in div');
}).toErrorDev('Hi');
}, 'Received more than one component stack for a warning');
});
it('fails if multiple strings are passed without an array wrapper', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi \n in div');
}).toErrorDev('Hi', 'Bye');
}, 'toErrorDev() second argument, when present, should be an object');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi \n in div');
console.error('Bye \n in div');
}).toErrorDev('Hi', 'Bye');
}, 'toErrorDev() second argument, when present, should be an object');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi \n in div');
console.error('Wow \n in div');
console.error('Bye \n in div');
}).toErrorDev('Hi', 'Bye');
}, 'toErrorDev() second argument, when present, should be an object');
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi \n in div');
console.error('Wow \n in div');
console.error('Bye \n in div');
}).toErrorDev('Hi', 'Wow', 'Bye');
}, 'toErrorDev() second argument, when present, should be an object');
});
it('fails on more than two arguments', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.error('Hi \n in div');
console.error('Wow \n in div');
console.error('Bye \n in div');
}).toErrorDev('Hi', undefined, 'Bye');
}, 'toErrorDev() received more than two arguments.');
});
}
});
describe('toWarnDev', () => {
it('does not fail if a warning contains a stack', () => {
expect(() => {
if (__DEV__) {
console.warn('Hello\n in div');
}
}).toWarnDev('Hello');
});
it('does not fail if all warnings contain a stack', () => {
expect(() => {
if (__DEV__) {
console.warn('Hello\n in div');
console.warn('Good day\n in div');
console.warn('Bye\n in div');
}
}).toWarnDev(['Hello', 'Good day', 'Bye']);
});
it('does not fail if warnings without stack explicitly opt out', () => {
expect(() => {
if (__DEV__) {
console.warn('Hello');
}
}).toWarnDev('Hello', {withoutStack: true});
expect(() => {
if (__DEV__) {
console.warn('Hello');
console.warn('Good day');
console.warn('Bye');
}
}).toWarnDev(['Hello', 'Good day', 'Bye'], {withoutStack: true});
});
it('does not fail when expected stack-less warning number matches the actual one', () => {
expect(() => {
if (__DEV__) {
console.warn('Hello\n in div');
console.warn('Good day');
console.warn('Bye\n in div');
}
}).toWarnDev(['Hello', 'Good day', 'Bye'], {withoutStack: 1});
});
if (__DEV__) {
// Helper methods avoids invalid toWarn().toThrow() nesting
// See no-to-warn-dev-within-to-throw
const expectToWarnAndToThrow = (expectBlock, expectedErrorMessage) => {
let caughtError;
try {
expectBlock();
} catch (error) {
caughtError = error;
}
expect(caughtError).toBeDefined();
expect(caughtError.message).toContain(expectedErrorMessage);
};
it('fails if a warning does not contain a stack', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello');
}).toWarnDev('Hello');
}, 'Received warning unexpectedly does not include a component stack');
});
it('fails if some warnings do not contain a stack', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello\n in div');
console.warn('Good day\n in div');
console.warn('Bye');
}).toWarnDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello');
console.warn('Good day\n in div');
console.warn('Bye\n in div');
}).toWarnDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello\n in div');
console.warn('Good day');
console.warn('Bye\n in div');
}).toWarnDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello');
console.warn('Good day');
console.warn('Bye');
}).toWarnDev(['Hello', 'Good day', 'Bye']);
}, 'Received warning unexpectedly does not include a component stack');
});
it('fails if warning is expected to not have a stack, but does', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello\n in div');
}).toWarnDev('Hello', {withoutStack: true});
}, 'Received warning unexpectedly includes a component stack');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello\n in div');
console.warn('Good day');
console.warn('Bye\n in div');
}).toWarnDev(['Hello', 'Good day', 'Bye'], {
withoutStack: true,
});
}, 'Received warning unexpectedly includes a component stack');
});
it('fails if expected stack-less warning number does not match the actual one', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hello\n in div');
console.warn('Good day');
console.warn('Bye\n in div');
}).toWarnDev(['Hello', 'Good day', 'Bye'], {
withoutStack: 4,
});
}, 'Expected 4 warnings without a component stack but received 1');
});
it('fails if withoutStack is invalid', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi');
}).toWarnDev('Hi', {withoutStack: null});
}, 'Instead received object');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi');
}).toWarnDev('Hi', {withoutStack: {}});
}, 'Instead received object');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi');
}).toWarnDev('Hi', {withoutStack: 'haha'});
}, 'Instead received string');
});
it('fails if the argument number does not match', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi %s', 'Sara', 'extra');
}).toWarnDev('Hi', {withoutStack: true});
}, 'Received 2 arguments for a message with 1 placeholders');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi %s');
}).toWarnDev('Hi', {withoutStack: true});
}, 'Received 0 arguments for a message with 1 placeholders');
});
it('fails if stack is passed twice', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi %s%s', '\n in div', '\n in div');
}).toWarnDev('Hi');
}, 'Received more than one component stack for a warning');
});
it('fails if multiple strings are passed without an array wrapper', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi \n in div');
}).toWarnDev('Hi', 'Bye');
}, 'toWarnDev() second argument, when present, should be an object');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi \n in div');
console.warn('Bye \n in div');
}).toWarnDev('Hi', 'Bye');
}, 'toWarnDev() second argument, when present, should be an object');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi \n in div');
console.warn('Wow \n in div');
console.warn('Bye \n in div');
}).toWarnDev('Hi', 'Bye');
}, 'toWarnDev() second argument, when present, should be an object');
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi \n in div');
console.warn('Wow \n in div');
console.warn('Bye \n in div');
}).toWarnDev('Hi', 'Wow', 'Bye');
}, 'toWarnDev() second argument, when present, should be an object');
});
it('fails on more than two arguments', () => {
expectToWarnAndToThrow(() => {
expect(() => {
console.warn('Hi \n in div');
console.warn('Wow \n in div');
console.warn('Bye \n in div');
}).toWarnDev('Hi', undefined, 'Bye');
}, 'toWarnDev() received more than two arguments.');
});
}
});
| 34.52506 | 92 | 0.529629 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/* eslint-disable react-internal/prod-error-codes */
// 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 |
Tricks-Web-Penetration-Tester | // @flow
import type {ComponentType} from "react";
import createListComponent from './createListComponent';
import type { Props, ScrollToAlign } from './createListComponent';
const DEFAULT_ESTIMATED_ITEM_SIZE = 50;
type VariableSizeProps = {|
estimatedItemSize: number,
...Props<any>,
|};
type itemSizeGetter = (index: number) => number;
type ItemMetadata = {|
offset: number,
size: number,
|};
type InstanceProps = {|
itemMetadataMap: { [index: number]: ItemMetadata, ... },
estimatedItemSize: number,
lastMeasuredIndex: number,
|};
const getItemMetadata = (
props: Props<any>,
index: number,
instanceProps: InstanceProps
): ItemMetadata => {
const { itemSize } = ((props: any): VariableSizeProps);
const { itemMetadataMap, lastMeasuredIndex } = instanceProps;
if (index > lastMeasuredIndex) {
let offset = 0;
if (lastMeasuredIndex >= 0) {
const itemMetadata = itemMetadataMap[lastMeasuredIndex];
offset = itemMetadata.offset + itemMetadata.size;
}
for (let i = lastMeasuredIndex + 1; i <= index; i++) {
let size = ((itemSize: any): itemSizeGetter)(i);
itemMetadataMap[i] = {
offset,
size,
};
offset += size;
}
instanceProps.lastMeasuredIndex = index;
}
return itemMetadataMap[index];
};
const findNearestItem = (
props: Props<any>,
instanceProps: InstanceProps,
offset: number
) => {
const { itemMetadataMap, lastMeasuredIndex } = instanceProps;
const lastMeasuredItemOffset =
lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0;
if (lastMeasuredItemOffset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return findNearestItemBinarySearch(
props,
instanceProps,
lastMeasuredIndex,
0,
offset
);
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of items as a binary search would.
// The overall complexity for this approach is O(log n).
return findNearestItemExponentialSearch(
props,
instanceProps,
Math.max(0, lastMeasuredIndex),
offset
);
}
};
const findNearestItemBinarySearch = (
props: Props<any>,
instanceProps: InstanceProps,
high: number,
low: number,
offset: number
): number => {
while (low <= high) {
const middle = low + Math.floor((high - low) / 2);
const currentOffset = getItemMetadata(props, middle, instanceProps).offset;
if (currentOffset === offset) {
return middle;
} else if (currentOffset < offset) {
low = middle + 1;
} else if (currentOffset > offset) {
high = middle - 1;
}
}
if (low > 0) {
return low - 1;
} else {
return 0;
}
};
const findNearestItemExponentialSearch = (
props: Props<any>,
instanceProps: InstanceProps,
index: number,
offset: number
): number => {
const { itemCount } = props;
let interval = 1;
while (
index < itemCount &&
getItemMetadata(props, index, instanceProps).offset < offset
) {
index += interval;
interval *= 2;
}
return findNearestItemBinarySearch(
props,
instanceProps,
Math.min(index, itemCount - 1),
Math.floor(index / 2),
offset
);
};
const getEstimatedTotalSize = (
{ itemCount }: Props<any>,
{ itemMetadataMap, estimatedItemSize, lastMeasuredIndex }: InstanceProps
) => {
let totalSizeOfMeasuredItems = 0;
// Edge case check for when the number of items decreases while a scroll is in progress.
// https://github.com/bvaughn/react-window/pull/138
if (lastMeasuredIndex >= itemCount) {
lastMeasuredIndex = itemCount - 1;
}
if (lastMeasuredIndex >= 0) {
const itemMetadata = itemMetadataMap[lastMeasuredIndex];
totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size;
}
const numUnmeasuredItems = itemCount - lastMeasuredIndex - 1;
const totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedItemSize;
return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems;
};
const VariableSizeList: ComponentType<Props<any>> = createListComponent({
getItemOffset: (
props: Props<any>,
index: number,
instanceProps: InstanceProps
): number => getItemMetadata(props, index, instanceProps).offset,
getItemSize: (
props: Props<any>,
index: number,
instanceProps: InstanceProps
): number => instanceProps.itemMetadataMap[index].size,
getEstimatedTotalSize,
getOffsetForIndexAndAlignment: (
props: Props<any>,
index: number,
align: ScrollToAlign,
scrollOffset: number,
instanceProps: InstanceProps
): number => {
const { direction, height, layout, width } = props;
// TODO Deprecate direction "horizontal"
const isHorizontal = direction === 'horizontal' || layout === 'horizontal';
const size = (((isHorizontal ? width : height): any): number);
const itemMetadata = getItemMetadata(props, index, instanceProps);
// Get estimated total size after ItemMetadata is computed,
// To ensure it reflects actual measurements instead of just estimates.
const estimatedTotalSize = getEstimatedTotalSize(props, instanceProps);
const maxOffset = Math.max(
0,
Math.min(estimatedTotalSize - size, itemMetadata.offset)
);
const minOffset = Math.max(
0,
itemMetadata.offset - size + itemMetadata.size
);
if (align === 'smart') {
if (
scrollOffset >= minOffset - size &&
scrollOffset <= maxOffset + size
) {
align = 'auto';
} else {
align = 'center';
}
}
switch (align) {
case 'start':
return maxOffset;
case 'end':
return minOffset;
case 'center':
return Math.round(minOffset + (maxOffset - minOffset) / 2);
case 'auto':
default:
if (scrollOffset >= minOffset && scrollOffset <= maxOffset) {
return scrollOffset;
} else if (scrollOffset < minOffset) {
return minOffset;
} else {
return maxOffset;
}
}
},
getStartIndexForOffset: (
props: Props<any>,
offset: number,
instanceProps: InstanceProps
): number => findNearestItem(props, instanceProps, offset),
getStopIndexForStartIndex: (
props: Props<any>,
startIndex: number,
scrollOffset: number,
instanceProps: InstanceProps
): number => {
const { direction, height, itemCount, layout, width } = props;
// TODO Deprecate direction "horizontal"
const isHorizontal = direction === 'horizontal' || layout === 'horizontal';
const size = (((isHorizontal ? width : height): any): number);
const itemMetadata = getItemMetadata(props, startIndex, instanceProps);
const maxOffset = scrollOffset + size;
let offset = itemMetadata.offset + itemMetadata.size;
let stopIndex = startIndex;
while (stopIndex < itemCount - 1 && offset < maxOffset) {
stopIndex++;
offset += getItemMetadata(props, stopIndex, instanceProps).size;
}
return stopIndex;
},
initInstanceProps(props: Props<any>, instance: any): InstanceProps {
const { estimatedItemSize } = ((props: any): VariableSizeProps);
const instanceProps = {
itemMetadataMap: {},
estimatedItemSize: estimatedItemSize || DEFAULT_ESTIMATED_ITEM_SIZE,
lastMeasuredIndex: -1,
};
instance.resetAfterIndex = (
index: number,
shouldForceUpdate?: boolean = true
) => {
instanceProps.lastMeasuredIndex = Math.min(
instanceProps.lastMeasuredIndex,
index - 1
);
// We could potentially optimize further by only evicting styles after this index,
// But since styles are only cached while scrolling is in progress-
// It seems an unnecessary optimization.
// It's unlikely that resetAfterIndex() will be called while a user is scrolling.
instance._getItemStyleCache(-1);
if (shouldForceUpdate) {
instance.forceUpdate();
}
};
return instanceProps;
},
shouldResetStyleCacheOnItemSizeChange: false,
validateProps: ({ itemSize }: Props<any>): void => {
if (process.env.NODE_ENV !== 'production') {
if (typeof itemSize !== 'function') {
throw Error(
'An invalid "itemSize" prop has been specified. ' +
'Value should be a function. ' +
`"${itemSize === null ? 'null' : typeof itemSize}" was specified.`
);
}
}
},
});
export default VariableSizeList;
| 26.059561 | 108 | 0.654501 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Rect} from '../../view-base';
export function positioningScaleFactor(
intrinsicWidth: number,
frame: Rect,
): number {
return frame.size.width / intrinsicWidth;
}
export function timestampToPosition(
timestamp: number,
scaleFactor: number,
frame: Rect,
): number {
return frame.origin.x + timestamp * scaleFactor;
}
export function positionToTimestamp(
position: number,
scaleFactor: number,
frame: Rect,
): number {
return (position - frame.origin.x) / scaleFactor;
}
export function durationToWidth(duration: number, scaleFactor: number): number {
return duration * scaleFactor;
}
export function widthToDuration(width: number, scaleFactor: number): number {
return width / scaleFactor;
}
| 21.380952 | 80 | 0.72524 |
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 {isEnabled} from 'react-dom-bindings/src/events/ReactDOMEventListener';
import Internals from './src/ReactDOMSharedInternals';
// For classic WWW builds, include a few internals that are already in use.
Object.assign((Internals: any), {
ReactBrowserEventEmitter: {
isEnabled,
},
});
export {
createPortal,
createRoot,
hydrateRoot,
findDOMNode,
flushSync,
hydrate,
render,
unmountComponentAtNode,
unstable_batchedUpdates,
unstable_createEventHandle,
unstable_renderSubtreeIntoContainer,
unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority.
useFormStatus,
useFormState,
prefetchDNS,
preconnect,
preload,
preloadModule,
preinit,
preinitModule,
version,
} from './src/client/ReactDOM';
export {Internals as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED};
| 22.369565 | 107 | 0.742086 |
null | 'use strict';
const chalk = require('chalk');
const util = require('util');
const shouldIgnoreConsoleError = require('./shouldIgnoreConsoleError');
const {getTestFlags} = require('./TestFlags');
if (process.env.REACT_CLASS_EQUIVALENCE_TEST) {
// Inside the class equivalence tester, we have a custom environment, let's
// require that instead.
require('./spec-equivalence-reporter/setupTests.js');
} else {
const errorMap = require('../error-codes/codes.json');
// By default, jest.spyOn also calls the spied method.
const spyOn = jest.spyOn;
const noop = jest.fn;
// Spying on console methods in production builds can mask errors.
// This is why we added an explicit spyOnDev() helper.
// It's too easy to accidentally use the more familiar spyOn() helper though,
// So we disable it entirely.
// Spying on both dev and prod will require using both spyOnDev() and spyOnProd().
global.spyOn = function () {
throw new Error(
'Do not use spyOn(). ' +
'It can accidentally hide unexpected errors in production builds. ' +
'Use spyOnDev(), spyOnProd(), or spyOnDevAndProd() instead.'
);
};
if (process.env.NODE_ENV === 'production') {
global.spyOnDev = noop;
global.spyOnProd = spyOn;
global.spyOnDevAndProd = spyOn;
} else {
global.spyOnDev = spyOn;
global.spyOnProd = noop;
global.spyOnDevAndProd = spyOn;
}
expect.extend({
...require('./matchers/reactTestMatchers'),
...require('./matchers/toThrow'),
...require('./matchers/toWarnDev'),
});
// We have a Babel transform that inserts guards against infinite loops.
// If a loop runs for too many iterations, we throw an error and set this
// global variable. The global lets us detect an infinite loop even if
// the actual error object ends up being caught and ignored. An infinite
// loop must always fail the test!
beforeEach(() => {
global.infiniteLoopError = null;
});
afterEach(() => {
const error = global.infiniteLoopError;
global.infiniteLoopError = null;
if (error) {
throw error;
}
});
// TODO: Consider consolidating this with `yieldValue`. In both cases, tests
// should not be allowed to exit without asserting on the entire log.
const patchConsoleMethod = (methodName, unexpectedConsoleCallStacks) => {
const newMethod = function (format, ...args) {
// Ignore uncaught errors reported by jsdom
// and React addendums because they're too noisy.
if (methodName === 'error' && shouldIgnoreConsoleError(format, args)) {
return;
}
// Capture the call stack now so we can warn about it later.
// The call stack has helpful information for the test author.
// Don't throw yet though b'c it might be accidentally caught and suppressed.
const stack = new Error().stack;
unexpectedConsoleCallStacks.push([
stack.slice(stack.indexOf('\n') + 1),
util.format(format, ...args),
]);
};
console[methodName] = newMethod;
return newMethod;
};
const flushUnexpectedConsoleCalls = (
mockMethod,
methodName,
expectedMatcher,
unexpectedConsoleCallStacks
) => {
if (
console[methodName] !== mockMethod &&
!jest.isMockFunction(console[methodName])
) {
throw new Error(
`Test did not tear down console.${methodName} mock properly.`
);
}
if (unexpectedConsoleCallStacks.length > 0) {
const messages = unexpectedConsoleCallStacks.map(
([stack, message]) =>
`${chalk.red(message)}\n` +
`${stack
.split('\n')
.map(line => chalk.gray(line))
.join('\n')}`
);
const message =
`Expected test not to call ${chalk.bold(
`console.${methodName}()`
)}.\n\n` +
'If the warning is expected, test for it explicitly by:\n' +
`1. Using the ${chalk.bold('.' + expectedMatcher + '()')} ` +
`matcher, or...\n` +
`2. Mock it out using ${chalk.bold(
'spyOnDev'
)}(console, '${methodName}') or ${chalk.bold(
'spyOnProd'
)}(console, '${methodName}'), and test that the warning occurs.`;
throw new Error(`${message}\n\n${messages.join('\n\n')}`);
}
};
const unexpectedErrorCallStacks = [];
const unexpectedWarnCallStacks = [];
const errorMethod = patchConsoleMethod('error', unexpectedErrorCallStacks);
const warnMethod = patchConsoleMethod('warn', unexpectedWarnCallStacks);
const flushAllUnexpectedConsoleCalls = () => {
flushUnexpectedConsoleCalls(
errorMethod,
'error',
'toErrorDev',
unexpectedErrorCallStacks
);
flushUnexpectedConsoleCalls(
warnMethod,
'warn',
'toWarnDev',
unexpectedWarnCallStacks
);
unexpectedErrorCallStacks.length = 0;
unexpectedWarnCallStacks.length = 0;
};
const resetAllUnexpectedConsoleCalls = () => {
unexpectedErrorCallStacks.length = 0;
unexpectedWarnCallStacks.length = 0;
};
beforeEach(resetAllUnexpectedConsoleCalls);
afterEach(flushAllUnexpectedConsoleCalls);
if (process.env.NODE_ENV === 'production') {
// In production, we strip error messages and turn them into codes.
// This decodes them back so that the test assertions on them work.
// 1. `ErrorProxy` decodes error messages at Error construction time and
// also proxies error instances with `proxyErrorInstance`.
// 2. `proxyErrorInstance` decodes error messages when the `message`
// property is changed.
const decodeErrorMessage = function (message) {
if (!message) {
return message;
}
const re = /error-decoder.html\?invariant=(\d+)([^\s]*)/;
const matches = message.match(re);
if (!matches || matches.length !== 3) {
return message;
}
const code = parseInt(matches[1], 10);
const args = matches[2]
.split('&')
.filter(s => s.startsWith('args[]='))
.map(s => s.slice('args[]='.length))
.map(decodeURIComponent);
const format = errorMap[code];
let argIndex = 0;
return format.replace(/%s/g, () => args[argIndex++]);
};
const OriginalError = global.Error;
// V8's Error.captureStackTrace (used in Jest) fails if the error object is
// a Proxy, so we need to pass it the unproxied instance.
const originalErrorInstances = new WeakMap();
const captureStackTrace = function (error, ...args) {
return OriginalError.captureStackTrace.call(
this,
originalErrorInstances.get(error) ||
// Sometimes this wrapper receives an already-unproxied instance.
error,
...args
);
};
const proxyErrorInstance = error => {
const proxy = new Proxy(error, {
set(target, key, value, receiver) {
if (key === 'message') {
return Reflect.set(
target,
key,
decodeErrorMessage(value),
receiver
);
}
return Reflect.set(target, key, value, receiver);
},
});
originalErrorInstances.set(proxy, error);
return proxy;
};
const ErrorProxy = new Proxy(OriginalError, {
apply(target, thisArg, argumentsList) {
const error = Reflect.apply(target, thisArg, argumentsList);
error.message = decodeErrorMessage(error.message);
return proxyErrorInstance(error);
},
construct(target, argumentsList, newTarget) {
const error = Reflect.construct(target, argumentsList, newTarget);
error.message = decodeErrorMessage(error.message);
return proxyErrorInstance(error);
},
get(target, key, receiver) {
if (key === 'captureStackTrace') {
return captureStackTrace;
}
return Reflect.get(target, key, receiver);
},
});
ErrorProxy.OriginalError = OriginalError;
global.Error = ErrorProxy;
}
const expectTestToFail = async (callback, errorMsg) => {
if (callback.length > 0) {
throw Error(
'Gated test helpers do not support the `done` callback. Return a ' +
'promise instead.'
);
}
try {
const maybePromise = callback();
if (
maybePromise !== undefined &&
maybePromise !== null &&
typeof maybePromise.then === 'function'
) {
await maybePromise;
}
// Flush unexpected console calls inside the test itself, instead of in
// `afterEach` like we normally do. `afterEach` is too late because if it
// throws, we won't have captured it.
flushAllUnexpectedConsoleCalls();
} catch (error) {
// Failed as expected
resetAllUnexpectedConsoleCalls();
return;
}
throw Error(errorMsg);
};
const gatedErrorMessage = 'Gated test was expected to fail, but it passed.';
global._test_gate = (gateFn, testName, callback) => {
let shouldPass;
try {
const flags = getTestFlags();
shouldPass = gateFn(flags);
} catch (e) {
test(testName, () => {
throw e;
});
return;
}
if (shouldPass) {
test(testName, callback);
} else {
test(`[GATED, SHOULD FAIL] ${testName}`, () =>
expectTestToFail(callback, gatedErrorMessage));
}
};
global._test_gate_focus = (gateFn, testName, callback) => {
let shouldPass;
try {
const flags = getTestFlags();
shouldPass = gateFn(flags);
} catch (e) {
test.only(testName, () => {
throw e;
});
return;
}
if (shouldPass) {
test.only(testName, callback);
} else {
test.only(`[GATED, SHOULD FAIL] ${testName}`, () =>
expectTestToFail(callback, gatedErrorMessage));
}
};
// Dynamic version of @gate pragma
global.gate = fn => {
const flags = getTestFlags();
return fn(flags);
};
}
| 30.983923 | 84 | 0.616831 |
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('ReactDOMComponentTree', () => {
let React;
let ReactDOM;
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('finds nodes for instances on events', () => {
const mouseOverID = 'mouseOverID';
const clickID = 'clickID';
let currentTargetID = null;
// the current target of an event is set to result of getNodeFromInstance
// when an event is dispatched so we can test behavior by invoking
// events on elements in the tree and confirming the expected node is
// set as the current target
class Component extends React.Component {
handler = e => {
currentTargetID = e.currentTarget.id;
};
render() {
return (
<div id={mouseOverID} onMouseOver={this.handler}>
<div id={clickID} onClick={this.handler} />
</div>
);
}
}
function simulateMouseEvent(elem, type) {
const event = new MouseEvent(type, {
bubbles: true,
});
elem.dispatchEvent(event);
}
const component = <Component />;
ReactDOM.render(component, container);
expect(currentTargetID).toBe(null);
simulateMouseEvent(document.getElementById(mouseOverID), 'mouseover');
expect(currentTargetID).toBe(mouseOverID);
simulateMouseEvent(document.getElementById(clickID), 'click');
expect(currentTargetID).toBe(clickID);
});
it('finds closest instance for node when an event happens', () => {
const nonReactElemID = 'aID';
const innerHTML = {__html: `<div id="${nonReactElemID}"></div>`};
const closestInstanceID = 'closestInstance';
let currentTargetID = null;
class ClosestInstance extends React.Component {
_onClick = e => {
currentTargetID = e.currentTarget.id;
};
render() {
return (
<div
id={closestInstanceID}
onClick={this._onClick}
dangerouslySetInnerHTML={innerHTML}
/>
);
}
}
function simulateClick(elem) {
const event = new MouseEvent('click', {
bubbles: true,
});
elem.dispatchEvent(event);
}
const component = <ClosestInstance />;
ReactDOM.render(<section>{component}</section>, container);
expect(currentTargetID).toBe(null);
simulateClick(document.getElementById(nonReactElemID));
expect(currentTargetID).toBe(closestInstanceID);
});
it('updates event handlers from fiber props', () => {
let action = '';
let instance;
const handlerA = () => (action = 'A');
const handlerB = () => (action = 'B');
function simulateMouseOver(target) {
const event = new MouseEvent('mouseover', {
bubbles: true,
});
target.dispatchEvent(event);
}
class HandlerFlipper extends React.Component {
state = {flip: false};
flip() {
this.setState({flip: true});
}
render() {
return (
<div
id="update"
onMouseOver={this.state.flip ? handlerB : handlerA}
/>
);
}
}
ReactDOM.render(
<HandlerFlipper key="1" ref={n => (instance = n)} />,
container,
);
const node = container.firstChild;
simulateMouseOver(node);
expect(action).toEqual('A');
action = '';
// Render with the other event handler.
instance.flip();
simulateMouseOver(node);
expect(action).toEqual('B');
});
it('finds a controlled instance from node and gets its current fiber props', () => {
const inputID = 'inputID';
const startValue = undefined;
const finishValue = 'finish';
class Controlled extends React.Component {
state = {value: startValue};
a = null;
_onChange = e => this.setState({value: e.currentTarget.value});
render() {
return (
<input
id={inputID}
type="text"
ref={n => (this.a = n)}
value={this.state.value}
onChange={this._onChange}
/>
);
}
}
const setUntrackedInputValue = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
'value',
).set;
function simulateInput(elem, value) {
const inputEvent = new Event('input', {
bubbles: true,
});
setUntrackedInputValue.call(elem, value);
elem.dispatchEvent(inputEvent);
}
const component = <Controlled />;
const instance = ReactDOM.render(component, container);
expect(() => simulateInput(instance.a, finishValue)).toErrorDev(
'Warning: A component is changing an uncontrolled input to be controlled. ' +
'This is likely caused by the value changing from undefined to ' +
'a defined value, which should not happen. ' +
'Decide between using a controlled or uncontrolled input ' +
'element for the lifetime of the component. More info: ' +
'https://reactjs.org/link/controlled-components',
);
});
it('finds instance of node that is attempted to be unmounted', () => {
const component = <div />;
const node = ReactDOM.render(<div>{component}</div>, container);
expect(() => ReactDOM.unmountComponentAtNode(node)).toErrorDev(
"unmountComponentAtNode(): The node you're attempting to unmount " +
'was rendered by React and is not a top-level container. You may ' +
'have accidentally passed in a React root node instead of its ' +
'container.',
{withoutStack: true},
);
});
it('finds instance from node to stop rendering over other react rendered components', () => {
const component = (
<div>
<span>Hello</span>
</div>
);
const anotherComponent = <div />;
const instance = ReactDOM.render(component, container);
expect(() => ReactDOM.render(anotherComponent, instance)).toErrorDev(
'render(...): Replacing React-rendered children with a new root ' +
'component. If you intended to update the children of this node, ' +
'you should instead have the existing children update their state ' +
'and render the new components instead of calling ReactDOM.render.',
{withoutStack: true},
);
});
});
| 29.369863 | 95 | 0.61218 |
null | #!/usr/bin/env node
'use strict';
const {join} = require('path');
const {readJsonSync} = require('fs-extra');
const clear = require('clear');
const {getPublicPackages, handleError} = require('./utils');
const theme = require('./theme');
const checkNPMPermissions = require('./publish-commands/check-npm-permissions');
const confirmSkippedPackages = require('./publish-commands/confirm-skipped-packages');
const confirmVersionAndTags = require('./publish-commands/confirm-version-and-tags');
const parseParams = require('./publish-commands/parse-params');
const printFollowUpInstructions = require('./publish-commands/print-follow-up-instructions');
const promptForOTP = require('./publish-commands/prompt-for-otp');
const publishToNPM = require('./publish-commands/publish-to-npm');
const updateStableVersionNumbers = require('./publish-commands/update-stable-version-numbers');
const validateTags = require('./publish-commands/validate-tags');
const validateSkipPackages = require('./publish-commands/validate-skip-packages');
const run = async () => {
try {
const params = parseParams();
const version = readJsonSync(
'./build/node_modules/react/package.json'
).version;
const isExperimental = version.includes('experimental');
params.cwd = join(__dirname, '..', '..');
params.packages = await getPublicPackages(isExperimental);
// Pre-filter any skipped packages to simplify the following commands.
// As part of doing this we can also validate that none of the skipped packages were misspelled.
params.skipPackages.forEach(packageName => {
const index = params.packages.indexOf(packageName);
if (index < 0) {
console.log(
theme`Invalid skip package {package ${packageName}} specified.`
);
process.exit(1);
} else {
params.packages.splice(index, 1);
}
});
await validateTags(params);
await confirmSkippedPackages(params);
await confirmVersionAndTags(params);
await validateSkipPackages(params);
await checkNPMPermissions(params);
const packageNames = params.packages;
if (params.ci) {
let failed = false;
for (let i = 0; i < packageNames.length; i++) {
try {
const packageName = packageNames[i];
await publishToNPM(params, packageName, null);
} catch (error) {
failed = true;
console.error(error.message);
console.log();
console.log(
theme.error`Publish failed. Will attempt to publish remaining packages.`
);
}
}
if (failed) {
console.log(theme.error`One or more packages failed to publish.`);
process.exit(1);
}
} else {
clear();
let otp = await promptForOTP(params);
for (let i = 0; i < packageNames.length; ) {
const packageName = packageNames[i];
try {
await publishToNPM(params, packageName, otp);
i++;
} catch (error) {
console.error(error.message);
console.log();
console.log(
theme.error`Publish failed. Enter a fresh otp code to retry.`
);
otp = await promptForOTP(params);
// Try publishing package again
continue;
}
}
await updateStableVersionNumbers(params);
await printFollowUpInstructions(params);
}
} catch (error) {
handleError(error);
}
};
run();
| 32.592233 | 100 | 0.643539 |
null | #!/usr/bin/env node
'use strict';
const clear = require('clear');
const {join, relative} = require('path');
const theme = require('../theme');
module.exports = async ({build}) => {
const commandPath = relative(
process.env.PWD,
join(__dirname, '../download-experimental-build.js')
);
clear();
const message = theme`
{caution An experimental build has been downloaded!}
You can download this build again by running:
{path ${commandPath}} --build={build ${build}}
`;
console.log(message.replace(/\n +/g, '\n').trim());
};
| 20.615385 | 56 | 0.632799 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from '../ReactFiber';
import type {CapturedValue} from '../ReactCapturedValue';
import {ClassComponent} from '../ReactWorkTags';
// Module provided by RN:
import {ReactFiberErrorDialog as RNImpl} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
if (typeof RNImpl.showErrorDialog !== 'function') {
throw new Error(
'Expected ReactFiberErrorDialog.showErrorDialog to be a function.',
);
}
export function showErrorDialog(
boundary: Fiber,
errorInfo: CapturedValue<mixed>,
): boolean {
const capturedError = {
componentStack: errorInfo.stack !== null ? errorInfo.stack : '',
error: errorInfo.value,
errorBoundary:
boundary !== null && boundary.tag === ClassComponent
? boundary.stateNode
: null,
};
return RNImpl.showErrorDialog(capturedError);
}
| 26.578947 | 112 | 0.710602 |
owtf | 'use server';
import {setServerState} from './ServerState.js';
export async function like() {
setServerState('Liked!');
return new Promise((resolve, reject) => resolve('Liked'));
}
export async function greet(formData) {
const name = formData.get('name') || 'you';
setServerState('Hi ' + name);
const file = formData.get('file');
if (file) {
return `Ok, ${name}, here is ${file.name}:
${(await file.text()).toUpperCase()}
`;
}
return 'Hi ' + name + '!';
}
| 22.333333 | 60 | 0.613497 |
owtf | var path = require('path');
module.exports = {
entry: './input',
output: {
filename: 'output.js',
},
resolve: {
root: path.resolve('../../../../build/oss-experimental'),
alias: {
react: 'react/umd/react.production.min',
'react-dom': 'react-dom/umd/react-dom.production.min',
},
},
};
| 19.25 | 61 | 0.560372 |
null | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/scheduler.production.min.js');
} else {
module.exports = require('./cjs/scheduler.development.js');
}
| 23.875 | 64 | 0.676768 |
diff-droid | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireWildcard(require("react"));
var _jsxFileName = "";
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function Component() {
const [count, setCount] = (0, _react.useState)(0);
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 5
}
}, /*#__PURE__*/_react.default.createElement("p", {
__source: {
fileName: _jsxFileName,
lineNumber: 17,
columnNumber: 7
}
}, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", {
onClick: () => setCount(count + 1),
__source: {
fileName: _jsxFileName,
lineNumber: 18,
columnNumber: 7
}
}, "Click me"));
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkV4YW1wbGUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJzZXRDb3VudCJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50LCBzZXRDb3VudF0gPSB1c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gKFxuICAgIDxkaXY+XG4gICAgICA8cD5Zb3UgY2xpY2tlZCB7Y291bnR9IHRpbWVzPC9wPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXsoKSA9PiBzZXRDb3VudChjb3VudCArIDEpfT5DbGljayBtZTwvYnV0dG9uPlxuICAgIDwvZGl2PlxuICApO1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsImNvdW50Il0sIm1hcHBpbmdzIjoiQ0FBRDthNEJDQSxBV0RBIn1dXX0= | 79.282051 | 1,372 | 0.795208 |
Ethical-Hacking-Scripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {
createContext,
forwardRef,
Fragment,
memo,
useCallback,
useContext,
useDebugValue,
useEffect,
useState,
} from 'react';
const object = {
string: 'abc',
number: 123,
boolean: true,
null: null,
undefined: undefined,
array: ['a', 'b', 'c'],
object: {foo: 1, bar: 2, baz: 3},
};
function useNestedInnerHook() {
return useState(123);
}
function useNestedOuterHook() {
return useNestedInnerHook();
}
function useCustomObject() {
useDebugValue(object);
return useState(123);
}
function useDeepHookA() {
useDebugValue('useDeepHookA');
useDeepHookB();
}
function useDeepHookB() {
useDebugValue('useDeepHookB');
useDeepHookC();
}
function useDeepHookC() {
useDebugValue('useDeepHookC');
useDeepHookD();
}
function useDeepHookD() {
useDebugValue('useDeepHookD');
useDeepHookE();
}
function useDeepHookE() {
useDebugValue('useDeepHookE');
useDeepHookF();
}
function useDeepHookF() {
useDebugValue('useDeepHookF');
}
const ContextA = createContext('A');
const ContextB = createContext('B');
function FunctionWithHooks(props: any, ref: React$Ref<any>) {
const [count, updateCount] = useState(0);
// eslint-disable-next-line no-unused-vars
const contextValueA = useContext(ContextA);
// eslint-disable-next-line no-unused-vars
const [_, __] = useState(object);
// Custom hook with a custom debug label
const debouncedCount = useDebounce(count, 1000);
useCustomObject();
const onClick = useCallback(
function onClick() {
updateCount(count + 1);
},
[count],
);
// Tests nested custom hooks
useNestedOuterHook();
// eslint-disable-next-line no-unused-vars
const contextValueB = useContext(ContextB);
// Verify deep nesting doesn't break
useDeepHookA();
return <button onClick={onClick}>Count: {debouncedCount}</button>;
}
const MemoWithHooks = memo(FunctionWithHooks);
const ForwardRefWithHooks = forwardRef(FunctionWithHooks);
function wrapWithHoc(Component: (props: any, ref: React$Ref<any>) => any) {
function Hoc() {
return <Component />;
}
// $FlowFixMe[prop-missing]
const displayName = Component.displayName || Component.name;
// $FlowFixMe[incompatible-type] found when upgrading Flow
Hoc.displayName = `withHoc(${displayName})`;
return Hoc;
}
const HocWithHooks = wrapWithHoc(FunctionWithHooks);
export default function CustomHooks(): React.Node {
return (
<Fragment>
<FunctionWithHooks />
<MemoWithHooks />
<ForwardRefWithHooks />
<HocWithHooks />
</Fragment>
);
}
// Below copied from https://usehooks.com/
function useDebounce(value: number, delay: number) {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
// Show the value in DevTools
useDebugValue(debouncedValue);
useEffect(
() => {
// Update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cancel the timeout if value changes (also on delay change or unmount)
// This is how we prevent debounced value from updating if value is changed ...
// .. within the delay period. Timeout gets cleared and restarted.
return () => {
clearTimeout(handler);
};
},
[value, delay], // Only re-call effect if value or delay changes
);
return debouncedValue;
}
// Above copied from https://usehooks.com/
| 22.375796 | 85 | 0.683565 |
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+IHt9XTtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJjb3VudCIsImRhcmtNb2RlIiwiaXNEYXJrTW9kZSJdLCJtYXBwaW5ncyI6IkNBQUQ7YXFCQ0EsQVdEQTtpQmJFQSxBZUZBO29DVkdBLEFlSEEifV1dXX0= | 92.142857 | 2,884 | 0.838734 |
Mastering-Machine-Learning-for-Penetration-Testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {useContext, useMemo, useRef, useState} from 'react';
import {unstable_batchedUpdates as batchedUpdates} from 'react-dom';
import {copy} from 'clipboard-js';
import {
BridgeContext,
StoreContext,
} from 'react-devtools-shared/src/devtools/views/context';
import Button from '../../Button';
import ButtonIcon from '../../ButtonIcon';
import {serializeDataForCopy} from '../../utils';
import AutoSizeInput from './AutoSizeInput';
import styles from './StyleEditor.css';
import {sanitizeForParse} from '../../../utils';
import type {Style} from './types';
type Props = {
id: number,
style: Style,
};
type ChangeAttributeFn = (oldName: string, newName: string, value: any) => void;
type ChangeValueFn = (name: string, value: any) => void;
export default function StyleEditor({id, style}: Props): React.Node {
const bridge = useContext(BridgeContext);
const store = useContext(StoreContext);
const changeAttribute = (oldName: string, newName: string, value: any) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
bridge.send('NativeStyleEditor_renameAttribute', {
id,
rendererID,
oldName,
newName,
value,
});
}
};
const changeValue = (name: string, value: any) => {
const rendererID = store.getRendererIDForElement(id);
if (rendererID !== null) {
bridge.send('NativeStyleEditor_setValue', {
id,
rendererID,
name,
value,
});
}
};
const keys = useMemo(() => Array.from(Object.keys(style)), [style]);
const handleCopy = () => copy(serializeDataForCopy(style));
return (
<div className={styles.StyleEditor}>
<div className={styles.HeaderRow}>
<div className={styles.Header}>
<div className={styles.Brackets}>{'style {'}</div>
</div>
<Button onClick={handleCopy} title="Copy to clipboard">
<ButtonIcon type="copy" />
</Button>
</div>
{keys.length > 0 &&
keys.map(attribute => (
<Row
key={attribute}
attribute={attribute}
changeAttribute={changeAttribute}
changeValue={changeValue}
validAttributes={store.nativeStyleEditorValidAttributes}
value={style[attribute]}
/>
))}
<NewRow
changeAttribute={changeAttribute}
changeValue={changeValue}
validAttributes={store.nativeStyleEditorValidAttributes}
/>
<div className={styles.Brackets}>{'}'}</div>
</div>
);
}
type NewRowProps = {
changeAttribute: ChangeAttributeFn,
changeValue: ChangeValueFn,
validAttributes: $ReadOnlyArray<string> | null,
};
function NewRow({changeAttribute, changeValue, validAttributes}: NewRowProps) {
const [key, setKey] = useState<number>(0);
const reset = () => setKey(key + 1);
const newAttributeRef = useRef<string>('');
const changeAttributeWrapper = (
oldAttribute: string,
newAttribute: string,
value: any,
) => {
// Ignore attribute changes until a value has been specified
newAttributeRef.current = newAttribute;
};
const changeValueWrapper = (attribute: string, value: any) => {
// Blur events should reset/cancel if there's no value or no attribute
if (newAttributeRef.current !== '') {
if (value !== '') {
changeValue(newAttributeRef.current, value);
}
reset();
}
};
return (
<Row
key={key}
attribute={''}
attributePlaceholder="attribute"
changeAttribute={changeAttributeWrapper}
changeValue={changeValueWrapper}
validAttributes={validAttributes}
value={''}
valuePlaceholder="value"
/>
);
}
type RowProps = {
attribute: string,
attributePlaceholder?: string,
changeAttribute: ChangeAttributeFn,
changeValue: ChangeValueFn,
validAttributes: $ReadOnlyArray<string> | null,
value: any,
valuePlaceholder?: string,
};
function Row({
attribute,
attributePlaceholder,
changeAttribute,
changeValue,
validAttributes,
value,
valuePlaceholder,
}: RowProps) {
// TODO (RN style editor) Use @reach/combobox to auto-complete attributes.
// The list of valid attributes would need to be injected by RN backend,
// which would need to require them from ReactNativeViewViewConfig "validAttributes.style" keys.
// This would need to degrade gracefully for react-native-web,
// although we could let it also inject a custom set of allowed attributes.
const [localAttribute, setLocalAttribute] = useState(attribute);
const [localValue, setLocalValue] = useState(JSON.stringify(value));
const [isAttributeValid, setIsAttributeValid] = useState(true);
const [isValueValid, setIsValueValid] = useState(true);
// $FlowFixMe[missing-local-annot]
const validateAndSetLocalAttribute = newAttribute => {
const isValid =
newAttribute === '' ||
validAttributes === null ||
validAttributes.indexOf(newAttribute) >= 0;
batchedUpdates(() => {
setLocalAttribute(newAttribute);
setIsAttributeValid(isValid);
});
};
// $FlowFixMe[missing-local-annot]
const validateAndSetLocalValue = newValue => {
let isValid = false;
try {
JSON.parse(sanitizeForParse(newValue));
isValid = true;
} catch (error) {}
batchedUpdates(() => {
setLocalValue(newValue);
setIsValueValid(isValid);
});
};
const resetAttribute = () => {
setLocalAttribute(attribute);
};
const resetValue = () => {
setLocalValue(value);
};
const submitValueChange = () => {
if (isAttributeValid && isValueValid) {
const parsedLocalValue = JSON.parse(sanitizeForParse(localValue));
if (value !== parsedLocalValue) {
changeValue(attribute, parsedLocalValue);
}
}
};
const submitAttributeChange = () => {
if (isAttributeValid && isValueValid) {
if (attribute !== localAttribute) {
changeAttribute(attribute, localAttribute, value);
}
}
};
return (
<div className={styles.Row}>
<Field
className={isAttributeValid ? styles.Attribute : styles.Invalid}
onChange={validateAndSetLocalAttribute}
onReset={resetAttribute}
onSubmit={submitAttributeChange}
placeholder={attributePlaceholder}
value={localAttribute}
/>
:
<Field
className={isValueValid ? styles.Value : styles.Invalid}
onChange={validateAndSetLocalValue}
onReset={resetValue}
onSubmit={submitValueChange}
placeholder={valuePlaceholder}
value={localValue}
/>
;
</div>
);
}
type FieldProps = {
className: string,
onChange: (value: any) => void,
onReset: () => void,
onSubmit: () => void,
placeholder?: string,
value: any,
};
function Field({
className,
onChange,
onReset,
onSubmit,
placeholder,
value,
}: FieldProps) {
// $FlowFixMe[missing-local-annot]
const onKeyDown = event => {
switch (event.key) {
case 'Enter':
onSubmit();
break;
case 'Escape':
onReset();
break;
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
case 'ArrowUp':
event.stopPropagation();
break;
default:
break;
}
};
return (
<AutoSizeInput
className={`${className} ${styles.Input}`}
onBlur={onSubmit}
onChange={(event: $FlowFixMe) => onChange(event.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
value={value}
/>
);
}
| 25.325503 | 98 | 0.638067 |
null | 'use strict';
const semver = require('semver');
const {ReactVersion} = require('../../../ReactVersions');
const {
DARK_MODE_DIMMED_WARNING_COLOR,
DARK_MODE_DIMMED_ERROR_COLOR,
DARK_MODE_DIMMED_LOG_COLOR,
LIGHT_MODE_DIMMED_WARNING_COLOR,
LIGHT_MODE_DIMMED_ERROR_COLOR,
LIGHT_MODE_DIMMED_LOG_COLOR,
} = require('react-devtools-extensions/utils');
// DevTools stores preferences between sessions in localStorage
if (!global.hasOwnProperty('localStorage')) {
global.localStorage = require('local-storage-fallback').default;
}
// Mimic the global we set with Webpack's DefinePlugin
global.__DEV__ = process.env.NODE_ENV !== 'production';
global.__TEST__ = true;
global.process.env.DARK_MODE_DIMMED_WARNING_COLOR =
DARK_MODE_DIMMED_WARNING_COLOR;
global.process.env.DARK_MODE_DIMMED_ERROR_COLOR = DARK_MODE_DIMMED_ERROR_COLOR;
global.process.env.DARK_MODE_DIMMED_LOG_COLOR = DARK_MODE_DIMMED_LOG_COLOR;
global.process.env.LIGHT_MODE_DIMMED_WARNING_COLOR =
LIGHT_MODE_DIMMED_WARNING_COLOR;
global.process.env.LIGHT_MODE_DIMMED_ERROR_COLOR =
LIGHT_MODE_DIMMED_ERROR_COLOR;
global.process.env.LIGHT_MODE_DIMMED_LOG_COLOR = LIGHT_MODE_DIMMED_LOG_COLOR;
global._test_react_version = (range, testName, callback) => {
const reactVersion = process.env.REACT_VERSION || ReactVersion;
const shouldPass = semver.satisfies(reactVersion, range);
if (shouldPass) {
test(testName, callback);
} else {
test.skip(testName, callback);
}
};
global._test_react_version_focus = (range, testName, callback) => {
const reactVersion = process.env.REACT_VERSION || ReactVersion;
const shouldPass = semver.satisfies(reactVersion, range);
if (shouldPass) {
// eslint-disable-next-line jest/no-focused-tests
test.only(testName, callback);
} else {
test.skip(testName, callback);
}
};
global._test_ignore_for_react_version = (testName, callback) => {
test.skip(testName, callback);
};
| 31.05 | 79 | 0.728928 |
owtf | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
module.exports = {
// Text colors
primary: '#23272F', // gray-90
'primary-dark': '#F6F7F9', // gray-5
secondary: '#404756', // gray-70
'secondary-dark': '#EBECF0', // gray-10
tertiary: '#5E687E', // gray-50
'tertiary-dark': '#99A1B3', // gray-30
link: '#087EA4', // blue-50
'link-dark': '#149ECA', // blue-40
syntax: '#EBECF0', // gray-10
wash: '#FFFFFF',
'wash-dark': '#23272F', // gray-90
card: '#F6F7F9', // gray-05
'card-dark': '#343A46', // gray-80
highlight: '#E6F7FF', // blue-10
'highlight-dark': 'rgba(88,175,223,.1)',
border: '#EBECF0', // gray-10
'border-dark': '#343A46', // gray-80
'secondary-button': '#EBECF0', // gray-10
'secondary-button-dark': '#404756', // gray-70
// Gray
'gray-95': '#16181D',
'gray-90': '#23272F',
'gray-80': '#343A46',
'gray-70': '#404756',
'gray-60': '#4E5769',
'gray-50': '#5E687E',
'gray-40': '#78839B',
'gray-30': '#99A1B3',
'gray-20': '#BCC1CD',
'gray-15': '#D0D3DC',
'gray-10': '#EBECF0',
'gray-5': '#F6F7F9',
// Blue
'blue-80': '#043849',
'blue-60': '#045975',
'blue-50': '#087EA4',
'blue-40': '#149ECA', // Brand Blue
'blue-30': '#58C4DC', // unused
'blue-20': '#ABE2ED',
'blue-10': '#E6F7FF', // todo: doesn't match illustrations
'blue-5': '#E6F6FA',
// Yellow
'yellow-60': '#B65700',
'yellow-50': '#C76A15',
'yellow-40': '#DB7D27', // unused
'yellow-30': '#FABD62', // unused
'yellow-20': '#FCDEB0', // unused
'yellow-10': '#FDE7C7',
'yellow-5': '#FEF5E7',
// Purple
'purple-60': '#2B3491', // unused
'purple-50': '#575FB7',
'purple-40': '#6B75DB',
'purple-30': '#8891EC',
'purple-20': '#C3C8F5', // unused
'purple-10': '#E7E9FB',
'purple-5': '#F3F4FD',
// Green
'green-60': '#2B6E62',
'green-50': '#388F7F',
'green-40': '#44AC99',
'green-30': '#7FCCBF',
'green-20': '#ABDED5',
'green-10': '#E5F5F2',
'green-5': '#F4FBF9',
// RED
'red-60': '#712D28',
'red-50': '#A6423A', // unused
'red-40': '#C1554D',
'red-30': '#D07D77',
'red-20': '#E5B7B3', // unused
'red-10': '#F2DBD9', // unused
'red-5': '#FAF1F0',
// MISC
'code-block': '#99a1b30f', // gray-30 @ 6%
'gradient-blue': '#58C4DC', // Only used for the landing gradient for now.
github: {
highlight: '#fffbdd',
},
};
| 23.989362 | 76 | 0.543015 |
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';
const objectWithModifiedHasOwnProperty = {
foo: 'abc',
bar: 123,
hasOwnProperty: true,
};
const objectWithNullProto = Object.create(null);
// $FlowFixMe[prop-missing] found when upgrading Flow
objectWithNullProto.foo = 'abc';
// $FlowFixMe[prop-missing] found when upgrading Flow
objectWithNullProto.bar = 123;
export default function EdgeCaseObjects(): React.Node {
return (
<ChildComponent
objectWithModifiedHasOwnProperty={objectWithModifiedHasOwnProperty}
objectWithNullProto={objectWithNullProto}
/>
);
}
function ChildComponent(props: any) {
return null;
}
| 22.222222 | 73 | 0.730539 |
Python-Penetration-Testing-for-Developers | 'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-server-dom-esm-client.node.production.min.js');
} else {
module.exports = require('./cjs/react-server-dom-esm-client.node.development.js');
}
| 29.625 | 87 | 0.696721 |
cybersecurity-penetration-testing | 'use strict';
function checkDCE() {
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
) {
return;
}
if (process.env.NODE_ENV !== 'production') {
// This branch is unreachable because this function is only called
// in production, but the condition is true only in development.
// Therefore if the branch is still here, dead code elimination wasn't
// properly applied.
// Don't change the message. React DevTools relies on it. Also make sure
// this message doesn't occur elsewhere in this function, or it will cause
// a false positive.
throw new Error('^_^');
}
try {
// Verify that the code above has been dead code eliminated (DCE'd).
__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
} catch (err) {
// DevTools shouldn't crash React, no matter what.
// We should still report in case we break this code.
console.error(err);
}
}
if (process.env.NODE_ENV === 'production') {
// DCE check should happen before ReactDOM bundle executes so that
// DevTools can report bad minification during injection.
checkDCE();
module.exports = require('./cjs/react-dom-unstable_testing.production.min.js');
} else {
module.exports = require('./cjs/react-dom-unstable_testing.development.js');
}
| 34.846154 | 81 | 0.675734 |
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';
const fs = require('fs');
const ReactVersionSrc = fs.readFileSync(
require.resolve('../../packages/shared/ReactVersion')
);
const reactVersion = /export default '([^']+)';/.exec(ReactVersionSrc)[1];
const versions = {
'packages/react/package.json': require('../../packages/react/package.json')
.version,
'packages/react-dom/package.json':
require('../../packages/react-dom/package.json').version,
'packages/react-test-renderer/package.json':
require('../../packages/react-test-renderer/package.json').version,
'packages/shared/ReactVersion.js': reactVersion,
};
let allVersionsMatch = true;
Object.keys(versions).forEach(function (name) {
const version = versions[name];
if (version !== reactVersion) {
allVersionsMatch = false;
console.log(
'%s version does not match package.json. Expected %s, saw %s.',
name,
reactVersion,
version
);
}
});
if (!allVersionsMatch) {
process.exit(1);
}
| 26.069767 | 77 | 0.676698 |
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 function loadChunk(filename: string): Promise<mixed> {
return __turbopack_load__(filename);
}
| 22.692308 | 66 | 0.703583 |
Python-Penetration-Testing-Cookbook | "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; }
// ?sourceMappingURL=([^\s'"]+)/gm
function Component() {
const [count, setCount] = (0, _react.useState)(0);
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 18,
columnNumber: 5
}
}, /*#__PURE__*/_react.default.createElement("p", {
__source: {
fileName: _jsxFileName,
lineNumber: 19,
columnNumber: 7
}
}, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", {
onClick: () => setCount(count + 1),
__source: {
fileName: _jsxFileName,
lineNumber: 20,
columnNumber: 7
}
}, "Click me"));
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbnRhaW5pbmdTdHJpbmdTb3VyY2VNYXBwaW5nVVJMLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFFQTtBQUVBLFNBQUFBLFNBQUEsR0FBQTtBQUNBLFFBQUEsQ0FBQUMsS0FBQSxFQUFBQyxRQUFBLElBQUEscUJBQUEsQ0FBQSxDQUFBO0FBRUEsc0JBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEscUJBQUFELEtBQUEsV0FEQSxlQUVBO0FBQUEsSUFBQSxPQUFBLEVBQUEsTUFBQUMsUUFBQSxDQUFBRCxLQUFBLEdBQUEsQ0FBQSxDQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUZBLENBREE7QUFNQSIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QsIHt1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG4vLyA/c291cmNlTWFwcGluZ1VSTD0oW15cXHMnXCJdKykvZ21cblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50LCBzZXRDb3VudF0gPSB1c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gKFxuICAgIDxkaXY+XG4gICAgICA8cD5Zb3UgY2xpY2tlZCB7Y291bnR9IHRpbWVzPC9wPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXsoKSA9PiBzZXRDb3VudChjb3VudCArIDEpfT5DbGljayBtZTwvYnV0dG9uPlxuICAgIDwvZGl2PlxuICApO1xufVxuIl19 | 77.45 | 1,344 | 0.790564 |
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';
let Activity;
let React = require('react');
let ReactDOM;
let ReactDOMClient;
let ReactDOMServer;
let ReactFeatureFlags;
let Scheduler;
let Suspense;
let SuspenseList;
let useSyncExternalStore;
let act;
let IdleEventPriority;
let waitForAll;
let waitFor;
let waitForPaint;
let assertLog;
function normalizeCodeLocInfo(strOrErr) {
if (strOrErr && strOrErr.replace) {
return strOrErr.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function (m, name) {
return '\n in ' + name + ' (at **)';
});
}
return strOrErr;
}
function dispatchMouseEvent(to, from) {
if (!to) {
to = null;
}
if (!from) {
from = null;
}
if (from) {
const mouseOutEvent = document.createEvent('MouseEvents');
mouseOutEvent.initMouseEvent(
'mouseout',
true,
true,
window,
0,
50,
50,
50,
50,
false,
false,
false,
false,
0,
to,
);
from.dispatchEvent(mouseOutEvent);
}
if (to) {
const mouseOverEvent = document.createEvent('MouseEvents');
mouseOverEvent.initMouseEvent(
'mouseover',
true,
true,
window,
0,
50,
50,
50,
50,
false,
false,
false,
false,
0,
from,
);
to.dispatchEvent(mouseOverEvent);
}
}
class TestAppClass extends React.Component {
render() {
return (
<div>
<>{''}</>
<>{'Hello'}</>
</div>
);
}
}
describe('ReactDOMServerPartialHydration', () => {
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.enableSuspenseCallback = true;
ReactFeatureFlags.enableCreateEventHandleAPI = true;
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
act = require('internal-test-utils').act;
ReactDOMServer = require('react-dom/server');
Scheduler = require('scheduler');
Activity = React.unstable_Activity;
Suspense = React.Suspense;
useSyncExternalStore = React.useSyncExternalStore;
if (gate(flags => flags.enableSuspenseList)) {
SuspenseList = React.unstable_SuspenseList;
}
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
assertLog = InternalTestUtils.assertLog;
waitForPaint = InternalTestUtils.waitForPaint;
waitFor = InternalTestUtils.waitFor;
IdleEventPriority = require('react-reconciler/constants').IdleEventPriority;
});
// 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('hydrates a parent even if a child Suspense boundary is blocked', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref}>
<Child />
</span>
</Suspense>
</div>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
expect(ref.current).toBe(null);
// Resolving the promise should continue hydration
suspend = false;
resolve();
await promise;
await waitForAll([]);
// We should now have hydrated with a ref on the existing span.
expect(ref.current).toBe(span);
});
it('can hydrate siblings of a suspended component without errors', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function App() {
return (
<Suspense fallback="Loading...">
<Child />
<Suspense fallback="Loading...">
<div>Hello</div>
</Suspense>
</Suspense>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
expect(container.textContent).toBe('HelloHello');
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
await waitForAll([]);
// Expect the server-generated HTML to stay intact.
expect(container.textContent).toBe('HelloHello');
// Resolving the promise should continue hydration
suspend = false;
resolve();
await promise;
await waitForAll([]);
// Hydration should not change anything.
expect(container.textContent).toBe('HelloHello');
});
it('falls back to client rendering boundary on mismatch', async () => {
// We can't use the toErrorDev helper here because this is async.
const originalConsoleError = console.error;
const mockError = jest.fn();
console.error = (...args) => {
mockError(...args.map(normalizeCodeLocInfo));
};
let client = false;
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => {
resolve = () => {
suspend = false;
resolvePromise();
};
});
function Child() {
if (suspend) {
Scheduler.log('Suspend');
throw promise;
} else {
Scheduler.log('Hello');
return 'Hello';
}
}
function Component({shouldMismatch}) {
Scheduler.log('Component');
if (shouldMismatch && client) {
return <article>Mismatch</article>;
}
return <div>Component</div>;
}
function App() {
return (
<Suspense fallback="Loading...">
<Child />
<Component />
<Component />
<Component />
<Component shouldMismatch={true} />
</Suspense>
);
}
try {
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('section');
container.innerHTML = finalHTML;
assertLog(['Hello', 'Component', 'Component', 'Component', 'Component']);
expect(container.innerHTML).toBe(
'<!--$-->Hello<div>Component</div><div>Component</div><div>Component</div><div>Component</div><!--/$-->',
);
suspend = true;
client = true;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
await waitForAll(['Suspend']);
jest.runAllTimers();
// Unchanged
expect(container.innerHTML).toBe(
'<!--$-->Hello<div>Component</div><div>Component</div><div>Component</div><div>Component</div><!--/$-->',
);
suspend = false;
resolve();
await promise;
await waitForAll([
// first pass, mismatches at end
'Hello',
'Component',
'Component',
'Component',
'Component',
// second pass as client render
'Hello',
'Component',
'Component',
'Component',
'Component',
// Hydration mismatch is logged
'Hydration failed because the initial UI does not match what was rendered on the server.',
'There was an error while hydrating this Suspense boundary. Switched to client rendering.',
]);
// Client rendered - suspense comment nodes removed
expect(container.innerHTML).toBe(
'Hello<div>Component</div><div>Component</div><div>Component</div><article>Mismatch</article>',
);
if (__DEV__) {
const secondToLastCall =
mockError.mock.calls[mockError.mock.calls.length - 2];
expect(secondToLastCall).toEqual([
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'article',
'section',
'\n' +
' in article (at **)\n' +
' in Component (at **)\n' +
' in Suspense (at **)\n' +
' in App (at **)',
]);
}
} finally {
console.error = originalConsoleError;
}
});
it('calls the hydration callbacks after hydration or deletion', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
let suspend2 = false;
const promise2 = new Promise(() => {});
function Child2() {
if (suspend2) {
throw promise2;
} else {
return 'World';
}
}
function App({value}) {
return (
<div>
<Suspense fallback="Loading...">
<Child />
</Suspense>
<Suspense fallback="Loading...">
<Child2 value={value} />
</Suspense>
</div>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
suspend = false;
suspend2 = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const hydrated = [];
const deleted = [];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
suspend2 = true;
const root = ReactDOMClient.hydrateRoot(container, <App />, {
onHydrated(node) {
hydrated.push(node);
},
onDeleted(node) {
deleted.push(node);
},
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
await waitForAll([]);
expect(hydrated.length).toBe(0);
expect(deleted.length).toBe(0);
await act(async () => {
// Resolving the promise should continue hydration
suspend = false;
resolve();
await promise;
});
expect(hydrated.length).toBe(1);
expect(deleted.length).toBe(0);
// Performing an update should force it to delete the boundary
await act(() => {
root.render(<App value={true} />);
});
expect(hydrated.length).toBe(1);
expect(deleted.length).toBe(1);
});
it('hydrates an empty suspense boundary', async () => {
function App() {
return (
<div>
<Suspense fallback="Loading..." />
<div>Sibling</div>
</div>
);
}
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
expect(container.innerHTML).toContain('<div>Sibling</div>');
});
it('recovers with client render when server rendered additional nodes at suspense root', async () => {
function CheckIfHydrating({children}) {
// This is a trick to check whether we're hydrating or not, since React
// doesn't expose that information currently except
// via useSyncExternalStore.
let serverOrClient = '(unknown)';
useSyncExternalStore(
() => {},
() => {
serverOrClient = 'Client rendered';
return null;
},
() => {
serverOrClient = 'Server rendered';
return null;
},
);
Scheduler.log(serverOrClient);
return null;
}
const ref = React.createRef();
function App({hasB}) {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref}>A</span>
{hasB ? <span>B</span> : null}
<CheckIfHydrating />
</Suspense>
<div>Sibling</div>
</div>
);
}
const finalHTML = ReactDOMServer.renderToString(<App hasB={true} />);
assertLog(['Server rendered']);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
expect(container.innerHTML).toContain('<span>A</span>');
expect(container.innerHTML).toContain('<span>B</span>');
expect(ref.current).toBe(null);
await expect(async () => {
await act(() => {
ReactDOMClient.hydrateRoot(container, <App hasB={false} />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
});
}).toErrorDev('Did not expect server HTML to contain a <span> in <div>');
expect(container.innerHTML).toContain('<span>A</span>');
expect(container.innerHTML).not.toContain('<span>B</span>');
assertLog([
'Server rendered',
'Client rendered',
'There was an error while hydrating this Suspense boundary. ' +
'Switched to client rendering.',
]);
expect(ref.current).not.toBe(span);
});
it('recovers with client render when server rendered additional nodes at suspense root after unsuspending', async () => {
// We can't use the toErrorDev helper here because this is async.
const originalConsoleError = console.error;
const mockError = jest.fn();
console.error = (...args) => {
mockError(...args.map(normalizeCodeLocInfo));
};
const ref = React.createRef();
let shouldSuspend = false;
let resolve;
const promise = new Promise(res => {
resolve = () => {
shouldSuspend = false;
res();
};
});
function Suspender() {
if (shouldSuspend) {
throw promise;
}
return <></>;
}
function App({hasB}) {
return (
<div>
<Suspense fallback="Loading...">
<Suspender />
<span ref={ref}>A</span>
{hasB ? <span>B</span> : null}
</Suspense>
<div>Sibling</div>
</div>
);
}
try {
const finalHTML = ReactDOMServer.renderToString(<App hasB={true} />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
expect(container.innerHTML).toContain('<span>A</span>');
expect(container.innerHTML).toContain('<span>B</span>');
expect(ref.current).toBe(null);
shouldSuspend = true;
await act(() => {
ReactDOMClient.hydrateRoot(container, <App hasB={false} />);
});
await act(() => {
resolve();
});
expect(container.innerHTML).toContain('<span>A</span>');
expect(container.innerHTML).not.toContain('<span>B</span>');
expect(ref.current).not.toBe(span);
if (__DEV__) {
expect(mockError).toHaveBeenCalledWith(
'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s',
'span',
'div',
'\n' +
' in Suspense (at **)\n' +
' in div (at **)\n' +
' in App (at **)',
);
}
} finally {
console.error = originalConsoleError;
}
});
it('recovers with client render when server rendered additional nodes deep inside suspense root', async () => {
const ref = React.createRef();
function App({hasB}) {
return (
<div>
<Suspense fallback="Loading...">
<div>
<span ref={ref}>A</span>
{hasB ? <span>B</span> : null}
</div>
</Suspense>
<div>Sibling</div>
</div>
);
}
const finalHTML = ReactDOMServer.renderToString(<App hasB={true} />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
expect(container.innerHTML).toContain('<span>A</span>');
expect(container.innerHTML).toContain('<span>B</span>');
expect(ref.current).toBe(null);
await expect(async () => {
await act(() => {
ReactDOMClient.hydrateRoot(container, <App hasB={false} />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
});
}).toErrorDev('Did not expect server HTML to contain a <span> in <div>');
assertLog([
'Hydration failed because the initial UI does not match what was rendered on the server.',
'There was an error while hydrating this Suspense boundary. Switched to client rendering.',
]);
expect(container.innerHTML).toContain('<span>A</span>');
expect(container.innerHTML).not.toContain('<span>B</span>');
expect(ref.current).not.toBe(span);
});
it('calls the onDeleted hydration callback if the parent gets deleted', async () => {
let suspend = false;
const promise = new Promise(() => {});
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function App({deleted}) {
if (deleted) {
return null;
}
return (
<div>
<Suspense fallback="Loading...">
<Child />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const deleted = [];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = await act(() => {
return ReactDOMClient.hydrateRoot(container, <App />, {
onDeleted(node) {
deleted.push(node);
},
});
});
expect(deleted.length).toBe(0);
await act(() => {
root.render(<App deleted={true} />);
});
// The callback should have been invoked.
expect(deleted.length).toBe(1);
});
it('warns and replaces the boundary content in legacy mode', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref}>
<Child />
</span>
</Suspense>
</div>
);
}
// Don't suspend on the server.
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we try to hydrate.
suspend = true;
await expect(async () => {
await act(() => {
ReactDOM.hydrate(<App />, container);
});
}).toErrorDev(
'Warning: Cannot hydrate Suspense in legacy mode. Switch from ' +
'ReactDOM.hydrate(element, container) to ' +
'ReactDOMClient.hydrateRoot(container, <App />)' +
'.render(element) or remove the Suspense components from the server ' +
'rendered components.' +
'\n in Suspense (at **)' +
'\n in div (at **)' +
'\n in App (at **)',
);
// We're now in loading state.
expect(container.textContent).toBe('Loading...');
const span2 = container.getElementsByTagName('span')[0];
// This is a new node.
expect(span).not.toBe(span2);
if (gate(flags => flags.dfsEffectsRefactor)) {
// The effects list refactor causes this to be null because the Suspense Activity's child
// is null. However, since we can't hydrate Suspense in legacy this change in behavior is ok
expect(ref.current).toBe(null);
} else {
expect(ref.current).toBe(span2);
}
// Resolving the promise should render the final content.
suspend = false;
await act(() => resolve());
// We should now have hydrated with a ref on the existing span.
expect(container.textContent).toBe('Hello');
});
it('can insert siblings before the dehydrated boundary', async () => {
let suspend = false;
const promise = new Promise(() => {});
let showSibling;
function Child() {
if (suspend) {
throw promise;
} else {
return 'Second';
}
}
function Sibling() {
const [visible, setVisibilty] = React.useState(false);
showSibling = () => setVisibilty(true);
if (visible) {
return <div>First</div>;
}
return null;
}
function App() {
return (
<div>
<Sibling />
<Suspense fallback="Loading...">
<span>
<Child />
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
await act(() => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container.firstChild.firstChild.tagName).not.toBe('DIV');
// In this state, we can still update the siblings.
await act(() => showSibling());
expect(container.firstChild.firstChild.tagName).toBe('DIV');
expect(container.firstChild.firstChild.textContent).toBe('First');
});
it('can delete the dehydrated boundary before it is hydrated', async () => {
let suspend = false;
const promise = new Promise(() => {});
let hideMiddle;
function Child() {
if (suspend) {
throw promise;
} else {
return (
<>
<div>Middle</div>
Some text
</>
);
}
}
function App() {
const [visible, setVisibilty] = React.useState(true);
hideMiddle = () => setVisibilty(false);
return (
<div>
<div>Before</div>
{visible ? (
<Suspense fallback="Loading...">
<Child />
</Suspense>
) : null}
<div>After</div>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
await act(() => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(container.firstChild.children[1].textContent).toBe('Middle');
// In this state, we can still delete the boundary.
await act(() => hideMiddle());
expect(container.firstChild.children[1].textContent).toBe('After');
});
it('blocks updates to hydrate the content first if props have changed', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({text}) {
if (suspend) {
throw promise;
} else {
return text;
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref} className={className}>
<Child text={text} />
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<App text="Hello" className="hello" />,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
);
await waitForAll([]);
expect(ref.current).toBe(null);
expect(span.textContent).toBe('Hello');
// Render an update, which will be higher or the same priority as pinging the hydration.
root.render(<App text="Hi" className="hi" />);
// At the same time, resolving the promise so that rendering can complete.
// This should first complete the hydration and then flush the update onto the hydrated state.
await act(async () => {
suspend = false;
resolve();
await promise;
});
// The new span should be the same since we should have successfully hydrated
// before changing it.
const newSpan = container.getElementsByTagName('span')[0];
expect(span).toBe(newSpan);
// We should now have fully rendered with a ref on the new span.
expect(ref.current).toBe(span);
expect(span.textContent).toBe('Hi');
// If we ended up hydrating the existing content, we won't have properly
// patched up the tree, which might mean we haven't patched the className.
expect(span.className).toBe('hi');
});
// @gate experimental || www
it('blocks updates to hydrate the content first if props changed at idle priority', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({text}) {
if (suspend) {
throw promise;
} else {
return text;
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref} className={className}>
<Child text={text} />
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<App text="Hello" className="hello" />,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
);
await waitForAll([]);
expect(ref.current).toBe(null);
expect(span.textContent).toBe('Hello');
// Schedule an update at idle priority
ReactDOM.unstable_runWithPriority(IdleEventPriority, () => {
root.render(<App text="Hi" className="hi" />);
});
// At the same time, resolving the promise so that rendering can complete.
suspend = false;
resolve();
await promise;
// This should first complete the hydration and then flush the update onto the hydrated state.
await waitForAll([]);
// The new span should be the same since we should have successfully hydrated
// before changing it.
const newSpan = container.getElementsByTagName('span')[0];
expect(span).toBe(newSpan);
// We should now have fully rendered with a ref on the new span.
expect(ref.current).toBe(span);
expect(span.textContent).toBe('Hi');
// If we ended up hydrating the existing content, we won't have properly
// patched up the tree, which might mean we haven't patched the className.
expect(span.className).toBe('hi');
});
it('shows the fallback if props have changed before hydration completes and is still suspended', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({text}) {
if (suspend) {
throw promise;
} else {
return text;
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref} className={className}>
<Child text={text} />
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<App text="Hello" className="hello" />,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
{
onRecoverableError(error) {
Scheduler.log(error.message);
},
},
);
await waitForAll([]);
expect(ref.current).toBe(null);
// Render an update, but leave it still suspended.
await act(() => {
root.render(<App text="Hi" className="hi" />);
});
// Flushing now should delete the existing content and show the fallback.
expect(container.getElementsByTagName('span').length).toBe(0);
expect(ref.current).toBe(null);
expect(container.textContent).toBe('Loading...');
// Unsuspending shows the content.
await act(async () => {
suspend = false;
resolve();
await promise;
});
const span = container.getElementsByTagName('span')[0];
expect(span.textContent).toBe('Hi');
expect(span.className).toBe('hi');
expect(ref.current).toBe(span);
expect(container.textContent).toBe('Hi');
});
it('treats missing fallback the same as if it was defined', async () => {
// This is the same exact test as above but with a nested Suspense without a fallback.
// This should be a noop.
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({text}) {
if (suspend) {
throw promise;
} else {
return text;
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref} className={className}>
<Suspense>
<Child text={text} />
</Suspense>
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<App text="Hello" className="hello" />,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
{
onRecoverableError(error) {
Scheduler.log(error.message);
},
},
);
await waitForAll([]);
const span = container.getElementsByTagName('span')[0];
expect(ref.current).toBe(span);
// Render an update, but leave it still suspended.
// Flushing now should delete the existing content and show the fallback.
await act(() => {
root.render(<App text="Hi" className="hi" />);
});
expect(container.getElementsByTagName('span').length).toBe(1);
expect(ref.current).toBe(span);
expect(container.textContent).toBe('');
// Unsuspending shows the content.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(span.textContent).toBe('Hi');
expect(span.className).toBe('hi');
expect(ref.current).toBe(span);
expect(container.textContent).toBe('Hi');
});
it('clears nested suspense boundaries if they did not hydrate yet', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({text}) {
if (suspend) {
throw promise;
} else {
return text;
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<Suspense fallback="Never happens">
<Child text={text} />
</Suspense>{' '}
<span ref={ref} className={className}>
<Child text={text} />
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<App text="Hello" className="hello" />,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
{
onRecoverableError(error) {
Scheduler.log(error.message);
},
},
);
await waitForAll([]);
expect(ref.current).toBe(null);
// Render an update, but leave it still suspended.
// Flushing now should delete the existing content and show the fallback.
await act(() => {
root.render(<App text="Hi" className="hi" />);
});
expect(container.getElementsByTagName('span').length).toBe(0);
expect(ref.current).toBe(null);
expect(container.textContent).toBe('Loading...');
// Unsuspending shows the content.
await act(async () => {
suspend = false;
resolve();
await promise;
});
await waitForAll([]);
const span = container.getElementsByTagName('span')[0];
expect(span.textContent).toBe('Hi');
expect(span.className).toBe('hi');
expect(ref.current).toBe(span);
expect(container.textContent).toBe('Hi Hi');
});
it('hydrates first if props changed but we are able to resolve within a timeout', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({text}) {
if (suspend) {
throw promise;
} else {
return text;
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref} className={className}>
<Child text={text} />
</span>
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<App text="Hello" className="hello" />,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
);
await waitForAll([]);
expect(ref.current).toBe(null);
expect(container.textContent).toBe('Hello');
// Render an update with a long timeout.
React.startTransition(() => root.render(<App text="Hi" className="hi" />));
// This shouldn't force the fallback yet.
await waitForAll([]);
expect(ref.current).toBe(null);
expect(container.textContent).toBe('Hello');
// Resolving the promise so that rendering can complete.
// This should first complete the hydration and then flush the update onto the hydrated state.
suspend = false;
await act(() => resolve());
// The new span should be the same since we should have successfully hydrated
// before changing it.
const newSpan = container.getElementsByTagName('span')[0];
expect(span).toBe(newSpan);
// We should now have fully rendered with a ref on the new span.
expect(ref.current).toBe(span);
expect(container.textContent).toBe('Hi');
// If we ended up hydrating the existing content, we won't have properly
// patched up the tree, which might mean we haven't patched the className.
expect(span.className).toBe('hi');
});
it('warns but works if setState is called before commit in a dehydrated component', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
let updateText;
function Child() {
const [state, setState] = React.useState('Hello');
updateText = setState;
Scheduler.log('Child');
if (suspend) {
throw promise;
} else {
return state;
}
}
function Sibling() {
Scheduler.log('Sibling');
return null;
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Child />
<Sibling />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
assertLog(['Child', 'Sibling']);
const container = document.createElement('div');
container.innerHTML = finalHTML;
ReactDOMClient.hydrateRoot(
container,
<App text="Hello" className="hello" />,
);
await act(async () => {
suspend = true;
await waitFor(['Child']);
// While we're part way through the hydration, we update the state.
// This will schedule an update on the children of the suspense boundary.
expect(() => updateText('Hi')).toErrorDev(
"Can't perform a React state update on a component that hasn't mounted yet.",
);
// This will throw it away and rerender.
await waitForAll(['Child']);
expect(container.textContent).toBe('Hello');
suspend = false;
resolve();
await promise;
});
assertLog(['Child', 'Sibling']);
expect(container.textContent).toBe('Hello');
});
it('blocks the update to hydrate first if context has changed', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
const Context = React.createContext(null);
function Child() {
const {text, className} = React.useContext(Context);
if (suspend) {
throw promise;
} else {
return (
<span ref={ref} className={className}>
{text}
</span>
);
}
}
const App = React.memo(function App() {
return (
<div>
<Suspense fallback="Loading...">
<Child />
</Suspense>
</div>
);
});
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<Context.Provider value={{text: 'Hello', className: 'hello'}}>
<App />
</Context.Provider>,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<Context.Provider value={{text: 'Hello', className: 'hello'}}>
<App />
</Context.Provider>,
);
await waitForAll([]);
expect(ref.current).toBe(null);
expect(span.textContent).toBe('Hello');
// Render an update, which will be higher or the same priority as pinging the hydration.
root.render(
<Context.Provider value={{text: 'Hi', className: 'hi'}}>
<App />
</Context.Provider>,
);
// At the same time, resolving the promise so that rendering can complete.
// This should first complete the hydration and then flush the update onto the hydrated state.
await act(async () => {
suspend = false;
resolve();
await promise;
});
// Since this should have been hydrated, this should still be the same span.
const newSpan = container.getElementsByTagName('span')[0];
expect(newSpan).toBe(span);
// We should now have fully rendered with a ref on the new span.
expect(ref.current).toBe(span);
expect(span.textContent).toBe('Hi');
// If we ended up hydrating the existing content, we won't have properly
// patched up the tree, which might mean we haven't patched the className.
expect(span.className).toBe('hi');
});
it('shows the fallback if context has changed before hydration completes and is still suspended', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
const Context = React.createContext(null);
function Child() {
const {text, className} = React.useContext(Context);
if (suspend) {
throw promise;
} else {
return (
<span ref={ref} className={className}>
{text}
</span>
);
}
}
const App = React.memo(function App() {
return (
<div>
<Suspense fallback="Loading...">
<Child />
</Suspense>
</div>
);
});
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<Context.Provider value={{text: 'Hello', className: 'hello'}}>
<App />
</Context.Provider>,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<Context.Provider value={{text: 'Hello', className: 'hello'}}>
<App />
</Context.Provider>,
{
onRecoverableError(error) {
Scheduler.log(error.message);
},
},
);
await waitForAll([]);
expect(ref.current).toBe(null);
// Render an update, but leave it still suspended.
// Flushing now should delete the existing content and show the fallback.
await act(() => {
root.render(
<Context.Provider value={{text: 'Hi', className: 'hi'}}>
<App />
</Context.Provider>,
);
});
expect(container.getElementsByTagName('span').length).toBe(0);
expect(ref.current).toBe(null);
expect(container.textContent).toBe('Loading...');
// Unsuspending shows the content.
await act(async () => {
suspend = false;
resolve();
await promise;
});
const span = container.getElementsByTagName('span')[0];
expect(span.textContent).toBe('Hi');
expect(span.className).toBe('hi');
expect(ref.current).toBe(span);
expect(container.textContent).toBe('Hi');
});
it('replaces the fallback with client content if it is not rendered by the server', async () => {
let suspend = false;
const promise = new Promise(resolvePromise => {});
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref}>
<Child />
</span>
</Suspense>
</div>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
suspend = true;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
expect(container.getElementsByTagName('span').length).toBe(0);
// On the client we have the data available quickly for some reason.
suspend = false;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
if (__DEV__) {
await waitForAll([
'The server did not finish this Suspense boundary: The server used' +
' "renderToString" which does not support Suspense. If you intended' +
' for this Suspense boundary to render the fallback content on the' +
' server consider throwing an Error somewhere within the Suspense boundary.' +
' If you intended to have the server wait for the suspended component' +
' please switch to "renderToPipeableStream" which supports Suspense on the server',
]);
} else {
await waitForAll([
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
]);
}
jest.runAllTimers();
expect(container.textContent).toBe('Hello');
const span = container.getElementsByTagName('span')[0];
expect(ref.current).toBe(span);
});
it('replaces the fallback within the suspended time if there is a nested suspense', async () => {
let suspend = false;
const promise = new Promise(resolvePromise => {});
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function InnerChild() {
// Always suspends indefinitely
throw promise;
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<span ref={ref}>
<Child />
</span>
<Suspense fallback={null}>
<InnerChild />
</Suspense>
</Suspense>
</div>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
suspend = true;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
expect(container.getElementsByTagName('span').length).toBe(0);
// On the client we have the data available quickly for some reason.
suspend = false;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
if (__DEV__) {
await waitForAll([
'The server did not finish this Suspense boundary: The server used' +
' "renderToString" which does not support Suspense. If you intended' +
' for this Suspense boundary to render the fallback content on the' +
' server consider throwing an Error somewhere within the Suspense boundary.' +
' If you intended to have the server wait for the suspended component' +
' please switch to "renderToPipeableStream" which supports Suspense on the server',
]);
} else {
await waitForAll([
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
]);
}
// This will have exceeded the suspended time so we should timeout.
jest.advanceTimersByTime(500);
// The boundary should longer be suspended for the middle content
// even though the inner boundary is still suspended.
expect(container.textContent).toBe('Hello');
const span = container.getElementsByTagName('span')[0];
expect(ref.current).toBe(span);
});
it('replaces the fallback within the suspended time if there is a nested suspense in a nested suspense', async () => {
let suspend = false;
const promise = new Promise(resolvePromise => {});
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function InnerChild() {
// Always suspends indefinitely
throw promise;
}
function App() {
return (
<div>
<Suspense fallback="Another layer">
<Suspense fallback="Loading...">
<span ref={ref}>
<Child />
</span>
<Suspense fallback={null}>
<InnerChild />
</Suspense>
</Suspense>
</Suspense>
</div>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
suspend = true;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
expect(container.getElementsByTagName('span').length).toBe(0);
// On the client we have the data available quickly for some reason.
suspend = false;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
if (__DEV__) {
await waitForAll([
'The server did not finish this Suspense boundary: The server used' +
' "renderToString" which does not support Suspense. If you intended' +
' for this Suspense boundary to render the fallback content on the' +
' server consider throwing an Error somewhere within the Suspense boundary.' +
' If you intended to have the server wait for the suspended component' +
' please switch to "renderToPipeableStream" which supports Suspense on the server',
]);
} else {
await waitForAll([
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
]);
}
// This will have exceeded the suspended time so we should timeout.
jest.advanceTimersByTime(500);
// The boundary should longer be suspended for the middle content
// even though the inner boundary is still suspended.
expect(container.textContent).toBe('Hello');
const span = container.getElementsByTagName('span')[0];
expect(ref.current).toBe(span);
});
// @gate enableSuspenseList
it('shows inserted items in a SuspenseList before content is hydrated', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({children}) {
if (suspend) {
throw promise;
} else {
return children;
}
}
// These are hoisted to avoid them from rerendering.
const a = (
<Suspense fallback="Loading A">
<Child>
<span>A</span>
</Child>
</Suspense>
);
const b = (
<Suspense fallback="Loading B">
<Child>
<span ref={ref}>B</span>
</Child>
</Suspense>
);
function App({showMore}) {
return (
<SuspenseList revealOrder="forwards">
{a}
{b}
{showMore ? (
<Suspense fallback="Loading C">
<span>C</span>
</Suspense>
) : null}
</SuspenseList>
);
}
suspend = false;
const html = ReactDOMServer.renderToString(<App showMore={false} />);
const container = document.createElement('div');
container.innerHTML = html;
const spanB = container.getElementsByTagName('span')[1];
suspend = true;
const root = await act(() =>
ReactDOMClient.hydrateRoot(container, <App showMore={false} />),
);
// We're not hydrated yet.
expect(ref.current).toBe(null);
expect(container.textContent).toBe('AB');
// Add more rows before we've hydrated the first two.
await act(() => {
root.render(<App showMore={true} />);
});
// We're not hydrated yet.
expect(ref.current).toBe(null);
// Since the first two are already showing their final content
// we should be able to show the real content.
expect(container.textContent).toBe('ABC');
suspend = false;
await act(async () => {
await resolve();
});
expect(container.textContent).toBe('ABC');
// We've hydrated the same span.
expect(ref.current).toBe(spanB);
});
// @gate enableSuspenseList
it('shows is able to hydrate boundaries even if others in a list are pending', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({children}) {
if (suspend) {
throw promise;
} else {
return children;
}
}
const promise2 = new Promise(() => {});
function AlwaysSuspend() {
throw promise2;
}
// This is hoisted to avoid them from rerendering.
const a = (
<Suspense fallback="Loading A">
<Child>
<span ref={ref}>A</span>
</Child>
</Suspense>
);
function App({showMore}) {
return (
<SuspenseList revealOrder="together">
{a}
{showMore ? (
<Suspense fallback="Loading B">
<AlwaysSuspend />
</Suspense>
) : null}
</SuspenseList>
);
}
suspend = false;
const html = ReactDOMServer.renderToString(<App showMore={false} />);
const container = document.createElement('div');
container.innerHTML = html;
const spanA = container.getElementsByTagName('span')[0];
suspend = true;
const root = await act(() =>
ReactDOMClient.hydrateRoot(container, <App showMore={false} />),
);
// We're not hydrated yet.
expect(ref.current).toBe(null);
expect(container.textContent).toBe('A');
await act(async () => {
// Add another row before we've hydrated the first one.
root.render(<App showMore={true} />);
// At the same time, we resolve the blocking promise.
suspend = false;
await resolve();
});
// We should have been able to hydrate the first row.
expect(ref.current).toBe(spanA);
// Even though we're still slowing B.
expect(container.textContent).toBe('ALoading B');
});
// @gate enableSuspenseList
it('clears server boundaries when SuspenseList runs out of time hydrating', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child({children}) {
if (suspend) {
throw promise;
} else {
return children;
}
}
function Before() {
Scheduler.log('Before');
return null;
}
function After() {
Scheduler.log('After');
return null;
}
function FirstRow() {
return (
<>
<Before />
<Suspense fallback="Loading A">
<span>A</span>
</Suspense>
<After />
</>
);
}
function App() {
return (
<Suspense fallback={null}>
<SuspenseList revealOrder="forwards" tail="hidden">
<FirstRow />
<Suspense fallback="Loading B">
<Child>
<span ref={ref}>B</span>
</Child>
</Suspense>
</SuspenseList>
</Suspense>
);
}
suspend = false;
const html = ReactDOMServer.renderToString(<App />);
assertLog(['Before', 'After']);
const container = document.createElement('div');
container.innerHTML = html;
const b = container.getElementsByTagName('span')[1];
expect(b.textContent).toBe('B');
const root = ReactDOMClient.hydrateRoot(container, <App />);
// Increase hydration priority to higher than "offscreen".
root.unstable_scheduleHydration(b);
suspend = true;
await act(async () => {
if (gate(flags => flags.forceConcurrentByDefaultForTesting)) {
await waitFor(['Before']);
// This took a long time to render.
Scheduler.unstable_advanceTime(1000);
await waitFor(['After']);
} else {
await waitFor(['Before', 'After']);
}
// This will cause us to skip the second row completely.
});
// We haven't hydrated the second child but the placeholder is still in the list.
expect(ref.current).toBe(null);
expect(container.textContent).toBe('AB');
suspend = false;
await act(async () => {
// Resolve the boundary to be in its resolved final state.
await resolve();
});
expect(container.textContent).toBe('AB');
expect(ref.current).toBe(b);
});
// @gate enableSuspenseList
it('clears server boundaries when SuspenseList suspends last row hydrating', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
function Child({children}) {
if (suspend) {
throw promise;
} else {
return children;
}
}
function App() {
return (
<Suspense fallback={null}>
<SuspenseList revealOrder="forwards" tail="hidden">
<Suspense fallback="Loading A">
<span>A</span>
</Suspense>
<Suspense fallback="Loading B">
<Child>
<span>B</span>
</Child>
</Suspense>
</SuspenseList>
</Suspense>
);
}
suspend = true;
const html = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = html;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
suspend = true;
if (__DEV__) {
await waitForAll([
'The server did not finish this Suspense boundary: The server used' +
' "renderToString" which does not support Suspense. If you intended' +
' for this Suspense boundary to render the fallback content on the' +
' server consider throwing an Error somewhere within the Suspense boundary.' +
' If you intended to have the server wait for the suspended component' +
' please switch to "renderToPipeableStream" which supports Suspense on the server',
]);
} else {
await waitForAll([
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
]);
}
// We haven't hydrated the second child but the placeholder is still in the list.
expect(container.textContent).toBe('ALoading B');
suspend = false;
await act(async () => {
// Resolve the boundary to be in its resolved final state.
await resolve();
});
expect(container.textContent).toBe('AB');
});
it('can client render nested boundaries', async () => {
let suspend = false;
const promise = new Promise(() => {});
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
function App() {
return (
<div>
<Suspense
fallback={
<>
<Suspense fallback="Loading...">
<Child />
</Suspense>
<span>Inner Sibling</span>
</>
}>
<Child />
</Suspense>
<span ref={ref}>Sibling</span>
</div>
);
}
suspend = true;
const html = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = html + '<!--unrelated comment-->';
const span = container.getElementsByTagName('span')[1];
suspend = false;
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
if (__DEV__) {
await waitForAll([
'The server did not finish this Suspense boundary: The server used' +
' "renderToString" which does not support Suspense. If you intended' +
' for this Suspense boundary to render the fallback content on the' +
' server consider throwing an Error somewhere within the Suspense boundary.' +
' If you intended to have the server wait for the suspended component' +
' please switch to "renderToPipeableStream" which supports Suspense on the server',
]);
} else {
await waitForAll([
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
]);
}
jest.runAllTimers();
expect(ref.current).toBe(span);
expect(span.parentNode).not.toBe(null);
// It leaves non-React comments alone.
expect(container.lastChild.nodeType).toBe(8);
expect(container.lastChild.data).toBe('unrelated comment');
});
it('can hydrate TWO suspense boundaries', async () => {
const ref1 = React.createRef();
const ref2 = React.createRef();
function App() {
return (
<div>
<Suspense fallback="Loading 1...">
<span ref={ref1}>1</span>
</Suspense>
<Suspense fallback="Loading 2...">
<span ref={ref2}>2</span>
</Suspense>
</div>
);
}
// First we render the final HTML. With the streaming renderer
// this may have suspense points on the server but here we want
// to test the completed HTML. Don't suspend on the server.
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span1 = container.getElementsByTagName('span')[0];
const span2 = container.getElementsByTagName('span')[1];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
expect(ref1.current).toBe(span1);
expect(ref2.current).toBe(span2);
});
it('regenerates if it cannot hydrate before changes to props/context expire', async () => {
let suspend = false;
const promise = new Promise(resolvePromise => {});
const ref = React.createRef();
const ClassName = React.createContext(null);
function Child({text}) {
const className = React.useContext(ClassName);
if (suspend && className !== 'hi' && text !== 'Hi') {
// Never suspends on the newer data.
throw promise;
} else {
return (
<span ref={ref} className={className}>
{text}
</span>
);
}
}
function App({text, className}) {
return (
<div>
<Suspense fallback="Loading...">
<Child text={text} />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(
<ClassName.Provider value={'hello'}>
<App text="Hello" />
</ClassName.Provider>,
);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<ClassName.Provider value={'hello'}>
<App text="Hello" />
</ClassName.Provider>,
{
onRecoverableError(error) {
Scheduler.log(error.message);
},
},
);
await waitForAll([]);
expect(ref.current).toBe(null);
expect(span.textContent).toBe('Hello');
// Render an update, which will be higher or the same priority as pinging the hydration.
// The new update doesn't suspend.
// Since we're still suspended on the original data, we can't hydrate.
// This will force all expiration times to flush.
await act(() => {
root.render(
<ClassName.Provider value={'hi'}>
<App text="Hi" />
</ClassName.Provider>,
);
});
// This will now be a new span because we weren't able to hydrate before
const newSpan = container.getElementsByTagName('span')[0];
expect(newSpan).not.toBe(span);
// We should now have fully rendered with a ref on the new span.
expect(ref.current).toBe(newSpan);
expect(newSpan.textContent).toBe('Hi');
// If we ended up hydrating the existing content, we won't have properly
// patched up the tree, which might mean we haven't patched the className.
expect(newSpan.className).toBe('hi');
});
it('does not invoke an event on a hydrated node until it commits', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
function Sibling({text}) {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
let clicks = 0;
function Button() {
const [clicked, setClicked] = React.useState(false);
if (clicked) {
return null;
}
return (
<a
onClick={() => {
setClicked(true);
clicks++;
}}>
Click me
</a>
);
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Button />
<Sibling />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const a = container.getElementsByTagName('a')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
expect(container.textContent).toBe('Click meHello');
// We're now partially hydrated.
await act(() => {
a.click();
});
expect(clicks).toBe(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(clicks).toBe(0);
expect(container.textContent).toBe('Click meHello');
document.body.removeChild(container);
});
// @gate www
it('does not invoke an event on a hydrated event handle until it commits', async () => {
const setClick = ReactDOM.unstable_createEventHandle('click');
let suspend = false;
let isServerRendering = true;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
function Sibling({text}) {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
const onEvent = jest.fn();
function Button() {
const ref = React.useRef(null);
if (!isServerRendering) {
React.useLayoutEffect(() => {
return setClick(ref.current, onEvent);
});
}
return <a ref={ref}>Click me</a>;
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Button />
<Sibling />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const a = container.getElementsByTagName('a')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
isServerRendering = false;
ReactDOMClient.hydrateRoot(container, <App />);
// We'll do one click before hydrating.
a.click();
// This should be delayed.
expect(onEvent).toHaveBeenCalledTimes(0);
await waitForAll([]);
// We're now partially hydrated.
await act(() => {
a.click();
});
// We should not have invoked the event yet because we're not
// yet hydrated.
expect(onEvent).toHaveBeenCalledTimes(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(onEvent).toHaveBeenCalledTimes(0);
document.body.removeChild(container);
});
it('invokes discrete events on nested suspense boundaries in a root (legacy system)', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
let clicks = 0;
function Button() {
return (
<a
onClick={() => {
clicks++;
}}>
Click me
</a>
);
}
function Child() {
if (suspend) {
throw promise;
} else {
return (
<Suspense fallback="Loading...">
<Button />
</Suspense>
);
}
}
function App() {
return (
<Suspense fallback="Loading...">
<Child />
</Suspense>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const a = container.getElementsByTagName('a')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
ReactDOMClient.hydrateRoot(container, <App />);
// We'll do one click before hydrating.
await act(() => {
a.click();
});
// This should be delayed.
expect(clicks).toBe(0);
await waitForAll([]);
// We're now partially hydrated.
await act(() => {
a.click();
});
expect(clicks).toBe(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(clicks).toBe(0);
document.body.removeChild(container);
});
// @gate www
it('invokes discrete events on nested suspense boundaries in a root (createEventHandle)', async () => {
let suspend = false;
let isServerRendering = true;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const onEvent = jest.fn();
const setClick = ReactDOM.unstable_createEventHandle('click');
function Button() {
const ref = React.useRef(null);
if (!isServerRendering) {
React.useLayoutEffect(() => {
return setClick(ref.current, onEvent);
});
}
return <a ref={ref}>Click me</a>;
}
function Child() {
if (suspend) {
throw promise;
} else {
return (
<Suspense fallback="Loading...">
<Button />
</Suspense>
);
}
}
function App() {
return (
<Suspense fallback="Loading...">
<Child />
</Suspense>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const a = container.getElementsByTagName('a')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
isServerRendering = false;
ReactDOMClient.hydrateRoot(container, <App />);
// We'll do one click before hydrating.
a.click();
// This should be delayed.
expect(onEvent).toHaveBeenCalledTimes(0);
await waitForAll([]);
// We're now partially hydrated.
await act(() => {
a.click();
});
// We should not have invoked the event yet because we're not
// yet hydrated.
expect(onEvent).toHaveBeenCalledTimes(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(onEvent).toHaveBeenCalledTimes(0);
document.body.removeChild(container);
});
it('does not invoke the parent of dehydrated boundary event', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
let clicksOnParent = 0;
let clicksOnChild = 0;
function Child({text}) {
if (suspend) {
throw promise;
} else {
return (
<span
onClick={e => {
// The stopPropagation is showing an example why invoking
// the event on only a parent might not be correct.
e.stopPropagation();
clicksOnChild++;
}}>
Hello
</span>
);
}
}
function App() {
return (
<div onClick={() => clicksOnParent++}>
<Suspense fallback="Loading...">
<Child />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const span = container.getElementsByTagName('span')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
// We're now partially hydrated.
await act(() => {
span.click();
});
expect(clicksOnChild).toBe(0);
expect(clicksOnParent).toBe(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(clicksOnChild).toBe(0);
expect(clicksOnParent).toBe(0);
document.body.removeChild(container);
});
it('does not invoke an event on a parent tree when a subtree is dehydrated', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
let clicks = 0;
const childSlotRef = React.createRef();
function Parent() {
return <div onClick={() => clicks++} ref={childSlotRef} />;
}
function Child({text}) {
if (suspend) {
throw promise;
} else {
return <a>Click me</a>;
}
}
function App() {
// The root is a Suspense boundary.
return (
<Suspense fallback="Loading...">
<Child />
</Suspense>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const parentContainer = document.createElement('div');
const childContainer = document.createElement('div');
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(parentContainer);
// We're going to use a different root as a parent.
// This lets us detect whether an event goes through React's event system.
const parentRoot = ReactDOMClient.createRoot(parentContainer);
await act(() => parentRoot.render(<Parent />));
childSlotRef.current.appendChild(childContainer);
childContainer.innerHTML = finalHTML;
const a = childContainer.getElementsByTagName('a')[0];
suspend = true;
// Hydrate asynchronously.
await act(() => ReactDOMClient.hydrateRoot(childContainer, <App />));
// The Suspense boundary is not yet hydrated.
await act(() => {
a.click();
});
expect(clicks).toBe(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
expect(clicks).toBe(0);
document.body.removeChild(parentContainer);
});
it('blocks only on the last continuous event (legacy system)', async () => {
let suspend1 = false;
let resolve1;
const promise1 = new Promise(resolvePromise => (resolve1 = resolvePromise));
let suspend2 = false;
let resolve2;
const promise2 = new Promise(resolvePromise => (resolve2 = resolvePromise));
function First({text}) {
if (suspend1) {
throw promise1;
} else {
return 'Hello';
}
}
function Second({text}) {
if (suspend2) {
throw promise2;
} else {
return 'World';
}
}
const ops = [];
function App() {
return (
<div>
<Suspense fallback="Loading First...">
<span
onMouseEnter={() => ops.push('Mouse Enter First')}
onMouseLeave={() => ops.push('Mouse Leave First')}
/>
{/* We suspend after to test what happens when we eager
attach the listener. */}
<First />
</Suspense>
<Suspense fallback="Loading Second...">
<span
onMouseEnter={() => ops.push('Mouse Enter Second')}
onMouseLeave={() => ops.push('Mouse Leave Second')}>
<Second />
</span>
</Suspense>
</div>
);
}
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const appDiv = container.getElementsByTagName('div')[0];
const firstSpan = appDiv.getElementsByTagName('span')[0];
const secondSpan = appDiv.getElementsByTagName('span')[1];
expect(firstSpan.textContent).toBe('');
expect(secondSpan.textContent).toBe('World');
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend1 = true;
suspend2 = true;
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
dispatchMouseEvent(appDiv, null);
dispatchMouseEvent(firstSpan, appDiv);
dispatchMouseEvent(secondSpan, firstSpan);
// Neither target is yet hydrated.
expect(ops).toEqual([]);
// Resolving the second promise so that rendering can complete.
suspend2 = false;
resolve2();
await promise2;
await waitForAll([]);
// We've unblocked the current hover target so we should be
// able to replay it now.
expect(ops).toEqual(['Mouse Enter Second']);
// Resolving the first promise has no effect now.
suspend1 = false;
resolve1();
await promise1;
await waitForAll([]);
expect(ops).toEqual(['Mouse Enter Second']);
document.body.removeChild(container);
});
it('finishes normal pri work before continuing to hydrate a retry', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
const ref = React.createRef();
function Child() {
if (suspend) {
throw promise;
} else {
Scheduler.log('Child');
return 'Hello';
}
}
function Sibling() {
Scheduler.log('Sibling');
React.useLayoutEffect(() => {
Scheduler.log('Commit Sibling');
});
return 'World';
}
// Avoid rerendering the tree by hoisting it.
const tree = (
<Suspense fallback="Loading...">
<span ref={ref}>
<Child />
</span>
</Suspense>
);
function App({showSibling}) {
return (
<div>
{tree}
{showSibling ? <Sibling /> : null}
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
assertLog(['Child']);
const container = document.createElement('div');
container.innerHTML = finalHTML;
suspend = true;
const root = ReactDOMClient.hydrateRoot(
container,
<App showSibling={false} />,
);
await waitForAll([]);
expect(ref.current).toBe(null);
expect(container.textContent).toBe('Hello');
// Resolving the promise should continue hydration
suspend = false;
resolve();
await promise;
Scheduler.unstable_advanceTime(100);
// Before we have a chance to flush it, we'll also render an update.
root.render(<App showSibling={true} />);
// When we flush we expect the Normal pri render to take priority
// over hydration.
await waitFor(['Sibling', 'Commit Sibling']);
// We shouldn't have hydrated the child yet.
expect(ref.current).toBe(null);
// But we did have a chance to update the content.
expect(container.textContent).toBe('HelloWorld');
await waitForAll(['Child']);
// Now we're hydrated.
expect(ref.current).not.toBe(null);
});
it('regression test: does not overfire non-bubbling browser events', async () => {
let suspend = false;
let resolve;
const promise = new Promise(resolvePromise => (resolve = resolvePromise));
function Sibling({text}) {
if (suspend) {
throw promise;
} else {
return 'Hello';
}
}
let submits = 0;
function Form() {
const [submitted, setSubmitted] = React.useState(false);
if (submitted) {
return null;
}
return (
<form
onSubmit={() => {
setSubmitted(true);
submits++;
}}>
Click me
</form>
);
}
function App() {
return (
<div>
<Suspense fallback="Loading...">
<Form />
<Sibling />
</Suspense>
</div>
);
}
suspend = false;
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// We need this to be in the document since we'll dispatch events on it.
document.body.appendChild(container);
const form = container.getElementsByTagName('form')[0];
// On the client we don't have all data yet but we want to start
// hydrating anyway.
suspend = true;
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
expect(container.textContent).toBe('Click meHello');
// We're now partially hydrated.
await act(() => {
form.dispatchEvent(
new window.Event('submit', {
bubbles: true,
}),
);
});
expect(submits).toBe(0);
// Resolving the promise so that rendering can complete.
await act(async () => {
suspend = false;
resolve();
await promise;
});
// discrete event not replayed
expect(submits).toBe(0);
expect(container.textContent).toBe('Click meHello');
document.body.removeChild(container);
});
// This test fails, in both forks. Without a boundary, the deferred tree won't
// re-enter hydration mode. It doesn't come up in practice because there's
// always a parent Suspense boundary. But it's still a bug. Leaving for a
// follow up.
//
// @gate FIXME
it('hydrates a hidden subtree outside of a Suspense boundary', async () => {
const ref = React.createRef();
function App() {
return (
<LegacyHiddenDiv mode="hidden">
<span ref={ref}>Hidden child</span>
</LegacyHiddenDiv>
);
}
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
expect(span.innerHTML).toBe('Hidden child');
await act(() =>
ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.log('Log recoverable error: ' + error.message);
},
}),
);
expect(ref.current).toBe(span);
expect(span.innerHTML).toBe('Hidden child');
});
// @gate www
it('renders a hidden LegacyHidden component inside a Suspense boundary', async () => {
const ref = React.createRef();
function App() {
return (
<Suspense fallback="Loading...">
<LegacyHiddenDiv mode="hidden">
<span ref={ref}>Hidden child</span>
</LegacyHiddenDiv>
</Suspense>
);
}
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
expect(span.innerHTML).toBe('Hidden child');
await act(() => ReactDOMClient.hydrateRoot(container, <App />));
expect(ref.current).toBe(span);
expect(span.innerHTML).toBe('Hidden child');
});
// @gate www
it('renders a visible LegacyHidden component', async () => {
const ref = React.createRef();
function App() {
return (
<LegacyHiddenDiv mode="visible">
<span ref={ref}>Hidden child</span>
</LegacyHiddenDiv>
);
}
const finalHTML = ReactDOMServer.renderToString(<App />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const span = container.getElementsByTagName('span')[0];
await act(() => ReactDOMClient.hydrateRoot(container, <App />));
expect(ref.current).toBe(span);
expect(ref.current.innerHTML).toBe('Hidden child');
});
// @gate enableActivity
it('a visible Activity component acts like a fragment', async () => {
const ref = React.createRef();
function App() {
return (
<Activity mode="visible">
<span ref={ref}>Child</span>
</Activity>
);
}
const finalHTML = ReactDOMServer.renderToString(<App />);
assertLog([]);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// Visible Activity boundaries behave exactly like fragments: a
// pure indirection.
expect(container).toMatchInlineSnapshot(`
<div>
<span>
Child
</span>
</div>
`);
const span = container.getElementsByTagName('span')[0];
// The tree successfully hydrates
ReactDOMClient.hydrateRoot(container, <App />);
await waitForAll([]);
expect(ref.current).toBe(span);
});
// @gate enableActivity
it('a hidden Activity component is skipped over during server rendering', async () => {
const visibleRef = React.createRef();
function HiddenChild() {
Scheduler.log('HiddenChild');
return <span>Hidden</span>;
}
function App() {
Scheduler.log('App');
return (
<>
<span ref={visibleRef}>Visible</span>
<Activity mode="hidden">
<HiddenChild />
</Activity>
</>
);
}
// During server rendering, the Child component should not be evaluated,
// because it's inside a hidden tree.
const finalHTML = ReactDOMServer.renderToString(<App />);
assertLog(['App']);
const container = document.createElement('div');
container.innerHTML = finalHTML;
// The hidden child is not part of the server rendered HTML
expect(container).toMatchInlineSnapshot(`
<div>
<span>
Visible
</span>
</div>
`);
const visibleSpan = container.getElementsByTagName('span')[0];
// The visible span successfully hydrates
ReactDOMClient.hydrateRoot(container, <App />);
await waitForPaint(['App']);
expect(visibleRef.current).toBe(visibleSpan);
// Subsequently, the hidden child is prerendered on the client
await waitForPaint(['HiddenChild']);
expect(container).toMatchInlineSnapshot(`
<div>
<span>
Visible
</span>
<span
style="display: none;"
>
Hidden
</span>
</div>
`);
});
function itHydratesWithoutMismatch(msg, App) {
it('hydrates without mismatch ' + msg, async () => {
const container = document.createElement('div');
document.body.appendChild(container);
const finalHTML = ReactDOMServer.renderToString(<App />);
container.innerHTML = finalHTML;
await act(() => ReactDOMClient.hydrateRoot(container, <App />));
});
}
itHydratesWithoutMismatch('an empty string with neighbors', function App() {
return (
<div>
<div id="test">Test</div>
{'' && <div>Test</div>}
{'Test'}
</div>
);
});
itHydratesWithoutMismatch('an empty string', function App() {
return '';
});
itHydratesWithoutMismatch(
'an empty string simple in fragment',
function App() {
return (
<>
{''}
{'sup'}
</>
);
},
);
itHydratesWithoutMismatch(
'an empty string simple in suspense',
function App() {
return <Suspense>{'' && false}</Suspense>;
},
);
itHydratesWithoutMismatch('an empty string in class component', TestAppClass);
it('fallback to client render on hydration mismatch at root', async () => {
let suspend = true;
let resolve;
const promise = new Promise((res, rej) => {
resolve = () => {
suspend = false;
res();
};
});
function App({isClient}) {
return (
<>
<Suspense fallback={<div>Loading</div>}>
<ChildThatSuspends id={1} isClient={isClient} />
</Suspense>
{isClient ? <span>client</span> : <div>server</div>}
<Suspense fallback={<div>Loading</div>}>
<ChildThatSuspends id={2} isClient={isClient} />
</Suspense>
</>
);
}
function ChildThatSuspends({id, isClient}) {
if (isClient && suspend) {
throw promise;
}
return <div>{id}</div>;
}
const finalHTML = ReactDOMServer.renderToString(<App isClient={false} />);
const container = document.createElement('div');
document.body.appendChild(container);
container.innerHTML = finalHTML;
await expect(async () => {
await act(() => {
ReactDOMClient.hydrateRoot(container, <App isClient={true} />, {
onRecoverableError(error) {
Scheduler.log('Log recoverable error: ' + error.message);
},
});
});
}).toErrorDev(
[
'Warning: An error occurred during hydration. ' +
'The server HTML was replaced with client content in <div>.',
'Warning: Expected server HTML to contain a matching <span> in <div>.\n' +
' in span (at **)\n' +
' in App (at **)',
],
{withoutStack: 1},
);
assertLog([
'Log recoverable error: Hydration failed because the initial UI does not match what was rendered on the server.',
'Log recoverable error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.',
]);
// We show fallback state when mismatch happens at root
expect(container.innerHTML).toEqual(
'<div>Loading</div><span>client</span><div>Loading</div>',
);
await act(async () => {
resolve();
await promise;
});
expect(container.innerHTML).toEqual(
'<div>1</div><span>client</span><div>2</div>',
);
});
// @gate enableClientRenderFallbackOnTextMismatch
it("falls back to client rendering when there's a text mismatch (direct text child)", async () => {
function DirectTextChild({text}) {
return <div>{text}</div>;
}
const container = document.createElement('div');
container.innerHTML = ReactDOMServer.renderToString(
<DirectTextChild text="good" />,
);
await expect(async () => {
await act(() => {
ReactDOMClient.hydrateRoot(container, <DirectTextChild text="bad" />, {
onRecoverableError(error) {
Scheduler.log(error.message);
},
});
});
}).toErrorDev(
[
'Text content did not match. Server: "good" Client: "bad"',
'An error occurred during hydration. The server HTML was replaced with ' +
'client content in <div>.',
],
{withoutStack: 1},
);
assertLog([
'Text content does not match server-rendered HTML.',
'There was an error while hydrating. Because the error happened outside ' +
'of a Suspense boundary, the entire root will switch to client rendering.',
]);
});
// @gate enableClientRenderFallbackOnTextMismatch
it("falls back to client rendering when there's a text mismatch (text child with siblings)", async () => {
function Sibling() {
return 'Sibling';
}
function TextChildWithSibling({text}) {
return (
<div>
<Sibling />
{text}
</div>
);
}
const container2 = document.createElement('div');
container2.innerHTML = ReactDOMServer.renderToString(
<TextChildWithSibling text="good" />,
);
await expect(async () => {
await act(() => {
ReactDOMClient.hydrateRoot(
container2,
<TextChildWithSibling text="bad" />,
{
onRecoverableError(error) {
Scheduler.log(error.message);
},
},
);
});
}).toErrorDev(
[
'Text content did not match. Server: "good" Client: "bad"',
'An error occurred during hydration. The server HTML was replaced with ' +
'client content in <div>.',
],
{withoutStack: 1},
);
assertLog([
'Text content does not match server-rendered HTML.',
'There was an error while hydrating. Because the error happened outside ' +
'of a Suspense boundary, the entire root will switch to client rendering.',
]);
});
});
| 26.873149 | 175 | 0.589011 |
cybersecurity-penetration-testing | 'use strict';
module.exports = require('./server.node');
| 13.75 | 42 | 0.672414 |
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 {Dispatcher} from 'react-reconciler/src/ReactInternalTypes';
import type {
ReactContext,
StartTransitionOptions,
Thenable,
Usable,
ReactCustomFormAction,
Awaited,
} from 'shared/ReactTypes';
import type {ResumableState} from './ReactFizzConfig';
import type {Request, Task, KeyNode} from './ReactFizzServer';
import type {ThenableState} from './ReactFizzThenable';
import type {TransitionStatus} from './ReactFizzConfig';
import {readContext as readContextImpl} from './ReactFizzNewContext';
import {getTreeId} from './ReactFizzTreeContext';
import {createThenableState, trackUsedThenable} from './ReactFizzThenable';
import {makeId, NotPendingTransition} from './ReactFizzConfig';
import {createFastHash} from './ReactServerStreamConfig';
import {
enableCache,
enableUseEffectEventHook,
enableUseMemoCacheHook,
enableAsyncActions,
enableFormActions,
enableUseDeferredValueInitialArg,
} from 'shared/ReactFeatureFlags';
import is from 'shared/objectIs';
import {
REACT_SERVER_CONTEXT_TYPE,
REACT_CONTEXT_TYPE,
REACT_MEMO_CACHE_SENTINEL,
} from 'shared/ReactSymbols';
import {checkAttributeStringCoercion} from 'shared/CheckStringCoercion';
import {getFormState} from './ReactFizzServer';
type BasicStateAction<S> = (S => S) | S;
type Dispatch<A> = A => void;
type Update<A> = {
action: A,
next: Update<A> | null,
};
type UpdateQueue<A> = {
last: Update<A> | null,
dispatch: any,
};
type Hook = {
memoizedState: any,
queue: UpdateQueue<any> | null,
next: Hook | null,
};
let currentlyRenderingComponent: Object | null = null;
let currentlyRenderingTask: Task | null = null;
let currentlyRenderingRequest: Request | null = null;
let currentlyRenderingKeyPath: KeyNode | null = null;
let firstWorkInProgressHook: Hook | null = null;
let workInProgressHook: Hook | null = null;
// Whether the work-in-progress hook is a re-rendered hook
let isReRender: boolean = false;
// Whether an update was scheduled during the currently executing render pass.
let didScheduleRenderPhaseUpdate: boolean = false;
// Counts the number of useId hooks in this component
let localIdCounter: number = 0;
// Chunks that should be pushed to the stream once the component
// finishes rendering.
// Counts the number of useFormState calls in this component
let formStateCounter: number = 0;
// The index of the useFormState hook that matches the one passed in at the
// root during an MPA navigation, if any.
let formStateMatchingIndex: number = -1;
// Counts the number of use(thenable) calls in this component
let thenableIndexCounter: number = 0;
let thenableState: ThenableState | null = null;
// Lazily created map of render-phase updates
let renderPhaseUpdates: Map<UpdateQueue<any>, Update<any>> | null = null;
// Counter to prevent infinite loops.
let numberOfReRenders: number = 0;
const RE_RENDER_LIMIT = 25;
let isInHookUserCodeInDev = false;
// In DEV, this is the name of the currently executing primitive hook
let currentHookNameInDev: ?string;
function resolveCurrentlyRenderingComponent(): Object {
if (currentlyRenderingComponent === null) {
throw new Error(
'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
' one of the following reasons:\n' +
'1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
'2. You might be breaking the Rules of Hooks\n' +
'3. You might have more than one copy of React in the same app\n' +
'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.',
);
}
if (__DEV__) {
if (isInHookUserCodeInDev) {
console.error(
'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' +
'You can only call Hooks at the top level of your React function. ' +
'For more information, see ' +
'https://reactjs.org/link/rules-of-hooks',
);
}
}
return currentlyRenderingComponent;
}
function areHookInputsEqual(
nextDeps: Array<mixed>,
prevDeps: Array<mixed> | null,
) {
if (prevDeps === null) {
if (__DEV__) {
console.error(
'%s received a final argument during this render, but not during ' +
'the previous render. Even though the final argument is optional, ' +
'its type cannot change between renders.',
currentHookNameInDev,
);
}
return false;
}
if (__DEV__) {
// Don't bother comparing lengths in prod because these arrays should be
// passed inline.
if (nextDeps.length !== prevDeps.length) {
console.error(
'The final argument passed to %s changed size between renders. The ' +
'order and size of this array must remain constant.\n\n' +
'Previous: %s\n' +
'Incoming: %s',
currentHookNameInDev,
`[${nextDeps.join(', ')}]`,
`[${prevDeps.join(', ')}]`,
);
}
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
for (let i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
// $FlowFixMe[incompatible-use] found when upgrading Flow
if (is(nextDeps[i], prevDeps[i])) {
continue;
}
return false;
}
return true;
}
function createHook(): Hook {
if (numberOfReRenders > 0) {
throw new Error('Rendered more hooks than during the previous render');
}
return {
memoizedState: null,
queue: null,
next: null,
};
}
function createWorkInProgressHook(): Hook {
if (workInProgressHook === null) {
// This is the first hook in the list
if (firstWorkInProgressHook === null) {
isReRender = false;
firstWorkInProgressHook = workInProgressHook = createHook();
} else {
// There's already a work-in-progress. Reuse it.
isReRender = true;
workInProgressHook = firstWorkInProgressHook;
}
} else {
if (workInProgressHook.next === null) {
isReRender = false;
// Append to the end of the list
workInProgressHook = workInProgressHook.next = createHook();
} else {
// There's already a work-in-progress. Reuse it.
isReRender = true;
workInProgressHook = workInProgressHook.next;
}
}
return workInProgressHook;
}
export function prepareToUseHooks(
request: Request,
task: Task,
keyPath: KeyNode | null,
componentIdentity: Object,
prevThenableState: ThenableState | null,
): void {
currentlyRenderingComponent = componentIdentity;
currentlyRenderingTask = task;
currentlyRenderingRequest = request;
currentlyRenderingKeyPath = keyPath;
if (__DEV__) {
isInHookUserCodeInDev = false;
}
// The following should have already been reset
// didScheduleRenderPhaseUpdate = false;
// firstWorkInProgressHook = null;
// numberOfReRenders = 0;
// renderPhaseUpdates = null;
// workInProgressHook = null;
localIdCounter = 0;
formStateCounter = 0;
formStateMatchingIndex = -1;
thenableIndexCounter = 0;
thenableState = prevThenableState;
}
export function finishHooks(
Component: any,
props: any,
children: any,
refOrContext: any,
): any {
// This must be called after every function component to prevent hooks from
// being used in classes.
while (didScheduleRenderPhaseUpdate) {
// Updates were scheduled during the render phase. They are stored in
// the `renderPhaseUpdates` map. Call the component again, reusing the
// work-in-progress hooks and applying the additional updates on top. Keep
// restarting until no more updates are scheduled.
didScheduleRenderPhaseUpdate = false;
localIdCounter = 0;
formStateCounter = 0;
formStateMatchingIndex = -1;
thenableIndexCounter = 0;
numberOfReRenders += 1;
// Start over from the beginning of the list
workInProgressHook = null;
children = Component(props, refOrContext);
}
resetHooksState();
return children;
}
export function getThenableStateAfterSuspending(): null | ThenableState {
const state = thenableState;
thenableState = null;
return state;
}
export function checkDidRenderIdHook(): boolean {
// This should be called immediately after every finishHooks call.
// Conceptually, it's part of the return value of finishHooks; it's only a
// separate function to avoid using an array tuple.
const didRenderIdHook = localIdCounter !== 0;
return didRenderIdHook;
}
export function getFormStateCount(): number {
// This should be called immediately after every finishHooks call.
// Conceptually, it's part of the return value of finishHooks; it's only a
// separate function to avoid using an array tuple.
return formStateCounter;
}
export function getFormStateMatchingIndex(): number {
// This should be called immediately after every finishHooks call.
// Conceptually, it's part of the return value of finishHooks; it's only a
// separate function to avoid using an array tuple.
return formStateMatchingIndex;
}
// Reset the internal hooks state if an error occurs while rendering a component
export function resetHooksState(): void {
if (__DEV__) {
isInHookUserCodeInDev = false;
}
currentlyRenderingComponent = null;
currentlyRenderingTask = null;
currentlyRenderingRequest = null;
currentlyRenderingKeyPath = null;
didScheduleRenderPhaseUpdate = false;
firstWorkInProgressHook = null;
numberOfReRenders = 0;
renderPhaseUpdates = null;
workInProgressHook = null;
}
function readContext<T>(context: ReactContext<T>): T {
if (__DEV__) {
if (isInHookUserCodeInDev) {
console.error(
'Context can only be read while React is rendering. ' +
'In classes, you can read it in the render method or getDerivedStateFromProps. ' +
'In function components, you can read it directly in the function body, but not ' +
'inside Hooks like useReducer() or useMemo().',
);
}
}
return readContextImpl(context);
}
function useContext<T>(context: ReactContext<T>): T {
if (__DEV__) {
currentHookNameInDev = 'useContext';
}
resolveCurrentlyRenderingComponent();
return readContextImpl(context);
}
function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
// $FlowFixMe[incompatible-use]: Flow doesn't like mixed types
return typeof action === 'function' ? action(state) : action;
}
export function useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
if (__DEV__) {
currentHookNameInDev = 'useState';
}
return useReducer(
basicStateReducer,
// useReducer has a special case to support lazy useState initializers
(initialState: any),
);
}
export function useReducer<S, I, A>(
reducer: (S, A) => S,
initialArg: I,
init?: I => S,
): [S, Dispatch<A>] {
if (__DEV__) {
if (reducer !== basicStateReducer) {
currentHookNameInDev = 'useReducer';
}
}
currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
workInProgressHook = createWorkInProgressHook();
if (isReRender) {
// This is a re-render. Apply the new render phase updates to the previous
// current hook.
const queue: UpdateQueue<A> = (workInProgressHook.queue: any);
const dispatch: Dispatch<A> = (queue.dispatch: any);
if (renderPhaseUpdates !== null) {
// Render phase updates are stored in a map of queue -> linked list
const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
if (firstRenderPhaseUpdate !== undefined) {
// $FlowFixMe[incompatible-use] found when upgrading Flow
renderPhaseUpdates.delete(queue);
// $FlowFixMe[incompatible-use] found when upgrading Flow
let newState = workInProgressHook.memoizedState;
let update: Update<any> = firstRenderPhaseUpdate;
do {
// Process this render phase update. We don't have to check the
// priority because it will always be the same as the current
// render's.
const action = update.action;
if (__DEV__) {
isInHookUserCodeInDev = true;
}
newState = reducer(newState, action);
if (__DEV__) {
isInHookUserCodeInDev = false;
}
// $FlowFixMe[incompatible-type] we bail out when we get a null
update = update.next;
} while (update !== null);
// $FlowFixMe[incompatible-use] found when upgrading Flow
workInProgressHook.memoizedState = newState;
return [newState, dispatch];
}
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
return [workInProgressHook.memoizedState, dispatch];
} else {
if (__DEV__) {
isInHookUserCodeInDev = true;
}
let initialState;
if (reducer === basicStateReducer) {
// Special case for `useState`.
initialState =
typeof initialArg === 'function'
? ((initialArg: any): () => S)()
: ((initialArg: any): S);
} else {
initialState =
init !== undefined ? init(initialArg) : ((initialArg: any): S);
}
if (__DEV__) {
isInHookUserCodeInDev = false;
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
workInProgressHook.memoizedState = initialState;
// $FlowFixMe[incompatible-use] found when upgrading Flow
const queue: UpdateQueue<A> = (workInProgressHook.queue = {
last: null,
dispatch: null,
});
const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind(
null,
currentlyRenderingComponent,
queue,
): any));
// $FlowFixMe[incompatible-use] found when upgrading Flow
return [workInProgressHook.memoizedState, dispatch];
}
}
function useMemo<T>(nextCreate: () => T, deps: Array<mixed> | void | null): T {
currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
workInProgressHook = createWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
if (workInProgressHook !== null) {
const prevState = workInProgressHook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
const prevDeps = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
}
if (__DEV__) {
isInHookUserCodeInDev = true;
}
const nextValue = nextCreate();
if (__DEV__) {
isInHookUserCodeInDev = false;
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
workInProgressHook.memoizedState = [nextValue, nextDeps];
return nextValue;
}
function useRef<T>(initialValue: T): {current: T} {
currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
workInProgressHook = createWorkInProgressHook();
const previousRef = workInProgressHook.memoizedState;
if (previousRef === null) {
const ref = {current: initialValue};
if (__DEV__) {
Object.seal(ref);
}
// $FlowFixMe[incompatible-use] found when upgrading Flow
workInProgressHook.memoizedState = ref;
return ref;
} else {
return previousRef;
}
}
function dispatchAction<A>(
componentIdentity: Object,
queue: UpdateQueue<A>,
action: A,
): void {
if (numberOfReRenders >= RE_RENDER_LIMIT) {
throw new Error(
'Too many re-renders. React limits the number of renders to prevent ' +
'an infinite loop.',
);
}
if (componentIdentity === currentlyRenderingComponent) {
// This is a render phase update. Stash it in a lazily-created map of
// queue -> linked list of updates. After this render pass, we'll restart
// and apply the stashed updates on top of the work-in-progress hook.
didScheduleRenderPhaseUpdate = true;
const update: Update<A> = {
action,
next: null,
};
if (renderPhaseUpdates === null) {
renderPhaseUpdates = new Map();
}
const firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
if (firstRenderPhaseUpdate === undefined) {
// $FlowFixMe[incompatible-use] found when upgrading Flow
renderPhaseUpdates.set(queue, update);
} else {
// Append the update to the end of the list.
let lastRenderPhaseUpdate = firstRenderPhaseUpdate;
while (lastRenderPhaseUpdate.next !== null) {
lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
}
lastRenderPhaseUpdate.next = update;
}
} else {
// This means an update has happened after the function component has
// returned. On the server this is a no-op. In React Fiber, the update
// would be scheduled for a future render.
}
}
export function useCallback<T>(
callback: T,
deps: Array<mixed> | void | null,
): T {
return useMemo(() => callback, deps);
}
function throwOnUseEffectEventCall() {
throw new Error(
"A function wrapped in useEffectEvent can't be called during rendering.",
);
}
export function useEffectEvent<Args, Return, F: (...Array<Args>) => Return>(
callback: F,
): F {
// $FlowIgnore[incompatible-return]
return throwOnUseEffectEventCall;
}
function useSyncExternalStore<T>(
subscribe: (() => void) => () => void,
getSnapshot: () => T,
getServerSnapshot?: () => T,
): T {
if (getServerSnapshot === undefined) {
throw new Error(
'Missing getServerSnapshot, which is required for ' +
'server-rendered content. Will revert to client rendering.',
);
}
return getServerSnapshot();
}
function useDeferredValue<T>(value: T, initialValue?: T): T {
resolveCurrentlyRenderingComponent();
if (enableUseDeferredValueInitialArg) {
return initialValue !== undefined ? initialValue : value;
} else {
return value;
}
}
function unsupportedStartTransition() {
throw new Error('startTransition cannot be called during server rendering.');
}
function useTransition(): [
boolean,
(callback: () => void, options?: StartTransitionOptions) => void,
] {
resolveCurrentlyRenderingComponent();
return [false, unsupportedStartTransition];
}
function useHostTransitionStatus(): TransitionStatus {
resolveCurrentlyRenderingComponent();
return NotPendingTransition;
}
function unsupportedSetOptimisticState() {
throw new Error('Cannot update optimistic state while rendering.');
}
function useOptimistic<S, A>(
passthrough: S,
reducer: ?(S, A) => S,
): [S, (A) => void] {
resolveCurrentlyRenderingComponent();
return [passthrough, unsupportedSetOptimisticState];
}
function createPostbackFormStateKey(
permalink: string | void,
componentKeyPath: KeyNode | null,
hookIndex: number,
): string {
if (permalink !== undefined) {
// Don't bother to hash a permalink-based key since it's already short.
return 'p' + permalink;
} else {
// Append a node to the key path that represents the form state hook.
const keyPath: KeyNode = [componentKeyPath, null, hookIndex];
// Key paths are hashed to reduce the size. It does not need to be secure,
// and it's more important that it's fast than that it's completely
// collision-free.
const keyPathHash = createFastHash(JSON.stringify(keyPath));
return 'k' + keyPathHash;
}
}
function useFormState<S, P>(
action: (Awaited<S>, P) => S,
initialState: Awaited<S>,
permalink?: string,
): [Awaited<S>, (P) => void] {
resolveCurrentlyRenderingComponent();
// Count the number of useFormState hooks per component. We also use this to
// track the position of this useFormState hook relative to the other ones in
// this component, so we can generate a unique key for each one.
const formStateHookIndex = formStateCounter++;
const request: Request = (currentlyRenderingRequest: any);
// $FlowIgnore[prop-missing]
const formAction = action.$$FORM_ACTION;
if (typeof formAction === 'function') {
// This is a server action. These have additional features to enable
// MPA-style form submissions with progressive enhancement.
// TODO: If the same permalink is passed to multiple useFormStates, and
// they all have the same action signature, Fizz will pass the postback
// state to all of them. We should probably only pass it to the first one,
// and/or warn.
// The key is lazily generated and deduped so the that the keypath doesn't
// get JSON.stringify-ed unnecessarily, and at most once.
let nextPostbackStateKey = null;
// Determine the current form state. If we received state during an MPA form
// submission, then we will reuse that, if the action identity matches.
// Otherwise we'll use the initial state argument. We will emit a comment
// marker into the stream that indicates whether the state was reused.
let state = initialState;
const componentKeyPath = (currentlyRenderingKeyPath: any);
const postbackFormState = getFormState(request);
// $FlowIgnore[prop-missing]
const isSignatureEqual = action.$$IS_SIGNATURE_EQUAL;
if (postbackFormState !== null && typeof isSignatureEqual === 'function') {
const postbackKey = postbackFormState[1];
const postbackReferenceId = postbackFormState[2];
const postbackBoundArity = postbackFormState[3];
if (
isSignatureEqual.call(action, postbackReferenceId, postbackBoundArity)
) {
nextPostbackStateKey = createPostbackFormStateKey(
permalink,
componentKeyPath,
formStateHookIndex,
);
if (postbackKey === nextPostbackStateKey) {
// This was a match
formStateMatchingIndex = formStateHookIndex;
// Reuse the state that was submitted by the form.
state = postbackFormState[0];
}
}
}
// Bind the state to the first argument of the action.
const boundAction = action.bind(null, state);
// Wrap the action so the return value is void.
const dispatch = (payload: P): void => {
boundAction(payload);
};
// $FlowIgnore[prop-missing]
if (typeof boundAction.$$FORM_ACTION === 'function') {
// $FlowIgnore[prop-missing]
dispatch.$$FORM_ACTION = (prefix: string) => {
const metadata: ReactCustomFormAction =
boundAction.$$FORM_ACTION(prefix);
// Override the action URL
if (permalink !== undefined) {
if (__DEV__) {
checkAttributeStringCoercion(permalink, 'target');
}
permalink += '';
metadata.action = permalink;
}
const formData = metadata.data;
if (formData) {
if (nextPostbackStateKey === null) {
nextPostbackStateKey = createPostbackFormStateKey(
permalink,
componentKeyPath,
formStateHookIndex,
);
}
formData.append('$ACTION_KEY', nextPostbackStateKey);
}
return metadata;
};
}
return [state, dispatch];
} else {
// This is not a server action, so the implementation is much simpler.
// Bind the state to the first argument of the action.
const boundAction = action.bind(null, initialState);
// Wrap the action so the return value is void.
const dispatch = (payload: P): void => {
boundAction(payload);
};
return [initialState, dispatch];
}
}
function useId(): string {
const task: Task = (currentlyRenderingTask: any);
const treeId = getTreeId(task.treeContext);
const resumableState = currentResumableState;
if (resumableState === null) {
throw new Error(
'Invalid hook call. Hooks can only be called inside of the body of a function component.',
);
}
const localId = localIdCounter++;
return makeId(resumableState, treeId, localId);
}
function use<T>(usable: Usable<T>): T {
if (usable !== null && typeof usable === 'object') {
// $FlowFixMe[method-unbinding]
if (typeof usable.then === 'function') {
// This is a thenable.
const thenable: Thenable<T> = (usable: any);
return unwrapThenable(thenable);
} else if (
usable.$$typeof === REACT_CONTEXT_TYPE ||
usable.$$typeof === REACT_SERVER_CONTEXT_TYPE
) {
const context: ReactContext<T> = (usable: any);
return readContext(context);
}
}
// eslint-disable-next-line react-internal/safe-string-coercion
throw new Error('An unsupported type was passed to use(): ' + String(usable));
}
export function unwrapThenable<T>(thenable: Thenable<T>): T {
const index = thenableIndexCounter;
thenableIndexCounter += 1;
if (thenableState === null) {
thenableState = createThenableState();
}
return trackUsedThenable(thenableState, thenable, index);
}
function unsupportedRefresh() {
throw new Error('Cache cannot be refreshed during server rendering.');
}
function useCacheRefresh(): <T>(?() => T, ?T) => void {
return unsupportedRefresh;
}
function useMemoCache(size: number): Array<any> {
const data = new Array<any>(size);
for (let i = 0; i < size; i++) {
data[i] = REACT_MEMO_CACHE_SENTINEL;
}
return data;
}
function noop(): void {}
export const HooksDispatcher: Dispatcher = {
readContext,
use,
useContext,
useMemo,
useReducer,
useRef,
useState,
useInsertionEffect: noop,
useLayoutEffect: noop,
useCallback,
// useImperativeHandle is not run in the server environment
useImperativeHandle: noop,
// Effects are not run in the server environment.
useEffect: noop,
// Debugging effect
useDebugValue: noop,
useDeferredValue,
useTransition,
useId,
// Subscriptions are not setup in a server environment.
useSyncExternalStore,
};
if (enableCache) {
HooksDispatcher.useCacheRefresh = useCacheRefresh;
}
if (enableUseEffectEventHook) {
HooksDispatcher.useEffectEvent = useEffectEvent;
}
if (enableUseMemoCacheHook) {
HooksDispatcher.useMemoCache = useMemoCache;
}
if (enableFormActions && enableAsyncActions) {
HooksDispatcher.useHostTransitionStatus = useHostTransitionStatus;
}
if (enableAsyncActions) {
HooksDispatcher.useOptimistic = useOptimistic;
HooksDispatcher.useFormState = useFormState;
}
export let currentResumableState: null | ResumableState = (null: any);
export function setCurrentResumableState(
resumableState: null | ResumableState,
): void {
currentResumableState = resumableState;
}
| 30.588024 | 119 | 0.681289 |
Python-Penetration-Testing-Cookbook | "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,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFTQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7OztBQUVBIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5fSBmcm9tICcuL0NvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5JztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhDdXN0b21Ib29rfSBmcm9tICcuL0NvbXBvbmVudFdpdGhDdXN0b21Ib29rJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzJztcbmV4cG9ydCB7Q29tcG9uZW50IGFzIENvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZX0gZnJvbSAnLi9Db21wb25lbnRXaXRoTXVsdGlwbGVIb29rc1BlckxpbmUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgQ29tcG9uZW50V2l0aE5lc3RlZEhvb2tzfSBmcm9tICcuL0NvbXBvbmVudFdpdGhOZXN0ZWRIb29rcyc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBDb250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTH0gZnJvbSAnLi9Db250YWluaW5nU3RyaW5nU291cmNlTWFwcGluZ1VSTCc7XG5leHBvcnQge0NvbXBvbmVudCBhcyBFeGFtcGxlfSBmcm9tICcuL0V4YW1wbGUnO1xuZXhwb3J0IHtDb21wb25lbnQgYXMgSW5saW5lUmVxdWlyZX0gZnJvbSAnLi9JbmxpbmVSZXF1aXJlJztcbmltcG9ydCAqIGFzIFRvRG9MaXN0IGZyb20gJy4vVG9Eb0xpc3QnO1xuZXhwb3J0IHtUb0RvTGlzdH07XG5leHBvcnQge2RlZmF1bHQgYXMgdXNlVGhlbWV9IGZyb20gJy4vdXNlVGhlbWUnO1xuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiJdLCJtYXBwaW5ncyI6IkNBQUQifV1dfX1dfQ== | 56.213483 | 1,828 | 0.822039 |
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,
ReactRenderer,
} from 'react-devtools-shared/src/backend/types';
import {hasAssignedBackend} from 'react-devtools-shared/src/backend/utils';
import {COMPACT_VERSION_NAME} from 'react-devtools-extensions/src/utils';
let welcomeHasInitialized = false;
function welcome(event: $FlowFixMe) {
if (
event.source !== window ||
event.data.source !== 'react-devtools-content-script'
) {
return;
}
// In some circumstances, this method is called more than once for a single welcome message.
// The exact circumstances of this are unclear, though it seems related to 3rd party event batching code.
//
// Regardless, call this method multiple times can cause DevTools to add duplicate elements to the Store
// (and throw an error) or worse yet, choke up entirely and freeze the browser.
//
// The simplest solution is to ignore the duplicate events.
// To be clear, this SHOULD NOT BE NECESSARY, since we remove the event handler below.
//
// See https://github.com/facebook/react/issues/24162
if (welcomeHasInitialized) {
console.warn(
'React DevTools detected duplicate welcome "message" events from the content script.',
);
return;
}
welcomeHasInitialized = true;
window.removeEventListener('message', welcome);
setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__);
}
window.addEventListener('message', welcome);
function setup(hook: ?DevToolsHook) {
// this should not happen, but Chrome can be weird sometimes
if (hook == null) {
return;
}
// register renderers that have already injected themselves.
hook.renderers.forEach(renderer => {
registerRenderer(renderer, hook);
});
// Activate and remove from required all present backends, registered within the hook
hook.backends.forEach((_, backendVersion) => {
requiredBackends.delete(backendVersion);
activateBackend(backendVersion, hook);
});
updateRequiredBackends();
// register renderers that inject themselves later.
hook.sub('renderer', ({renderer}) => {
registerRenderer(renderer, hook);
updateRequiredBackends();
});
// listen for backend installations.
hook.sub('devtools-backend-installed', version => {
activateBackend(version, hook);
updateRequiredBackends();
});
}
const requiredBackends = new Set<string>();
function registerRenderer(renderer: ReactRenderer, hook: DevToolsHook) {
let version = renderer.reconcilerVersion || renderer.version;
if (!hasAssignedBackend(version)) {
version = COMPACT_VERSION_NAME;
}
// Check if required backend is already activated, no need to require again
if (!hook.backends.has(version)) {
requiredBackends.add(version);
}
}
function activateBackend(version: string, hook: DevToolsHook) {
const backend = hook.backends.get(version);
if (!backend) {
throw new Error(`Could not find backend for version "${version}"`);
}
const {Agent, Bridge, initBackend, setupNativeStyleEditor} = backend;
const bridge = new Bridge({
listen(fn) {
const listener = (event: $FlowFixMe) => {
if (
event.source !== window ||
!event.data ||
event.data.source !== 'react-devtools-content-script' ||
!event.data.payload
) {
return;
}
fn(event.data.payload);
};
window.addEventListener('message', listener);
return () => {
window.removeEventListener('message', listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
window.postMessage(
{
source: 'react-devtools-bridge',
payload: {event, payload},
},
'*',
transferable,
);
},
});
const agent = new Agent(bridge);
agent.addListener('shutdown', () => {
// If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down,
// and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here.
hook.emit('shutdown');
});
initBackend(hook, agent, window);
// Setup React Native style editor if a renderer like react-native-web has injected it.
if (typeof setupNativeStyleEditor === 'function' && hook.resolveRNStyle) {
setupNativeStyleEditor(
bridge,
agent,
hook.resolveRNStyle,
hook.nativeStyleEditorValidAttributes,
);
}
// Let the frontend know that the backend has attached listeners and is ready for messages.
// This covers the case of syncing saved values after reloading/navigating while DevTools remain open.
bridge.send('extensionBackendInitialized');
// this backend is activated
requiredBackends.delete(version);
}
// tell the service worker which versions of backends are needed for the current page
function updateRequiredBackends() {
if (requiredBackends.size === 0) {
return;
}
window.postMessage(
{
source: 'react-devtools-backend-manager',
payload: {
type: 'require-backends',
versions: Array.from(requiredBackends),
},
},
'*',
);
}
| 28.4 | 110 | 0.675865 |
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 {useContext} from 'react';
import {StoreContext} from '../context';
import {
ComponentFilterElementType,
ElementTypeSuspense,
} from 'react-devtools-shared/src/frontend/types';
export default function CannotSuspendWarningMessage(): React.Node {
const store = useContext(StoreContext);
const areSuspenseElementsHidden = !!store.componentFilters.find(
filter =>
filter.type === ComponentFilterElementType &&
filter.value === ElementTypeSuspense &&
filter.isEnabled,
);
// Has the user filtered out Suspense nodes from the tree?
// If so, the selected element might actually be in a Suspense tree after all.
if (areSuspenseElementsHidden) {
return (
<div>
Suspended state cannot be toggled while Suspense components are hidden.
Disable the filter and try again.
</div>
);
} else {
return (
<div>
The selected element is not within a Suspense container. Suspending it
would cause an error.
</div>
);
}
}
| 27 | 80 | 0.683876 |
Effective-Python-Penetration-Testing | export const CHANGE_LOG_URL =
'https://github.com/facebook/react/blob/main/packages/react-devtools/CHANGELOG.md';
export const UNSUPPORTED_VERSION_URL =
'https://reactjs.org/blog/2019/08/15/new-react-devtools.html#how-do-i-get-the-old-version-back';
export const REACT_DEVTOOLS_WORKPLACE_URL =
'https://fburl.com/react-devtools-workplace-group';
import type {
Theme,
DisplayDensity,
} from './devtools/views/Settings/SettingsContext';
export const THEME_STYLES: {[style: Theme | DisplayDensity]: any, ...} = {
light: {
'--color-attribute-name': '#ef6632',
'--color-attribute-name-not-editable': '#23272f',
'--color-attribute-name-inverted': 'rgba(255, 255, 255, 0.7)',
'--color-attribute-value': '#1a1aa6',
'--color-attribute-value-inverted': '#ffffff',
'--color-attribute-editable-value': '#1a1aa6',
'--color-background': '#ffffff',
'--color-background-hover': 'rgba(0, 136, 250, 0.1)',
'--color-background-inactive': '#e5e5e5',
'--color-background-invalid': '#fff0f0',
'--color-background-selected': '#0088fa',
'--color-button-background': '#ffffff',
'--color-button-background-focus': '#ededed',
'--color-button': '#5f6673',
'--color-button-disabled': '#cfd1d5',
'--color-button-active': '#0088fa',
'--color-button-focus': '#23272f',
'--color-button-hover': '#23272f',
'--color-border': '#eeeeee',
'--color-commit-did-not-render-fill': '#cfd1d5',
'--color-commit-did-not-render-fill-text': '#000000',
'--color-commit-did-not-render-pattern': '#cfd1d5',
'--color-commit-did-not-render-pattern-text': '#333333',
'--color-commit-gradient-0': '#37afa9',
'--color-commit-gradient-1': '#63b19e',
'--color-commit-gradient-2': '#80b393',
'--color-commit-gradient-3': '#97b488',
'--color-commit-gradient-4': '#abb67d',
'--color-commit-gradient-5': '#beb771',
'--color-commit-gradient-6': '#cfb965',
'--color-commit-gradient-7': '#dfba57',
'--color-commit-gradient-8': '#efbb49',
'--color-commit-gradient-9': '#febc38',
'--color-commit-gradient-text': '#000000',
'--color-component-name': '#6a51b2',
'--color-component-name-inverted': '#ffffff',
'--color-component-badge-background': 'rgba(0, 0, 0, 0.1)',
'--color-component-badge-background-inverted': 'rgba(255, 255, 255, 0.25)',
'--color-component-badge-count': '#777d88',
'--color-component-badge-count-inverted': 'rgba(255, 255, 255, 0.7)',
'--color-console-error-badge-text': '#ffffff',
'--color-console-error-background': '#fff0f0',
'--color-console-error-border': '#ffd6d6',
'--color-console-error-icon': '#eb3941',
'--color-console-error-text': '#fe2e31',
'--color-console-warning-badge-text': '#000000',
'--color-console-warning-background': '#fffbe5',
'--color-console-warning-border': '#fff5c1',
'--color-console-warning-icon': '#f4bd00',
'--color-console-warning-text': '#64460c',
'--color-context-background': 'rgba(0,0,0,.9)',
'--color-context-background-hover': 'rgba(255, 255, 255, 0.1)',
'--color-context-background-selected': '#178fb9',
'--color-context-border': '#3d424a',
'--color-context-text': '#ffffff',
'--color-context-text-selected': '#ffffff',
'--color-dim': '#777d88',
'--color-dimmer': '#cfd1d5',
'--color-dimmest': '#eff0f1',
'--color-error-background': 'hsl(0, 100%, 97%)',
'--color-error-border': 'hsl(0, 100%, 92%)',
'--color-error-text': '#ff0000',
'--color-expand-collapse-toggle': '#777d88',
'--color-forget-badge': '#2683E2',
'--color-link': '#0000ff',
'--color-modal-background': 'rgba(255, 255, 255, 0.75)',
'--color-bridge-version-npm-background': '#eff0f1',
'--color-bridge-version-npm-text': '#000000',
'--color-bridge-version-number': '#0088fa',
'--color-primitive-hook-badge-background': '#e5e5e5',
'--color-primitive-hook-badge-text': '#5f6673',
'--color-record-active': '#fc3a4b',
'--color-record-hover': '#3578e5',
'--color-record-inactive': '#0088fa',
'--color-resize-bar': '#eeeeee',
'--color-resize-bar-active': '#dcdcdc',
'--color-resize-bar-border': '#d1d1d1',
'--color-resize-bar-dot': '#333333',
'--color-timeline-internal-module': '#d1d1d1',
'--color-timeline-internal-module-hover': '#c9c9c9',
'--color-timeline-internal-module-text': '#444',
'--color-timeline-native-event': '#ccc',
'--color-timeline-native-event-hover': '#aaa',
'--color-timeline-network-primary': '#fcf3dc',
'--color-timeline-network-primary-hover': '#f0e7d1',
'--color-timeline-network-secondary': '#efc457',
'--color-timeline-network-secondary-hover': '#e3ba52',
'--color-timeline-priority-background': '#f6f6f6',
'--color-timeline-priority-border': '#eeeeee',
'--color-timeline-user-timing': '#c9cacd',
'--color-timeline-user-timing-hover': '#93959a',
'--color-timeline-react-idle': '#d3e5f6',
'--color-timeline-react-idle-hover': '#c3d9ef',
'--color-timeline-react-render': '#9fc3f3',
'--color-timeline-react-render-hover': '#83afe9',
'--color-timeline-react-render-text': '#11365e',
'--color-timeline-react-commit': '#c88ff0',
'--color-timeline-react-commit-hover': '#b281d6',
'--color-timeline-react-commit-text': '#3e2c4a',
'--color-timeline-react-layout-effects': '#b281d6',
'--color-timeline-react-layout-effects-hover': '#9d71bd',
'--color-timeline-react-layout-effects-text': '#3e2c4a',
'--color-timeline-react-passive-effects': '#b281d6',
'--color-timeline-react-passive-effects-hover': '#9d71bd',
'--color-timeline-react-passive-effects-text': '#3e2c4a',
'--color-timeline-react-schedule': '#9fc3f3',
'--color-timeline-react-schedule-hover': '#2683E2',
'--color-timeline-react-suspense-rejected': '#f1cc14',
'--color-timeline-react-suspense-rejected-hover': '#ffdf37',
'--color-timeline-react-suspense-resolved': '#a6e59f',
'--color-timeline-react-suspense-resolved-hover': '#89d281',
'--color-timeline-react-suspense-unresolved': '#c9cacd',
'--color-timeline-react-suspense-unresolved-hover': '#93959a',
'--color-timeline-thrown-error': '#ee1638',
'--color-timeline-thrown-error-hover': '#da1030',
'--color-timeline-text-color': '#000000',
'--color-timeline-text-dim-color': '#ccc',
'--color-timeline-react-work-border': '#eeeeee',
'--color-search-match': 'yellow',
'--color-search-match-current': '#f7923b',
'--color-selected-tree-highlight-active': 'rgba(0, 136, 250, 0.1)',
'--color-selected-tree-highlight-inactive': 'rgba(0, 0, 0, 0.05)',
'--color-scroll-caret': 'rgba(150, 150, 150, 0.5)',
'--color-tab-selected-border': '#0088fa',
'--color-text': '#000000',
'--color-text-invalid': '#ff0000',
'--color-text-selected': '#ffffff',
'--color-toggle-background-invalid': '#fc3a4b',
'--color-toggle-background-on': '#0088fa',
'--color-toggle-background-off': '#cfd1d5',
'--color-toggle-text': '#ffffff',
'--color-warning-background': '#fb3655',
'--color-warning-background-hover': '#f82042',
'--color-warning-text-color': '#ffffff',
'--color-warning-text-color-inverted': '#fd4d69',
// The styles below should be kept in sync with 'root.css'
// They are repeated there because they're used by e.g. tooltips or context menus
// which get rendered outside of the DOM subtree (where normal theme/styles are written).
'--color-scroll-thumb': '#c2c2c2',
'--color-scroll-track': '#fafafa',
'--color-tooltip-background': 'rgba(0, 0, 0, 0.9)',
'--color-tooltip-text': '#ffffff',
},
dark: {
'--color-attribute-name': '#9d87d2',
'--color-attribute-name-not-editable': '#ededed',
'--color-attribute-name-inverted': '#282828',
'--color-attribute-value': '#cedae0',
'--color-attribute-value-inverted': '#ffffff',
'--color-attribute-editable-value': 'yellow',
'--color-background': '#282c34',
'--color-background-hover': 'rgba(255, 255, 255, 0.1)',
'--color-background-inactive': '#3d424a',
'--color-background-invalid': '#5c0000',
'--color-background-selected': '#178fb9',
'--color-button-background': '#282c34',
'--color-button-background-focus': '#3d424a',
'--color-button': '#afb3b9',
'--color-button-active': '#61dafb',
'--color-button-disabled': '#4f5766',
'--color-button-focus': '#a2e9fc',
'--color-button-hover': '#ededed',
'--color-border': '#3d424a',
'--color-commit-did-not-render-fill': '#777d88',
'--color-commit-did-not-render-fill-text': '#000000',
'--color-commit-did-not-render-pattern': '#666c77',
'--color-commit-did-not-render-pattern-text': '#ffffff',
'--color-commit-gradient-0': '#37afa9',
'--color-commit-gradient-1': '#63b19e',
'--color-commit-gradient-2': '#80b393',
'--color-commit-gradient-3': '#97b488',
'--color-commit-gradient-4': '#abb67d',
'--color-commit-gradient-5': '#beb771',
'--color-commit-gradient-6': '#cfb965',
'--color-commit-gradient-7': '#dfba57',
'--color-commit-gradient-8': '#efbb49',
'--color-commit-gradient-9': '#febc38',
'--color-commit-gradient-text': '#000000',
'--color-component-name': '#61dafb',
'--color-component-name-inverted': '#282828',
'--color-component-badge-background': 'rgba(255, 255, 255, 0.25)',
'--color-component-badge-background-inverted': 'rgba(0, 0, 0, 0.25)',
'--color-component-badge-count': '#8f949d',
'--color-component-badge-count-inverted': 'rgba(255, 255, 255, 0.7)',
'--color-console-error-badge-text': '#000000',
'--color-console-error-background': '#290000',
'--color-console-error-border': '#5c0000',
'--color-console-error-icon': '#eb3941',
'--color-console-error-text': '#fc7f7f',
'--color-console-warning-badge-text': '#000000',
'--color-console-warning-background': '#332b00',
'--color-console-warning-border': '#665500',
'--color-console-warning-icon': '#f4bd00',
'--color-console-warning-text': '#f5f2ed',
'--color-context-background': 'rgba(255,255,255,.95)',
'--color-context-background-hover': 'rgba(0, 136, 250, 0.1)',
'--color-context-background-selected': '#0088fa',
'--color-context-border': '#eeeeee',
'--color-context-text': '#000000',
'--color-context-text-selected': '#ffffff',
'--color-dim': '#8f949d',
'--color-dimmer': '#777d88',
'--color-dimmest': '#4f5766',
'--color-error-background': '#200',
'--color-error-border': '#900',
'--color-error-text': '#f55',
'--color-expand-collapse-toggle': '#8f949d',
'--color-forget-badge': '#2683E2',
'--color-link': '#61dafb',
'--color-modal-background': 'rgba(0, 0, 0, 0.75)',
'--color-bridge-version-npm-background': 'rgba(0, 0, 0, 0.25)',
'--color-bridge-version-npm-text': '#ffffff',
'--color-bridge-version-number': 'yellow',
'--color-primitive-hook-badge-background': 'rgba(0, 0, 0, 0.25)',
'--color-primitive-hook-badge-text': 'rgba(255, 255, 255, 0.7)',
'--color-record-active': '#fc3a4b',
'--color-record-hover': '#a2e9fc',
'--color-record-inactive': '#61dafb',
'--color-resize-bar': '#282c34',
'--color-resize-bar-active': '#31363f',
'--color-resize-bar-border': '#3d424a',
'--color-resize-bar-dot': '#cfd1d5',
'--color-timeline-internal-module': '#303542',
'--color-timeline-internal-module-hover': '#363b4a',
'--color-timeline-internal-module-text': '#7f8899',
'--color-timeline-native-event': '#b2b2b2',
'--color-timeline-native-event-hover': '#949494',
'--color-timeline-network-primary': '#fcf3dc',
'--color-timeline-network-primary-hover': '#e3dbc5',
'--color-timeline-network-secondary': '#efc457',
'--color-timeline-network-secondary-hover': '#d6af4d',
'--color-timeline-priority-background': '#1d2129',
'--color-timeline-priority-border': '#282c34',
'--color-timeline-user-timing': '#c9cacd',
'--color-timeline-user-timing-hover': '#93959a',
'--color-timeline-react-idle': '#3d485b',
'--color-timeline-react-idle-hover': '#465269',
'--color-timeline-react-render': '#2683E2',
'--color-timeline-react-render-hover': '#1a76d4',
'--color-timeline-react-render-text': '#11365e',
'--color-timeline-react-commit': '#731fad',
'--color-timeline-react-commit-hover': '#611b94',
'--color-timeline-react-commit-text': '#e5c1ff',
'--color-timeline-react-layout-effects': '#611b94',
'--color-timeline-react-layout-effects-hover': '#51167a',
'--color-timeline-react-layout-effects-text': '#e5c1ff',
'--color-timeline-react-passive-effects': '#611b94',
'--color-timeline-react-passive-effects-hover': '#51167a',
'--color-timeline-react-passive-effects-text': '#e5c1ff',
'--color-timeline-react-schedule': '#2683E2',
'--color-timeline-react-schedule-hover': '#1a76d4',
'--color-timeline-react-suspense-rejected': '#f1cc14',
'--color-timeline-react-suspense-rejected-hover': '#e4c00f',
'--color-timeline-react-suspense-resolved': '#a6e59f',
'--color-timeline-react-suspense-resolved-hover': '#89d281',
'--color-timeline-react-suspense-unresolved': '#c9cacd',
'--color-timeline-react-suspense-unresolved-hover': '#93959a',
'--color-timeline-thrown-error': '#fb3655',
'--color-timeline-thrown-error-hover': '#f82042',
'--color-timeline-text-color': '#282c34',
'--color-timeline-text-dim-color': '#555b66',
'--color-timeline-react-work-border': '#3d424a',
'--color-search-match': 'yellow',
'--color-search-match-current': '#f7923b',
'--color-selected-tree-highlight-active': 'rgba(23, 143, 185, 0.15)',
'--color-selected-tree-highlight-inactive': 'rgba(255, 255, 255, 0.05)',
'--color-scroll-caret': '#4f5766',
'--color-shadow': 'rgba(0, 0, 0, 0.5)',
'--color-tab-selected-border': '#178fb9',
'--color-text': '#ffffff',
'--color-text-invalid': '#ff8080',
'--color-text-selected': '#ffffff',
'--color-toggle-background-invalid': '#fc3a4b',
'--color-toggle-background-on': '#178fb9',
'--color-toggle-background-off': '#777d88',
'--color-toggle-text': '#ffffff',
'--color-warning-background': '#ee1638',
'--color-warning-background-hover': '#da1030',
'--color-warning-text-color': '#ffffff',
'--color-warning-text-color-inverted': '#ee1638',
// The styles below should be kept in sync with 'root.css'
// They are repeated there because they're used by e.g. tooltips or context menus
// which get rendered outside of the DOM subtree (where normal theme/styles are written).
'--color-scroll-thumb': '#afb3b9',
'--color-scroll-track': '#313640',
'--color-tooltip-background': 'rgba(255, 255, 255, 0.95)',
'--color-tooltip-text': '#000000',
},
compact: {
'--font-size-monospace-small': '9px',
'--font-size-monospace-normal': '11px',
'--font-size-monospace-large': '15px',
'--font-size-sans-small': '10px',
'--font-size-sans-normal': '12px',
'--font-size-sans-large': '14px',
'--line-height-data': '18px',
},
comfortable: {
'--font-size-monospace-small': '10px',
'--font-size-monospace-normal': '13px',
'--font-size-monospace-large': '17px',
'--font-size-sans-small': '12px',
'--font-size-sans-normal': '14px',
'--font-size-sans-large': '16px',
'--line-height-data': '22px',
},
};
// HACK
//
// Sometimes the inline target is rendered before root styles are applied,
// which would result in e.g. NaN itemSize being passed to react-window list.
const COMFORTABLE_LINE_HEIGHT: number = parseInt(
THEME_STYLES.comfortable['--line-height-data'],
10,
);
const COMPACT_LINE_HEIGHT: number = parseInt(
THEME_STYLES.compact['--line-height-data'],
10,
);
export {COMFORTABLE_LINE_HEIGHT, COMPACT_LINE_HEIGHT};
| 45.475073 | 98 | 0.626806 |
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
*/
// 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.
export const REACT_ELEMENT_TYPE: symbol = Symbol.for('react.element');
export const REACT_PORTAL_TYPE: symbol = Symbol.for('react.portal');
export const REACT_FRAGMENT_TYPE: symbol = Symbol.for('react.fragment');
export const REACT_STRICT_MODE_TYPE: symbol = Symbol.for('react.strict_mode');
export const REACT_PROFILER_TYPE: symbol = Symbol.for('react.profiler');
export const REACT_PROVIDER_TYPE: symbol = Symbol.for('react.provider');
export const REACT_CONTEXT_TYPE: symbol = Symbol.for('react.context');
export const REACT_SERVER_CONTEXT_TYPE: symbol = Symbol.for(
'react.server_context',
);
export const REACT_FORWARD_REF_TYPE: symbol = Symbol.for('react.forward_ref');
export const REACT_SUSPENSE_TYPE: symbol = Symbol.for('react.suspense');
export const REACT_SUSPENSE_LIST_TYPE: symbol = Symbol.for(
'react.suspense_list',
);
export const REACT_MEMO_TYPE: symbol = Symbol.for('react.memo');
export const REACT_LAZY_TYPE: symbol = Symbol.for('react.lazy');
export const REACT_SCOPE_TYPE: symbol = Symbol.for('react.scope');
export const REACT_DEBUG_TRACING_MODE_TYPE: symbol = Symbol.for(
'react.debug_trace_mode',
);
export const REACT_OFFSCREEN_TYPE: symbol = Symbol.for('react.offscreen');
export const REACT_LEGACY_HIDDEN_TYPE: symbol = Symbol.for(
'react.legacy_hidden',
);
export const REACT_CACHE_TYPE: symbol = Symbol.for('react.cache');
export const REACT_TRACING_MARKER_TYPE: symbol = Symbol.for(
'react.tracing_marker',
);
export const REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED: symbol = Symbol.for(
'react.default_value',
);
export const REACT_MEMO_CACHE_SENTINEL: symbol = Symbol.for(
'react.memo_cache_sentinel',
);
export const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone');
const MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
const FAUX_ITERATOR_SYMBOL = '@@iterator';
export function getIteratorFn(maybeIterable: ?any): ?() => ?Iterator<any> {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
const maybeIterator =
(MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||
maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
| 36.898551 | 82 | 0.734124 |
Hands-On-AWS-Penetration-Testing-with-Kali-Linux | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import styles from './Icon.css';
export type IconType =
| 'arrow'
| 'bug'
| 'code'
| 'components'
| 'copy'
| 'error'
| 'facebook'
| 'flame-chart'
| 'profiler'
| 'ranked-chart'
| 'timeline'
| 'search'
| 'settings'
| 'store-as-global-variable'
| 'strict-mode-non-compliant'
| 'warning';
type Props = {
className?: string,
title?: string,
type: IconType,
};
export default function Icon({
className = '',
title = '',
type,
}: Props): React.Node {
let pathData = null;
switch (type) {
case 'arrow':
pathData = PATH_ARROW;
break;
case 'bug':
pathData = PATH_BUG;
break;
case 'code':
pathData = PATH_CODE;
break;
case 'components':
pathData = PATH_COMPONENTS;
break;
case 'copy':
pathData = PATH_COPY;
break;
case 'error':
pathData = PATH_ERROR;
break;
case 'facebook':
pathData = PATH_FACEBOOK;
break;
case 'flame-chart':
pathData = PATH_FLAME_CHART;
break;
case 'profiler':
pathData = PATH_PROFILER;
break;
case 'ranked-chart':
pathData = PATH_RANKED_CHART;
break;
case 'timeline':
pathData = PATH_SCHEDULING_PROFILER;
break;
case 'search':
pathData = PATH_SEARCH;
break;
case 'settings':
pathData = PATH_SETTINGS;
break;
case 'store-as-global-variable':
pathData = PATH_STORE_AS_GLOBAL_VARIABLE;
break;
case 'strict-mode-non-compliant':
pathData = PATH_STRICT_MODE_NON_COMPLIANT;
break;
case 'warning':
pathData = PATH_WARNING;
break;
default:
console.warn(`Unsupported type "${type}" specified for Icon`);
break;
}
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={`${styles.Icon} ${className}`}
width="24"
height="24"
viewBox="0 0 24 24">
{title && <title>{title}</title>}
<path d="M0 0h24v24H0z" fill="none" />
<path fill="currentColor" d={pathData} />
</svg>
);
}
const PATH_ARROW = 'M8 5v14l11-7z';
const PATH_BUG = `
M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49
0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09
1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21
5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z
`;
const PATH_CODE = `
M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z
`;
const PATH_COMPONENTS =
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z';
const PATH_COPY = `
M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3a2 2 0 0 0 2 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9a2 2 0 0 0-2
2v10a2 2 0 0 0 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z
`;
const PATH_ERROR = `M16.971 0h-9.942l-7.029 7.029v9.941l7.029 7.03h9.941l7.03-7.029v-9.942l-7.029-7.029zm-1.402 16.945l-3.554-3.521-3.518 3.568-1.418-1.418 3.507-3.566-3.586-3.472 1.418-1.417 3.581 3.458 3.539-3.583 1.431 1.431-3.535 3.568 3.566 3.522-1.431 1.43z`;
const PATH_FACEBOOK = `
M22,12c0-5.52-4.48-10-10-10S2,6.48,2,12c0,4.84,3.44,8.87,8,9.8V15H8v-3h2V9.5C10,7.57,11.57,6,13.5,6H16v3h-2 c-0.55,0-1,0.45-1,1v2h3v3h-3v6.95C18.05,21.45,22,17.19,22,12z
`;
const PATH_FLAME_CHART = `
M10.0650893,21.5040462 C7.14020814,20.6850349 5,18.0558698 5,14.9390244 C5,14.017627
5,9.81707317 7.83333333,7.37804878 C7.83333333,7.37804878 7.58333333,11.199187 10,
10.6300813 C11.125,10.326087 13.0062497,7.63043487 8.91666667,2.5 C14.1666667,3.06910569
19,9.32926829 19,14.9390244 C19,18.0558698 16.8597919,20.6850349 13.9349107,21.5040462
C14.454014,21.0118505 14.7765152,20.3233394 14.7765152,19.5613412 C14.7765152,17.2826087
12,15.0875871 12,15.0875871 C12,15.0875871 9.22348485,17.2826087 9.22348485,19.5613412
C9.22348485,20.3233394 9.54598603,21.0118505 10.0650893,21.5040462 Z M12.0833333,20.6514763
C11.3814715,20.6514763 10.8125,20.1226027 10.8125,19.4702042 C10.8125,18.6069669
12.0833333,16.9347829 12.0833333,16.9347829 C12.0833333,16.9347829 13.3541667,18.6069669
13.3541667,19.4702042 C13.3541667,20.1226027 12.7851952,20.6514763 12.0833333,20.6514763 Z
`;
const PATH_PROFILER = 'M5 9.2h3V19H5zM10.6 5h2.8v14h-2.8zm5.6 8H19v6h-2.8z';
const PATH_SCHEDULING_PROFILER = `
M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0
16H5V9h14v10zm0-12H5V5h14v2zM7 11h5v5H7z
`;
const PATH_SEARCH = `
M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91
16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99
5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z
`;
const PATH_RANKED_CHART = 'M3 5h18v3H3zM3 10.5h13v3H3zM3 16h8v3H3z';
const PATH_SETTINGS = `
M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49
1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38
2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11
1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4
1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49
1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5
3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z
`;
const PATH_STORE_AS_GLOBAL_VARIABLE = `
M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41
3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04
1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6
8h-4v-2h4v2zm0-4h-4v-2h4v2z
`;
const PATH_STRICT_MODE_NON_COMPLIANT = `
M4.47 21h15.06c1.54 0 2.5-1.67 1.73-3L13.73 4.99c-.77-1.33-2.69-1.33-3.46 0L2.74 18c-.77 1.33.19 3 1.73 3zM12
14c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .45 1 1v2c0 .55-.45 1-1 1zm1 4h-2v-2h2v2z
`;
const PATH_WARNING = `M12 1l-12 22h24l-12-22zm-1 8h2v7h-2v-7zm1 11.25c-.69 0-1.25-.56-1.25-1.25s.56-1.25 1.25-1.25 1.25.56 1.25 1.25-.56 1.25-1.25 1.25z`;
| 34.671958 | 265 | 0.643525 |
null | 'use strict';
jest.mock('shared/ReactFeatureFlags', () => {
jest.mock(
'ReactFeatureFlags',
() => jest.requireActual('shared/forks/ReactFeatureFlags.www-dynamic'),
{virtual: true}
);
const actual = jest.requireActual('shared/forks/ReactFeatureFlags.www');
// This flag is only used by tests, it should never be set elsewhere.
actual.forceConcurrentByDefaultForTesting = !__VARIANT__;
return actual;
});
jest.mock('scheduler/src/SchedulerFeatureFlags', () => {
const schedulerSrcPath = process.cwd() + '/packages/scheduler';
jest.mock(
'SchedulerFeatureFlags',
() =>
jest.requireActual(
schedulerSrcPath + '/src/forks/SchedulerFeatureFlags.www-dynamic'
),
{virtual: true}
);
const actual = jest.requireActual(
schedulerSrcPath + '/src/forks/SchedulerFeatureFlags.www'
);
// These flags are not a dynamic on www, but we still want to run
// tests in both versions.
actual.enableIsInputPending = __VARIANT__;
actual.enableIsInputPendingContinuous = __VARIANT__;
actual.enableProfiling = __VARIANT__;
actual.enableSchedulerDebugging = __VARIANT__;
return actual;
});
global.__WWW__ = true;
| 27.047619 | 75 | 0.68904 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Instance} from 'react-reconciler/src/ReactFiberConfig';
import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
import type {
Family,
RefreshUpdate,
ScheduleRefresh,
ScheduleRoot,
FindHostInstancesForRefresh,
SetRefreshHandler,
} from 'react-reconciler/src/ReactFiberHotReloading';
import type {ReactNodeList} from 'shared/ReactTypes';
import {REACT_MEMO_TYPE, REACT_FORWARD_REF_TYPE} from 'shared/ReactSymbols';
type Signature = {
ownKey: string,
forceReset: boolean,
fullKey: string | null, // Contains keys of nested Hooks. Computed lazily.
getCustomHooks: () => Array<Function>,
};
type RendererHelpers = {
findHostInstancesForRefresh: FindHostInstancesForRefresh,
scheduleRefresh: ScheduleRefresh,
scheduleRoot: ScheduleRoot,
setRefreshHandler: SetRefreshHandler,
};
if (!__DEV__) {
throw new Error(
'React Refresh runtime should not be included in the production bundle.',
);
}
// In old environments, we'll leak previous types after every edit.
const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
// We never remove these associations.
// It's OK to reference families, but use WeakMap/Set for types.
const allFamiliesByID: Map<string, Family> = new Map();
const allFamiliesByType: WeakMap<any, Family> | Map<any, Family> =
new PossiblyWeakMap();
const allSignaturesByType: WeakMap<any, Signature> | Map<any, Signature> =
new PossiblyWeakMap();
// This WeakMap is read by React, so we only put families
// that have actually been edited here. This keeps checks fast.
const updatedFamiliesByType: WeakMap<any, Family> | Map<any, Family> =
new PossiblyWeakMap();
// This is cleared on every performReactRefresh() call.
// It is an array of [Family, NextType] tuples.
let pendingUpdates: Array<[Family, any]> = [];
// This is injected by the renderer via DevTools global hook.
const helpersByRendererID: Map<number, RendererHelpers> = new Map();
const helpersByRoot: Map<FiberRoot, RendererHelpers> = new Map();
// We keep track of mounted roots so we can schedule updates.
const mountedRoots: Set<FiberRoot> = new Set();
// If a root captures an error, we remember it so we can retry on edit.
const failedRoots: Set<FiberRoot> = new Set();
// In environments that support WeakMap, we also remember the last element for every root.
// It needs to be weak because we do this even for roots that failed to mount.
// If there is no WeakMap, we won't attempt to do retrying.
const rootElements: WeakMap<any, ReactNodeList> | null =
typeof WeakMap === 'function' ? new WeakMap() : null;
let isPerformingRefresh = false;
function computeFullKey(signature: Signature): string {
if (signature.fullKey !== null) {
return signature.fullKey;
}
let fullKey: string = signature.ownKey;
let hooks;
try {
hooks = signature.getCustomHooks();
} catch (err) {
// This can happen in an edge case, e.g. if expression like Foo.useSomething
// depends on Foo which is lazily initialized during rendering.
// In that case just assume we'll have to remount.
signature.forceReset = true;
signature.fullKey = fullKey;
return fullKey;
}
for (let i = 0; i < hooks.length; i++) {
const hook = hooks[i];
if (typeof hook !== 'function') {
// Something's wrong. Assume we need to remount.
signature.forceReset = true;
signature.fullKey = fullKey;
return fullKey;
}
const nestedHookSignature = allSignaturesByType.get(hook);
if (nestedHookSignature === undefined) {
// No signature means Hook wasn't in the source code, e.g. in a library.
// We'll skip it because we can assume it won't change during this session.
continue;
}
const nestedHookKey = computeFullKey(nestedHookSignature);
if (nestedHookSignature.forceReset) {
signature.forceReset = true;
}
fullKey += '\n---\n' + nestedHookKey;
}
signature.fullKey = fullKey;
return fullKey;
}
function haveEqualSignatures(prevType: any, nextType: any) {
const prevSignature = allSignaturesByType.get(prevType);
const nextSignature = allSignaturesByType.get(nextType);
if (prevSignature === undefined && nextSignature === undefined) {
return true;
}
if (prevSignature === undefined || nextSignature === undefined) {
return false;
}
if (computeFullKey(prevSignature) !== computeFullKey(nextSignature)) {
return false;
}
if (nextSignature.forceReset) {
return false;
}
return true;
}
function isReactClass(type: any) {
return type.prototype && type.prototype.isReactComponent;
}
function canPreserveStateBetween(prevType: any, nextType: any) {
if (isReactClass(prevType) || isReactClass(nextType)) {
return false;
}
if (haveEqualSignatures(prevType, nextType)) {
return true;
}
return false;
}
function resolveFamily(type: any) {
// Only check updated types to keep lookups fast.
return updatedFamiliesByType.get(type);
}
// If we didn't care about IE11, we could use new Map/Set(iterable).
function cloneMap<K, V>(map: Map<K, V>): Map<K, V> {
const clone = new Map<K, V>();
map.forEach((value, key) => {
clone.set(key, value);
});
return clone;
}
function cloneSet<T>(set: Set<T>): Set<T> {
const clone = new Set<T>();
set.forEach(value => {
clone.add(value);
});
return clone;
}
// This is a safety mechanism to protect against rogue getters and Proxies.
function getProperty(object: any, property: string) {
try {
return object[property];
} catch (err) {
// Intentionally ignore.
return undefined;
}
}
export function performReactRefresh(): RefreshUpdate | null {
if (!__DEV__) {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
if (pendingUpdates.length === 0) {
return null;
}
if (isPerformingRefresh) {
return null;
}
isPerformingRefresh = true;
try {
const staleFamilies = new Set<Family>();
const updatedFamilies = new Set<Family>();
const updates = pendingUpdates;
pendingUpdates = [];
updates.forEach(([family, nextType]) => {
// Now that we got a real edit, we can create associations
// that will be read by the React reconciler.
const prevType = family.current;
updatedFamiliesByType.set(prevType, family);
updatedFamiliesByType.set(nextType, family);
family.current = nextType;
// Determine whether this should be a re-render or a re-mount.
if (canPreserveStateBetween(prevType, nextType)) {
updatedFamilies.add(family);
} else {
staleFamilies.add(family);
}
});
// TODO: rename these fields to something more meaningful.
const update: RefreshUpdate = {
updatedFamilies, // Families that will re-render preserving state
staleFamilies, // Families that will be remounted
};
helpersByRendererID.forEach(helpers => {
// Even if there are no roots, set the handler on first update.
// This ensures that if *new* roots are mounted, they'll use the resolve handler.
helpers.setRefreshHandler(resolveFamily);
});
let didError = false;
let firstError = null;
// We snapshot maps and sets that are mutated during commits.
// If we don't do this, there is a risk they will be mutated while
// we iterate over them. For example, trying to recover a failed root
// may cause another root to be added to the failed list -- an infinite loop.
const failedRootsSnapshot = cloneSet(failedRoots);
const mountedRootsSnapshot = cloneSet(mountedRoots);
const helpersByRootSnapshot = cloneMap(helpersByRoot);
failedRootsSnapshot.forEach(root => {
const helpers = helpersByRootSnapshot.get(root);
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
);
}
if (!failedRoots.has(root)) {
// No longer failed.
}
if (rootElements === null) {
return;
}
if (!rootElements.has(root)) {
return;
}
const element = rootElements.get(root);
try {
helpers.scheduleRoot(root, element);
} catch (err) {
if (!didError) {
didError = true;
firstError = err;
}
// Keep trying other roots.
}
});
mountedRootsSnapshot.forEach(root => {
const helpers = helpersByRootSnapshot.get(root);
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
);
}
if (!mountedRoots.has(root)) {
// No longer mounted.
}
try {
helpers.scheduleRefresh(root, update);
} catch (err) {
if (!didError) {
didError = true;
firstError = err;
}
// Keep trying other roots.
}
});
if (didError) {
throw firstError;
}
return update;
} finally {
isPerformingRefresh = false;
}
}
export function register(type: any, id: string): void {
if (__DEV__) {
if (type === null) {
return;
}
if (typeof type !== 'function' && typeof type !== 'object') {
return;
}
// This can happen in an edge case, e.g. if we register
// return value of a HOC but it returns a cached component.
// Ignore anything but the first registration for each type.
if (allFamiliesByType.has(type)) {
return;
}
// Create family or remember to update it.
// None of this bookkeeping affects reconciliation
// until the first performReactRefresh() call above.
let family = allFamiliesByID.get(id);
if (family === undefined) {
family = {current: type};
allFamiliesByID.set(id, family);
} else {
pendingUpdates.push([family, type]);
}
allFamiliesByType.set(type, family);
// Visit inner types because we might not have registered them.
if (typeof type === 'object' && type !== null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
register(type.render, id + '$render');
break;
case REACT_MEMO_TYPE:
register(type.type, id + '$type');
break;
}
}
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function setSignature(
type: any,
key: string,
forceReset?: boolean = false,
getCustomHooks?: () => Array<Function>,
): void {
if (__DEV__) {
if (!allSignaturesByType.has(type)) {
allSignaturesByType.set(type, {
forceReset,
ownKey: key,
fullKey: null,
getCustomHooks: getCustomHooks || (() => []),
});
}
// Visit inner types because we might not have signed them.
if (typeof type === 'object' && type !== null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
setSignature(type.render, key, forceReset, getCustomHooks);
break;
case REACT_MEMO_TYPE:
setSignature(type.type, key, forceReset, getCustomHooks);
break;
}
}
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
// This is lazily called during first render for a type.
// It captures Hook list at that time so inline requires don't break comparisons.
export function collectCustomHooksForSignature(type: any) {
if (__DEV__) {
const signature = allSignaturesByType.get(type);
if (signature !== undefined) {
computeFullKey(signature);
}
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function getFamilyByID(id: string): Family | void {
if (__DEV__) {
return allFamiliesByID.get(id);
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function getFamilyByType(type: any): Family | void {
if (__DEV__) {
return allFamiliesByType.get(type);
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function findAffectedHostInstances(
families: Array<Family>,
): Set<Instance> {
if (__DEV__) {
const affectedInstances = new Set<Instance>();
mountedRoots.forEach(root => {
const helpers = helpersByRoot.get(root);
if (helpers === undefined) {
throw new Error(
'Could not find helpers for a root. This is a bug in React Refresh.',
);
}
const instancesForRoot = helpers.findHostInstancesForRefresh(
root,
families,
);
instancesForRoot.forEach(inst => {
affectedInstances.add(inst);
});
});
return affectedInstances;
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function injectIntoGlobalHook(globalObject: any): void {
if (__DEV__) {
// For React Native, the global hook will be set up by require('react-devtools-core').
// That code will run before us. So we need to monkeypatch functions on existing hook.
// For React Web, the global hook will be set up by the extension.
// This will also run before us.
let hook = globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__;
if (hook === undefined) {
// However, if there is no DevTools extension, we'll need to set up the global hook ourselves.
// Note that in this case it's important that renderer code runs *after* this method call.
// Otherwise, the renderer will think that there is no global hook, and won't do the injection.
let nextID = 0;
globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
renderers: new Map(),
supportsFiber: true,
inject: injected => nextID++,
onScheduleFiberRoot: (
id: number,
root: FiberRoot,
children: ReactNodeList,
) => {},
onCommitFiberRoot: (
id: number,
root: FiberRoot,
maybePriorityLevel: mixed,
didError: boolean,
) => {},
onCommitFiberUnmount() {},
};
}
if (hook.isDisabled) {
// This isn't a real property on the hook, but it can be set to opt out
// of DevTools integration and associated warnings and logs.
// Using console['warn'] to evade Babel and ESLint
console['warn'](
'Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). ' +
'Fast Refresh is not compatible with this shim and will be disabled.',
);
return;
}
// Here, we just want to get a reference to scheduleRefresh.
const oldInject = hook.inject;
hook.inject = function (this: mixed, injected) {
const id = oldInject.apply(this, arguments);
if (
typeof injected.scheduleRefresh === 'function' &&
typeof injected.setRefreshHandler === 'function'
) {
// This version supports React Refresh.
helpersByRendererID.set(id, ((injected: any): RendererHelpers));
}
return id;
};
// Do the same for any already injected roots.
// This is useful if ReactDOM has already been initialized.
// https://github.com/facebook/react/issues/17626
hook.renderers.forEach((injected, id) => {
if (
typeof injected.scheduleRefresh === 'function' &&
typeof injected.setRefreshHandler === 'function'
) {
// This version supports React Refresh.
helpersByRendererID.set(id, ((injected: any): RendererHelpers));
}
});
// We also want to track currently mounted roots.
const oldOnCommitFiberRoot = hook.onCommitFiberRoot;
const oldOnScheduleFiberRoot = hook.onScheduleFiberRoot || (() => {});
hook.onScheduleFiberRoot = function (
this: mixed,
id: number,
root: FiberRoot,
children: ReactNodeList,
) {
if (!isPerformingRefresh) {
// If it was intentionally scheduled, don't attempt to restore.
// This includes intentionally scheduled unmounts.
failedRoots.delete(root);
if (rootElements !== null) {
rootElements.set(root, children);
}
}
return oldOnScheduleFiberRoot.apply(this, arguments);
};
hook.onCommitFiberRoot = function (
this: mixed,
id: number,
root: FiberRoot,
maybePriorityLevel: mixed,
didError: boolean,
) {
const helpers = helpersByRendererID.get(id);
if (helpers !== undefined) {
helpersByRoot.set(root, helpers);
const current = root.current;
const alternate = current.alternate;
// We need to determine whether this root has just (un)mounted.
// This logic is copy-pasted from similar logic in the DevTools backend.
// If this breaks with some refactoring, you'll want to update DevTools too.
if (alternate !== null) {
const wasMounted =
alternate.memoizedState != null &&
alternate.memoizedState.element != null &&
mountedRoots.has(root);
const isMounted =
current.memoizedState != null &&
current.memoizedState.element != null;
if (!wasMounted && isMounted) {
// Mount a new root.
mountedRoots.add(root);
failedRoots.delete(root);
} else if (wasMounted && isMounted) {
// Update an existing root.
// This doesn't affect our mounted root Set.
} else if (wasMounted && !isMounted) {
// Unmount an existing root.
mountedRoots.delete(root);
if (didError) {
// We'll remount it on future edits.
failedRoots.add(root);
} else {
helpersByRoot.delete(root);
}
} else if (!wasMounted && !isMounted) {
if (didError) {
// We'll remount it on future edits.
failedRoots.add(root);
}
}
} else {
// Mount a new root.
mountedRoots.add(root);
}
}
// Always call the decorated DevTools hook.
return oldOnCommitFiberRoot.apply(this, arguments);
};
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function hasUnrecoverableErrors(): boolean {
// TODO: delete this after removing dependency in RN.
return false;
}
// Exposed for testing.
export function _getMountedRootCount(): number {
if (__DEV__) {
return mountedRoots.size;
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
// This is a wrapper over more primitive functions for setting signature.
// Signatures let us decide whether the Hook order has changed on refresh.
//
// This function is intended to be used as a transform target, e.g.:
// var _s = createSignatureFunctionForTransform()
//
// function Hello() {
// const [foo, setFoo] = useState(0);
// const value = useCustomHook();
// _s(); /* Call without arguments triggers collecting the custom Hook list.
// * This doesn't happen during the module evaluation because we
// * don't want to change the module order with inline requires.
// * Next calls are noops. */
// return <h1>Hi</h1>;
// }
//
// /* Call with arguments attaches the signature to the type: */
// _s(
// Hello,
// 'useState{[foo, setFoo]}(0)',
// () => [useCustomHook], /* Lazy to avoid triggering inline requires */
// );
export function createSignatureFunctionForTransform(): <T>(
type: T,
key: string,
forceReset?: boolean,
getCustomHooks?: () => Array<Function>,
) => T | void {
if (__DEV__) {
let savedType: mixed;
let hasCustomHooks: boolean;
let didCollectHooks = false;
return function <T>(
type: T,
key: string,
forceReset?: boolean,
getCustomHooks?: () => Array<Function>,
): T | void {
if (typeof key === 'string') {
// We're in the initial phase that associates signatures
// with the functions. Note this may be called multiple times
// in HOC chains like _s(hoc1(_s(hoc2(_s(actualFunction))))).
if (!savedType) {
// We're in the innermost call, so this is the actual type.
savedType = type;
hasCustomHooks = typeof getCustomHooks === 'function';
}
// Set the signature for all types (even wrappers!) in case
// they have no signatures of their own. This is to prevent
// problems like https://github.com/facebook/react/issues/20417.
if (
type != null &&
(typeof type === 'function' || typeof type === 'object')
) {
setSignature(type, key, forceReset, getCustomHooks);
}
return type;
} else {
// We're in the _s() call without arguments, which means
// this is the time to collect custom Hook signatures.
// Only do this once. This path is hot and runs *inside* every render!
if (!didCollectHooks && hasCustomHooks) {
didCollectHooks = true;
collectCustomHooksForSignature(savedType);
}
}
};
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
export function isLikelyComponentType(type: any): boolean {
if (__DEV__) {
switch (typeof type) {
case 'function': {
// First, deal with classes.
if (type.prototype != null) {
if (type.prototype.isReactComponent) {
// React class.
return true;
}
const ownNames = Object.getOwnPropertyNames(type.prototype);
if (ownNames.length > 1 || ownNames[0] !== 'constructor') {
// This looks like a class.
return false;
}
// eslint-disable-next-line no-proto
if (type.prototype.__proto__ !== Object.prototype) {
// It has a superclass.
return false;
}
// Pass through.
// This looks like a regular function with empty prototype.
}
// For plain functions and arrows, use name as a heuristic.
const name = type.name || type.displayName;
return typeof name === 'string' && /^[A-Z]/.test(name);
}
case 'object': {
if (type != null) {
switch (getProperty(type, '$$typeof')) {
case REACT_FORWARD_REF_TYPE:
case REACT_MEMO_TYPE:
// Definitely React components.
return true;
default:
return false;
}
}
return false;
}
default: {
return false;
}
}
} else {
throw new Error(
'Unexpected call to React Refresh in a production environment.',
);
}
}
| 30.435135 | 101 | 0.624393 |
owtf | // Example
const Throw = React.lazy(() => {
throw new Error('Example');
});
const Component = React.memo(function Component({children}) {
return children;
});
function DisplayName({children}) {
return children;
}
DisplayName.displayName = 'Custom Name';
class NativeClass extends React.Component {
render() {
return this.props.children;
}
}
class FrozenClass extends React.Component {
constructor() {
super();
}
render() {
return this.props.children;
}
}
Object.freeze(FrozenClass.prototype);
| 16.064516 | 61 | 0.683712 |
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 {
COMFORTABLE_LINE_HEIGHT,
COMPACT_LINE_HEIGHT,
} from 'react-devtools-shared/src/devtools/constants.js';
export const REACT_TOTAL_NUM_LANES = 31;
// Increment this number any time a backwards breaking change is made to the profiler metadata.
export const SCHEDULING_PROFILER_VERSION = 1;
export const SNAPSHOT_MAX_HEIGHT = 60;
| 25.047619 | 95 | 0.739927 |
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.
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
import isValidElementType from 'shared/isValidElementType';
import getComponentNameFromType from 'shared/getComponentNameFromType';
import checkPropTypes from 'shared/checkPropTypes';
import {
getIteratorFn,
REACT_FORWARD_REF_TYPE,
REACT_MEMO_TYPE,
REACT_FRAGMENT_TYPE,
REACT_ELEMENT_TYPE,
} from 'shared/ReactSymbols';
import hasOwnProperty from 'shared/hasOwnProperty';
import isArray from 'shared/isArray';
import {jsxDEV} from './ReactJSXElement';
import {describeUnknownElementTypeFrameInDEV} from 'shared/ReactComponentStackFrame';
import ReactSharedInternals from 'shared/ReactSharedInternals';
const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
const ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
const REACT_CLIENT_REFERENCE = Symbol.for('react.client.reference');
function setCurrentlyValidatingElement(element) {
if (__DEV__) {
if (element) {
const owner = element._owner;
const stack = describeUnknownElementTypeFrameInDEV(
element.type,
element._source,
owner ? owner.type : null,
);
ReactDebugCurrentFrame.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame.setExtraStackFrame(null);
}
}
}
let propTypesMisspellWarningShown;
if (__DEV__) {
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
*/
export function isValidElement(object) {
if (__DEV__) {
return (
typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE
);
}
}
function getDeclarationErrorAddendum() {
if (__DEV__) {
if (ReactCurrentOwner.current) {
const name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
}
function getSourceInfoErrorAddendum(source) {
if (__DEV__) {
if (source !== undefined) {
const fileName = source.fileName.replace(/^.*[\\\/]/, '');
const 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.
*/
const ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
if (__DEV__) {
let info = getDeclarationErrorAddendum();
if (!info) {
const parentName = getComponentNameFromType(parentType);
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 (__DEV__) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
const 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.
let childOwner = '';
if (
element &&
element._owner &&
element._owner !== ReactCurrentOwner.current
) {
// Give the component that originally created this child.
childOwner = ` It was passed a child from ${getComponentNameFromType(
element._owner.type,
)}.`;
}
setCurrentlyValidatingElement(element);
console.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(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 (__DEV__) {
if (typeof node !== 'object' || !node) {
return;
}
if (node.$$typeof === REACT_CLIENT_REFERENCE) {
// This is a reference to a client component so it's unknown.
} else if (isArray(node)) {
for (let i = 0; i < node.length; i++) {
const 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 {
const 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) {
const iterator = iteratorFn.call(node);
let 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) {
if (__DEV__) {
const type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
if (type.$$typeof === REACT_CLIENT_REFERENCE) {
return;
}
let 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:
const name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true;
// Intentionally inside to avoid triggering lazy initializers:
const name = getComponentNameFromType(type);
console.error(
'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?',
name || 'Unknown',
);
}
if (
typeof type.getDefaultProps === 'function' &&
!type.getDefaultProps.isReactClassApproved
) {
console.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) {
if (__DEV__) {
const keys = Object.keys(fragment.props);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement(fragment);
console.error(
'Invalid prop `%s` supplied to `React.Fragment`. ' +
'React.Fragment can only have `key` and `children` props.',
key,
);
setCurrentlyValidatingElement(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement(fragment);
console.error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement(null);
}
}
}
const didWarnAboutKeySpread = {};
export function jsxWithValidation(
type,
props,
key,
isStaticChildren,
source,
self,
) {
if (__DEV__) {
const 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) {
let 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.";
}
const sourceInfo = getSourceInfoErrorAddendum(source);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
let typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = `<${getComponentNameFromType(type.type) || 'Unknown'} />`;
info =
' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
console.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,
);
}
const 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) {
const children = props.children;
if (children !== undefined) {
if (isStaticChildren) {
if (isArray(children)) {
for (let i = 0; i < children.length; i++) {
validateChildKeys(children[i], type);
}
if (Object.freeze) {
Object.freeze(children);
}
} else {
console.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 (hasOwnProperty.call(props, 'key')) {
const componentName = getComponentNameFromType(type);
const keys = Object.keys(props).filter(k => k !== 'key');
const beforeExample =
keys.length > 0
? '{key: someKey, ' + keys.join(': ..., ') + ': ...}'
: '{key: someKey}';
if (!didWarnAboutKeySpread[componentName + beforeExample]) {
const afterExample =
keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
console.error(
'A props object containing a "key" prop is being spread into JSX:\n' +
' let props = %s;\n' +
' <%s {...props} />\n' +
'React keys must be passed directly to JSX without using spread:\n' +
' let props = %s;\n' +
' <%s key={someKey} {...props} />',
beforeExample,
componentName,
afterExample,
componentName,
);
didWarnAboutKeySpread[componentName + beforeExample] = true;
}
}
if (type === REACT_FRAGMENT_TYPE) {
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.
export function jsxWithValidationStatic(type, props, key) {
if (__DEV__) {
return jsxWithValidation(type, props, key, true);
}
}
export function jsxWithValidationDynamic(type, props, key) {
if (__DEV__) {
return jsxWithValidation(type, props, key, false);
}
}
| 29.901566 | 110 | 0.621561 |
owtf | const {createElement, useLayoutEffect, useState} = React;
const {createRoot} = ReactDOM;
function App() {
const [isMounted, setIsMounted] = useState(false);
useLayoutEffect(() => {
setIsMounted(true);
}, []);
return createElement('div', null, `isMounted? ${isMounted}`);
}
const container = document.getElementById('container');
const root = createRoot(container);
root.render(createElement(App));
| 26.533333 | 63 | 0.711165 |
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 {Size, IntrinsicSize, Rect} from './geometry';
import type {
Interaction,
MouseDownInteraction,
MouseMoveInteraction,
MouseUpInteraction,
WheelWithShiftInteraction,
} from './useCanvasInteraction';
import type {ScrollState} from './utils/scrollState';
import type {ViewRefs} from './Surface';
import type {ViewState} from '../types';
import {Surface} from './Surface';
import {View} from './View';
import {rectContainsPoint} from './geometry';
import {
clampState,
areScrollStatesEqual,
translateState,
} from './utils/scrollState';
import {MOVE_WHEEL_DELTA_THRESHOLD} from './constants';
import {COLORS} from '../content-views/constants';
const CARET_MARGIN = 3;
const CARET_WIDTH = 5;
const CARET_HEIGHT = 3;
type OnChangeCallback = (
scrollState: ScrollState,
containerLength: number,
) => void;
export class VerticalScrollView extends View {
_contentView: View;
_isPanning: boolean;
_mutableViewStateKey: string;
_onChangeCallback: OnChangeCallback | null;
_scrollState: ScrollState;
_viewState: ViewState;
constructor(
surface: Surface,
frame: Rect,
contentView: View,
viewState: ViewState,
label: string,
) {
super(surface, frame);
this._contentView = contentView;
this._isPanning = false;
this._mutableViewStateKey = label + ':VerticalScrollView';
this._onChangeCallback = null;
this._scrollState = {
offset: 0,
length: 0,
};
this._viewState = viewState;
this.addSubview(contentView);
this._restoreMutableViewState();
}
setFrame(newFrame: Rect) {
super.setFrame(newFrame);
// Revalidate scrollState
this._setScrollState(this._scrollState);
}
desiredSize(): Size | IntrinsicSize {
return this._contentView.desiredSize();
}
draw(context: CanvasRenderingContext2D, viewRefs: ViewRefs) {
super.draw(context, viewRefs);
// Show carets if there's scroll overflow above or below the viewable area.
if (this.frame.size.height > CARET_HEIGHT * 2 + CARET_MARGIN * 3) {
const offset = this._scrollState.offset;
const desiredSize = this._contentView.desiredSize();
const above = offset;
const below = this.frame.size.height - desiredSize.height - offset;
if (above < 0 || below < 0) {
const {visibleArea} = this;
const {x, y} = visibleArea.origin;
const {width, height} = visibleArea.size;
const horizontalCenter = x + width / 2;
const halfWidth = CARET_WIDTH;
const left = horizontalCenter + halfWidth;
const right = horizontalCenter - halfWidth;
if (above < 0) {
const topY = y + CARET_MARGIN;
context.beginPath();
context.moveTo(horizontalCenter, topY);
context.lineTo(left, topY + CARET_HEIGHT);
context.lineTo(right, topY + CARET_HEIGHT);
context.closePath();
context.fillStyle = COLORS.SCROLL_CARET;
context.fill();
}
if (below < 0) {
const bottomY = y + height - CARET_MARGIN;
context.beginPath();
context.moveTo(horizontalCenter, bottomY);
context.lineTo(left, bottomY - CARET_HEIGHT);
context.lineTo(right, bottomY - CARET_HEIGHT);
context.closePath();
context.fillStyle = COLORS.SCROLL_CARET;
context.fill();
}
}
}
}
layoutSubviews() {
const {offset} = this._scrollState;
const desiredSize = this._contentView.desiredSize();
const minimumHeight = this.frame.size.height;
const desiredHeight = desiredSize ? desiredSize.height : 0;
// Force view to take up at least all remaining vertical space.
const height = Math.max(desiredHeight, minimumHeight);
const proposedFrame = {
origin: {
x: this.frame.origin.x,
y: this.frame.origin.y + offset,
},
size: {
width: this.frame.size.width,
height,
},
};
this._contentView.setFrame(proposedFrame);
super.layoutSubviews();
}
handleInteraction(interaction: Interaction): ?boolean {
switch (interaction.type) {
case 'mousedown':
return this._handleMouseDown(interaction);
case 'mousemove':
return this._handleMouseMove(interaction);
case 'mouseup':
return this._handleMouseUp(interaction);
case 'wheel-shift':
return this._handleWheelShift(interaction);
}
}
onChange(callback: OnChangeCallback) {
this._onChangeCallback = callback;
}
scrollBy(deltaY: number): boolean {
const newState = translateState({
state: this._scrollState,
delta: -deltaY,
containerLength: this.frame.size.height,
});
// If the state is updated by this wheel scroll,
// return true to prevent the interaction from bubbling.
// For instance, this prevents the outermost container from also scrolling.
return this._setScrollState(newState);
}
_handleMouseDown(interaction: MouseDownInteraction) {
if (rectContainsPoint(interaction.payload.location, this.frame)) {
const frameHeight = this.frame.size.height;
const contentHeight = this._contentView.desiredSize().height;
// Don't claim drag operations if the content is not tall enough to be scrollable.
// This would block any outer scroll views from working.
if (frameHeight < contentHeight) {
this._isPanning = true;
}
}
}
_handleMouseMove(interaction: MouseMoveInteraction): void | boolean {
if (!this._isPanning) {
return;
}
// Don't prevent mouse-move events from bubbling if they are horizontal drags.
const {movementX, movementY} = interaction.payload.event;
if (Math.abs(movementX) > Math.abs(movementY)) {
return;
}
const newState = translateState({
state: this._scrollState,
delta: interaction.payload.event.movementY,
containerLength: this.frame.size.height,
});
this._setScrollState(newState);
return true;
}
_handleMouseUp(interaction: MouseUpInteraction) {
if (this._isPanning) {
this._isPanning = false;
}
}
_handleWheelShift(interaction: WheelWithShiftInteraction): boolean {
const {
location,
delta: {deltaX, deltaY},
} = interaction.payload;
if (!rectContainsPoint(location, this.frame)) {
return false; // Not scrolling on view
}
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
if (absDeltaX > absDeltaY) {
return false; // Scrolling horizontally
}
if (absDeltaY < MOVE_WHEEL_DELTA_THRESHOLD) {
return false; // Movement was too small and should be ignored.
}
return this.scrollBy(deltaY);
}
_restoreMutableViewState() {
if (
this._viewState.viewToMutableViewStateMap.has(this._mutableViewStateKey)
) {
this._scrollState = ((this._viewState.viewToMutableViewStateMap.get(
this._mutableViewStateKey,
): any): ScrollState);
} else {
this._viewState.viewToMutableViewStateMap.set(
this._mutableViewStateKey,
this._scrollState,
);
}
this.setNeedsDisplay();
}
_setScrollState(proposedState: ScrollState): boolean {
const contentHeight = this._contentView.frame.size.height;
const containerHeight = this.frame.size.height;
const clampedState = clampState({
state: proposedState,
minContentLength: contentHeight,
maxContentLength: contentHeight,
containerLength: containerHeight,
});
if (!areScrollStatesEqual(clampedState, this._scrollState)) {
this._scrollState.offset = clampedState.offset;
this._scrollState.length = clampedState.length;
this.setNeedsDisplay();
if (this._onChangeCallback !== null) {
this._onChangeCallback(clampedState, this.frame.size.height);
}
return true;
}
// Don't allow wheel events to bubble past this view even if we've scrolled to the edge.
// It just feels bad to have the scrolling jump unexpectedly from in a container to the outer page.
// The only exception is when the container fits the content (no scrolling).
if (contentHeight === containerHeight) {
return false;
}
return true;
}
}
| 27.449664 | 103 | 0.658606 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactNoopPersistent;
let waitForAll;
describe('ReactPersistent', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoopPersistent = require('react-noop-renderer/persistent');
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
});
// Inlined from shared folder so we can run this test on a bundle.
function createPortal(children, containerInfo, implementation, key) {
return {
$$typeof: Symbol.for('react.portal'),
key: key == null ? null : String(key),
children,
containerInfo,
implementation,
};
}
function render(element) {
ReactNoopPersistent.render(element);
}
function div(...children) {
children = children.map(c =>
typeof c === 'string' ? {text: c, hidden: false} : c,
);
return {type: 'div', children, prop: undefined, hidden: false};
}
function span(prop) {
return {type: 'span', children: [], prop, hidden: false};
}
// For persistent renderers we have to mix deep equality and reference equality checks
// for which we need the actual children.
// None of the tests are gated and the underlying implementation is rarely touch
// so it's unlikely we deal with failing `toEqual` checks which cause bad performance.
function dangerouslyGetChildren() {
return ReactNoopPersistent.dangerouslyGetChildren();
}
it('can update child nodes of a host instance', async () => {
function Bar(props) {
return <span>{props.text}</span>;
}
function Foo(props) {
return (
<div>
<Bar text={props.text} />
{props.text === 'World' ? <Bar text={props.text} /> : null}
</div>
);
}
render(<Foo text="Hello" />);
await waitForAll([]);
const originalChildren = dangerouslyGetChildren();
expect(originalChildren).toEqual([div(span())]);
render(<Foo text="World" />);
await waitForAll([]);
const newChildren = dangerouslyGetChildren();
expect(newChildren).toEqual([div(span(), span())]);
expect(originalChildren).toEqual([div(span())]);
});
it('can reuse child nodes between updates', async () => {
function Baz(props) {
return <span prop={props.text} />;
}
class Bar extends React.Component {
shouldComponentUpdate(newProps) {
return false;
}
render() {
return <Baz text={this.props.text} />;
}
}
function Foo(props) {
return (
<div>
<Bar text={props.text} />
{props.text === 'World' ? <Bar text={props.text} /> : null}
</div>
);
}
render(<Foo text="Hello" />);
await waitForAll([]);
const originalChildren = dangerouslyGetChildren();
expect(originalChildren).toEqual([div(span('Hello'))]);
render(<Foo text="World" />);
await waitForAll([]);
const newChildren = dangerouslyGetChildren();
expect(newChildren).toEqual([div(span('Hello'), span('World'))]);
expect(originalChildren).toEqual([div(span('Hello'))]);
// Reused node should have reference equality
expect(newChildren[0].children[0]).toBe(originalChildren[0].children[0]);
});
it('can update child text nodes', async () => {
function Foo(props) {
return (
<div>
{props.text}
<span />
</div>
);
}
render(<Foo text="Hello" />);
await waitForAll([]);
const originalChildren = dangerouslyGetChildren();
expect(originalChildren).toEqual([div('Hello', span())]);
render(<Foo text="World" />);
await waitForAll([]);
const newChildren = dangerouslyGetChildren();
expect(newChildren).toEqual([div('World', span())]);
expect(originalChildren).toEqual([div('Hello', span())]);
});
it('supports portals', async () => {
function Parent(props) {
return <div>{props.children}</div>;
}
function BailoutSpan() {
return <span />;
}
class BailoutTest extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
return <BailoutSpan />;
}
}
function Child(props) {
return (
<div>
<BailoutTest />
{props.children}
</div>
);
}
const portalContainer = {rootID: 'persistent-portal-test', children: []};
const emptyPortalChildSet = portalContainer.children;
render(<Parent>{createPortal(<Child />, portalContainer, null)}</Parent>);
await waitForAll([]);
expect(emptyPortalChildSet).toEqual([]);
const originalChildren = dangerouslyGetChildren();
expect(originalChildren).toEqual([div()]);
const originalPortalChildren = portalContainer.children;
expect(originalPortalChildren).toEqual([div(span())]);
render(
<Parent>
{createPortal(<Child>Hello {'World'}</Child>, portalContainer, null)}
</Parent>,
);
await waitForAll([]);
const newChildren = dangerouslyGetChildren();
expect(newChildren).toEqual([div()]);
const newPortalChildren = portalContainer.children;
expect(newPortalChildren).toEqual([div(span(), 'Hello ', 'World')]);
expect(originalChildren).toEqual([div()]);
expect(originalPortalChildren).toEqual([div(span())]);
// Reused portal children should have reference equality
expect(newPortalChildren[0].children[0]).toBe(
originalPortalChildren[0].children[0],
);
// Deleting the Portal, should clear its children
render(<Parent />);
await waitForAll([]);
const clearedPortalChildren = portalContainer.children;
expect(clearedPortalChildren).toEqual([]);
// The original is unchanged.
expect(newPortalChildren).toEqual([div(span(), 'Hello ', 'World')]);
});
});
| 26.953917 | 89 | 0.624073 |
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 {withSyncPerfMeasurements} from 'react-devtools-shared/src/PerformanceLoggingUtils';
import traverse from '@babel/traverse';
import type {HooksNode} from 'react-debug-tools/src/ReactDebugHooks';
// Missing types in @babel/traverse
type NodePath = any;
type Node = any;
// Missing types in @babel/types
type File = any;
export type Position = {
line: number,
column: number,
};
export type SourceFileASTWithHookDetails = {
sourceFileAST: File,
line: number,
source: string,
};
export const NO_HOOK_NAME = '<no-hook>';
const AST_NODE_TYPES = Object.freeze({
PROGRAM: 'Program',
CALL_EXPRESSION: 'CallExpression',
MEMBER_EXPRESSION: 'MemberExpression',
ARRAY_PATTERN: 'ArrayPattern',
IDENTIFIER: 'Identifier',
NUMERIC_LITERAL: 'NumericLiteral',
VARIABLE_DECLARATOR: 'VariableDeclarator',
});
// Check if line number obtained from source map and the line number in hook node match
function checkNodeLocation(
path: NodePath,
line: number,
column?: number | null = null,
): boolean {
const {start, end} = path.node.loc;
if (line !== start.line) {
return false;
}
if (column !== null) {
// Column numbers are represented differently between tools/engines.
// Error.prototype.stack columns are 1-based (like most IDEs) but ASTs are 0-based.
//
// In practice this will probably never matter,
// because this code matches the 1-based Error stack location for the hook Identifier (e.g. useState)
// with the larger 0-based VariableDeclarator (e.g. [foo, setFoo] = useState())
// so the ranges should always overlap.
//
// For more info see https://github.com/facebook/react/pull/21833#discussion_r666831276
column -= 1;
if (
(line === start.line && column < start.column) ||
(line === end.line && column > end.column)
) {
return false;
}
}
return true;
}
// Checks whether hookNode is a member of targetHookNode
function filterMemberNodesOfTargetHook(
targetHookNode: NodePath,
hookNode: NodePath,
): boolean {
const targetHookName = targetHookNode.node.id.name;
return (
targetHookName != null &&
(targetHookName ===
(hookNode.node.init.object && hookNode.node.init.object.name) ||
targetHookName === hookNode.node.init.name)
);
}
// Checks whether hook is the first member node of a state variable declaration node
function filterMemberWithHookVariableName(hook: NodePath): boolean {
return (
hook.node.init.property.type === AST_NODE_TYPES.NUMERIC_LITERAL &&
hook.node.init.property.value === 0
);
}
// Returns all AST Nodes associated with 'potentialReactHookASTNode'
function getFilteredHookASTNodes(
potentialReactHookASTNode: NodePath,
potentialHooksFound: Array<NodePath>,
source: string,
): Array<NodePath> {
let nodesAssociatedWithReactHookASTNode: NodePath[] = [];
if (nodeContainsHookVariableName(potentialReactHookASTNode)) {
// made custom hooks to enter this, always
// Case 1.
// Directly usable Node -> const ref = useRef(null);
// -> const [tick, setTick] = useState(1);
// Case 2.
// Custom Hooks -> const someVariable = useSomeCustomHook();
// -> const [someVariable, someFunction] = useAnotherCustomHook();
nodesAssociatedWithReactHookASTNode.unshift(potentialReactHookASTNode);
} else {
// Case 3.
// Indirectly usable Node -> const tickState = useState(1);
// [tick, setTick] = tickState;
// -> const tickState = useState(1);
// const tick = tickState[0];
// const setTick = tickState[1];
nodesAssociatedWithReactHookASTNode = potentialHooksFound.filter(hookNode =>
filterMemberNodesOfTargetHook(potentialReactHookASTNode, hookNode),
);
}
return nodesAssociatedWithReactHookASTNode;
}
// Returns Hook name
export function getHookName(
hook: HooksNode,
originalSourceAST: mixed,
originalSourceCode: string,
originalSourceLineNumber: number,
originalSourceColumnNumber: number,
): string | null {
const hooksFromAST = withSyncPerfMeasurements(
'getPotentialHookDeclarationsFromAST(originalSourceAST)',
() => getPotentialHookDeclarationsFromAST(originalSourceAST),
);
let potentialReactHookASTNode = null;
if (originalSourceColumnNumber === 0) {
// This most likely indicates a source map type like 'cheap-module-source-map'
// that intentionally drops column numbers for compilation speed in DEV builds.
// In this case, we can assume there's probably only one hook per line (true in most cases)
// and just fail if we find more than one match.
const matchingNodes = hooksFromAST.filter(node => {
const nodeLocationCheck = checkNodeLocation(
node,
originalSourceLineNumber,
);
const hookDeclarationCheck = isConfirmedHookDeclaration(node);
return nodeLocationCheck && hookDeclarationCheck;
});
if (matchingNodes.length === 1) {
potentialReactHookASTNode = matchingNodes[0];
}
} else {
potentialReactHookASTNode = hooksFromAST.find(node => {
const nodeLocationCheck = checkNodeLocation(
node,
originalSourceLineNumber,
originalSourceColumnNumber,
);
const hookDeclarationCheck = isConfirmedHookDeclaration(node);
return nodeLocationCheck && hookDeclarationCheck;
});
}
if (!potentialReactHookASTNode) {
return null;
}
// nodesAssociatedWithReactHookASTNode could directly be used to obtain the hook variable name
// depending on the type of potentialReactHookASTNode
try {
const nodesAssociatedWithReactHookASTNode = withSyncPerfMeasurements(
'getFilteredHookASTNodes()',
() =>
getFilteredHookASTNodes(
potentialReactHookASTNode,
hooksFromAST,
originalSourceCode,
),
);
const name = withSyncPerfMeasurements('getHookNameFromNode()', () =>
getHookNameFromNode(
hook,
nodesAssociatedWithReactHookASTNode,
potentialReactHookASTNode,
),
);
return name;
} catch (error) {
console.error(error);
return null;
}
}
function getHookNameFromNode(
originalHook: HooksNode,
nodesAssociatedWithReactHookASTNode: NodePath[],
potentialReactHookASTNode: NodePath,
): string | null {
let hookVariableName: string | null;
const isCustomHook = originalHook.id === null;
switch (nodesAssociatedWithReactHookASTNode.length) {
case 1:
// CASE 1A (nodesAssociatedWithReactHookASTNode[0] !== potentialReactHookASTNode):
// const flagState = useState(true); -> later referenced as
// const [flag, setFlag] = flagState;
//
// CASE 1B (nodesAssociatedWithReactHookASTNode[0] === potentialReactHookASTNode):
// const [flag, setFlag] = useState(true); -> we have access to the hook variable straight away
//
// CASE 1C (isCustomHook && nodesAssociatedWithReactHookASTNode[0] === potentialReactHookASTNode):
// const someVariable = useSomeCustomHook(); -> we have access to hook variable straight away
// const [someVariable, someFunction] = useAnotherCustomHook(); -> we ignore variable names in this case
// as it is unclear what variable name to show
if (
isCustomHook &&
nodesAssociatedWithReactHookASTNode[0] === potentialReactHookASTNode
) {
hookVariableName = getHookVariableName(
potentialReactHookASTNode,
isCustomHook,
);
break;
}
hookVariableName = getHookVariableName(
nodesAssociatedWithReactHookASTNode[0],
);
break;
case 2:
// const flagState = useState(true); -> later referenced as
// const flag = flagState[0];
// const setFlag = flagState[1];
nodesAssociatedWithReactHookASTNode =
nodesAssociatedWithReactHookASTNode.filter(hookPath =>
filterMemberWithHookVariableName(hookPath),
);
if (nodesAssociatedWithReactHookASTNode.length !== 1) {
// Something went wrong, only a single desirable hook should remain here
throw new Error("Couldn't isolate AST Node containing hook variable.");
}
hookVariableName = getHookVariableName(
nodesAssociatedWithReactHookASTNode[0],
);
break;
default:
// Case 0:
// const flagState = useState(true); -> which is not accessed anywhere
//
// Case > 2 (fallback):
// const someState = React.useState(() => 0)
//
// const stateVariable = someState[0]
// const setStateVariable = someState[1]
//
// const [number2, setNumber2] = someState
//
// We assign the state variable for 'someState' to multiple variables,
// and hence cannot isolate a unique variable name. In such cases,
// default to showing 'someState'
hookVariableName = getHookVariableName(potentialReactHookASTNode);
break;
}
return hookVariableName;
}
// Extracts the variable name from hook node path
function getHookVariableName(
hook: NodePath,
isCustomHook: boolean = false,
): string | null {
const nodeType = hook.node.id.type;
switch (nodeType) {
case AST_NODE_TYPES.ARRAY_PATTERN:
return !isCustomHook ? hook.node.id.elements[0]?.name ?? null : null;
case AST_NODE_TYPES.IDENTIFIER:
return hook.node.id.name;
default:
return null;
}
}
function getPotentialHookDeclarationsFromAST(sourceAST: File): NodePath[] {
const potentialHooksFound: NodePath[] = [];
withSyncPerfMeasurements('traverse(sourceAST)', () =>
traverse(sourceAST, {
enter(path) {
if (path.isVariableDeclarator() && isPotentialHookDeclaration(path)) {
potentialHooksFound.push(path);
}
},
}),
);
return potentialHooksFound;
}
/**
* This function traverses the sourceAST and returns a mapping
* that maps locations in the source code to their corresponding
* Hook name, if there is a relevant Hook name for that location.
*
* A location in the source code is represented by line and column
* numbers as a Position object: { line, column }.
* - line is 1-indexed.
* - column is 0-indexed.
*
* A Hook name will be assigned to a Hook CallExpression if the
* CallExpression is for a variable declaration (i.e. it returns
* a value that is assigned to a variable), and if we can reliably
* infer the correct name to use (see comments in the function body
* for more details).
*
* The returned mapping is an array of locations and their assigned
* names, sorted by location. Specifically, each entry in the array
* contains a `name` and a `start` Position. The `name` of a given
* entry is the "assigned" name in the source code until the `start`
* of the **next** entry. This means that given the mapping, in order
* to determine the Hook name assigned for a given source location, we
* need to find the adjacent entries that most closely contain the given
* location.
*
* E.g. for the following code:
*
* 1| function Component() {
* 2| const [state, setState] = useState(0);
* 3| ^---------^ -> Cols 28 - 38: Hook CallExpression
* 4|
* 5| useEffect(() => {...}); -> call ignored since not declaring a variable
* 6|
* 7| return (...);
* 8| }
*
* The returned "mapping" would be something like:
* [
* {name: '<no-hook>', start: {line: 1, column: 0}},
* {name: 'state', start: {line: 2, column: 28}},
* {name: '<no-hook>', start: {line: 2, column: 38}},
* ]
*
* Where the Hook name `state` (corresponding to the `state` variable)
* is assigned to the location in the code for the CallExpression
* representing the call to `useState(0)` (line 2, col 28-38).
*/
export function getHookNamesMappingFromAST(
sourceAST: File,
): $ReadOnlyArray<{name: string, start: Position}> {
const hookStack: Array<{name: string, start: $FlowFixMe}> = [];
const hookNames = [];
const pushFrame = (name: string, node: Node) => {
const nameInfo = {name, start: {...node.loc.start}};
hookStack.unshift(nameInfo);
hookNames.push(nameInfo);
};
const popFrame = (node: Node) => {
hookStack.shift();
const top = hookStack[0];
if (top != null) {
hookNames.push({name: top.name, start: {...node.loc.end}});
}
};
traverse(sourceAST, {
[AST_NODE_TYPES.PROGRAM]: {
enter(path) {
pushFrame(NO_HOOK_NAME, path.node);
},
exit(path) {
popFrame(path.node);
},
},
[AST_NODE_TYPES.VARIABLE_DECLARATOR]: {
enter(path) {
// Check if this variable declaration corresponds to a variable
// declared by calling a Hook.
if (isConfirmedHookDeclaration(path)) {
const hookDeclaredVariableName = getHookVariableName(path);
if (!hookDeclaredVariableName) {
return;
}
const callExpressionNode = assertCallExpression(path.node.init);
// Check if this variable declaration corresponds to a call to a
// built-in Hook that returns a tuple (useState, useReducer,
// useTransition).
// If it doesn't, we immediately use the declared variable name
// as the Hook name. We do this because for any other Hooks that
// aren't the built-in Hooks that return a tuple, we can't reliably
// extract a Hook name from other variable declarations derived from
// this one, since we don't know which of the declared variables
// are the relevant ones to track and show in dev tools.
if (!isBuiltInHookThatReturnsTuple(path)) {
pushFrame(hookDeclaredVariableName, callExpressionNode);
return;
}
// Check if the variable declared by the Hook call is referenced
// anywhere else in the code. If not, we immediately use the
// declared variable name as the Hook name.
const referencePaths =
hookDeclaredVariableName != null
? path.scope.bindings[hookDeclaredVariableName]?.referencePaths
: null;
if (referencePaths == null) {
pushFrame(hookDeclaredVariableName, callExpressionNode);
return;
}
// Check each reference to the variable declared by the Hook call,
// and for each, we do the following:
let declaredVariableName = null;
for (let i = 0; i <= referencePaths.length; i++) {
const referencePath = referencePaths[i];
if (declaredVariableName != null) {
break;
}
// 1. Check if the reference is contained within a VariableDeclarator
// Node. This will allow us to determine if the variable declared by
// the Hook call is being used to declare other variables.
let variableDeclaratorPath = referencePath;
while (
variableDeclaratorPath != null &&
variableDeclaratorPath.node.type !==
AST_NODE_TYPES.VARIABLE_DECLARATOR
) {
variableDeclaratorPath = variableDeclaratorPath.parentPath;
}
// 2. If we find a VariableDeclarator containing the
// referenced variable, we extract the Hook name from the new
// variable declaration.
// E.g., a case like the following:
// const countState = useState(0);
// const count = countState[0];
// const setCount = countState[1]
// Where the reference to `countState` is later referenced
// within a VariableDeclarator, so we can extract `count` as
// the Hook name.
const varDeclInit = variableDeclaratorPath?.node.init;
if (varDeclInit != null) {
switch (varDeclInit.type) {
case AST_NODE_TYPES.MEMBER_EXPRESSION: {
// When encountering a MemberExpression inside the new
// variable declaration, we only want to extract the variable
// name if we're assigning the value of the first member,
// which is handled by `filterMemberWithHookVariableName`.
// E.g.
// const countState = useState(0);
// const count = countState[0]; -> extract the name from this reference
// const setCount = countState[1]; -> ignore this reference
if (
filterMemberWithHookVariableName(variableDeclaratorPath)
) {
declaredVariableName = getHookVariableName(
variableDeclaratorPath,
);
}
break;
}
case AST_NODE_TYPES.IDENTIFIER: {
declaredVariableName = getHookVariableName(
variableDeclaratorPath,
);
break;
}
default:
break;
}
}
}
// If we were able to extract a name from the new variable
// declaration, use it as the Hook name. Otherwise, use the
// original declared variable as the variable name.
if (declaredVariableName != null) {
pushFrame(declaredVariableName, callExpressionNode);
} else {
pushFrame(hookDeclaredVariableName, callExpressionNode);
}
}
},
exit(path) {
if (isConfirmedHookDeclaration(path)) {
const callExpressionNode = assertCallExpression(path.node.init);
popFrame(callExpressionNode);
}
},
},
});
return hookNames;
}
// Check if 'path' contains declaration of the form const X = useState(0);
function isConfirmedHookDeclaration(path: NodePath): boolean {
const nodeInit = path.node.init;
if (nodeInit == null || nodeInit.type !== AST_NODE_TYPES.CALL_EXPRESSION) {
return false;
}
const callee = nodeInit.callee;
return isHook(callee);
}
// We consider hooks to be a hook name identifier or a member expression containing a hook name.
function isHook(node: Node): boolean {
if (node.type === AST_NODE_TYPES.IDENTIFIER) {
return isHookName(node.name);
} else if (
node.type === AST_NODE_TYPES.MEMBER_EXPRESSION &&
!node.computed &&
isHook(node.property)
) {
const obj = node.object;
const isPascalCaseNameSpace = /^[A-Z].*/;
return (
obj.type === AST_NODE_TYPES.IDENTIFIER &&
isPascalCaseNameSpace.test(obj.name)
);
} else {
// TODO Possibly handle inline require statements e.g. require("useStable")(...)
// This does not seem like a high priority, since inline requires are probably
// not common and are also typically in compiled code rather than source code.
return false;
}
}
// Catch all identifiers that begin with "use"
// followed by an uppercase Latin character to exclude identifiers like "user".
// Copied from packages/eslint-plugin-react-hooks/src/RulesOfHooks
function isHookName(name: string): boolean {
return /^use[A-Z0-9].*$/.test(name);
}
// Check if the AST Node COULD be a React Hook
function isPotentialHookDeclaration(path: NodePath): boolean {
// The array potentialHooksFound will contain all potential hook declaration cases we support
const nodePathInit = path.node.init;
if (nodePathInit != null) {
if (nodePathInit.type === AST_NODE_TYPES.CALL_EXPRESSION) {
// CASE: CallExpression
// 1. const [count, setCount] = useState(0); -> destructured pattern
// 2. const [A, setA] = useState(0), const [B, setB] = useState(0); -> multiple inline declarations
// 3. const [
// count,
// setCount
// ] = useState(0); -> multiline hook declaration
// 4. const ref = useRef(null); -> generic hooks
const callee = nodePathInit.callee;
return isHook(callee);
} else if (
nodePathInit.type === AST_NODE_TYPES.MEMBER_EXPRESSION ||
nodePathInit.type === AST_NODE_TYPES.IDENTIFIER
) {
// CASE: MemberExpression
// const countState = React.useState(0);
// const count = countState[0];
// const setCount = countState[1]; -> Accessing members following hook declaration
// CASE: Identifier
// const countState = React.useState(0);
// const [count, setCount] = countState; -> destructuring syntax following hook declaration
return true;
}
}
return false;
}
/// Check whether 'node' is hook declaration of form useState(0); OR React.useState(0);
function isReactFunction(node: Node, functionName: string): boolean {
return (
node.name === functionName ||
(node.type === 'MemberExpression' &&
node.object.name === 'React' &&
node.property.name === functionName)
);
}
// Check if 'path' is either State or Reducer hook
function isBuiltInHookThatReturnsTuple(path: NodePath): boolean {
const callee = path.node.init.callee;
return (
isReactFunction(callee, 'useState') ||
isReactFunction(callee, 'useReducer') ||
isReactFunction(callee, 'useTransition')
);
}
// Check whether hookNode of a declaration contains obvious variable name
function nodeContainsHookVariableName(hookNode: NodePath): boolean {
// We determine cases where variable names are obvious in declarations. Examples:
// const [tick, setTick] = useState(1); OR const ref = useRef(null);
// Here tick/ref are obvious hook variables in the hook declaration node itself
// 1. True for satisfying above cases
// 2. False for everything else. Examples:
// const countState = React.useState(0);
// const count = countState[0];
// const setCount = countState[1]; -> not obvious, hook variable can't be determined
// from the hook declaration node alone
// 3. For custom hooks we force pass true since we are only concerned with the AST node
// regardless of how it is accessed in source code. (See: getHookVariableName)
const node = hookNode.node.id;
if (
node.type === AST_NODE_TYPES.ARRAY_PATTERN ||
(node.type === AST_NODE_TYPES.IDENTIFIER &&
!isBuiltInHookThatReturnsTuple(hookNode))
) {
return true;
}
return false;
}
function assertCallExpression(node: Node): Node {
if (node.type !== AST_NODE_TYPES.CALL_EXPRESSION) {
throw new Error('Expected a CallExpression node for a Hook declaration.');
}
return node;
}
| 34.965517 | 116 | 0.643321 |
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 LRU from 'lru-cache';
import {
isElement,
typeOf,
ContextConsumer,
ContextProvider,
ForwardRef,
Fragment,
Lazy,
Memo,
Portal,
Profiler,
StrictMode,
Suspense,
} from 'react-is';
import {
REACT_SUSPENSE_LIST_TYPE as SuspenseList,
REACT_TRACING_MARKER_TYPE as TracingMarker,
} from 'shared/ReactSymbols';
import {
TREE_OPERATION_ADD,
TREE_OPERATION_REMOVE,
TREE_OPERATION_REMOVE_ROOT,
TREE_OPERATION_REORDER_CHILDREN,
TREE_OPERATION_SET_SUBTREE_MODE,
TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS,
TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY,
LOCAL_STORAGE_OPEN_IN_EDITOR_URL,
LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS,
LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY,
LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY,
LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE,
} from './constants';
import {
ComponentFilterElementType,
ElementTypeHostComponent,
} from './frontend/types';
import {
ElementTypeRoot,
ElementTypeClass,
ElementTypeForwardRef,
ElementTypeFunction,
ElementTypeMemo,
} from 'react-devtools-shared/src/frontend/types';
import {localStorageGetItem, localStorageSetItem} from './storage';
import {meta} from './hydration';
import isArray from './isArray';
import type {
ComponentFilter,
ElementType,
BrowserTheme,
SerializedElement as SerializedElementFrontend,
LRUCache,
} from 'react-devtools-shared/src/frontend/types';
import type {SerializedElement as SerializedElementBackend} from 'react-devtools-shared/src/backend/types';
// $FlowFixMe[method-unbinding]
const hasOwnProperty = Object.prototype.hasOwnProperty;
const cachedDisplayNames: WeakMap<Function, string> = new WeakMap();
// On large trees, encoding takes significant time.
// Try to reuse the already encoded strings.
const encodedStringCache: LRUCache<string, Array<number>> = new LRU({
max: 1000,
});
export function alphaSortKeys(
a: string | number | symbol,
b: string | number | symbol,
): number {
if (a.toString() > b.toString()) {
return 1;
} else if (b.toString() > a.toString()) {
return -1;
} else {
return 0;
}
}
export function getAllEnumerableKeys(
obj: Object,
): Set<string | number | symbol> {
const keys = new Set<string | number | symbol>();
let current = obj;
while (current != null) {
const currentKeys = [
...Object.keys(current),
...Object.getOwnPropertySymbols(current),
];
const descriptors = Object.getOwnPropertyDescriptors(current);
currentKeys.forEach(key => {
// $FlowFixMe[incompatible-type]: key can be a Symbol https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor
if (descriptors[key].enumerable) {
keys.add(key);
}
});
current = Object.getPrototypeOf(current);
}
return keys;
}
// Mirror https://github.com/facebook/react/blob/7c21bf72ace77094fd1910cc350a548287ef8350/packages/shared/getComponentName.js#L27-L37
export function getWrappedDisplayName(
outerType: mixed,
innerType: any,
wrapperName: string,
fallbackName?: string,
): string {
const displayName = (outerType: any)?.displayName;
return (
displayName || `${wrapperName}(${getDisplayName(innerType, fallbackName)})`
);
}
export function getDisplayName(
type: Function,
fallbackName: string = 'Anonymous',
): string {
const nameFromCache = cachedDisplayNames.get(type);
if (nameFromCache != null) {
return nameFromCache;
}
let displayName = fallbackName;
// The displayName property is not guaranteed to be a string.
// It's only safe to use for our purposes if it's a string.
// github.com/facebook/react-devtools/issues/803
if (typeof type.displayName === 'string') {
displayName = type.displayName;
} else if (typeof type.name === 'string' && type.name !== '') {
displayName = type.name;
}
cachedDisplayNames.set(type, displayName);
return displayName;
}
let uidCounter: number = 0;
export function getUID(): number {
return ++uidCounter;
}
export function utfDecodeStringWithRanges(
array: Array<number>,
left: number,
right: number,
): string {
let string = '';
for (let i = left; i <= right; i++) {
string += String.fromCodePoint(array[i]);
}
return string;
}
function surrogatePairToCodePoint(
charCode1: number,
charCode2: number,
): number {
return ((charCode1 & 0x3ff) << 10) + (charCode2 & 0x3ff) + 0x10000;
}
// Credit for this encoding approach goes to Tim Down:
// https://stackoverflow.com/questions/4877326/how-can-i-tell-if-a-string-contains-multibyte-characters-in-javascript
export function utfEncodeString(string: string): Array<number> {
const cached = encodedStringCache.get(string);
if (cached !== undefined) {
return cached;
}
const encoded = [];
let i = 0;
let charCode;
while (i < string.length) {
charCode = string.charCodeAt(i);
// Handle multibyte unicode characters (like emoji).
if ((charCode & 0xf800) === 0xd800) {
encoded.push(surrogatePairToCodePoint(charCode, string.charCodeAt(++i)));
} else {
encoded.push(charCode);
}
++i;
}
encodedStringCache.set(string, encoded);
return encoded;
}
export function printOperationsArray(operations: Array<number>) {
// The first two values are always rendererID and rootID
const rendererID = operations[0];
const rootID = operations[1];
const logs = [`operations for renderer:${rendererID} and root:${rootID}`];
let i = 2;
// 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: {
const id = ((operations[i + 1]: any): number);
const type = ((operations[i + 2]: any): ElementType);
i += 3;
if (type === ElementTypeRoot) {
logs.push(`Add new root node ${id}`);
i++; // isStrictModeCompliant
i++; // supportsProfiling
i++; // supportsStrictMode
i++; // hasOwnerMetadata
} else {
const parentID = ((operations[i]: any): number);
i++;
i++; // ownerID
const displayNameStringID = operations[i];
const displayName = stringTable[displayNameStringID];
i++;
i++; // key
logs.push(
`Add node ${id} (${displayName || 'null'}) as child of ${parentID}`,
);
}
break;
}
case TREE_OPERATION_REMOVE: {
const removeLength = ((operations[i + 1]: any): number);
i += 2;
for (let removeIndex = 0; removeIndex < removeLength; removeIndex++) {
const id = ((operations[i]: any): number);
i += 1;
logs.push(`Remove node ${id}`);
}
break;
}
case TREE_OPERATION_REMOVE_ROOT: {
i += 1;
logs.push(`Remove root ${rootID}`);
break;
}
case TREE_OPERATION_SET_SUBTREE_MODE: {
const id = operations[i + 1];
const mode = operations[i + 1];
i += 3;
logs.push(`Mode ${mode} set for subtree with root ${id}`);
break;
}
case TREE_OPERATION_REORDER_CHILDREN: {
const id = ((operations[i + 1]: any): number);
const numChildren = ((operations[i + 2]: any): number);
i += 3;
const children = operations.slice(i, i + numChildren);
i += numChildren;
logs.push(`Re-order node ${id} children ${children.join(',')}`);
break;
}
case TREE_OPERATION_UPDATE_TREE_BASE_DURATION:
// Base duration updates are only sent while profiling is in progress.
// We can ignore them at this point.
// The profiler UI uses them lazily in order to generate the tree.
i += 3;
break;
case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:
const id = operations[i + 1];
const numErrors = operations[i + 2];
const numWarnings = operations[i + 3];
i += 4;
logs.push(
`Node ${id} has ${numErrors} errors and ${numWarnings} warnings`,
);
break;
default:
throw Error(`Unsupported Bridge operation "${operation}"`);
}
}
console.log(logs.join('\n '));
}
export function getDefaultComponentFilters(): Array<ComponentFilter> {
return [
{
type: ComponentFilterElementType,
value: ElementTypeHostComponent,
isEnabled: true,
},
];
}
export function getSavedComponentFilters(): Array<ComponentFilter> {
try {
const raw = localStorageGetItem(
LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY,
);
if (raw != null) {
return JSON.parse(raw);
}
} catch (error) {}
return getDefaultComponentFilters();
}
export function setSavedComponentFilters(
componentFilters: Array<ComponentFilter>,
): void {
localStorageSetItem(
LOCAL_STORAGE_COMPONENT_FILTER_PREFERENCES_KEY,
JSON.stringify(componentFilters),
);
}
function parseBool(s: ?string): ?boolean {
if (s === 'true') {
return true;
}
if (s === 'false') {
return false;
}
}
export function castBool(v: any): ?boolean {
if (v === true || v === false) {
return v;
}
}
export function castBrowserTheme(v: any): ?BrowserTheme {
if (v === 'light' || v === 'dark' || v === 'auto') {
return v;
}
}
export function getAppendComponentStack(): boolean {
const raw = localStorageGetItem(
LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY,
);
return parseBool(raw) ?? true;
}
export function getBreakOnConsoleErrors(): boolean {
const raw = localStorageGetItem(LOCAL_STORAGE_SHOULD_BREAK_ON_CONSOLE_ERRORS);
return parseBool(raw) ?? false;
}
export function getHideConsoleLogsInStrictMode(): boolean {
const raw = localStorageGetItem(
LOCAL_STORAGE_HIDE_CONSOLE_LOGS_IN_STRICT_MODE,
);
return parseBool(raw) ?? false;
}
export function getShowInlineWarningsAndErrors(): boolean {
const raw = localStorageGetItem(
LOCAL_STORAGE_SHOW_INLINE_WARNINGS_AND_ERRORS_KEY,
);
return parseBool(raw) ?? true;
}
export function getDefaultOpenInEditorURL(): string {
return typeof process.env.EDITOR_URL === 'string'
? process.env.EDITOR_URL
: '';
}
export function getOpenInEditorURL(): string {
try {
const raw = localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL);
if (raw != null) {
return JSON.parse(raw);
}
} catch (error) {}
return getDefaultOpenInEditorURL();
}
type ParseElementDisplayNameFromBackendReturn = {
formattedDisplayName: string | null,
hocDisplayNames: Array<string> | null,
compiledWithForget: boolean,
};
export function parseElementDisplayNameFromBackend(
displayName: string | null,
type: ElementType,
): ParseElementDisplayNameFromBackendReturn {
if (displayName === null) {
return {
formattedDisplayName: null,
hocDisplayNames: null,
compiledWithForget: false,
};
}
if (displayName.startsWith('Forget(')) {
const displayNameWithoutForgetWrapper = displayName.slice(
7,
displayName.length - 1,
);
const {formattedDisplayName, hocDisplayNames} =
parseElementDisplayNameFromBackend(displayNameWithoutForgetWrapper, type);
return {formattedDisplayName, hocDisplayNames, compiledWithForget: true};
}
let hocDisplayNames = null;
switch (type) {
case ElementTypeClass:
case ElementTypeForwardRef:
case ElementTypeFunction:
case ElementTypeMemo:
if (displayName.indexOf('(') >= 0) {
const matches = displayName.match(/[^()]+/g);
if (matches != null) {
displayName = matches.pop();
hocDisplayNames = matches;
}
}
break;
default:
break;
}
return {
formattedDisplayName: displayName,
hocDisplayNames,
compiledWithForget: false,
};
}
// Pulled from react-compat
// https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349
export function shallowDiffers(prev: Object, next: Object): boolean {
for (const attribute in prev) {
if (!(attribute in next)) {
return true;
}
}
for (const attribute in next) {
if (prev[attribute] !== next[attribute]) {
return true;
}
}
return false;
}
export function getInObject(object: Object, path: Array<string | number>): any {
return path.reduce((reduced: Object, attr: any): any => {
if (reduced) {
if (hasOwnProperty.call(reduced, attr)) {
return reduced[attr];
}
if (typeof reduced[Symbol.iterator] === 'function') {
// Convert iterable to array and return array[index]
//
// TRICKY
// Don't use [...spread] syntax for this purpose.
// This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values.
// Other types (e.g. typed arrays, Sets) will not spread correctly.
return Array.from(reduced)[attr];
}
}
return null;
}, object);
}
export function deletePathInObject(
object: Object,
path: Array<string | number>,
) {
const length = path.length;
const last = path[length - 1];
if (object != null) {
const parent = getInObject(object, path.slice(0, length - 1));
if (parent) {
if (isArray(parent)) {
parent.splice(((last: any): number), 1);
} else {
delete parent[last];
}
}
}
}
export function renamePathInObject(
object: Object,
oldPath: Array<string | number>,
newPath: Array<string | number>,
) {
const length = oldPath.length;
if (object != null) {
const parent = getInObject(object, oldPath.slice(0, length - 1));
if (parent) {
const lastOld = oldPath[length - 1];
const lastNew = newPath[length - 1];
parent[lastNew] = parent[lastOld];
if (isArray(parent)) {
parent.splice(((lastOld: any): number), 1);
} else {
delete parent[lastOld];
}
}
}
}
export function setInObject(
object: Object,
path: Array<string | number>,
value: any,
) {
const length = path.length;
const last = path[length - 1];
if (object != null) {
const parent = getInObject(object, path.slice(0, length - 1));
if (parent) {
parent[last] = value;
}
}
}
export type DataType =
| 'array'
| 'array_buffer'
| 'bigint'
| 'boolean'
| 'class_instance'
| 'data_view'
| 'date'
| 'function'
| 'html_all_collection'
| 'html_element'
| 'infinity'
| 'iterator'
| 'opaque_iterator'
| 'nan'
| 'null'
| 'number'
| 'object'
| 'react_element'
| 'regexp'
| 'string'
| 'symbol'
| 'typed_array'
| 'undefined'
| 'unknown';
/**
* Get a enhanced/artificial type string based on the object instance
*/
export function getDataType(data: Object): DataType {
if (data === null) {
return 'null';
} else if (data === undefined) {
return 'undefined';
}
if (isElement(data)) {
return 'react_element';
}
if (typeof HTMLElement !== 'undefined' && data instanceof HTMLElement) {
return 'html_element';
}
const type = typeof data;
switch (type) {
case 'bigint':
return 'bigint';
case 'boolean':
return 'boolean';
case 'function':
return 'function';
case 'number':
if (Number.isNaN(data)) {
return 'nan';
} else if (!Number.isFinite(data)) {
return 'infinity';
} else {
return 'number';
}
case 'object':
if (isArray(data)) {
return 'array';
} else if (ArrayBuffer.isView(data)) {
return hasOwnProperty.call(data.constructor, 'BYTES_PER_ELEMENT')
? 'typed_array'
: 'data_view';
} else if (data.constructor && data.constructor.name === 'ArrayBuffer') {
// HACK This ArrayBuffer check is gross; is there a better way?
// We could try to create a new DataView with the value.
// If it doesn't error, we know it's an ArrayBuffer,
// but this seems kind of awkward and expensive.
return 'array_buffer';
} else if (typeof data[Symbol.iterator] === 'function') {
const iterator = data[Symbol.iterator]();
if (!iterator) {
// Proxies might break assumptoins about iterators.
// See github.com/facebook/react/issues/21654
} else {
return iterator === data ? 'opaque_iterator' : 'iterator';
}
} else if (data.constructor && data.constructor.name === 'RegExp') {
return 'regexp';
} else {
// $FlowFixMe[method-unbinding]
const toStringValue = Object.prototype.toString.call(data);
if (toStringValue === '[object Date]') {
return 'date';
} else if (toStringValue === '[object HTMLAllCollection]') {
return 'html_all_collection';
}
}
if (!isPlainObject(data)) {
return 'class_instance';
}
return 'object';
case 'string':
return 'string';
case 'symbol':
return 'symbol';
case 'undefined':
if (
// $FlowFixMe[method-unbinding]
Object.prototype.toString.call(data) === '[object HTMLAllCollection]'
) {
return 'html_all_collection';
}
return 'undefined';
default:
return 'unknown';
}
}
export function getDisplayNameForReactElement(
element: React$Element<any>,
): string | null {
const elementType = typeOf(element);
switch (elementType) {
case ContextConsumer:
return 'ContextConsumer';
case ContextProvider:
return 'ContextProvider';
case ForwardRef:
return 'ForwardRef';
case Fragment:
return 'Fragment';
case Lazy:
return 'Lazy';
case Memo:
return 'Memo';
case Portal:
return 'Portal';
case Profiler:
return 'Profiler';
case StrictMode:
return 'StrictMode';
case Suspense:
return 'Suspense';
case SuspenseList:
return 'SuspenseList';
case TracingMarker:
return 'TracingMarker';
default:
const {type} = element;
if (typeof type === 'string') {
return type;
} else if (typeof type === 'function') {
return getDisplayName(type, 'Anonymous');
} else if (type != null) {
return 'NotImplementedInDevtools';
} else {
return 'Element';
}
}
}
const MAX_PREVIEW_STRING_LENGTH = 50;
function truncateForDisplay(
string: string,
length: number = MAX_PREVIEW_STRING_LENGTH,
) {
if (string.length > length) {
return string.slice(0, length) + '…';
} else {
return string;
}
}
// Attempts to mimic Chrome's inline preview for values.
// For example, the following value...
// {
// foo: 123,
// bar: "abc",
// baz: [true, false],
// qux: { ab: 1, cd: 2 }
// };
//
// Would show a preview of...
// {foo: 123, bar: "abc", baz: Array(2), qux: {…}}
//
// And the following value...
// [
// 123,
// "abc",
// [true, false],
// { foo: 123, bar: "abc" }
// ];
//
// Would show a preview of...
// [123, "abc", Array(2), {…}]
export function formatDataForPreview(
data: any,
showFormattedValue: boolean,
): string {
if (data != null && hasOwnProperty.call(data, meta.type)) {
return showFormattedValue
? data[meta.preview_long]
: data[meta.preview_short];
}
const type = getDataType(data);
switch (type) {
case 'html_element':
return `<${truncateForDisplay(data.tagName.toLowerCase())} />`;
case 'function':
return truncateForDisplay(
`ƒ ${typeof data.name === 'function' ? '' : data.name}() {}`,
);
case 'string':
return `"${data}"`;
case 'bigint':
return truncateForDisplay(data.toString() + 'n');
case 'regexp':
return truncateForDisplay(data.toString());
case 'symbol':
return truncateForDisplay(data.toString());
case 'react_element':
return `<${truncateForDisplay(
getDisplayNameForReactElement(data) || 'Unknown',
)} />`;
case 'array_buffer':
return `ArrayBuffer(${data.byteLength})`;
case 'data_view':
return `DataView(${data.buffer.byteLength})`;
case 'array':
if (showFormattedValue) {
let formatted = '';
for (let i = 0; i < data.length; i++) {
if (i > 0) {
formatted += ', ';
}
formatted += formatDataForPreview(data[i], false);
if (formatted.length > MAX_PREVIEW_STRING_LENGTH) {
// Prevent doing a lot of unnecessary iteration...
break;
}
}
return `[${truncateForDisplay(formatted)}]`;
} else {
const length = hasOwnProperty.call(data, meta.size)
? data[meta.size]
: data.length;
return `Array(${length})`;
}
case 'typed_array':
const shortName = `${data.constructor.name}(${data.length})`;
if (showFormattedValue) {
let formatted = '';
for (let i = 0; i < data.length; i++) {
if (i > 0) {
formatted += ', ';
}
formatted += data[i];
if (formatted.length > MAX_PREVIEW_STRING_LENGTH) {
// Prevent doing a lot of unnecessary iteration...
break;
}
}
return `${shortName} [${truncateForDisplay(formatted)}]`;
} else {
return shortName;
}
case 'iterator':
const name = data.constructor.name;
if (showFormattedValue) {
// TRICKY
// Don't use [...spread] syntax for this purpose.
// This project uses @babel/plugin-transform-spread in "loose" mode which only works with Array values.
// Other types (e.g. typed arrays, Sets) will not spread correctly.
const array = Array.from(data);
let formatted = '';
for (let i = 0; i < array.length; i++) {
const entryOrEntries = array[i];
if (i > 0) {
formatted += ', ';
}
// TRICKY
// Browsers display Maps and Sets differently.
// To mimic their behavior, detect if we've been given an entries tuple.
// Map(2) {"abc" => 123, "def" => 123}
// Set(2) {"abc", 123}
if (isArray(entryOrEntries)) {
const key = formatDataForPreview(entryOrEntries[0], true);
const value = formatDataForPreview(entryOrEntries[1], false);
formatted += `${key} => ${value}`;
} else {
formatted += formatDataForPreview(entryOrEntries, false);
}
if (formatted.length > MAX_PREVIEW_STRING_LENGTH) {
// Prevent doing a lot of unnecessary iteration...
break;
}
}
return `${name}(${data.size}) {${truncateForDisplay(formatted)}}`;
} else {
return `${name}(${data.size})`;
}
case 'opaque_iterator': {
return data[Symbol.toStringTag];
}
case 'date':
return data.toString();
case 'class_instance':
return data.constructor.name;
case 'object':
if (showFormattedValue) {
const keys = Array.from(getAllEnumerableKeys(data)).sort(alphaSortKeys);
let formatted = '';
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (i > 0) {
formatted += ', ';
}
formatted += `${key.toString()}: ${formatDataForPreview(
data[key],
false,
)}`;
if (formatted.length > MAX_PREVIEW_STRING_LENGTH) {
// Prevent doing a lot of unnecessary iteration...
break;
}
}
return `{${truncateForDisplay(formatted)}}`;
} else {
return '{…}';
}
case 'boolean':
case 'number':
case 'infinity':
case 'nan':
case 'null':
case 'undefined':
return data;
default:
try {
return truncateForDisplay(String(data));
} catch (error) {
return 'unserializable';
}
}
}
// Basically checking that the object only has Object in its prototype chain
export const isPlainObject = (object: Object): boolean => {
const objectPrototype = Object.getPrototypeOf(object);
if (!objectPrototype) return true;
const objectParentPrototype = Object.getPrototypeOf(objectPrototype);
return !objectParentPrototype;
};
export function backendToFrontendSerializedElementMapper(
element: SerializedElementBackend,
): SerializedElementFrontend {
const {formattedDisplayName, hocDisplayNames, compiledWithForget} =
parseElementDisplayNameFromBackend(element.displayName, element.type);
return {
...element,
displayName: formattedDisplayName,
hocDisplayNames,
compiledWithForget,
};
}
| 26.069223 | 172 | 0.615454 |
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¶m=some_value | 36.325843 | 743 | 0.727793 |
owtf | import Fixture from '../../Fixture';
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import InputTestCase from './InputTestCase';
import ReplaceEmailInput from './ReplaceEmailInput';
const React = window.React;
class TextInputFixtures extends React.Component {
render() {
return (
<FixtureSet
title="Inputs"
description="Common behavior across controlled and uncontrolled inputs">
<TestCase title="Numbers in a controlled text field with no handler">
<TestCase.Steps>
<li>Move the cursor to after "2" in the text field</li>
<li>Type ".2" into the text input</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The text field's value should not update.
</TestCase.ExpectedResult>
<Fixture>
<div className="control-box">
<fieldset>
<legend>Value as number</legend>
<input value={2} onChange={() => {}} />
</fieldset>
<fieldset>
<legend>Value as string</legend>
<input value={'2'} onChange={() => {}} />
</fieldset>
</div>
</Fixture>
<p className="footnote">
This issue was first introduced when we added extra logic to number
inputs to prevent unexpected behavior in Chrome and Safari (see the
number input test case).
</p>
</TestCase>
<TestCase
title="Required Inputs"
affectedBrowsers="Firefox"
relatedIssues="8395">
<TestCase.Steps>
<li>View this test in Firefox</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
You should{' '}
<b>
<i>not</i>
</b>{' '}
see a red aura, indicating the input is invalid.
<br />
This aura looks roughly like:
<input style={{boxShadow: '0 0 1px 1px red', marginLeft: 8}} />
</TestCase.ExpectedResult>
<Fixture>
<form className="control-box">
<fieldset>
<legend>Empty value prop string</legend>
<input value="" required={true} />
</fieldset>
<fieldset>
<legend>No value prop</legend>
<input required={true} />
</fieldset>
<fieldset>
<legend>Empty defaultValue prop string</legend>
<input required={true} defaultValue="" />
</fieldset>
<fieldset>
<legend>No value prop date input</legend>
<input type="date" required={true} />
</fieldset>
<fieldset>
<legend>Empty value prop date input</legend>
<input type="date" value="" required={true} />
</fieldset>
</form>
</Fixture>
<p className="footnote">
Checking the date type is also important because of a prior fix for
iOS Safari that involved assigning over value/defaultValue
properties of the input to prevent a display bug. This also triggers
input validation.
</p>
<p className="footnote">
The date inputs should be blank in iOS. This is not a bug.
</p>
</TestCase>
<TestCase title="Cursor when editing email inputs">
<TestCase.Steps>
<li>Type "[email protected]"</li>
<li>Select "@"</li>
<li>Type ".", to replace "@" with a period</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The text field's cursor should not jump to the end.
</TestCase.ExpectedResult>
<InputTestCase type="email" defaultValue="" />
</TestCase>
<TestCase title="Cursor when editing url inputs">
<TestCase.Steps>
<li>Type "http://www.example.com"</li>
<li>Select "www."</li>
<li>Press backspace/delete</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The text field's cursor should not jump to the end.
</TestCase.ExpectedResult>
<InputTestCase type="url" defaultValue="" />
</TestCase>
<TestCase
title="Replacing email input with text disabled input"
relatedIssues="12062">
<TestCase.Steps>
<li>Type "[email protected]"</li>
<li>Press enter</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
There should be no selection-related error in the console.
</TestCase.ExpectedResult>
<ReplaceEmailInput />
</TestCase>
<TestCase title="All inputs" description="General test of all inputs">
<InputTestCase type="text" defaultValue="Text" />
<InputTestCase type="email" defaultValue="[email protected]" />
<InputTestCase type="number" defaultValue={0} />
<InputTestCase type="url" defaultValue="http://example.com" />
<InputTestCase type="tel" defaultValue="555-555-5555" />
<InputTestCase type="color" defaultValue="#ff0000" />
<InputTestCase type="date" defaultValue="2017-01-01" />
<InputTestCase
type="datetime-local"
defaultValue="2017-01-01T01:00"
/>
<InputTestCase type="time" defaultValue="01:00" />
<InputTestCase type="month" defaultValue="2017-01" />
<InputTestCase type="week" defaultValue="2017-W01" />
<InputTestCase type="range" defaultValue={0.5} />
<InputTestCase type="password" defaultValue="" />
</TestCase>
</FixtureSet>
);
}
}
export default TextInputFixtures;
| 34.089286 | 80 | 0.543264 |
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; }
// ?sourceMappingURL=([^\s'"]+)/gm
function Component() {
const [count, setCount] = (0, _react.useState)(0);
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 18,
columnNumber: 5
}
}, /*#__PURE__*/_react.default.createElement("p", {
__source: {
fileName: _jsxFileName,
lineNumber: 19,
columnNumber: 7
}
}, "You clicked ", count, " times"), /*#__PURE__*/_react.default.createElement("button", {
onClick: () => setCount(count + 1),
__source: {
fileName: _jsxFileName,
lineNumber: 20,
columnNumber: 7
}
}, "Click me"));
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbnRhaW5pbmdTdHJpbmdTb3VyY2VNYXBwaW5nVVJMLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFFQTtBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0IscUJBQVMsQ0FBVCxDQUExQjtBQUVBLHNCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLHFCQUFnQkQsS0FBaEIsV0FERixlQUVFO0FBQVEsSUFBQSxPQUFPLEVBQUUsTUFBTUMsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUEvQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFGRixDQURGO0FBTUQiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlU3RhdGV9IGZyb20gJ3JlYWN0JztcblxuLy8gP3NvdXJjZU1hcHBpbmdVUkw9KFteXFxzJ1wiXSspL2dtXG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIChcbiAgICA8ZGl2PlxuICAgICAgPHA+WW91IGNsaWNrZWQge2NvdW50fSB0aW1lczwvcD5cbiAgICAgIDxidXR0b24gb25DbGljaz17KCkgPT4gc2V0Q291bnQoY291bnQgKyAxKX0+Q2xpY2sgbWU8L2J1dHRvbj5cbiAgICA8L2Rpdj5cbiAgKTtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJjb3VudCJdLCJtYXBwaW5ncyI6IkNBQUQ7ZTRCQ0EsQVdEQSJ9XV1dfX1dfQ== | 83.05 | 1,568 | 0.803927 |
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, FiberRoot} from './ReactInternalTypes';
import type {Lanes} from './ReactFiberLane';
import type {StackCursor} from './ReactFiberStack';
import type {Cache, SpawnedCachePool} from './ReactFiberCacheComponent';
import type {Transition} from './ReactFiberTracingMarkerComponent';
import {enableCache, enableTransitionTracing} from 'shared/ReactFeatureFlags';
import {isPrimaryRenderer} from './ReactFiberConfig';
import {createCursor, push, pop} from './ReactFiberStack';
import {
getWorkInProgressRoot,
getWorkInProgressTransitions,
} from './ReactFiberWorkLoop';
import {
createCache,
retainCache,
CacheContext,
} from './ReactFiberCacheComponent';
import ReactSharedInternals from 'shared/ReactSharedInternals';
const {ReactCurrentBatchConfig} = ReactSharedInternals;
export const NoTransition = null;
export function requestCurrentTransition(): Transition | null {
return ReactCurrentBatchConfig.transition;
}
// When retrying a Suspense/Offscreen boundary, we restore the cache that was
// used during the previous render by placing it here, on the stack.
const resumedCache: StackCursor<Cache | null> = createCursor(null);
// During the render/synchronous commit phase, we don't actually process the
// transitions. Therefore, we want to lazily combine transitions. Instead of
// comparing the arrays of transitions when we combine them and storing them
// and filtering out the duplicates, we will instead store the unprocessed transitions
// in an array and actually filter them in the passive phase.
const transitionStack: StackCursor<Array<Transition> | null> =
createCursor(null);
function peekCacheFromPool(): Cache | null {
if (!enableCache) {
return (null: any);
}
// Check if the cache pool already has a cache we can use.
// If we're rendering inside a Suspense boundary that is currently hidden,
// we should use the same cache that we used during the previous render, if
// one exists.
const cacheResumedFromPreviousRender = resumedCache.current;
if (cacheResumedFromPreviousRender !== null) {
return cacheResumedFromPreviousRender;
}
// Otherwise, check the root's cache pool.
const root = (getWorkInProgressRoot(): any);
const cacheFromRootCachePool = root.pooledCache;
return cacheFromRootCachePool;
}
export function requestCacheFromPool(renderLanes: Lanes): Cache {
// Similar to previous function, except if there's not already a cache in the
// pool, we allocate a new one.
const cacheFromPool = peekCacheFromPool();
if (cacheFromPool !== null) {
return cacheFromPool;
}
// Create a fresh cache and add it to the root cache pool. A cache can have
// multiple owners:
// - A cache pool that lives on the FiberRoot. This is where all fresh caches
// are originally created (TODO: except during refreshes, until we implement
// this correctly). The root takes ownership immediately when the cache is
// created. Conceptually, root.pooledCache is an Option<Arc<Cache>> (owned),
// and the return value of this function is a &Arc<Cache> (borrowed).
// - One of several fiber types: host root, cache boundary, suspense
// component. These retain and release in the commit phase.
const root = (getWorkInProgressRoot(): any);
const freshCache = createCache();
root.pooledCache = freshCache;
retainCache(freshCache);
if (freshCache !== null) {
root.pooledCacheLanes |= renderLanes;
}
return freshCache;
}
export function pushRootTransition(
workInProgress: Fiber,
root: FiberRoot,
renderLanes: Lanes,
) {
if (enableTransitionTracing) {
const rootTransitions = getWorkInProgressTransitions();
push(transitionStack, rootTransitions, workInProgress);
}
}
export function popRootTransition(
workInProgress: Fiber,
root: FiberRoot,
renderLanes: Lanes,
) {
if (enableTransitionTracing) {
pop(transitionStack, workInProgress);
}
}
export function pushTransition(
offscreenWorkInProgress: Fiber,
prevCachePool: SpawnedCachePool | null,
newTransitions: Array<Transition> | null,
): void {
if (enableCache) {
if (prevCachePool === null) {
push(resumedCache, resumedCache.current, offscreenWorkInProgress);
} else {
push(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
}
}
if (enableTransitionTracing) {
if (transitionStack.current === null) {
push(transitionStack, newTransitions, offscreenWorkInProgress);
} else if (newTransitions === null) {
push(transitionStack, transitionStack.current, offscreenWorkInProgress);
} else {
push(
transitionStack,
transitionStack.current.concat(newTransitions),
offscreenWorkInProgress,
);
}
}
}
export function popTransition(workInProgress: Fiber, current: Fiber | null) {
if (current !== null) {
if (enableTransitionTracing) {
pop(transitionStack, workInProgress);
}
if (enableCache) {
pop(resumedCache, workInProgress);
}
}
}
export function getPendingTransitions(): Array<Transition> | null {
if (!enableTransitionTracing) {
return null;
}
return transitionStack.current;
}
export function getSuspendedCache(): SpawnedCachePool | null {
if (!enableCache) {
return null;
}
// This function is called when a Suspense boundary suspends. It returns the
// cache that would have been used to render fresh data during this render,
// if there was any, so that we can resume rendering with the same cache when
// we receive more data.
const cacheFromPool = peekCacheFromPool();
if (cacheFromPool === null) {
return null;
}
return {
// We must also save the parent, so that when we resume we can detect
// a refresh.
parent: isPrimaryRenderer
? CacheContext._currentValue
: CacheContext._currentValue2,
pool: cacheFromPool,
};
}
export function getOffscreenDeferredCache(): SpawnedCachePool | null {
if (!enableCache) {
return null;
}
const cacheFromPool = peekCacheFromPool();
if (cacheFromPool === null) {
return null;
}
return {
// We must also store the parent, so that when we resume we can detect
// a refresh.
parent: isPrimaryRenderer
? CacheContext._currentValue
: CacheContext._currentValue2,
pool: cacheFromPool,
};
}
| 29.905213 | 86 | 0.725153 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOMServer;
let Suspense;
describe('ReactDOMServerFB', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOMServer = require('../ReactDOMServerFB');
Suspense = React.Suspense;
});
const theError = new Error('This is an error');
function Throw() {
throw theError;
}
const theInfinitePromise = new Promise(() => {});
function InfiniteSuspend() {
throw theInfinitePromise;
}
function readResult(stream) {
let result = '';
while (!ReactDOMServer.hasFinished(stream)) {
result += ReactDOMServer.renderNextChunk(stream);
}
return result;
}
it('should be able to render basic HTML', async () => {
const stream = ReactDOMServer.renderToStream(<div>hello world</div>, {
onError(x) {
console.error(x);
},
});
const result = readResult(stream);
expect(result).toMatchInlineSnapshot(`"<div>hello world</div>"`);
});
it('should emit bootstrap script src at the end', () => {
const stream = ReactDOMServer.renderToStream(<div>hello world</div>, {
bootstrapScriptContent: 'INIT();',
bootstrapScripts: ['init.js'],
bootstrapModules: ['init.mjs'],
onError(x) {
console.error(x);
},
});
const result = 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';
}
const stream = ReactDOMServer.renderToStream(
<div>
<Suspense fallback="Loading">
<Wait />
</Suspense>
</div>,
{
onError(x) {
console.error(x);
},
},
);
await jest.runAllTimers();
// Resolve the loading.
hasLoaded = true;
await resolve();
await jest.runAllTimers();
const result = readResult(stream);
expect(result).toMatchInlineSnapshot(`"<div><!--$-->Done<!--/$--></div>"`);
});
it('should throw an error when an error is thrown at the root', () => {
const reportedErrors = [];
const stream = ReactDOMServer.renderToStream(
<div>
<Throw />
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
let caughtError = null;
let result = '';
try {
result = readResult(stream);
} catch (x) {
caughtError = x;
}
expect(caughtError).toBe(theError);
expect(result).toBe('');
expect(reportedErrors).toEqual([theError]);
});
it('should throw an error when an error is thrown inside a fallback', () => {
const reportedErrors = [];
const stream = ReactDOMServer.renderToStream(
<div>
<Suspense fallback={<Throw />}>
<InfiniteSuspend />
</Suspense>
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
let caughtError = null;
let result = '';
try {
result = readResult(stream);
} catch (x) {
caughtError = x;
}
expect(caughtError).toBe(theError);
expect(result).toBe('');
expect(reportedErrors).toEqual([theError]);
});
it('should not throw an error when an error is thrown inside suspense boundary', async () => {
const reportedErrors = [];
const stream = ReactDOMServer.renderToStream(
<div>
<Suspense fallback={<div>Loading</div>}>
<Throw />
</Suspense>
</div>,
{
onError(x) {
reportedErrors.push(x);
},
},
);
const result = readResult(stream);
expect(result).toContain('Loading');
expect(reportedErrors).toEqual([theError]);
});
it('should be able to complete by aborting even if the promise never resolves', () => {
const errors = [];
const stream = ReactDOMServer.renderToStream(
<div>
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
</div>,
{
onError(x) {
errors.push(x.message);
},
},
);
const partial = ReactDOMServer.renderNextChunk(stream);
expect(partial).toContain('Loading');
ReactDOMServer.abortStream(stream);
const remaining = readResult(stream);
expect(remaining).toEqual('');
expect(errors).toEqual([
'The render was aborted by the server without a reason.',
]);
});
it('should allow setting an abort reason', () => {
const errors = [];
const stream = ReactDOMServer.renderToStream(
<div>
<Suspense fallback={<div>Loading</div>}>
<InfiniteSuspend />
</Suspense>
</div>,
{
onError(error) {
errors.push(error);
},
},
);
ReactDOMServer.abortStream(stream, theError);
expect(errors).toEqual([theError]);
});
});
| 24.470046 | 283 | 0.578176 |
owtf | import cn from 'classnames';
import semver from 'semver';
import PropTypes from 'prop-types';
import IssueList from './IssueList';
import {parse} from 'query-string';
import {semverString} from './propTypes';
const React = window.React;
const propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.node.isRequired,
resolvedIn: semverString,
introducedIn: semverString,
resolvedBy: PropTypes.string,
};
class TestCase extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
complete: false,
};
}
handleChange = e => {
this.setState({
complete: e.target.checked,
});
};
render() {
const {
title,
description,
introducedIn,
resolvedIn,
resolvedBy,
affectedBrowsers,
relatedIssues,
children,
} = this.props;
let {complete} = this.state;
const {version} = parse(window.location.search);
const isTestFixed =
!version || !resolvedIn || semver.gte(version, resolvedIn);
complete = !isTestFixed || complete;
return (
<section className={cn('test-case', complete && 'test-case--complete')}>
<h2 className="test-case__title type-subheading">
<label>
<input
className="test-case__title__check"
type="checkbox"
checked={complete}
onChange={this.handleChange}
/>{' '}
{title}
</label>
</h2>
<dl className="test-case__details">
{introducedIn && <dt>First broken in: </dt>}
{introducedIn && (
<dd>
<a
href={'https://github.com/facebook/react/tag/v' + introducedIn}>
<code>{introducedIn}</code>
</a>
</dd>
)}
{resolvedIn && <dt>First supported in: </dt>}
{resolvedIn && (
<dd>
<a href={'https://github.com/facebook/react/tag/v' + resolvedIn}>
<code>{resolvedIn}</code>
</a>
</dd>
)}
{resolvedBy && <dt>Fixed by: </dt>}
{resolvedBy && (
<dd>
<a
href={
'https://github.com/facebook/react/pull/' +
resolvedBy.slice(1)
}>
<code>{resolvedBy}</code>
</a>
</dd>
)}
{affectedBrowsers && <dt>Affected browsers: </dt>}
{affectedBrowsers && <dd>{affectedBrowsers}</dd>}
{relatedIssues && <dt>Related Issues: </dt>}
{relatedIssues && (
<dd>
<IssueList issues={relatedIssues} />
</dd>
)}
</dl>
<p className="test-case__desc">{description}</p>
<div className="test-case__body">
{!isTestFixed && (
<p className="test-case__invalid-version">
<strong>Note:</strong> This test case was fixed in a later version
of React. This test is not expected to pass for the selected
version, and that's ok!
</p>
)}
{children}
</div>
</section>
);
}
}
TestCase.propTypes = propTypes;
TestCase.Steps = class extends React.Component {
render() {
const {children} = this.props;
return (
<div>
<h3>Steps to reproduce:</h3>
<ol>{children}</ol>
</div>
);
}
};
TestCase.ExpectedResult = class extends React.Component {
render() {
const {children} = this.props;
return (
<div>
<h3>Expected Result:</h3>
<p>{children}</p>
</div>
);
}
};
export default TestCase;
| 23.187097 | 80 | 0.51254 |
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
*/
// Parsing source and source maps is done in a Web Worker
// because parsing is CPU intensive and should not block the UI thread.
//
// Fetching source and source map files is intentionally done on the UI thread
// so that loaded source files can reuse the browser's Network cache.
// Requests made from within an extension do not share the page's Network cache,
// but messages can be sent from the UI thread to the content script
// which can make a request from the page's context (with caching).
//
// Some overhead may be incurred sharing (serializing) the loaded data between contexts,
// but less than fetching the file to begin with,
// and in some cases we can avoid serializing the source code at all
// (e.g. when we are in an environment that supports our custom metadata format).
//
// The overall flow of this file is such:
// 1. Find the Set of source files defining the hooks and load them all.
// Then for each source file, do the following:
//
// a. Search loaded source file to see if a source map is available.
// If so, load that file and pass it to a Worker for parsing.
// The source map is used to retrieve the original source,
// which is then also parsed in the Worker to infer hook names.
// This is less ideal because parsing a full source map is slower,
// since we need to evaluate the mappings in order to map the runtime code to the original source,
// but at least the eventual source that we parse to an AST is small/fast.
//
// b. If no source map, pass the full source to a Worker for parsing.
// Use the source to infer hook names.
// This is the least optimal route as parsing the full source is very CPU intensive.
//
// In the future, we may add an additional optimization the above sequence.
// This check would come before the source map check:
//
// a. Search loaded source file to see if a custom React metadata file is available.
// If so, load that file and pass it to a Worker for parsing and extracting.
// This is the fastest option since our custom metadata file is much smaller than a full source map,
// and there is no need to convert runtime code to the original source.
import {__DEBUG__} from 'react-devtools-shared/src/constants';
import {getHookSourceLocationKey} from 'react-devtools-shared/src/hookNamesCache';
import {sourceMapIncludesSource} from '../SourceMapUtils';
import {
withAsyncPerfMeasurements,
withCallbackPerfMeasurements,
withSyncPerfMeasurements,
} from 'react-devtools-shared/src/PerformanceLoggingUtils';
import type {
HooksNode,
HookSource,
HooksTree,
} from 'react-debug-tools/src/ReactDebugHooks';
import type {MixedSourceMap} from '../SourceMapTypes';
import type {FetchFileWithCaching} from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext';
// Prefer a cached albeit stale response to reduce download time.
// We wouldn't want to load/parse a newer version of the source (even if one existed).
const FETCH_OPTIONS = {cache: 'force-cache'};
const MAX_SOURCE_LENGTH = 100_000_000;
export type HookSourceAndMetadata = {
// Generated by react-debug-tools.
hookSource: HookSource,
// Compiled code (React components or custom hooks) containing primitive hook calls.
runtimeSourceCode: string | null,
// Same as hookSource.fileName but guaranteed to be non-null.
runtimeSourceURL: string,
// Raw source map JSON.
// Either decoded from an inline source map or loaded from an externa source map file.
// Sources without source maps won't have this.
sourceMapJSON: MixedSourceMap | null,
// External URL of source map.
// Sources without source maps (or with inline source maps) won't have this.
sourceMapURL: string | null,
};
export type LocationKeyToHookSourceAndMetadata = Map<
string,
HookSourceAndMetadata,
>;
export type HooksList = Array<HooksNode>;
export async function loadSourceAndMetadata(
hooksList: HooksList,
fetchFileWithCaching: FetchFileWithCaching | null,
): Promise<LocationKeyToHookSourceAndMetadata> {
return withAsyncPerfMeasurements('loadSourceAndMetadata()', async () => {
const locationKeyToHookSourceAndMetadata = withSyncPerfMeasurements(
'initializeHookSourceAndMetadata',
() => initializeHookSourceAndMetadata(hooksList),
);
await withAsyncPerfMeasurements('loadSourceFiles()', () =>
loadSourceFiles(locationKeyToHookSourceAndMetadata, fetchFileWithCaching),
);
await withAsyncPerfMeasurements('extractAndLoadSourceMapJSON()', () =>
extractAndLoadSourceMapJSON(locationKeyToHookSourceAndMetadata),
);
// At this point, we've loaded JS source (text) and source map (JSON).
// The remaining works (parsing these) is CPU intensive and should be done in a worker.
return locationKeyToHookSourceAndMetadata;
});
}
function decodeBase64String(encoded: string): Object {
if (typeof atob === 'function') {
return atob(encoded);
} else if (
typeof Buffer !== 'undefined' &&
Buffer !== null &&
typeof Buffer.from === 'function'
) {
return Buffer.from(encoded, 'base64');
} else {
throw Error('Cannot decode base64 string');
}
}
function extractAndLoadSourceMapJSON(
locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata,
): Promise<Array<$Call<<T>(p: Promise<T> | T) => T, Promise<void>>>> {
// Deduplicate fetches, since there can be multiple location keys per source map.
const dedupedFetchPromises = new Map<string, Promise<$FlowFixMe>>();
if (__DEBUG__) {
console.log(
'extractAndLoadSourceMapJSON() load',
locationKeyToHookSourceAndMetadata.size,
'source maps',
);
}
const setterPromises = [];
locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => {
const sourceMapRegex = / ?sourceMappingURL=([^\s'"]+)/gm;
const runtimeSourceCode =
((hookSourceAndMetadata.runtimeSourceCode: any): string);
// TODO (named hooks) Search for our custom metadata first.
// If it's found, we should use it rather than source maps.
// TODO (named hooks) If this RegExp search is slow, we could try breaking it up
// first using an indexOf(' sourceMappingURL=') to find the start of the comment
// (probably at the end of the file) and then running the RegExp on the remaining substring.
let sourceMappingURLMatch = withSyncPerfMeasurements(
'sourceMapRegex.exec(runtimeSourceCode)',
() => sourceMapRegex.exec(runtimeSourceCode),
);
if (sourceMappingURLMatch == null) {
if (__DEBUG__) {
console.log('extractAndLoadSourceMapJSON() No source map found');
}
// Maybe file has not been transformed; we'll try to parse it as-is in parseSourceAST().
} else {
const externalSourceMapURLs = [];
while (sourceMappingURLMatch != null) {
const {runtimeSourceURL} = hookSourceAndMetadata;
const sourceMappingURL = sourceMappingURLMatch[1];
const hasInlineSourceMap = sourceMappingURL.indexOf('base64,') >= 0;
if (hasInlineSourceMap) {
try {
// TODO (named hooks) deduplicate parsing in this branch (similar to fetching in the other branch)
// since there can be multiple location keys per source map.
// Web apps like Code Sandbox embed multiple inline source maps.
// In this case, we need to loop through and find the right one.
// We may also need to trim any part of this string that isn't based64 encoded data.
const trimmed = ((sourceMappingURL.match(
/base64,([a-zA-Z0-9+\/=]+)/,
): any): Array<string>)[1];
const decoded = withSyncPerfMeasurements(
'decodeBase64String()',
() => decodeBase64String(trimmed),
);
const sourceMapJSON = withSyncPerfMeasurements(
'JSON.parse(decoded)',
() => JSON.parse(decoded),
);
if (__DEBUG__) {
console.groupCollapsed(
'extractAndLoadSourceMapJSON() Inline source map',
);
console.log(sourceMapJSON);
console.groupEnd();
}
// Hook source might be a URL like "https://4syus.csb.app/src/App.js"
// Parsed source map might be a partial path like "src/App.js"
if (sourceMapIncludesSource(sourceMapJSON, runtimeSourceURL)) {
hookSourceAndMetadata.sourceMapJSON = sourceMapJSON;
// OPTIMIZATION If we've located a source map for this source,
// we'll use it to retrieve the original source (to extract hook names).
// We only fall back to parsing the full source code is when there's no source map.
// The source is (potentially) very large,
// So we can avoid the overhead of serializing it unnecessarily.
hookSourceAndMetadata.runtimeSourceCode = null;
break;
}
} catch (error) {
// We've likely encountered a string in the source code that looks like a source map but isn't.
// Maybe the source code contains a "sourceMappingURL" comment or soething similar.
// In either case, let's skip this and keep looking.
}
} else {
externalSourceMapURLs.push(sourceMappingURL);
}
// If the first source map we found wasn't a match, check for more.
sourceMappingURLMatch = withSyncPerfMeasurements(
'sourceMapRegex.exec(runtimeSourceCode)',
() => sourceMapRegex.exec(runtimeSourceCode),
);
}
if (hookSourceAndMetadata.sourceMapJSON === null) {
externalSourceMapURLs.forEach((sourceMappingURL, index) => {
if (index !== externalSourceMapURLs.length - 1) {
// Files with external source maps should only have a single source map.
// More than one result might indicate an edge case,
// like a string in the source code that matched our "sourceMappingURL" regex.
// We should just skip over cases like this.
console.warn(
`More than one external source map detected in the source file; skipping "${sourceMappingURL}"`,
);
return;
}
const {runtimeSourceURL} = hookSourceAndMetadata;
let url = sourceMappingURL;
if (!url.startsWith('http') && !url.startsWith('/')) {
// Resolve paths relative to the location of the file name
const lastSlashIdx = runtimeSourceURL.lastIndexOf('/');
if (lastSlashIdx !== -1) {
const baseURL = runtimeSourceURL.slice(
0,
runtimeSourceURL.lastIndexOf('/'),
);
url = `${baseURL}/${url}`;
}
}
hookSourceAndMetadata.sourceMapURL = url;
const fetchPromise =
dedupedFetchPromises.get(url) ||
fetchFile(url).then(
sourceMapContents => {
const sourceMapJSON = withSyncPerfMeasurements(
'JSON.parse(sourceMapContents)',
() => JSON.parse(sourceMapContents),
);
return sourceMapJSON;
},
// In this case, we fall back to the assumption that the source has no source map.
// This might indicate an (unlikely) edge case that had no source map,
// but contained the string "sourceMappingURL".
error => null,
);
if (__DEBUG__) {
if (!dedupedFetchPromises.has(url)) {
console.log(
`extractAndLoadSourceMapJSON() External source map "${url}"`,
);
}
}
dedupedFetchPromises.set(url, fetchPromise);
setterPromises.push(
fetchPromise.then(sourceMapJSON => {
if (sourceMapJSON !== null) {
hookSourceAndMetadata.sourceMapJSON = sourceMapJSON;
// OPTIMIZATION If we've located a source map for this source,
// we'll use it to retrieve the original source (to extract hook names).
// We only fall back to parsing the full source code is when there's no source map.
// The source is (potentially) very large,
// So we can avoid the overhead of serializing it unnecessarily.
hookSourceAndMetadata.runtimeSourceCode = null;
}
}),
);
});
}
}
});
return Promise.all(setterPromises);
}
function fetchFile(
url: string,
markName: string = 'fetchFile',
): Promise<string> {
return withCallbackPerfMeasurements(`${markName}("${url}")`, done => {
return new Promise((resolve, reject) => {
fetch(url, FETCH_OPTIONS).then(
response => {
if (response.ok) {
response
.text()
.then(text => {
done();
resolve(text);
})
.catch(error => {
if (__DEBUG__) {
console.log(
`${markName}() Could not read text for url "${url}"`,
);
}
done();
reject(null);
});
} else {
if (__DEBUG__) {
console.log(`${markName}() Got bad response for url "${url}"`);
}
done();
reject(null);
}
},
error => {
if (__DEBUG__) {
console.log(`${markName}() Could not fetch file: ${error.message}`);
}
done();
reject(null);
},
);
});
});
}
export function hasNamedHooks(hooksTree: HooksTree): boolean {
for (let i = 0; i < hooksTree.length; i++) {
const hook = hooksTree[i];
if (!isUnnamedBuiltInHook(hook)) {
return true;
}
if (hook.subHooks.length > 0) {
if (hasNamedHooks(hook.subHooks)) {
return true;
}
}
}
return false;
}
export function flattenHooksList(hooksTree: HooksTree): HooksList {
const hooksList: HooksList = [];
withSyncPerfMeasurements('flattenHooksList()', () => {
flattenHooksListImpl(hooksTree, hooksList);
});
if (__DEBUG__) {
console.log('flattenHooksList() hooksList:', hooksList);
}
return hooksList;
}
function flattenHooksListImpl(
hooksTree: HooksTree,
hooksList: Array<HooksNode>,
): void {
for (let i = 0; i < hooksTree.length; i++) {
const hook = hooksTree[i];
if (isUnnamedBuiltInHook(hook)) {
// No need to load source code or do any parsing for unnamed hooks.
if (__DEBUG__) {
console.log('flattenHooksListImpl() Skipping unnamed hook', hook);
}
continue;
}
hooksList.push(hook);
if (hook.subHooks.length > 0) {
flattenHooksListImpl(hook.subHooks, hooksList);
}
}
}
function initializeHookSourceAndMetadata(
hooksList: Array<HooksNode>,
): LocationKeyToHookSourceAndMetadata {
// Create map of unique source locations (file names plus line and column numbers) to metadata about hooks.
const locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata =
new Map();
for (let i = 0; i < hooksList.length; i++) {
const hook = hooksList[i];
const hookSource = hook.hookSource;
if (hookSource == null) {
// Older versions of react-debug-tools don't include this information.
// In this case, we can't continue.
throw Error('Hook source code location not found.');
}
const locationKey = getHookSourceLocationKey(hookSource);
if (!locationKeyToHookSourceAndMetadata.has(locationKey)) {
// Can't be null because getHookSourceLocationKey() would have thrown
const runtimeSourceURL = ((hookSource.fileName: any): string);
const hookSourceAndMetadata: HookSourceAndMetadata = {
hookSource,
runtimeSourceCode: null,
runtimeSourceURL,
sourceMapJSON: null,
sourceMapURL: null,
};
locationKeyToHookSourceAndMetadata.set(
locationKey,
hookSourceAndMetadata,
);
}
}
return locationKeyToHookSourceAndMetadata;
}
// Determines whether incoming hook is a primitive hook that gets assigned to variables.
function isUnnamedBuiltInHook(hook: HooksNode) {
return ['Effect', 'ImperativeHandle', 'LayoutEffect', 'DebugValue'].includes(
hook.name,
);
}
function loadSourceFiles(
locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata,
fetchFileWithCaching: FetchFileWithCaching | null,
): Promise<Array<$Call<<T>(p: Promise<T> | T) => T, Promise<void>>>> {
// Deduplicate fetches, since there can be multiple location keys per file.
const dedupedFetchPromises = new Map<string, Promise<$FlowFixMe>>();
const setterPromises = [];
locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => {
const {runtimeSourceURL} = hookSourceAndMetadata;
let fetchFileFunction = fetchFile;
if (fetchFileWithCaching != null) {
// If a helper function has been injected to fetch with caching,
// use it to fetch the (already loaded) source file.
fetchFileFunction = url => {
return withAsyncPerfMeasurements(
`fetchFileWithCaching("${url}")`,
() => {
return ((fetchFileWithCaching: any): FetchFileWithCaching)(url);
},
);
};
}
const fetchPromise =
dedupedFetchPromises.get(runtimeSourceURL) ||
fetchFileFunction(runtimeSourceURL).then(runtimeSourceCode => {
// TODO (named hooks) Re-think this; the main case where it matters is when there's no source-maps,
// because then we need to parse the full source file as an AST.
if (runtimeSourceCode.length > MAX_SOURCE_LENGTH) {
throw Error('Source code too large to parse');
}
if (__DEBUG__) {
console.groupCollapsed(
`loadSourceFiles() runtimeSourceURL "${runtimeSourceURL}"`,
);
console.log(runtimeSourceCode);
console.groupEnd();
}
return runtimeSourceCode;
});
dedupedFetchPromises.set(runtimeSourceURL, fetchPromise);
setterPromises.push(
fetchPromise.then(runtimeSourceCode => {
hookSourceAndMetadata.runtimeSourceCode = runtimeSourceCode;
}),
);
});
return Promise.all(setterPromises);
}
| 35.426357 | 122 | 0.638681 |
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 {SettingsContext} from './SettingsContext';
import styles from './SettingsShared.css';
export default function DebuggingSettings(_: {}): React.Node {
const {
appendComponentStack,
breakOnConsoleErrors,
hideConsoleLogsInStrictMode,
setAppendComponentStack,
setBreakOnConsoleErrors,
setShowInlineWarningsAndErrors,
showInlineWarningsAndErrors,
setHideConsoleLogsInStrictMode,
} = useContext(SettingsContext);
return (
<div className={styles.Settings}>
<div className={styles.Setting}>
<label>
<input
type="checkbox"
checked={appendComponentStack}
onChange={({currentTarget}) =>
setAppendComponentStack(currentTarget.checked)
}
/>{' '}
Append component stacks to console warnings and errors.
</label>
</div>
<div className={styles.Setting}>
<label>
<input
type="checkbox"
checked={showInlineWarningsAndErrors}
onChange={({currentTarget}) =>
setShowInlineWarningsAndErrors(currentTarget.checked)
}
/>{' '}
Show inline warnings and errors.
</label>
</div>
<div className={styles.Setting}>
<label>
<input
type="checkbox"
checked={breakOnConsoleErrors}
onChange={({currentTarget}) =>
setBreakOnConsoleErrors(currentTarget.checked)
}
/>{' '}
Break on warnings
</label>
</div>
<div className={styles.Setting}>
<label>
<input
type="checkbox"
checked={hideConsoleLogsInStrictMode}
onChange={({currentTarget}) =>
setHideConsoleLogsInStrictMode(currentTarget.checked)
}
/>{' '}
Hide logs during second render in Strict Mode
</label>
</div>
</div>
);
}
| 25.797619 | 67 | 0.582667 |
Advanced-Infrastructure-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 loadChunk(chunkId: string, filename: string): Promise<mixed> {
return __webpack_chunk_load__(chunkId);
}
| 24.230769 | 78 | 0.706422 |
null | 'use strict';
const fetch = require('node-fetch');
const {writeFileSync} = require('fs');
const stories = 50;
async function getStory(id) {
const storyRes = await fetch(
`https://hacker-news.firebaseio.com/v0/item/${id}.json`
);
return await storyRes.json();
}
async function getTopStories() {
const topStoriesRes = await fetch(
'https://hacker-news.firebaseio.com/v0/topstories.js'
);
const topStoriesIds = await topStoriesRes.json();
const topStories = [];
for (let i = 0; i < stories; i++) {
const topStoriesId = topStoriesIds[i];
topStories.push(await getStory(topStoriesId));
}
writeFileSync(
'top-stories.json',
`window.stories = ${JSON.stringify(topStories)}`
);
}
getTopStories();
| 20.852941 | 59 | 0.672507 |
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';
let React;
let ReactDOM;
let ReactDOMClient;
let ReactDOMServer;
let ReactDOMServerBrowser;
let waitForAll;
let act;
// These tests rely both on ReactDOMServer and ReactDOM.
// If a test only needs ReactDOMServer, put it in ReactServerRendering-test instead.
describe('ReactDOMServerHydration', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMClient = require('react-dom/client');
ReactDOMServer = require('react-dom/server');
ReactDOMServerBrowser = require('react-dom/server.browser');
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
act = InternalTestUtils.act;
});
it('should have the correct mounting behavior (new hydrate API)', () => {
let mountCount = 0;
let numClicks = 0;
class TestComponent extends React.Component {
spanRef = React.createRef();
componentDidMount() {
mountCount++;
}
click = () => {
numClicks++;
};
render() {
return (
<span ref={this.spanRef} onClick={this.click}>
Name: {this.props.name}
</span>
);
}
}
const element = document.createElement('div');
document.body.appendChild(element);
try {
ReactDOM.render(<TestComponent />, element);
let lastMarkup = element.innerHTML;
// Exercise the update path. Markup should not change,
// but some lifecycle methods should be run again.
ReactDOM.render(<TestComponent name="x" />, element);
expect(mountCount).toEqual(1);
// Unmount and remount. We should get another mount event and
// we should get different markup, as the IDs are unique each time.
ReactDOM.unmountComponentAtNode(element);
expect(element.innerHTML).toEqual('');
ReactDOM.render(<TestComponent name="x" />, element);
expect(mountCount).toEqual(2);
expect(element.innerHTML).not.toEqual(lastMarkup);
// Now kill the node and render it on top of server-rendered markup, as if
// we used server rendering. We should mount again, but the markup should
// be unchanged. We will append a sentinel at the end of innerHTML to be
// sure that innerHTML was not changed.
ReactDOM.unmountComponentAtNode(element);
expect(element.innerHTML).toEqual('');
lastMarkup = ReactDOMServer.renderToString(<TestComponent name="x" />);
element.innerHTML = lastMarkup;
let instance = ReactDOM.hydrate(<TestComponent name="x" />, element);
expect(mountCount).toEqual(3);
expect(element.innerHTML).toBe(lastMarkup);
// Ensure the events system works after mount into server markup
expect(numClicks).toEqual(0);
instance.spanRef.current.click();
expect(numClicks).toEqual(1);
ReactDOM.unmountComponentAtNode(element);
expect(element.innerHTML).toEqual('');
// Now simulate a situation where the app is not idempotent. React should
// warn but do the right thing.
element.innerHTML = lastMarkup;
expect(() => {
instance = ReactDOM.hydrate(<TestComponent name="y" />, element);
}).toErrorDev('Text content did not match. Server: "x" Client: "y"');
expect(mountCount).toEqual(4);
expect(element.innerHTML.length > 0).toBe(true);
expect(element.innerHTML).not.toEqual(lastMarkup);
// Ensure the events system works after markup mismatch.
expect(numClicks).toEqual(1);
instance.spanRef.current.click();
expect(numClicks).toEqual(2);
} finally {
document.body.removeChild(element);
}
});
// We have a polyfill for autoFocus on the client, but we intentionally don't
// want it to call focus() when hydrating because this can mess up existing
// focus before the JS has loaded.
it('should emit autofocus on the server but not focus() when hydrating', () => {
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(
<input autoFocus={true} />,
);
expect(element.firstChild.autofocus).toBe(true);
// It should not be called on mount.
element.firstChild.focus = jest.fn();
ReactDOM.hydrate(<input autoFocus={true} />, element);
expect(element.firstChild.focus).not.toHaveBeenCalled();
// Or during an update.
ReactDOM.render(<input autoFocus={true} />, element);
expect(element.firstChild.focus).not.toHaveBeenCalled();
});
it('should not focus on either server or client with autofocus={false}', () => {
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(
<input autoFocus={false} />,
);
expect(element.firstChild.autofocus).toBe(false);
element.firstChild.focus = jest.fn();
ReactDOM.hydrate(<input autoFocus={false} />, element);
expect(element.firstChild.focus).not.toHaveBeenCalled();
ReactDOM.render(<input autoFocus={false} />, element);
expect(element.firstChild.focus).not.toHaveBeenCalled();
});
// Regression test for https://github.com/facebook/react/issues/11726
it('should not focus on either server or client with autofocus={false} even if there is a markup mismatch', () => {
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(
<button autoFocus={false}>server</button>,
);
expect(element.firstChild.autofocus).toBe(false);
element.firstChild.focus = jest.fn();
expect(() =>
ReactDOM.hydrate(<button autoFocus={false}>client</button>, element),
).toErrorDev(
'Warning: Text content did not match. Server: "server" Client: "client"',
);
expect(element.firstChild.focus).not.toHaveBeenCalled();
});
it('should warn when the style property differs', () => {
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(
<div style={{textDecoration: 'none', color: 'black', height: '10px'}} />,
);
expect(element.firstChild.style.textDecoration).toBe('none');
expect(element.firstChild.style.color).toBe('black');
expect(() =>
ReactDOM.hydrate(
<div
style={{textDecoration: 'none', color: 'white', height: '10px'}}
/>,
element,
),
).toErrorDev(
'Warning: Prop `style` did not match. Server: ' +
'"text-decoration:none;color:black;height:10px" Client: ' +
'"text-decoration:none;color:white;height:10px"',
);
});
// @gate !disableIEWorkarounds || !__DEV__
it('should not warn when the style property differs on whitespace or order in IE', () => {
document.documentMode = 11;
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
try {
const element = document.createElement('div');
// Simulate IE normalizing the style attribute. IE makes it equal to
// what's available under `node.style.cssText`.
element.innerHTML =
'<div style="height: 10px; color: black; text-decoration: none;"></div>';
// We don't expect to see false positive warnings.
// https://github.com/facebook/react/issues/11807
ReactDOM.hydrate(
<div
style={{textDecoration: 'none', color: 'black', height: '10px'}}
/>,
element,
);
} finally {
delete document.documentMode;
}
});
it('should warn when the style property differs on whitespace in non-IE browsers', () => {
const element = document.createElement('div');
element.innerHTML =
'<div style="text-decoration: none; color: black; height: 10px;"></div>';
expect(() =>
ReactDOM.hydrate(
<div
style={{textDecoration: 'none', color: 'black', height: '10px'}}
/>,
element,
),
).toErrorDev(
'Warning: Prop `style` did not match. Server: ' +
'"text-decoration: none; color: black; height: 10px;" Client: ' +
'"text-decoration:none;color:black;height:10px"',
);
});
it('should throw rendering portals on the server', () => {
const div = document.createElement('div');
expect(() => {
ReactDOMServer.renderToString(
<div>{ReactDOM.createPortal(<div />, div)}</div>,
);
}).toThrow(
'Portals are not currently supported by the server renderer. ' +
'Render them conditionally so that they only appear on the client render.',
);
});
it('should be able to render and hydrate Mode components', () => {
class ComponentWithWarning extends React.Component {
componentWillMount() {
// Expected warning
}
render() {
return 'Hi';
}
}
const markup = (
<React.StrictMode>
<ComponentWithWarning />
</React.StrictMode>
);
const element = document.createElement('div');
expect(() => {
element.innerHTML = ReactDOMServer.renderToString(markup);
}).toWarnDev('componentWillMount has been renamed');
expect(element.textContent).toBe('Hi');
expect(() => {
ReactDOM.hydrate(markup, element);
}).toWarnDev('componentWillMount has been renamed', {
withoutStack: true,
});
expect(element.textContent).toBe('Hi');
});
it('should be able to render and hydrate forwardRef components', () => {
const FunctionComponent = ({label, forwardedRef}) => (
<div ref={forwardedRef}>{label}</div>
);
const WrappedFunctionComponent = React.forwardRef((props, ref) => (
<FunctionComponent {...props} forwardedRef={ref} />
));
const ref = React.createRef();
const markup = <WrappedFunctionComponent ref={ref} label="Hi" />;
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(markup);
expect(element.textContent).toBe('Hi');
expect(ref.current).toBe(null);
ReactDOM.hydrate(markup, element);
expect(element.textContent).toBe('Hi');
expect(ref.current.tagName).toBe('DIV');
});
it('should be able to render and hydrate Profiler components', () => {
const callback = jest.fn();
const markup = (
<React.Profiler id="profiler" onRender={callback}>
<div>Hi</div>
</React.Profiler>
);
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(markup);
expect(element.textContent).toBe('Hi');
expect(callback).not.toHaveBeenCalled();
ReactDOM.hydrate(markup, element);
expect(element.textContent).toBe('Hi');
if (__DEV__) {
expect(callback).toHaveBeenCalledTimes(1);
const [id, phase] = callback.mock.calls[0];
expect(id).toBe('profiler');
expect(phase).toBe('mount');
} else {
expect(callback).toHaveBeenCalledTimes(0);
}
});
// Regression test for https://github.com/facebook/react/issues/11423
it('should ignore noscript content on the client and not warn about mismatches', () => {
const callback = jest.fn();
const TestComponent = ({onRender}) => {
onRender();
return <div>Enable JavaScript to run this app.</div>;
};
const markup = (
<noscript>
<TestComponent onRender={callback} />
</noscript>
);
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(markup);
expect(callback).toHaveBeenCalledTimes(1);
expect(element.textContent).toBe(
'<div>Enable JavaScript to run this app.</div>',
);
// On the client we want to keep the existing markup, but not render the
// actual elements for performance reasons and to avoid for example
// downloading images. This should also not warn for hydration mismatches.
ReactDOM.hydrate(markup, element);
expect(callback).toHaveBeenCalledTimes(1);
expect(element.textContent).toBe(
'<div>Enable JavaScript to run this app.</div>',
);
});
it('should be able to use lazy components after hydrating', async () => {
const Lazy = React.lazy(
() =>
new Promise(resolve => {
setTimeout(
() =>
resolve({
default: function World() {
return 'world';
},
}),
1000,
);
}),
);
class HelloWorld extends React.Component {
state = {isClient: false};
componentDidMount() {
this.setState({
isClient: true,
});
}
render() {
return (
<div>
Hello{' '}
{this.state.isClient && (
<React.Suspense fallback="loading">
<Lazy />
</React.Suspense>
)}
</div>
);
}
}
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(<HelloWorld />);
expect(element.textContent).toBe('Hello ');
ReactDOM.hydrate(<HelloWorld />, element);
expect(element.textContent).toBe('Hello loading');
// Resolve Lazy component
await act(() => jest.runAllTimers());
expect(element.textContent).toBe('Hello world');
});
it('does not re-enter hydration after committing the first one', async () => {
const finalHTML = ReactDOMServer.renderToString(<div />);
const container = document.createElement('div');
container.innerHTML = finalHTML;
const root = await act(() =>
ReactDOMClient.hydrateRoot(container, <div />),
);
await act(() => root.render(null));
// This should not reenter hydration state and therefore not trigger hydration
// warnings.
await act(() => root.render(<div />));
});
it('Suspense + hydration in legacy mode', () => {
const element = document.createElement('div');
element.innerHTML = '<div><div>Hello World</div></div>';
const div = element.firstChild.firstChild;
const ref = React.createRef();
expect(() =>
ReactDOM.hydrate(
<div>
<React.Suspense fallback={null}>
<div ref={ref}>Hello World</div>
</React.Suspense>
</div>,
element,
),
).toErrorDev(
'Warning: Did not expect server HTML to contain a <div> in <div>.',
);
// The content should've been client rendered and replaced the
// existing div.
expect(ref.current).not.toBe(div);
// The HTML should be the same though.
expect(element.innerHTML).toBe('<div><div>Hello World</div></div>');
});
it('Suspense + hydration in legacy mode (at root)', () => {
const element = document.createElement('div');
element.innerHTML = '<div>Hello World</div>';
const div = element.firstChild;
const ref = React.createRef();
ReactDOM.hydrate(
<React.Suspense fallback={null}>
<div ref={ref}>Hello World</div>
</React.Suspense>,
element,
);
// The content should've been client rendered.
expect(ref.current).not.toBe(div);
// Unfortunately, since we don't delete the tail at the root, a duplicate will remain.
expect(element.innerHTML).toBe(
'<div>Hello World</div><div>Hello World</div>',
);
});
it('Suspense + hydration in legacy mode with no fallback', () => {
const element = document.createElement('div');
element.innerHTML = '<div>Hello World</div>';
const div = element.firstChild;
const ref = React.createRef();
ReactDOM.hydrate(
<React.Suspense>
<div ref={ref}>Hello World</div>
</React.Suspense>,
element,
);
// The content should've been client rendered.
expect(ref.current).not.toBe(div);
// Unfortunately, since we don't delete the tail at the root, a duplicate will remain.
expect(element.innerHTML).toBe(
'<div>Hello World</div><div>Hello World</div>',
);
});
// regression test for https://github.com/facebook/react/issues/17170
it('should not warn if dangerouslySetInnerHtml=undefined', () => {
const domElement = document.createElement('div');
const reactElement = (
<div dangerouslySetInnerHTML={undefined}>
<p>Hello, World!</p>
</div>
);
const markup = ReactDOMServer.renderToStaticMarkup(reactElement);
domElement.innerHTML = markup;
ReactDOM.hydrate(reactElement, domElement);
expect(domElement.innerHTML).toEqual(markup);
});
it('should warn if innerHTML mismatches with dangerouslySetInnerHTML=undefined and children on the client', () => {
const domElement = document.createElement('div');
const markup = ReactDOMServer.renderToStaticMarkup(
<div dangerouslySetInnerHTML={{__html: '<p>server</p>'}} />,
);
domElement.innerHTML = markup;
expect(() => {
ReactDOM.hydrate(
<div dangerouslySetInnerHTML={undefined}>
<p>client</p>
</div>,
domElement,
);
expect(domElement.innerHTML).not.toEqual(markup);
}).toErrorDev(
'Warning: Text content did not match. Server: "server" Client: "client"',
);
});
it('should warn if innerHTML mismatches with dangerouslySetInnerHTML=undefined on the client', () => {
const domElement = document.createElement('div');
const markup = ReactDOMServer.renderToStaticMarkup(
<div dangerouslySetInnerHTML={{__html: '<p>server</p>'}} />,
);
domElement.innerHTML = markup;
expect(() => {
ReactDOM.hydrate(<div dangerouslySetInnerHTML={undefined} />, domElement);
expect(domElement.innerHTML).not.toEqual(markup);
}).toErrorDev(
'Warning: Did not expect server HTML to contain a <p> in <div>',
);
});
it('should warn when hydrating read-only properties', () => {
const readOnlyProperties = [
'offsetParent',
'offsetTop',
'offsetLeft',
'offsetWidth',
'offsetHeight',
'isContentEditable',
'outerText',
'outerHTML',
];
readOnlyProperties.forEach(readOnlyProperty => {
const props = {};
props[readOnlyProperty] = 'hello';
const jsx = React.createElement('my-custom-element', props);
const element = document.createElement('div');
element.innerHTML = ReactDOMServer.renderToString(jsx);
if (gate(flags => flags.enableCustomElementPropertySupport)) {
expect(() => ReactDOM.hydrate(jsx, element)).toErrorDev(
`Warning: Assignment to read-only property will result in a no-op: \`${readOnlyProperty}\``,
);
} else {
ReactDOM.hydrate(jsx, element);
}
});
});
// @gate enableCustomElementPropertySupport
it('should not re-assign properties on hydration', () => {
const container = document.createElement('div');
document.body.appendChild(container);
const jsx = React.createElement('my-custom-element', {
str: 'string',
obj: {foo: 'bar'},
});
container.innerHTML = ReactDOMServer.renderToString(jsx);
const customElement = container.querySelector('my-custom-element');
// Install setters to activate `in` check
Object.defineProperty(customElement, 'str', {
set: function (x) {
this._str = x;
},
get: function () {
return this._str;
},
});
Object.defineProperty(customElement, 'obj', {
set: function (x) {
this._obj = x;
},
get: function () {
return this._obj;
},
});
ReactDOM.hydrate(jsx, container);
expect(customElement.getAttribute('str')).toBe('string');
expect(customElement.getAttribute('obj')).toBe(null);
expect(customElement.str).toBe(undefined);
expect(customElement.obj).toBe(undefined);
});
it('refers users to apis that support Suspense when something suspends', async () => {
const theInfinitePromise = new Promise(() => {});
function InfiniteSuspend() {
throw theInfinitePromise;
}
function App({isClient}) {
return (
<div>
<React.Suspense fallback={'fallback'}>
{isClient ? 'resolved' : <InfiniteSuspend />}
</React.Suspense>
</div>
);
}
const container = document.createElement('div');
container.innerHTML = ReactDOMServer.renderToString(
<App isClient={false} />,
);
const errors = [];
ReactDOMClient.hydrateRoot(container, <App isClient={true} />, {
onRecoverableError(error, errorInfo) {
errors.push(error.message);
},
});
await waitForAll([]);
expect(errors.length).toBe(1);
if (__DEV__) {
expect(errors[0]).toBe(
'The server did not finish this Suspense boundary: The server used "renderToString" ' +
'which does not support Suspense. If you intended for this Suspense boundary to render ' +
'the fallback content on the server consider throwing an Error somewhere within the ' +
'Suspense boundary. If you intended to have the server wait for the suspended component ' +
'please switch to "renderToPipeableStream" which supports Suspense on the server',
);
} else {
expect(errors[0]).toBe(
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
);
}
});
it('refers users to apis that support Suspense when something suspends (browser)', async () => {
const theInfinitePromise = new Promise(() => {});
function InfiniteSuspend() {
throw theInfinitePromise;
}
function App({isClient}) {
return (
<div>
<React.Suspense fallback={'fallback'}>
{isClient ? 'resolved' : <InfiniteSuspend />}
</React.Suspense>
</div>
);
}
const container = document.createElement('div');
container.innerHTML = ReactDOMServerBrowser.renderToString(
<App isClient={false} />,
);
const errors = [];
ReactDOMClient.hydrateRoot(container, <App isClient={true} />, {
onRecoverableError(error, errorInfo) {
errors.push(error.message);
},
});
await waitForAll([]);
expect(errors.length).toBe(1);
if (__DEV__) {
expect(errors[0]).toBe(
'The server did not finish this Suspense boundary: The server used "renderToString" ' +
'which does not support Suspense. If you intended for this Suspense boundary to render ' +
'the fallback content on the server consider throwing an Error somewhere within the ' +
'Suspense boundary. If you intended to have the server wait for the suspended component ' +
'please switch to "renderToReadableStream" which supports Suspense on the server',
);
} else {
expect(errors[0]).toBe(
'The server could not finish this Suspense boundary, likely due to ' +
'an error during server rendering. Switched to client rendering.',
);
}
});
// @gate enableFormActions
it('allows rendering extra hidden inputs in a form', async () => {
const element = document.createElement('div');
element.innerHTML =
'<form>' +
'<input type="hidden" /><input type="hidden" name="a" value="A" />' +
'<input type="hidden" /><input type="submit" name="b" value="B" />' +
'<input type="hidden" /><button name="c" value="C"></button>' +
'<input type="hidden" />' +
'</form>';
const form = element.firstChild;
const ref = React.createRef();
const a = React.createRef();
const b = React.createRef();
const c = React.createRef();
await act(async () => {
ReactDOMClient.hydrateRoot(
element,
<form ref={ref}>
<input type="hidden" name="a" value="A" ref={a} />
<input type="submit" name="b" value="B" ref={b} />
<button name="c" value="C" ref={c} />
</form>,
);
});
// The content should not have been client rendered.
expect(ref.current).toBe(form);
expect(a.current.name).toBe('a');
expect(a.current.value).toBe('A');
expect(b.current.name).toBe('b');
expect(b.current.value).toBe('B');
expect(c.current.name).toBe('c');
expect(c.current.value).toBe('C');
});
// @gate enableFormActions
it('allows rendering extra hidden inputs immediately before a text instance', async () => {
const element = document.createElement('div');
element.innerHTML =
'<button><input name="a" value="A" type="hidden" />Click <!-- -->me</button>';
const button = element.firstChild;
const ref = React.createRef();
const extraText = 'me';
await act(() => {
ReactDOMClient.hydrateRoot(
element,
<button ref={ref}>Click {extraText}</button>,
);
});
expect(ref.current).toBe(button);
});
});
| 32.278146 | 117 | 0.626612 |
Python-Penetration-Testing-for-Developers | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactNoop;
let waitForAll;
// This is a new feature in Fiber so I put it in its own test file. It could
// probably move to one of the other test files once it is official.
describe('ReactTopLevelText', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
const InternalTestUtils = require('internal-test-utils');
waitForAll = InternalTestUtils.waitForAll;
});
it('should render a component returning strings directly from render', async () => {
const Text = ({value}) => value;
ReactNoop.render(<Text value="foo" />);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput('foo');
});
it('should render a component returning numbers directly from render', async () => {
const Text = ({value}) => value;
ReactNoop.render(<Text value={10} />);
await waitForAll([]);
expect(ReactNoop).toMatchRenderedOutput('10');
});
});
| 27.697674 | 86 | 0.670722 |
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 {memo, useCallback, useContext} from 'react';
import {areEqual} from 'react-window';
import {minBarWidth} from './constants';
import {getGradientColor} from './utils';
import ChartNode from './ChartNode';
import {SettingsContext} from '../Settings/SettingsContext';
import type {ItemData} from './CommitRanked';
type Props = {
data: ItemData,
index: number,
style: Object,
};
function CommitRankedListItem({data, index, style}: Props) {
const {
chartData,
onElementMouseEnter,
onElementMouseLeave,
scaleX,
selectedFiberIndex,
selectFiber,
width,
} = data;
const node = chartData.nodes[index];
const {lineHeight} = useContext(SettingsContext);
const handleClick = useCallback(
(event: $FlowFixMe) => {
event.stopPropagation();
const {id, name} = node;
selectFiber(id, name);
},
[node, selectFiber],
);
const handleMouseEnter = () => {
const {id, name} = node;
onElementMouseEnter({id, name});
};
const handleMouseLeave = () => {
onElementMouseLeave();
};
// List items are absolutely positioned using the CSS "top" attribute.
// The "left" value will always be 0.
// Since height is fixed, and width is based on the node's duration,
// We can ignore those values as well.
const top = parseInt(style.top, 10);
return (
<ChartNode
color={getGradientColor(node.value / chartData.maxValue)}
height={lineHeight}
isDimmed={index < selectedFiberIndex}
key={node.id}
label={node.label}
onClick={handleClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
width={Math.max(minBarWidth, scaleX(node.value, width))}
x={0}
y={top}
/>
);
}
export default (memo(
CommitRankedListItem,
areEqual,
): React.ComponentType<Props>);
| 23.081395 | 72 | 0.663285 |
GWT-Penetration-Testing-Toolset | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
// Reach styles need to come before any component styles.
// This makes overriding the styles simpler.
import '@reach/menu-button/styles.css';
import '@reach/tooltip/styles.css';
import * as React from 'react';
import {useCallback, useEffect, useLayoutEffect, useMemo, useRef} from 'react';
import Store from '../store';
import {
BridgeContext,
ContextMenuContext,
StoreContext,
OptionsContext,
} from './context';
import Components from './Components/Components';
import Profiler from './Profiler/Profiler';
import TabBar from './TabBar';
import {SettingsContextController} from './Settings/SettingsContext';
import {TreeContextController} from './Components/TreeContext';
import ViewElementSourceContext from './Components/ViewElementSourceContext';
import ViewSourceContext from './Components/ViewSourceContext';
import FetchFileWithCachingContext from './Components/FetchFileWithCachingContext';
import HookNamesModuleLoaderContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext';
import {ProfilerContextController} from './Profiler/ProfilerContext';
import {TimelineContextController} from 'react-devtools-timeline/src/TimelineContext';
import {ModalDialogContextController} from './ModalDialog';
import ReactLogo from './ReactLogo';
import UnsupportedBridgeProtocolDialog from './UnsupportedBridgeProtocolDialog';
import UnsupportedVersionDialog from './UnsupportedVersionDialog';
import WarnIfLegacyBackendDetected from './WarnIfLegacyBackendDetected';
import {useLocalStorage} from './hooks';
import ThemeProvider from './ThemeProvider';
import {LOCAL_STORAGE_DEFAULT_TAB_KEY} from '../../constants';
import {logEvent} from '../../Logger';
import styles from './DevTools.css';
import './root.css';
import type {InspectedElement} from 'react-devtools-shared/src/frontend/types';
import type {FetchFileWithCaching} from './Components/FetchFileWithCachingContext';
import type {HookNamesModuleLoaderFunction} from 'react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type {BrowserTheme} from 'react-devtools-shared/src/frontend/types';
export type TabID = 'components' | 'profiler';
export type ViewElementSource = (
id: number,
inspectedElement: InspectedElement,
) => void;
export type ViewUrlSource = (url: string, row: number, column: number) => void;
export type ViewAttributeSource = (
id: number,
path: Array<string | number>,
) => void;
export type CanViewElementSource = (
inspectedElement: InspectedElement,
) => boolean;
export type Props = {
bridge: FrontendBridge,
browserTheme?: BrowserTheme,
canViewElementSourceFunction?: ?CanViewElementSource,
defaultTab?: TabID,
enabledInspectedElementContextMenu?: boolean,
showTabBar?: boolean,
store: Store,
warnIfLegacyBackendDetected?: boolean,
warnIfUnsupportedVersionDetected?: boolean,
viewAttributeSourceFunction?: ?ViewAttributeSource,
viewElementSourceFunction?: ?ViewElementSource,
viewUrlSourceFunction?: ?ViewUrlSource,
readOnly?: boolean,
hideSettings?: boolean,
hideToggleErrorAction?: boolean,
hideToggleSuspenseAction?: boolean,
hideLogAction?: boolean,
hideViewSourceAction?: boolean,
// This property is used only by the web extension target.
// The built-in tab UI is hidden in that case, in favor of the browser's own panel tabs.
// This is done to save space within the app.
// Because of this, the extension needs to be able to change which tab is active/rendered.
overrideTab?: TabID,
// To avoid potential multi-root trickiness, the web extension uses portals to render tabs.
// The root <DevTools> app is rendered in the top-level extension window,
// but individual tabs (e.g. Components, Profiling) can be rendered into portals within their browser panels.
componentsPortalContainer?: Element,
profilerPortalContainer?: Element,
// Loads and parses source maps for function components
// and extracts hook "names" based on the variables the hook return values get assigned to.
// Not every DevTools build can load source maps, so this property is optional.
fetchFileWithCaching?: ?FetchFileWithCaching,
// TODO (Webpack 5) Hopefully we can remove this prop after the Webpack 5 migration.
hookNamesModuleLoaderFunction?: ?HookNamesModuleLoaderFunction,
};
const componentsTab = {
id: ('components': TabID),
icon: 'components',
label: 'Components',
title: 'React Components',
};
const profilerTab = {
id: ('profiler': TabID),
icon: 'profiler',
label: 'Profiler',
title: 'React Profiler',
};
const tabs = [componentsTab, profilerTab];
export default function DevTools({
bridge,
browserTheme = 'light',
canViewElementSourceFunction,
componentsPortalContainer,
defaultTab = 'components',
enabledInspectedElementContextMenu = false,
fetchFileWithCaching,
hookNamesModuleLoaderFunction,
overrideTab,
profilerPortalContainer,
showTabBar = false,
store,
warnIfLegacyBackendDetected = false,
warnIfUnsupportedVersionDetected = false,
viewAttributeSourceFunction,
viewElementSourceFunction,
viewUrlSourceFunction,
readOnly,
hideSettings,
hideToggleErrorAction,
hideToggleSuspenseAction,
hideLogAction,
hideViewSourceAction,
}: Props): React.Node {
const [currentTab, setTab] = useLocalStorage<TabID>(
LOCAL_STORAGE_DEFAULT_TAB_KEY,
defaultTab,
);
let tab = currentTab;
if (overrideTab != null) {
tab = overrideTab;
}
const selectTab = useCallback(
(tabId: TabID) => {
// We show the TabBar when DevTools is NOT rendered as a browser extension.
// In this case, we want to capture when people select tabs with the TabBar.
// When DevTools is rendered as an extension, we capture this event when
// the browser devtools panel changes.
if (showTabBar === true) {
if (tabId === 'components') {
logEvent({event_name: 'selected-components-tab'});
} else {
logEvent({event_name: 'selected-profiler-tab'});
}
}
setTab(tabId);
},
[setTab, showTabBar],
);
const options = useMemo(
() => ({
readOnly: readOnly || false,
hideSettings: hideSettings || false,
hideToggleErrorAction: hideToggleErrorAction || false,
hideToggleSuspenseAction: hideToggleSuspenseAction || false,
hideLogAction: hideLogAction || false,
hideViewSourceAction: hideViewSourceAction || false,
}),
[
readOnly,
hideSettings,
hideToggleErrorAction,
hideToggleSuspenseAction,
hideLogAction,
hideViewSourceAction,
],
);
const viewElementSource = useMemo(
() => ({
canViewElementSourceFunction: canViewElementSourceFunction || null,
viewElementSourceFunction: viewElementSourceFunction || null,
}),
[canViewElementSourceFunction, viewElementSourceFunction],
);
const viewSource = useMemo(
() => ({
viewUrlSourceFunction: viewUrlSourceFunction || null,
// todo(blakef): Add inspect(...) method here and remove viewElementSource
// to consolidate source code inspection.
}),
[viewUrlSourceFunction],
);
const contextMenu = useMemo(
() => ({
isEnabledForInspectedElement: enabledInspectedElementContextMenu,
viewAttributeSourceFunction: viewAttributeSourceFunction || null,
}),
[enabledInspectedElementContextMenu, viewAttributeSourceFunction],
);
const devToolsRef = useRef<HTMLElement | null>(null);
useEffect(() => {
if (!showTabBar) {
return;
}
const div = devToolsRef.current;
if (div === null) {
return;
}
const ownerWindow = div.ownerDocument.defaultView;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey) {
switch (event.key) {
case '1':
selectTab(tabs[0].id);
event.preventDefault();
event.stopPropagation();
break;
case '2':
selectTab(tabs[1].id);
event.preventDefault();
event.stopPropagation();
break;
}
}
};
ownerWindow.addEventListener('keydown', handleKeyDown);
return () => {
ownerWindow.removeEventListener('keydown', handleKeyDown);
};
}, [showTabBar]);
useLayoutEffect(() => {
return () => {
try {
// Shut the Bridge down synchronously (during unmount).
bridge.shutdown();
} catch (error) {
// Attempting to use a disconnected port.
}
};
}, [bridge]);
useEffect(() => {
logEvent({event_name: 'loaded-dev-tools'});
}, []);
return (
<BridgeContext.Provider value={bridge}>
<StoreContext.Provider value={store}>
<OptionsContext.Provider value={options}>
<ContextMenuContext.Provider value={contextMenu}>
<ModalDialogContextController>
<SettingsContextController
browserTheme={browserTheme}
componentsPortalContainer={componentsPortalContainer}
profilerPortalContainer={profilerPortalContainer}>
<ViewElementSourceContext.Provider value={viewElementSource}>
<ViewSourceContext.Provider value={viewSource}>
<HookNamesModuleLoaderContext.Provider
value={hookNamesModuleLoaderFunction || null}>
<FetchFileWithCachingContext.Provider
value={fetchFileWithCaching || null}>
<TreeContextController>
<ProfilerContextController>
<TimelineContextController>
<ThemeProvider>
<div
className={styles.DevTools}
ref={devToolsRef}
data-react-devtools-portal-root={true}>
{showTabBar && (
<div className={styles.TabBar}>
<ReactLogo />
<span className={styles.DevToolsVersion}>
{process.env.DEVTOOLS_VERSION}
</span>
<div className={styles.Spacer} />
<TabBar
currentTab={tab}
id="DevTools"
selectTab={selectTab}
tabs={tabs}
type="navigation"
/>
</div>
)}
<div
className={styles.TabContent}
hidden={tab !== 'components'}>
<Components
portalContainer={
componentsPortalContainer
}
/>
</div>
<div
className={styles.TabContent}
hidden={tab !== 'profiler'}>
<Profiler
portalContainer={profilerPortalContainer}
/>
</div>
</div>
</ThemeProvider>
</TimelineContextController>
</ProfilerContextController>
</TreeContextController>
</FetchFileWithCachingContext.Provider>
</HookNamesModuleLoaderContext.Provider>
</ViewSourceContext.Provider>
</ViewElementSourceContext.Provider>
</SettingsContextController>
<UnsupportedBridgeProtocolDialog />
{warnIfLegacyBackendDetected && <WarnIfLegacyBackendDetected />}
{warnIfUnsupportedVersionDetected && <UnsupportedVersionDialog />}
</ModalDialogContextController>
</ContextMenuContext.Provider>
</OptionsContext.Provider>
</StoreContext.Provider>
</BridgeContext.Provider>
);
}
| 35.816619 | 132 | 0.618773 |
Python-Penetration-Testing-Cookbook | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireDefault(require("react"));
var _useTheme = _interopRequireDefault(require("./useTheme"));
var _jsxFileName = "";
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function Component() {
const theme = (0, _useTheme.default)();
return /*#__PURE__*/_react.default.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 16,
columnNumber: 10
}
}, "theme: ", theme);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVBLFNBQUFBLFNBQUEsR0FBQTtBQUNBLFFBQUFDLEtBQUEsR0FBQSx3QkFBQTtBQUVBLHNCQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUFBQSxLQUFBLENBQUE7QUFDQSIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnO1xuaW1wb3J0IHVzZVRoZW1lIGZyb20gJy4vdXNlVGhlbWUnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCB0aGVtZSA9IHVzZVRoZW1lKCk7XG5cbiAgcmV0dXJuIDxkaXY+dGhlbWU6IHt0aGVtZX08L2Rpdj47XG59XG4iXX0= | 57.538462 | 920 | 0.850099 |
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 Badge from './Badge';
import ForgetBadge from './ForgetBadge';
import IndexableDisplayName from './IndexableDisplayName';
import styles from './IndexableElementBadges.css';
type Props = {
hocDisplayNames: Array<string> | null,
compiledWithForget: boolean,
elementID: number,
className?: string,
};
export default function IndexableElementBadges({
compiledWithForget,
hocDisplayNames,
elementID,
className = '',
}: Props): React.Node {
if (
!compiledWithForget &&
(hocDisplayNames == null || hocDisplayNames.length === 0)
) {
return null;
}
return (
<div className={`${styles.Root} ${className}`}>
{compiledWithForget && (
<ForgetBadge indexable={true} elementID={elementID} />
)}
{hocDisplayNames != null && hocDisplayNames.length > 0 && (
<Badge>
<IndexableDisplayName
displayName={hocDisplayNames[0]}
id={elementID}
/>
</Badge>
)}
{hocDisplayNames != null && hocDisplayNames.length > 1 && (
<div className={styles.ExtraLabel}>+{hocDisplayNames.length - 1}</div>
)}
</div>
);
}
| 22.525424 | 78 | 0.635184 |
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.
*/
let didWarnValueNull = false;
export function validateProperties(type, props) {
if (__DEV__) {
if (type !== 'input' && type !== 'textarea' && type !== 'select') {
return;
}
if (props != null && props.value === null && !didWarnValueNull) {
didWarnValueNull = true;
if (type === 'select' && props.multiple) {
console.error(
'`value` prop on `%s` should not be null. ' +
'Consider using an empty array when `multiple` is set to `true` ' +
'to clear the component or `undefined` for uncontrolled components.',
type,
);
} else {
console.error(
'`value` prop on `%s` should not be null. ' +
'Consider using an empty string to clear the component or `undefined` ' +
'for uncontrolled components.',
type,
);
}
}
}
}
| 28.805556 | 85 | 0.564366 |
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 {isStartish, isMoveish, isEndish} from './ResponderTopLevelEventTypes';
/**
* Tracks the position and time of each active touch by `touch.identifier`. We
* should typically only see IDs in the range of 1-20 because IDs get recycled
* when touches end and start again.
*/
type TouchRecord = {
touchActive: boolean,
startPageX: number,
startPageY: number,
startTimeStamp: number,
currentPageX: number,
currentPageY: number,
currentTimeStamp: number,
previousPageX: number,
previousPageY: number,
previousTimeStamp: number,
};
const MAX_TOUCH_BANK = 20;
const touchBank: Array<TouchRecord> = [];
const touchHistory = {
touchBank,
numberActiveTouches: 0,
// If there is only one active touch, we remember its location. This prevents
// us having to loop through all of the touches all the time in the most
// common case.
indexOfSingleActiveTouch: -1,
mostRecentTimeStamp: 0,
};
type Touch = {
identifier: ?number,
pageX: number,
pageY: number,
timestamp: number,
...
};
type TouchEvent = {
changedTouches: Array<Touch>,
touches: Array<Touch>,
...
};
function timestampForTouch(touch: Touch): number {
// The legacy internal implementation provides "timeStamp", which has been
// renamed to "timestamp". Let both work for now while we iron it out
// TODO (evv): rename timeStamp to timestamp in internal code
return (touch: any).timeStamp || touch.timestamp;
}
/**
* TODO: Instead of making gestures recompute filtered velocity, we could
* include a built in velocity computation that can be reused globally.
*/
function createTouchRecord(touch: Touch): TouchRecord {
return {
touchActive: true,
startPageX: touch.pageX,
startPageY: touch.pageY,
startTimeStamp: timestampForTouch(touch),
currentPageX: touch.pageX,
currentPageY: touch.pageY,
currentTimeStamp: timestampForTouch(touch),
previousPageX: touch.pageX,
previousPageY: touch.pageY,
previousTimeStamp: timestampForTouch(touch),
};
}
function resetTouchRecord(touchRecord: TouchRecord, touch: Touch): void {
touchRecord.touchActive = true;
touchRecord.startPageX = touch.pageX;
touchRecord.startPageY = touch.pageY;
touchRecord.startTimeStamp = timestampForTouch(touch);
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchRecord.previousPageX = touch.pageX;
touchRecord.previousPageY = touch.pageY;
touchRecord.previousTimeStamp = timestampForTouch(touch);
}
function getTouchIdentifier({identifier}: Touch): number {
if (identifier == null) {
throw new Error('Touch object is missing identifier.');
}
if (__DEV__) {
if (identifier > MAX_TOUCH_BANK) {
console.error(
'Touch identifier %s is greater than maximum supported %s which causes ' +
'performance issues backfilling array locations for all of the indices.',
identifier,
MAX_TOUCH_BANK,
);
}
}
return identifier;
}
function recordTouchStart(touch: Touch): void {
const identifier = getTouchIdentifier(touch);
const touchRecord = touchBank[identifier];
if (touchRecord) {
resetTouchRecord(touchRecord, touch);
} else {
touchBank[identifier] = createTouchRecord(touch);
}
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
}
function recordTouchMove(touch: Touch): void {
const touchRecord = touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = true;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
if (__DEV__) {
console.warn(
'Cannot record touch move without a touch start.\n' +
'Touch Move: %s\n' +
'Touch Bank: %s',
printTouch(touch),
printTouchBank(),
);
}
}
}
function recordTouchEnd(touch: Touch): void {
const touchRecord = touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = false;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
if (__DEV__) {
console.warn(
'Cannot record touch end without a touch start.\n' +
'Touch End: %s\n' +
'Touch Bank: %s',
printTouch(touch),
printTouchBank(),
);
}
}
}
function printTouch(touch: Touch): string {
return JSON.stringify({
identifier: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
timestamp: timestampForTouch(touch),
});
}
function printTouchBank(): string {
let printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
if (touchBank.length > MAX_TOUCH_BANK) {
printed += ' (original size: ' + touchBank.length + ')';
}
return printed;
}
let instrumentationCallback: ?(string, TouchEvent) => void;
const ResponderTouchHistoryStore = {
/**
* Registers a listener which can be used to instrument every touch event.
*/
instrument(callback: (string, TouchEvent) => void): void {
instrumentationCallback = callback;
},
recordTouchTrack(topLevelType: string, nativeEvent: TouchEvent): void {
if (instrumentationCallback != null) {
instrumentationCallback(topLevelType, nativeEvent);
}
if (isMoveish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchMove);
} else if (isStartish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchStart);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
touchHistory.indexOfSingleActiveTouch =
nativeEvent.touches[0].identifier;
}
} else if (isEndish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchEnd);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
for (let i = 0; i < touchBank.length; i++) {
const touchTrackToCheck = touchBank[i];
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
touchHistory.indexOfSingleActiveTouch = i;
break;
}
}
if (__DEV__) {
const activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
if (activeRecord == null || !activeRecord.touchActive) {
console.error('Cannot find single active touch.');
}
}
}
}
},
touchHistory,
};
export default ResponderTouchHistoryStore;
| 30.004219 | 83 | 0.698108 |
null | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export type ModuleLoading = null;
export function prepareDestinationWithChunks(
moduleLoading: ModuleLoading,
chunks: mixed,
nonce: ?string,
) {
// In the browser we don't need to prepare our destination since the browser is the Destination
}
| 23.052632 | 97 | 0.730263 |
owtf | module.exports = {
presets: [
[
'@babel/react',
{
runtime: 'automatic',
development: process.env.BABEL_ENV === 'development',
},
],
],
plugins: ['@babel/plugin-transform-modules-commonjs'],
};
| 17.615385 | 61 | 0.53112 |
Hands-On-Penetration-Testing-with-Python | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
/**
* 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.
*
*
*/
function Component() {
const [count] = require('react').useState(0);
return count;
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJyZXF1aXJlIiwidXNlU3RhdGUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFBQTs7Ozs7Ozs7QUFTTyxTQUFTQSxTQUFULEdBQXFCO0FBQzFCLFFBQU0sQ0FBQ0MsS0FBRCxJQUFVQyxPQUFPLENBQUMsT0FBRCxDQUFQLENBQWlCQyxRQUFqQixDQUEwQixDQUExQixDQUFoQjs7QUFFQSxTQUFPRixLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50XSA9IHJlcXVpcmUoJ3JlYWN0JykudXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIGNvdW50O1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiJdLCJtYXBwaW5ncyI6IkNBQUQifV1dXX0= | 63.047619 | 944 | 0.895833 |
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
*/
module.exports = {
showErrorDialog: jest.fn(),
};
| 19.307692 | 66 | 0.684411 |
owtf | import React, {createRef, PureComponent} from 'react';
const SPEED = 0.003 / Math.PI;
const FRAMES = 10;
export default class Clock extends PureComponent {
faceRef = createRef();
arcGroupRef = createRef();
clockHandRef = createRef();
frame = null;
hitCounter = 0;
rotation = 0;
t0 = Date.now();
arcs = [];
animate = () => {
const now = Date.now();
const td = now - this.t0;
this.rotation = (this.rotation + SPEED * td) % (2 * Math.PI);
this.t0 = now;
this.arcs.push({rotation: this.rotation, td});
let lx, ly, tx, ty;
if (this.arcs.length > FRAMES) {
this.arcs.forEach(({rotation, td}, i) => {
lx = tx;
ly = ty;
const r = 145;
tx = 155 + r * Math.cos(rotation);
ty = 155 + r * Math.sin(rotation);
const bigArc = SPEED * td < Math.PI ? '0' : '1';
const path = `M${tx} ${ty}A${r} ${r} 0 ${bigArc} 0 ${lx} ${ly}L155 155`;
const hue = 120 - Math.min(120, td / 4);
const colour = `hsl(${hue}, 100%, ${60 - i * (30 / FRAMES)}%)`;
if (i !== 0) {
const arcEl = this.arcGroupRef.current.children[i - 1];
arcEl.setAttribute('d', path);
arcEl.setAttribute('fill', colour);
}
});
this.clockHandRef.current.setAttribute('d', `M155 155L${tx} ${ty}`);
this.arcs.shift();
}
if (this.hitCounter > 0) {
this.faceRef.current.setAttribute(
'fill',
`hsla(0, 0%, ${this.hitCounter}%, 0.95)`
);
this.hitCounter -= 1;
} else {
this.hitCounter = 0;
this.faceRef.current.setAttribute('fill', 'hsla(0, 0%, 5%, 0.95)');
}
this.frame = requestAnimationFrame(this.animate);
};
componentDidMount() {
this.frame = requestAnimationFrame(this.animate);
if (this.faceRef.current) {
this.faceRef.current.addEventListener('click', this.handleClick);
}
}
componentDidUpdate() {
console.log('componentDidUpdate()', this.faceRef.current);
}
componentWillUnmount() {
this.faceRef.current.removeEventListener('click', this.handleClick);
if (this.frame) {
cancelAnimationFrame(this.frame);
}
}
handleClick = e => {
e.stopPropagation();
this.hitCounter = 50;
};
render() {
const paths = new Array(FRAMES);
for (let i = 0; i < FRAMES; i++) {
paths.push(<path className="arcHand" key={i} />);
}
return (
<div className="stutterer">
<svg height="310" width="310">
<circle
className="clockFace"
onClick={this.handleClick}
cx={155}
cy={155}
r={150}
ref={this.faceRef}
/>
<g ref={this.arcGroupRef}>{paths}</g>
<path className="clockHand" ref={this.clockHandRef} />
</svg>
</div>
);
}
}
| 25.783019 | 80 | 0.545807 |
PenetrationTestingScripts | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
describe('Stylex plugin utils', () => {
let getStyleXData;
let styleElements;
function defineStyles(style) {
const styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.appendChild(document.createTextNode(style));
styleElements.push(styleElement);
document.head.appendChild(styleElement);
}
beforeEach(() => {
getStyleXData = require('../utils').getStyleXData;
styleElements = [];
});
afterEach(() => {
styleElements.forEach(styleElement => {
document.head.removeChild(styleElement);
});
});
it('should gracefully handle empty values', () => {
expect(getStyleXData(null)).toMatchInlineSnapshot(`
{
"resolvedStyles": {},
"sources": [],
}
`);
expect(getStyleXData(undefined)).toMatchInlineSnapshot(`
{
"resolvedStyles": {},
"sources": [],
}
`);
expect(getStyleXData('')).toMatchInlineSnapshot(`
{
"resolvedStyles": {},
"sources": [],
}
`);
expect(getStyleXData([undefined])).toMatchInlineSnapshot(`
{
"resolvedStyles": {},
"sources": [],
}
`);
});
it('should support simple style objects', () => {
defineStyles(`
.foo {
display: flex;
}
.bar: {
align-items: center;
}
.baz {
flex-direction: center;
}
`);
expect(
getStyleXData({
// The source/module styles are defined in
Example__style: 'Example__style',
// Map of CSS style to StyleX class name, booleans, or nested structures
display: 'foo',
flexDirection: 'baz',
alignItems: 'bar',
}),
).toMatchInlineSnapshot(`
{
"resolvedStyles": {
"alignItems": "center",
"display": "flex",
"flexDirection": "center",
},
"sources": [
"Example__style",
],
}
`);
});
it('should support multiple style objects', () => {
defineStyles(`
.foo {
display: flex;
}
.bar: {
align-items: center;
}
.baz {
flex-direction: center;
}
`);
expect(
getStyleXData([
{Example1__style: 'Example1__style', display: 'foo'},
{
Example2__style: 'Example2__style',
flexDirection: 'baz',
alignItems: 'bar',
},
]),
).toMatchInlineSnapshot(`
{
"resolvedStyles": {
"alignItems": "center",
"display": "flex",
"flexDirection": "center",
},
"sources": [
"Example1__style",
"Example2__style",
],
}
`);
});
it('should filter empty rules', () => {
defineStyles(`
.foo {
display: flex;
}
.bar: {
align-items: center;
}
.baz {
flex-direction: center;
}
`);
expect(
getStyleXData([
false,
{Example1__style: 'Example1__style', display: 'foo'},
false,
false,
{
Example2__style: 'Example2__style',
flexDirection: 'baz',
alignItems: 'bar',
},
false,
]),
).toMatchInlineSnapshot(`
{
"resolvedStyles": {
"alignItems": "center",
"display": "flex",
"flexDirection": "center",
},
"sources": [
"Example1__style",
"Example2__style",
],
}
`);
});
it('should support pseudo-classes', () => {
defineStyles(`
.foo {
color: black;
}
.bar: {
color: blue;
}
.baz {
text-decoration: none;
}
`);
expect(
getStyleXData({
// The source/module styles are defined in
Example__style: 'Example__style',
// Map of CSS style to StyleX class name, booleans, or nested structures
color: 'foo',
':hover': {
color: 'bar',
textDecoration: 'baz',
},
}),
).toMatchInlineSnapshot(`
{
"resolvedStyles": {
":hover": {
"color": "blue",
"textDecoration": "none",
},
"color": "black",
},
"sources": [
"Example__style",
],
}
`);
});
it('should support nested selectors', () => {
defineStyles(`
.foo {
display: flex;
}
.bar: {
align-items: center;
}
.baz {
flex-direction: center;
}
`);
expect(
getStyleXData([
{Example1__style: 'Example1__style', display: 'foo'},
false,
[
false,
{Example2__style: 'Example2__style', flexDirection: 'baz'},
{Example3__style: 'Example3__style', alignItems: 'bar'},
],
false,
]),
).toMatchInlineSnapshot(`
{
"resolvedStyles": {
"alignItems": "center",
"display": "flex",
"flexDirection": "center",
},
"sources": [
"Example1__style",
"Example2__style",
"Example3__style",
],
}
`);
});
});
| 19.759542 | 80 | 0.477933 |
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 typeof ReactTestRenderer from 'react-test-renderer';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type Store from 'react-devtools-shared/src/devtools/store';
import type {ProfilingDataFrontend} from 'react-devtools-shared/src/devtools/views/Profiler/types';
import type {ElementType} from 'react-devtools-shared/src/frontend/types';
export function act(
callback: Function,
recursivelyFlush: boolean = true,
): void {
const {act: actTestRenderer} = require('react-test-renderer');
// Use `require('react-dom/test-utils').act` as a fallback for React 17, which can be used in integration tests for React DevTools.
const actDOM =
require('react').unstable_act || require('react-dom/test-utils').act;
actDOM(() => {
actTestRenderer(() => {
callback();
});
});
if (recursivelyFlush) {
// Flush Bridge operations
while (jest.getTimerCount() > 0) {
actDOM(() => {
actTestRenderer(() => {
jest.runAllTimers();
});
});
}
}
}
export async function actAsync(
cb: () => *,
recursivelyFlush: boolean = true,
): Promise<void> {
const {act: actTestRenderer} = require('react-test-renderer');
// Use `require('react-dom/test-utils').act` as a fallback for React 17, which can be used in integration tests for React DevTools.
const actDOM =
require('react').unstable_act || require('react-dom/test-utils').act;
await actDOM(async () => {
await actTestRenderer(async () => {
await cb();
});
});
if (recursivelyFlush) {
while (jest.getTimerCount() > 0) {
await actDOM(async () => {
await actTestRenderer(async () => {
jest.runAllTimers();
});
});
}
} else {
await actDOM(async () => {
await actTestRenderer(async () => {
jest.runOnlyPendingTimers();
});
});
}
}
export function beforeEachProfiling(): void {
// Mock React's timing information so that test runs are predictable.
jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_mock'));
// DevTools itself uses performance.now() to offset commit times
// so they appear relative to when profiling was started in the UI.
jest
.spyOn(performance, 'now')
.mockImplementation(
jest.requireActual('scheduler/unstable_mock').unstable_now,
);
}
export function createDisplayNameFilter(
source: string,
isEnabled: boolean = true,
) {
const Types = require('react-devtools-shared/src/frontend/types');
let isValid = true;
try {
new RegExp(source); // eslint-disable-line no-new
} catch (error) {
isValid = false;
}
return {
type: Types.ComponentFilterDisplayName,
isEnabled,
isValid,
value: source,
};
}
export function createHOCFilter(isEnabled: boolean = true) {
const Types = require('react-devtools-shared/src/frontend/types');
return {
type: Types.ComponentFilterHOC,
isEnabled,
isValid: true,
};
}
export function createElementTypeFilter(
elementType: ElementType,
isEnabled: boolean = true,
) {
const Types = require('react-devtools-shared/src/frontend/types');
return {
type: Types.ComponentFilterElementType,
isEnabled,
value: elementType,
};
}
export function createLocationFilter(
source: string,
isEnabled: boolean = true,
) {
const Types = require('react-devtools-shared/src/frontend/types');
let isValid = true;
try {
new RegExp(source); // eslint-disable-line no-new
} catch (error) {
isValid = false;
}
return {
type: Types.ComponentFilterLocation,
isEnabled,
isValid,
value: source,
};
}
export function getRendererID(): number {
if (global.agent == null) {
throw Error('Agent unavailable.');
}
const ids = Object.keys(global.agent._rendererInterfaces);
const id = ids.find(innerID => {
const rendererInterface = global.agent._rendererInterfaces[innerID];
return rendererInterface.renderer.rendererPackageName === 'react-dom';
});
if (id == null) {
throw Error('Could not find renderer.');
}
return parseInt(id, 10);
}
export function legacyRender(elements, container) {
if (container == null) {
container = document.createElement('div');
}
const ReactDOM = require('react-dom');
withErrorsOrWarningsIgnored(
['ReactDOM.render is no longer supported in React 18'],
() => {
ReactDOM.render(elements, container);
},
);
return () => {
ReactDOM.unmountComponentAtNode(container);
};
}
export function requireTestRenderer(): ReactTestRenderer {
let hook;
try {
// Hide the hook before requiring TestRenderer, so we don't end up with a loop.
hook = global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
delete global.__REACT_DEVTOOLS_GLOBAL_HOOK__;
return require('react-test-renderer');
} finally {
global.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook;
}
}
export function exportImportHelper(bridge: FrontendBridge, store: Store): void {
const {
prepareProfilingDataExport,
prepareProfilingDataFrontendFromExport,
} = require('react-devtools-shared/src/devtools/views/Profiler/utils');
const {profilerStore} = store;
expect(profilerStore.profilingData).not.toBeNull();
const profilingDataFrontendInitial =
((profilerStore.profilingData: any): ProfilingDataFrontend);
expect(profilingDataFrontendInitial.imported).toBe(false);
const profilingDataExport = prepareProfilingDataExport(
profilingDataFrontendInitial,
);
// Simulate writing/reading to disk.
const serializedProfilingDataExport = JSON.stringify(
profilingDataExport,
null,
2,
);
const parsedProfilingDataExport = JSON.parse(serializedProfilingDataExport);
const profilingDataFrontend = prepareProfilingDataFrontendFromExport(
(parsedProfilingDataExport: any),
);
expect(profilingDataFrontend.imported).toBe(true);
// Sanity check that profiling snapshots are serialized correctly.
expect(profilingDataFrontendInitial.dataForRoots).toEqual(
profilingDataFrontend.dataForRoots,
);
expect(profilingDataFrontendInitial.timelineData).toEqual(
profilingDataFrontend.timelineData,
);
// Snapshot the JSON-parsed object, rather than the raw string, because Jest formats the diff nicer.
// expect(parsedProfilingDataExport).toMatchSnapshot('imported data');
act(() => {
// Apply the new exported-then-imported data so tests can re-run assertions.
profilerStore.profilingData = profilingDataFrontend;
});
}
/**
* Runs `fn` while preventing console error and warnings that partially match any given `errorOrWarningMessages` from appearing in the console.
* @param errorOrWarningMessages Messages are matched partially (i.e. indexOf), pre-formatting.
* @param fn
*/
export function withErrorsOrWarningsIgnored<T: void | Promise<void>>(
errorOrWarningMessages: string[],
fn: () => T,
): T {
// withErrorsOrWarningsIgnored() may be nested.
const prev = global._ignoredErrorOrWarningMessages || [];
let resetIgnoredErrorOrWarningMessages = true;
try {
global._ignoredErrorOrWarningMessages = [
...prev,
...errorOrWarningMessages,
];
const maybeThenable = fn();
if (
maybeThenable !== undefined &&
typeof maybeThenable.then === 'function'
) {
resetIgnoredErrorOrWarningMessages = false;
return maybeThenable.then(
() => {
global._ignoredErrorOrWarningMessages = prev;
},
() => {
global._ignoredErrorOrWarningMessages = prev;
},
);
}
} finally {
if (resetIgnoredErrorOrWarningMessages) {
global._ignoredErrorOrWarningMessages = prev;
}
}
}
export function overrideFeatureFlags(overrideFlags) {
jest.mock('react-devtools-feature-flags', () => {
const actualFlags = jest.requireActual('react-devtools-feature-flags');
return {
...actualFlags,
...overrideFlags,
};
});
}
export 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 **)';
});
}
| 27.119355 | 143 | 0.678981 |
cybersecurity-penetration-testing | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @noflow
*/
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {findCurrentFiberUsingSlowPath} from 'react-reconciler/src/ReactFiberTreeReflection';
import {get as getInstance} from 'shared/ReactInstanceMap';
import {
ClassComponent,
FunctionComponent,
HostComponent,
HostHoistable,
HostSingleton,
HostText,
} from 'react-reconciler/src/ReactWorkTags';
import {SyntheticEvent} from 'react-dom-bindings/src/events/SyntheticEvent';
import {ELEMENT_NODE} from 'react-dom-bindings/src/client/HTMLNodeType';
import {
rethrowCaughtError,
invokeGuardedCallbackAndCatchFirstError,
} from 'shared/ReactErrorUtils';
import {enableFloat} from 'shared/ReactFeatureFlags';
import assign from 'shared/assign';
import isArray from 'shared/isArray';
// Keep in sync with ReactDOM.js:
const SecretInternals =
ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
const EventInternals = SecretInternals.Events;
const getInstanceFromNode = EventInternals[0];
const getNodeFromInstance = EventInternals[1];
const getFiberCurrentPropsFromNode = EventInternals[2];
const enqueueStateRestore = EventInternals[3];
const restoreStateIfNeeded = EventInternals[4];
const act = React.unstable_act;
function Event(suffix) {}
let hasWarnedAboutDeprecatedMockComponent = false;
/**
* @class ReactTestUtils
*/
function findAllInRenderedFiberTreeInternal(fiber, test) {
if (!fiber) {
return [];
}
const currentParent = findCurrentFiberUsingSlowPath(fiber);
if (!currentParent) {
return [];
}
let node = currentParent;
const ret = [];
while (true) {
if (
node.tag === HostComponent ||
node.tag === HostText ||
node.tag === ClassComponent ||
node.tag === FunctionComponent ||
(enableFloat ? node.tag === HostHoistable : false) ||
node.tag === HostSingleton
) {
const publicInst = node.stateNode;
if (test(publicInst)) {
ret.push(publicInst);
}
}
if (node.child) {
node.child.return = node;
node = node.child;
continue;
}
if (node === currentParent) {
return ret;
}
while (!node.sibling) {
if (!node.return || node.return === currentParent) {
return ret;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function validateClassInstance(inst, methodName) {
if (!inst) {
// This is probably too relaxed but it's existing behavior.
return;
}
if (getInstance(inst)) {
// This is a public instance indeed.
return;
}
let received;
const stringified = String(inst);
if (isArray(inst)) {
received = 'an array';
} else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
received = 'a DOM node';
} else if (stringified === '[object Object]') {
received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
} else {
received = stringified;
}
throw new Error(
`${methodName}(...): the first argument must be a React class instance. ` +
`Instead received: ${received}.`,
);
}
/**
* Utilities for making it easy to test React components.
*
* See https://reactjs.org/docs/test-utils.html
*
* Todo: Support the entire DOM.scry query syntax. For now, these simple
* utilities will suffice for testing purposes.
* @lends ReactTestUtils
*/
function renderIntoDocument(element) {
const div = document.createElement('div');
// None of our tests actually require attaching the container to the
// DOM, and doing so creates a mess that we rely on test isolation to
// clean up, so we're going to stop honoring the name of this method
// (and probably rename it eventually) if no problems arise.
// document.documentElement.appendChild(div);
return ReactDOM.render(element, div);
}
function isElement(element) {
return React.isValidElement(element);
}
function isElementOfType(inst, convenienceConstructor) {
return React.isValidElement(inst) && inst.type === convenienceConstructor;
}
function isDOMComponent(inst) {
return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
}
function isDOMComponentElement(inst) {
return !!(inst && React.isValidElement(inst) && !!inst.tagName);
}
function isCompositeComponent(inst) {
if (isDOMComponent(inst)) {
// Accessing inst.setState warns; just return false as that'll be what
// this returns when we have DOM nodes as refs directly
return false;
}
return (
inst != null &&
typeof inst.render === 'function' &&
typeof inst.setState === 'function'
);
}
function isCompositeComponentWithType(inst, type) {
if (!isCompositeComponent(inst)) {
return false;
}
const internalInstance = getInstance(inst);
const constructor = internalInstance.type;
return constructor === type;
}
function findAllInRenderedTree(inst, test) {
validateClassInstance(inst, 'findAllInRenderedTree');
if (!inst) {
return [];
}
const internalInstance = getInstance(inst);
return findAllInRenderedFiberTreeInternal(internalInstance, test);
}
/**
* Finds all instances of components in the rendered tree that are DOM
* components with the class name matching `className`.
* @return {array} an array of all the matches.
*/
function scryRenderedDOMComponentsWithClass(root, classNames) {
validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
return findAllInRenderedTree(root, function (inst) {
if (isDOMComponent(inst)) {
let className = inst.className;
if (typeof className !== 'string') {
// SVG, probably.
className = inst.getAttribute('class') || '';
}
const classList = className.split(/\s+/);
if (!isArray(classNames)) {
if (classNames === undefined) {
throw new Error(
'TestUtils.scryRenderedDOMComponentsWithClass expects a ' +
'className as a second argument.',
);
}
classNames = classNames.split(/\s+/);
}
return classNames.every(function (name) {
return classList.indexOf(name) !== -1;
});
}
return false;
});
}
/**
* Like scryRenderedDOMComponentsWithClass but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
function findRenderedDOMComponentWithClass(root, className) {
validateClassInstance(root, 'findRenderedDOMComponentWithClass');
const all = scryRenderedDOMComponentsWithClass(root, className);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match (found: ' +
all.length +
') ' +
'for class:' +
className,
);
}
return all[0];
}
/**
* Finds all instances of components in the rendered tree that are DOM
* components with the tag name matching `tagName`.
* @return {array} an array of all the matches.
*/
function scryRenderedDOMComponentsWithTag(root, tagName) {
validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
return findAllInRenderedTree(root, function (inst) {
return (
isDOMComponent(inst) &&
inst.tagName.toUpperCase() === tagName.toUpperCase()
);
});
}
/**
* Like scryRenderedDOMComponentsWithTag but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
function findRenderedDOMComponentWithTag(root, tagName) {
validateClassInstance(root, 'findRenderedDOMComponentWithTag');
const all = scryRenderedDOMComponentsWithTag(root, tagName);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match (found: ' +
all.length +
') ' +
'for tag:' +
tagName,
);
}
return all[0];
}
/**
* Finds all instances of components with type equal to `componentType`.
* @return {array} an array of all the matches.
*/
function scryRenderedComponentsWithType(root, componentType) {
validateClassInstance(root, 'scryRenderedComponentsWithType');
return findAllInRenderedTree(root, function (inst) {
return isCompositeComponentWithType(inst, componentType);
});
}
/**
* Same as `scryRenderedComponentsWithType` but expects there to be one result
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactComponent} The one match.
*/
function findRenderedComponentWithType(root, componentType) {
validateClassInstance(root, 'findRenderedComponentWithType');
const all = scryRenderedComponentsWithType(root, componentType);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match (found: ' +
all.length +
') ' +
'for componentType:' +
componentType,
);
}
return all[0];
}
/**
* Pass a mocked component module to this method to augment it with
* useful methods that allow it to be used as a dummy React component.
* Instead of rendering as usual, the component will become a simple
* <div> containing any provided children.
*
* @param {object} module the mock function object exported from a
* module that defines the component to be mocked
* @param {?string} mockTagName optional dummy root tag name to return
* from render method (overrides
* module.mockTagName if provided)
* @return {object} the ReactTestUtils object (for chaining)
*/
function mockComponent(module, mockTagName) {
if (__DEV__) {
if (!hasWarnedAboutDeprecatedMockComponent) {
hasWarnedAboutDeprecatedMockComponent = true;
console.warn(
'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.',
);
}
}
mockTagName = mockTagName || module.mockTagName || 'div';
module.prototype.render.mockImplementation(function () {
return React.createElement(mockTagName, null, this.props.children);
});
return this;
}
function nativeTouchData(x, y) {
return {
touches: [{pageX: x, pageY: y}],
};
}
// Start of inline: the below functions were inlined from
// EventPropagator.js, as they deviated from ReactDOM's newer
// implementations.
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
function executeDispatch(event, listener, inst) {
const type = event.type || 'unknown-event';
event.currentTarget = getNodeFromInstance(inst);
invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event) {
const dispatchListeners = event._dispatchListeners;
const dispatchInstances = event._dispatchInstances;
if (isArray(dispatchListeners)) {
for (let i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = null;
}
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @private
*/
function executeDispatchesAndRelease(event /* ReactSyntheticEvent */) {
if (event) {
executeDispatchesInOrder(event);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
}
function isInteractive(tag) {
return (
tag === 'button' ||
tag === 'input' ||
tag === 'select' ||
tag === 'textarea'
);
}
function getParent(inst) {
do {
inst = inst.return;
// TODO: If this is a HostRoot we might want to bail out.
// That is depending on if we want nested subtrees (layers) to bubble
// events to their parent. We could also go through parentNode on the
// host node but that wouldn't work for React Native and doesn't let us
// do the portal feature.
} while (inst && inst.tag !== HostComponent && inst.tag !== HostSingleton);
if (inst) {
return inst;
}
return null;
}
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*/
export function traverseTwoPhase(inst, fn, arg) {
const path = [];
while (inst) {
path.push(inst);
inst = getParent(inst);
}
let i;
for (i = path.length; i-- > 0; ) {
fn(path[i], 'captured', arg);
}
for (i = 0; i < path.length; i++) {
fn(path[i], 'bubbled', arg);
}
}
function shouldPreventMouseEvent(name, type, props) {
switch (name) {
case 'onClick':
case 'onClickCapture':
case 'onDoubleClick':
case 'onDoubleClickCapture':
case 'onMouseDown':
case 'onMouseDownCapture':
case 'onMouseMove':
case 'onMouseMoveCapture':
case 'onMouseUp':
case 'onMouseUpCapture':
case 'onMouseEnter':
return !!(props.disabled && isInteractive(type));
default:
return false;
}
}
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
function getListener(inst /* Fiber */, registrationName: string) {
// TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
// live here; needs to be moved to a better place soon
const stateNode = inst.stateNode;
if (!stateNode) {
// Work in progress (ex: onload events in incremental mode).
return null;
}
const props = getFiberCurrentPropsFromNode(stateNode);
if (!props) {
// Work in progress.
return null;
}
const listener = props[registrationName];
if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
return null;
}
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;
}
function listenerAtPhase(inst, event, propagationPhase: PropagationPhases) {
let registrationName = event._reactName;
if (propagationPhase === 'captured') {
registrationName += 'Capture';
}
return getListener(inst, registrationName);
}
function accumulateDispatches(inst, ignoredDirection, event) {
if (inst && event && event._reactName) {
const registrationName = event._reactName;
const listener = getListener(inst, registrationName);
if (listener) {
if (event._dispatchListeners == null) {
event._dispatchListeners = [];
}
if (event._dispatchInstances == null) {
event._dispatchInstances = [];
}
event._dispatchListeners.push(listener);
event._dispatchInstances.push(inst);
}
}
}
function accumulateDirectionalDispatches(inst, phase, event) {
if (__DEV__) {
if (!inst) {
console.error('Dispatching inst must not be null');
}
}
const listener = listenerAtPhase(inst, event, phase);
if (listener) {
if (event._dispatchListeners == null) {
event._dispatchListeners = [];
}
if (event._dispatchInstances == null) {
event._dispatchInstances = [];
}
event._dispatchListeners.push(listener);
event._dispatchInstances.push(inst);
}
}
function accumulateDirectDispatchesSingle(event) {
if (event && event._reactName) {
accumulateDispatches(event._targetInst, null, event);
}
}
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event._reactName) {
traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
}
// End of inline
const Simulate = {};
const directDispatchEventTypes = new Set([
'mouseEnter',
'mouseLeave',
'pointerEnter',
'pointerLeave',
]);
/**
* Exports:
*
* - `Simulate.click(Element)`
* - `Simulate.mouseMove(Element)`
* - `Simulate.change(Element)`
* - ... (All keys from event plugin `eventTypes` objects)
*/
function makeSimulator(eventType) {
return function (domNode, eventData) {
if (React.isValidElement(domNode)) {
throw new Error(
'TestUtils.Simulate expected a DOM node as the first argument but received ' +
'a React element. Pass the DOM node you wish to simulate the event on instead. ' +
'Note that TestUtils.Simulate will not work if you are using shallow rendering.',
);
}
if (isCompositeComponent(domNode)) {
throw new Error(
'TestUtils.Simulate expected a DOM node as the first argument but received ' +
'a component instance. Pass the DOM node you wish to simulate the event on instead.',
);
}
const reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
const fakeNativeEvent = new Event();
fakeNativeEvent.target = domNode;
fakeNativeEvent.type = eventType.toLowerCase();
const targetInst = getInstanceFromNode(domNode);
const event = new SyntheticEvent(
reactName,
fakeNativeEvent.type,
targetInst,
fakeNativeEvent,
domNode,
);
// Since we aren't using pooling, always persist the event. This will make
// sure it's marked and won't warn when setting additional properties.
event.persist();
assign(event, eventData);
if (directDispatchEventTypes.has(eventType)) {
accumulateDirectDispatchesSingle(event);
} else {
accumulateTwoPhaseDispatchesSingle(event);
}
ReactDOM.unstable_batchedUpdates(function () {
// Normally extractEvent enqueues a state restore, but we'll just always
// do that since we're by-passing it here.
enqueueStateRestore(domNode);
executeDispatchesAndRelease(event);
rethrowCaughtError();
});
restoreStateIfNeeded();
};
}
// A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.
const simulatedEventTypes = [
'blur',
'cancel',
'click',
'close',
'contextMenu',
'copy',
'cut',
'auxClick',
'doubleClick',
'dragEnd',
'dragStart',
'drop',
'focus',
'input',
'invalid',
'keyDown',
'keyPress',
'keyUp',
'mouseDown',
'mouseUp',
'paste',
'pause',
'play',
'pointerCancel',
'pointerDown',
'pointerUp',
'rateChange',
'reset',
'resize',
'seeked',
'submit',
'touchCancel',
'touchEnd',
'touchStart',
'volumeChange',
'drag',
'dragEnter',
'dragExit',
'dragLeave',
'dragOver',
'mouseMove',
'mouseOut',
'mouseOver',
'pointerMove',
'pointerOut',
'pointerOver',
'scroll',
'toggle',
'touchMove',
'wheel',
'abort',
'animationEnd',
'animationIteration',
'animationStart',
'canPlay',
'canPlayThrough',
'durationChange',
'emptied',
'encrypted',
'ended',
'error',
'gotPointerCapture',
'load',
'loadedData',
'loadedMetadata',
'loadStart',
'lostPointerCapture',
'playing',
'progress',
'seeking',
'stalled',
'suspend',
'timeUpdate',
'transitionEnd',
'waiting',
'mouseEnter',
'mouseLeave',
'pointerEnter',
'pointerLeave',
'change',
'select',
'beforeInput',
'compositionEnd',
'compositionStart',
'compositionUpdate',
];
function buildSimulators() {
simulatedEventTypes.forEach(eventType => {
Simulate[eventType] = makeSimulator(eventType);
});
}
buildSimulators();
export {
renderIntoDocument,
isElement,
isElementOfType,
isDOMComponent,
isDOMComponentElement,
isCompositeComponent,
isCompositeComponentWithType,
findAllInRenderedTree,
scryRenderedDOMComponentsWithClass,
findRenderedDOMComponentWithClass,
scryRenderedDOMComponentsWithTag,
findRenderedDOMComponentWithTag,
scryRenderedComponentsWithType,
findRenderedComponentWithType,
mockComponent,
nativeTouchData,
Simulate,
act,
};
| 26.5722 | 120 | 0.67719 |
Hands-On-Penetration-Testing-with-Python | "use strict";
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const {
useMemo,
useState
} = require('react');
function Component(props) {
const InnerComponent = useMemo(() => () => {
const [state] = useState(0);
return state;
});
props.callback(InnerComponent);
return null;
}
module.exports = {
Component
};
//# sourceMappingURL=ComponentWithNestedHooks.js.map?foo=bar¶m=some_value | 19.071429 | 77 | 0.675579 |
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 {
CrossOriginEnum,
PreloadImplOptions,
PreloadModuleImplOptions,
PreinitStyleOptions,
PreinitScriptOptions,
PreinitModuleScriptOptions,
} from 'react-dom/src/shared/ReactDOMTypes';
import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals';
const ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher;
import {ReactDOMFlightServerDispatcher} from './ReactDOMFlightServerHostDispatcher';
export function prepareHostDispatcher(): void {
ReactDOMCurrentDispatcher.current = ReactDOMFlightServerDispatcher;
}
// Used to distinguish these contexts from ones used in other renderers.
// E.g. this can be used to distinguish legacy renderers from this modern one.
export const isPrimaryRenderer = true;
// We use zero to represent the absence of an explicit precedence because it is
// small, smaller than how we encode undefined, and is unambiguous. We could use
// a different tuple structure to encode this instead but this makes the runtime
// cost cheaper by eliminating a type checks in more positions.
type UnspecifiedPrecedence = 0;
// prettier-ignore
type TypeMap = {
// prefetchDNS(href)
'D': /* href */ string,
// preconnect(href, options)
'C':
| /* href */ string
| [/* href */ string, CrossOriginEnum],
// preconnect(href, options)
'L':
| [/* href */ string, /* as */ string]
| [/* href */ string, /* as */ string, PreloadImplOptions],
'm':
| /* href */ string
| [/* href */ string, PreloadModuleImplOptions],
'S':
| /* href */ string
| [/* href */ string, /* precedence */ string]
| [/* href */ string, /* precedence */ string | UnspecifiedPrecedence, PreinitStyleOptions],
'X':
| /* href */ string
| [/* href */ string, PreinitScriptOptions],
'M':
| /* href */ string
| [/* href */ string, PreinitModuleScriptOptions],
}
export type HintCode = $Keys<TypeMap>;
export type HintModel<T: HintCode> = TypeMap[T];
export type Hints = Set<string>;
export function createHints(): Hints {
return new Set();
}
| 29.712329 | 96 | 0.701919 |
Subsets and Splits