repo_name
stringlengths
4
68
text
stringlengths
21
269k
avg_line_length
float64
9.4
9.51k
max_line_length
int64
20
28.5k
alphnanum_fraction
float64
0.3
0.92
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; // Set by `yarn test-fire`. const {disableInputAttributeSyncing} = require('shared/ReactFeatureFlags'); function emptyFunction() {} describe('ReactDOMInput', () => { let React; let ReactDOM; let ReactDOMClient; let ReactDOMServer; let Scheduler; let act; let assertLog; let setUntrackedValue; let setUntrackedChecked; let container; function dispatchEventOnNode(node, type) { node.dispatchEvent(new Event(type, {bubbles: true, cancelable: true})); } function isValueDirty(node) { // Return the "dirty value flag" as defined in the HTML spec. Cast to text // input to sidestep complicated value sanitization behaviors. const copy = node.cloneNode(); copy.type = 'text'; // If modifying the attribute now doesn't change the value, the value was already detached. copy.defaultValue += Math.random(); return copy.value === node.value; } function isCheckedDirty(node) { // Return the "dirty checked flag" as defined in the HTML spec. if (node.checked !== node.defaultChecked) { return true; } const copy = node.cloneNode(); copy.type = 'checkbox'; copy.defaultChecked = !copy.defaultChecked; return copy.checked === node.checked; } function getTrackedAndCurrentInputValue(elem: HTMLElement): [mixed, mixed] { const tracker = elem._valueTracker; if (!tracker) { throw new Error('No input tracker'); } return [ tracker.getValue(), elem.nodeName === 'INPUT' && (elem.type === 'checkbox' || elem.type === 'radio') ? String(elem.checked) : elem.value, ]; } function assertInputTrackingIsCurrent(parent) { parent.querySelectorAll('input, textarea, select').forEach(input => { const [trackedValue, currentValue] = getTrackedAndCurrentInputValue(input); if (trackedValue !== currentValue) { throw new Error( `Input ${input.outerHTML} is currently ${currentValue} but tracker thinks it's ${trackedValue}`, ); } }); } beforeEach(() => { jest.resetModules(); setUntrackedValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value', ).set; setUntrackedChecked = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'checked', ).set; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMServer = require('react-dom/server'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; assertLog = require('internal-test-utils').assertLog; container = document.createElement('div'); document.body.appendChild(container); }); afterEach(() => { document.body.removeChild(container); jest.restoreAllMocks(); }); it('should warn for controlled value of 0 with missing onChange', () => { expect(() => { ReactDOM.render(<input type="text" value={0} />, container); }).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should warn for controlled value of "" with missing onChange', () => { expect(() => { ReactDOM.render(<input type="text" value="" />, container); }).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should warn for controlled value of "0" with missing onChange', () => { expect(() => { ReactDOM.render(<input type="text" value="0" />, container); }).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should warn for controlled value of false with missing onChange', () => { expect(() => ReactDOM.render(<input type="checkbox" checked={false} />, container), ).toErrorDev( 'Warning: You provided a `checked` prop to a form field without an `onChange` handler.', ); }); it('should warn with checked and no onChange handler with readOnly specified', () => { ReactDOM.render( <input type="checkbox" checked={false} readOnly={true} />, container, ); ReactDOM.unmountComponentAtNode(container); expect(() => ReactDOM.render( <input type="checkbox" checked={false} readOnly={false} />, container, ), ).toErrorDev( 'Warning: You provided a `checked` prop to a form field without an `onChange` handler. ' + 'This will render a read-only field. If the field should be mutable use `defaultChecked`. ' + 'Otherwise, set either `onChange` or `readOnly`.', ); }); it('should not warn about missing onChange in uncontrolled inputs', () => { ReactDOM.render(<input />, container); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<input value={undefined} />, container); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<input type="text" />, container); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<input type="text" value={undefined} />, container); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<input type="checkbox" />, container); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<input type="checkbox" checked={undefined} />, container); }); it('should not warn with value and onInput handler', () => { ReactDOM.render(<input value="..." onInput={() => {}} />, container); }); it('should properly control a value even if no event listener exists', () => { let node; expect(() => { node = ReactDOM.render(<input type="text" value="lion" />, container); }).toErrorDev( 'Warning: You provided a `value` prop to a form field without an `onChange` handler.', ); expect(isValueDirty(node)).toBe(true); setUntrackedValue.call(node, 'giraffe'); // This must use the native event dispatching. If we simulate, we will // bypass the lazy event attachment system so we won't actually test this. dispatchEventOnNode(node, 'input'); expect(node.value).toBe('lion'); expect(isValueDirty(node)).toBe(true); }); it('should control a value in reentrant events', () => { class ControlledInputs extends React.Component { state = {value: 'lion'}; a = null; b = null; switchedFocus = false; change(newValue) { this.setState({value: newValue}); // Calling focus here will blur the text box which causes a native // change event. Ideally we shouldn't have to fire this ourselves. // Don't remove unless you've verified the fix in #8240 is still covered. dispatchEventOnNode(this.a, 'input'); this.b.focus(); } blur(currentValue) { this.switchedFocus = true; // currentValue should be 'giraffe' here because we should not have // restored it on the target yet. this.setState({value: currentValue}); } render() { return ( <div> <input type="text" ref={n => (this.a = n)} value={this.state.value} onChange={e => this.change(e.target.value)} onBlur={e => this.blur(e.target.value)} /> <input type="text" ref={n => (this.b = n)} /> </div> ); } } const instance = ReactDOM.render(<ControlledInputs />, container); // Focus the field so we can later blur it. // Don't remove unless you've verified the fix in #8240 is still covered. instance.a.focus(); setUntrackedValue.call(instance.a, 'giraffe'); // This must use the native event dispatching. If we simulate, we will // bypass the lazy event attachment system so we won't actually test this. dispatchEventOnNode(instance.a, 'input'); dispatchEventOnNode(instance.a, 'blur'); dispatchEventOnNode(instance.a, 'focusout'); expect(instance.a.value).toBe('giraffe'); expect(instance.switchedFocus).toBe(true); }); it('should control values in reentrant events with different targets', () => { class ControlledInputs extends React.Component { state = {value: 'lion'}; a = null; b = null; change(newValue) { // This click will change the checkbox's value to false. Then it will // invoke an inner change event. When we finally, flush, we need to // reset the checkbox's value to true since that is its controlled // value. this.b.click(); } render() { return ( <div> <input type="text" ref={n => (this.a = n)} value="lion" onChange={e => this.change(e.target.value)} /> <input type="checkbox" ref={n => (this.b = n)} checked={true} onChange={() => {}} /> </div> ); } } const instance = ReactDOM.render(<ControlledInputs />, container); setUntrackedValue.call(instance.a, 'giraffe'); // This must use the native event dispatching. If we simulate, we will // bypass the lazy event attachment system so we won't actually test this. dispatchEventOnNode(instance.a, 'input'); expect(instance.a.value).toBe('lion'); expect(instance.b.checked).toBe(true); }); describe('switching text inputs between numeric and string numbers', () => { it('does change the number 2 to "2.0" with no change handler', () => { const stub = <input type="text" value={2} onChange={jest.fn()} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, '2.0'); dispatchEventOnNode(node, 'input'); expect(node.value).toBe('2'); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe('2'); } }); it('does change the string "2" to "2.0" with no change handler', () => { const stub = <input type="text" value={'2'} onChange={jest.fn()} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, '2.0'); dispatchEventOnNode(node, 'input'); expect(node.value).toBe('2'); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe('2'); } }); it('changes the number 2 to "2.0" using a change handler', () => { class Stub extends React.Component { state = { value: 2, }; onChange = event => { this.setState({value: event.target.value}); }; render() { const {value} = this.state; return <input type="text" value={value} onChange={this.onChange} />; } } const stub = ReactDOM.render(<Stub />, container); const node = ReactDOM.findDOMNode(stub); setUntrackedValue.call(node, '2.0'); dispatchEventOnNode(node, 'input'); expect(node.value).toBe('2.0'); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe('2.0'); } }); }); it('does change the string ".98" to "0.98" with no change handler', () => { class Stub extends React.Component { state = { value: '.98', }; render() { return <input type="number" value={this.state.value} />; } } let stub; expect(() => { stub = ReactDOM.render(<Stub />, container); }).toErrorDev( 'You provided a `value` prop to a form field ' + 'without an `onChange` handler.', ); const node = ReactDOM.findDOMNode(stub); stub.setState({value: '0.98'}); expect(node.value).toEqual('0.98'); }); it('performs a state change from "" to 0', () => { class Stub extends React.Component { state = { value: '', }; render() { return <input type="number" value={this.state.value} readOnly={true} />; } } const stub = ReactDOM.render(<Stub />, container); const node = ReactDOM.findDOMNode(stub); stub.setState({value: 0}); expect(node.value).toEqual('0'); }); it('updates the value on radio buttons from "" to 0', function () { ReactDOM.render( <input type="radio" value="" onChange={function () {}} />, container, ); ReactDOM.render( <input type="radio" value={0} onChange={function () {}} />, container, ); expect(container.firstChild.value).toBe('0'); expect(container.firstChild.getAttribute('value')).toBe('0'); }); it('updates the value on checkboxes from "" to 0', function () { ReactDOM.render( <input type="checkbox" value="" onChange={function () {}} />, container, ); ReactDOM.render( <input type="checkbox" value={0} onChange={function () {}} />, container, ); expect(container.firstChild.value).toBe('0'); expect(container.firstChild.getAttribute('value')).toBe('0'); }); it('distinguishes precision for extra zeroes in string number values', () => { class Stub extends React.Component { state = { value: '3.0000', }; render() { return <input type="number" value={this.state.value} />; } } let stub; expect(() => { stub = ReactDOM.render(<Stub />, container); }).toErrorDev( 'You provided a `value` prop to a form field ' + 'without an `onChange` handler.', ); const node = ReactDOM.findDOMNode(stub); stub.setState({value: '3'}); expect(node.value).toEqual('3'); }); it('should display `defaultValue` of number 0', () => { const stub = <input type="text" defaultValue={0} />; const node = ReactDOM.render(stub, container); expect(node.getAttribute('value')).toBe('0'); expect(node.value).toBe('0'); }); it('only assigns defaultValue if it changes', () => { class Test extends React.Component { render() { return <input defaultValue="0" />; } } const component = ReactDOM.render(<Test />, container); const node = ReactDOM.findDOMNode(component); Object.defineProperty(node, 'defaultValue', { get() { return '0'; }, set(value) { throw new Error( `defaultValue was assigned ${value}, but it did not change!`, ); }, }); component.forceUpdate(); }); it('should display "true" for `defaultValue` of `true`', () => { const stub = <input type="text" defaultValue={true} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('true'); }); it('should display "false" for `defaultValue` of `false`', () => { const stub = <input type="text" defaultValue={false} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('false'); }); it('should update `defaultValue` for uncontrolled input', () => { const node = ReactDOM.render( <input type="text" defaultValue="0" />, container, ); expect(node.value).toBe('0'); expect(node.defaultValue).toBe('0'); if (disableInputAttributeSyncing) { expect(isValueDirty(node)).toBe(false); } else { expect(isValueDirty(node)).toBe(true); } ReactDOM.render(<input type="text" defaultValue="1" />, container); if (disableInputAttributeSyncing) { expect(node.value).toBe('1'); expect(node.defaultValue).toBe('1'); expect(isValueDirty(node)).toBe(false); } else { expect(node.value).toBe('0'); expect(node.defaultValue).toBe('1'); expect(isValueDirty(node)).toBe(true); } }); it('should update `defaultValue` for uncontrolled date/time input', () => { const node = ReactDOM.render( <input type="date" defaultValue="1980-01-01" />, container, ); expect(node.value).toBe('1980-01-01'); expect(node.defaultValue).toBe('1980-01-01'); ReactDOM.render(<input type="date" defaultValue="2000-01-01" />, container); if (disableInputAttributeSyncing) { expect(node.value).toBe('2000-01-01'); expect(node.defaultValue).toBe('2000-01-01'); } else { expect(node.value).toBe('1980-01-01'); expect(node.defaultValue).toBe('2000-01-01'); } ReactDOM.render(<input type="date" />, container); }); it('should take `defaultValue` when changing to uncontrolled input', () => { const node = ReactDOM.render( <input type="text" value="0" readOnly={true} />, container, ); expect(node.value).toBe('0'); expect(isValueDirty(node)).toBe(true); expect(() => ReactDOM.render(<input type="text" defaultValue="1" />, container), ).toErrorDev( 'A component is changing a controlled input to be uncontrolled.', ); expect(node.value).toBe('0'); expect(isValueDirty(node)).toBe(true); }); it('should render defaultValue for SSR', () => { const markup = ReactDOMServer.renderToString( <input type="text" defaultValue="1" />, ); const div = document.createElement('div'); div.innerHTML = markup; expect(div.firstChild.getAttribute('value')).toBe('1'); expect(div.firstChild.getAttribute('defaultValue')).toBe(null); }); it('should render value for SSR', () => { const element = <input type="text" value="1" onChange={() => {}} />; const markup = ReactDOMServer.renderToString(element); const div = document.createElement('div'); div.innerHTML = markup; expect(div.firstChild.getAttribute('value')).toBe('1'); expect(div.firstChild.getAttribute('defaultValue')).toBe(null); }); it('should render name attribute if it is supplied', () => { const node = ReactDOM.render(<input type="text" name="name" />, container); expect(node.name).toBe('name'); expect(container.firstChild.getAttribute('name')).toBe('name'); }); it('should render name attribute if it is supplied for SSR', () => { const element = <input type="text" name="name" />; const markup = ReactDOMServer.renderToString(element); const div = document.createElement('div'); div.innerHTML = markup; expect(div.firstChild.getAttribute('name')).toBe('name'); }); it('should not render name attribute if it is not supplied', () => { ReactDOM.render(<input type="text" />, container); expect(container.firstChild.getAttribute('name')).toBe(null); }); it('should not render name attribute if it is not supplied for SSR', () => { const element = <input type="text" />; const markup = ReactDOMServer.renderToString(element); const div = document.createElement('div'); div.innerHTML = markup; expect(div.firstChild.getAttribute('name')).toBe(null); }); it('should display "foobar" for `defaultValue` of `objToString`', () => { const objToString = { toString: function () { return 'foobar'; }, }; const stub = <input type="text" defaultValue={objToString} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('foobar'); }); it('should throw for date inputs if `defaultValue` is an object where valueOf() throws', () => { class TemporalLike { valueOf() { // Throwing here is the behavior of ECMAScript "Temporal" date/time API. // See https://tc39.es/proposal-temporal/docs/plaindate.html#valueOf throw new TypeError('prod message'); } toString() { return '2020-01-01'; } } const test = () => ReactDOM.render( <input defaultValue={new TemporalLike()} type="date" />, container, ); expect(() => expect(test).toThrowError(new TypeError('prod message')), ).toErrorDev( 'Form field values (value, checked, defaultValue, or defaultChecked props) must be ' + 'strings, not TemporalLike. This value must be coerced to a string before using it here.', ); }); it('should throw for text inputs if `defaultValue` is an object where valueOf() throws', () => { class TemporalLike { valueOf() { // Throwing here is the behavior of ECMAScript "Temporal" date/time API. // See https://tc39.es/proposal-temporal/docs/plaindate.html#valueOf throw new TypeError('prod message'); } toString() { return '2020-01-01'; } } const test = () => ReactDOM.render( <input defaultValue={new TemporalLike()} type="text" />, container, ); expect(() => expect(test).toThrowError(new TypeError('prod message')), ).toErrorDev( 'Form field values (value, checked, defaultValue, or defaultChecked props) must be ' + 'strings, not TemporalLike. This value must be coerced to a string before using it here.', ); }); it('should throw for date inputs if `value` is an object where valueOf() throws', () => { class TemporalLike { valueOf() { // Throwing here is the behavior of ECMAScript "Temporal" date/time API. // See https://tc39.es/proposal-temporal/docs/plaindate.html#valueOf throw new TypeError('prod message'); } toString() { return '2020-01-01'; } } const test = () => ReactDOM.render( <input value={new TemporalLike()} type="date" onChange={() => {}} />, container, ); expect(() => expect(test).toThrowError(new TypeError('prod message')), ).toErrorDev( 'Form field values (value, checked, defaultValue, or defaultChecked props) must be ' + 'strings, not TemporalLike. This value must be coerced to a string before using it here.', ); }); it('should throw for text inputs if `value` is an object where valueOf() throws', () => { class TemporalLike { valueOf() { // Throwing here is the behavior of ECMAScript "Temporal" date/time API. // See https://tc39.es/proposal-temporal/docs/plaindate.html#valueOf throw new TypeError('prod message'); } toString() { return '2020-01-01'; } } const test = () => ReactDOM.render( <input value={new TemporalLike()} type="text" onChange={() => {}} />, container, ); expect(() => expect(test).toThrowError(new TypeError('prod message')), ).toErrorDev( 'Form field values (value, checked, defaultValue, or defaultChecked props) must be ' + 'strings, not TemporalLike. This value must be coerced to a string before using it here.', ); }); it('should display `value` of number 0', () => { const stub = <input type="text" value={0} onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('0'); }); it('should allow setting `value` to `true`', () => { let stub = <input type="text" value="yolo" onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('yolo'); stub = ReactDOM.render( <input type="text" value={true} onChange={emptyFunction} />, container, ); expect(node.value).toEqual('true'); }); it('should allow setting `value` to `false`', () => { let stub = <input type="text" value="yolo" onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('yolo'); stub = ReactDOM.render( <input type="text" value={false} onChange={emptyFunction} />, container, ); expect(node.value).toEqual('false'); }); it('should allow setting `value` to `objToString`', () => { let stub = <input type="text" value="foo" onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); expect(node.value).toBe('foo'); const objToString = { toString: function () { return 'foobar'; }, }; stub = ReactDOM.render( <input type="text" value={objToString} onChange={emptyFunction} />, container, ); expect(node.value).toEqual('foobar'); }); it('should not incur unnecessary DOM mutations', () => { ReactDOM.render(<input value="a" onChange={() => {}} />, container); const node = container.firstChild; let nodeValue = 'a'; const nodeValueSetter = jest.fn(); Object.defineProperty(node, 'value', { get: function () { return nodeValue; }, set: nodeValueSetter.mockImplementation(function (newValue) { nodeValue = newValue; }), }); ReactDOM.render(<input value="a" onChange={() => {}} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(0); ReactDOM.render(<input value="b" onChange={() => {}} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(1); }); it('should not incur unnecessary DOM mutations for numeric type conversion', () => { ReactDOM.render(<input value="0" onChange={() => {}} />, container); const node = container.firstChild; let nodeValue = '0'; const nodeValueSetter = jest.fn(); Object.defineProperty(node, 'value', { get: function () { return nodeValue; }, set: nodeValueSetter.mockImplementation(function (newValue) { nodeValue = newValue; }), }); ReactDOM.render(<input value={0} onChange={() => {}} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(0); }); it('should not incur unnecessary DOM mutations for the boolean type conversion', () => { ReactDOM.render(<input value="true" onChange={() => {}} />, container); const node = container.firstChild; let nodeValue = 'true'; const nodeValueSetter = jest.fn(); Object.defineProperty(node, 'value', { get: function () { return nodeValue; }, set: nodeValueSetter.mockImplementation(function (newValue) { nodeValue = newValue; }), }); ReactDOM.render(<input value={true} onChange={() => {}} />, container); expect(nodeValueSetter).toHaveBeenCalledTimes(0); }); it('should properly control a value of number `0`', () => { const stub = <input type="text" value={0} onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, 'giraffe'); dispatchEventOnNode(node, 'input'); expect(node.value).toBe('0'); }); it('should properly control 0.0 for a text input', () => { const stub = <input type="text" value={0} onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, '0.0'); dispatchEventOnNode(node, 'input'); expect(node.value).toBe('0'); }); it('should properly control 0.0 for a number input', () => { const stub = <input type="number" value={0} onChange={emptyFunction} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, '0.0'); dispatchEventOnNode(node, 'input'); if (disableInputAttributeSyncing) { expect(node.value).toBe('0.0'); expect(node.hasAttribute('value')).toBe(false); } else { dispatchEventOnNode(node, 'blur'); dispatchEventOnNode(node, 'focusout'); expect(node.value).toBe('0.0'); expect(node.getAttribute('value')).toBe('0.0'); } }); it('should properly transition from an empty value to 0', function () { ReactDOM.render( <input type="text" value="" onChange={emptyFunction} />, container, ); const node = container.firstChild; expect(isValueDirty(node)).toBe(false); ReactDOM.render( <input type="text" value={0} onChange={emptyFunction} />, container, ); expect(node.value).toBe('0'); expect(isValueDirty(node)).toBe(true); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.defaultValue).toBe('0'); } }); it('should properly transition from 0 to an empty value', function () { ReactDOM.render( <input type="text" value={0} onChange={emptyFunction} />, container, ); const node = container.firstChild; expect(isValueDirty(node)).toBe(true); ReactDOM.render( <input type="text" value="" onChange={emptyFunction} />, container, ); expect(node.value).toBe(''); expect(node.defaultValue).toBe(''); expect(isValueDirty(node)).toBe(true); }); it('should properly transition a text input from 0 to an empty 0.0', function () { ReactDOM.render( <input type="text" value={0} onChange={emptyFunction} />, container, ); ReactDOM.render( <input type="text" value="0.0" onChange={emptyFunction} />, container, ); const node = container.firstChild; expect(node.value).toBe('0.0'); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.defaultValue).toBe('0.0'); } }); it('should properly transition a number input from "" to 0', function () { ReactDOM.render( <input type="number" value="" onChange={emptyFunction} />, container, ); ReactDOM.render( <input type="number" value={0} onChange={emptyFunction} />, container, ); const node = container.firstChild; expect(node.value).toBe('0'); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.defaultValue).toBe('0'); } }); it('should properly transition a number input from "" to "0"', function () { ReactDOM.render( <input type="number" value="" onChange={emptyFunction} />, container, ); ReactDOM.render( <input type="number" value="0" onChange={emptyFunction} />, container, ); const node = container.firstChild; expect(node.value).toBe('0'); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.defaultValue).toBe('0'); } }); it('should have the correct target value', () => { let handled = false; const handler = function (event) { expect(event.target.nodeName).toBe('INPUT'); handled = true; }; const stub = <input type="text" value={0} onChange={handler} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, 'giraffe'); dispatchEventOnNode(node, 'input'); expect(handled).toBe(true); }); it('should restore uncontrolled inputs to last defaultValue upon reset', () => { const inputRef = React.createRef(); ReactDOM.render( <form> <input defaultValue="default1" ref={inputRef} /> <input type="reset" /> </form>, container, ); expect(inputRef.current.value).toBe('default1'); if (disableInputAttributeSyncing) { expect(isValueDirty(inputRef.current)).toBe(false); } else { expect(isValueDirty(inputRef.current)).toBe(true); } setUntrackedValue.call(inputRef.current, 'changed'); dispatchEventOnNode(inputRef.current, 'input'); expect(inputRef.current.value).toBe('changed'); expect(isValueDirty(inputRef.current)).toBe(true); ReactDOM.render( <form> <input defaultValue="default2" ref={inputRef} /> <input type="reset" /> </form>, container, ); expect(inputRef.current.value).toBe('changed'); expect(isValueDirty(inputRef.current)).toBe(true); container.firstChild.reset(); // Note: I don't know if we want to always support this. // But it's current behavior so worth being intentional if we break it. // https://github.com/facebook/react/issues/4618 expect(inputRef.current.value).toBe('default2'); expect(isValueDirty(inputRef.current)).toBe(false); }); it('should not set a value for submit buttons unnecessarily', () => { const stub = <input type="submit" />; ReactDOM.render(stub, container); const node = container.firstChild; // The value shouldn't be '', or else the button will have no text; it // should have the default "Submit" or "Submit Query" label. Most browsers // report this as not having a `value` attribute at all; IE reports it as // the actual label that the user sees. expect(node.hasAttribute('value')).toBe(false); }); it('should remove the value attribute on submit inputs when value is updated to undefined', () => { const stub = <input type="submit" value="foo" onChange={emptyFunction} />; ReactDOM.render(stub, container); // Not really relevant to this particular test, but changing to undefined // should nonetheless trigger a warning expect(() => ReactDOM.render( <input type="submit" value={undefined} onChange={emptyFunction} />, container, ), ).toErrorDev( 'A component is changing a controlled input to be uncontrolled.', ); const node = container.firstChild; expect(node.getAttribute('value')).toBe(null); }); it('should remove the value attribute on reset inputs when value is updated to undefined', () => { const stub = <input type="reset" value="foo" onChange={emptyFunction} />; ReactDOM.render(stub, container); // Not really relevant to this particular test, but changing to undefined // should nonetheless trigger a warning expect(() => ReactDOM.render( <input type="reset" value={undefined} onChange={emptyFunction} />, container, ), ).toErrorDev( 'A component is changing a controlled input to be uncontrolled.', ); const node = container.firstChild; expect(node.getAttribute('value')).toBe(null); }); it('should set a value on a submit input', () => { const stub = <input type="submit" value="banana" />; ReactDOM.render(stub, container); const node = container.firstChild; expect(node.getAttribute('value')).toBe('banana'); }); it('should not set an undefined value on a submit input', () => { const stub = <input type="submit" value={undefined} />; ReactDOM.render(stub, container); const node = container.firstChild; // Note: it shouldn't be an empty string // because that would erase the "submit" label. expect(node.getAttribute('value')).toBe(null); ReactDOM.render(stub, container); expect(node.getAttribute('value')).toBe(null); }); it('should not set an undefined value on a reset input', () => { const stub = <input type="reset" value={undefined} />; ReactDOM.render(stub, container); const node = container.firstChild; // Note: it shouldn't be an empty string // because that would erase the "reset" label. expect(node.getAttribute('value')).toBe(null); ReactDOM.render(stub, container); expect(node.getAttribute('value')).toBe(null); }); it('should not set a null value on a submit input', () => { const stub = <input type="submit" value={null} />; expect(() => { ReactDOM.render(stub, container); }).toErrorDev('`value` prop on `input` should not be null'); const node = container.firstChild; // Note: it shouldn't be an empty string // because that would erase the "submit" label. expect(node.getAttribute('value')).toBe(null); ReactDOM.render(stub, container); expect(node.getAttribute('value')).toBe(null); }); it('should not set a null value on a reset input', () => { const stub = <input type="reset" value={null} />; expect(() => { ReactDOM.render(stub, container); }).toErrorDev('`value` prop on `input` should not be null'); const node = container.firstChild; // Note: it shouldn't be an empty string // because that would erase the "reset" label. expect(node.getAttribute('value')).toBe(null); ReactDOM.render(stub, container); expect(node.getAttribute('value')).toBe(null); }); it('should set a value on a reset input', () => { const stub = <input type="reset" value="banana" />; ReactDOM.render(stub, container); const node = container.firstChild; expect(node.getAttribute('value')).toBe('banana'); }); it('should set an empty string value on a submit input', () => { const stub = <input type="submit" value="" />; ReactDOM.render(stub, container); const node = container.firstChild; expect(node.getAttribute('value')).toBe(''); }); it('should set an empty string value on a reset input', () => { const stub = <input type="reset" value="" />; ReactDOM.render(stub, container); const node = container.firstChild; expect(node.getAttribute('value')).toBe(''); }); it('should control radio buttons', () => { class RadioGroup extends React.Component { aRef = React.createRef(); bRef = React.createRef(); cRef = React.createRef(); render() { return ( <div> <input ref={this.aRef} type="radio" name="fruit" checked={true} onChange={emptyFunction} data-which="a" /> A <input ref={this.bRef} type="radio" name="fruit" onChange={emptyFunction} data-which="b" /> B <form> <input ref={this.cRef} type="radio" name="fruit" defaultChecked={true} onChange={emptyFunction} data-which="c" /> </form> </div> ); } } const stub = ReactDOM.render(<RadioGroup />, container); const aNode = stub.aRef.current; const bNode = stub.bRef.current; const cNode = stub.cRef.current; expect(aNode.checked).toBe(true); expect(bNode.checked).toBe(false); // c is in a separate form and shouldn't be affected at all here expect(cNode.checked).toBe(true); if (disableInputAttributeSyncing) { expect(aNode.hasAttribute('checked')).toBe(false); expect(bNode.hasAttribute('checked')).toBe(false); expect(cNode.hasAttribute('checked')).toBe(true); } else { expect(aNode.hasAttribute('checked')).toBe(true); expect(bNode.hasAttribute('checked')).toBe(false); expect(cNode.hasAttribute('checked')).toBe(true); } expect(isCheckedDirty(aNode)).toBe(true); expect(isCheckedDirty(bNode)).toBe(true); expect(isCheckedDirty(cNode)).toBe(true); assertInputTrackingIsCurrent(container); setUntrackedChecked.call(bNode, true); expect(aNode.checked).toBe(false); expect(cNode.checked).toBe(true); // The original 'checked' attribute should be unchanged if (disableInputAttributeSyncing) { expect(aNode.hasAttribute('checked')).toBe(false); expect(bNode.hasAttribute('checked')).toBe(false); expect(cNode.hasAttribute('checked')).toBe(true); } else { expect(aNode.hasAttribute('checked')).toBe(true); expect(bNode.hasAttribute('checked')).toBe(false); expect(cNode.hasAttribute('checked')).toBe(true); } // Now let's run the actual ReactDOMInput change event handler dispatchEventOnNode(bNode, 'click'); // The original state should have been restored expect(aNode.checked).toBe(true); expect(cNode.checked).toBe(true); expect(isCheckedDirty(aNode)).toBe(true); expect(isCheckedDirty(bNode)).toBe(true); expect(isCheckedDirty(cNode)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should hydrate controlled radio buttons', async () => { function App() { const [current, setCurrent] = React.useState('a'); return ( <> <input type="radio" name="fruit" checked={current === 'a'} onChange={() => { Scheduler.log('click a'); setCurrent('a'); }} /> <input type="radio" name="fruit" checked={current === 'b'} onChange={() => { Scheduler.log('click b'); setCurrent('b'); }} /> <input type="radio" name="fruit" checked={current === 'c'} onChange={() => { Scheduler.log('click c'); // Let's say the user can't pick C }} /> </> ); } const html = ReactDOMServer.renderToString(<App />); container.innerHTML = html; const [a, b, c] = container.querySelectorAll('input'); expect(a.checked).toBe(true); expect(b.checked).toBe(false); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(false); expect(isCheckedDirty(b)).toBe(false); expect(isCheckedDirty(c)).toBe(false); // Click on B before hydrating b.checked = true; expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(false); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); // Currently, we don't fire onChange when hydrating assertLog([]); // Strangely, we leave `b` checked even though we rendered A with // checked={true} and B with checked={false}. Arguably this is a bug. expect(a.checked).toBe(false); expect(b.checked).toBe(true); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(true); assertInputTrackingIsCurrent(container); // If we click on C now though... await act(async () => { setUntrackedChecked.call(c, true); dispatchEventOnNode(c, 'click'); }); // then since C's onClick doesn't set state, A becomes rechecked. assertLog(['click c']); expect(a.checked).toBe(true); expect(b.checked).toBe(false); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(true); assertInputTrackingIsCurrent(container); // And we can also change to B properly after hydration. await act(async () => { setUntrackedChecked.call(b, true); dispatchEventOnNode(b, 'click'); }); assertLog(['click b']); expect(a.checked).toBe(false); expect(b.checked).toBe(true); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should hydrate uncontrolled radio buttons', async () => { function App() { return ( <> <input type="radio" name="fruit" defaultChecked={true} onChange={() => Scheduler.log('click a')} /> <input type="radio" name="fruit" defaultChecked={false} onChange={() => Scheduler.log('click b')} /> <input type="radio" name="fruit" defaultChecked={false} onChange={() => Scheduler.log('click c')} /> </> ); } const html = ReactDOMServer.renderToString(<App />); container.innerHTML = html; const [a, b, c] = container.querySelectorAll('input'); expect(a.checked).toBe(true); expect(b.checked).toBe(false); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(false); expect(isCheckedDirty(b)).toBe(false); expect(isCheckedDirty(c)).toBe(false); // Click on B before hydrating b.checked = true; expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(false); await act(async () => { ReactDOMClient.hydrateRoot(container, <App />); }); // Currently, we don't fire onChange when hydrating assertLog([]); expect(a.checked).toBe(false); expect(b.checked).toBe(true); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(true); assertInputTrackingIsCurrent(container); // Click back to A await act(async () => { setUntrackedChecked.call(a, true); dispatchEventOnNode(a, 'click'); }); assertLog(['click a']); expect(a.checked).toBe(true); expect(b.checked).toBe(false); expect(c.checked).toBe(false); expect(isCheckedDirty(a)).toBe(true); expect(isCheckedDirty(b)).toBe(true); expect(isCheckedDirty(c)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should check the correct radio when the selected name moves', () => { class App extends React.Component { state = { updated: false, }; onClick = () => { this.setState({updated: !this.state.updated}); }; render() { const {updated} = this.state; const radioName = updated ? 'secondName' : 'firstName'; return ( <div> <button type="button" onClick={this.onClick} /> <input type="radio" name={radioName} onChange={emptyFunction} checked={updated === true} /> <input type="radio" name={radioName} onChange={emptyFunction} checked={updated === false} /> </div> ); } } const stub = ReactDOM.render(<App />, container); const buttonNode = ReactDOM.findDOMNode(stub).childNodes[0]; const firstRadioNode = ReactDOM.findDOMNode(stub).childNodes[1]; expect(isCheckedDirty(firstRadioNode)).toBe(true); expect(firstRadioNode.checked).toBe(false); assertInputTrackingIsCurrent(container); dispatchEventOnNode(buttonNode, 'click'); expect(firstRadioNode.checked).toBe(true); assertInputTrackingIsCurrent(container); dispatchEventOnNode(buttonNode, 'click'); expect(firstRadioNode.checked).toBe(false); assertInputTrackingIsCurrent(container); }); it("shouldn't get tricked by changing radio names, part 2", () => { ReactDOM.render( <div> <input type="radio" name="a" value="1" checked={true} onChange={() => {}} /> <input type="radio" name="a" value="2" checked={false} onChange={() => {}} /> </div>, container, ); const one = container.querySelector('input[name="a"][value="1"]'); const two = container.querySelector('input[name="a"][value="2"]'); expect(one.checked).toBe(true); expect(two.checked).toBe(false); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); ReactDOM.render( <div> <input type="radio" name="a" value="1" checked={true} onChange={() => {}} /> <input type="radio" name="b" value="2" checked={true} onChange={() => {}} /> </div>, container, ); expect(one.checked).toBe(true); expect(two.checked).toBe(true); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should control radio buttons if the tree updates during render', () => { const sharedParent = container; const container1 = document.createElement('div'); const container2 = document.createElement('div'); sharedParent.appendChild(container1); let aNode; let bNode; class ComponentA extends React.Component { state = {changed: false}; handleChange = () => { this.setState({ changed: true, }); }; componentDidUpdate() { sharedParent.appendChild(container2); } componentDidMount() { ReactDOM.render(<ComponentB />, container2); } render() { return ( <div> <input ref={n => (aNode = n)} type="radio" name="fruit" checked={false} onChange={this.handleChange} /> A </div> ); } } class ComponentB extends React.Component { render() { return ( <div> <input ref={n => (bNode = n)} type="radio" name="fruit" checked={true} onChange={emptyFunction} /> B </div> ); } } ReactDOM.render(<ComponentA />, container1); expect(aNode.checked).toBe(false); expect(bNode.checked).toBe(true); expect(isCheckedDirty(aNode)).toBe(true); expect(isCheckedDirty(bNode)).toBe(true); assertInputTrackingIsCurrent(container); setUntrackedChecked.call(aNode, true); // This next line isn't necessary in a proper browser environment, but // jsdom doesn't uncheck the others in a group (because they are not yet // sharing a parent), which makes this whole test a little less effective. setUntrackedChecked.call(bNode, false); // Now let's run the actual ReactDOMInput change event handler dispatchEventOnNode(aNode, 'click'); // The original state should have been restored expect(aNode.checked).toBe(false); expect(bNode.checked).toBe(true); expect(isCheckedDirty(aNode)).toBe(true); expect(isCheckedDirty(bNode)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should control radio buttons if the tree updates during render (case 2; #26876)', () => { let thunk = null; function App() { const [disabled, setDisabled] = React.useState(false); const [value, setValue] = React.useState('one'); function handleChange(e) { setDisabled(true); // Pretend this is in a setTimeout or something thunk = () => { setDisabled(false); setValue(e.target.value); }; } return ( <> <input type="radio" name="fruit" value="one" checked={value === 'one'} onChange={handleChange} disabled={disabled} /> <input type="radio" name="fruit" value="two" checked={value === 'two'} onChange={handleChange} disabled={disabled} /> </> ); } ReactDOM.render(<App />, container); const [one, two] = container.querySelectorAll('input'); expect(one.checked).toBe(true); expect(two.checked).toBe(false); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); // Click two setUntrackedChecked.call(two, true); dispatchEventOnNode(two, 'click'); expect(one.checked).toBe(true); expect(two.checked).toBe(false); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); // After a delay... ReactDOM.unstable_batchedUpdates(thunk); expect(one.checked).toBe(false); expect(two.checked).toBe(true); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); // Click back to one setUntrackedChecked.call(one, true); dispatchEventOnNode(one, 'click'); expect(one.checked).toBe(false); expect(two.checked).toBe(true); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); // After a delay... ReactDOM.unstable_batchedUpdates(thunk); expect(one.checked).toBe(true); expect(two.checked).toBe(false); expect(isCheckedDirty(one)).toBe(true); expect(isCheckedDirty(two)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should warn with value and no onChange handler and readOnly specified', () => { ReactDOM.render( <input type="text" value="zoink" readOnly={true} />, container, ); ReactDOM.unmountComponentAtNode(container); expect(() => ReactDOM.render( <input type="text" value="zoink" readOnly={false} />, container, ), ).toErrorDev( 'Warning: You provided a `value` prop to a form ' + 'field without an `onChange` handler. This will render a read-only ' + 'field. If the field should be mutable use `defaultValue`. ' + 'Otherwise, set either `onChange` or `readOnly`.\n' + ' in input (at **)', ); }); it('should have a this value of undefined if bind is not used', () => { expect.assertions(1); const unboundInputOnChange = function () { expect(this).toBe(undefined); }; const stub = <input type="text" onChange={unboundInputOnChange} />; const node = ReactDOM.render(stub, container); setUntrackedValue.call(node, 'giraffe'); dispatchEventOnNode(node, 'input'); }); it('should update defaultValue to empty string', () => { ReactDOM.render(<input type="text" defaultValue={'foo'} />, container); if (disableInputAttributeSyncing) { expect(isValueDirty(container.firstChild)).toBe(false); } else { expect(isValueDirty(container.firstChild)).toBe(true); } ReactDOM.render(<input type="text" defaultValue={''} />, container); expect(container.firstChild.defaultValue).toBe(''); if (disableInputAttributeSyncing) { expect(isValueDirty(container.firstChild)).toBe(false); } else { expect(isValueDirty(container.firstChild)).toBe(true); } }); it('should warn if value is null', () => { expect(() => ReactDOM.render(<input type="text" value={null} />, container), ).toErrorDev( '`value` prop on `input` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', ); ReactDOM.unmountComponentAtNode(container); ReactDOM.render(<input type="text" value={null} />, container); }); it('should warn if checked and defaultChecked props are specified', () => { expect(() => ReactDOM.render( <input type="radio" checked={true} defaultChecked={true} readOnly={true} />, container, ), ).toErrorDev( 'A component contains an input of type radio with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', ); ReactDOM.unmountComponentAtNode(container); ReactDOM.render( <input type="radio" checked={true} defaultChecked={true} readOnly={true} />, container, ); }); it('should warn if value and defaultValue props are specified', () => { expect(() => ReactDOM.render( <input type="text" value="foo" defaultValue="bar" readOnly={true} />, container, ), ).toErrorDev( 'A component contains an input of type text with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', ); ReactDOM.unmountComponentAtNode(container); ReactDOM.render( <input type="text" value="foo" defaultValue="bar" readOnly={true} />, container, ); }); it('should warn if controlled input switches to uncontrolled (value is undefined)', () => { const stub = ( <input type="text" value="controlled" onChange={emptyFunction} /> ); ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="text" />, container)).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if controlled input switches to uncontrolled (value is null)', () => { const stub = ( <input type="text" value="controlled" onChange={emptyFunction} /> ); ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="text" value={null} />, container), ).toErrorDev([ '`value` prop on `input` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` for uncontrolled components', 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ]); }); it('should warn if controlled input switches to uncontrolled with defaultValue', () => { const stub = ( <input type="text" value="controlled" onChange={emptyFunction} /> ); ReactDOM.render(stub, container); expect(() => ReactDOM.render( <input type="text" defaultValue="uncontrolled" />, container, ), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if uncontrolled input (value is undefined) switches to controlled', () => { const stub = <input type="text" />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="text" value="controlled" />, container), ).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\n' + ' in input (at **)', ); }); it('should warn if uncontrolled input (value is null) switches to controlled', () => { const stub = <input type="text" value={null} />; expect(() => ReactDOM.render(stub, container)).toErrorDev( '`value` prop on `input` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` for uncontrolled components.', ); expect(() => ReactDOM.render(<input type="text" value="controlled" />, container), ).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\n' + ' in input (at **)', ); }); it('should warn if controlled checkbox switches to uncontrolled (checked is undefined)', () => { const stub = ( <input type="checkbox" checked={true} onChange={emptyFunction} /> ); ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="checkbox" />, container), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if controlled checkbox switches to uncontrolled (checked is null)', () => { const stub = ( <input type="checkbox" checked={true} onChange={emptyFunction} /> ); ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="checkbox" checked={null} />, container), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if controlled checkbox switches to uncontrolled with defaultChecked', () => { const stub = ( <input type="checkbox" checked={true} onChange={emptyFunction} /> ); ReactDOM.render(stub, container); expect(() => ReactDOM.render( <input type="checkbox" defaultChecked={true} />, container, ), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if uncontrolled checkbox (checked is undefined) switches to controlled', () => { const stub = <input type="checkbox" />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="checkbox" checked={true} />, container), ).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\n' + ' in input (at **)', ); }); it('should warn if uncontrolled checkbox (checked is null) switches to controlled', () => { const stub = <input type="checkbox" checked={null} />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="checkbox" checked={true} />, container), ).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\n' + ' in input (at **)', ); }); it('should warn if controlled radio switches to uncontrolled (checked is undefined)', () => { const stub = <input type="radio" checked={true} onChange={emptyFunction} />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="radio" />, container)).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if controlled radio switches to uncontrolled (checked is null)', () => { const stub = <input type="radio" checked={true} onChange={emptyFunction} />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="radio" checked={null} />, container), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if controlled radio switches to uncontrolled with defaultChecked', () => { const stub = <input type="radio" checked={true} onChange={emptyFunction} />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="radio" defaultChecked={true} />, container), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('should warn if uncontrolled radio (checked is undefined) switches to controlled', () => { const stub = <input type="radio" />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="radio" checked={true} />, container), ).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\n' + ' in input (at **)', ); }); it('should warn if uncontrolled radio (checked is null) switches to controlled', () => { const stub = <input type="radio" checked={null} />; ReactDOM.render(stub, container); expect(() => ReactDOM.render(<input type="radio" checked={true} />, container), ).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\n' + ' in input (at **)', ); }); it('should not warn if radio value changes but never becomes controlled', () => { ReactDOM.render(<input type="radio" value="value" />, container); ReactDOM.render(<input type="radio" />, container); ReactDOM.render( <input type="radio" value="value" defaultChecked={true} />, container, ); ReactDOM.render( <input type="radio" value="value" onChange={() => null} />, container, ); ReactDOM.render(<input type="radio" />, container); }); it('should not warn if radio value changes but never becomes uncontrolled', () => { ReactDOM.render( <input type="radio" checked={false} onChange={() => null} />, container, ); const input = container.querySelector('input'); expect(isCheckedDirty(input)).toBe(true); ReactDOM.render( <input type="radio" value="value" defaultChecked={true} checked={false} onChange={() => null} />, container, ); expect(isCheckedDirty(input)).toBe(true); assertInputTrackingIsCurrent(container); }); it('should warn if radio checked false changes to become uncontrolled', () => { ReactDOM.render( <input type="radio" value="value" checked={false} onChange={() => null} />, container, ); expect(() => ReactDOM.render(<input type="radio" value="value" />, container), ).toErrorDev( 'Warning: A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, 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\n' + ' in input (at **)', ); }); it('sets type, step, min, max before value always', () => { const log = []; const originalCreateElement = document.createElement; spyOnDevAndProd(document, 'createElement').mockImplementation( function (type) { const el = originalCreateElement.apply(this, arguments); let value = ''; let typeProp = ''; if (type === 'input') { Object.defineProperty(el, 'type', { get: function () { return typeProp; }, set: function (val) { typeProp = String(val); log.push('set property type'); }, }); Object.defineProperty(el, 'value', { get: function () { return value; }, set: function (val) { value = String(val); log.push('set property value'); }, }); spyOnDevAndProd(el, 'setAttribute').mockImplementation( function (name) { log.push('set attribute ' + name); }, ); } return el; }, ); ReactDOM.render( <input value="0" onChange={() => {}} type="range" min="0" max="100" step="1" />, container, ); expect(log).toEqual([ 'set attribute min', 'set attribute max', 'set attribute step', 'set property type', 'set property value', ]); }); it('sets value properly with type coming later in props', () => { const input = ReactDOM.render(<input value="hi" type="radio" />, container); expect(input.value).toBe('hi'); }); it('does not raise a validation warning when it switches types', () => { class Input extends React.Component { state = {type: 'number', value: 1000}; render() { const {value, type} = this.state; return <input onChange={() => {}} type={type} value={value} />; } } const input = ReactDOM.render(<Input />, container); const node = ReactDOM.findDOMNode(input); // If the value is set before the type, a validation warning will raise and // the value will not be assigned. input.setState({type: 'text', value: 'Test'}); expect(node.value).toEqual('Test'); }); it('resets value of date/time input to fix bugs in iOS Safari', () => { function strify(x) { return JSON.stringify(x, null, 2); } const log = []; const originalCreateElement = document.createElement; spyOnDevAndProd(document, 'createElement').mockImplementation( function (type) { const el = originalCreateElement.apply(this, arguments); const getDefaultValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'defaultValue', ).get; const setDefaultValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'defaultValue', ).set; const getValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value', ).get; const setValue = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value', ).set; const getType = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'type', ).get; const setType = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'type', ).set; if (type === 'input') { Object.defineProperty(el, 'defaultValue', { get: function () { return getDefaultValue.call(this); }, set: function (val) { log.push(`node.defaultValue = ${strify(val)}`); setDefaultValue.call(this, val); }, }); Object.defineProperty(el, 'value', { get: function () { return getValue.call(this); }, set: function (val) { log.push(`node.value = ${strify(val)}`); setValue.call(this, val); }, }); Object.defineProperty(el, 'type', { get: function () { return getType.call(this); }, set: function (val) { log.push(`node.type = ${strify(val)}`); setType.call(this, val); }, }); spyOnDevAndProd(el, 'setAttribute').mockImplementation( function (name, val) { log.push(`node.setAttribute(${strify(name)}, ${strify(val)})`); }, ); } return el; }, ); ReactDOM.render(<input type="date" defaultValue="1980-01-01" />, container); if (disableInputAttributeSyncing) { expect(log).toEqual([ 'node.type = "date"', 'node.defaultValue = "1980-01-01"', // TODO: it's possible this reintroduces the bug because we don't assign `value` at all. // Need to check this on mobile Safari and Chrome. ]); } else { expect(log).toEqual([ 'node.type = "date"', // value must be assigned before defaultValue. This fixes an issue where the // visually displayed value of date inputs disappears on mobile Safari and Chrome: // https://github.com/facebook/react/issues/7233 'node.value = "1980-01-01"', 'node.defaultValue = "1980-01-01"', ]); } }); describe('assigning the value attribute on controlled inputs', function () { function getTestInput() { return class extends React.Component { state = { value: this.props.value == null ? '' : this.props.value, }; onChange = event => { this.setState({value: event.target.value}); }; render() { const type = this.props.type; const value = this.state.value; return <input type={type} value={value} onChange={this.onChange} />; } }; } it('always sets the attribute when values change on text inputs', function () { const Input = getTestInput(); const stub = ReactDOM.render(<Input type="text" />, container); const node = ReactDOM.findDOMNode(stub); expect(isValueDirty(node)).toBe(false); setUntrackedValue.call(node, '2'); dispatchEventOnNode(node, 'input'); expect(isValueDirty(node)).toBe(true); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe('2'); } }); it('does not set the value attribute on number inputs if focused', () => { const Input = getTestInput(); const stub = ReactDOM.render( <Input type="number" value="1" />, container, ); const node = ReactDOM.findDOMNode(stub); expect(isValueDirty(node)).toBe(true); node.focus(); setUntrackedValue.call(node, '2'); dispatchEventOnNode(node, 'input'); expect(isValueDirty(node)).toBe(true); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe('1'); } }); it('sets the value attribute on number inputs on blur', () => { const Input = getTestInput(); const stub = ReactDOM.render( <Input type="number" value="1" />, container, ); const node = ReactDOM.findDOMNode(stub); expect(isValueDirty(node)).toBe(true); node.focus(); setUntrackedValue.call(node, '2'); dispatchEventOnNode(node, 'input'); node.blur(); expect(isValueDirty(node)).toBe(true); if (disableInputAttributeSyncing) { expect(node.value).toBe('2'); expect(node.hasAttribute('value')).toBe(false); } else { expect(node.value).toBe('2'); expect(node.getAttribute('value')).toBe('2'); } }); it('an uncontrolled number input will not update the value attribute on blur', () => { const node = ReactDOM.render( <input type="number" defaultValue="1" />, container, ); if (disableInputAttributeSyncing) { expect(isValueDirty(node)).toBe(false); } else { expect(isValueDirty(node)).toBe(true); } node.focus(); setUntrackedValue.call(node, 4); dispatchEventOnNode(node, 'input'); node.blur(); expect(isValueDirty(node)).toBe(true); expect(node.getAttribute('value')).toBe('1'); }); it('an uncontrolled text input will not update the value attribute on blur', () => { const node = ReactDOM.render( <input type="text" defaultValue="1" />, container, ); if (disableInputAttributeSyncing) { expect(isValueDirty(node)).toBe(false); } else { expect(isValueDirty(node)).toBe(true); } node.focus(); setUntrackedValue.call(node, 4); dispatchEventOnNode(node, 'input'); node.blur(); expect(isValueDirty(node)).toBe(true); expect(node.getAttribute('value')).toBe('1'); }); }); describe('setting a controlled input to undefined', () => { let input; function renderInputWithStringThenWithUndefined() { let setValueToUndefined; class Input extends React.Component { constructor() { super(); setValueToUndefined = () => this.setState({value: undefined}); } state = {value: 'first'}; render() { return ( <input onChange={e => this.setState({value: e.target.value})} value={this.state.value} /> ); } } const stub = ReactDOM.render(<Input />, container); input = ReactDOM.findDOMNode(stub); setUntrackedValue.call(input, 'latest'); dispatchEventOnNode(input, 'input'); setValueToUndefined(); } it('reverts the value attribute to the initial value', () => { expect(renderInputWithStringThenWithUndefined).toErrorDev( 'A component is changing a controlled input to be uncontrolled.', ); if (disableInputAttributeSyncing) { expect(input.getAttribute('value')).toBe(null); } else { expect(input.getAttribute('value')).toBe('latest'); } }); it('preserves the value property', () => { expect(renderInputWithStringThenWithUndefined).toErrorDev( 'A component is changing a controlled input to be uncontrolled.', ); expect(input.value).toBe('latest'); }); }); describe('setting a controlled input to null', () => { let input; function renderInputWithStringThenWithNull() { let setValueToNull; class Input extends React.Component { constructor() { super(); setValueToNull = () => this.setState({value: null}); } state = {value: 'first'}; render() { return ( <input onChange={e => this.setState({value: e.target.value})} value={this.state.value} /> ); } } const stub = ReactDOM.render(<Input />, container); input = ReactDOM.findDOMNode(stub); setUntrackedValue.call(input, 'latest'); dispatchEventOnNode(input, 'input'); setValueToNull(); } it('reverts the value attribute to the initial value', () => { expect(renderInputWithStringThenWithNull).toErrorDev([ '`value` prop on `input` should not be null. ' + 'Consider using an empty string to clear the component ' + 'or `undefined` for uncontrolled components.', 'A component is changing a controlled input to be uncontrolled.', ]); if (disableInputAttributeSyncing) { expect(input.getAttribute('value')).toBe(null); } else { expect(input.getAttribute('value')).toBe('latest'); } }); it('preserves the value property', () => { expect(renderInputWithStringThenWithNull).toErrorDev([ '`value` prop on `input` should not be null. ' + 'Consider using an empty string to clear the component ' + 'or `undefined` for uncontrolled components.', 'A component is changing a controlled input to be uncontrolled.', ]); expect(input.value).toBe('latest'); }); }); describe('When given a Symbol value', function () { it('treats initial Symbol value as an empty string', function () { expect(() => ReactDOM.render( <input value={Symbol('foobar')} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe(''); } }); it('treats updated Symbol value as an empty string', function () { ReactDOM.render(<input value="foo" onChange={() => {}} />, container); expect(() => ReactDOM.render( <input value={Symbol('foobar')} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe(''); } }); it('treats initial Symbol defaultValue as an empty string', function () { ReactDOM.render(<input defaultValue={Symbol('foobar')} />, container); const node = container.firstChild; expect(node.value).toBe(''); expect(node.getAttribute('value')).toBe(''); // TODO: we should warn here. }); it('treats updated Symbol defaultValue as an empty string', function () { ReactDOM.render(<input defaultValue="foo" />, container); ReactDOM.render(<input defaultValue={Symbol('foobar')} />, container); const node = container.firstChild; if (disableInputAttributeSyncing) { expect(node.value).toBe(''); } else { expect(node.value).toBe('foo'); } expect(node.getAttribute('value')).toBe(''); // TODO: we should warn here. }); }); describe('When given a function value', function () { it('treats initial function value as an empty string', function () { expect(() => ReactDOM.render( <input value={() => {}} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe(''); } }); it('treats updated function value as an empty string', function () { ReactDOM.render(<input value="foo" onChange={() => {}} />, container); expect(() => ReactDOM.render( <input value={() => {}} onChange={() => {}} />, container, ), ).toErrorDev('Invalid value for prop `value`'); const node = container.firstChild; expect(node.value).toBe(''); if (disableInputAttributeSyncing) { expect(node.hasAttribute('value')).toBe(false); } else { expect(node.getAttribute('value')).toBe(''); } }); it('treats initial function defaultValue as an empty string', function () { ReactDOM.render(<input defaultValue={() => {}} />, container); const node = container.firstChild; expect(node.value).toBe(''); expect(node.getAttribute('value')).toBe(''); // TODO: we should warn here. }); it('treats updated function defaultValue as an empty string', function () { ReactDOM.render(<input defaultValue="foo" />, container); ReactDOM.render(<input defaultValue={() => {}} />, container); const node = container.firstChild; if (disableInputAttributeSyncing) { expect(node.value).toBe(''); expect(node.getAttribute('value')).toBe(''); } else { expect(node.value).toBe('foo'); expect(node.getAttribute('value')).toBe(''); } // TODO: we should warn here. }); }); describe('checked inputs without a value property', function () { // In absence of a value, radio and checkboxes report a value of "on". // Between 16 and 16.2, we assigned a node's value to it's current // value in order to "dettach" it from defaultValue. This had the unfortunate // side-effect of assigning value="on" to radio and checkboxes it('does not add "on" in absence of value on a checkbox', function () { ReactDOM.render( <input type="checkbox" defaultChecked={true} />, container, ); const node = container.firstChild; expect(node.value).toBe('on'); expect(node.hasAttribute('value')).toBe(false); }); it('does not add "on" in absence of value on a radio', function () { ReactDOM.render(<input type="radio" defaultChecked={true} />, container); const node = container.firstChild; expect(node.value).toBe('on'); expect(node.hasAttribute('value')).toBe(false); }); }); it('should remove previous `defaultValue`', () => { const node = ReactDOM.render( <input type="text" defaultValue="0" />, container, ); expect(node.value).toBe('0'); expect(node.defaultValue).toBe('0'); ReactDOM.render(<input type="text" />, container); expect(node.defaultValue).toBe(''); }); it('should treat `defaultValue={null}` as missing', () => { const node = ReactDOM.render( <input type="text" defaultValue="0" />, container, ); expect(node.value).toBe('0'); expect(node.defaultValue).toBe('0'); ReactDOM.render(<input type="text" defaultValue={null} />, container); expect(node.defaultValue).toBe(''); }); it('should notice input changes when reverting back to original value', () => { const log = []; function onChange(e) { log.push(e.target.value); } ReactDOM.render( <input type="text" value="" onChange={onChange} />, container, ); ReactDOM.render( <input type="text" value="a" onChange={onChange} />, container, ); const node = container.firstChild; setUntrackedValue.call(node, ''); dispatchEventOnNode(node, 'input'); expect(log).toEqual(['']); expect(node.value).toBe('a'); }); });
32.30855
114
0.603321
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export default class UnknownHookError extends Error { constructor(message: string) { super(message); // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) { Error.captureStackTrace(this, UnknownHookError); } this.name = 'UnknownHookError'; } }
23.636364
89
0.700555
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_PORTAL_TYPE} from 'shared/ReactSymbols'; import {checkKeyStringCoercion} from 'shared/CheckStringCoercion'; import type {ReactNodeList, ReactPortal} from 'shared/ReactTypes'; export function createPortal( children: ReactNodeList, containerInfo: any, // TODO: figure out the API for cross-renderer implementation. implementation: any, key: ?string = null, ): ReactPortal { if (__DEV__) { checkKeyStringCoercion(key); } return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children, containerInfo, implementation, }; }
24.588235
68
0.697353
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ const uppercasePattern = /([A-Z])/g; const msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. */ export default function hyphenateStyleName(name: string): string { return name .replace(uppercasePattern, '-$1') .toLowerCase() .replace(msPattern, '-ms-'); }
24.8125
78
0.666667
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 {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type Store from 'react-devtools-shared/src/devtools/store'; describe('ProfilingCache', () => { let PropTypes; let React; let ReactDOM; let ReactDOMClient; let Scheduler; let bridge: FrontendBridge; let legacyRender; let store: Store; let utils; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; store.recordChangeDescriptions = true; PropTypes = require('prop-types'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); Scheduler = require('scheduler'); }); // @reactVersion >= 16.9 it('should collect data for each root (including ones added or mounted after profiling started)', () => { const Parent = ({count}) => { Scheduler.unstable_advanceTime(10); const children = new Array(count) .fill(true) .map((_, index) => <Child key={index} duration={index} />); return ( <React.Fragment> {children} <MemoizedChild duration={1} /> </React.Fragment> ); }; const Child = ({duration}) => { Scheduler.unstable_advanceTime(duration); return null; }; const MemoizedChild = React.memo(Child); const RootA = ({children}) => children; const RootB = ({children}) => children; const RootC = ({children}) => children; const containerA = document.createElement('div'); const containerB = document.createElement('div'); const containerC = document.createElement('div'); utils.act(() => legacyRender( <RootA> <Parent count={2} /> </RootA>, containerA, ), ); utils.act(() => legacyRender( <RootB> <Parent count={1} /> </RootB>, containerB, ), ); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender( <RootA> <Parent count={3} /> </RootA>, containerA, ), ); utils.act(() => legacyRender( <RootC> <Parent count={1} /> </RootC>, containerC, ), ); utils.act(() => legacyRender( <RootA> <Parent count={1} /> </RootA>, containerA, ), ); utils.act(() => ReactDOM.unmountComponentAtNode(containerB)); utils.act(() => legacyRender( <RootA> <Parent count={0} /> </RootA>, containerA, ), ); utils.act(() => store.profilerStore.stopProfiling()); utils.act(() => ReactDOM.unmountComponentAtNode(containerA)); const rootIDs = Array.from( store.profilerStore.profilingData.dataForRoots.values(), ).map(({rootID}) => rootID); expect(rootIDs).toHaveLength(3); const originalProfilingDataForRoot = []; let data = store.profilerStore.getDataForRoot(rootIDs[0]); expect(data.displayName).toMatchInlineSnapshot(`"RootA"`); expect(data.commitData).toHaveLength(3); originalProfilingDataForRoot.push(data); data = store.profilerStore.getDataForRoot(rootIDs[1]); expect(data.displayName).toMatchInlineSnapshot(`"RootC"`); expect(data.commitData).toHaveLength(1); originalProfilingDataForRoot.push(data); data = store.profilerStore.getDataForRoot(rootIDs[2]); expect(data.displayName).toMatchInlineSnapshot(`"RootB"`); expect(data.commitData).toHaveLength(1); originalProfilingDataForRoot.push(data); utils.exportImportHelper(bridge, store); rootIDs.forEach((rootID, index) => { const current = store.profilerStore.getDataForRoot(rootID); const prev = originalProfilingDataForRoot[index]; expect(current).toEqual(prev); }); }); // @reactVersion >= 16.9 it('should collect data for each commit', () => { const Parent = ({count}) => { Scheduler.unstable_advanceTime(10); const children = new Array(count) .fill(true) .map((_, index) => <Child key={index} duration={index} />); return ( <React.Fragment> {children} <MemoizedChild duration={1} /> </React.Fragment> ); }; const Child = ({duration}) => { Scheduler.unstable_advanceTime(duration); return null; }; const MemoizedChild = React.memo(Child); const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<Parent count={2} />, container)); utils.act(() => legacyRender(<Parent count={3} />, container)); utils.act(() => legacyRender(<Parent count={1} />, container)); utils.act(() => legacyRender(<Parent count={0} />, container)); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const prevCommitData = store.profilerStore.getDataForRoot(rootID).commitData; expect(prevCommitData).toHaveLength(4); utils.exportImportHelper(bridge, store); const nextCommitData = store.profilerStore.getDataForRoot(rootID).commitData; expect(nextCommitData).toHaveLength(4); nextCommitData.forEach((commitData, index) => { expect(commitData).toEqual(prevCommitData[index]); }); }); // @reactVersion >= 16.9 it('should record changed props/state/context/hooks', () => { let instance = null; const ModernContext = React.createContext(0); class LegacyContextProvider extends React.Component<any, {count: number}> { static childContextTypes = { count: PropTypes.number, }; state = {count: 0}; getChildContext() { return this.state; } render() { instance = this; return ( <ModernContext.Provider value={this.state.count}> <React.Fragment> <ModernContextConsumer /> <LegacyContextConsumer /> </React.Fragment> </ModernContext.Provider> ); } } const FunctionComponentWithHooks = ({count}) => { React.useMemo(() => count, [count]); return null; }; class ModernContextConsumer extends React.Component<any> { static contextType = ModernContext; render() { return <FunctionComponentWithHooks count={this.context} />; } } class LegacyContextConsumer extends React.Component<any> { static contextTypes = { count: PropTypes.number, }; render() { return <FunctionComponentWithHooks count={this.context.count} />; } } const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<LegacyContextProvider />, container)); expect(instance).not.toBeNull(); utils.act(() => (instance: any).setState({count: 1})); utils.act(() => legacyRender(<LegacyContextProvider foo={123} />, container), ); utils.act(() => legacyRender(<LegacyContextProvider bar="abc" />, container), ); utils.act(() => legacyRender(<LegacyContextProvider />, container)); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; let changeDescriptions = store.profilerStore .getDataForRoot(rootID) .commitData.map(commitData => commitData.changeDescriptions); expect(changeDescriptions).toHaveLength(5); expect(changeDescriptions[0]).toMatchInlineSnapshot(` Map { 2 => { "context": null, "didHooksChange": false, "isFirstMount": true, "props": null, "state": null, }, 4 => { "context": null, "didHooksChange": false, "isFirstMount": true, "props": null, "state": null, }, 5 => { "context": null, "didHooksChange": false, "isFirstMount": true, "props": null, "state": null, }, 6 => { "context": null, "didHooksChange": false, "isFirstMount": true, "props": null, "state": null, }, 7 => { "context": null, "didHooksChange": false, "isFirstMount": true, "props": null, "state": null, }, } `); expect(changeDescriptions[1]).toMatchInlineSnapshot(` Map { 5 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [ "count", ], "state": null, }, 4 => { "context": true, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 7 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [ "count", ], "state": null, }, 6 => { "context": [ "count", ], "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 2 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": [ "count", ], }, } `); expect(changeDescriptions[2]).toMatchInlineSnapshot(` Map { 5 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, 4 => { "context": false, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 7 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, 6 => { "context": [], "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 2 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [ "foo", ], "state": [], }, } `); expect(changeDescriptions[3]).toMatchInlineSnapshot(` Map { 5 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, 4 => { "context": false, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 7 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, 6 => { "context": [], "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 2 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [ "foo", "bar", ], "state": [], }, } `); expect(changeDescriptions[4]).toMatchInlineSnapshot(` Map { 5 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, 4 => { "context": false, "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 7 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, 6 => { "context": [], "didHooksChange": false, "hooks": null, "isFirstMount": false, "props": [], "state": null, }, 2 => { "context": null, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [ "bar", ], "state": [], }, } `); utils.exportImportHelper(bridge, store); const prevChangeDescriptions = [...changeDescriptions]; changeDescriptions = store.profilerStore .getDataForRoot(rootID) .commitData.map(commitData => commitData.changeDescriptions); expect(changeDescriptions).toHaveLength(5); for (let commitIndex = 0; commitIndex < 5; commitIndex++) { expect(changeDescriptions[commitIndex]).toEqual( prevChangeDescriptions[commitIndex], ); } }); // @reactVersion >= 18.0 it('should properly detect changed hooks', () => { const Context = React.createContext(0); function reducer(state, action) { switch (action.type) { case 'invert': return {value: !state.value}; default: throw new Error(); } } let snapshot = 0; function getServerSnapshot() { return snapshot; } function getClientSnapshot() { return snapshot; } let syncExternalStoreCallback; function subscribe(callback) { syncExternalStoreCallback = callback; } let dispatch = null; let setState = null; const Component = ({count, string}) => { // These hooks may change and initiate re-renders. setState = React.useState('abc')[1]; dispatch = React.useReducer(reducer, {value: true})[1]; React.useSyncExternalStore( subscribe, getClientSnapshot, getServerSnapshot, ); // This hook's return value may change between renders, // but the hook itself isn't stateful. React.useContext(Context); // These hooks never change in a way that schedules an update. React.useCallback(() => () => {}, [string]); React.useMemo(() => string, [string]); React.useCallback(() => () => {}, [count]); React.useMemo(() => count, [count]); React.useCallback(() => () => {}); React.useMemo(() => string); // These hooks never change in a way that schedules an update. React.useEffect(() => {}, [string]); React.useLayoutEffect(() => {}, [string]); React.useEffect(() => {}, [count]); React.useLayoutEffect(() => {}, [count]); React.useEffect(() => {}); React.useLayoutEffect(() => {}); return null; }; const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender( <Context.Provider value={true}> <Component count={1} /> </Context.Provider>, container, ), ); // Second render has no changed hooks, only changed props. utils.act(() => legacyRender( <Context.Provider value={true}> <Component count={2} /> </Context.Provider>, container, ), ); // Third render has a changed reducer hook. utils.act(() => dispatch({type: 'invert'})); // Fourth render has a changed state hook. utils.act(() => setState('def')); // Fifth render has a changed context value, but no changed hook. utils.act(() => legacyRender( <Context.Provider value={false}> <Component count={2} /> </Context.Provider>, container, ), ); // 6th renderer is triggered by a sync external store change. utils.act(() => { snapshot++; syncExternalStoreCallback(); }); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const changeDescriptions = store.profilerStore .getDataForRoot(rootID) .commitData.map(commitData => commitData.changeDescriptions); expect(changeDescriptions).toHaveLength(6); // 1st render: No change expect(changeDescriptions[0]).toMatchInlineSnapshot(` Map { 3 => { "context": null, "didHooksChange": false, "isFirstMount": true, "props": null, "state": null, }, } `); // 2nd render: Changed props expect(changeDescriptions[1]).toMatchInlineSnapshot(` Map { 3 => { "context": false, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [ "count", ], "state": null, }, } `); // 3rd render: Changed useReducer expect(changeDescriptions[2]).toMatchInlineSnapshot(` Map { 3 => { "context": false, "didHooksChange": true, "hooks": [ 1, ], "isFirstMount": false, "props": [], "state": null, }, } `); // 4th render: Changed useState expect(changeDescriptions[3]).toMatchInlineSnapshot(` Map { 3 => { "context": false, "didHooksChange": true, "hooks": [ 0, ], "isFirstMount": false, "props": [], "state": null, }, } `); // 5th render: Changed context expect(changeDescriptions[4]).toMatchInlineSnapshot(` Map { 3 => { "context": true, "didHooksChange": false, "hooks": [], "isFirstMount": false, "props": [], "state": null, }, } `); // 6th render: Sync external store expect(changeDescriptions[5]).toMatchInlineSnapshot(` Map { 3 => { "context": false, "didHooksChange": true, "hooks": [ 2, ], "isFirstMount": false, "props": [], "state": null, }, } `); expect(changeDescriptions).toHaveLength(6); // Export and re-import profile data and make sure it is retained. utils.exportImportHelper(bridge, store); for (let commitIndex = 0; commitIndex < 6; commitIndex++) { const commitData = store.profilerStore.getCommitData(rootID, commitIndex); expect(commitData.changeDescriptions).toEqual( changeDescriptions[commitIndex], ); } }); // @reactVersion >= 18.0 it('should calculate durations based on actual children (not filtered children)', () => { store.componentFilters = [utils.createDisplayNameFilter('^Parent$')]; const Grandparent = () => { Scheduler.unstable_advanceTime(10); return ( <React.Fragment> <Parent key="one" /> <Parent key="two" /> </React.Fragment> ); }; const Parent = () => { Scheduler.unstable_advanceTime(2); return <Child />; }; const Child = () => { Scheduler.unstable_advanceTime(1); return null; }; utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); utils.act(() => store.profilerStore.stopProfiling()); expect(store).toMatchInlineSnapshot(` [root] ▾ <Grandparent> <Child> <Child> `); const rootID = store.roots[0]; const commitData = store.profilerStore.getDataForRoot(rootID).commitData; expect(commitData).toHaveLength(1); // Actual duration should also include both filtered <Parent> components. expect(commitData[0].fiberActualDurations).toMatchInlineSnapshot(` Map { 1 => 16, 2 => 16, 4 => 1, 6 => 1, } `); expect(commitData[0].fiberSelfDurations).toMatchInlineSnapshot(` Map { 1 => 0, 2 => 10, 4 => 1, 6 => 1, } `); }); // @reactVersion >= 17.0 it('should calculate durations correctly for suspended views', async () => { let data; const getData = () => { if (data) { return data; } else { throw new Promise(resolve => { data = 'abc'; resolve(data); }); } }; const Parent = () => { Scheduler.unstable_advanceTime(10); return ( <React.Suspense fallback={<Fallback />}> <Async /> </React.Suspense> ); }; const Fallback = () => { Scheduler.unstable_advanceTime(2); return 'Fallback...'; }; const Async = () => { Scheduler.unstable_advanceTime(3); return getData(); }; utils.act(() => store.profilerStore.startProfiling()); await utils.actAsync(() => legacyRender(<Parent />, document.createElement('div')), ); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const commitData = store.profilerStore.getDataForRoot(rootID).commitData; expect(commitData).toHaveLength(2); expect(commitData[0].fiberActualDurations).toMatchInlineSnapshot(` Map { 1 => 15, 2 => 15, 3 => 5, 4 => 2, } `); expect(commitData[0].fiberSelfDurations).toMatchInlineSnapshot(` Map { 1 => 0, 2 => 10, 3 => 3, 4 => 2, } `); expect(commitData[1].fiberActualDurations).toMatchInlineSnapshot(` Map { 7 => 3, 3 => 3, } `); expect(commitData[1].fiberSelfDurations).toMatchInlineSnapshot(` Map { 7 => 3, 3 => 0, } `); }); // @reactVersion >= 16.9 it('should collect data for each rendered fiber', () => { const Parent = ({count}) => { Scheduler.unstable_advanceTime(10); const children = new Array(count) .fill(true) .map((_, index) => <Child key={index} duration={index} />); return ( <React.Fragment> {children} <MemoizedChild duration={1} /> </React.Fragment> ); }; const Child = ({duration}) => { Scheduler.unstable_advanceTime(duration); return null; }; const MemoizedChild = React.memo(Child); const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<Parent count={1} />, container)); utils.act(() => legacyRender(<Parent count={2} />, container)); utils.act(() => legacyRender(<Parent count={3} />, container)); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const allFiberCommits = []; for (let index = 0; index < store.numElements; index++) { const fiberID = store.getElementIDAtIndex(index); const fiberCommits = store.profilerStore.profilingCache.getFiberCommits({ fiberID, rootID, }); allFiberCommits.push(fiberCommits); } expect(allFiberCommits).toMatchInlineSnapshot(` [ [ 0, 1, 2, ], [ 0, 1, 2, ], [ 1, 2, ], [ 2, ], [ 0, ], ] `); utils.exportImportHelper(bridge, store); for (let index = 0; index < store.numElements; index++) { const fiberID = store.getElementIDAtIndex(index); const fiberCommits = store.profilerStore.profilingCache.getFiberCommits({ fiberID, rootID, }); expect(fiberCommits).toEqual(allFiberCommits[index]); } }); // @reactVersion >= 18.0.0 // @reactVersion <= 18.2.0 it('should handle unexpectedly shallow suspense trees for react v[18.0.0 - 18.2.0]', () => { const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<React.Suspense />, container)); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const commitData = store.profilerStore.getDataForRoot(rootID).commitData; expect(commitData).toMatchInlineSnapshot(` [ { "changeDescriptions": Map {}, "duration": 0, "effectDuration": null, "fiberActualDurations": Map { 1 => 0, 2 => 0, }, "fiberSelfDurations": Map { 1 => 0, 2 => 0, }, "passiveEffectDuration": null, "priorityLevel": "Immediate", "timestamp": 0, "updaters": [ { "compiledWithForget": false, "displayName": "render()", "hocDisplayNames": null, "id": 1, "key": null, "type": 11, }, ], }, ] `); }); // This test is not gated. // For this test we use the current version of react, built from source. it('should handle unexpectedly shallow suspense trees', () => { const container = document.createElement('div'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => legacyRender(<React.Suspense />, container)); utils.act(() => store.profilerStore.stopProfiling()); const rootID = store.roots[0]; const commitData = store.profilerStore.getDataForRoot(rootID).commitData; expect(commitData).toMatchInlineSnapshot(` [ { "changeDescriptions": Map {}, "duration": 0, "effectDuration": null, "fiberActualDurations": Map { 1 => 0, 2 => 0, }, "fiberSelfDurations": Map { 1 => 0, 2 => 0, }, "passiveEffectDuration": null, "priorityLevel": "Normal", "timestamp": 0, "updaters": [ { "compiledWithForget": false, "displayName": "render()", "hocDisplayNames": null, "id": 1, "key": null, "type": 11, }, ], }, ] `); }); // See https://github.com/facebook/react/issues/18831 // @reactVersion >= 16.9 it('should not crash during route transitions with Suspense', () => { const RouterContext = React.createContext(); function App() { return ( <Router> <Switch> <Route path="/"> <Home /> </Route> <Route path="/about"> <About /> </Route> </Switch> </Router> ); } const Home = () => { return ( <React.Suspense> <Link path="/about">Home</Link> </React.Suspense> ); }; const About = () => <div>About</div>; // Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Router.js function Router({children}) { const [path, setPath] = React.useState('/'); return ( <RouterContext.Provider value={{path, setPath}}> {children} </RouterContext.Provider> ); } // Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Switch.js function Switch({children}) { return ( <RouterContext.Consumer> {context => { let element = null; React.Children.forEach(children, child => { if (context.path === child.props.path) { element = child.props.children; } }); return element ? React.cloneElement(element) : null; }} </RouterContext.Consumer> ); } // Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js function Route({children, path}) { return null; } const linkRef = React.createRef(); // Mimics https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js function Link({children, path}) { return ( <RouterContext.Consumer> {context => { return ( <button ref={linkRef} onClick={() => context.setPath(path)}> {children} </button> ); }} </RouterContext.Consumer> ); } const {Simulate} = require('react-dom/test-utils'); const container = document.createElement('div'); utils.act(() => legacyRender(<App />, container)); expect(container.textContent).toBe('Home'); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => Simulate.click(linkRef.current)); utils.act(() => store.profilerStore.stopProfiling()); expect(container.textContent).toBe('About'); }); // @reactVersion >= 18.0 it('components that were deleted and added to updaters during the layout phase should not crash', () => { let setChildUnmounted; function Child() { const [, setState] = React.useState(false); React.useLayoutEffect(() => { return () => setState(true); }); return null; } function App() { const [childUnmounted, _setChildUnmounted] = React.useState(false); setChildUnmounted = _setChildUnmounted; return <>{!childUnmounted && <Child />}</>; } const root = ReactDOMClient.createRoot(document.createElement('div')); utils.act(() => root.render(<App />)); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => setChildUnmounted(true)); utils.act(() => store.profilerStore.stopProfiling()); const updaters = store.profilerStore.getCommitData( store.roots[0], 0, ).updaters; expect(updaters.length).toEqual(1); expect(updaters[0].displayName).toEqual('App'); }); // @reactVersion >= 18.0 it('components in a deleted subtree and added to updaters during the layout phase should not crash', () => { let setChildUnmounted; function Child() { return <GrandChild />; } function GrandChild() { const [, setState] = React.useState(false); React.useLayoutEffect(() => { return () => setState(true); }); return null; } function App() { const [childUnmounted, _setChildUnmounted] = React.useState(false); setChildUnmounted = _setChildUnmounted; return <>{!childUnmounted && <Child />}</>; } const root = ReactDOMClient.createRoot(document.createElement('div')); utils.act(() => root.render(<App />)); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => setChildUnmounted(true)); utils.act(() => store.profilerStore.stopProfiling()); const updaters = store.profilerStore.getCommitData( store.roots[0], 0, ).updaters; expect(updaters.length).toEqual(1); expect(updaters[0].displayName).toEqual('App'); }); // @reactVersion >= 18.0 it('components that were deleted should not be added to updaters during the passive phase', () => { let setChildUnmounted; function Child() { const [, setState] = React.useState(false); React.useEffect(() => { return () => setState(true); }); return null; } function App() { const [childUnmounted, _setChildUnmounted] = React.useState(false); setChildUnmounted = _setChildUnmounted; return <>{!childUnmounted && <Child />}</>; } const root = ReactDOMClient.createRoot(document.createElement('div')); utils.act(() => root.render(<App />)); utils.act(() => store.profilerStore.startProfiling()); utils.act(() => setChildUnmounted(true)); utils.act(() => store.profilerStore.stopProfiling()); const updaters = store.profilerStore.getCommitData( store.roots[0], 0, ).updaters; expect(updaters.length).toEqual(1); expect(updaters[0].displayName).toEqual('App'); }); });
25.906481
113
0.535459
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-refresh-babel.production.min.js'); } else { module.exports = require('./cjs/react-refresh-babel.development.js'); }
26.375
74
0.688073
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-interactions-events/scroll.production.min.js'); } else { module.exports = require('./cjs/react-interactions-events/scroll.development.js'); }
29.625
87
0.713115
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 minimist = require('minimist'); const runESLint = require('../eslint'); async function main() { console.log('Linting all files...'); // https://circleci.com/docs/2.0/env-vars/#circleci-environment-variable-descriptions if (!process.env.CI) { console.log('Hint: run `yarn linc` to only lint changed files.'); } // eslint-disable-next-line no-unused-vars const {_, ...cliOptions} = minimist(process.argv.slice(2)); if (await runESLint({onlyChanged: false, ...cliOptions})) { console.log('Lint passed.'); } else { console.log('Lint failed.'); process.exit(1); } } main();
24.65625
87
0.665854
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); 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=Example.js.map?foo=bar&param=some_value
45.641026
743
0.648515
PenetrationTestingScripts
// Portal target container. window.container = document.getElementById('container'); let hasInjectedStyles = false; // DevTools styles are injected into the top-level document head (where the main React app is rendered). // This method copies those styles to the child window where each panel (e.g. Elements, Profiler) is portaled. window.injectStyles = getLinkTags => { if (!hasInjectedStyles) { hasInjectedStyles = true; const linkTags = getLinkTags(); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const linkTag of linkTags) { document.head.appendChild(linkTag); } } };
30.35
110
0.722045
owtf
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-jsx-runtime.production.min.js'); } else { module.exports = require('./cjs/react-jsx-runtime.development.js'); }
25.875
72
0.682243
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'; /** * turns * { 'MUCH ERROR': '0', 'SUCH WRONG': '1' } * into * { 0: 'MUCH ERROR', 1: 'SUCH WRONG' } */ function invertObject(targetObj) { const result = {}; const mapKeys = Object.keys(targetObj); // eslint-disable-next-line no-for-of-loops/no-for-of-loops for (const originalKey of mapKeys) { const originalVal = targetObj[originalKey]; result[originalVal] = originalKey; } return result; } module.exports = invertObject;
21.133333
66
0.662142
PenTestScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /* 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
owtf
'use strict'; // This file is a proxy for our rule definition that will // load the latest built version on every check. This makes // it convenient to test inside IDEs (which would otherwise // load a version of our rule once and never restart the server). // See instructions in ../index.js playground. let build; reload(); function reload() { for (let id in require.cache) { if (/eslint-plugin-react-hooks/.test(id)) { delete require.cache[id]; } } // Point to the built version. build = require('../../../build/oss-experimental/eslint-plugin-react-hooks'); } let rules = {}; for (let key in build.rules) { if (build.rules.hasOwnProperty(key)) { rules[key] = Object.assign({}, build.rules, { create() { // Reload changes to the built rule reload(); return build.rules[key].create.apply(this, arguments); }, }); } } module.exports = {rules};
24.555556
79
0.645267
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 type {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import { createContext, useCallback, useContext, useMemo, useReducer, useRef, } from 'react'; import Button from './Button'; import {useModalDismissSignal} from './hooks'; import styles from './ModalDialog.css'; type ID = any; type DIALOG_ACTION_HIDE = { type: 'HIDE', id: ID, }; type DIALOG_ACTION_SHOW = { type: 'SHOW', canBeDismissed?: boolean, content: React$Node, id: ID, title?: React$Node | null, }; type Action = DIALOG_ACTION_HIDE | DIALOG_ACTION_SHOW; type Dispatch = (action: Action) => void; type Dialog = { canBeDismissed: boolean, content: React$Node | null, id: ID, title: React$Node | null, }; type State = { dialogs: Array<Dialog>, }; type ModalDialogContextType = { ...State, dispatch: Dispatch, }; const ModalDialogContext: ReactContext<ModalDialogContextType> = createContext<ModalDialogContextType>(((null: any): ModalDialogContextType)); ModalDialogContext.displayName = 'ModalDialogContext'; function dialogReducer(state: State, action: Action) { switch (action.type) { case 'HIDE': return { dialogs: state.dialogs.filter(dialog => dialog.id !== action.id), }; case 'SHOW': return { dialogs: [ ...state.dialogs, { canBeDismissed: action.canBeDismissed !== false, content: action.content, id: action.id, title: action.title || null, }, ], }; default: throw new Error(`Invalid action "${action.type}"`); } } type Props = { children: React$Node, }; function ModalDialogContextController({children}: Props): React.Node { const [state, dispatch] = useReducer<State, State, Action>(dialogReducer, { dialogs: [], }); const value = useMemo<ModalDialogContextType>( () => ({ dialogs: state.dialogs, dispatch, }), [state, dispatch], ); return ( <ModalDialogContext.Provider value={value}> {children} </ModalDialogContext.Provider> ); } function ModalDialog(_: {}): React.Node { const {dialogs, dispatch} = useContext(ModalDialogContext); if (dialogs.length === 0) { return null; } return ( <div className={styles.Background}> {dialogs.map(dialog => ( <ModalDialogImpl key={dialog.id} canBeDismissed={dialog.canBeDismissed} content={dialog.content} dispatch={dispatch} id={dialog.id} title={dialog.title} /> ))} </div> ); } function ModalDialogImpl({ canBeDismissed, content, dispatch, id, title, }: { canBeDismissed: boolean, content: React$Node | null, dispatch: Dispatch, id: ID, title: React$Node | null, }) { const dismissModal = useCallback(() => { if (canBeDismissed) { dispatch({type: 'HIDE', id}); } }, [canBeDismissed, dispatch]); const dialogRef = useRef<HTMLDivElement | null>(null); // It's important to trap click events within the dialog, // so the dismiss hook will use it for click hit detection. // Because multiple tabs may be showing this ModalDialog, // the normal `dialog.contains(target)` check would fail on a background tab. useModalDismissSignal(dialogRef, dismissModal, false); // Clicks on the dialog should not bubble. // This way we can dismiss by listening to clicks on the background. const handleDialogClick = (event: any) => { event.stopPropagation(); // It is important that we don't also prevent default, // or clicks within the dialog (e.g. on links) won't work. }; return ( <div ref={dialogRef} className={styles.Dialog} onClick={handleDialogClick}> {title !== null && <div className={styles.Title}>{title}</div>} {content} {canBeDismissed && ( <div className={styles.Buttons}> <Button autoFocus={true} className={styles.Button} onClick={dismissModal}> Okay </Button> </div> )} </div> ); } export {ModalDialog, ModalDialogContext, ModalDialogContextController};
22.374332
79
0.629977
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {useCallback, useContext, useMemo} from 'react'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import {BridgeContext, StoreContext} from '../context'; import {useSubscription} from '../hooks'; type SubscriptionData = { recordChangeDescriptions: boolean, supportsReloadAndProfile: boolean, }; export default function ReloadAndProfileButton({ disabled, }: { disabled: boolean, }): React.Node { const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const subscription = useMemo( () => ({ getCurrentValue: () => ({ recordChangeDescriptions: store.recordChangeDescriptions, supportsReloadAndProfile: store.supportsReloadAndProfile, }), subscribe: (callback: Function) => { store.addListener('recordChangeDescriptions', callback); store.addListener('supportsReloadAndProfile', callback); return () => { store.removeListener('recordChangeDescriptions', callback); store.removeListener('supportsReloadAndProfile', callback); }; }, }), [store], ); const {recordChangeDescriptions, supportsReloadAndProfile} = useSubscription<SubscriptionData>(subscription); const reloadAndProfile = useCallback(() => { // TODO If we want to support reload-and-profile for e.g. React Native, // we might need to also start profiling here before reloading the app (since DevTools itself isn't reloaded). // We'd probably want to do this before reloading though, to avoid sending a message on a disconnected port in the browser. // For now, let's just skip doing it entirely to avoid paying snapshot costs for data we don't need. // startProfiling(); bridge.send('reloadAndProfile', recordChangeDescriptions); }, [bridge, recordChangeDescriptions]); if (!supportsReloadAndProfile) { return null; } return ( <Button disabled={disabled} onClick={reloadAndProfile} title="Reload and start profiling"> <ButtonIcon type="reload" /> </Button> ); }
30.739726
127
0.693869
cybersecurity-penetration-testing
/** @flow */ import {createElement} from 'react'; import {createRoot} from 'react-dom/client'; import { activate as activateBackend, initialize as initializeBackend, } from 'react-devtools-inline/backend'; import {initialize as initializeFrontend} from 'react-devtools-inline/frontend'; import {initDevTools} from 'react-devtools-shared/src/devtools'; // This is a pretty gross hack to make the runtime loaded named-hooks-code work. // TODO (Webpack 5) Hoepfully we can remove this once we upgrade to Webpack 5. // $FlowFixMe[cannot-resolve-name] __webpack_public_path__ = '/dist/'; // eslint-disable-line no-undef const iframe = ((document.getElementById('target'): any): HTMLIFrameElement); const {contentDocument, contentWindow} = iframe; // Helps with positioning Overlay UI. contentWindow.__REACT_DEVTOOLS_TARGET_WINDOW__ = window; initializeBackend(contentWindow); // Initialize the front end and activate the backend early so that we are able // to pass console settings in local storage to the backend before initial render const DevTools = initializeFrontend(contentWindow); // Activate the backend only once the DevTools frontend Store has been initialized. // Otherwise the Store may miss important initial tree op codes. activateBackend(contentWindow); const container = ((document.getElementById('devtools'): any): HTMLElement); let isTestAppMounted = true; const mountButton = ((document.getElementById( 'mountButton', ): any): HTMLButtonElement); mountButton.addEventListener('click', function () { if (isTestAppMounted) { if (typeof window.unmountTestApp === 'function') { window.unmountTestApp(); mountButton.innerText = 'Mount test app'; isTestAppMounted = false; } } else { if (typeof window.mountTestApp === 'function') { window.mountTestApp(); mountButton.innerText = 'Unmount test app'; isTestAppMounted = true; } } }); // TODO (Webpack 5) Hopefully we can remove this prop after the Webpack 5 migration. function hookNamesModuleLoaderFunction() { return import('react-devtools-inline/hookNames'); } inject('dist/app-index.js', () => { initDevTools({ connect(cb) { const root = createRoot(container); root.render( createElement(DevTools, { browserTheme: 'light', enabledInspectedElementContextMenu: true, hookNamesModuleLoaderFunction, showTabBar: true, warnIfLegacyBackendDetected: true, warnIfUnsupportedVersionDetected: true, }), ); }, onReload(reloadFn) { iframe.onload = reloadFn; }, }); }); function inject(sourcePath: string, callback: () => void) { const script = contentDocument.createElement('script'); script.onload = callback; script.src = sourcePath; ((contentDocument.body: any): HTMLBodyElement).appendChild(script); }
30.505495
84
0.710747
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 {createAsyncHook, executionAsyncId} from './ReactFlightServerConfig'; import {enableAsyncDebugInfo} from 'shared/ReactFeatureFlags'; // Initialize the tracing of async operations. // We do this globally since the async work can potentially eagerly // start before the first request and once requests start they can interleave. // In theory we could enable and disable using a ref count of active requests // but given that typically this is just a live server, it doesn't really matter. export function initAsyncDebugInfo(): void { if (__DEV__ && enableAsyncDebugInfo) { createAsyncHook({ init(asyncId: number, type: string, triggerAsyncId: number): void { // TODO }, promiseResolve(asyncId: number): void { // TODO executionAsyncId(); }, destroy(asyncId: number): void { // TODO }, }).enable(); } }
31.147059
81
0.686813
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-turbopack-client.node.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-turbopack-client.node.development.js'); }
31.125
93
0.710938
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'; // Polyfills for test environment global.ReadableStream = require('web-streams-polyfill/ponyfill/es6').ReadableStream; global.TextEncoder = require('util').TextEncoder; global.TextDecoder = require('util').TextDecoder; let clientExports; let serverExports; let webpackMap; let webpackServerMap; let act; let React; let ReactDOM; let ReactDOMClient; let ReactDOMFizzServer; let ReactServerDOMServer; let ReactServerDOMClient; let Suspense; let use; let ReactServer; let ReactServerDOM; describe('ReactFlightDOMBrowser', () => { beforeEach(() => { jest.resetModules(); // Simulate the condition resolution jest.mock('react', () => require('react/react.shared-subset')); jest.mock('react-server-dom-webpack/server', () => require('react-server-dom-webpack/server.browser'), ); const WebpackMock = require('./utils/WebpackMock'); clientExports = WebpackMock.clientExports; serverExports = WebpackMock.serverExports; webpackMap = WebpackMock.webpackMap; webpackServerMap = WebpackMock.webpackServerMap; ReactServer = require('react'); ReactServerDOM = require('react-dom'); ReactServerDOMServer = require('react-server-dom-webpack/server.browser'); __unmockReact(); jest.resetModules(); act = require('internal-test-utils').act; React = require('react'); ReactDOM = require('react-dom'); ReactDOMClient = require('react-dom/client'); ReactDOMFizzServer = require('react-dom/server.browser'); ReactServerDOMClient = require('react-server-dom-webpack/client'); Suspense = React.Suspense; use = React.use; }); function makeDelayedText(Model) { let error, _resolve, _reject; let promise = new Promise((resolve, reject) => { _resolve = () => { promise = null; resolve(); }; _reject = e => { error = e; promise = null; reject(e); }; }); function DelayedText({children}, data) { if (promise) { throw promise; } if (error) { throw error; } return <Model>{children}</Model>; } return [DelayedText, _resolve, _reject]; } const theInfinitePromise = new Promise(() => {}); function InfiniteSuspend() { throw theInfinitePromise; } function requireServerRef(ref) { let name = ''; let resolvedModuleData = webpackServerMap[ref]; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // We didn't find this specific export name but we might have the * export // which contains this name as well. // TODO: It's unfortunate that we now have to parse this string. We should // probably go back to encoding path and name separately on the client reference. const idx = ref.lastIndexOf('#'); if (idx !== -1) { name = ref.slice(idx + 1); resolvedModuleData = webpackServerMap[ref.slice(0, idx)]; } if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + ref + '" in the React Client Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } } const mod = __webpack_require__(resolvedModuleData.id); if (name === '*') { return mod; } return mod[name]; } async function callServer(actionId, body) { const fn = requireServerRef(actionId); const args = await ReactServerDOMServer.decodeReply(body, webpackServerMap); return fn.apply(null, args); } it('should resolve HTML using W3C streams', async () => { function Text({children}) { return <span>{children}</span>; } function HTML() { return ( <div> <Text>hello</Text> <Text>world</Text> </div> ); } function App() { const model = { html: <HTML />, }; return model; } const stream = ReactServerDOMServer.renderToReadableStream(<App />); const response = ReactServerDOMClient.createFromReadableStream(stream); const model = await response; expect(model).toEqual({ html: ( <div> <span>hello</span> <span>world</span> </div> ), }); }); it('should resolve HTML using W3C streams', async () => { function Text({children}) { return <span>{children}</span>; } function HTML() { return ( <div> <Text>hello</Text> <Text>world</Text> </div> ); } function App() { const model = { html: <HTML />, }; return model; } const stream = ReactServerDOMServer.renderToReadableStream(<App />); const response = ReactServerDOMClient.createFromReadableStream(stream); const model = await response; expect(model).toEqual({ html: ( <div> <span>hello</span> <span>world</span> </div> ), }); }); it('should progressively reveal server components', async () => { let reportedErrors = []; // Client Components class ErrorBoundary extends React.Component { state = {hasError: false, error: null}; static getDerivedStateFromError(error) { return { hasError: true, error, }; } render() { if (this.state.hasError) { return this.props.fallback(this.state.error); } return this.props.children; } } let errorBoundaryFn; if (__DEV__) { errorBoundaryFn = e => ( <p> {e.message} + {e.digest} </p> ); } else { errorBoundaryFn = e => { expect(e.message).toBe( 'An error occurred in the Server Components render. The specific message is omitted in production' + ' builds to avoid leaking sensitive details. A digest property is included on this error instance which' + ' may provide additional details about the nature of the error.', ); return <p>{e.digest}</p>; }; } function MyErrorBoundary({children}) { return ( <ErrorBoundary fallback={errorBoundaryFn}>{children}</ErrorBoundary> ); } // Model function Text({children}) { return children; } const [Friends, resolveFriends] = makeDelayedText(Text); const [Name, resolveName] = makeDelayedText(Text); const [Posts, resolvePosts] = makeDelayedText(Text); const [Photos, resolvePhotos] = makeDelayedText(Text); const [Games, , rejectGames] = makeDelayedText(Text); // View function ProfileDetails({avatar}) { return ( <div> <Name>:name:</Name> {avatar} </div> ); } function ProfileSidebar({friends}) { return ( <div> <Photos>:photos:</Photos> {friends} </div> ); } function ProfilePosts({posts}) { return <div>{posts}</div>; } function ProfileGames({games}) { return <div>{games}</div>; } const MyErrorBoundaryClient = clientExports(MyErrorBoundary); function ProfileContent() { return ( <> <ProfileDetails avatar={<Text>:avatar:</Text>} /> <Suspense fallback={<p>(loading sidebar)</p>}> <ProfileSidebar friends={<Friends>:friends:</Friends>} /> </Suspense> <Suspense fallback={<p>(loading posts)</p>}> <ProfilePosts posts={<Posts>:posts:</Posts>} /> </Suspense> <MyErrorBoundaryClient> <Suspense fallback={<p>(loading games)</p>}> <ProfileGames games={<Games>:games:</Games>} /> </Suspense> </MyErrorBoundaryClient> </> ); } const model = { rootContent: <ProfileContent />, }; function ProfilePage({response}) { return use(response).rootContent; } const stream = ReactServerDOMServer.renderToReadableStream( model, webpackMap, { onError(x) { reportedErrors.push(x); return __DEV__ ? `a dev digest` : `digest("${x.message}")`; }, }, ); const response = ReactServerDOMClient.createFromReadableStream(stream); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <Suspense fallback={<p>(loading)</p>}> <ProfilePage response={response} /> </Suspense>, ); }); expect(container.innerHTML).toBe('<p>(loading)</p>'); // This isn't enough to show anything. await act(() => { resolveFriends(); }); expect(container.innerHTML).toBe('<p>(loading)</p>'); // We can now show the details. Sidebar and posts are still loading. await act(() => { resolveName(); }); // Advance time enough to trigger a nested fallback. jest.advanceTimersByTime(500); expect(container.innerHTML).toBe( '<div>:name::avatar:</div>' + '<p>(loading sidebar)</p>' + '<p>(loading posts)</p>' + '<p>(loading games)</p>', ); expect(reportedErrors).toEqual([]); const theError = new Error('Game over'); // Let's *fail* loading games. await act(() => { rejectGames(theError); }); const gamesExpectedValue = __DEV__ ? '<p>Game over + a dev digest</p>' : '<p>digest("Game over")</p>'; expect(container.innerHTML).toBe( '<div>:name::avatar:</div>' + '<p>(loading sidebar)</p>' + '<p>(loading posts)</p>' + gamesExpectedValue, ); expect(reportedErrors).toEqual([theError]); reportedErrors = []; // We can now show the sidebar. await act(() => { resolvePhotos(); }); expect(container.innerHTML).toBe( '<div>:name::avatar:</div>' + '<div>:photos::friends:</div>' + '<p>(loading posts)</p>' + gamesExpectedValue, ); // Show everything. await act(() => { resolvePosts(); }); expect(container.innerHTML).toBe( '<div>:name::avatar:</div>' + '<div>:photos::friends:</div>' + '<div>:posts:</div>' + gamesExpectedValue, ); expect(reportedErrors).toEqual([]); }); it('should close the stream upon completion when rendering to W3C streams', async () => { // Model function Text({children}) { return children; } const [Friends, resolveFriends] = makeDelayedText(Text); const [Name, resolveName] = makeDelayedText(Text); const [Posts, resolvePosts] = makeDelayedText(Text); const [Photos, resolvePhotos] = makeDelayedText(Text); // View function ProfileDetails({avatar}) { return ( <div> <Name>:name:</Name> {avatar} </div> ); } function ProfileSidebar({friends}) { return ( <div> <Photos>:photos:</Photos> {friends} </div> ); } function ProfilePosts({posts}) { return <div>{posts}</div>; } function ProfileContent() { return ( <Suspense fallback="(loading everything)"> <ProfileDetails avatar={<Text>:avatar:</Text>} /> <Suspense fallback={<p>(loading sidebar)</p>}> <ProfileSidebar friends={<Friends>:friends:</Friends>} /> </Suspense> <Suspense fallback={<p>(loading posts)</p>}> <ProfilePosts posts={<Posts>:posts:</Posts>} /> </Suspense> </Suspense> ); } const model = { rootContent: <ProfileContent />, }; const stream = ReactServerDOMServer.renderToReadableStream( model, webpackMap, ); const reader = stream.getReader(); const decoder = new TextDecoder(); let flightResponse = ''; let isDone = false; reader.read().then(function progress({done, value}) { if (done) { isDone = true; return; } flightResponse += decoder.decode(value); return reader.read().then(progress); }); // Advance time enough to trigger a nested fallback. jest.advanceTimersByTime(500); await act(() => {}); expect(flightResponse).toContain('(loading everything)'); expect(flightResponse).toContain('(loading sidebar)'); expect(flightResponse).toContain('(loading posts)'); expect(flightResponse).not.toContain(':friends:'); expect(flightResponse).not.toContain(':name:'); await act(() => { resolveFriends(); }); expect(flightResponse).toContain(':friends:'); await act(() => { resolveName(); }); expect(flightResponse).toContain(':name:'); await act(() => { resolvePhotos(); }); expect(flightResponse).toContain(':photos:'); await act(() => { resolvePosts(); }); expect(flightResponse).toContain(':posts:'); // Final pending chunk is written; stream should be closed. expect(isDone).toBeTruthy(); }); it('should be able to complete after aborting and throw the reason client-side', async () => { const reportedErrors = []; let errorBoundaryFn; if (__DEV__) { errorBoundaryFn = e => ( <p> {e.message} + {e.digest} </p> ); } else { errorBoundaryFn = e => { expect(e.message).toBe( 'An error occurred in the Server Components render. The specific message is omitted in production' + ' builds to avoid leaking sensitive details. A digest property is included on this error instance which' + ' may provide additional details about the nature of the error.', ); return <p>{e.digest}</p>; }; } class ErrorBoundary extends React.Component { state = {hasError: false, error: null}; static getDerivedStateFromError(error) { return { hasError: true, error, }; } render() { if (this.state.hasError) { return this.props.fallback(this.state.error); } return this.props.children; } } const controller = new AbortController(); const stream = ReactServerDOMServer.renderToReadableStream( <div> <InfiniteSuspend /> </div>, webpackMap, { signal: controller.signal, onError(x) { const message = typeof x === 'string' ? x : x.message; reportedErrors.push(x); return __DEV__ ? 'a dev digest' : `digest("${message}")`; }, }, ); const response = ReactServerDOMClient.createFromReadableStream(stream); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); function App({res}) { return use(res); } await act(() => { root.render( <ErrorBoundary fallback={errorBoundaryFn}> <Suspense fallback={<p>(loading)</p>}> <App res={response} /> </Suspense> </ErrorBoundary>, ); }); expect(container.innerHTML).toBe('<p>(loading)</p>'); await act(() => { controller.abort('for reasons'); }); const expectedValue = __DEV__ ? '<p>Error: for reasons + a dev digest</p>' : '<p>digest("for reasons")</p>'; expect(container.innerHTML).toBe(expectedValue); expect(reportedErrors).toEqual(['for reasons']); }); it('should warn in DEV a child is missing keys', async () => { function ParentClient({children}) { return children; } const Parent = clientExports(ParentClient); const ParentModule = clientExports({Parent: ParentClient}); await expect(async () => { const stream = ReactServerDOMServer.renderToReadableStream( <> <Parent>{Array(6).fill(<div>no key</div>)}</Parent> <ParentModule.Parent> {Array(6).fill(<div>no key</div>)} </ParentModule.Parent> </>, webpackMap, ); await ReactServerDOMClient.createFromReadableStream(stream); }).toErrorDev( 'Each child in a list should have a unique "key" prop. ' + 'See https://reactjs.org/link/warning-keys for more information.', ); }); it('basic use(promise)', async () => { function Server() { return ( ReactServer.use(Promise.resolve('A')) + ReactServer.use(Promise.resolve('B')) + ReactServer.use(Promise.resolve('C')) ); } const stream = ReactServerDOMServer.renderToReadableStream(<Server />); const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <Suspense fallback="Loading..."> <Client /> </Suspense>, ); }); expect(container.innerHTML).toBe('ABC'); }); // @gate enableServerContext it('basic use(context)', async () => { let ContextA; let ContextB; expect(() => { ContextA = React.createServerContext('ContextA', ''); ContextB = React.createServerContext('ContextB', 'B'); }).toErrorDev( [ 'Server Context is deprecated and will soon be removed. ' + 'It was never documented and we have found it not to be useful ' + 'enough to warrant the downside it imposes on all apps.', 'Server Context is deprecated and will soon be removed. ' + 'It was never documented and we have found it not to be useful ' + 'enough to warrant the downside it imposes on all apps.', ], {withoutStack: true}, ); function ServerComponent() { return ReactServer.use(ContextA) + ReactServer.use(ContextB); } function Server() { return ( <ContextA.Provider value="A"> <ServerComponent /> </ContextA.Provider> ); } const stream = ReactServerDOMServer.renderToReadableStream(<Server />); const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { // Client uses a different renderer. // We reset _currentRenderer here to not trigger a warning about multiple // renderers concurrently using this context ContextA._currentRenderer = null; root.render(<Client />); }); expect(container.innerHTML).toBe('AB'); }); it('use(promise) in multiple components', async () => { function Child({prefix}) { return ( prefix + ReactServer.use(Promise.resolve('C')) + ReactServer.use(Promise.resolve('D')) ); } function Parent() { return ( <Child prefix={ ReactServer.use(Promise.resolve('A')) + ReactServer.use(Promise.resolve('B')) } /> ); } const stream = ReactServerDOMServer.renderToReadableStream(<Parent />); const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <Suspense fallback="Loading..."> <Client /> </Suspense>, ); }); expect(container.innerHTML).toBe('ABCD'); }); it('using a rejected promise will throw', async () => { const promiseA = Promise.resolve('A'); const promiseB = Promise.reject(new Error('Oops!')); const promiseC = Promise.resolve('C'); // Jest/Node will raise an unhandled rejected error unless we await this. It // works fine in the browser, though. await expect(promiseB).rejects.toThrow('Oops!'); function Server() { return ( ReactServer.use(promiseA) + ReactServer.use(promiseB) + ReactServer.use(promiseC) ); } const reportedErrors = []; const stream = ReactServerDOMServer.renderToReadableStream( <Server />, webpackMap, { onError(x) { reportedErrors.push(x); return __DEV__ ? 'a dev digest' : `digest("${x.message}")`; }, }, ); const response = ReactServerDOMClient.createFromReadableStream(stream); class ErrorBoundary extends React.Component { state = {error: null}; static getDerivedStateFromError(error) { return {error}; } render() { if (this.state.error) { return __DEV__ ? this.state.error.message + ' + ' + this.state.error.digest : this.state.error.digest; } return this.props.children; } } function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <ErrorBoundary> <Client /> </ErrorBoundary>, ); }); expect(container.innerHTML).toBe( __DEV__ ? 'Oops! + a dev digest' : 'digest("Oops!")', ); expect(reportedErrors.length).toBe(1); expect(reportedErrors[0].message).toBe('Oops!'); }); it("use a promise that's already been instrumented and resolved", async () => { const thenable = { status: 'fulfilled', value: 'Hi', then() {}, }; // This will never suspend because the thenable already resolved function Server() { return ReactServer.use(thenable); } const stream = ReactServerDOMServer.renderToReadableStream(<Server />); const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Client />); }); expect(container.innerHTML).toBe('Hi'); }); it('unwraps thenable that fulfills synchronously without suspending', async () => { function Server() { const thenable = { then(resolve) { // This thenable immediately resolves, synchronously, without waiting // a microtask. resolve('Hi'); }, }; try { return ReactServer.use(thenable); } catch { throw new Error( '`use` should not suspend because the thenable resolved synchronously.', ); } } // Because the thenable resolves synchronously, we should be able to finish // rendering synchronously, with no fallback. const stream = ReactServerDOMServer.renderToReadableStream(<Server />); const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Client />); }); expect(container.innerHTML).toBe('Hi'); }); it('can pass a higher order function by reference from server to client', async () => { let actionProxy; function Client({action}) { actionProxy = action; return 'Click Me'; } function greet(transform, text) { return 'Hello ' + transform(text); } function upper(text) { return text.toUpperCase(); } const ServerModuleA = serverExports({ greet, }); const ServerModuleB = serverExports({ upper, }); const ClientRef = clientExports(Client); const boundFn = ServerModuleA.greet.bind(null, ServerModuleB.upper); const stream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={boundFn} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(stream, { async callServer(ref, args) { const body = await ReactServerDOMClient.encodeReply(args); return callServer(ref, body); }, }); function App() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); expect(container.innerHTML).toBe('Click Me'); expect(typeof actionProxy).toBe('function'); expect(actionProxy).not.toBe(boundFn); const result = await actionProxy('hi'); expect(result).toBe('Hello HI'); }); it('can call a module split server function', async () => { let actionProxy; function Client({action}) { actionProxy = action; return 'Click Me'; } function greet(text) { return 'Hello ' + text; } const ServerModule = serverExports({ // This gets split into another module split: greet, }); const ClientRef = clientExports(Client); const stream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={ServerModule.split} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(stream, { async callServer(ref, args) { const body = await ReactServerDOMClient.encodeReply(args); return callServer(ref, body); }, }); function App() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); expect(container.innerHTML).toBe('Click Me'); expect(typeof actionProxy).toBe('function'); const result = await actionProxy('Split'); expect(result).toBe('Hello Split'); }); it('can pass a server function by importing from client back to server', async () => { function greet(transform, text) { return 'Hello ' + transform(text); } function upper(text) { return text.toUpperCase(); } const ServerModuleA = serverExports({ greet, }); const ServerModuleB = serverExports({ upper, }); let actionProxy; // This is a Proxy representing ServerModuleB in the Client bundle. const ServerModuleBImportedOnClient = { upper: ReactServerDOMClient.createServerReference( ServerModuleB.upper.$$id, async function (ref, args) { const body = await ReactServerDOMClient.encodeReply(args); return callServer(ref, body); }, ), }; function Client({action}) { // Client side pass a Server Reference into an action. actionProxy = text => action(ServerModuleBImportedOnClient.upper, text); return 'Click Me'; } const ClientRef = clientExports(Client); const stream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={ServerModuleA.greet} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(stream, { async callServer(ref, args) { const body = await ReactServerDOMClient.encodeReply(args); return callServer(ref, body); }, }); function App() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); expect(container.innerHTML).toBe('Click Me'); const result = await actionProxy('hi'); expect(result).toBe('Hello HI'); }); it('can bind arguments to a server reference', async () => { let actionProxy; function Client({action}) { actionProxy = action; return 'Click Me'; } const greet = serverExports(function greet(a, b, c) { return a + ' ' + b + c; }); const ClientRef = clientExports(Client); const stream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={greet.bind(null, 'Hello').bind(null, 'World')} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(stream, { async callServer(actionId, args) { const body = await ReactServerDOMClient.encodeReply(args); return callServer(actionId, body); }, }); function App() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); expect(container.innerHTML).toBe('Click Me'); expect(typeof actionProxy).toBe('function'); expect(actionProxy).not.toBe(greet); const result = await actionProxy('!'); expect(result).toBe('Hello World!'); }); it('propagates server reference errors to the client', async () => { let actionProxy; function Client({action}) { actionProxy = action; return 'Click Me'; } async function send(text) { return Promise.reject(new Error(`Error for ${text}`)); } const ServerModule = serverExports({send}); const ClientRef = clientExports(Client); const stream = ReactServerDOMServer.renderToReadableStream( <ClientRef action={ServerModule.send} />, webpackMap, ); const response = ReactServerDOMClient.createFromReadableStream(stream, { async callServer(actionId, args) { const body = await ReactServerDOMClient.encodeReply(args); return ReactServerDOMClient.createFromReadableStream( ReactServerDOMServer.renderToReadableStream( callServer(actionId, body), null, {onError: error => 'test-error-digest'}, ), ); }, }); function App() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); if (__DEV__) { await expect(actionProxy('test')).rejects.toThrow('Error for test'); } else { let thrownError; try { await actionProxy('test'); } catch (error) { thrownError = error; } expect(thrownError).toEqual( new Error( 'An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.', ), ); expect(thrownError.digest).toBe('test-error-digest'); } }); it('supports Float hints before the first await in server components in Fiber', async () => { function Component() { return <p>hello world</p>; } const ClientComponent = clientExports(Component); async function ServerComponent() { ReactServerDOM.preload('before', {as: 'style'}); await 1; ReactServerDOM.preload('after', {as: 'style'}); return <ClientComponent />; } const stream = ReactServerDOMServer.renderToReadableStream( <ServerComponent />, webpackMap, ); let response = null; function getResponse() { if (response === null) { response = ReactServerDOMClient.createFromReadableStream(stream); } return response; } function App() { return getResponse(); } // pausing to let Flight runtime tick. This is a test only artifact of the fact that // we aren't operating separate module graphs for flight and fiber. In a real app // each would have their own dispatcher and there would be no cross dispatching. await 1; const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<App />); }); expect(document.head.innerHTML).toBe( '<link rel="preload" href="before" as="style">', ); expect(container.innerHTML).toBe('<p>hello world</p>'); }); it('Does not support Float hints in server components anywhere in Fizz', async () => { // In environments that do not support AsyncLocalStorage the Flight client has no ability // to scope hint dispatching to a specific Request. In Fiber this isn't a problem because // the Browser scope acts like a singleton and we can dispatch away. But in Fizz we need to have // a reference to Resources and this is only possible during render unless you support AsyncLocalStorage. function Component() { return <p>hello world</p>; } const ClientComponent = clientExports(Component); async function ServerComponent() { ReactDOM.preload('before', {as: 'style'}); await 1; ReactDOM.preload('after', {as: 'style'}); return <ClientComponent />; } const stream = ReactServerDOMServer.renderToReadableStream( <ServerComponent />, webpackMap, ); let response = null; function getResponse() { if (response === null) { response = ReactServerDOMClient.createFromReadableStream(stream); } return response; } function App() { return ( <html> <body>{getResponse()}</body> </html> ); } // pausing to let Flight runtime tick. This is a test only artifact of the fact that // we aren't operating separate module graphs for flight and fiber. In a real app // each would have their own dispatcher and there would be no cross dispatching. await 1; let fizzStream; await act(async () => { fizzStream = await ReactDOMFizzServer.renderToReadableStream(<App />); }); const decoder = new TextDecoder(); const reader = fizzStream.getReader(); let content = ''; while (true) { const {done, value} = await reader.read(); if (done) { content += decoder.decode(); break; } content += decoder.decode(value, {stream: true}); } expect(content).toEqual( '<!DOCTYPE html><html><head>' + '</head><body><p>hello world</p></body></html>', ); }); // @gate enablePostpone it('supports postpone in Server Components', async () => { function Server() { React.unstable_postpone('testing postpone'); return 'Not shown'; } let postponed = null; const stream = ReactServerDOMServer.renderToReadableStream( <Suspense fallback="Loading..."> <Server /> </Suspense>, null, { onPostpone(reason) { postponed = reason; }, }, ); const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <div> Shell: <Client /> </div>, ); }); // We should have reserved the shell already. Which means that the Server // Component should've been a lazy component. expect(container.innerHTML).toContain('Shell:'); expect(container.innerHTML).toContain('Loading...'); expect(container.innerHTML).not.toContain('Not shown'); expect(postponed).toBe('testing postpone'); }); it('should not continue rendering after the reader cancels', async () => { let hasLoaded = false; let resolve; let rendered = false; const promise = new Promise(r => (resolve = r)); function Wait() { if (!hasLoaded) { throw promise; } rendered = true; return 'Done'; } const errors = []; const stream = await ReactServerDOMServer.renderToReadableStream( <div> <Suspense fallback={<div>Loading</div>}> <Wait /> </Suspense> </div>, null, { onError(x) { errors.push(x.message); }, }, ); expect(rendered).toBe(false); const reader = stream.getReader(); await reader.read(); await reader.cancel(); expect(errors).toEqual([ 'The render was aborted by the server without a reason.', ]); hasLoaded = true; resolve(); await jest.runAllTimers(); expect(rendered).toBe(false); expect(errors).toEqual([ 'The render was aborted by the server without a reason.', ]); }); // @gate enablePostpone it('postpones when abort passes a postpone signal', async () => { const infinitePromise = new Promise(() => {}); function Server() { return infinitePromise; } let postponed = null; let error = null; const controller = new AbortController(); const stream = ReactServerDOMServer.renderToReadableStream( <Suspense fallback="Loading..."> <Server /> </Suspense>, null, { onError(x) { error = x; }, onPostpone(reason) { postponed = reason; }, signal: controller.signal, }, ); try { React.unstable_postpone('testing postpone'); } catch (reason) { controller.abort(reason); } const response = ReactServerDOMClient.createFromReadableStream(stream); function Client() { return use(response); } const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(async () => { root.render( <div> Shell: <Client /> </div>, ); }); // We should have reserved the shell already. Which means that the Server // Component should've been a lazy component. expect(container.innerHTML).toContain('Shell:'); expect(container.innerHTML).toContain('Loading...'); expect(container.innerHTML).not.toContain('Not shown'); expect(postponed).toBe('testing postpone'); expect(error).toBe(null); }); });
26.398135
273
0.599105
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.profiling.min.js'); } else { module.exports = require('./cjs/react-dom.development.js'); }
33.948718
78
0.670338
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useTheme; exports.ThemeContext = void 0; var _react = require("react"); /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const ThemeContext = /*#__PURE__*/(0, _react.createContext)('bright'); exports.ThemeContext = ThemeContext; function useTheme() { const theme = (0, _react.useContext)(ThemeContext); (0, _react.useDebugValue)(theme); return theme; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInVzZVRoZW1lLmpzIl0sIm5hbWVzIjpbIlRoZW1lQ29udGV4dCIsInVzZVRoZW1lIiwidGhlbWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O0FBU0E7O0FBVEE7Ozs7Ozs7O0FBV08sTUFBTUEsWUFBWSxnQkFBRywwQkFBYyxRQUFkLENBQXJCOzs7QUFFUSxTQUFTQyxRQUFULEdBQW9CO0FBQ2pDLFFBQU1DLEtBQUssR0FBRyx1QkFBV0YsWUFBWCxDQUFkO0FBQ0EsNEJBQWNFLEtBQWQ7QUFDQSxTQUFPQSxLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0LCB1c2VEZWJ1Z1ZhbHVlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBjb25zdCBUaGVtZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0KCdicmlnaHQnKTtcblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gdXNlVGhlbWUoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlQ29udGV4dChUaGVtZUNvbnRleHQpO1xuICB1c2VEZWJ1Z1ZhbHVlKHRoZW1lKTtcbiAgcmV0dXJuIHRoZW1lO1xufVxuIl19fV19
63.962963
1,144
0.88591
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. * * @jest-environment node */ 'use strict'; const ReactNativeAttributePayload = require('../ReactNativeAttributePayload'); const diff = ReactNativeAttributePayload.diff; describe('ReactNativeAttributePayload', () => { it('should work with simple example', () => { expect(diff({a: 1, c: 3}, {b: 2, c: 3}, {a: true, b: true})).toEqual({ a: null, b: 2, }); }); it('should skip fields that are equal', () => { expect( diff( {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0}, {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0}, {a: true, b: true, c: true, d: true, e: true, f: true}, ), ).toEqual(null); }); it('should remove fields', () => { expect(diff({a: 1}, {}, {a: true})).toEqual({a: null}); }); it('should remove fields that are set to undefined', () => { expect(diff({a: 1}, {a: undefined}, {a: true})).toEqual({a: null}); }); it('should ignore invalid fields', () => { expect(diff({a: 1}, {b: 2}, {})).toEqual(null); }); it('should use the diff attribute', () => { const diffA = jest.fn((a, b) => true); const diffB = jest.fn((a, b) => false); expect( diff( {a: [1], b: [3]}, {a: [2], b: [4]}, {a: {diff: diffA}, b: {diff: diffB}}, ), ).toEqual({a: [2]}); expect(diffA).toBeCalledWith([1], [2]); expect(diffB).toBeCalledWith([3], [4]); }); it('should not use the diff attribute on addition/removal', () => { const diffA = jest.fn(); const diffB = jest.fn(); expect( diff({a: [1]}, {b: [2]}, {a: {diff: diffA}, b: {diff: diffB}}), ).toEqual({a: null, b: [2]}); expect(diffA).not.toBeCalled(); expect(diffB).not.toBeCalled(); }); it('should do deep diffs of Objects by default', () => { expect( diff( {a: [1], b: {k: [3, 4]}, c: {k: [4, 4]}}, {a: [2], b: {k: [3, 4]}, c: {k: [4, 5]}}, {a: true, b: true, c: true}, ), ).toEqual({a: [2], c: {k: [4, 5]}}); }); it('should work with undefined styles', () => { expect( diff( {style: {a: '#ffffff', b: 1}}, {style: undefined}, {style: {b: true}}, ), ).toEqual({b: null}); expect( diff( {style: undefined}, {style: {a: '#ffffff', b: 1}}, {style: {b: true}}, ), ).toEqual({b: 1}); expect( diff({style: undefined}, {style: undefined}, {style: {b: true}}), ).toEqual(null); }); it('should work with empty styles', () => { expect(diff({a: 1, c: 3}, {}, {a: true, b: true})).toEqual({a: null}); expect(diff({}, {a: 1, c: 3}, {a: true, b: true})).toEqual({a: 1}); expect(diff({}, {}, {a: true, b: true})).toEqual(null); }); it('should flatten nested styles and predefined styles', () => { const validStyleAttribute = {someStyle: {foo: true, bar: true}}; expect( diff({}, {someStyle: [{foo: 1}, {bar: 2}]}, validStyleAttribute), ).toEqual({foo: 1, bar: 2}); expect( diff({someStyle: [{foo: 1}, {bar: 2}]}, {}, validStyleAttribute), ).toEqual({foo: null, bar: null}); const barStyle = { bar: 3, }; expect( diff( {}, {someStyle: [[{foo: 1}, {foo: 2}], barStyle]}, validStyleAttribute, ), ).toEqual({foo: 2, bar: 3}); }); it('should reset a value to a previous if it is removed', () => { const validStyleAttribute = {someStyle: {foo: true, bar: true}}; expect( diff( {someStyle: [{foo: 1}, {foo: 3}]}, {someStyle: [{foo: 1}, {bar: 2}]}, validStyleAttribute, ), ).toEqual({foo: 1, bar: 2}); }); it('should not clear removed props if they are still in another slot', () => { const validStyleAttribute = {someStyle: {foo: true, bar: true}}; expect( diff( {someStyle: [{}, {foo: 3, bar: 2}]}, {someStyle: [{foo: 3}, {bar: 2}]}, validStyleAttribute, ), ).toEqual({foo: 3}); // this should ideally be null. heuristic tradeoff. expect( diff( {someStyle: [{}, {foo: 3, bar: 2}]}, {someStyle: [{foo: 1, bar: 1}, {bar: 2}]}, validStyleAttribute, ), ).toEqual({bar: 2, foo: 1}); }); it('should clear a prop if a later style is explicit null/undefined', () => { const validStyleAttribute = {someStyle: {foo: true, bar: true}}; expect( diff( {someStyle: [{}, {foo: 3, bar: 2}]}, {someStyle: [{foo: 1}, {bar: 2, foo: null}]}, validStyleAttribute, ), ).toEqual({foo: null}); expect( diff( {someStyle: [{foo: 3}, {foo: null, bar: 2}]}, {someStyle: [{foo: null}, {bar: 2}]}, validStyleAttribute, ), ).toEqual({foo: null}); expect( diff( {someStyle: [{foo: 1}, {foo: null}]}, {someStyle: [{foo: 2}, {foo: null}]}, validStyleAttribute, ), ).toEqual({foo: null}); // this should ideally be null. heuristic. // Test the same case with object equality because an early bailout doesn't // work in this case. const fooObj = {foo: 3}; expect( diff( {someStyle: [{foo: 1}, fooObj]}, {someStyle: [{foo: 2}, fooObj]}, validStyleAttribute, ), ).toEqual({foo: 3}); // this should ideally be null. heuristic. expect( diff( {someStyle: [{foo: 1}, {foo: 3}]}, {someStyle: [{foo: 2}, {foo: undefined}]}, validStyleAttribute, ), ).toEqual({foo: null}); // this should ideally be null. heuristic. }); // Function properties are just markers to native that events should be sent. it('should convert functions to booleans', () => { // Note that if the property changes from one function to another, we don't // need to send an update. expect( diff( { a: function () { return 1; }, b: function () { return 2; }, c: 3, }, { b: function () { return 9; }, c: function () { return 3; }, }, {a: true, b: true, c: true}, ), ).toEqual({a: null, c: true}); }); it('should skip changed functions', () => { expect( diff( { a: function () { return 1; }, }, { a: function () { return 9; }, }, {a: true}, ), ).toEqual(null); }); it('should skip deeply-nested changed functions', () => { expect( diff( { wrapper: { a: function () { return 1; }, }, }, { wrapper: { a: function () { return 9; }, }, }, {wrapper: true}, ), ).toEqual(null); }); });
24.912727
80
0.481825
owtf
const React = window.React; const fixturePath = window.location.pathname; /** * A simple routing component that renders the appropriate * fixture based on the location pathname. */ class FixturesPage extends React.Component { static defaultProps = { fixturePath: fixturePath === '/' ? '/home' : fixturePath, }; state = { isLoading: true, error: null, Fixture: null, }; componentDidMount() { this.loadFixture(); } async loadFixture() { const {fixturePath} = this.props; try { const module = await import(`.${fixturePath}`); this.setState({Fixture: module.default}); } catch (error) { console.error(error); this.setState({error}); } finally { this.setState({isLoading: false}); } } render() { const {Fixture, error, isLoading} = this.state; if (isLoading) { return null; } if (error) { return <FixtureError error={error} />; } return <Fixture />; } } function FixtureError({error}) { return ( <section> <h2>Error loading fixture</h2> <p>{error.message}</p> </section> ); } export default FixturesPage;
17.507937
61
0.606009
Penetration-Testing-with-Shellcode
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/ReactFlightDOMServerEdge';
22
66
0.702381
Python-Penetration-Testing-Cookbook
"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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJyZXF1aXJlIiwidXNlU3RhdGUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFBQTs7Ozs7Ozs7QUFTQSxTQUFBQSxTQUFBLEdBQUE7QUFDQSxRQUFBLENBQUFDLEtBQUEsSUFBQUMsT0FBQSxDQUFBLE9BQUEsQ0FBQSxDQUFBQyxRQUFBLENBQUEsQ0FBQSxDQUFBOztBQUVBLFNBQUFGLEtBQUE7QUFDQSIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBbY291bnRdID0gcmVxdWlyZSgncmVhY3QnKS51c2VTdGF0ZSgwKTtcblxuICByZXR1cm4gY291bnQ7XG59XG4iXX0=
57.904762
836
0.886731
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); const TEXT_NODE_TYPE = 3; let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('basic rendering', function () { itRenders('a blank div', async render => { const e = await render(<div />); expect(e.tagName).toBe('DIV'); }); itRenders('a self-closing tag', async render => { const e = await render(<br />); expect(e.tagName).toBe('BR'); }); itRenders('a self-closing tag as a child', async render => { const e = await render( <div> <br /> </div>, ); expect(e.childNodes.length).toBe(1); expect(e.firstChild.tagName).toBe('BR'); }); itRenders('a string', async render => { const e = await render('Hello'); expect(e.nodeType).toBe(3); expect(e.nodeValue).toMatch('Hello'); }); itRenders('a number', async render => { const e = await render(42); expect(e.nodeType).toBe(3); expect(e.nodeValue).toMatch('42'); }); itRenders('an array with one child', async render => { const e = await render([<div key={1}>text1</div>]); const parent = e.parentNode; expect(parent.childNodes[0].tagName).toBe('DIV'); }); itRenders('an array with several children', async render => { const Header = props => { return <p>header</p>; }; const Footer = props => { return [<h2 key={1}>footer</h2>, <h3 key={2}>about</h3>]; }; const e = await render([ <div key={1}>text1</div>, <span key={2}>text2</span>, <Header key={3} />, <Footer key={4} />, ]); const parent = e.parentNode; expect(parent.childNodes[0].tagName).toBe('DIV'); expect(parent.childNodes[1].tagName).toBe('SPAN'); expect(parent.childNodes[2].tagName).toBe('P'); expect(parent.childNodes[3].tagName).toBe('H2'); expect(parent.childNodes[4].tagName).toBe('H3'); }); itRenders('a nested array', async render => { const e = await render([ [<div key={1}>text1</div>], <span key={1}>text2</span>, [[[null, <p key={1} />], false]], ]); const parent = e.parentNode; expect(parent.childNodes[0].tagName).toBe('DIV'); expect(parent.childNodes[1].tagName).toBe('SPAN'); expect(parent.childNodes[2].tagName).toBe('P'); }); itRenders('an iterable', async render => { const threeDivIterable = { '@@iterator': function () { let i = 0; return { next: function () { if (i++ < 3) { return {value: <div key={i} />, done: false}; } else { return {value: undefined, done: true}; } }, }; }, }; const e = await render(threeDivIterable); const parent = e.parentNode; expect(parent.childNodes.length).toBe(3); expect(parent.childNodes[0].tagName).toBe('DIV'); expect(parent.childNodes[1].tagName).toBe('DIV'); expect(parent.childNodes[2].tagName).toBe('DIV'); }); itRenders('emptyish values', async render => { const e = await render(0); expect(e.nodeType).toBe(TEXT_NODE_TYPE); expect(e.nodeValue).toMatch('0'); // Empty string is special because client renders a node // but server returns empty HTML. So we compare parent text. expect((await render(<div>{''}</div>)).textContent).toBe(''); expect(await render([])).toBe(null); expect(await render(false)).toBe(null); expect(await render(true)).toBe(null); expect(await render(undefined)).toBe(null); expect(await render([[[false]], undefined])).toBe(null); }); }); });
28.585987
93
0.585702
PenetrationTestingScripts
/* global chrome */ import { getAppendComponentStack, getBreakOnConsoleErrors, getSavedComponentFilters, getShowInlineWarningsAndErrors, getHideConsoleLogsInStrictMode, } from 'react-devtools-shared/src/utils'; import {getBrowserTheme} from 'react-devtools-extensions/src/utils'; // The renderer interface can't read saved component filters directly, // because they are stored in localStorage within the context of the extension. // Instead it relies on the extension to pass filters through. function syncSavedPreferences() { chrome.devtools.inspectedWindow.eval( `window.__REACT_DEVTOOLS_APPEND_COMPONENT_STACK__ = ${JSON.stringify( getAppendComponentStack(), )}; window.__REACT_DEVTOOLS_BREAK_ON_CONSOLE_ERRORS__ = ${JSON.stringify( getBreakOnConsoleErrors(), )}; window.__REACT_DEVTOOLS_COMPONENT_FILTERS__ = ${JSON.stringify( getSavedComponentFilters(), )}; window.__REACT_DEVTOOLS_SHOW_INLINE_WARNINGS_AND_ERRORS__ = ${JSON.stringify( getShowInlineWarningsAndErrors(), )}; window.__REACT_DEVTOOLS_HIDE_CONSOLE_LOGS_IN_STRICT_MODE__ = ${JSON.stringify( getHideConsoleLogsInStrictMode(), )}; window.__REACT_DEVTOOLS_BROWSER_THEME__ = ${JSON.stringify( getBrowserTheme(), )};`, ); } export default syncSavedPreferences;
33
82
0.723019
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 type {ReactContext, Thenable} from 'shared/ReactTypes'; import * as React from 'react'; import {createContext} from 'react'; // TODO (cache) Remove this cache; it is outdated and will not work with newer APIs like startTransition. // Cache implementation was forked from the React repo: // https://github.com/facebook/react/blob/main/packages/react-cache/src/ReactCache.js // // This cache is simpler than react-cache in that: // 1. Individual items don't need to be invalidated. // Profiling data is invalidated as a whole. // 2. We didn't need the added overhead of an LRU cache. // The size of this cache is bounded by how many renders were profiled, // and it will be fully reset between profiling sessions. export type {Thenable}; interface Suspender { then(resolve: () => mixed, reject: () => mixed): mixed; } type PendingResult = { status: 0, value: Suspender, }; type ResolvedResult<Value> = { status: 1, value: Value, }; type RejectedResult = { status: 2, value: mixed, }; type Result<Value> = PendingResult | ResolvedResult<Value> | RejectedResult; export type Resource<Input, Key, Value> = { clear(): void, invalidate(Key): void, read(Input): Value, preload(Input): void, write(Key, Value): void, }; const Pending = 0; const Resolved = 1; const Rejected = 2; const ReactCurrentDispatcher = (React: any) .__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher; function readContext(Context: ReactContext<null>) { const dispatcher = ReactCurrentDispatcher.current; if (dispatcher === null) { throw new Error( 'react-cache: read and preload may only be called from within a ' + "component's render. They are not supported in event handlers or " + 'lifecycle methods.', ); } return dispatcher.readContext(Context); } const CacheContext = createContext(null); type Config = {useWeakMap?: boolean, ...}; const entries: Map< Resource<any, any, any>, Map<any, any> | WeakMap<any, any>, > = new Map(); const resourceConfigs: Map<Resource<any, any, any>, Config> = new Map(); function getEntriesForResource( resource: any, ): Map<any, any> | WeakMap<any, any> { let entriesForResource: Map<any, any> | WeakMap<any, any> = ((entries.get( resource, ): any): Map<any, any>); if (entriesForResource === undefined) { const config = resourceConfigs.get(resource); entriesForResource = config !== undefined && config.useWeakMap ? new WeakMap() : new Map(); entries.set(resource, entriesForResource); } return entriesForResource; } function accessResult<Input, Key, Value>( resource: any, fetch: Input => Thenable<Value>, input: Input, key: Key, ): Result<Value> { const entriesForResource = getEntriesForResource(resource); const entry = entriesForResource.get(key); if (entry === undefined) { const thenable = fetch(input); thenable.then( value => { if (newResult.status === Pending) { const resolvedResult: ResolvedResult<Value> = (newResult: any); resolvedResult.status = Resolved; resolvedResult.value = value; } }, error => { if (newResult.status === Pending) { const rejectedResult: RejectedResult = (newResult: any); rejectedResult.status = Rejected; rejectedResult.value = error; } }, ); const newResult: PendingResult = { status: Pending, value: thenable, }; entriesForResource.set(key, newResult); return newResult; } else { return entry; } } export function createResource<Input, Key, Value>( fetch: Input => Thenable<Value>, hashInput: Input => Key, config?: Config = {}, ): Resource<Input, Key, Value> { const resource = { clear(): void { entries.delete(resource); }, invalidate(key: Key): void { const entriesForResource = getEntriesForResource(resource); entriesForResource.delete(key); }, read(input: Input): Value { // Prevent access outside of render. readContext(CacheContext); const key = hashInput(input); const result: Result<Value> = accessResult(resource, fetch, input, key); switch (result.status) { case Pending: { const suspender = result.value; throw suspender; } case Resolved: { const value = result.value; return value; } case Rejected: { const error = result.value; throw error; } default: // Should be unreachable return (undefined: any); } }, preload(input: Input): void { // Prevent access outside of render. readContext(CacheContext); const key = hashInput(input); accessResult(resource, fetch, input, key); }, write(key: Key, value: Value): void { const entriesForResource = getEntriesForResource(resource); const resolvedResult: ResolvedResult<Value> = { status: Resolved, value, }; entriesForResource.set(key, resolvedResult); }, }; resourceConfigs.set(resource, config); return resource; } export function invalidateResources(): void { entries.clear(); }
25.323671
105
0.648678
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; export const defaultPointerId = 1; export const defaultPointerSize = 23; export const defaultBrowserChromeSize = 50; /** * Button property * This property only guarantees to indicate which buttons are pressed during events caused by pressing or * releasing one or multiple buttons. As such, it is not reliable for events such as 'mouseenter', 'mouseleave', * 'mouseover', 'mouseout' or 'mousemove'. Furthermore, the semantics differ for PointerEvent, where the value * for 'pointermove' will always be -1. */ export const buttonType = { // no change since last event none: -1, // left-mouse // touch contact // pen contact primary: 0, // right-mouse // pen barrel button secondary: 2, // middle mouse auxiliary: 1, // back mouse back: 3, // forward mouse forward: 4, // pen eraser eraser: 5, }; /** * Buttons bitmask */ export const buttonsType = { none: 0, // left-mouse // touch contact // pen contact primary: 1, // right-mouse // pen barrel button secondary: 2, // middle mouse auxiliary: 4, // back mouse back: 8, // forward mouse forward: 16, // pen eraser eraser: 32, };
20.045455
112
0.674352
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactNoop; let Scheduler; let act; let waitForAll; let waitFor; let assertLog; let waitForPaint; describe('ReactIncrementalScheduling', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; assertLog = InternalTestUtils.assertLog; waitForPaint = InternalTestUtils.waitForPaint; }); it('schedules and flushes deferred work', async () => { ReactNoop.render(<span prop="1" />); expect(ReactNoop).toMatchRenderedOutput(null); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="1" />); }); it('searches for work on other roots once the current root completes', async () => { ReactNoop.renderToRootWithID(<span prop="a:1" />, 'a'); ReactNoop.renderToRootWithID(<span prop="b:1" />, 'b'); ReactNoop.renderToRootWithID(<span prop="c:1" />, 'c'); await waitForAll([]); expect(ReactNoop.getChildrenAsJSX('a')).toEqual(<span prop="a:1" />); expect(ReactNoop.getChildrenAsJSX('b')).toEqual(<span prop="b:1" />); expect(ReactNoop.getChildrenAsJSX('c')).toEqual(<span prop="c:1" />); }); it('schedules top-level updates in order of priority', async () => { // Initial render. ReactNoop.render(<span prop={1} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />); ReactNoop.batchedUpdates(() => { ReactNoop.render(<span prop={5} />); ReactNoop.flushSync(() => { ReactNoop.render(<span prop={2} />); ReactNoop.render(<span prop={3} />); ReactNoop.render(<span prop={4} />); }); }); // The sync updates flush first. expect(ReactNoop).toMatchRenderedOutput(<span prop={4} />); // The terminal value should be the last update that was scheduled, // regardless of priority. In this case, that's the last sync update. await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={4} />); }); it('schedules top-level updates with same priority in order of insertion', async () => { // Initial render. ReactNoop.render(<span prop={1} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />); ReactNoop.render(<span prop={2} />); ReactNoop.render(<span prop={3} />); ReactNoop.render(<span prop={4} />); ReactNoop.render(<span prop={5} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop={5} />); }); it('works on deferred roots in the order they were scheduled', async () => { const {useEffect} = React; function Text({text}) { useEffect(() => { Scheduler.log(text); }, [text]); return text; } await act(() => { ReactNoop.renderToRootWithID(<Text text="a:1" />, 'a'); ReactNoop.renderToRootWithID(<Text text="b:1" />, 'b'); ReactNoop.renderToRootWithID(<Text text="c:1" />, 'c'); }); assertLog(['a:1', 'b:1', 'c:1']); expect(ReactNoop.getChildrenAsJSX('a')).toEqual('a:1'); expect(ReactNoop.getChildrenAsJSX('b')).toEqual('b:1'); expect(ReactNoop.getChildrenAsJSX('c')).toEqual('c:1'); // Schedule deferred work in the reverse order await act(async () => { React.startTransition(() => { ReactNoop.renderToRootWithID(<Text text="c:2" />, 'c'); ReactNoop.renderToRootWithID(<Text text="b:2" />, 'b'); }); // Ensure it starts in the order it was scheduled await waitFor(['c:2']); expect(ReactNoop.getChildrenAsJSX('a')).toEqual('a:1'); expect(ReactNoop.getChildrenAsJSX('b')).toEqual('b:1'); expect(ReactNoop.getChildrenAsJSX('c')).toEqual('c:2'); // Schedule last bit of work, it will get processed the last React.startTransition(() => { ReactNoop.renderToRootWithID(<Text text="a:2" />, 'a'); }); // Keep performing work in the order it was scheduled await waitFor(['b:2']); expect(ReactNoop.getChildrenAsJSX('a')).toEqual('a:1'); expect(ReactNoop.getChildrenAsJSX('b')).toEqual('b:2'); expect(ReactNoop.getChildrenAsJSX('c')).toEqual('c:2'); await waitFor(['a:2']); expect(ReactNoop.getChildrenAsJSX('a')).toEqual('a:2'); expect(ReactNoop.getChildrenAsJSX('b')).toEqual('b:2'); expect(ReactNoop.getChildrenAsJSX('c')).toEqual('c:2'); }); }); it('schedules sync updates when inside componentDidMount/Update', async () => { let instance; class Foo extends React.Component { state = {tick: 0}; componentDidMount() { Scheduler.log( 'componentDidMount (before setState): ' + this.state.tick, ); this.setState({tick: 1}); // We're in a batch. Update hasn't flushed yet. Scheduler.log('componentDidMount (after setState): ' + this.state.tick); } componentDidUpdate() { Scheduler.log('componentDidUpdate: ' + this.state.tick); if (this.state.tick === 2) { Scheduler.log( 'componentDidUpdate (before setState): ' + this.state.tick, ); this.setState({tick: 3}); Scheduler.log( 'componentDidUpdate (after setState): ' + this.state.tick, ); // We're in a batch. Update hasn't flushed yet. } } render() { Scheduler.log('render: ' + this.state.tick); instance = this; return <span prop={this.state.tick} />; } } React.startTransition(() => { ReactNoop.render(<Foo />); }); // Render without committing await waitFor(['render: 0']); // Do one more unit of work to commit expect(ReactNoop.flushNextYield()).toEqual([ 'componentDidMount (before setState): 0', 'componentDidMount (after setState): 0', // If the setState inside componentDidMount were deferred, there would be // no more ops. Because it has Task priority, we get these ops, too: 'render: 1', 'componentDidUpdate: 1', ]); React.startTransition(() => { instance.setState({tick: 2}); }); await waitFor(['render: 2']); expect(ReactNoop.flushNextYield()).toEqual([ 'componentDidUpdate: 2', 'componentDidUpdate (before setState): 2', 'componentDidUpdate (after setState): 2', // If the setState inside componentDidUpdate were deferred, there would be // no more ops. Because it has Task priority, we get these ops, too: 'render: 3', 'componentDidUpdate: 3', ]); }); it('can opt-in to async scheduling inside componentDidMount/Update', async () => { let instance; class Foo extends React.Component { state = {tick: 0}; componentDidMount() { React.startTransition(() => { Scheduler.log( 'componentDidMount (before setState): ' + this.state.tick, ); this.setState({tick: 1}); Scheduler.log( 'componentDidMount (after setState): ' + this.state.tick, ); }); } componentDidUpdate() { React.startTransition(() => { Scheduler.log('componentDidUpdate: ' + this.state.tick); if (this.state.tick === 2) { Scheduler.log( 'componentDidUpdate (before setState): ' + this.state.tick, ); this.setState({tick: 3}); Scheduler.log( 'componentDidUpdate (after setState): ' + this.state.tick, ); } }); } render() { Scheduler.log('render: ' + this.state.tick); instance = this; return <span prop={this.state.tick} />; } } ReactNoop.flushSync(() => { ReactNoop.render(<Foo />); }); // The cDM update should not have flushed yet because it has async priority. assertLog([ 'render: 0', 'componentDidMount (before setState): 0', 'componentDidMount (after setState): 0', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop={0} />); // Now flush the cDM update. await waitForAll(['render: 1', 'componentDidUpdate: 1']); expect(ReactNoop).toMatchRenderedOutput(<span prop={1} />); React.startTransition(() => { instance.setState({tick: 2}); }); await waitForPaint([ 'render: 2', 'componentDidUpdate: 2', 'componentDidUpdate (before setState): 2', 'componentDidUpdate (after setState): 2', ]); expect(ReactNoop).toMatchRenderedOutput(<span prop={2} />); // Now flush the cDU update. await waitForAll(['render: 3', 'componentDidUpdate: 3']); expect(ReactNoop).toMatchRenderedOutput(<span prop={3} />); }); it('performs Task work even after time runs out', async () => { class Foo extends React.Component { state = {step: 1}; componentDidMount() { this.setState({step: 2}, () => { this.setState({step: 3}, () => { this.setState({step: 4}, () => { this.setState({step: 5}); }); }); }); } render() { Scheduler.log('Foo'); return <span prop={this.state.step} />; } } React.startTransition(() => { ReactNoop.render(<Foo />); }); // This should be just enough to complete all the work, but not enough to // commit it. await waitFor(['Foo']); expect(ReactNoop).toMatchRenderedOutput(null); // Do one more unit of work. ReactNoop.flushNextYield(); // The updates should all be flushed with Task priority expect(ReactNoop).toMatchRenderedOutput(<span prop={5} />); }); });
30.933754
90
0.598004
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment node */ // sanity tests for act() const React = require('react'); const ReactNoop = require('react-noop-renderer'); const Scheduler = require('scheduler'); const act = require('internal-test-utils').act; const {assertLog, waitForAll} = require('internal-test-utils'); // TODO: These tests are no longer specific to the noop renderer // implementation. They test the internal implementation we use in the React // test suite. describe('internal act()', () => { it('can use act to flush effects', async () => { function App(props) { React.useEffect(props.callback); return null; } const calledLog = []; await act(() => { ReactNoop.render( <App callback={() => { calledLog.push(calledLog.length); }} />, ); }); await waitForAll([]); expect(calledLog).toEqual([0]); }); it('should work with async/await', async () => { function App() { const [ctr, setCtr] = React.useState(0); async function someAsyncFunction() { Scheduler.log('stage 1'); await null; Scheduler.log('stage 2'); await null; setCtr(1); } React.useEffect(() => { someAsyncFunction(); }, []); return ctr; } await act(() => { ReactNoop.render(<App />); }); assertLog(['stage 1', 'stage 2']); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput('1'); }); });
24.692308
76
0.588376
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; var React = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlRvRG9MaXN0LmpzIl0sIm5hbWVzIjpbIkxpc3RJdGVtIiwiaXRlbSIsInJlbW92ZUl0ZW0iLCJ0b2dnbGVJdGVtIiwiaGFuZGxlRGVsZXRlIiwiaGFuZGxlVG9nZ2xlIiwiaXNDb21wbGV0ZSIsInRleHQiLCJMaXN0IiwicHJvcHMiLCJuZXdJdGVtVGV4dCIsInNldE5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJzZXRJdGVtcyIsImlkIiwidWlkIiwic2V0VUlEIiwiaGFuZGxlQ2xpY2siLCJoYW5kbGVLZXlQcmVzcyIsImV2ZW50Iiwia2V5IiwiaGFuZGxlQ2hhbmdlIiwiY3VycmVudFRhcmdldCIsInZhbHVlIiwiaXRlbVRvUmVtb3ZlIiwiZmlsdGVyIiwiaXRlbVRvVG9nZ2xlIiwiaW5kZXgiLCJmaW5kSW5kZXgiLCJzbGljZSIsImNvbmNhdCIsIm1hcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFHTyxTQUFTQSxRQUFULENBQWtCO0FBQUNDLEVBQUFBLElBQUQ7QUFBT0MsRUFBQUEsVUFBUDtBQUFtQkMsRUFBQUE7QUFBbkIsQ0FBbEIsRUFBa0Q7QUFDdkQsUUFBTUMsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0QsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPQyxVQUFQLENBRmtCLENBQXJCO0FBSUEsUUFBTUcsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0YsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPRSxVQUFQLENBRmtCLENBQXJCO0FBSUEsc0JBQ0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0U7QUFBUSxJQUFBLE9BQU8sRUFBRUMsWUFBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQ0UsSUFBQSxPQUFPLEVBQUVILElBQUksQ0FBQ0ssVUFEaEI7QUFFRSxJQUFBLFFBQVEsRUFBRUQsWUFGWjtBQUdFLElBQUEsSUFBSSxFQUFDLFVBSFA7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFERixFQUtLLEdBTEwsRUFNR0osSUFBSSxDQUFDTSxJQU5SLENBRkYsQ0FERjtBQWFEOztBQUVNLFNBQVNDLElBQVQsQ0FBY0MsS0FBZCxFQUFxQjtBQUMxQixRQUFNLENBQUNDLFdBQUQsRUFBY0MsY0FBZCxJQUFnQyxvQkFBUyxFQUFULENBQXRDO0FBQ0EsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0Isb0JBQVMsQ0FDakM7QUFBQ0MsSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FEaUMsRUFFakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FGaUMsRUFHakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLEtBQXBCO0FBQTJCQyxJQUFBQSxJQUFJLEVBQUU7QUFBakMsR0FIaUMsQ0FBVCxDQUExQjtBQUtBLFFBQU0sQ0FBQ1EsR0FBRCxFQUFNQyxNQUFOLElBQWdCLG9CQUFTLENBQVQsQ0FBdEI7QUFFQSxRQUFNQyxXQUFXLEdBQUcsdUJBQVksTUFBTTtBQUNwQyxRQUFJUCxXQUFXLEtBQUssRUFBcEIsRUFBd0I7QUFDdEJHLE1BQUFBLFFBQVEsQ0FBQyxDQUNQLEdBQUdELEtBREksRUFFUDtBQUNFRSxRQUFBQSxFQUFFLEVBQUVDLEdBRE47QUFFRVQsUUFBQUEsVUFBVSxFQUFFLEtBRmQ7QUFHRUMsUUFBQUEsSUFBSSxFQUFFRztBQUhSLE9BRk8sQ0FBRCxDQUFSO0FBUUFNLE1BQUFBLE1BQU0sQ0FBQ0QsR0FBRyxHQUFHLENBQVAsQ0FBTjtBQUNBSixNQUFBQSxjQUFjLENBQUMsRUFBRCxDQUFkO0FBQ0Q7QUFDRixHQWJtQixFQWFqQixDQUFDRCxXQUFELEVBQWNFLEtBQWQsRUFBcUJHLEdBQXJCLENBYmlCLENBQXBCO0FBZUEsUUFBTUcsY0FBYyxHQUFHLHVCQUNyQkMsS0FBSyxJQUFJO0FBQ1AsUUFBSUEsS0FBSyxDQUFDQyxHQUFOLEtBQWMsT0FBbEIsRUFBMkI7QUFDekJILE1BQUFBLFdBQVc7QUFDWjtBQUNGLEdBTG9CLEVBTXJCLENBQUNBLFdBQUQsQ0FOcUIsQ0FBdkI7QUFTQSxRQUFNSSxZQUFZLEdBQUcsdUJBQ25CRixLQUFLLElBQUk7QUFDUFIsSUFBQUEsY0FBYyxDQUFDUSxLQUFLLENBQUNHLGFBQU4sQ0FBb0JDLEtBQXJCLENBQWQ7QUFDRCxHQUhrQixFQUluQixDQUFDWixjQUFELENBSm1CLENBQXJCO0FBT0EsUUFBTVQsVUFBVSxHQUFHLHVCQUNqQnNCLFlBQVksSUFBSVgsUUFBUSxDQUFDRCxLQUFLLENBQUNhLE1BQU4sQ0FBYXhCLElBQUksSUFBSUEsSUFBSSxLQUFLdUIsWUFBOUIsQ0FBRCxDQURQLEVBRWpCLENBQUNaLEtBQUQsQ0FGaUIsQ0FBbkI7QUFLQSxRQUFNVCxVQUFVLEdBQUcsdUJBQ2pCdUIsWUFBWSxJQUFJO0FBQ2Q7QUFDQTtBQUNBLFVBQU1DLEtBQUssR0FBR2YsS0FBSyxDQUFDZ0IsU0FBTixDQUFnQjNCLElBQUksSUFBSUEsSUFBSSxDQUFDYSxFQUFMLEtBQVlZLFlBQVksQ0FBQ1osRUFBakQsQ0FBZDtBQUVBRCxJQUFBQSxRQUFRLENBQ05ELEtBQUssQ0FDRmlCLEtBREgsQ0FDUyxDQURULEVBQ1lGLEtBRFosRUFFR0csTUFGSCxDQUVVLEVBQ04sR0FBR0osWUFERztBQUVOcEIsTUFBQUEsVUFBVSxFQUFFLENBQUNvQixZQUFZLENBQUNwQjtBQUZwQixLQUZWLEVBTUd3QixNQU5ILENBTVVsQixLQUFLLENBQUNpQixLQUFOLENBQVlGLEtBQUssR0FBRyxDQUFwQixDQU5WLENBRE0sQ0FBUjtBQVNELEdBZmdCLEVBZ0JqQixDQUFDZixLQUFELENBaEJpQixDQUFuQjtBQW1CQSxzQkFDRSxvQkFBQyxjQUFEO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLFlBREYsZUFFRTtBQUNFLElBQUEsSUFBSSxFQUFDLE1BRFA7QUFFRSxJQUFBLFdBQVcsRUFBQyxrQkFGZDtBQUdFLElBQUEsS0FBSyxFQUFFRixXQUhUO0FBSUUsSUFBQSxRQUFRLEVBQUVXLFlBSlo7QUFLRSxJQUFBLFVBQVUsRUFBRUgsY0FMZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQUZGLGVBU0U7QUFBUSxJQUFBLFFBQVEsRUFBRVIsV0FBVyxLQUFLLEVBQWxDO0FBQXNDLElBQUEsT0FBTyxFQUFFTyxXQUEvQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDRTtBQUFNLElBQUEsSUFBSSxFQUFDLEtBQVg7QUFBaUIsa0JBQVcsVUFBNUI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsV0FERixDQVRGLGVBY0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDR0wsS0FBSyxDQUFDbUIsR0FBTixDQUFVOUIsSUFBSSxpQkFDYixvQkFBQyxRQUFEO0FBQ0UsSUFBQSxHQUFHLEVBQUVBLElBQUksQ0FBQ2EsRUFEWjtBQUVFLElBQUEsSUFBSSxFQUFFYixJQUZSO0FBR0UsSUFBQSxVQUFVLEVBQUVDLFVBSGQ7QUFJRSxJQUFBLFVBQVUsRUFBRUMsVUFKZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQURELENBREgsQ0FkRixDQURGO0FBMkJEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcbmltcG9ydCB7RnJhZ21lbnQsIHVzZUNhbGxiYWNrLCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gTGlzdEl0ZW0oe2l0ZW0sIHJlbW92ZUl0ZW0sIHRvZ2dsZUl0ZW19KSB7XG4gIGNvbnN0IGhhbmRsZURlbGV0ZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICByZW1vdmVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgcmVtb3ZlSXRlbV0pO1xuXG4gIGNvbnN0IGhhbmRsZVRvZ2dsZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICB0b2dnbGVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgdG9nZ2xlSXRlbV0pO1xuXG4gIHJldHVybiAoXG4gICAgPGxpPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXtoYW5kbGVEZWxldGV9PkRlbGV0ZTwvYnV0dG9uPlxuICAgICAgPGxhYmVsPlxuICAgICAgICA8aW5wdXRcbiAgICAgICAgICBjaGVja2VkPXtpdGVtLmlzQ29tcGxldGV9XG4gICAgICAgICAgb25DaGFuZ2U9e2hhbmRsZVRvZ2dsZX1cbiAgICAgICAgICB0eXBlPVwiY2hlY2tib3hcIlxuICAgICAgICAvPnsnICd9XG4gICAgICAgIHtpdGVtLnRleHR9XG4gICAgICA8L2xhYmVsPlxuICAgIDwvbGk+XG4gICk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBMaXN0KHByb3BzKSB7XG4gIGNvbnN0IFtuZXdJdGVtVGV4dCwgc2V0TmV3SXRlbVRleHRdID0gdXNlU3RhdGUoJycpO1xuICBjb25zdCBbaXRlbXMsIHNldEl0ZW1zXSA9IHVzZVN0YXRlKFtcbiAgICB7aWQ6IDEsIGlzQ29tcGxldGU6IHRydWUsIHRleHQ6ICdGaXJzdCd9LFxuICAgIHtpZDogMiwgaXNDb21wbGV0ZTogdHJ1ZSwgdGV4dDogJ1NlY29uZCd9LFxuICAgIHtpZDogMywgaXNDb21wbGV0ZTogZmFsc2UsIHRleHQ6ICdUaGlyZCd9LFxuICBdKTtcbiAgY29uc3QgW3VpZCwgc2V0VUlEXSA9IHVzZVN0YXRlKDQpO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIGlmIChuZXdJdGVtVGV4dCAhPT0gJycpIHtcbiAgICAgIHNldEl0ZW1zKFtcbiAgICAgICAgLi4uaXRlbXMsXG4gICAgICAgIHtcbiAgICAgICAgICBpZDogdWlkLFxuICAgICAgICAgIGlzQ29tcGxldGU6IGZhbHNlLFxuICAgICAgICAgIHRleHQ6IG5ld0l0ZW1UZXh0LFxuICAgICAgICB9LFxuICAgICAgXSk7XG4gICAgICBzZXRVSUQodWlkICsgMSk7XG4gICAgICBzZXROZXdJdGVtVGV4dCgnJyk7XG4gICAgfVxuICB9LCBbbmV3SXRlbVRleHQsIGl0ZW1zLCB1aWRdKTtcblxuICBjb25zdCBoYW5kbGVLZXlQcmVzcyA9IHVzZUNhbGxiYWNrKFxuICAgIGV2ZW50ID0+IHtcbiAgICAgIGlmIChldmVudC5rZXkgPT09ICdFbnRlcicpIHtcbiAgICAgICAgaGFuZGxlQ2xpY2soKTtcbiAgICAgIH1cbiAgICB9LFxuICAgIFtoYW5kbGVDbGlja10sXG4gICk7XG5cbiAgY29uc3QgaGFuZGxlQ2hhbmdlID0gdXNlQ2FsbGJhY2soXG4gICAgZXZlbnQgPT4ge1xuICAgICAgc2V0TmV3SXRlbVRleHQoZXZlbnQuY3VycmVudFRhcmdldC52YWx1ZSk7XG4gICAgfSxcbiAgICBbc2V0TmV3SXRlbVRleHRdLFxuICApO1xuXG4gIGNvbnN0IHJlbW92ZUl0ZW0gPSB1c2VDYWxsYmFjayhcbiAgICBpdGVtVG9SZW1vdmUgPT4gc2V0SXRlbXMoaXRlbXMuZmlsdGVyKGl0ZW0gPT4gaXRlbSAhPT0gaXRlbVRvUmVtb3ZlKSksXG4gICAgW2l0ZW1zXSxcbiAgKTtcblxuICBjb25zdCB0b2dnbGVJdGVtID0gdXNlQ2FsbGJhY2soXG4gICAgaXRlbVRvVG9nZ2xlID0+IHtcbiAgICAgIC8vIERvbnQgdXNlIGluZGV4T2YoKVxuICAgICAgLy8gYmVjYXVzZSBlZGl0aW5nIHByb3BzIGluIERldlRvb2xzIGNyZWF0ZXMgYSBuZXcgT2JqZWN0LlxuICAgICAgY29uc3QgaW5kZXggPSBpdGVtcy5maW5kSW5kZXgoaXRlbSA9PiBpdGVtLmlkID09PSBpdGVtVG9Ub2dnbGUuaWQpO1xuXG4gICAgICBzZXRJdGVtcyhcbiAgICAgICAgaXRlbXNcbiAgICAgICAgICAuc2xpY2UoMCwgaW5kZXgpXG4gICAgICAgICAgLmNvbmNhdCh7XG4gICAgICAgICAgICAuLi5pdGVtVG9Ub2dnbGUsXG4gICAgICAgICAgICBpc0NvbXBsZXRlOiAhaXRlbVRvVG9nZ2xlLmlzQ29tcGxldGUsXG4gICAgICAgICAgfSlcbiAgICAgICAgICAuY29uY2F0KGl0ZW1zLnNsaWNlKGluZGV4ICsgMSkpLFxuICAgICAgKTtcbiAgICB9LFxuICAgIFtpdGVtc10sXG4gICk7XG5cbiAgcmV0dXJuIChcbiAgICA8RnJhZ21lbnQ+XG4gICAgICA8aDE+TGlzdDwvaDE+XG4gICAgICA8aW5wdXRcbiAgICAgICAgdHlwZT1cInRleHRcIlxuICAgICAgICBwbGFjZWhvbGRlcj1cIk5ldyBsaXN0IGl0ZW0uLi5cIlxuICAgICAgICB2YWx1ZT17bmV3SXRlbVRleHR9XG4gICAgICAgIG9uQ2hhbmdlPXtoYW5kbGVDaGFuZ2V9XG4gICAgICAgIG9uS2V5UHJlc3M9e2hhbmRsZUtleVByZXNzfVxuICAgICAgLz5cbiAgICAgIDxidXR0b24gZGlzYWJsZWQ9e25ld0l0ZW1UZXh0ID09PSAnJ30gb25DbGljaz17aGFuZGxlQ2xpY2t9PlxuICAgICAgICA8c3BhbiByb2xlPVwiaW1nXCIgYXJpYS1sYWJlbD1cIkFkZCBpdGVtXCI+XG4gICAgICAgICAgQWRkXG4gICAgICAgIDwvc3Bhbj5cbiAgICAgIDwvYnV0dG9uPlxuICAgICAgPHVsPlxuICAgICAgICB7aXRlbXMubWFwKGl0ZW0gPT4gKFxuICAgICAgICAgIDxMaXN0SXRlbVxuICAgICAgICAgICAga2V5PXtpdGVtLmlkfVxuICAgICAgICAgICAgaXRlbT17aXRlbX1cbiAgICAgICAgICAgIHJlbW92ZUl0ZW09e3JlbW92ZUl0ZW19XG4gICAgICAgICAgICB0b2dnbGVJdGVtPXt0b2dnbGVJdGVtfVxuICAgICAgICAgIC8+XG4gICAgICAgICkpfVxuICAgICAgPC91bD5cbiAgICA8L0ZyYWdtZW50PlxuICApO1xufVxuIl0sInhfZmFjZWJvb2tfc291cmNlcyI6W1tudWxsLFt7Im5hbWVzIjpbIjxuby1ob29rPiIsImhhbmRsZURlbGV0ZSIsImhhbmRsZVRvZ2dsZSIsIm5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJ1aWQiLCJoYW5kbGVDbGljayIsImhhbmRsZUtleVByZXNzIiwiaGFuZGxlQ2hhbmdlIiwicmVtb3ZlSXRlbSIsInRvZ2dsZUl0ZW0iXSwibWFwcGluZ3MiOiJDQUFEO2N1QkNBO2dCQ0RBO2tCREVBO29CQ0ZBO3NDZ0JHQSxBWUhBO3VDeEJJQTsyQ3hCSkE7NENvQktBLEFXTEE7OENiTUE7MkRTTkE7NkROT0E7b0V0QlBBO3NFb0JRQTsyRXBCUkE7NkVrQlNBO2dGbEJUQTtrRmtCVUE7bUdsQlZBIn1dXV19
87.71875
9,228
0.859025
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 {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type {ServerContextJSONValue, Thenable} from 'shared/ReactTypes'; import type {ClientManifest} from './ReactFlightServerConfigWebpackBundler'; import type {ServerManifest} from 'react-client/src/ReactFlightClientConfig'; import { createRequest, startWork, startFlowing, stopFlowing, abort, } from 'react-server/src/ReactFlightServer'; import { createResponse, close, getRoot, } from 'react-server/src/ReactFlightReplyServer'; import { decodeAction, decodeFormState, } from 'react-server/src/ReactFlightActionServer'; export { registerServerReference, registerClientReference, createClientModuleProxy, } from './ReactFlightWebpackReferences'; type Options = { identifierPrefix?: string, signal?: AbortSignal, context?: Array<[string, ServerContextJSONValue]>, onError?: (error: mixed) => void, onPostpone?: (reason: string) => void, }; function renderToReadableStream( model: ReactClientValue, webpackMap: ClientManifest, options?: Options, ): ReadableStream { const request = createRequest( model, webpackMap, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, options ? options.onPostpone : undefined, ); if (options && options.signal) { const signal = options.signal; if (signal.aborted) { abort(request, (signal: any).reason); } else { const listener = () => { abort(request, (signal: any).reason); signal.removeEventListener('abort', listener); }; signal.addEventListener('abort', listener); } } const stream = new ReadableStream( { type: 'bytes', start: (controller): ?Promise<void> => { startWork(request); }, pull: (controller): ?Promise<void> => { startFlowing(request, controller); }, cancel: (reason): ?Promise<void> => { stopFlowing(request); abort(request, reason); }, }, // $FlowFixMe[prop-missing] size() methods are not allowed on byte streams. {highWaterMark: 0}, ); return stream; } function decodeReply<T>( body: string | FormData, webpackMap: ServerManifest, ): Thenable<T> { if (typeof body === 'string') { const form = new FormData(); form.append('0', body); body = form; } const response = createResponse(webpackMap, '', body); const root = getRoot<T>(response); close(response); return root; } export {renderToReadableStream, decodeReply, decodeAction, decodeFormState};
24.844037
79
0.679688
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-unstable-cache.production.min.js'); } else { module.exports = require('./cjs/react-unstable-cache.development.js'); }
26.625
75
0.690909
null
'use strict'; module.exports = require('./cjs/react-suspense-test-utils.js');
19
63
0.708861
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type { Destination, Chunk, PrecomputedChunk, } from 'react-server/src/ReactServerStreamConfig'; import {setCheckIsClientReference} from './ReactFlightReferencesFB'; import { createRequest, startWork, startFlowing, } from 'react-server/src/ReactFlightServer'; import {setByteLengthOfChunkImplementation} from 'react-server/src/ReactServerStreamConfig'; export { registerClientReference, registerServerReference, getRequestedClientReferencesKeys, clearRequestedClientReferencesKeysSet, setCheckIsClientReference, } from './ReactFlightReferencesFB'; type Options = { onError?: (error: mixed) => void, }; function renderToDestination( destination: Destination, model: ReactClientValue, options?: Options, ): void { if (!configured) { throw new Error( 'Please make sure to call `setConfig(...)` before calling `renderToDestination`.', ); } const request = createRequest( model, null, options ? options.onError : undefined, ); startWork(request); startFlowing(request, destination); } type Config = { byteLength: (chunk: Chunk | PrecomputedChunk) => number, isClientReference: (reference: mixed) => boolean, }; let configured = false; function setConfig(config: Config): void { setByteLengthOfChunkImplementation(config.byteLength); setCheckIsClientReference(config.isClientReference); configured = true; } export {renderToDestination, setConfig};
22.833333
92
0.742857
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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZS5qcyJdLCJuYW1lcyI6WyJBIiwiQiIsIkNvbXBvbmVudCIsImEiLCJiIiwiYyIsImQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7QUFUQTs7Ozs7Ozs7QUFXQSxNQUFNQSxDQUFDLGdCQUFHLDBCQUFjLENBQWQsQ0FBVjtBQUNBLE1BQU1DLENBQUMsZ0JBQUcsMEJBQWMsQ0FBZCxDQUFWOztBQUVPLFNBQVNDLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsQ0FBQyxHQUFHLHVCQUFXSCxDQUFYLENBQVY7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdILENBQVgsQ0FBVixDQUYwQixDQUkxQjs7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBVjtBQUFBLFFBQXlCTSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBN0IsQ0FMMEIsQ0FLa0I7O0FBRTVDLFNBQU9FLENBQUMsR0FBR0MsQ0FBSixHQUFRQyxDQUFSLEdBQVlDLENBQW5CO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0fSBmcm9tICdyZWFjdCc7XG5cbmNvbnN0IEEgPSBjcmVhdGVDb250ZXh0KDEpO1xuY29uc3QgQiA9IGNyZWF0ZUNvbnRleHQoMik7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IGEgPSB1c2VDb250ZXh0KEEpO1xuICBjb25zdCBiID0gdXNlQ29udGV4dChCKTtcblxuICAvLyBwcmV0dGllci1pZ25vcmVcbiAgY29uc3QgYyA9IHVzZUNvbnRleHQoQSksIGQgPSB1c2VDb250ZXh0KEIpOyAvLyBlc2xpbnQtZGlzYWJsZS1saW5lIG9uZS12YXJcblxuICByZXR1cm4gYSArIGIgKyBjICsgZDtcbn1cbiJdLCJ4X2ZhY2Vib29rX3NvdXJjZXMiOltbbnVsbCxbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJhIiwiYiIsImMiLCJkIl0sIm1hcHBpbmdzIjoiQ0FBRDtnQllDQSxBYURBO2lCYkVBLEFhRkE7b0JiR0EsQWFIQSxBTUlBLEFhSkEifV1dXX0=
77.233333
1,640
0.883205
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ const aliases = new Map([ ['acceptCharset', 'accept-charset'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv'], // HTML and SVG attributes, but the SVG attribute is case sensitive.], ['crossOrigin', 'crossorigin'], // This is a list of all SVG attributes that need special casing. // Regular attributes that just accept strings.], ['accentHeight', 'accent-height'], ['alignmentBaseline', 'alignment-baseline'], ['arabicForm', 'arabic-form'], ['baselineShift', 'baseline-shift'], ['capHeight', 'cap-height'], ['clipPath', 'clip-path'], ['clipRule', 'clip-rule'], ['colorInterpolation', 'color-interpolation'], ['colorInterpolationFilters', 'color-interpolation-filters'], ['colorProfile', 'color-profile'], ['colorRendering', 'color-rendering'], ['dominantBaseline', 'dominant-baseline'], ['enableBackground', 'enable-background'], ['fillOpacity', 'fill-opacity'], ['fillRule', 'fill-rule'], ['floodColor', 'flood-color'], ['floodOpacity', 'flood-opacity'], ['fontFamily', 'font-family'], ['fontSize', 'font-size'], ['fontSizeAdjust', 'font-size-adjust'], ['fontStretch', 'font-stretch'], ['fontStyle', 'font-style'], ['fontVariant', 'font-variant'], ['fontWeight', 'font-weight'], ['glyphName', 'glyph-name'], ['glyphOrientationHorizontal', 'glyph-orientation-horizontal'], ['glyphOrientationVertical', 'glyph-orientation-vertical'], ['horizAdvX', 'horiz-adv-x'], ['horizOriginX', 'horiz-origin-x'], ['imageRendering', 'image-rendering'], ['letterSpacing', 'letter-spacing'], ['lightingColor', 'lighting-color'], ['markerEnd', 'marker-end'], ['markerMid', 'marker-mid'], ['markerStart', 'marker-start'], ['overlinePosition', 'overline-position'], ['overlineThickness', 'overline-thickness'], ['paintOrder', 'paint-order'], ['panose-1', 'panose-1'], ['pointerEvents', 'pointer-events'], ['renderingIntent', 'rendering-intent'], ['shapeRendering', 'shape-rendering'], ['stopColor', 'stop-color'], ['stopOpacity', 'stop-opacity'], ['strikethroughPosition', 'strikethrough-position'], ['strikethroughThickness', 'strikethrough-thickness'], ['strokeDasharray', 'stroke-dasharray'], ['strokeDashoffset', 'stroke-dashoffset'], ['strokeLinecap', 'stroke-linecap'], ['strokeLinejoin', 'stroke-linejoin'], ['strokeMiterlimit', 'stroke-miterlimit'], ['strokeOpacity', 'stroke-opacity'], ['strokeWidth', 'stroke-width'], ['textAnchor', 'text-anchor'], ['textDecoration', 'text-decoration'], ['textRendering', 'text-rendering'], ['transformOrigin', 'transform-origin'], ['underlinePosition', 'underline-position'], ['underlineThickness', 'underline-thickness'], ['unicodeBidi', 'unicode-bidi'], ['unicodeRange', 'unicode-range'], ['unitsPerEm', 'units-per-em'], ['vAlphabetic', 'v-alphabetic'], ['vHanging', 'v-hanging'], ['vIdeographic', 'v-ideographic'], ['vMathematical', 'v-mathematical'], ['vectorEffect', 'vector-effect'], ['vertAdvY', 'vert-adv-y'], ['vertOriginX', 'vert-origin-x'], ['vertOriginY', 'vert-origin-y'], ['wordSpacing', 'word-spacing'], ['writingMode', 'writing-mode'], ['xmlnsXlink', 'xmlns:xlink'], ['xHeight', 'x-height'], ]); export default function (name: string): string { return aliases.get(name) || name; }
35.010309
72
0.662658
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {AnyNativeEvent} from '../events/PluginModuleType'; // This exists to avoid circular dependency between ReactDOMEventReplaying // and DOMPluginEventSystem. let currentReplayingEvent = null; export function setReplayingEvent(event: AnyNativeEvent): void { if (__DEV__) { if (currentReplayingEvent !== null) { console.error( 'Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.', ); } } currentReplayingEvent = event; } export function resetReplayingEvent(): void { if (__DEV__) { if (currentReplayingEvent === null) { console.error( 'Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.', ); } } currentReplayingEvent = null; } export function isReplayingEvent(event: AnyNativeEvent): boolean { return event === currentReplayingEvent; }
26.627907
74
0.682393
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; let React; let ReactNoop; let Scheduler; let waitForAll; let waitFor; let waitForPaint; describe('ReactIncrementalSideEffects', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForPaint = InternalTestUtils.waitForPaint; }); // Note: This is based on a similar component we use in www. We can delete // once the extra div wrapper is no longer necessary. function LegacyHiddenDiv({children, mode}) { return ( <div hidden={mode === 'hidden'}> <React.unstable_LegacyHidden mode={mode === 'hidden' ? 'unstable-defer-without-hiding' : mode}> {children} </React.unstable_LegacyHidden> </div> ); } it('can 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> ); } ReactNoop.render(<Foo text="Hello" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span>Hello</span> </div>, ); ReactNoop.render(<Foo text="World" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span>World</span> <span>World</span> </div>, ); }); it('can update child nodes of a fragment', async function () { function Bar(props) { return <span>{props.text}</span>; } function Foo(props) { return ( <div> <Bar text={props.text} /> {props.text === 'World' ? [<Bar key="a" text={props.text} />, <div key="b" />] : props.text === 'Hi' ? [<div key="b" />, <Bar key="a" text={props.text} />] : null} <span prop="test" /> </div> ); } ReactNoop.render(<Foo text="Hello" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span>Hello</span> <span prop="test" /> </div>, ); ReactNoop.render(<Foo text="World" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span>World</span> <span>World</span> <div /> <span prop="test" /> </div>, ); ReactNoop.render(<Foo text="Hi" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span>Hi</span> <div /> <span>Hi</span> <span prop="test" /> </div>, ); }); it('can update child nodes rendering into text nodes', async function () { function Bar(props) { return props.text; } function Foo(props) { return ( <div> <Bar text={props.text} /> {props.text === 'World' ? [<Bar key="a" text={props.text} />, '!'] : null} </div> ); } ReactNoop.render(<Foo text="Hello" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div>Hello</div>); ReactNoop.render(<Foo text="World" />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div>WorldWorld!</div>); }); it('can deletes children either components, host or text', async function () { function Bar(props) { return <span prop={props.children} />; } function Foo(props) { return ( <div> {props.show ? [<div key="a" />, <Bar key="b">Hello</Bar>, 'World'] : []} </div> ); } ReactNoop.render(<Foo show={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <div /> <span prop="Hello" /> World </div>, ); ReactNoop.render(<Foo show={false} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div />); }); it('can delete a child that changes type - implicit keys', async function () { let unmounted = false; class ClassComponent extends React.Component { componentWillUnmount() { unmounted = true; } render() { return <span prop="Class" />; } } function FunctionComponent(props) { return <span prop="Function" />; } function Foo(props) { return ( <div> {props.useClass ? ( <ClassComponent /> ) : props.useFunction ? ( <FunctionComponent /> ) : props.useText ? ( 'Text' ) : null} Trail </div> ); } ReactNoop.render(<Foo useClass={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop="Class" /> Trail </div>, ); expect(unmounted).toBe(false); ReactNoop.render(<Foo useFunction={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop="Function" /> Trail </div>, ); expect(unmounted).toBe(true); ReactNoop.render(<Foo useText={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div>TextTrail</div>); ReactNoop.render(<Foo />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div>Trail</div>); }); it('can delete a child that changes type - explicit keys', async function () { let unmounted = false; class ClassComponent extends React.Component { componentWillUnmount() { unmounted = true; } render() { return <span prop="Class" />; } } function FunctionComponent(props) { return <span prop="Function" />; } function Foo(props) { return ( <div> {props.useClass ? ( <ClassComponent key="a" /> ) : props.useFunction ? ( <FunctionComponent key="a" /> ) : null} Trail </div> ); } ReactNoop.render(<Foo useClass={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop="Class" /> Trail </div>, ); expect(unmounted).toBe(false); ReactNoop.render(<Foo useFunction={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop="Function" /> Trail </div>, ); expect(unmounted).toBe(true); ReactNoop.render(<Foo />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div>Trail</div>); }); it('can delete a child when it unmounts inside a portal', async () => { function Bar(props) { return <span prop={props.children} />; } const portalContainer = ReactNoop.getOrCreateRootContainer('portalContainer'); function Foo(props) { return ReactNoop.createPortal( props.show ? [<div key="a" />, <Bar key="b">Hello</Bar>, 'World'] : [], portalContainer, null, ); } ReactNoop.render( <div> <Foo show={true} /> </div>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div />); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual( <> <div /> <span prop="Hello" /> World </>, ); ReactNoop.render( <div> <Foo show={false} /> </div>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div />); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual(null); ReactNoop.render( <div> <Foo show={true} /> </div>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div />); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual( <> <div /> <span prop="Hello" /> World </>, ); ReactNoop.render(null); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual(null); ReactNoop.render(<Foo show={false} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual(null); ReactNoop.render(<Foo show={true} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual( <> <div /> <span prop="Hello" /> World </>, ); ReactNoop.render(null); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual(null); }); it('can delete a child when it unmounts with a portal', async () => { function Bar(props) { return <span prop={props.children} />; } const portalContainer = ReactNoop.getOrCreateRootContainer('portalContainer'); function Foo(props) { return ReactNoop.createPortal( [<div key="a" />, <Bar key="b">Hello</Bar>, 'World'], portalContainer, null, ); } ReactNoop.render( <div> <Foo /> </div>, ); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<div />); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual( <> <div /> <span prop="Hello" /> World </>, ); ReactNoop.render(null); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual(null); ReactNoop.render(<Foo />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual( <> <div /> <span prop="Hello" /> World </>, ); ReactNoop.render(null); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(null); expect(ReactNoop.getChildrenAsJSX('portalContainer')).toEqual(null); }); it('does not update child nodes if a flush is aborted', async () => { function Bar(props) { Scheduler.log('Bar'); return <span prop={props.text} />; } function Foo(props) { Scheduler.log('Foo'); return ( <div> <div> <Bar text={props.text} /> {props.text === 'Hello' ? <Bar text={props.text} /> : null} </div> <Bar text="Yo" /> </div> ); } ReactNoop.render(<Foo text="Hello" />); await waitForAll(['Foo', 'Bar', 'Bar', 'Bar']); expect(ReactNoop).toMatchRenderedOutput( <div> <div> <span prop="Hello" /> <span prop="Hello" /> </div> <span prop="Yo" /> </div>, ); React.startTransition(() => { ReactNoop.render(<Foo text="World" />); }); // Flush some of the work without committing await waitFor(['Foo', 'Bar']); expect(ReactNoop).toMatchRenderedOutput( <div> <div> <span prop="Hello" /> <span prop="Hello" /> </div> <span prop="Yo" /> </div>, ); }); // @gate www it('preserves a previously rendered node when deprioritized', async () => { function Middle(props) { Scheduler.log('Middle'); return <span prop={props.children} />; } function Foo(props) { Scheduler.log('Foo'); return ( <div> <LegacyHiddenDiv mode="hidden"> <Middle>{props.text}</Middle> </LegacyHiddenDiv> </div> ); } ReactNoop.render(<Foo text="foo" />); await waitForAll(['Foo', 'Middle']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> <div hidden={true}> <span prop="foo" /> </div> </div>, ); ReactNoop.render(<Foo text="bar" />, () => Scheduler.log('commit')); await waitFor(['Foo', 'commit']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> <div hidden={true}> <span prop="foo" /> </div> </div>, ); await waitForAll(['Middle']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> <div hidden={true}> <span prop="bar" /> </div> </div>, ); }); // @gate www it('can reuse side-effects after being preempted', async () => { function Bar(props) { Scheduler.log('Bar'); return <span prop={props.children} />; } const middleContent = ( <div> <Bar>Hello</Bar> <Bar>World</Bar> </div> ); function Foo(props) { Scheduler.log('Foo'); return ( <LegacyHiddenDiv mode="hidden"> {props.step === 0 ? ( <div> <Bar>Hi</Bar> <Bar>{props.text}</Bar> </div> ) : ( middleContent )} </LegacyHiddenDiv> ); } // Init ReactNoop.render(<Foo text="foo" step={0} />); await waitForAll(['Foo', 'Bar', 'Bar']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <div> <span prop="Hi" /> <span prop="foo" /> </div> </div>, ); // Make a quick update which will schedule low priority work to // update the middle content. ReactNoop.render(<Foo text="bar" step={1} />, () => Scheduler.log('commit'), ); await waitFor(['Foo', 'commit', 'Bar']); // The tree remains unchanged. expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <div> <span prop="Hi" /> <span prop="foo" /> </div> </div>, ); // The first Bar has already completed its update but we'll interrupt it to // render some higher priority work. The middle content will bailout so // it remains untouched which means that it should reuse it next time. ReactNoop.render(<Foo text="foo" step={1} />); await waitForAll(['Foo', 'Bar', 'Bar']); // Since we did nothing to the middle subtree during the interruption, // we should be able to reuse the reconciliation work that we already did // without restarting. The side-effects should still be replayed. expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <div> <span prop="Hello" /> <span prop="World" /> </div> </div>, ); }); // @gate www it('can reuse side-effects after being preempted, if shouldComponentUpdate is false', async () => { class Bar extends React.Component { shouldComponentUpdate(nextProps) { return this.props.children !== nextProps.children; } render() { Scheduler.log('Bar'); return <span prop={this.props.children} />; } } class Content extends React.Component { shouldComponentUpdate(nextProps) { return this.props.step !== nextProps.step; } render() { Scheduler.log('Content'); return ( <div> <Bar>{this.props.step === 0 ? 'Hi' : 'Hello'}</Bar> <Bar>{this.props.step === 0 ? this.props.text : 'World'}</Bar> </div> ); } } function Foo(props) { Scheduler.log('Foo'); return ( <LegacyHiddenDiv mode="hidden"> <Content step={props.step} text={props.text} /> </LegacyHiddenDiv> ); } // Init ReactNoop.render(<Foo text="foo" step={0} />); await waitForAll(['Foo', 'Content', 'Bar', 'Bar']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <div> <span prop="Hi" /> <span prop="foo" /> </div> </div>, ); // Make a quick update which will schedule low priority work to // update the middle content. ReactNoop.render(<Foo text="bar" step={1} />); await waitFor(['Foo', 'Content', 'Bar']); // The tree remains unchanged. expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <div> <span prop="Hi" /> <span prop="foo" /> </div> </div>, ); // The first Bar has already completed its update but we'll interrupt it to // render some higher priority work. The middle content will bailout so // it remains untouched which means that it should reuse it next time. ReactNoop.render(<Foo text="foo" step={1} />); await waitForAll(['Foo', 'Content', 'Bar', 'Bar']); // Since we did nothing to the middle subtree during the interruption, // we should be able to reuse the reconciliation work that we already did // without restarting. The side-effects should still be replayed. expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <div> <span prop="Hello" /> <span prop="World" /> </div> </div>, ); }); it('can update a completed tree before it has a chance to commit', async () => { function Foo(props) { Scheduler.log('Foo ' + props.step); return <span prop={props.step} />; } React.startTransition(() => { ReactNoop.render(<Foo step={1} />); }); // This should be just enough to complete the tree without committing it await waitFor(['Foo 1']); expect(ReactNoop.getChildrenAsJSX()).toEqual(null); // To confirm, perform one more unit of work. The tree should now // be flushed. await waitForPaint([]); expect(ReactNoop.getChildrenAsJSX()).toEqual(<span prop={1} />); React.startTransition(() => { ReactNoop.render(<Foo step={2} />); }); // This should be just enough to complete the tree without committing it await waitFor(['Foo 2']); expect(ReactNoop.getChildrenAsJSX()).toEqual(<span prop={1} />); // This time, before we commit the tree, we update the root component with // new props React.startTransition(() => { ReactNoop.render(<Foo step={3} />); }); expect(ReactNoop.getChildrenAsJSX()).toEqual(<span prop={1} />); // Now let's commit. We already had a commit that was pending, which will // render 2. await waitForPaint([]); expect(ReactNoop.getChildrenAsJSX()).toEqual(<span prop={2} />); // If we flush the rest of the work, we should get another commit that // renders 3. If it renders 2 again, that means an update was dropped. await waitForAll(['Foo 3']); expect(ReactNoop.getChildrenAsJSX()).toEqual(<span prop={3} />); }); // @gate www it('updates a child even though the old props is empty', async () => { function Foo(props) { return ( <LegacyHiddenDiv mode="hidden"> <span prop={1} /> </LegacyHiddenDiv> ); } ReactNoop.render(<Foo />); await waitForAll([]); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div hidden={true}> <span prop={1} /> </div>, ); }); xit('can defer side-effects and resume them later on', async () => { class Bar extends React.Component { shouldComponentUpdate(nextProps) { return this.props.idx !== nextProps.idx; } render() { return <span prop={this.props.idx} />; } } function Foo(props) { return ( <div> <span prop={props.tick} /> <div hidden={true}> <Bar idx={props.idx} /> <Bar idx={props.idx + 1} /> </div> </div> ); } ReactNoop.render(<Foo tick={0} idx={0} />); ReactNoop.flushDeferredPri(40 + 25); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={0} /> <div /> </div>, ); ReactNoop.render(<Foo tick={1} idx={0} />); ReactNoop.flushDeferredPri(35 + 25); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={1} /> <div>{/*still not rendered yet*/}</div> </div>, ); ReactNoop.flushDeferredPri(30 + 25); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={1} /> <div> {/* Now we had enough time to finish the spans. */} <span prop={0} /> <span prop={1} /> </div> , </div>, ); const innerSpanA = ReactNoop.dangerouslyGetChildren()[0].children[1].children[1]; ReactNoop.render(<Foo tick={2} idx={1} />); ReactNoop.flushDeferredPri(30 + 25); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={2} /> <div> {/* Still same old numbers. */} <span prop={0} /> <span prop={1} /> </div> </div>, ); ReactNoop.render(<Foo tick={3} idx={1} />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={3} /> <div> {/* New numbers. */} <span prop={1} /> <span prop={2} /> </div> </div>, ); const innerSpanB = ReactNoop.dangerouslyGetChildren()[0].children[1].children[1]; // This should have been an update to an existing instance, not recreation. // We verify that by ensuring that the child instance was the same as // before. expect(innerSpanA).toBe(innerSpanB); }); xit('can defer side-effects and reuse them later - complex', async function () { let ops = []; class Bar extends React.Component { shouldComponentUpdate(nextProps) { return this.props.idx !== nextProps.idx; } render() { ops.push('Bar'); return <span prop={this.props.idx} />; } } class Baz extends React.Component { shouldComponentUpdate(nextProps) { return this.props.idx !== nextProps.idx; } render() { ops.push('Baz'); return [ <Bar key="a" idx={this.props.idx} />, <Bar key="b" idx={this.props.idx} />, ]; } } function Foo(props) { ops.push('Foo'); return ( <div> <span prop={props.tick} /> <div hidden={true}> <Baz idx={props.idx} /> <Baz idx={props.idx} /> <Baz idx={props.idx} /> </div> </div> ); } ReactNoop.render(<Foo tick={0} idx={0} />); ReactNoop.flushDeferredPri(65 + 5); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={0} /> {/*the spans are down-prioritized and not rendered yet*/} <div /> </div>, ); expect(ops).toEqual(['Foo', 'Baz', 'Bar']); ops = []; ReactNoop.render(<Foo tick={1} idx={0} />); ReactNoop.flushDeferredPri(70); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={1} /> {/*still not rendered yet*/} <div /> </div>, ); expect(ops).toEqual(['Foo']); ops = []; await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput([ <div> <span prop={1} />, <div> {/* Now we had enough time to finish the spans. */} <span prop={0} />, <span prop={0} />, <span prop={0} />, <span prop={0} />, <span prop={0} />, <span prop={0} />, </div> </div>, ]); expect(ops).toEqual(['Bar', 'Baz', 'Bar', 'Bar', 'Baz', 'Bar', 'Bar']); ops = []; // Now we're going to update the index but we'll only let it finish half // way through. ReactNoop.render(<Foo tick={2} idx={1} />); ReactNoop.flushDeferredPri(95); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={2} />, <div> {/* Still same old numbers. */} <span prop={0} /> <span prop={0} /> <span prop={0} /> <span prop={0} /> <span prop={0} /> <span prop={0} /> </div> </div>, ); // We let it finish half way through. That means we'll have one fully // completed Baz, one half-way completed Baz and one fully incomplete Baz. expect(ops).toEqual(['Foo', 'Baz', 'Bar', 'Bar', 'Baz', 'Bar']); ops = []; // We'll update again, without letting the new index update yet. Only half // way through. ReactNoop.render(<Foo tick={3} idx={1} />); ReactNoop.flushDeferredPri(50); expect(ReactNoop).toMatchRenderedOutput( <div> <span prop={3} /> <div> {/* Old numbers. */} <span prop={0} /> <span prop={0} /> <span prop={0} /> <span prop={0} /> <span prop={0} /> <span prop={0} /> </div> </div>, ); expect(ops).toEqual(['Foo']); ops = []; // We should now be able to reuse some of the work we've already done // and replay those side-effects. await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput([ <div> <span prop={3} />, <div> {/* New numbers. */} <span prop={1} /> <span prop={1} /> <span prop={1} /> <span prop={1} /> <span prop={1} /> <span prop={1} /> </div> </div>, ]); expect(ops).toEqual(['Bar', 'Baz', 'Bar', 'Bar']); }); // @gate www it('deprioritizes setStates that happens within a deprioritized tree', async () => { const barInstances = []; class Bar extends React.Component { constructor() { super(); this.state = {active: false}; } activate() { this.setState({active: true}); } render() { barInstances.push(this); Scheduler.log('Bar'); return <span prop={this.state.active ? 'X' : this.props.idx} />; } } function Foo(props) { Scheduler.log('Foo'); return ( <div> <span prop={props.tick} /> <LegacyHiddenDiv mode="hidden"> <Bar idx={props.idx} /> <Bar idx={props.idx} /> <Bar idx={props.idx} /> </LegacyHiddenDiv> </div> ); } ReactNoop.render(<Foo tick={0} idx={0} />); await waitForAll(['Foo', 'Bar', 'Bar', 'Bar']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> <span prop={0} /> <div hidden={true}> <span prop={0} /> <span prop={0} /> <span prop={0} /> </div> </div>, ); ReactNoop.render(<Foo tick={1} idx={1} />); await waitFor(['Foo', 'Bar', 'Bar']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> {/* Updated */} <span prop={1} /> <div hidden={true}> <span prop={0} /> <span prop={0} /> <span prop={0} /> </div> </div>, ); barInstances[0].activate(); // This should not be enough time to render the content of all the hidden // items. Including the set state since that is deprioritized. // ReactNoop.flushDeferredPri(35); await waitFor(['Bar']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> {/* Updated */} <span prop={1} /> <div hidden={true}> {/* Still not updated */} <span prop={0} /> <span prop={0} /> <span prop={0} /> </div> </div>, ); // However, once we render fully, we will have enough time to finish it all // at once. await waitForAll(['Bar', 'Bar']); expect(ReactNoop.getChildrenAsJSX()).toEqual( <div> <span prop={1} /> <div hidden={true}> {/* Now we had enough time to finish the spans. */} <span prop="X" /> <span prop={1} /> <span prop={1} /> </div> </div>, ); }); // TODO: Test that side-effects are not cut off when a work in progress node // moves to "current" without flushing due to having lower priority. Does this // even happen? Maybe a child doesn't get processed because it is lower prio? it('calls callback after update is flushed', async () => { let instance; class Foo extends React.Component { constructor() { super(); instance = this; this.state = {text: 'foo'}; } render() { return <span prop={this.state.text} />; } } ReactNoop.render(<Foo />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="foo" />); let called = false; instance.setState({text: 'bar'}, () => { expect(ReactNoop).toMatchRenderedOutput(<span prop="bar" />); called = true; }); await waitForAll([]); expect(called).toBe(true); }); it('calls setState callback even if component bails out', async () => { let instance; class Foo extends React.Component { constructor() { super(); instance = this; this.state = {text: 'foo'}; } shouldComponentUpdate(nextProps, nextState) { return this.state.text !== nextState.text; } render() { return <span prop={this.state.text} />; } } ReactNoop.render(<Foo />); await waitForAll([]); expect(ReactNoop).toMatchRenderedOutput(<span prop="foo" />); let called = false; instance.setState({}, () => { called = true; }); await waitForAll([]); expect(called).toBe(true); }); // TODO: Test that callbacks are not lost if an update is preempted. it('calls componentWillUnmount after a deletion, even if nested', async () => { const ops = []; class Bar extends React.Component { componentWillUnmount() { ops.push(this.props.name); } render() { return <span />; } } class Wrapper extends React.Component { componentWillUnmount() { ops.push('Wrapper'); } render() { return <Bar name={this.props.name} />; } } function Foo(props) { return ( <div> {props.show ? [ <Bar key="a" name="A" />, <Wrapper key="b" name="B" />, <div key="cd"> <Bar name="C" /> <Wrapper name="D" />, </div>, [<Bar key="e" name="E" />, <Bar key="f" name="F" />], ] : []} <div>{props.show ? <Bar key="g" name="G" /> : null}</div> <Bar name="this should not unmount" /> </div> ); } ReactNoop.render(<Foo show={true} />); await waitForAll([]); expect(ops).toEqual([]); ReactNoop.render(<Foo show={false} />); await waitForAll([]); expect(ops).toEqual([ 'A', 'Wrapper', 'B', 'C', 'Wrapper', 'D', 'E', 'F', 'G', ]); }); it('calls componentDidMount/Update after insertion/update', async () => { let ops = []; class Bar extends React.Component { componentDidMount() { ops.push('mount:' + this.props.name); } componentDidUpdate() { ops.push('update:' + this.props.name); } render() { return <span />; } } class Wrapper extends React.Component { componentDidMount() { ops.push('mount:wrapper-' + this.props.name); } componentDidUpdate() { ops.push('update:wrapper-' + this.props.name); } render() { return <Bar name={this.props.name} />; } } function Foo(props) { return ( <div> <Bar key="a" name="A" /> <Wrapper key="b" name="B" /> <div key="cd"> <Bar name="C" /> <Wrapper name="D" /> </div> {[<Bar key="e" name="E" />, <Bar key="f" name="F" />]} <div> <Bar key="g" name="G" /> </div> </div> ); } ReactNoop.render(<Foo />); await waitForAll([]); expect(ops).toEqual([ 'mount:A', 'mount:B', 'mount:wrapper-B', 'mount:C', 'mount:D', 'mount:wrapper-D', 'mount:E', 'mount:F', 'mount:G', ]); ops = []; ReactNoop.render(<Foo />); await waitForAll([]); expect(ops).toEqual([ 'update:A', 'update:B', 'update:wrapper-B', 'update:C', 'update:D', 'update:wrapper-D', 'update:E', 'update:F', 'update:G', ]); }); it('invokes ref callbacks after insertion/update/unmount', async () => { let classInstance = null; let ops = []; class ClassComponent extends React.Component { render() { classInstance = this; return <span />; } } function FunctionComponent(props) { return <span />; } function Foo(props) { return props.show ? ( <div> <ClassComponent ref={n => ops.push(n)} /> <FunctionComponent ref={n => ops.push(n)} /> <div ref={n => ops.push(n)} /> </div> ) : null; } ReactNoop.render(<Foo show={true} />); await expect(async () => await waitForAll([])).toErrorDev( 'Warning: Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?\n\n' + 'Check the render method ' + 'of `Foo`.\n' + ' in FunctionComponent (at **)\n' + ' in div (at **)\n' + ' in Foo (at **)', ); expect(ops).toEqual([ classInstance, // no call for function components {type: 'div', children: [], prop: undefined, hidden: false}, ]); ops = []; // Refs that switch function instances get reinvoked ReactNoop.render(<Foo show={true} />); await waitForAll([]); expect(ops).toEqual([ // detach all refs that switched handlers first. null, null, // reattach as a separate phase classInstance, {type: 'div', children: [], prop: undefined, hidden: false}, ]); ops = []; ReactNoop.render(<Foo show={false} />); await waitForAll([]); expect(ops).toEqual([ // unmount null, null, ]); }); // TODO: Test that mounts, updates, refs, unmounts and deletions happen in the // expected way for aborted and resumed render life-cycles. it('supports string refs', async () => { let fooInstance = null; class Bar extends React.Component { componentDidMount() { this.test = 'test'; } render() { return <div />; } } class Foo extends React.Component { render() { fooInstance = this; return <Bar ref="bar" />; } } ReactNoop.render(<Foo />); await expect(async () => { await waitForAll([]); }).toErrorDev([ 'Warning: Component "Foo" contains the string ref "bar". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref\n' + ' in Foo (at **)', ]); expect(fooInstance.refs.bar.test).toEqual('test'); }); });
24.973818
102
0.531739
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 {ReactServerContext} from 'shared/ReactTypes'; export const ContextRegistry: { [globalName: string]: ReactServerContext<any>, } = {};
22.6
66
0.711048
cybersecurity-penetration-testing
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-interactions-events/focus.production.min.js'); } else { module.exports = require('./cjs/react-interactions-events/focus.development.js'); }
29.375
86
0.710744
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ /** * This is a renderer of React that doesn't have a render target output. * It is useful to demonstrate the internals of the reconciler in isolation * and for testing semantics of reconciliation separate from the host * environment. */ import type {ReactClientValue} from 'react-server/src/ReactFlightServer'; import type {ServerContextJSONValue} from 'shared/ReactTypes'; import {saveModule} from 'react-noop-renderer/flight-modules'; import ReactFlightServer from 'react-server/flight'; type Destination = Array<Uint8Array>; const textEncoder = new TextEncoder(); const ReactNoopFlightServer = ReactFlightServer({ scheduleWork(callback: () => void) { callback(); }, beginWriting(destination: Destination): void {}, writeChunk(destination: Destination, chunk: string): void { destination.push(chunk); }, writeChunkAndReturn(destination: Destination, chunk: string): boolean { destination.push(chunk); return true; }, completeWriting(destination: Destination): void {}, close(destination: Destination): void {}, closeWithError(destination: Destination, error: mixed): void {}, flushBuffered(destination: Destination): void {}, stringToChunk(content: string): Uint8Array { return textEncoder.encode(content); }, stringToPrecomputedChunk(content: string): Uint8Array { return textEncoder.encode(content); }, clonePrecomputedChunk(chunk: Uint8Array): Uint8Array { return chunk; }, isClientReference(reference: Object): boolean { return reference.$$typeof === Symbol.for('react.client.reference'); }, isServerReference(reference: Object): boolean { return reference.$$typeof === Symbol.for('react.server.reference'); }, getClientReferenceKey(reference: Object): Object { return reference; }, resolveClientReferenceMetadata( config: void, reference: {$$typeof: symbol, value: any}, ) { return saveModule(reference.value); }, prepareHostDispatcher() {}, }); type Options = { onError?: (error: mixed) => void, context?: Array<[string, ServerContextJSONValue]>, identifierPrefix?: string, }; function render(model: ReactClientValue, options?: Options): Destination { const destination: Destination = []; const bundlerConfig = undefined; const request = ReactNoopFlightServer.createRequest( model, bundlerConfig, options ? options.onError : undefined, options ? options.context : undefined, options ? options.identifierPrefix : undefined, ); ReactNoopFlightServer.startWork(request); ReactNoopFlightServer.startFlowing(request, destination); return destination; } export {render};
29.526882
75
0.727273
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactTestRenderer; let act; let useState; let useTransition; const SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED = 10; describe('ReactStartTransition', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactTestRenderer = require('react-test-renderer'); act = require('internal-test-utils').act; useState = React.useState; useTransition = React.useTransition; }); it('Warns if a suspicious number of fibers are updated inside startTransition', async () => { const subs = new Set(); const useUserSpaceSubscription = () => { const setState = useState(0)[1]; subs.add(setState); }; let triggerHookTransition; const Component = ({level}) => { useUserSpaceSubscription(); if (level === 0) { triggerHookTransition = useTransition()[1]; } if (level < SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED) { return <Component level={level + 1} />; } return null; }; await act(() => { ReactTestRenderer.create(<Component level={0} />, { isConcurrent: true, }); }); await expect(async () => { await act(() => { React.startTransition(() => { subs.forEach(setState => { setState(state => state + 1); }); }); }); }).toWarnDev( [ 'Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.', ], {withoutStack: true}, ); await expect(async () => { await act(() => { triggerHookTransition(() => { subs.forEach(setState => { setState(state => state + 1); }); }); }); }).toWarnDev( [ 'Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.', ], {withoutStack: true}, ); }); });
25.318681
95
0.579783
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment node */ 'use strict'; const React = require('react'); let ReactTestRenderer; let Context; const RCTView = 'RCTView'; const View = props => <RCTView {...props} />; describe('ReactTestRendererTraversal', () => { beforeEach(() => { jest.resetModules(); ReactTestRenderer = require('react-test-renderer'); Context = React.createContext(null); }); class Example extends React.Component { render() { return ( <View> <View foo="foo"> <View bar="bar" /> <View bar="bar" baz="baz" itself="itself" /> <View /> <ExampleSpread bar="bar" /> <ExampleFn bar="bar" bing="bing" /> <ExampleNull bar="bar" /> <ExampleNull null="null"> <View void="void" /> <View void="void" /> </ExampleNull> <React.Profiler id="test" onRender={() => {}}> <ExampleForwardRef qux="qux" /> </React.Profiler> <> <> <Context.Provider value={null}> <Context.Consumer> {() => <View nested={true} />} </Context.Consumer> </Context.Provider> </> <View nested={true} /> <View nested={true} /> </> </View> </View> ); } } class ExampleSpread extends React.Component { render = () => <View {...this.props} />; } const ExampleFn = props => <View baz="baz" />; const ExampleNull = props => null; const ExampleForwardRef = React.forwardRef((props, ref) => ( <View {...props} ref={ref} /> )); it('initializes', () => { const render = ReactTestRenderer.create(<Example />); const hasFooProp = node => node.props.hasOwnProperty('foo'); // assert .props, .type and .parent attributes const foo = render.root.find(hasFooProp); expect(foo.props.children).toHaveLength(9); expect(foo.type).toBe(View); expect(render.root.parent).toBe(null); expect(foo.children[0].parent).toBe(foo); }); it('searches via .find() / .findAll()', () => { const render = ReactTestRenderer.create(<Example />); const hasFooProp = node => node.props.hasOwnProperty('foo'); const hasBarProp = node => node.props.hasOwnProperty('bar'); const hasBazProp = node => node.props.hasOwnProperty('baz'); const hasBingProp = node => node.props.hasOwnProperty('bing'); const hasNullProp = node => node.props.hasOwnProperty('null'); const hasVoidProp = node => node.props.hasOwnProperty('void'); const hasItselfProp = node => node.props.hasOwnProperty('itself'); const hasNestedProp = node => node.props.hasOwnProperty('nested'); expect(() => render.root.find(hasFooProp)).not.toThrow(); // 1 match expect(() => render.root.find(hasBarProp)).toThrow(); // >1 matches expect(() => render.root.find(hasBazProp)).toThrow(); // >1 matches expect(() => render.root.find(hasBingProp)).not.toThrow(); // 1 match expect(() => render.root.find(hasNullProp)).not.toThrow(); // 1 match expect(() => render.root.find(hasVoidProp)).toThrow(); // 0 matches expect(() => render.root.find(hasNestedProp)).toThrow(); // >1 matches // same assertion as .find(), but confirm length expect(render.root.findAll(hasFooProp, {deep: false})).toHaveLength(1); expect(render.root.findAll(hasBarProp, {deep: false})).toHaveLength(5); expect(render.root.findAll(hasBazProp, {deep: false})).toHaveLength(2); expect(render.root.findAll(hasBingProp, {deep: false})).toHaveLength(1); expect(render.root.findAll(hasNullProp, {deep: false})).toHaveLength(1); expect(render.root.findAll(hasVoidProp, {deep: false})).toHaveLength(0); expect(render.root.findAll(hasNestedProp, {deep: false})).toHaveLength(3); // note: with {deep: true}, .findAll() will continue to // search children, even after finding a match expect(render.root.findAll(hasFooProp)).toHaveLength(2); expect(render.root.findAll(hasBarProp)).toHaveLength(9); expect(render.root.findAll(hasBazProp)).toHaveLength(4); expect(render.root.findAll(hasBingProp)).toHaveLength(1); // no spread expect(render.root.findAll(hasNullProp)).toHaveLength(1); // no spread expect(render.root.findAll(hasVoidProp)).toHaveLength(0); expect(render.root.findAll(hasNestedProp, {deep: false})).toHaveLength(3); const bing = render.root.find(hasBingProp); expect(bing.find(hasBarProp)).toBe(bing); expect(bing.find(hasBingProp)).toBe(bing); expect(bing.findAll(hasBazProp, {deep: false})).toHaveLength(1); expect(bing.findAll(hasBazProp)).toHaveLength(2); const foo = render.root.find(hasFooProp); expect(foo.findAll(hasFooProp, {deep: false})).toHaveLength(1); expect(foo.findAll(hasFooProp)).toHaveLength(2); const itself = foo.find(hasItselfProp); expect(itself.find(hasBarProp)).toBe(itself); expect(itself.find(hasBazProp)).toBe(itself); expect(itself.findAll(hasBazProp, {deep: false})).toHaveLength(1); expect(itself.findAll(hasBazProp)).toHaveLength(2); }); it('searches via .findByType() / .findAllByType()', () => { const render = ReactTestRenderer.create(<Example />); expect(() => render.root.findByType(ExampleFn)).not.toThrow(); // 1 match expect(() => render.root.findByType(View)).not.toThrow(); // 1 match expect(() => render.root.findByType(ExampleForwardRef)).not.toThrow(); // 1 match // note: there are clearly multiple <View /> in general, but there // is only one being rendered at root node level expect(() => render.root.findByType(ExampleNull)).toThrow(); // 2 matches expect(render.root.findAllByType(ExampleFn)).toHaveLength(1); expect(render.root.findAllByType(View, {deep: false})).toHaveLength(1); expect(render.root.findAllByType(View)).toHaveLength(11); expect(render.root.findAllByType(ExampleNull)).toHaveLength(2); expect(render.root.findAllByType(ExampleForwardRef)).toHaveLength(1); const nulls = render.root.findAllByType(ExampleNull); expect(nulls[0].findAllByType(View)).toHaveLength(0); expect(nulls[1].findAllByType(View)).toHaveLength(0); const fn = render.root.findAllByType(ExampleFn); expect(fn[0].findAllByType(View)).toHaveLength(1); }); it('searches via .findByProps() / .findAllByProps()', () => { const render = ReactTestRenderer.create(<Example />); const foo = 'foo'; const bar = 'bar'; const baz = 'baz'; const qux = 'qux'; expect(() => render.root.findByProps({foo})).not.toThrow(); // 1 match expect(() => render.root.findByProps({bar})).toThrow(); // >1 matches expect(() => render.root.findByProps({baz})).toThrow(); // >1 matches expect(() => render.root.findByProps({qux})).not.toThrow(); // 1 match expect(render.root.findAllByProps({foo}, {deep: false})).toHaveLength(1); expect(render.root.findAllByProps({bar}, {deep: false})).toHaveLength(5); expect(render.root.findAllByProps({baz}, {deep: false})).toHaveLength(2); expect(render.root.findAllByProps({qux}, {deep: false})).toHaveLength(1); expect(render.root.findAllByProps({foo})).toHaveLength(2); expect(render.root.findAllByProps({bar})).toHaveLength(9); expect(render.root.findAllByProps({baz})).toHaveLength(4); expect(render.root.findAllByProps({qux})).toHaveLength(3); }); it('skips special nodes', () => { const render = ReactTestRenderer.create(<Example />); expect(render.root.findAllByType(React.Fragment)).toHaveLength(0); expect(render.root.findAllByType(Context.Consumer)).toHaveLength(0); expect(render.root.findAllByType(Context.Provider)).toHaveLength(0); const expectedParent = render.root.findByProps({foo: 'foo'}, {deep: false}) .children[0]; const nestedViews = render.root.findAllByProps( {nested: true}, {deep: false}, ); expect(nestedViews.length).toBe(3); expect(nestedViews[0].parent).toBe(expectedParent); expect(nestedViews[1].parent).toBe(expectedParent); expect(nestedViews[2].parent).toBe(expectedParent); }); it('can have special nodes as roots', () => { const FR = React.forwardRef((props, ref) => <section {...props} />); expect( ReactTestRenderer.create( <FR> <div /> <div /> </FR>, ).root.findAllByType('div').length, ).toBe(2); expect( ReactTestRenderer.create( <> <div /> <div /> </>, ).root.findAllByType('div').length, ).toBe(2); expect( ReactTestRenderer.create( <React.Fragment key="foo"> <div /> <div /> </React.Fragment>, ).root.findAllByType('div').length, ).toBe(2); expect( ReactTestRenderer.create( <React.StrictMode> <div /> <div /> </React.StrictMode>, ).root.findAllByType('div').length, ).toBe(2); expect( ReactTestRenderer.create( <Context.Provider value={null}> <div /> <div /> </Context.Provider>, ).root.findAllByType('div').length, ).toBe(2); }); });
37.315789
85
0.627602
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 {ReactScopeInstance} from 'shared/ReactTypes'; import type {DOMEventName} from '../events/DOMEventNames'; export type ReactDOMEventHandle = ( target: EventTarget | ReactScopeInstance, callback: (SyntheticEvent<EventTarget>) => void, ) => () => void; export type ReactDOMEventHandleListener = { callback: (SyntheticEvent<EventTarget>) => void, capture: boolean, type: DOMEventName, };
25.652174
66
0.722222
Tricks-Web-Penetration-Tester
// @flow import memoizeOne from 'memoize-one'; import * as React from 'react'; import { createElement, PureComponent } from 'react'; import { cancelTimeout, requestTimeout } from './timer'; import { getScrollbarSize, getRTLOffsetType } from './domHelpers'; import type { TimeoutID } from './timer'; type Direction = 'ltr' | 'rtl'; export type ScrollToAlign = 'auto' | 'smart' | 'center' | 'start' | 'end'; type itemSize = number | ((index: number) => number); type RenderComponentProps<T> = {| columnIndex: number, data: T, isScrolling?: boolean, rowIndex: number, style: Object, |}; export type RenderComponent<T> = React$ComponentType< $Shape<RenderComponentProps<T>> >; type ScrollDirection = 'forward' | 'backward'; type OnItemsRenderedCallback = ({ overscanColumnStartIndex: number, overscanColumnStopIndex: number, overscanRowStartIndex: number, overscanRowStopIndex: number, visibleColumnStartIndex: number, visibleColumnStopIndex: number, visibleRowStartIndex: number, visibleRowStopIndex: number, }) => void; type OnScrollCallback = ({ horizontalScrollDirection: ScrollDirection, scrollLeft: number, scrollTop: number, scrollUpdateWasRequested: boolean, verticalScrollDirection: ScrollDirection, }) => void; type ScrollEvent = SyntheticEvent<HTMLDivElement>; type ItemStyleCache = { [key: string]: Object }; type OuterProps = {| children: React$Node, className: string | void, onScroll: ScrollEvent => void, style: { [string]: mixed, }, |}; type InnerProps = {| children: React$Node, style: { [string]: mixed, }, |}; export type Props<T> = {| children: RenderComponent<T>, className?: string, columnCount: number, columnWidth: itemSize, direction: Direction, height: number, initialScrollLeft?: number, initialScrollTop?: number, innerRef?: any, innerElementType?: string | React.AbstractComponent<InnerProps, any>, innerTagName?: string, // deprecated itemData: T, itemKey?: (params: {| columnIndex: number, data: T, rowIndex: number, |}) => any, onItemsRendered?: OnItemsRenderedCallback, onScroll?: OnScrollCallback, outerRef?: any, outerElementType?: string | React.AbstractComponent<OuterProps, any>, outerTagName?: string, // deprecated overscanColumnCount?: number, overscanColumnsCount?: number, // deprecated overscanCount?: number, // deprecated overscanRowCount?: number, overscanRowsCount?: number, // deprecated rowCount: number, rowHeight: itemSize, style?: Object, useIsScrolling: boolean, width: number, |}; type State = {| instance: any, isScrolling: boolean, horizontalScrollDirection: ScrollDirection, scrollLeft: number, scrollTop: number, scrollUpdateWasRequested: boolean, verticalScrollDirection: ScrollDirection, |}; type getItemOffset = ( props: Props<any>, index: number, instanceProps: any ) => number; type getItemSize = ( props: Props<any>, index: number, instanceProps: any ) => number; type getEstimatedTotalSize = (props: Props<any>, instanceProps: any) => number; type GetOffsetForItemAndAlignment = ( props: Props<any>, index: number, align: ScrollToAlign, scrollOffset: number, instanceProps: any, scrollbarSize: number ) => number; type GetStartIndexForOffset = ( props: Props<any>, offset: number, instanceProps: any ) => number; type GetStopIndexForStartIndex = ( props: Props<any>, startIndex: number, scrollOffset: number, instanceProps: any ) => number; type InitInstanceProps = (props: Props<any>, instance: any) => any; type ValidateProps = (props: Props<any>) => void; const IS_SCROLLING_DEBOUNCE_INTERVAL = 150; const defaultItemKey = ( { columnIndex, data, rowIndex }: { columnIndex: number, data: any, rowIndex: number }, ) => `${rowIndex}:${columnIndex}`; // In DEV mode, this Set helps us only log a warning once per component instance. // This avoids spamming the console every time a render happens. let devWarningsOverscanCount = null; let devWarningsOverscanRowsColumnsCount = null; let devWarningsTagName = null; if (process.env.NODE_ENV !== 'production') { if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') { devWarningsOverscanCount = new WeakSet(); devWarningsOverscanRowsColumnsCount = new WeakSet(); devWarningsTagName = new WeakSet(); } } export default function createGridComponent({ getColumnOffset, getColumnStartIndexForOffset, getColumnStopIndexForStartIndex, getColumnWidth, getEstimatedTotalHeight, getEstimatedTotalWidth, getOffsetForColumnAndAlignment, getOffsetForRowAndAlignment, getRowHeight, getRowOffset, getRowStartIndexForOffset, getRowStopIndexForStartIndex, initInstanceProps, shouldResetStyleCacheOnItemSizeChange, validateProps, }: {| getColumnOffset: getItemOffset, getColumnStartIndexForOffset: GetStartIndexForOffset, getColumnStopIndexForStartIndex: GetStopIndexForStartIndex, getColumnWidth: getItemSize, getEstimatedTotalHeight: getEstimatedTotalSize, getEstimatedTotalWidth: getEstimatedTotalSize, getOffsetForColumnAndAlignment: GetOffsetForItemAndAlignment, getOffsetForRowAndAlignment: GetOffsetForItemAndAlignment, getRowOffset: getItemOffset, getRowHeight: getItemSize, getRowStartIndexForOffset: GetStartIndexForOffset, getRowStopIndexForStartIndex: GetStopIndexForStartIndex, initInstanceProps: InitInstanceProps, shouldResetStyleCacheOnItemSizeChange: boolean, validateProps: ValidateProps, |}): React.ComponentType<Props<mixed>> { return class Grid<T> extends PureComponent<Props<T>, State> { _instanceProps: any = initInstanceProps(this.props, this); _resetIsScrollingTimeoutId: TimeoutID | null = null; _outerRef: ?HTMLDivElement; static defaultProps: { direction: string, itemData: void, useIsScrolling: boolean } = { direction: 'ltr', itemData: undefined, useIsScrolling: false, }; state: State = { instance: this, isScrolling: false, horizontalScrollDirection: 'forward', scrollLeft: typeof this.props.initialScrollLeft === 'number' ? this.props.initialScrollLeft : 0, scrollTop: typeof this.props.initialScrollTop === 'number' ? this.props.initialScrollTop : 0, scrollUpdateWasRequested: false, verticalScrollDirection: 'forward', }; // Always use explicit constructor for React components. // It produces less code after transpilation. (#26) // eslint-disable-next-line no-useless-constructor constructor(props: Props<T>) { super(props); } static getDerivedStateFromProps( nextProps: Props<T>, prevState: State ): $Shape<State> | null { validateSharedProps(nextProps, prevState); validateProps(nextProps); return null; } scrollTo({ scrollLeft, scrollTop, }: { scrollLeft: number, scrollTop: number, }): void { if (scrollLeft !== undefined) { scrollLeft = Math.max(0, scrollLeft); } if (scrollTop !== undefined) { scrollTop = Math.max(0, scrollTop); } this.setState(prevState => { if (scrollLeft === undefined) { scrollLeft = prevState.scrollLeft; } if (scrollTop === undefined) { scrollTop = prevState.scrollTop; } if ( prevState.scrollLeft === scrollLeft && prevState.scrollTop === scrollTop ) { return null; } return { horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward', scrollLeft: scrollLeft, scrollTop: scrollTop, scrollUpdateWasRequested: true, verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward', }; }, this._resetIsScrollingDebounced); } scrollToItem({ align = 'auto', columnIndex, rowIndex, }: { align: ScrollToAlign, columnIndex?: number, rowIndex?: number, }): void { const { columnCount, height, rowCount, width } = this.props; const { scrollLeft, scrollTop } = this.state; const scrollbarSize = getScrollbarSize(); if (columnIndex !== undefined) { columnIndex = Math.max(0, Math.min(columnIndex, columnCount - 1)); } if (rowIndex !== undefined) { rowIndex = Math.max(0, Math.min(rowIndex, rowCount - 1)); } const estimatedTotalHeight = getEstimatedTotalHeight( this.props, this._instanceProps ); const estimatedTotalWidth = getEstimatedTotalWidth( this.props, this._instanceProps ); // The scrollbar size should be considered when scrolling an item into view, // to ensure it's fully visible. // But we only need to account for its size when it's actually visible. const horizontalScrollbarSize = estimatedTotalWidth > width ? scrollbarSize : 0; const verticalScrollbarSize = estimatedTotalHeight > height ? scrollbarSize : 0; this.scrollTo({ scrollLeft: columnIndex !== undefined ? getOffsetForColumnAndAlignment( this.props, columnIndex, align, scrollLeft, this._instanceProps, verticalScrollbarSize ) : scrollLeft, scrollTop: rowIndex !== undefined ? getOffsetForRowAndAlignment( this.props, rowIndex, align, scrollTop, this._instanceProps, horizontalScrollbarSize ) : scrollTop, }); } componentDidMount() { const { initialScrollLeft, initialScrollTop } = this.props; if (this._outerRef != null) { const outerRef = ((this._outerRef: any): HTMLElement); if (typeof initialScrollLeft === 'number') { outerRef.scrollLeft = initialScrollLeft; } if (typeof initialScrollTop === 'number') { outerRef.scrollTop = initialScrollTop; } } this._callPropsCallbacks(); } componentDidUpdate() { const { direction } = this.props; const { scrollLeft, scrollTop, scrollUpdateWasRequested } = this.state; if (scrollUpdateWasRequested && this._outerRef != null) { // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements. // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left). // So we need to determine which browser behavior we're dealing with, and mimic it. const outerRef = ((this._outerRef: any): HTMLElement); if (direction === 'rtl') { switch (getRTLOffsetType()) { case 'negative': outerRef.scrollLeft = -scrollLeft; break; case 'positive-ascending': outerRef.scrollLeft = scrollLeft; break; default: const { clientWidth, scrollWidth } = outerRef; outerRef.scrollLeft = scrollWidth - clientWidth - scrollLeft; break; } } else { outerRef.scrollLeft = Math.max(0, scrollLeft); } outerRef.scrollTop = Math.max(0, scrollTop); } this._callPropsCallbacks(); } componentWillUnmount() { if (this._resetIsScrollingTimeoutId !== null) { cancelTimeout(this._resetIsScrollingTimeoutId); } } render(): any { const { children, className, columnCount, direction, height, innerRef, innerElementType, innerTagName, itemData, itemKey = defaultItemKey, outerElementType, outerTagName, rowCount, style, useIsScrolling, width, } = this.props; const { isScrolling } = this.state; const [ columnStartIndex, columnStopIndex, ] = this._getHorizontalRangeToRender(); const [rowStartIndex, rowStopIndex] = this._getVerticalRangeToRender(); const items = []; if (columnCount > 0 && rowCount) { for ( let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++ ) { for ( let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++ ) { items.push( createElement(children, { columnIndex, data: itemData, isScrolling: useIsScrolling ? isScrolling : undefined, key: itemKey({ columnIndex, data: itemData, rowIndex }), rowIndex, style: this._getItemStyle(rowIndex, columnIndex), }) ); } } } // Read this value AFTER items have been created, // So their actual sizes (if variable) are taken into consideration. const estimatedTotalHeight = getEstimatedTotalHeight( this.props, this._instanceProps ); const estimatedTotalWidth = getEstimatedTotalWidth( this.props, this._instanceProps ); return createElement( outerElementType || outerTagName || 'div', { className, onScroll: this._onScroll, ref: this._outerRefSetter, style: { position: 'relative', height, width, overflow: 'auto', WebkitOverflowScrolling: 'touch', willChange: 'transform', direction, ...style, }, }, createElement(innerElementType || innerTagName || 'div', { children: items, ref: innerRef, style: { height: estimatedTotalHeight, pointerEvents: isScrolling ? 'none' : undefined, width: estimatedTotalWidth, }, }) ); } _callOnItemsRendered: (( overscanColumnStartIndex: number, overscanColumnStopIndex: number, overscanRowStartIndex: number, overscanRowStopIndex: number, visibleColumnStartIndex: number, visibleColumnStopIndex: number, visibleRowStartIndex: number, visibleRowStopIndex: number ) => void) = memoizeOne( ( overscanColumnStartIndex: number, overscanColumnStopIndex: number, overscanRowStartIndex: number, overscanRowStopIndex: number, visibleColumnStartIndex: number, visibleColumnStopIndex: number, visibleRowStartIndex: number, visibleRowStopIndex: number ) => ((this.props.onItemsRendered: any): OnItemsRenderedCallback)({ overscanColumnStartIndex, overscanColumnStopIndex, overscanRowStartIndex, overscanRowStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, visibleRowStartIndex, visibleRowStopIndex, }) ); _callOnScroll: (( scrollLeft: number, scrollTop: number, horizontalScrollDirection: ScrollDirection, verticalScrollDirection: ScrollDirection, scrollUpdateWasRequested: boolean ) => void) = memoizeOne( ( scrollLeft: number, scrollTop: number, horizontalScrollDirection: ScrollDirection, verticalScrollDirection: ScrollDirection, scrollUpdateWasRequested: boolean ) => ((this.props.onScroll: any): OnScrollCallback)({ horizontalScrollDirection, scrollLeft, scrollTop, verticalScrollDirection, scrollUpdateWasRequested, }) ); _callPropsCallbacks() { const { columnCount, onItemsRendered, onScroll, rowCount } = this.props; if (typeof onItemsRendered === 'function') { if (columnCount > 0 && rowCount > 0) { const [ overscanColumnStartIndex, overscanColumnStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, ] = this._getHorizontalRangeToRender(); const [ overscanRowStartIndex, overscanRowStopIndex, visibleRowStartIndex, visibleRowStopIndex, ] = this._getVerticalRangeToRender(); this._callOnItemsRendered( overscanColumnStartIndex, overscanColumnStopIndex, overscanRowStartIndex, overscanRowStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, visibleRowStartIndex, visibleRowStopIndex ); } } if (typeof onScroll === 'function') { const { horizontalScrollDirection, scrollLeft, scrollTop, scrollUpdateWasRequested, verticalScrollDirection, } = this.state; this._callOnScroll( scrollLeft, scrollTop, horizontalScrollDirection, verticalScrollDirection, scrollUpdateWasRequested ); } } // Lazily create and cache item styles while scrolling, // So that pure component sCU will prevent re-renders. // We maintain this cache, and pass a style prop rather than index, // So that List can clear cached styles and force item re-render if necessary. _getItemStyle = (rowIndex: number, columnIndex: number): Object => { const { columnWidth, direction, rowHeight } = this.props; const itemStyleCache = this._getItemStyleCache( shouldResetStyleCacheOnItemSizeChange && columnWidth, shouldResetStyleCacheOnItemSizeChange && direction, shouldResetStyleCacheOnItemSizeChange && rowHeight ); const key = `${rowIndex}:${columnIndex}`; let style; if (itemStyleCache.hasOwnProperty(key)) { style = itemStyleCache[key]; } else { itemStyleCache[key] = style = { position: 'absolute', // $FlowFixMe computed properties are unsupported [direction === 'rtl' ? 'right' : 'left']: getColumnOffset( this.props, columnIndex, this._instanceProps ), top: getRowOffset(this.props, rowIndex, this._instanceProps), height: getRowHeight(this.props, rowIndex, this._instanceProps), width: getColumnWidth(this.props, columnIndex, this._instanceProps), }; } return style; }; _getItemStyleCache: ((_: any, __: any, ___: any) => ItemStyleCache) = memoizeOne((_: any, __: any, ___: any) => ({})); _getHorizontalRangeToRender(): [number, number, number, number] { const { columnCount, overscanColumnCount, overscanColumnsCount, overscanCount, rowCount, } = this.props; const { horizontalScrollDirection, isScrolling, scrollLeft } = this.state; const overscanCountResolved: number = overscanColumnCount || overscanColumnsCount || overscanCount || 1; if (columnCount === 0 || rowCount === 0) { return [0, 0, 0, 0]; } const startIndex = getColumnStartIndexForOffset( this.props, scrollLeft, this._instanceProps ); const stopIndex = getColumnStopIndexForStartIndex( this.props, startIndex, scrollLeft, this._instanceProps ); // Overscan by one item in each direction so that tab/focus works. // If there isn't at least one extra item, tab loops back around. const overscanBackward = !isScrolling || horizontalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1; const overscanForward = !isScrolling || horizontalScrollDirection === 'forward' ? Math.max(1, overscanCountResolved) : 1; return [ Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(columnCount - 1, stopIndex + overscanForward)), startIndex, stopIndex, ]; } _getVerticalRangeToRender(): [number, number, number, number] { const { columnCount, overscanCount, overscanRowCount, overscanRowsCount, rowCount, } = this.props; const { isScrolling, verticalScrollDirection, scrollTop } = this.state; const overscanCountResolved: number = overscanRowCount || overscanRowsCount || overscanCount || 1; if (columnCount === 0 || rowCount === 0) { return [0, 0, 0, 0]; } const startIndex = getRowStartIndexForOffset( this.props, scrollTop, this._instanceProps ); const stopIndex = getRowStopIndexForStartIndex( this.props, startIndex, scrollTop, this._instanceProps ); // Overscan by one item in each direction so that tab/focus works. // If there isn't at least one extra item, tab loops back around. const overscanBackward = !isScrolling || verticalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1; const overscanForward = !isScrolling || verticalScrollDirection === 'forward' ? Math.max(1, overscanCountResolved) : 1; return [ Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(rowCount - 1, stopIndex + overscanForward)), startIndex, stopIndex, ]; } _onScroll = (event: ScrollEvent): void => { const { clientHeight, clientWidth, scrollLeft, scrollTop, scrollHeight, scrollWidth, } = event.currentTarget; this.setState(prevState => { if ( prevState.scrollLeft === scrollLeft && prevState.scrollTop === scrollTop ) { // Scroll position may have been updated by cDM/cDU, // In which case we don't need to trigger another render, // And we don't want to update state.isScrolling. return null; } const { direction } = this.props; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements. // This is not the case for all browsers though (e.g. Chrome reports values as positive, measured relative to the left). // It's also easier for this component if we convert offsets to the same format as they would be in for ltr. // So the simplest solution is to determine which browser behavior we're dealing with, and convert based on it. let calculatedScrollLeft = scrollLeft; if (direction === 'rtl') { switch (getRTLOffsetType()) { case 'negative': calculatedScrollLeft = -scrollLeft; break; case 'positive-descending': calculatedScrollLeft = scrollWidth - clientWidth - scrollLeft; break; } } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds. calculatedScrollLeft = Math.max( 0, Math.min(calculatedScrollLeft, scrollWidth - clientWidth) ); const calculatedScrollTop = Math.max( 0, Math.min(scrollTop, scrollHeight - clientHeight) ); return { isScrolling: true, horizontalScrollDirection: prevState.scrollLeft < scrollLeft ? 'forward' : 'backward', scrollLeft: calculatedScrollLeft, scrollTop: calculatedScrollTop, verticalScrollDirection: prevState.scrollTop < scrollTop ? 'forward' : 'backward', scrollUpdateWasRequested: false, }; }, this._resetIsScrollingDebounced); }; _outerRefSetter = (ref: any): void => { const { outerRef } = this.props; this._outerRef = ((ref: any): HTMLDivElement); if (typeof outerRef === 'function') { outerRef(ref); } else if ( outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current') ) { outerRef.current = ref; } }; _resetIsScrollingDebounced = () => { if (this._resetIsScrollingTimeoutId !== null) { cancelTimeout(this._resetIsScrollingTimeoutId); } this._resetIsScrollingTimeoutId = requestTimeout( this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL ); }; _resetIsScrolling = () => { this._resetIsScrollingTimeoutId = null; this.setState({ isScrolling: false }, () => { // Clear style cache after state update has been committed. // This way we don't break pure sCU for items that don't use isScrolling param. this._getItemStyleCache(-1); }); }; }; } const validateSharedProps = ( { children, direction, height, innerTagName, outerTagName, overscanColumnsCount, overscanCount, overscanRowsCount, width, }: Props<any>, { instance }: State ): void => { if (process.env.NODE_ENV !== 'production') { if (typeof overscanCount === 'number') { if (devWarningsOverscanCount && !devWarningsOverscanCount.has(instance)) { devWarningsOverscanCount.add(instance); console.warn( 'The overscanCount prop has been deprecated. ' + 'Please use the overscanColumnCount and overscanRowCount props instead.' ); } } if ( typeof overscanColumnsCount === 'number' || typeof overscanRowsCount === 'number' ) { if ( devWarningsOverscanRowsColumnsCount && !devWarningsOverscanRowsColumnsCount.has(instance) ) { devWarningsOverscanRowsColumnsCount.add(instance); console.warn( 'The overscanColumnsCount and overscanRowsCount props have been deprecated. ' + 'Please use the overscanColumnCount and overscanRowCount props instead.' ); } } if (innerTagName != null || outerTagName != null) { if (devWarningsTagName && !devWarningsTagName.has(instance)) { devWarningsTagName.add(instance); console.warn( 'The innerTagName and outerTagName props have been deprecated. ' + 'Please use the innerElementType and outerElementType props instead.' ); } } if (children == null) { throw Error( 'An invalid "children" prop has been specified. ' + 'Value should be a React component. ' + `"${children === null ? 'null' : typeof children}" was specified.` ); } switch (direction) { case 'ltr': case 'rtl': // Valid values break; default: throw Error( 'An invalid "direction" prop has been specified. ' + 'Value should be either "ltr" or "rtl". ' + `"${direction}" was specified.` ); } if (typeof width !== 'number') { throw Error( 'An invalid "width" prop has been specified. ' + 'Grids must specify a number for width. ' + `"${width === null ? 'null' : typeof width}" was specified.` ); } if (typeof height !== 'number') { throw Error( 'An invalid "height" prop has been specified. ' + 'Grids must specify a number for height. ' + `"${height === null ? 'null' : typeof height}" was specified.` ); } } };
29.13449
128
0.614584
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import ReactSharedInternals from 'shared/ReactSharedInternals'; let suppressWarning = false; export function setSuppressWarning(newSuppressWarning) { if (__DEV__) { suppressWarning = newSuppressWarning; } } // In DEV, calls to console.warn and console.error get replaced // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. export function warn(format, ...args) { if (__DEV__) { if (!suppressWarning) { printWarning('warn', format, args); } } } export function error(format, ...args) { if (__DEV__) { if (!suppressWarning) { printWarning('error', format, args); } } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. if (__DEV__) { const ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; const stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } // eslint-disable-next-line react-internal/safe-string-coercion const argsWithFormat = args.map(item => String(item)); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); } }
29.35
79
0.689011
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export default class EventEmitter<Events: Object> { listenersMap: Map<string, Array<Function>> = new Map(); addListener<Event: $Keys<Events>>( event: Event, listener: (...$ElementType<Events, Event>) => any, ): void { const listeners = this.listenersMap.get(event); if (listeners === undefined) { this.listenersMap.set(event, [listener]); } else { const index = listeners.indexOf(listener); if (index < 0) { listeners.push(listener); } } } emit<Event: $Keys<Events>>( event: Event, ...args: $ElementType<Events, Event> ): void { const listeners = this.listenersMap.get(event); if (listeners !== undefined) { if (listeners.length === 1) { // No need to clone or try/catch const listener = listeners[0]; listener.apply(null, args); } else { let didThrow = false; let caughtError = null; const clonedListeners = Array.from(listeners); for (let i = 0; i < clonedListeners.length; i++) { const listener = clonedListeners[i]; try { listener.apply(null, args); } catch (error) { if (caughtError === null) { didThrow = true; caughtError = error; } } } if (didThrow) { throw caughtError; } } } } removeAllListeners(): void { this.listenersMap.clear(); } removeListener(event: $Keys<Events>, listener: Function): void { const listeners = this.listenersMap.get(event); if (listeners !== undefined) { const index = listeners.indexOf(listener); if (index >= 0) { listeners.splice(index, 1); } } } }
24.644737
66
0.568789
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import * as React from 'react'; import {useLayoutEffect, useRef, useState} from 'react'; import {render} from 'react-dom'; function createContainer() { const container = document.createElement('div'); ((document.body: any): HTMLBodyElement).appendChild(container); return container; } function EffectWithState() { const [didMount, setDidMount] = useState(0); const renderCountRef = useRef(0); renderCountRef.current++; useLayoutEffect(() => { if (!didMount) { setDidMount(true); } }, [didMount]); return ( <ul> <li>Rendered {renderCountRef.current} times</li> {didMount && <li>Mounted!</li>} </ul> ); } render(<EffectWithState />, createContainer());
21.097561
66
0.669613
owtf
const React = window.React; const startDate = new Date(); /** * This test case was originally provided by @richsoni, * https://github.com/facebook/react/issues/8116 */ class SwitchDateTestCase extends React.Component { state = { fullDate: false, date: startDate, }; render() { const attrs = this.inputAttrs(); return ( <div> <p> <b>{attrs.type}</b> input type ({attrs.value}) </p> <p> <input type={attrs.type} value={attrs.value} onChange={this.onInputChange} /> <label> <input type="checkbox" checked={this.state.fullDate} onChange={this.updateFullDate} />{' '} Switch type </label> </p> </div> ); } inputAttrs() { if (this.state.fullDate) { return { type: 'datetime-local', value: this.state.date.toISOString().replace(/\..*Z/, ''), }; } else { return { type: 'date', value: this.state.date.toISOString().replace(/T.*/, ''), }; } } onInputChange = ({target: {value}}) => { const date = value ? new Date(Date.parse(value)) : startDate; this.setState({date}); }; updateFullDate = () => { this.setState({ fullDate: !this.state.fullDate, }); }; } export default SwitchDateTestCase;
20.014706
66
0.509804
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 styles from './ReactLogo.css'; type Props = { className?: string, }; export default function ReactLogo({className}: Props): React.Node { return ( <svg xmlns="http://www.w3.org/2000/svg" className={`${styles.ReactLogo} ${className || ''}`} viewBox="-11.5 -10.23174 23 20.46348"> <circle cx="0" cy="0" r="2.05" fill="currentColor" /> <g stroke="currentColor" strokeWidth="1" fill="none"> <ellipse rx="11" ry="4.2" /> <ellipse rx="11" ry="4.2" transform="rotate(60)" /> <ellipse rx="11" ry="4.2" transform="rotate(120)" /> </g> </svg> ); }
25
67
0.599767
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 {ReactServerContext} from 'shared/ReactTypes'; import { REACT_PROVIDER_TYPE, REACT_SERVER_CONTEXT_TYPE, REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, } from 'shared/ReactSymbols'; import ReactSharedInternals from 'shared/ReactSharedInternals'; const ContextRegistry = ReactSharedInternals.ContextRegistry; export function getOrCreateServerContext( globalName: string, ): ReactServerContext<any> { if (!ContextRegistry[globalName]) { const context: ReactServerContext<any> = { $$typeof: REACT_SERVER_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, _currentValue2: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, _defaultValue: REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: (null: any), Consumer: (null: any), _globalName: globalName, }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context, }; if (__DEV__) { let hasWarnedAboutUsingConsumer; context._currentRenderer = null; context._currentRenderer2 = null; Object.defineProperties( context, ({ Consumer: { get() { if (!hasWarnedAboutUsingConsumer) { console.error( 'Consumer pattern is not supported by ReactServerContext', ); hasWarnedAboutUsingConsumer = true; } return null; }, }, }: any), ); } ContextRegistry[globalName] = context; } return ContextRegistry[globalName]; }
29.910256
81
0.653112
owtf
import * as React from 'react'; import {use, Suspense, useState, startTransition} from 'react'; import ReactDOM from 'react-dom/client'; import {createFromFetch, encodeReply} from 'react-server-dom-webpack/client'; // TODO: This should be a dependency of the App but we haven't implemented CSS in Node yet. import './style.css'; let updateRoot; async function callServer(id, args) { const response = fetch('/', { method: 'POST', headers: { Accept: 'text/x-component', 'rsc-action': id, }, body: await encodeReply(args), }); const {returnValue, root} = await createFromFetch(response, {callServer}); // Refresh the tree with the new RSC payload. startTransition(() => { updateRoot(root); }); return returnValue; } function Shell({data}) { const [root, setRoot] = useState(data); updateRoot = setRoot; return root; } async function hydrateApp() { const {root, returnValue, formState} = await createFromFetch( fetch('/', { headers: { Accept: 'text/x-component', }, }), { callServer, } ); ReactDOM.hydrateRoot(document, <Shell data={root} />, { // TODO: This part doesn't actually work because the server only returns // form state during the request that submitted the form. Which means it // the state needs to be transported as part of the HTML stream. We intend // to add a feature to Fizz for this, but for now it's up to the // metaframework to implement correctly. formState: formState, }); } // Remove this line to simulate MPA behavior hydrateApp();
26.859649
91
0.666037
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React; let ReactDOMServer; describe('escapeTextForBrowser', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOMServer = require('react-dom/server'); }); it('ampersand is escaped when passed as text content', () => { const response = ReactDOMServer.renderToString(<span>{'&'}</span>); expect(response).toMatch('<span>&amp;</span>'); }); it('double quote is escaped when passed as text content', () => { const response = ReactDOMServer.renderToString(<span>{'"'}</span>); expect(response).toMatch('<span>&quot;</span>'); }); it('single quote is escaped when passed as text content', () => { const response = ReactDOMServer.renderToString(<span>{"'"}</span>); expect(response).toMatch('<span>&#x27;</span>'); }); it('greater than entity is escaped when passed as text content', () => { const response = ReactDOMServer.renderToString(<span>{'>'}</span>); expect(response).toMatch('<span>&gt;</span>'); }); it('lower than entity is escaped when passed as text content', () => { const response = ReactDOMServer.renderToString(<span>{'<'}</span>); expect(response).toMatch('<span>&lt;</span>'); }); it('number is correctly passed as text content', () => { const response = ReactDOMServer.renderToString(<span>{42}</span>); expect(response).toMatch('<span>42</span>'); }); it('number is escaped to string when passed as text content', () => { const response = ReactDOMServer.renderToString(<img data-attr={42} />); expect(response).toMatch('<img data-attr="42"/>'); }); it('escape text content representing a script tag', () => { const response = ReactDOMServer.renderToString( <span>{'<script type=\'\' src=""></script>'}</span>, ); expect(response).toMatch( '<span>&lt;script type=&#x27;&#x27; ' + 'src=&quot;&quot;&gt;&lt;/script&gt;</span>', ); }); });
31.328358
75
0.629561
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); 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=Example.js.map?foo=bar&param=some_value
45.641026
743
0.648515
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. * * @format * @flow strict-local */ 'use strict'; import {ReactNativeViewConfigRegistry} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import {type ViewConfig} from './ReactNativeTypes'; const {register} = ReactNativeViewConfigRegistry; /** * Creates a renderable ReactNative host component. * Use this method for view configs that are loaded from UIManager. * Use createReactNativeComponentClass() for view configs defined within JavaScript. * * @param {string} config iOS View configuration. * @private */ const createReactNativeComponentClass = function ( name: string, callback: () => ViewConfig, ): string { return register(name, callback); }; module.exports = createReactNativeComponentClass;
26.5
110
0.753747
Python-Penetration-Testing-Cookbook
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ListItem = ListItem; exports.List = List; var React = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ListItem({ item, removeItem, toggleItem }) { const handleDelete = (0, React.useCallback)(() => { removeItem(item); }, [item, removeItem]); const handleToggle = (0, React.useCallback)(() => { toggleItem(item); }, [item, toggleItem]); return /*#__PURE__*/React.createElement("li", { __source: { fileName: _jsxFileName, lineNumber: 23, columnNumber: 5 } }, /*#__PURE__*/React.createElement("button", { onClick: handleDelete, __source: { fileName: _jsxFileName, lineNumber: 24, columnNumber: 7 } }, "Delete"), /*#__PURE__*/React.createElement("label", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, /*#__PURE__*/React.createElement("input", { checked: item.isComplete, onChange: handleToggle, type: "checkbox", __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 9 } }), ' ', item.text)); } function List(props) { const [newItemText, setNewItemText] = (0, React.useState)(''); const [items, setItems] = (0, React.useState)([{ id: 1, isComplete: true, text: 'First' }, { id: 2, isComplete: true, text: 'Second' }, { id: 3, isComplete: false, text: 'Third' }]); const [uid, setUID] = (0, React.useState)(4); const handleClick = (0, React.useCallback)(() => { if (newItemText !== '') { setItems([...items, { id: uid, isComplete: false, text: newItemText }]); setUID(uid + 1); setNewItemText(''); } }, [newItemText, items, uid]); const handleKeyPress = (0, React.useCallback)(event => { if (event.key === 'Enter') { handleClick(); } }, [handleClick]); const handleChange = (0, React.useCallback)(event => { setNewItemText(event.currentTarget.value); }, [setNewItemText]); const removeItem = (0, React.useCallback)(itemToRemove => setItems(items.filter(item => item !== itemToRemove)), [items]); const toggleItem = (0, React.useCallback)(itemToToggle => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); setItems(items.slice(0, index).concat({ ...itemToToggle, isComplete: !itemToToggle.isComplete }).concat(items.slice(index + 1))); }, [items]); return /*#__PURE__*/React.createElement(React.Fragment, { __source: { fileName: _jsxFileName, lineNumber: 102, columnNumber: 5 } }, /*#__PURE__*/React.createElement("h1", { __source: { fileName: _jsxFileName, lineNumber: 103, columnNumber: 7 } }, "List"), /*#__PURE__*/React.createElement("input", { type: "text", placeholder: "New list item...", value: newItemText, onChange: handleChange, onKeyPress: handleKeyPress, __source: { fileName: _jsxFileName, lineNumber: 104, columnNumber: 7 } }), /*#__PURE__*/React.createElement("button", { disabled: newItemText === '', onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 111, columnNumber: 7 } }, /*#__PURE__*/React.createElement("span", { role: "img", "aria-label": "Add item", __source: { fileName: _jsxFileName, lineNumber: 112, columnNumber: 9 } }, "Add")), /*#__PURE__*/React.createElement("ul", { __source: { fileName: _jsxFileName, lineNumber: 116, columnNumber: 7 } }, items.map(item => /*#__PURE__*/React.createElement(ListItem, { key: item.id, item: item, removeItem: removeItem, toggleItem: toggleItem, __source: { fileName: _jsxFileName, lineNumber: 118, columnNumber: 11 } })))); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlRvRG9MaXN0LmpzIl0sIm5hbWVzIjpbIkxpc3RJdGVtIiwiaXRlbSIsInJlbW92ZUl0ZW0iLCJ0b2dnbGVJdGVtIiwiaGFuZGxlRGVsZXRlIiwiaGFuZGxlVG9nZ2xlIiwiaXNDb21wbGV0ZSIsInRleHQiLCJMaXN0IiwicHJvcHMiLCJuZXdJdGVtVGV4dCIsInNldE5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJzZXRJdGVtcyIsImlkIiwidWlkIiwic2V0VUlEIiwiaGFuZGxlQ2xpY2siLCJoYW5kbGVLZXlQcmVzcyIsImV2ZW50Iiwia2V5IiwiaGFuZGxlQ2hhbmdlIiwiY3VycmVudFRhcmdldCIsInZhbHVlIiwiaXRlbVRvUmVtb3ZlIiwiZmlsdGVyIiwiaXRlbVRvVG9nZ2xlIiwiaW5kZXgiLCJmaW5kSW5kZXgiLCJzbGljZSIsImNvbmNhdCIsIm1hcCJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7QUFTQTs7Ozs7Ozs7QUFHTyxTQUFTQSxRQUFULENBQWtCO0FBQUNDLEVBQUFBLElBQUQ7QUFBT0MsRUFBQUEsVUFBUDtBQUFtQkMsRUFBQUE7QUFBbkIsQ0FBbEIsRUFBa0Q7QUFDdkQsUUFBTUMsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0QsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPQyxVQUFQLENBRmtCLENBQXJCO0FBSUEsUUFBTUcsWUFBWSxHQUFHLHVCQUFZLE1BQU07QUFDckNGLElBQUFBLFVBQVUsQ0FBQ0YsSUFBRCxDQUFWO0FBQ0QsR0FGb0IsRUFFbEIsQ0FBQ0EsSUFBRCxFQUFPRSxVQUFQLENBRmtCLENBQXJCO0FBSUEsc0JBQ0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsa0JBQ0U7QUFBUSxJQUFBLE9BQU8sRUFBRUMsWUFBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQ0UsSUFBQSxPQUFPLEVBQUVILElBQUksQ0FBQ0ssVUFEaEI7QUFFRSxJQUFBLFFBQVEsRUFBRUQsWUFGWjtBQUdFLElBQUEsSUFBSSxFQUFDLFVBSFA7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsSUFERixFQUtLLEdBTEwsRUFNR0osSUFBSSxDQUFDTSxJQU5SLENBRkYsQ0FERjtBQWFEOztBQUVNLFNBQVNDLElBQVQsQ0FBY0MsS0FBZCxFQUFxQjtBQUMxQixRQUFNLENBQUNDLFdBQUQsRUFBY0MsY0FBZCxJQUFnQyxvQkFBUyxFQUFULENBQXRDO0FBQ0EsUUFBTSxDQUFDQyxLQUFELEVBQVFDLFFBQVIsSUFBb0Isb0JBQVMsQ0FDakM7QUFBQ0MsSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FEaUMsRUFFakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLElBQXBCO0FBQTBCQyxJQUFBQSxJQUFJLEVBQUU7QUFBaEMsR0FGaUMsRUFHakM7QUFBQ08sSUFBQUEsRUFBRSxFQUFFLENBQUw7QUFBUVIsSUFBQUEsVUFBVSxFQUFFLEtBQXBCO0FBQTJCQyxJQUFBQSxJQUFJLEVBQUU7QUFBakMsR0FIaUMsQ0FBVCxDQUExQjtBQUtBLFFBQU0sQ0FBQ1EsR0FBRCxFQUFNQyxNQUFOLElBQWdCLG9CQUFTLENBQVQsQ0FBdEI7QUFFQSxRQUFNQyxXQUFXLEdBQUcsdUJBQVksTUFBTTtBQUNwQyxRQUFJUCxXQUFXLEtBQUssRUFBcEIsRUFBd0I7QUFDdEJHLE1BQUFBLFFBQVEsQ0FBQyxDQUNQLEdBQUdELEtBREksRUFFUDtBQUNFRSxRQUFBQSxFQUFFLEVBQUVDLEdBRE47QUFFRVQsUUFBQUEsVUFBVSxFQUFFLEtBRmQ7QUFHRUMsUUFBQUEsSUFBSSxFQUFFRztBQUhSLE9BRk8sQ0FBRCxDQUFSO0FBUUFNLE1BQUFBLE1BQU0sQ0FBQ0QsR0FBRyxHQUFHLENBQVAsQ0FBTjtBQUNBSixNQUFBQSxjQUFjLENBQUMsRUFBRCxDQUFkO0FBQ0Q7QUFDRixHQWJtQixFQWFqQixDQUFDRCxXQUFELEVBQWNFLEtBQWQsRUFBcUJHLEdBQXJCLENBYmlCLENBQXBCO0FBZUEsUUFBTUcsY0FBYyxHQUFHLHVCQUNyQkMsS0FBSyxJQUFJO0FBQ1AsUUFBSUEsS0FBSyxDQUFDQyxHQUFOLEtBQWMsT0FBbEIsRUFBMkI7QUFDekJILE1BQUFBLFdBQVc7QUFDWjtBQUNGLEdBTG9CLEVBTXJCLENBQUNBLFdBQUQsQ0FOcUIsQ0FBdkI7QUFTQSxRQUFNSSxZQUFZLEdBQUcsdUJBQ25CRixLQUFLLElBQUk7QUFDUFIsSUFBQUEsY0FBYyxDQUFDUSxLQUFLLENBQUNHLGFBQU4sQ0FBb0JDLEtBQXJCLENBQWQ7QUFDRCxHQUhrQixFQUluQixDQUFDWixjQUFELENBSm1CLENBQXJCO0FBT0EsUUFBTVQsVUFBVSxHQUFHLHVCQUNqQnNCLFlBQVksSUFBSVgsUUFBUSxDQUFDRCxLQUFLLENBQUNhLE1BQU4sQ0FBYXhCLElBQUksSUFBSUEsSUFBSSxLQUFLdUIsWUFBOUIsQ0FBRCxDQURQLEVBRWpCLENBQUNaLEtBQUQsQ0FGaUIsQ0FBbkI7QUFLQSxRQUFNVCxVQUFVLEdBQUcsdUJBQ2pCdUIsWUFBWSxJQUFJO0FBQ2Q7QUFDQTtBQUNBLFVBQU1DLEtBQUssR0FBR2YsS0FBSyxDQUFDZ0IsU0FBTixDQUFnQjNCLElBQUksSUFBSUEsSUFBSSxDQUFDYSxFQUFMLEtBQVlZLFlBQVksQ0FBQ1osRUFBakQsQ0FBZDtBQUVBRCxJQUFBQSxRQUFRLENBQ05ELEtBQUssQ0FDRmlCLEtBREgsQ0FDUyxDQURULEVBQ1lGLEtBRFosRUFFR0csTUFGSCxDQUVVLEVBQ04sR0FBR0osWUFERztBQUVOcEIsTUFBQUEsVUFBVSxFQUFFLENBQUNvQixZQUFZLENBQUNwQjtBQUZwQixLQUZWLEVBTUd3QixNQU5ILENBTVVsQixLQUFLLENBQUNpQixLQUFOLENBQVlGLEtBQUssR0FBRyxDQUFwQixDQU5WLENBRE0sQ0FBUjtBQVNELEdBZmdCLEVBZ0JqQixDQUFDZixLQUFELENBaEJpQixDQUFuQjtBQW1CQSxzQkFDRSxvQkFBQyxjQUFEO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGtCQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLFlBREYsZUFFRTtBQUNFLElBQUEsSUFBSSxFQUFDLE1BRFA7QUFFRSxJQUFBLFdBQVcsRUFBQyxrQkFGZDtBQUdFLElBQUEsS0FBSyxFQUFFRixXQUhUO0FBSUUsSUFBQSxRQUFRLEVBQUVXLFlBSlo7QUFLRSxJQUFBLFVBQVUsRUFBRUgsY0FMZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQUZGLGVBU0U7QUFBUSxJQUFBLFFBQVEsRUFBRVIsV0FBVyxLQUFLLEVBQWxDO0FBQXNDLElBQUEsT0FBTyxFQUFFTyxXQUEvQztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxrQkFDRTtBQUFNLElBQUEsSUFBSSxFQUFDLEtBQVg7QUFBaUIsa0JBQVcsVUFBNUI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsV0FERixDQVRGLGVBY0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDR0wsS0FBSyxDQUFDbUIsR0FBTixDQUFVOUIsSUFBSSxpQkFDYixvQkFBQyxRQUFEO0FBQ0UsSUFBQSxHQUFHLEVBQUVBLElBQUksQ0FBQ2EsRUFEWjtBQUVFLElBQUEsSUFBSSxFQUFFYixJQUZSO0FBR0UsSUFBQSxVQUFVLEVBQUVDLFVBSGQ7QUFJRSxJQUFBLFVBQVUsRUFBRUMsVUFKZDtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxJQURELENBREgsQ0FkRixDQURGO0FBMkJEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCAqIGFzIFJlYWN0IGZyb20gJ3JlYWN0JztcbmltcG9ydCB7RnJhZ21lbnQsIHVzZUNhbGxiYWNrLCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gTGlzdEl0ZW0oe2l0ZW0sIHJlbW92ZUl0ZW0sIHRvZ2dsZUl0ZW19KSB7XG4gIGNvbnN0IGhhbmRsZURlbGV0ZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICByZW1vdmVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgcmVtb3ZlSXRlbV0pO1xuXG4gIGNvbnN0IGhhbmRsZVRvZ2dsZSA9IHVzZUNhbGxiYWNrKCgpID0+IHtcbiAgICB0b2dnbGVJdGVtKGl0ZW0pO1xuICB9LCBbaXRlbSwgdG9nZ2xlSXRlbV0pO1xuXG4gIHJldHVybiAoXG4gICAgPGxpPlxuICAgICAgPGJ1dHRvbiBvbkNsaWNrPXtoYW5kbGVEZWxldGV9PkRlbGV0ZTwvYnV0dG9uPlxuICAgICAgPGxhYmVsPlxuICAgICAgICA8aW5wdXRcbiAgICAgICAgICBjaGVja2VkPXtpdGVtLmlzQ29tcGxldGV9XG4gICAgICAgICAgb25DaGFuZ2U9e2hhbmRsZVRvZ2dsZX1cbiAgICAgICAgICB0eXBlPVwiY2hlY2tib3hcIlxuICAgICAgICAvPnsnICd9XG4gICAgICAgIHtpdGVtLnRleHR9XG4gICAgICA8L2xhYmVsPlxuICAgIDwvbGk+XG4gICk7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBMaXN0KHByb3BzKSB7XG4gIGNvbnN0IFtuZXdJdGVtVGV4dCwgc2V0TmV3SXRlbVRleHRdID0gdXNlU3RhdGUoJycpO1xuICBjb25zdCBbaXRlbXMsIHNldEl0ZW1zXSA9IHVzZVN0YXRlKFtcbiAgICB7aWQ6IDEsIGlzQ29tcGxldGU6IHRydWUsIHRleHQ6ICdGaXJzdCd9LFxuICAgIHtpZDogMiwgaXNDb21wbGV0ZTogdHJ1ZSwgdGV4dDogJ1NlY29uZCd9LFxuICAgIHtpZDogMywgaXNDb21wbGV0ZTogZmFsc2UsIHRleHQ6ICdUaGlyZCd9LFxuICBdKTtcbiAgY29uc3QgW3VpZCwgc2V0VUlEXSA9IHVzZVN0YXRlKDQpO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gdXNlQ2FsbGJhY2soKCkgPT4ge1xuICAgIGlmIChuZXdJdGVtVGV4dCAhPT0gJycpIHtcbiAgICAgIHNldEl0ZW1zKFtcbiAgICAgICAgLi4uaXRlbXMsXG4gICAgICAgIHtcbiAgICAgICAgICBpZDogdWlkLFxuICAgICAgICAgIGlzQ29tcGxldGU6IGZhbHNlLFxuICAgICAgICAgIHRleHQ6IG5ld0l0ZW1UZXh0LFxuICAgICAgICB9LFxuICAgICAgXSk7XG4gICAgICBzZXRVSUQodWlkICsgMSk7XG4gICAgICBzZXROZXdJdGVtVGV4dCgnJyk7XG4gICAgfVxuICB9LCBbbmV3SXRlbVRleHQsIGl0ZW1zLCB1aWRdKTtcblxuICBjb25zdCBoYW5kbGVLZXlQcmVzcyA9IHVzZUNhbGxiYWNrKFxuICAgIGV2ZW50ID0+IHtcbiAgICAgIGlmIChldmVudC5rZXkgPT09ICdFbnRlcicpIHtcbiAgICAgICAgaGFuZGxlQ2xpY2soKTtcbiAgICAgIH1cbiAgICB9LFxuICAgIFtoYW5kbGVDbGlja10sXG4gICk7XG5cbiAgY29uc3QgaGFuZGxlQ2hhbmdlID0gdXNlQ2FsbGJhY2soXG4gICAgZXZlbnQgPT4ge1xuICAgICAgc2V0TmV3SXRlbVRleHQoZXZlbnQuY3VycmVudFRhcmdldC52YWx1ZSk7XG4gICAgfSxcbiAgICBbc2V0TmV3SXRlbVRleHRdLFxuICApO1xuXG4gIGNvbnN0IHJlbW92ZUl0ZW0gPSB1c2VDYWxsYmFjayhcbiAgICBpdGVtVG9SZW1vdmUgPT4gc2V0SXRlbXMoaXRlbXMuZmlsdGVyKGl0ZW0gPT4gaXRlbSAhPT0gaXRlbVRvUmVtb3ZlKSksXG4gICAgW2l0ZW1zXSxcbiAgKTtcblxuICBjb25zdCB0b2dnbGVJdGVtID0gdXNlQ2FsbGJhY2soXG4gICAgaXRlbVRvVG9nZ2xlID0+IHtcbiAgICAgIC8vIERvbnQgdXNlIGluZGV4T2YoKVxuICAgICAgLy8gYmVjYXVzZSBlZGl0aW5nIHByb3BzIGluIERldlRvb2xzIGNyZWF0ZXMgYSBuZXcgT2JqZWN0LlxuICAgICAgY29uc3QgaW5kZXggPSBpdGVtcy5maW5kSW5kZXgoaXRlbSA9PiBpdGVtLmlkID09PSBpdGVtVG9Ub2dnbGUuaWQpO1xuXG4gICAgICBzZXRJdGVtcyhcbiAgICAgICAgaXRlbXNcbiAgICAgICAgICAuc2xpY2UoMCwgaW5kZXgpXG4gICAgICAgICAgLmNvbmNhdCh7XG4gICAgICAgICAgICAuLi5pdGVtVG9Ub2dnbGUsXG4gICAgICAgICAgICBpc0NvbXBsZXRlOiAhaXRlbVRvVG9nZ2xlLmlzQ29tcGxldGUsXG4gICAgICAgICAgfSlcbiAgICAgICAgICAuY29uY2F0KGl0ZW1zLnNsaWNlKGluZGV4ICsgMSkpLFxuICAgICAgKTtcbiAgICB9LFxuICAgIFtpdGVtc10sXG4gICk7XG5cbiAgcmV0dXJuIChcbiAgICA8RnJhZ21lbnQ+XG4gICAgICA8aDE+TGlzdDwvaDE+XG4gICAgICA8aW5wdXRcbiAgICAgICAgdHlwZT1cInRleHRcIlxuICAgICAgICBwbGFjZWhvbGRlcj1cIk5ldyBsaXN0IGl0ZW0uLi5cIlxuICAgICAgICB2YWx1ZT17bmV3SXRlbVRleHR9XG4gICAgICAgIG9uQ2hhbmdlPXtoYW5kbGVDaGFuZ2V9XG4gICAgICAgIG9uS2V5UHJlc3M9e2hhbmRsZUtleVByZXNzfVxuICAgICAgLz5cbiAgICAgIDxidXR0b24gZGlzYWJsZWQ9e25ld0l0ZW1UZXh0ID09PSAnJ30gb25DbGljaz17aGFuZGxlQ2xpY2t9PlxuICAgICAgICA8c3BhbiByb2xlPVwiaW1nXCIgYXJpYS1sYWJlbD1cIkFkZCBpdGVtXCI+XG4gICAgICAgICAgQWRkXG4gICAgICAgIDwvc3Bhbj5cbiAgICAgIDwvYnV0dG9uPlxuICAgICAgPHVsPlxuICAgICAgICB7aXRlbXMubWFwKGl0ZW0gPT4gKFxuICAgICAgICAgIDxMaXN0SXRlbVxuICAgICAgICAgICAga2V5PXtpdGVtLmlkfVxuICAgICAgICAgICAgaXRlbT17aXRlbX1cbiAgICAgICAgICAgIHJlbW92ZUl0ZW09e3JlbW92ZUl0ZW19XG4gICAgICAgICAgICB0b2dnbGVJdGVtPXt0b2dnbGVJdGVtfVxuICAgICAgICAgIC8+XG4gICAgICAgICkpfVxuICAgICAgPC91bD5cbiAgICA8L0ZyYWdtZW50PlxuICApO1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiIsImhhbmRsZURlbGV0ZSIsImhhbmRsZVRvZ2dsZSIsIm5ld0l0ZW1UZXh0IiwiaXRlbXMiLCJ1aWQiLCJoYW5kbGVDbGljayIsImhhbmRsZUtleVByZXNzIiwiaGFuZGxlQ2hhbmdlIiwicmVtb3ZlSXRlbSIsInRvZ2dsZUl0ZW0iXSwibWFwcGluZ3MiOiJDQUFEO2N1QkNBO2dCQ0RBO2tCREVBO29CQ0ZBO3NDZ0JHQSxBWUhBO3VDeEJJQTsyQ3hCSkE7NENvQktBLEFXTEE7OENiTUE7MkRTTkE7NkROT0E7b0V0QlBBO3NFb0JRQTsyRXBCUkE7NkVrQlNBO2dGbEJUQTtrRmtCVUE7bUdsQlZBIn1dXX19XX0=
88.19375
9,304
0.859706
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 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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5LmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50U3RhdGUiLCJjb3VudCIsInNldENvdW50IiwiZGFya01vZGUiLCJ1c2VJc0RhcmtNb2RlIiwiaXNEYXJrTW9kZSIsImhhbmRsZUNsaWNrIiwiZGFya01vZGVTdGF0ZSIsInVzZUVmZmVjdENyZWF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVBLFNBQUFBLFNBQUEsR0FBQTtBQUNBLFFBQUFDLFVBQUEsR0FBQSxxQkFBQSxDQUFBLENBQUE7QUFDQSxRQUFBQyxLQUFBLEdBQUFELFVBQUEsQ0FBQSxDQUFBLENBQUE7QUFDQSxRQUFBRSxRQUFBLEdBQUFGLFVBQUEsQ0FBQSxDQUFBLENBQUE7QUFFQSxRQUFBRyxRQUFBLEdBQUFDLGFBQUEsRUFBQTtBQUNBLFFBQUEsQ0FBQUMsVUFBQSxJQUFBRixRQUFBO0FBRUEsd0JBQUEsTUFBQSxDQUNBO0FBQ0EsR0FGQSxFQUVBLEVBRkE7O0FBSUEsUUFBQUcsV0FBQSxHQUFBLE1BQUFKLFFBQUEsQ0FBQUQsS0FBQSxHQUFBLENBQUEsQ0FBQTs7QUFFQSxzQkFDQSx5RUFDQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFBQUksVUFBQSxDQURBLGVBRUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQUFKLEtBQUEsQ0FGQSxlQUdBO0FBQUEsSUFBQSxPQUFBLEVBQUFLLFdBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsb0JBSEEsQ0FEQTtBQU9BOztBQUVBLFNBQUFGLGFBQUEsR0FBQTtBQUNBLFFBQUFHLGFBQUEsR0FBQSxxQkFBQSxLQUFBLENBQUE7QUFDQSxRQUFBLENBQUFGLFVBQUEsSUFBQUUsYUFBQTtBQUVBLHdCQUFBLFNBQUFDLGVBQUEsR0FBQSxDQUNBO0FBQ0EsR0FGQSxFQUVBLEVBRkE7QUFJQSxTQUFBLENBQUFILFVBQUEsRUFBQSxNQUFBLENBQUEsQ0FBQSxDQUFBO0FBQ0EiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlRWZmZWN0LCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBjb3VudFN0YXRlID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGNvdW50ID0gY291bnRTdGF0ZVswXTtcbiAgY29uc3Qgc2V0Q291bnQgPSBjb3VudFN0YXRlWzFdO1xuXG4gIGNvbnN0IGRhcmtNb2RlID0gdXNlSXNEYXJrTW9kZSgpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZTtcblxuICB1c2VFZmZlY3QoKCkgPT4ge1xuICAgIC8vIC4uLlxuICB9LCBbXSk7XG5cbiAgY29uc3QgaGFuZGxlQ2xpY2sgPSAoKSA9PiBzZXRDb3VudChjb3VudCArIDEpO1xuXG4gIHJldHVybiAoXG4gICAgPD5cbiAgICAgIDxkaXY+RGFyayBtb2RlPyB7aXNEYXJrTW9kZX08L2Rpdj5cbiAgICAgIDxkaXY+Q291bnQ6IHtjb3VudH08L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBkYXJrTW9kZVN0YXRlID0gdXNlU3RhdGUoZmFsc2UpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZVN0YXRlO1xuXG4gIHVzZUVmZmVjdChmdW5jdGlvbiB1c2VFZmZlY3RDcmVhdGUoKSB7XG4gICAgLy8gSGVyZSBpcyB3aGVyZSB3ZSBtYXkgbGlzdGVuIHRvIGEgXCJ0aGVtZVwiIGV2ZW50Li4uXG4gIH0sIFtdKTtcblxuICByZXR1cm4gW2lzRGFya01vZGUsICgpID0+IHt9XTtcbn1cbiJdfQ==
88.428571
2,676
0.831835
null
(function () { 'use strict'; var ReactImage0 = function (props) { if (props.x === 0) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (props.x === 15) { return React.createElement('i', { className: '_3ut_ img sp_i534r85sjIn sx_e8ac93', src: null, alt: '', }); } if (props.x === 22) { return React.createElement('i', { alt: '', className: '_3-8_ img sp_i534r85sjIn sx_7b15bc', src: null, }); } if (props.x === 29) { return React.createElement('i', { className: '_1m1s _4540 _p img sp_i534r85sjIn sx_f40b1c', src: null, alt: '', }); } if (props.x === 42) { return React.createElement( 'i', { alt: 'Warning', className: '_585p img sp_i534r85sjIn sx_20273d', src: null, }, React.createElement('u', null, 'Warning') ); } if (props.x === 67) { return React.createElement('i', { alt: '', className: '_3-8_ img sp_i534r85sjIn sx_b5d079', src: null, }); } if (props.x === 70) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_29f8c9', }); } if (props.x === 76) { return React.createElement('i', { alt: '', className: '_3-8_ img sp_i534r85sjIn sx_ef6a9c', src: null, }); } if (props.x === 79) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_6f8c43', }); } if (props.x === 88) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_e94a2d', }); } if (props.x === 91) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_7ed7d4', }); } if (props.x === 94) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_930440', }); } if (props.x === 98) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_750c83', }); } if (props.x === 108) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_73c1bb', }); } if (props.x === 111) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_29f28d', }); } if (props.x === 126) { return React.createElement('i', { src: null, alt: '', className: '_3-8_ img sp_i534r85sjIn sx_91c59e', }); } if (props.x === 127) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (props.x === 134) { return React.createElement('i', { src: null, alt: '', className: '_3-8_ img sp_i534r85sjIn sx_c8eb75', }); } if (props.x === 135) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (props.x === 148) { return React.createElement('i', { className: '_3yz6 _5whs img sp_i534r85sjIn sx_896996', src: null, alt: '', }); } if (props.x === 152) { return React.createElement('i', { className: '_5b5p _4gem img sp_i534r85sjIn sx_896996', src: null, alt: '', }); } if (props.x === 153) { return React.createElement('i', { className: '_541d img sp_i534r85sjIn sx_2f396a', src: null, alt: '', }); } if (props.x === 160) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_31d9b0', }); } if (props.x === 177) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_2c18b7', src: null, }); } if (props.x === 186) { return React.createElement('i', { src: null, alt: '', className: 'img sp_i534r85sjIn sx_0a681f', }); } if (props.x === 195) { return React.createElement('i', { className: '_1-lx img sp_OkER5ktbEyg sx_b369b4', src: null, alt: '', }); } if (props.x === 198) { return React.createElement('i', { className: '_1-lx img sp_i534r85sjIn sx_96948e', src: null, alt: '', }); } if (props.x === 237) { return React.createElement('i', { className: '_541d img sp_i534r85sjIn sx_2f396a', src: null, alt: '', }); } if (props.x === 266) { return React.createElement('i', { alt: '', className: '_3-99 img sp_i534r85sjIn sx_538591', src: null, }); } if (props.x === 314) { return React.createElement('i', { className: '_1cie _1cif img sp_i534r85sjIn sx_6e6820', src: null, alt: '', }); } if (props.x === 345) { return React.createElement('i', { className: '_1cie img sp_i534r85sjIn sx_e896cf', src: null, alt: '', }); } if (props.x === 351) { return React.createElement('i', { className: '_1cie img sp_i534r85sjIn sx_38fed8', src: null, alt: '', }); } }; var AbstractLink1 = function (props) { if (props.x === 1) { return React.createElement( 'a', { className: '_387r _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft', style: {width: 250, maxWidth: '250px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '236px'}}, null, React.createElement( 'span', null, React.createElement('span', {className: '_48u-'}, 'Account:'), ' ', 'Dick Madanson (10149999073643408)' ) ), React.createElement(ReactImage0, {x: 0}) ); } if (props.x === 43) { return React.createElement( 'a', { className: '_585q _50zy _50-0 _50z- _5upp _42ft', size: 'medium', type: null, title: 'Remove', 'data-hover': undefined, 'data-tooltip-alignh': undefined, 'data-tooltip-content': undefined, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, undefined, 'Remove', undefined ); } if (props.x === 49) { return React.createElement( 'a', { target: '_blank', href: '/ads/manage/billing.php?act=10149999073643408', rel: undefined, onClick: function () {}, }, React.createElement(XUIText29, {x: 48}) ); } if (props.x === 128) { return React.createElement( 'a', { className: ' _5bbf _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft', style: {maxWidth: '200px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '186px'}}, React.createElement(ReactImage0, {x: 126}), 'Search' ), React.createElement(ReactImage0, {x: 127}) ); } if (props.x === 136) { return React.createElement( 'a', { className: ' _5bbf _55pi _2agf _4jy0 _4jy4 _517h _51sy _42ft', style: {maxWidth: '200px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '186px'}}, React.createElement(ReactImage0, {x: 134}), 'Filters' ), React.createElement(ReactImage0, {x: 135}) ); } if (props.x === 178) { return React.createElement( 'a', { className: '_1_-t _1_-v _42ft', disabled: null, height: 'medium', role: 'button', label: null, href: '#', rel: undefined, onClick: function () {}, }, undefined, 'Lifetime', React.createElement(ReactImage0, {x: 177}) ); } if (props.x === 207) { return React.createElement( 'a', {href: '#', rel: undefined, onClick: function () {}}, 'Create Ad Set' ); } if (props.x === 209) { return React.createElement( 'a', {href: '#', rel: undefined, onClick: function () {}}, 'View Ad Set' ); } if (props.x === 241) { return React.createElement( 'a', {href: '#', rel: undefined, onClick: function () {}}, 'Set a Limit' ); } if (props.x === 267) { return React.createElement( 'a', { className: '_p _55pi _2agf _4jy0 _4jy3 _517h _51sy _42ft', style: {maxWidth: '200px'}, disabled: null, label: null, href: '#', rel: undefined, onClick: function () {}, }, null, React.createElement( 'span', {className: '_55pe', style: {maxWidth: '186px'}}, null, 'Links' ), React.createElement(ReactImage0, {x: 266}) ); } }; var Link2 = function (props) { if (props.x === 2) { return React.createElement(AbstractLink1, {x: 1}); } if (props.x === 44) { return React.createElement(AbstractLink1, {x: 43}); } if (props.x === 50) { return React.createElement(AbstractLink1, {x: 49}); } if (props.x === 129) { return React.createElement(AbstractLink1, {x: 128}); } if (props.x === 137) { return React.createElement(AbstractLink1, {x: 136}); } if (props.x === 179) { return React.createElement(AbstractLink1, {x: 178}); } if (props.x === 208) { return React.createElement(AbstractLink1, {x: 207}); } if (props.x === 210) { return React.createElement(AbstractLink1, {x: 209}); } if (props.x === 242) { return React.createElement(AbstractLink1, {x: 241}); } if (props.x === 268) { return React.createElement(AbstractLink1, {x: 267}); } }; var AbstractButton3 = function (props) { if (props.x === 3) { return React.createElement(Link2, {x: 2}); } if (props.x === 20) { return React.createElement( 'button', { className: '_5n7z _4jy0 _4jy4 _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, 'Discard Changes', undefined ); } if (props.x === 23) { return React.createElement( 'button', { className: '_5n7z _2yak _4lj- _4jy0 _4jy4 _517h _51sy _42ft _42fr', disabled: true, onClick: function () {}, 'data-tooltip-content': 'You have no changes to publish', 'data-hover': 'tooltip', label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 22}), 'Review Changes', undefined ); } if (props.x === 45) { return React.createElement(Link2, {x: 44}); } if (props.x === 68) { return React.createElement( 'button', { className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 67}), 'Create Campaign', undefined ); } if (props.x === 71) { return React.createElement( 'button', { className: '_u_k _3qx6 _p _4jy0 _4jy4 _517h _51sy _42ft', label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 70}), undefined, undefined ); } if (props.x === 77) { return React.createElement( 'button', { 'aria-label': 'Edit', 'data-tooltip-content': 'Edit Campaigns (Ctrl+U)', 'data-hover': 'tooltip', className: '_d2_ _u_k noMargin _4jy0 _4jy4 _517h _51sy _42ft', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 76}), 'Edit', undefined ); } if (props.x === 80) { return React.createElement( 'button', { className: '_u_k _3qx6 _p _4jy0 _4jy4 _517h _51sy _42ft', disabled: false, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 79}), undefined, undefined ); } if (props.x === 89) { return React.createElement( 'button', { 'aria-label': 'Revert', className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft _42fr', 'data-hover': 'tooltip', 'data-tooltip-content': 'Revert', disabled: true, onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 88}), undefined, undefined ); } if (props.x === 92) { return React.createElement( 'button', { 'aria-label': 'Delete', className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Delete', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 91}), undefined, undefined ); } if (props.x === 95) { return React.createElement( 'button', { 'aria-label': 'Duplicate', className: '_u_k _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Duplicate', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 94}), undefined, undefined ); } if (props.x === 99) { return React.createElement( 'button', { 'aria-label': 'Export & Import', className: '_u_k noMargin _p _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Export & Import', onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 98}), undefined, undefined ); } if (props.x === 109) { return React.createElement( 'button', { 'aria-label': 'Create Report', className: '_u_k _5n7z _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Create Report', disabled: false, style: {boxSizing: 'border-box', height: '28px', width: '48px'}, onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 108}), undefined, undefined ); } if (props.x === 112) { return React.createElement( 'button', { 'aria-label': 'Campaign Tags', className: ' _5uy7 _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'Campaign Tags', disabled: false, onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 111}), undefined, undefined ); } if (props.x === 130) { return React.createElement(Link2, {x: 129}); } if (props.x === 138) { return React.createElement(Link2, {x: 137}); } if (props.x === 149) { return React.createElement( 'button', { className: '_3yz9 _1t-2 _50z- _50zy _50zz _50z- _5upp _42ft', size: 'small', onClick: function () {}, type: 'button', title: 'Remove', 'data-hover': undefined, 'data-tooltip-alignh': undefined, 'data-tooltip-content': undefined, label: null, }, undefined, 'Remove', undefined ); } if (props.x === 156) { return React.createElement( 'button', { className: '_5b5u _5b5v _4jy0 _4jy3 _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, 'Apply', undefined ); } if (props.x === 161) { return React.createElement( 'button', { className: '_1wdf _4jy0 _517i _517h _51sy _42ft', onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 160}), undefined, undefined ); } if (props.x === 180) { return React.createElement(Link2, {x: 179}); } if (props.x === 187) { return React.createElement( 'button', { 'aria-label': 'List Settings', className: '_u_k _3c5o _1-r0 _4jy0 _4jy4 _517h _51sy _42ft', 'data-hover': 'tooltip', 'data-tooltip-content': 'List Settings', onClick: function () {}, label: null, type: 'submit', value: '1', }, React.createElement(ReactImage0, {x: 186}), undefined, undefined ); } if (props.x === 269) { return React.createElement(Link2, {x: 268}); } if (props.x === 303) { return React.createElement( 'button', { className: '_tm3 _tm6 _tm7 _4jy0 _4jy6 _517h _51sy _42ft', 'data-tooltip-position': 'right', 'data-tooltip-content': 'Campaigns', 'data-hover': 'tooltip', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, React.createElement( 'div', null, React.createElement('div', {className: '_tma'}), React.createElement('div', {className: '_tm8'}), React.createElement('div', {className: '_tm9'}, 1) ), undefined ); } if (props.x === 305) { return React.createElement( 'button', { className: '_tm4 _tm6 _4jy0 _4jy6 _517h _51sy _42ft', 'data-tooltip-position': 'right', 'data-tooltip-content': 'Ad Sets', 'data-hover': 'tooltip', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, React.createElement( 'div', null, React.createElement('div', {className: '_tma'}), React.createElement('div', {className: '_tm8'}), React.createElement('div', {className: '_tm9'}, 1) ), undefined ); } if (props.x === 307) { return React.createElement( 'button', { className: '_tm5 _tm6 _4jy0 _4jy6 _517h _51sy _42ft', 'data-tooltip-position': 'right', 'data-tooltip-content': 'Ads', 'data-hover': 'tooltip', onClick: function () {}, label: null, type: 'submit', value: '1', }, undefined, React.createElement( 'div', null, React.createElement('div', {className: '_tma'}), React.createElement('div', {className: '_tm8'}), React.createElement('div', {className: '_tm9'}, 1) ), undefined ); } }; var XUIButton4 = function (props) { if (props.x === 4) { return React.createElement(AbstractButton3, {x: 3}); } if (props.x === 21) { return React.createElement(AbstractButton3, {x: 20}); } if (props.x === 24) { return React.createElement(AbstractButton3, {x: 23}); } if (props.x === 69) { return React.createElement(AbstractButton3, {x: 68}); } if (props.x === 72) { return React.createElement(AbstractButton3, {x: 71}); } if (props.x === 78) { return React.createElement(AbstractButton3, {x: 77}); } if (props.x === 81) { return React.createElement(AbstractButton3, {x: 80}); } if (props.x === 90) { return React.createElement(AbstractButton3, {x: 89}); } if (props.x === 93) { return React.createElement(AbstractButton3, {x: 92}); } if (props.x === 96) { return React.createElement(AbstractButton3, {x: 95}); } if (props.x === 100) { return React.createElement(AbstractButton3, {x: 99}); } if (props.x === 110) { return React.createElement(AbstractButton3, {x: 109}); } if (props.x === 113) { return React.createElement(AbstractButton3, {x: 112}); } if (props.x === 131) { return React.createElement(AbstractButton3, {x: 130}); } if (props.x === 139) { return React.createElement(AbstractButton3, {x: 138}); } if (props.x === 157) { return React.createElement(AbstractButton3, {x: 156}); } if (props.x === 162) { return React.createElement(AbstractButton3, {x: 161}); } if (props.x === 188) { return React.createElement(AbstractButton3, {x: 187}); } if (props.x === 270) { return React.createElement(AbstractButton3, {x: 269}); } if (props.x === 304) { return React.createElement(AbstractButton3, {x: 303}); } if (props.x === 306) { return React.createElement(AbstractButton3, {x: 305}); } if (props.x === 308) { return React.createElement(AbstractButton3, {x: 307}); } }; var AbstractPopoverButton5 = function (props) { if (props.x === 5) { return React.createElement(XUIButton4, {x: 4}); } if (props.x === 132) { return React.createElement(XUIButton4, {x: 131}); } if (props.x === 140) { return React.createElement(XUIButton4, {x: 139}); } if (props.x === 271) { return React.createElement(XUIButton4, {x: 270}); } }; var ReactXUIPopoverButton6 = function (props) { if (props.x === 6) { return React.createElement(AbstractPopoverButton5, {x: 5}); } if (props.x === 133) { return React.createElement(AbstractPopoverButton5, {x: 132}); } if (props.x === 141) { return React.createElement(AbstractPopoverButton5, {x: 140}); } if (props.x === 272) { return React.createElement(AbstractPopoverButton5, {x: 271}); } }; var BIGAdAccountSelector7 = function (props) { if (props.x === 7) { return React.createElement( 'div', null, React.createElement(ReactXUIPopoverButton6, {x: 6}), null ); } }; var FluxContainer_AdsPEBIGAdAccountSelectorContainer_8 = function (props) { if (props.x === 8) { return React.createElement(BIGAdAccountSelector7, {x: 7}); } }; var ErrorBoundary9 = function (props) { if (props.x === 9) { return React.createElement( FluxContainer_AdsPEBIGAdAccountSelectorContainer_8, {x: 8} ); } if (props.x === 13) { return React.createElement(FluxContainer_AdsPENavigationBarContainer_12, { x: 12, }); } if (props.x === 27) { return React.createElement(FluxContainer_AdsPEPublishButtonContainer_18, { x: 26, }); } if (props.x === 32) { return React.createElement(ReactPopoverMenu20, {x: 31}); } if (props.x === 38) { return React.createElement(AdsPEResetDialog24, {x: 37}); } if (props.x === 57) { return React.createElement(FluxContainer_AdsPETopErrorContainer_35, { x: 56, }); } if (props.x === 60) { return React.createElement(FluxContainer_AdsGuidanceChannel_36, {x: 59}); } if (props.x === 64) { return React.createElement(FluxContainer_AdsBulkEditDialogContainer_38, { x: 63, }); } if (props.x === 124) { return React.createElement(AdsPECampaignGroupToolbarContainer57, { x: 123, }); } if (props.x === 170) { return React.createElement(AdsPEFilterContainer72, {x: 169}); } if (props.x === 175) { return React.createElement(AdsPETablePagerContainer75, {x: 174}); } if (props.x === 193) { return React.createElement(AdsPEStatRangeContainer81, {x: 192}); } if (props.x === 301) { return React.createElement( FluxContainer_AdsPEMultiTabDrawerContainer_137, {x: 300} ); } if (props.x === 311) { return React.createElement(AdsPEOrganizerContainer139, {x: 310}); } if (props.x === 471) { return React.createElement(AdsPECampaignGroupTableContainer159, {x: 470}); } if (props.x === 475) { return React.createElement(AdsPEContentContainer161, {x: 474}); } }; var AdsErrorBoundary10 = function (props) { if (props.x === 10) { return React.createElement(ErrorBoundary9, {x: 9}); } if (props.x === 14) { return React.createElement(ErrorBoundary9, {x: 13}); } if (props.x === 28) { return React.createElement(ErrorBoundary9, {x: 27}); } if (props.x === 33) { return React.createElement(ErrorBoundary9, {x: 32}); } if (props.x === 39) { return React.createElement(ErrorBoundary9, {x: 38}); } if (props.x === 58) { return React.createElement(ErrorBoundary9, {x: 57}); } if (props.x === 61) { return React.createElement(ErrorBoundary9, {x: 60}); } if (props.x === 65) { return React.createElement(ErrorBoundary9, {x: 64}); } if (props.x === 125) { return React.createElement(ErrorBoundary9, {x: 124}); } if (props.x === 171) { return React.createElement(ErrorBoundary9, {x: 170}); } if (props.x === 176) { return React.createElement(ErrorBoundary9, {x: 175}); } if (props.x === 194) { return React.createElement(ErrorBoundary9, {x: 193}); } if (props.x === 302) { return React.createElement(ErrorBoundary9, {x: 301}); } if (props.x === 312) { return React.createElement(ErrorBoundary9, {x: 311}); } if (props.x === 472) { return React.createElement(ErrorBoundary9, {x: 471}); } if (props.x === 476) { return React.createElement(ErrorBoundary9, {x: 475}); } }; var AdsPENavigationBar11 = function (props) { if (props.x === 11) { return React.createElement('div', {className: '_4t_9'}); } }; var FluxContainer_AdsPENavigationBarContainer_12 = function (props) { if (props.x === 12) { return React.createElement(AdsPENavigationBar11, {x: 11}); } }; var AdsPEDraftSyncStatus13 = function (props) { if (props.x === 16) { return React.createElement( 'div', {className: '_3ut-', onClick: function () {}}, React.createElement( 'span', {className: '_3uu0'}, React.createElement(ReactImage0, {x: 15}) ) ); } }; var FluxContainer_AdsPEDraftSyncStatusContainer_14 = function (props) { if (props.x === 17) { return React.createElement(AdsPEDraftSyncStatus13, {x: 16}); } }; var AdsPEDraftErrorsStatus15 = function (props) { if (props.x === 18) { return null; } }; var FluxContainer_viewFn_16 = function (props) { if (props.x === 19) { return React.createElement(AdsPEDraftErrorsStatus15, {x: 18}); } }; var AdsPEPublishButton17 = function (props) { if (props.x === 25) { return React.createElement( 'div', {className: '_5533'}, React.createElement(FluxContainer_AdsPEDraftSyncStatusContainer_14, { x: 17, }), React.createElement(FluxContainer_viewFn_16, {x: 19}), null, React.createElement(XUIButton4, {x: 21, key: 'discard'}), React.createElement(XUIButton4, {x: 24}) ); } }; var FluxContainer_AdsPEPublishButtonContainer_18 = function (props) { if (props.x === 26) { return React.createElement(AdsPEPublishButton17, {x: 25}); } }; var InlineBlock19 = function (props) { if (props.x === 30) { return React.createElement( 'div', {className: 'uiPopover _6a _6b', disabled: null}, React.createElement(ReactImage0, {x: 29, key: '.0'}) ); } if (props.x === 73) { return React.createElement( 'div', {className: 'uiPopover _6a _6b', disabled: null}, React.createElement(XUIButton4, {x: 72, key: '.0'}) ); } if (props.x === 82) { return React.createElement( 'div', {className: '_1nwm uiPopover _6a _6b', disabled: null}, React.createElement(XUIButton4, {x: 81, key: '.0'}) ); } if (props.x === 101) { return React.createElement( 'div', {size: 'large', className: 'uiPopover _6a _6b', disabled: null}, React.createElement(XUIButton4, {x: 100, key: '.0'}) ); } if (props.x === 273) { return React.createElement( 'div', { className: '_3-90 uiPopover _6a _6b', style: {marginTop: 2}, disabled: null, }, React.createElement(ReactXUIPopoverButton6, {x: 272, key: '.0'}) ); } }; var ReactPopoverMenu20 = function (props) { if (props.x === 31) { return React.createElement(InlineBlock19, {x: 30}); } if (props.x === 74) { return React.createElement(InlineBlock19, {x: 73}); } if (props.x === 83) { return React.createElement(InlineBlock19, {x: 82}); } if (props.x === 102) { return React.createElement(InlineBlock19, {x: 101}); } if (props.x === 274) { return React.createElement(InlineBlock19, {x: 273}); } }; var LeftRight21 = function (props) { if (props.x === 34) { return React.createElement( 'div', {className: 'clearfix'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, React.createElement( 'div', {className: '_34_j'}, React.createElement( 'div', {className: '_34_k'}, React.createElement(AdsErrorBoundary10, {x: 10}) ), React.createElement( 'div', {className: '_2u-6'}, React.createElement(AdsErrorBoundary10, {x: 14}) ) ) ), React.createElement( 'div', {key: 'right', className: '_ohf rfloat'}, React.createElement( 'div', {className: '_34_m'}, React.createElement( 'div', {key: '0', className: '_5ju2'}, React.createElement(AdsErrorBoundary10, {x: 28}) ), React.createElement( 'div', {key: '1', className: '_5ju2'}, React.createElement(AdsErrorBoundary10, {x: 33}) ) ) ) ); } if (props.x === 232) { return React.createElement( 'div', {direction: 'left', className: 'clearfix'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, React.createElement(AdsLabeledField104, {x: 231}) ), React.createElement( 'div', {key: 'right', className: ''}, React.createElement( 'div', {className: '_42ef'}, React.createElement( 'div', {className: '_2oc7'}, 'Clicks to Website' ) ) ) ); } if (props.x === 235) { return React.createElement( 'div', {className: '_3-8x clearfix', direction: 'left'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, React.createElement(AdsLabeledField104, {x: 234}) ), React.createElement( 'div', {key: 'right', className: ''}, React.createElement( 'div', {className: '_42ef'}, React.createElement('div', {className: '_2oc7'}, 'Auction') ) ) ); } if (props.x === 245) { return React.createElement( 'div', {className: '_3-8y clearfix', direction: 'left'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, React.createElement(AdsLabeledField104, {x: 240}) ), React.createElement( 'div', {key: 'right', className: ''}, React.createElement( 'div', {className: '_42ef'}, React.createElement( FluxContainer_AdsCampaignGroupSpendCapContainer_107, {x: 244} ) ) ) ); } if (props.x === 277) { return React.createElement( 'div', {className: '_5dw9 _5dwa clearfix'}, React.createElement( 'div', {key: 'left', className: '_ohe lfloat'}, React.createElement(XUICardHeaderTitle100, {x: 265, key: '.0'}) ), React.createElement( 'div', {key: 'right', className: '_ohf rfloat'}, React.createElement( FluxContainer_AdsPluginizedLinksMenuContainer_121, {x: 276, key: '.1'} ) ) ); } }; var AdsUnifiedNavigationLocalNav22 = function (props) { if (props.x === 35) { return React.createElement( 'div', {className: '_34_i'}, React.createElement(LeftRight21, {x: 34}) ); } }; var XUIDialog23 = function (props) { if (props.x === 36) { return null; } }; var AdsPEResetDialog24 = function (props) { if (props.x === 37) { return React.createElement( 'span', null, React.createElement(XUIDialog23, {x: 36, key: 'dialog/.0'}) ); } }; var AdsPETopNav25 = function (props) { if (props.x === 40) { return React.createElement( 'div', {style: {width: 1306}}, React.createElement(AdsUnifiedNavigationLocalNav22, {x: 35}), React.createElement(AdsErrorBoundary10, {x: 39}) ); } }; var FluxContainer_AdsPETopNavContainer_26 = function (props) { if (props.x === 41) { return React.createElement(AdsPETopNav25, {x: 40}); } }; var XUIAbstractGlyphButton27 = function (props) { if (props.x === 46) { return React.createElement(AbstractButton3, {x: 45}); } if (props.x === 150) { return React.createElement(AbstractButton3, {x: 149}); } }; var XUICloseButton28 = function (props) { if (props.x === 47) { return React.createElement(XUIAbstractGlyphButton27, {x: 46}); } if (props.x === 151) { return React.createElement(XUIAbstractGlyphButton27, {x: 150}); } }; var XUIText29 = function (props) { if (props.x === 48) { return React.createElement( 'span', {display: 'inline', className: ' _50f7'}, 'Ads Manager' ); } if (props.x === 205) { return React.createElement( 'span', {className: '_2x9f _50f5 _50f7', display: 'inline'}, 'Editing Campaign' ); } if (props.x === 206) { return React.createElement( 'span', {display: 'inline', className: ' _50f5 _50f7'}, 'Test Campaign' ); } }; var XUINotice30 = function (props) { if (props.x === 51) { return React.createElement( 'div', {size: 'medium', className: '_585n _585o _2wdd'}, React.createElement(ReactImage0, {x: 42}), React.createElement(XUICloseButton28, {x: 47}), React.createElement( 'div', {className: '_585r _2i-a _50f4'}, 'Please go to ', React.createElement(Link2, {x: 50}), ' to set up a payment method for this ad account.' ) ); } }; var ReactCSSTransitionGroupChild31 = function (props) { if (props.x === 52) { return React.createElement(XUINotice30, {x: 51}); } }; var ReactTransitionGroup32 = function (props) { if (props.x === 53) { return React.createElement( 'span', null, React.createElement(ReactCSSTransitionGroupChild31, {x: 52, key: '.0'}) ); } }; var ReactCSSTransitionGroup33 = function (props) { if (props.x === 54) { return React.createElement(ReactTransitionGroup32, {x: 53}); } }; var AdsPETopError34 = function (props) { if (props.x === 55) { return React.createElement( 'div', {className: '_2wdc'}, React.createElement(ReactCSSTransitionGroup33, {x: 54}) ); } }; var FluxContainer_AdsPETopErrorContainer_35 = function (props) { if (props.x === 56) { return React.createElement(AdsPETopError34, {x: 55}); } }; var FluxContainer_AdsGuidanceChannel_36 = function (props) { if (props.x === 59) { return null; } }; var ResponsiveBlock37 = function (props) { if (props.x === 62) { return React.createElement( 'div', {className: '_4u-c'}, [ React.createElement(AdsErrorBoundary10, {x: 58, key: 1}), React.createElement(AdsErrorBoundary10, {x: 61, key: 2}), ], React.createElement( 'div', {key: 'sensor', className: '_4u-f'}, React.createElement('iframe', { 'aria-hidden': 'true', className: '_1_xb', tabIndex: '-1', }) ) ); } if (props.x === 469) { return React.createElement( 'div', {className: '_4u-c'}, React.createElement(AdsPEDataTableContainer158, {x: 468}), React.createElement( 'div', {key: 'sensor', className: '_4u-f'}, React.createElement('iframe', { 'aria-hidden': 'true', className: '_1_xb', tabIndex: '-1', }) ) ); } }; var FluxContainer_AdsBulkEditDialogContainer_38 = function (props) { if (props.x === 63) { return null; } }; var Column39 = function (props) { if (props.x === 66) { return React.createElement( 'div', {className: '_4bl8 _4bl7'}, React.createElement( 'div', {className: '_3c5f'}, null, null, React.createElement('div', {className: '_3c5i'}), null ) ); } }; var XUIButtonGroup40 = function (props) { if (props.x === 75) { return React.createElement( 'div', {className: '_5n7z _51xa'}, React.createElement(XUIButton4, {x: 69}), React.createElement(ReactPopoverMenu20, {x: 74}) ); } if (props.x === 84) { return React.createElement( 'div', {className: '_5n7z _51xa'}, React.createElement(XUIButton4, {x: 78, key: 'edit'}), React.createElement(ReactPopoverMenu20, {x: 83, key: 'editMenu'}) ); } if (props.x === 97) { return React.createElement( 'div', {className: '_5n7z _51xa'}, React.createElement(XUIButton4, {x: 90, key: 'revert'}), React.createElement(XUIButton4, {x: 93, key: 'delete'}), React.createElement(XUIButton4, {x: 96, key: 'duplicate'}) ); } if (props.x === 117) { return React.createElement( 'div', {className: '_5n7z _51xa'}, React.createElement(AdsPEExportImportMenuContainer48, {x: 107}), React.createElement(XUIButton4, {x: 110, key: 'createReport'}), React.createElement(AdsPECampaignGroupTagContainer51, { x: 116, key: 'tags', }) ); } }; var AdsPEEditToolbarButton41 = function (props) { if (props.x === 85) { return React.createElement(XUIButtonGroup40, {x: 84}); } }; var FluxContainer_AdsPEEditCampaignGroupToolbarButtonContainer_42 = function ( props ) { if (props.x === 86) { return React.createElement(AdsPEEditToolbarButton41, {x: 85}); } }; var FluxContainer_AdsPEEditToolbarButtonContainer_43 = function (props) { if (props.x === 87) { return React.createElement( FluxContainer_AdsPEEditCampaignGroupToolbarButtonContainer_42, {x: 86} ); } }; var AdsPEExportImportMenu44 = function (props) { if (props.x === 103) { return React.createElement(ReactPopoverMenu20, {x: 102, key: 'export'}); } }; var FluxContainer_AdsPECustomizeExportContainer_45 = function (props) { if (props.x === 104) { return null; } }; var AdsPEExportAsTextDialog46 = function (props) { if (props.x === 105) { return null; } }; var FluxContainer_AdsPEExportAsTextDialogContainer_47 = function (props) { if (props.x === 106) { return React.createElement(AdsPEExportAsTextDialog46, {x: 105}); } }; var AdsPEExportImportMenuContainer48 = function (props) { if (props.x === 107) { return React.createElement( 'span', null, React.createElement(AdsPEExportImportMenu44, {x: 103}), React.createElement(FluxContainer_AdsPECustomizeExportContainer_45, { x: 104, }), React.createElement(FluxContainer_AdsPEExportAsTextDialogContainer_47, { x: 106, }), null, null ); } }; var Constructor49 = function (props) { if (props.x === 114) { return null; } if (props.x === 142) { return null; } if (props.x === 143) { return null; } if (props.x === 183) { return null; } }; var TagSelectorPopover50 = function (props) { if (props.x === 115) { return React.createElement( 'span', {className: ' _3d6e'}, React.createElement(XUIButton4, {x: 113}), React.createElement(Constructor49, {x: 114, key: 'layer'}) ); } }; var AdsPECampaignGroupTagContainer51 = function (props) { if (props.x === 116) { return React.createElement(TagSelectorPopover50, { x: 115, key: '98010048849317', }); } }; var AdsRuleToolbarMenu52 = function (props) { if (props.x === 118) { return null; } }; var FluxContainer_AdsPERuleToolbarMenuContainer_53 = function (props) { if (props.x === 119) { return React.createElement(AdsRuleToolbarMenu52, {x: 118}); } }; var FillColumn54 = function (props) { if (props.x === 120) { return React.createElement( 'div', {className: '_4bl9'}, React.createElement( 'span', {className: '_3c5e'}, React.createElement( 'span', null, React.createElement(XUIButtonGroup40, {x: 75}), React.createElement( FluxContainer_AdsPEEditToolbarButtonContainer_43, {x: 87} ), null, React.createElement(XUIButtonGroup40, {x: 97}) ), React.createElement(XUIButtonGroup40, {x: 117}), React.createElement(FluxContainer_AdsPERuleToolbarMenuContainer_53, { x: 119, }) ) ); } }; var Layout55 = function (props) { if (props.x === 121) { return React.createElement( 'div', {className: 'clearfix'}, React.createElement(Column39, {x: 66, key: '1'}), React.createElement(FillColumn54, {x: 120, key: '0'}) ); } }; var AdsPEMainPaneToolbar56 = function (props) { if (props.x === 122) { return React.createElement( 'div', {className: '_3c5b clearfix'}, React.createElement(Layout55, {x: 121}) ); } }; var AdsPECampaignGroupToolbarContainer57 = function (props) { if (props.x === 123) { return React.createElement(AdsPEMainPaneToolbar56, {x: 122}); } }; var AdsPEFiltersPopover58 = function (props) { if (props.x === 144) { return React.createElement( 'span', {className: '_5b-l _5bbe'}, React.createElement(ReactXUIPopoverButton6, {x: 133}), React.createElement(ReactXUIPopoverButton6, {x: 141}), [ React.createElement(Constructor49, {x: 142, key: 'filterMenu/.0'}), React.createElement(Constructor49, {x: 143, key: 'searchMenu/.0'}), ] ); } }; var AbstractCheckboxInput59 = function (props) { if (props.x === 145) { return React.createElement( 'label', {className: 'uiInputLabelInput _55sg _kv1'}, React.createElement('input', { checked: true, disabled: true, name: 'filterUnpublished', value: 'on', onClick: function () {}, className: null, id: 'js_input_label_21', type: 'checkbox', }), React.createElement('span', { 'data-hover': null, 'data-tooltip-content': undefined, }) ); } if (props.x === 336) { return React.createElement( 'label', {className: '_4h2r _55sg _kv1'}, React.createElement('input', { checked: undefined, onChange: function () {}, className: null, type: 'checkbox', }), React.createElement('span', { 'data-hover': null, 'data-tooltip-content': undefined, }) ); } }; var XUICheckboxInput60 = function (props) { if (props.x === 146) { return React.createElement(AbstractCheckboxInput59, {x: 145}); } if (props.x === 337) { return React.createElement(AbstractCheckboxInput59, {x: 336}); } }; var InputLabel61 = function (props) { if (props.x === 147) { return React.createElement( 'div', {display: 'block', className: 'uiInputLabel clearfix'}, React.createElement(XUICheckboxInput60, {x: 146}), React.createElement( 'label', {className: 'uiInputLabelLabel', htmlFor: 'js_input_label_21'}, 'Always show new items' ) ); } }; var AdsPopoverLink62 = function (props) { if (props.x === 154) { return React.createElement( 'span', null, React.createElement( 'span', { onMouseEnter: function () {}, onMouseLeave: function () {}, onMouseUp: undefined, }, React.createElement('span', {className: '_3o_j'}), React.createElement(ReactImage0, {x: 153}) ), null ); } if (props.x === 238) { return React.createElement( 'span', null, React.createElement( 'span', { onMouseEnter: function () {}, onMouseLeave: function () {}, onMouseUp: undefined, }, React.createElement('span', {className: '_3o_j'}), React.createElement(ReactImage0, {x: 237}) ), null ); } }; var AdsHelpLink63 = function (props) { if (props.x === 155) { return React.createElement(AdsPopoverLink62, {x: 154}); } if (props.x === 239) { return React.createElement(AdsPopoverLink62, {x: 238}); } }; var BUIFilterTokenInput64 = function (props) { if (props.x === 158) { return React.createElement( 'div', {className: '_5b5o _3yz3 _4cld'}, React.createElement( 'div', {className: '_5b5t _2d2k'}, React.createElement(ReactImage0, {x: 152}), React.createElement( 'div', {className: '_5b5r'}, 'Campaigns: (1)', React.createElement(AdsHelpLink63, {x: 155}) ) ), React.createElement(XUIButton4, {x: 157}) ); } }; var BUIFilterToken65 = function (props) { if (props.x === 159) { return React.createElement( 'div', {className: '_3yz1 _3yz2 _3dad'}, React.createElement( 'div', {className: '_3yz4', 'aria-hidden': false}, React.createElement( 'div', {onClick: function () {}, className: '_3yz5'}, React.createElement(ReactImage0, {x: 148}), React.createElement('div', {className: '_3yz7'}, 'Campaigns:'), React.createElement( 'div', { className: 'ellipsis _3yz8', 'data-hover': 'tooltip', 'data-tooltip-display': 'overflow', }, '(1)' ) ), null, React.createElement(XUICloseButton28, {x: 151}) ), React.createElement(BUIFilterTokenInput64, {x: 158}) ); } }; var BUIFilterTokenCreateButton66 = function (props) { if (props.x === 163) { return React.createElement( 'div', {className: '_1tc'}, React.createElement(XUIButton4, {x: 162}) ); } }; var BUIFilterTokenizer67 = function (props) { if (props.x === 164) { return React.createElement( 'div', {className: '_5b-m clearfix'}, undefined, [], React.createElement(BUIFilterToken65, {x: 159, key: 'token0'}), React.createElement(BUIFilterTokenCreateButton66, {x: 163}), null, React.createElement('div', {className: '_49u3'}) ); } }; var XUIAmbientNUX68 = function (props) { if (props.x === 165) { return null; } if (props.x === 189) { return null; } if (props.x === 200) { return null; } }; var XUIAmbientNUX69 = function (props) { if (props.x === 166) { return React.createElement(XUIAmbientNUX68, {x: 165}); } if (props.x === 190) { return React.createElement(XUIAmbientNUX68, {x: 189}); } if (props.x === 201) { return React.createElement(XUIAmbientNUX68, {x: 200}); } }; var AdsPEAmbientNUXMegaphone70 = function (props) { if (props.x === 167) { return React.createElement( 'span', null, React.createElement('span', {}), React.createElement(XUIAmbientNUX69, {x: 166, key: 'nux'}) ); } }; var AdsPEFilters71 = function (props) { if (props.x === 168) { return React.createElement( 'div', {className: '_4rw_'}, React.createElement(AdsPEFiltersPopover58, {x: 144}), React.createElement( 'div', {className: '_1eo'}, React.createElement(InputLabel61, {x: 147}) ), React.createElement(BUIFilterTokenizer67, {x: 164}), '', React.createElement(AdsPEAmbientNUXMegaphone70, {x: 167}) ); } }; var AdsPEFilterContainer72 = function (props) { if (props.x === 169) { return React.createElement(AdsPEFilters71, {x: 168}); } }; var AdsPETablePager73 = function (props) { if (props.x === 172) { return null; } }; var AdsPECampaignGroupTablePagerContainer74 = function (props) { if (props.x === 173) { return React.createElement(AdsPETablePager73, {x: 172}); } }; var AdsPETablePagerContainer75 = function (props) { if (props.x === 174) { return React.createElement(AdsPECampaignGroupTablePagerContainer74, { x: 173, }); } }; var ReactXUIError76 = function (props) { if (props.x === 181) { return React.createElement(AbstractButton3, {x: 180}); } if (props.x === 216) { return React.createElement( 'div', {className: '_40bf _2vl4 _1h18'}, null, null, React.createElement( 'div', {className: '_2vl9 _1h1f', style: {backgroundColor: '#fff'}}, React.createElement( 'div', {className: '_2vla _1h1g'}, React.createElement( 'div', null, null, React.createElement('textarea', { className: '_2vli _2vlj _1h26 _1h27', dir: 'auto', disabled: undefined, id: undefined, maxLength: null, value: 'Test Campaign', onBlur: function () {}, onChange: function () {}, onFocus: function () {}, onKeyDown: function () {}, }), null ), React.createElement('div', { 'aria-hidden': 'true', className: '_2vlk', }) ) ), null ); } if (props.x === 221) { return React.createElement(XUICard94, {x: 220}); } if (props.x === 250) { return React.createElement(XUICard94, {x: 249}); } if (props.x === 280) { return React.createElement(XUICard94, {x: 279}); } }; var BUIPopoverButton77 = function (props) { if (props.x === 182) { return React.createElement(ReactXUIError76, {x: 181}); } }; var BUIDateRangePicker78 = function (props) { if (props.x === 184) { return React.createElement( 'span', null, React.createElement(BUIPopoverButton77, {x: 182}), [React.createElement(Constructor49, {x: 183, key: 'layer/.0'})] ); } }; var AdsPEStatsRangePicker79 = function (props) { if (props.x === 185) { return React.createElement(BUIDateRangePicker78, {x: 184}); } }; var AdsPEStatRange80 = function (props) { if (props.x === 191) { return React.createElement( 'div', {className: '_3c5k'}, React.createElement('span', {className: '_3c5j'}, 'Stats:'), React.createElement( 'span', {className: '_3c5l'}, React.createElement(AdsPEStatsRangePicker79, {x: 185}), React.createElement(XUIButton4, {x: 188, key: 'settings'}) ), [React.createElement(XUIAmbientNUX69, {x: 190, key: 'roasNUX/.0'})] ); } }; var AdsPEStatRangeContainer81 = function (props) { if (props.x === 192) { return React.createElement(AdsPEStatRange80, {x: 191}); } }; var AdsPESideTrayTabButton82 = function (props) { if (props.x === 196) { return React.createElement( 'div', {className: '_1-ly _59j9 _d9a', onClick: function () {}}, React.createElement(ReactImage0, {x: 195}), React.createElement('div', {className: '_vf7'}), React.createElement('div', {className: '_vf8'}) ); } if (props.x === 199) { return React.createElement( 'div', {className: ' _1-lz _d9a', onClick: function () {}}, React.createElement(ReactImage0, {x: 198}), React.createElement('div', {className: '_vf7'}), React.createElement('div', {className: '_vf8'}) ); } if (props.x === 203) { return null; } }; var AdsPEEditorTrayTabButton83 = function (props) { if (props.x === 197) { return React.createElement(AdsPESideTrayTabButton82, {x: 196}); } }; var AdsPEInsightsTrayTabButton84 = function (props) { if (props.x === 202) { return React.createElement( 'span', null, React.createElement(AdsPESideTrayTabButton82, {x: 199}), React.createElement(XUIAmbientNUX69, {x: 201, key: 'roasNUX'}) ); } }; var AdsPENekoDebuggerTrayTabButton85 = function (props) { if (props.x === 204) { return React.createElement(AdsPESideTrayTabButton82, {x: 203}); } }; var AdsPEEditorChildLink86 = function (props) { if (props.x === 211) { return React.createElement( 'div', {className: '_3ywr'}, React.createElement(Link2, {x: 208}), React.createElement('span', {className: '_3ywq'}, '|'), React.createElement(Link2, {x: 210}) ); } }; var AdsPEEditorChildLinkContainer87 = function (props) { if (props.x === 212) { return React.createElement(AdsPEEditorChildLink86, {x: 211}); } }; var AdsPEHeaderSection88 = function (props) { if (props.x === 213) { return React.createElement( 'div', {className: '_yke'}, React.createElement('div', {className: '_2x9d _pr-'}), React.createElement(XUIText29, {x: 205}), React.createElement( 'div', {className: '_3a-a'}, React.createElement( 'div', {className: '_3a-b'}, React.createElement(XUIText29, {x: 206}) ) ), React.createElement(AdsPEEditorChildLinkContainer87, {x: 212}) ); } }; var AdsPECampaignGroupHeaderSectionContainer89 = function (props) { if (props.x === 214) { return React.createElement(AdsPEHeaderSection88, {x: 213}); } }; var AdsEditorLoadingErrors90 = function (props) { if (props.x === 215) { return null; } }; var AdsTextInput91 = function (props) { if (props.x === 217) { return React.createElement(ReactXUIError76, {x: 216}); } }; var BUIFormElement92 = function (props) { if (props.x === 218) { return React.createElement( 'div', {className: '_5521 clearfix'}, React.createElement( 'div', {className: '_5522 _3w5q'}, React.createElement( 'label', { onClick: undefined, htmlFor: '1467872040612:1961945894', className: '_5523 _3w5r', }, 'Campaign Name', null ) ), React.createElement( 'div', {className: '_5527'}, React.createElement( 'div', {className: '_5528'}, React.createElement( 'span', {key: '.0', className: '_40bg', id: '1467872040612:1961945894'}, React.createElement(AdsTextInput91, { x: 217, key: 'nameEditor98010048849317', }), null ) ), null ) ); } }; var BUIForm93 = function (props) { if (props.x === 219) { return React.createElement( 'div', {className: '_5ks1 _550r _550t _550y _3w5n'}, React.createElement(BUIFormElement92, {x: 218, key: '.0'}) ); } }; var XUICard94 = function (props) { if (props.x === 220) { return React.createElement( 'div', {className: '_40bc _12k2 _4-u2 _4-u8'}, React.createElement(BUIForm93, {x: 219}) ); } if (props.x === 249) { return React.createElement( 'div', {className: '_12k2 _4-u2 _4-u8'}, React.createElement(AdsCardHeader103, {x: 230}), React.createElement(AdsCardSection108, {x: 248}) ); } if (props.x === 279) { return React.createElement( 'div', {className: '_12k2 _4-u2 _4-u8'}, React.createElement(AdsCardLeftRightHeader122, {x: 278}) ); } }; var AdsCard95 = function (props) { if (props.x === 222) { return React.createElement(ReactXUIError76, {x: 221}); } if (props.x === 251) { return React.createElement(ReactXUIError76, {x: 250}); } if (props.x === 281) { return React.createElement(ReactXUIError76, {x: 280}); } }; var AdsEditorNameSection96 = function (props) { if (props.x === 223) { return React.createElement(AdsCard95, {x: 222}); } }; var AdsCampaignGroupNameSectionContainer97 = function (props) { if (props.x === 224) { return React.createElement(AdsEditorNameSection96, { x: 223, key: 'nameSection98010048849317', }); } }; var _render98 = function (props) { if (props.x === 225) { return React.createElement(AdsCampaignGroupNameSectionContainer97, { x: 224, }); } }; var AdsPluginWrapper99 = function (props) { if (props.x === 226) { return React.createElement(_render98, {x: 225}); } if (props.x === 255) { return React.createElement(_render111, {x: 254}); } if (props.x === 258) { return React.createElement(_render113, {x: 257}); } if (props.x === 287) { return React.createElement(_render127, {x: 286}); } if (props.x === 291) { return React.createElement(_render130, {x: 290}); } }; var XUICardHeaderTitle100 = function (props) { if (props.x === 227) { return React.createElement( 'span', {className: '_38my'}, 'Campaign Details', null, React.createElement('span', {className: '_c1c'}) ); } if (props.x === 265) { return React.createElement( 'span', {className: '_38my'}, [ React.createElement( 'span', {key: 1}, 'Campaign ID', ': ', '98010048849317' ), React.createElement( 'div', {className: '_5lh9', key: 2}, React.createElement( FluxContainer_AdsCampaignGroupStatusSwitchContainer_119, {x: 264} ) ), ], null, React.createElement('span', {className: '_c1c'}) ); } }; var XUICardSection101 = function (props) { if (props.x === 228) { return React.createElement( 'div', {className: '_5dw9 _5dwa _4-u3'}, [React.createElement(XUICardHeaderTitle100, {x: 227, key: '.0'})], undefined, undefined, React.createElement('div', {className: '_3s3-'}) ); } if (props.x === 247) { return React.createElement( 'div', {className: '_12jy _4-u3'}, React.createElement( 'div', {className: '_3-8j'}, React.createElement(FlexibleBlock105, {x: 233}), React.createElement(FlexibleBlock105, {x: 236}), React.createElement(FlexibleBlock105, {x: 246}), null, null ) ); } }; var XUICardHeader102 = function (props) { if (props.x === 229) { return React.createElement(XUICardSection101, {x: 228}); } }; var AdsCardHeader103 = function (props) { if (props.x === 230) { return React.createElement(XUICardHeader102, {x: 229}); } }; var AdsLabeledField104 = function (props) { if (props.x === 231) { return React.createElement( 'div', {className: '_2oc6 _3bvz', label: 'Objective'}, React.createElement( 'label', {className: '_4el4 _3qwj _3hy-', htmlFor: undefined}, 'Objective ' ), null, React.createElement('div', {className: '_3bv-'}) ); } if (props.x === 234) { return React.createElement( 'div', {className: '_2oc6 _3bvz', label: 'Buying Type'}, React.createElement( 'label', {className: '_4el4 _3qwj _3hy-', htmlFor: undefined}, 'Buying Type ' ), null, React.createElement('div', {className: '_3bv-'}) ); } if (props.x === 240) { return React.createElement( 'div', {className: '_2oc6 _3bvz'}, React.createElement( 'label', {className: '_4el4 _3qwj _3hy-', htmlFor: undefined}, 'Campaign Spending Limit ' ), React.createElement(AdsHelpLink63, {x: 239}), React.createElement('div', {className: '_3bv-'}) ); } }; var FlexibleBlock105 = function (props) { if (props.x === 233) { return React.createElement(LeftRight21, {x: 232}); } if (props.x === 236) { return React.createElement(LeftRight21, {x: 235}); } if (props.x === 246) { return React.createElement(LeftRight21, {x: 245}); } }; var AdsBulkCampaignSpendCapField106 = function (props) { if (props.x === 243) { return React.createElement( 'div', {className: '_33dv'}, '', React.createElement(Link2, {x: 242}), ' (optional)' ); } }; var FluxContainer_AdsCampaignGroupSpendCapContainer_107 = function (props) { if (props.x === 244) { return React.createElement(AdsBulkCampaignSpendCapField106, {x: 243}); } }; var AdsCardSection108 = function (props) { if (props.x === 248) { return React.createElement(XUICardSection101, {x: 247}); } }; var AdsEditorCampaignGroupDetailsSection109 = function (props) { if (props.x === 252) { return React.createElement(AdsCard95, {x: 251}); } }; var AdsEditorCampaignGroupDetailsSectionContainer110 = function (props) { if (props.x === 253) { return React.createElement(AdsEditorCampaignGroupDetailsSection109, { x: 252, key: 'campaignGroupDetailsSection98010048849317', }); } }; var _render111 = function (props) { if (props.x === 254) { return React.createElement( AdsEditorCampaignGroupDetailsSectionContainer110, {x: 253} ); } }; var FluxContainer_AdsEditorToplineDetailsSectionContainer_112 = function ( props ) { if (props.x === 256) { return null; } }; var _render113 = function (props) { if (props.x === 257) { return React.createElement( FluxContainer_AdsEditorToplineDetailsSectionContainer_112, {x: 256} ); } }; var AdsStickyArea114 = function (props) { if (props.x === 259) { return React.createElement( 'div', {}, React.createElement('div', {onWheel: function () {}}) ); } if (props.x === 292) { return React.createElement( 'div', {}, React.createElement('div', {onWheel: function () {}}, [ React.createElement( 'div', {key: 'campaign_group_errors_section98010048849317'}, React.createElement(AdsPluginWrapper99, {x: 291}) ), ]) ); } }; var FluxContainer_AdsEditorColumnContainer_115 = function (props) { if (props.x === 260) { return React.createElement( 'div', null, [ React.createElement( 'div', {key: 'campaign_group_name_section98010048849317'}, React.createElement(AdsPluginWrapper99, {x: 226}) ), React.createElement( 'div', {key: 'campaign_group_basic_section98010048849317'}, React.createElement(AdsPluginWrapper99, {x: 255}) ), React.createElement( 'div', {key: 'campaign_group_topline_section98010048849317'}, React.createElement(AdsPluginWrapper99, {x: 258}) ), ], React.createElement(AdsStickyArea114, {x: 259}) ); } if (props.x === 293) { return React.createElement( 'div', null, [ React.createElement( 'div', {key: 'campaign_group_navigation_section98010048849317'}, React.createElement(AdsPluginWrapper99, {x: 287}) ), ], React.createElement(AdsStickyArea114, {x: 292}) ); } }; var BUISwitch116 = function (props) { if (props.x === 261) { return React.createElement( 'div', { 'data-hover': 'tooltip', 'data-tooltip-content': 'Currently active. Click this switch to deactivate it.', 'data-tooltip-position': 'below', disabled: false, value: true, onToggle: function () {}, className: '_128j _128k _128n', role: 'checkbox', 'aria-checked': 'true', }, React.createElement( 'div', { className: '_128o', onClick: function () {}, onKeyDown: function () {}, onMouseDown: function () {}, tabIndex: '0', }, React.createElement('div', {className: '_128p'}) ), null ); } }; var AdsStatusSwitchInternal117 = function (props) { if (props.x === 262) { return React.createElement(BUISwitch116, {x: 261}); } }; var AdsStatusSwitch118 = function (props) { if (props.x === 263) { return React.createElement(AdsStatusSwitchInternal117, {x: 262}); } }; var FluxContainer_AdsCampaignGroupStatusSwitchContainer_119 = function ( props ) { if (props.x === 264) { return React.createElement(AdsStatusSwitch118, { x: 263, key: 'status98010048849317', }); } }; var AdsLinksMenu120 = function (props) { if (props.x === 275) { return React.createElement(ReactPopoverMenu20, {x: 274}); } }; var FluxContainer_AdsPluginizedLinksMenuContainer_121 = function (props) { if (props.x === 276) { return React.createElement( 'div', null, null, React.createElement(AdsLinksMenu120, {x: 275}) ); } }; var AdsCardLeftRightHeader122 = function (props) { if (props.x === 278) { return React.createElement(LeftRight21, {x: 277}); } }; var AdsPEIDSection123 = function (props) { if (props.x === 282) { return React.createElement(AdsCard95, {x: 281}); } }; var FluxContainer_AdsPECampaignGroupIDSectionContainer_124 = function ( props ) { if (props.x === 283) { return React.createElement(AdsPEIDSection123, {x: 282}); } }; var DeferredComponent125 = function (props) { if (props.x === 284) { return React.createElement( FluxContainer_AdsPECampaignGroupIDSectionContainer_124, {x: 283} ); } }; var BootloadedComponent126 = function (props) { if (props.x === 285) { return React.createElement(DeferredComponent125, {x: 284}); } }; var _render127 = function (props) { if (props.x === 286) { return React.createElement(BootloadedComponent126, {x: 285}); } }; var AdsEditorErrorsCard128 = function (props) { if (props.x === 288) { return null; } }; var FluxContainer_FunctionalContainer_129 = function (props) { if (props.x === 289) { return React.createElement(AdsEditorErrorsCard128, {x: 288}); } }; var _render130 = function (props) { if (props.x === 290) { return React.createElement(FluxContainer_FunctionalContainer_129, { x: 289, }); } }; var AdsEditorMultiColumnLayout131 = function (props) { if (props.x === 294) { return React.createElement( 'div', {className: '_psh'}, React.createElement( 'div', {className: '_3cc0'}, React.createElement( 'div', null, React.createElement(AdsEditorLoadingErrors90, {x: 215, key: '.0'}), React.createElement( 'div', {className: '_3ms3'}, React.createElement( 'div', {className: '_3ms4'}, React.createElement( FluxContainer_AdsEditorColumnContainer_115, {x: 260, key: '.1'} ) ), React.createElement( 'div', {className: '_3pvg'}, React.createElement( FluxContainer_AdsEditorColumnContainer_115, {x: 293, key: '.2'} ) ) ) ) ) ); } }; var AdsPECampaignGroupEditor132 = function (props) { if (props.x === 295) { return React.createElement( 'div', null, React.createElement(AdsPECampaignGroupHeaderSectionContainer89, { x: 214, }), React.createElement(AdsEditorMultiColumnLayout131, {x: 294}) ); } }; var AdsPECampaignGroupEditorContainer133 = function (props) { if (props.x === 296) { return React.createElement(AdsPECampaignGroupEditor132, {x: 295}); } }; var AdsPESideTrayTabContent134 = function (props) { if (props.x === 297) { return React.createElement( 'div', {className: '_1o_8 _44ra _5cyn'}, React.createElement(AdsPECampaignGroupEditorContainer133, {x: 296}) ); } }; var AdsPEEditorTrayTabContentContainer135 = function (props) { if (props.x === 298) { return React.createElement(AdsPESideTrayTabContent134, {x: 297}); } }; var AdsPEMultiTabDrawer136 = function (props) { if (props.x === 299) { return React.createElement( 'div', {className: '_2kev _2kex'}, React.createElement( 'div', {className: '_5yno'}, React.createElement(AdsPEEditorTrayTabButton83, { x: 197, key: 'editor_tray_button', }), React.createElement(AdsPEInsightsTrayTabButton84, { x: 202, key: 'insights_tray_button', }), React.createElement(AdsPENekoDebuggerTrayTabButton85, { x: 204, key: 'neko_debugger_tray_button', }) ), React.createElement( 'div', {className: '_5ynn'}, React.createElement(AdsPEEditorTrayTabContentContainer135, { x: 298, key: 'EDITOR_DRAWER', }), null ) ); } }; var FluxContainer_AdsPEMultiTabDrawerContainer_137 = function (props) { if (props.x === 300) { return React.createElement(AdsPEMultiTabDrawer136, {x: 299}); } }; var AdsPESimpleOrganizer138 = function (props) { if (props.x === 309) { return React.createElement( 'div', {className: '_tm2'}, React.createElement(XUIButton4, {x: 304}), React.createElement(XUIButton4, {x: 306}), React.createElement(XUIButton4, {x: 308}) ); } }; var AdsPEOrganizerContainer139 = function (props) { if (props.x === 310) { return React.createElement( 'div', null, React.createElement(AdsPESimpleOrganizer138, {x: 309}) ); } }; var FixedDataTableColumnResizeHandle140 = function (props) { if (props.x === 313) { return React.createElement( 'div', { className: '_3487 _3488 _3489', style: {width: 0, height: 25, left: 0}, }, React.createElement('div', {className: '_348a', style: {height: 25}}) ); } }; var AdsPETableHeader141 = function (props) { if (props.x === 315) { return React.createElement( 'div', {className: '_1cig _1ksv _1vd7 _4h2r', id: undefined}, React.createElement(ReactImage0, {x: 314}), React.createElement('span', {className: '_1cid'}, 'Campaigns') ); } if (props.x === 320) { return React.createElement( 'div', {className: '_1cig _1vd7 _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Performance') ); } if (props.x === 323) { return React.createElement( 'div', {className: '_1cig _1vd7 _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Overview') ); } if (props.x === 326) { return React.createElement( 'div', {className: '_1cig _1vd7 _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Toplines') ); } if (props.x === 329) { return React.createElement('div', { className: '_1cig _1vd7 _4h2r', id: undefined, }); } if (props.x === 340) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Campaign Name') ); } if (props.x === 346) { return React.createElement( 'div', { className: '_1cig _25fg', id: undefined, 'data-tooltip-content': 'Changed', 'data-hover': 'tooltip', }, React.createElement(ReactImage0, {x: 345}), null ); } if (props.x === 352) { return React.createElement( 'div', { className: '_1cig _25fg', id: 'ads_pe_table_error_header', 'data-tooltip-content': 'Errors', 'data-hover': 'tooltip', }, React.createElement(ReactImage0, {x: 351}), null ); } if (props.x === 357) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Status') ); } if (props.x === 362) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Delivery') ); } if (props.x === 369) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Results') ); } if (props.x === 374) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Cost') ); } if (props.x === 379) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Reach') ); } if (props.x === 384) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Impressions') ); } if (props.x === 389) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Clicks') ); } if (props.x === 394) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Avg. CPM') ); } if (props.x === 399) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Avg. CPC') ); } if (props.x === 404) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'CTR %') ); } if (props.x === 409) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Spent') ); } if (props.x === 414) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Objective') ); } if (props.x === 419) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Buying Type') ); } if (props.x === 424) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Campaign ID') ); } if (props.x === 429) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Start') ); } if (props.x === 434) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'End') ); } if (props.x === 439) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Date created') ); } if (props.x === 444) { return React.createElement( 'div', {className: '_1cig _25fg', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Date last edited') ); } if (props.x === 449) { return React.createElement( 'div', {className: '_1cig _25fg _4h2r', id: undefined}, null, React.createElement('span', {className: '_1cid'}, 'Tags') ); } if (props.x === 452) { return React.createElement('div', { className: '_1cig _25fg _4h2r', id: undefined, }); } }; var TransitionCell142 = function (props) { if (props.x === 316) { return React.createElement( 'div', { label: 'Campaigns', height: 40, width: 721, className: '_4lgc _4h2u', style: {height: 40, width: 721}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 315}) ) ) ); } if (props.x === 321) { return React.createElement( 'div', { label: 'Performance', height: 40, width: 798, className: '_4lgc _4h2u', style: {height: 40, width: 798}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 320}) ) ) ); } if (props.x === 324) { return React.createElement( 'div', { label: 'Overview', height: 40, width: 1022, className: '_4lgc _4h2u', style: {height: 40, width: 1022}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 323}) ) ) ); } if (props.x === 327) { return React.createElement( 'div', { label: 'Toplines', height: 40, width: 0, className: '_4lgc _4h2u', style: {height: 40, width: 0}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 326}) ) ) ); } if (props.x === 330) { return React.createElement( 'div', { label: '', height: 40, width: 25, className: '_4lgc _4h2u', style: {height: 40, width: 25}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 329}) ) ) ); } if (props.x === 338) { return React.createElement( 'div', { label: undefined, width: 42, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 42}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(XUICheckboxInput60, {x: 337}) ) ) ); } if (props.x === 343) { return React.createElement( 'div', { label: 'Campaign Name', width: 400, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 400}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 342}) ) ) ); } if (props.x === 349) { return React.createElement( 'div', { label: undefined, width: 33, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 33}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 348}) ) ) ); } if (props.x === 355) { return React.createElement( 'div', { label: undefined, width: 36, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 36}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 354}) ) ) ); } if (props.x === 360) { return React.createElement( 'div', { label: 'Status', width: 60, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 60}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 359}) ) ) ); } if (props.x === 365) { return React.createElement( 'div', { label: 'Delivery', width: 150, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 150}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 364}) ) ) ); } if (props.x === 372) { return React.createElement( 'div', { label: 'Results', width: 140, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 140}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 371}) ) ) ); } if (props.x === 377) { return React.createElement( 'div', { label: 'Cost', width: 140, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 140}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 376}) ) ) ); } if (props.x === 382) { return React.createElement( 'div', { label: 'Reach', width: 80, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 80}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 381}) ) ) ); } if (props.x === 387) { return React.createElement( 'div', { label: 'Impressions', width: 80, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 80}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 386}) ) ) ); } if (props.x === 392) { return React.createElement( 'div', { label: 'Clicks', width: 60, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 60}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 391}) ) ) ); } if (props.x === 397) { return React.createElement( 'div', { label: 'Avg. CPM', width: 80, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 80}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 396}) ) ) ); } if (props.x === 402) { return React.createElement( 'div', { label: 'Avg. CPC', width: 78, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 78}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 401}) ) ) ); } if (props.x === 407) { return React.createElement( 'div', { label: 'CTR %', width: 70, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 70}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 406}) ) ) ); } if (props.x === 412) { return React.createElement( 'div', { label: 'Spent', width: 70, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 70}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 411}) ) ) ); } if (props.x === 417) { return React.createElement( 'div', { label: 'Objective', width: 200, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 200}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 416}) ) ) ); } if (props.x === 422) { return React.createElement( 'div', { label: 'Buying Type', width: 100, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 100}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 421}) ) ) ); } if (props.x === 427) { return React.createElement( 'div', { label: 'Campaign ID', width: 120, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 120}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 426}) ) ) ); } if (props.x === 432) { return React.createElement( 'div', { label: 'Start', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 431}) ) ) ); } if (props.x === 437) { return React.createElement( 'div', { label: 'End', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 436}) ) ) ); } if (props.x === 442) { return React.createElement( 'div', { label: 'Date created', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 441}) ) ) ); } if (props.x === 447) { return React.createElement( 'div', { label: 'Date last edited', width: 113, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 113}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(FixedDataTableSortableHeader149, {x: 446}) ) ) ); } if (props.x === 450) { return React.createElement( 'div', { label: 'Tags', width: 150, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 150}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 449}) ) ) ); } if (props.x === 453) { return React.createElement( 'div', { label: '', width: 25, className: '_4lgc _4h2u', height: 25, style: {height: 25, width: 25}, }, React.createElement( 'div', {className: '_4lgd _4h2w'}, React.createElement( 'div', {className: '_4lge _4h2x'}, React.createElement(AdsPETableHeader141, {x: 452}) ) ) ); } }; var FixedDataTableCell143 = function (props) { if (props.x === 317) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 721, left: 0}}, undefined, React.createElement(TransitionCell142, {x: 316}) ); } if (props.x === 322) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 798, left: 0}}, undefined, React.createElement(TransitionCell142, {x: 321}) ); } if (props.x === 325) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 1022, left: 798}}, undefined, React.createElement(TransitionCell142, {x: 324}) ); } if (props.x === 328) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 0, left: 1820}}, undefined, React.createElement(TransitionCell142, {x: 327}) ); } if (props.x === 331) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 40, width: 25, left: 1820}}, undefined, React.createElement(TransitionCell142, {x: 330}) ); } if (props.x === 339) { return React.createElement( 'div', { className: '_4lg0 _4lg6 _4h2m', style: {height: 25, width: 42, left: 0}, }, undefined, React.createElement(TransitionCell142, {x: 338}) ); } if (props.x === 344) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 400, left: 42}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 343}) ); } if (props.x === 350) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 33, left: 442}}, undefined, React.createElement(TransitionCell142, {x: 349}) ); } if (props.x === 356) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 36, left: 475}}, undefined, React.createElement(TransitionCell142, {x: 355}) ); } if (props.x === 361) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 60, left: 511}}, undefined, React.createElement(TransitionCell142, {x: 360}) ); } if (props.x === 366) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 150, left: 571}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 365}) ); } if (props.x === 373) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 140, left: 0}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 372}) ); } if (props.x === 378) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 140, left: 140}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 377}) ); } if (props.x === 383) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 80, left: 280}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 382}) ); } if (props.x === 388) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 80, left: 360}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 387}) ); } if (props.x === 393) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 60, left: 440}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 392}) ); } if (props.x === 398) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 80, left: 500}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 397}) ); } if (props.x === 403) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 78, left: 580}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 402}) ); } if (props.x === 408) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 70, left: 658}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 407}) ); } if (props.x === 413) { return React.createElement( 'div', { className: '_4lg0 _4lg5 _4h2p _4h2m', style: {height: 25, width: 70, left: 728}, }, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 412}) ); } if (props.x === 418) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 200, left: 798}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 417}) ); } if (props.x === 423) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 100, left: 998}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 422}) ); } if (props.x === 428) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 120, left: 1098}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 427}) ); } if (props.x === 433) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1218}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 432}) ); } if (props.x === 438) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1331}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 437}) ); } if (props.x === 443) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1444}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 442}) ); } if (props.x === 448) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 113, left: 1557}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 447}) ); } if (props.x === 451) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 150, left: 1670}}, React.createElement( 'div', { className: '_4lg9', style: {height: 25}, onMouseDown: function () {}, }, React.createElement('div', { className: '_4lga _4lgb', style: {height: 25}, }) ), React.createElement(TransitionCell142, {x: 450}) ); } if (props.x === 454) { return React.createElement( 'div', {className: '_4lg0 _4h2m', style: {height: 25, width: 25, left: 1820}}, undefined, React.createElement(TransitionCell142, {x: 453}) ); } }; var FixedDataTableCellGroupImpl144 = function (props) { if (props.x === 318) { return React.createElement( 'div', { className: '_3pzj', style: { height: 40, position: 'absolute', width: 721, zIndex: 2, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, React.createElement(FixedDataTableCell143, {x: 317, key: 'cell_0'}) ); } if (props.x === 332) { return React.createElement( 'div', { className: '_3pzj', style: { height: 40, position: 'absolute', width: 1845, zIndex: 0, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, React.createElement(FixedDataTableCell143, {x: 322, key: 'cell_0'}), React.createElement(FixedDataTableCell143, {x: 325, key: 'cell_1'}), React.createElement(FixedDataTableCell143, {x: 328, key: 'cell_2'}), React.createElement(FixedDataTableCell143, {x: 331, key: 'cell_3'}) ); } if (props.x === 367) { return React.createElement( 'div', { className: '_3pzj', style: { height: 25, position: 'absolute', width: 721, zIndex: 2, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, React.createElement(FixedDataTableCell143, {x: 339, key: 'cell_0'}), React.createElement(FixedDataTableCell143, {x: 344, key: 'cell_1'}), React.createElement(FixedDataTableCell143, {x: 350, key: 'cell_2'}), React.createElement(FixedDataTableCell143, {x: 356, key: 'cell_3'}), React.createElement(FixedDataTableCell143, {x: 361, key: 'cell_4'}), React.createElement(FixedDataTableCell143, {x: 366, key: 'cell_5'}) ); } if (props.x === 455) { return React.createElement( 'div', { className: '_3pzj', style: { height: 25, position: 'absolute', width: 1845, zIndex: 0, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, React.createElement(FixedDataTableCell143, {x: 373, key: 'cell_0'}), React.createElement(FixedDataTableCell143, {x: 378, key: 'cell_1'}), React.createElement(FixedDataTableCell143, {x: 383, key: 'cell_2'}), React.createElement(FixedDataTableCell143, {x: 388, key: 'cell_3'}), React.createElement(FixedDataTableCell143, {x: 393, key: 'cell_4'}), React.createElement(FixedDataTableCell143, {x: 398, key: 'cell_5'}), React.createElement(FixedDataTableCell143, {x: 403, key: 'cell_6'}), React.createElement(FixedDataTableCell143, {x: 408, key: 'cell_7'}), React.createElement(FixedDataTableCell143, {x: 413, key: 'cell_8'}), React.createElement(FixedDataTableCell143, {x: 418, key: 'cell_9'}), React.createElement(FixedDataTableCell143, {x: 423, key: 'cell_10'}), React.createElement(FixedDataTableCell143, {x: 428, key: 'cell_11'}), React.createElement(FixedDataTableCell143, {x: 433, key: 'cell_12'}), React.createElement(FixedDataTableCell143, {x: 438, key: 'cell_13'}), React.createElement(FixedDataTableCell143, {x: 443, key: 'cell_14'}), React.createElement(FixedDataTableCell143, {x: 448, key: 'cell_15'}), React.createElement(FixedDataTableCell143, {x: 451, key: 'cell_16'}), React.createElement(FixedDataTableCell143, {x: 454, key: 'cell_17'}) ); } }; var FixedDataTableCellGroup145 = function (props) { if (props.x === 319) { return React.createElement( 'div', {style: {height: 40, left: 0}, className: '_3pzk'}, React.createElement(FixedDataTableCellGroupImpl144, {x: 318}) ); } if (props.x === 333) { return React.createElement( 'div', {style: {height: 40, left: 721}, className: '_3pzk'}, React.createElement(FixedDataTableCellGroupImpl144, {x: 332}) ); } if (props.x === 368) { return React.createElement( 'div', {style: {height: 25, left: 0}, className: '_3pzk'}, React.createElement(FixedDataTableCellGroupImpl144, {x: 367}) ); } if (props.x === 456) { return React.createElement( 'div', {style: {height: 25, left: 721}, className: '_3pzk'}, React.createElement(FixedDataTableCellGroupImpl144, {x: 455}) ); } }; var FixedDataTableRowImpl146 = function (props) { if (props.x === 334) { return React.createElement( 'div', { className: '_1gd4 _4li _52no _3h1a _1mib', onClick: null, onDoubleClick: null, onMouseDown: null, onMouseEnter: null, onMouseLeave: null, style: {width: 1209, height: 40}, }, React.createElement( 'div', {className: '_1gd5'}, React.createElement(FixedDataTableCellGroup145, { x: 319, key: 'fixed_cells', }), React.createElement(FixedDataTableCellGroup145, { x: 333, key: 'scrollable_cells', }), React.createElement('div', { className: '_1gd6 _1gd8', style: {left: 721, height: 40}, }) ) ); } if (props.x === 457) { return React.createElement( 'div', { className: '_1gd4 _4li _3h1a _1mib', onClick: null, onDoubleClick: null, onMouseDown: null, onMouseEnter: null, onMouseLeave: null, style: {width: 1209, height: 25}, }, React.createElement( 'div', {className: '_1gd5'}, React.createElement(FixedDataTableCellGroup145, { x: 368, key: 'fixed_cells', }), React.createElement(FixedDataTableCellGroup145, { x: 456, key: 'scrollable_cells', }), React.createElement('div', { className: '_1gd6 _1gd8', style: {left: 721, height: 25}, }) ) ); } }; var FixedDataTableRow147 = function (props) { if (props.x === 335) { return React.createElement( 'div', { style: { width: 1209, height: 40, zIndex: 1, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, className: '_1gda', }, React.createElement(FixedDataTableRowImpl146, {x: 334}) ); } if (props.x === 458) { return React.createElement( 'div', { style: { width: 1209, height: 25, zIndex: 1, transform: 'translate3d(0px,40px,0)', backfaceVisibility: 'hidden', }, className: '_1gda', }, React.createElement(FixedDataTableRowImpl146, {x: 457}) ); } }; var FixedDataTableAbstractSortableHeader148 = function (props) { if (props.x === 341) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 340}) ) ); } if (props.x === 347) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _1kst _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 346}) ) ); } if (props.x === 353) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _1kst _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 352}) ) ); } if (props.x === 358) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 357}) ) ); } if (props.x === 363) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _54_9 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 362}) ) ); } if (props.x === 370) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 369}) ) ); } if (props.x === 375) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 374}) ) ); } if (props.x === 380) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 379}) ) ); } if (props.x === 385) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 384}) ) ); } if (props.x === 390) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 389}) ) ); } if (props.x === 395) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 394}) ) ); } if (props.x === 400) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 399}) ) ); } if (props.x === 405) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 404}) ) ); } if (props.x === 410) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 409}) ) ); } if (props.x === 415) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 414}) ) ); } if (props.x === 420) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 419}) ) ); } if (props.x === 425) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 424}) ) ); } if (props.x === 430) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 429}) ) ); } if (props.x === 435) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 434}) ) ); } if (props.x === 440) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 439}) ) ); } if (props.x === 445) { return React.createElement( 'div', {onClick: function () {}, className: '_54_8 _4h2r _2wzx'}, React.createElement( 'div', {className: '_2eq6'}, null, React.createElement(AdsPETableHeader141, {x: 444}) ) ); } }; var FixedDataTableSortableHeader149 = function (props) { if (props.x === 342) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 341, }); } if (props.x === 348) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 347, }); } if (props.x === 354) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 353, }); } if (props.x === 359) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 358, }); } if (props.x === 364) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 363, }); } if (props.x === 371) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 370, }); } if (props.x === 376) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 375, }); } if (props.x === 381) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 380, }); } if (props.x === 386) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 385, }); } if (props.x === 391) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 390, }); } if (props.x === 396) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 395, }); } if (props.x === 401) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 400, }); } if (props.x === 406) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 405, }); } if (props.x === 411) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 410, }); } if (props.x === 416) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 415, }); } if (props.x === 421) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 420, }); } if (props.x === 426) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 425, }); } if (props.x === 431) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 430, }); } if (props.x === 436) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 435, }); } if (props.x === 441) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 440, }); } if (props.x === 446) { return React.createElement(FixedDataTableAbstractSortableHeader148, { x: 445, }); } }; var FixedDataTableBufferedRows150 = function (props) { if (props.x === 459) { return React.createElement('div', { style: { position: 'absolute', pointerEvents: 'auto', transform: 'translate3d(0px,65px,0)', backfaceVisibility: 'hidden', }, }); } }; var Scrollbar151 = function (props) { if (props.x === 460) { return null; } if (props.x === 461) { return React.createElement( 'div', { onFocus: function () {}, onBlur: function () {}, onKeyDown: function () {}, onMouseDown: function () {}, onWheel: function () {}, className: '_1t0r _1t0t _4jdr _1t0u', style: {width: 1209, zIndex: 99}, tabIndex: 0, }, React.createElement('div', { className: '_1t0w _1t0y _1t0_', style: { width: 561.6340607950117, transform: 'translate3d(4px,0px,0)', backfaceVisibility: 'hidden', }, }) ); } }; var HorizontalScrollbar152 = function (props) { if (props.x === 462) { return React.createElement( 'div', {className: '_3h1k _3h1m', style: {height: 15, width: 1209}}, React.createElement( 'div', { style: { height: 15, position: 'absolute', overflow: 'hidden', width: 1209, transform: 'translate3d(0px,0px,0)', backfaceVisibility: 'hidden', }, }, React.createElement(Scrollbar151, {x: 461}) ) ); } }; var FixedDataTable153 = function (props) { if (props.x === 463) { return React.createElement( 'div', { className: '_3h1i _1mie', onWheel: function () {}, style: {height: 25, width: 1209}, }, React.createElement( 'div', {className: '_3h1j', style: {height: 8, width: 1209}}, React.createElement(FixedDataTableColumnResizeHandle140, {x: 313}), React.createElement(FixedDataTableRow147, { x: 335, key: 'group_header', }), React.createElement(FixedDataTableRow147, {x: 458, key: 'header'}), React.createElement(FixedDataTableBufferedRows150, {x: 459}), null, undefined, React.createElement('div', { className: '_3h1e _3h1h', style: {top: 8}, }) ), React.createElement(Scrollbar151, {x: 460}), React.createElement(HorizontalScrollbar152, {x: 462}) ); } }; var TransitionTable154 = function (props) { if (props.x === 464) { return React.createElement(FixedDataTable153, {x: 463}); } }; var AdsSelectableFixedDataTable155 = function (props) { if (props.x === 465) { return React.createElement( 'div', {className: '_5hht'}, React.createElement(TransitionTable154, {x: 464}) ); } }; var AdsDataTableKeyboardSupportDecorator156 = function (props) { if (props.x === 466) { return React.createElement( 'div', {className: '_5d6f', tabIndex: '0', onKeyDown: function () {}}, React.createElement(AdsSelectableFixedDataTable155, {x: 465}) ); } }; var AdsEditableDataTableDecorator157 = function (props) { if (props.x === 467) { return React.createElement( 'div', {onCopy: function () {}}, React.createElement(AdsDataTableKeyboardSupportDecorator156, {x: 466}) ); } }; var AdsPEDataTableContainer158 = function (props) { if (props.x === 468) { return React.createElement( 'div', {className: '_35l_ _1hr clearfix'}, null, null, null, React.createElement(AdsEditableDataTableDecorator157, {x: 467}) ); } }; var AdsPECampaignGroupTableContainer159 = function (props) { if (props.x === 470) { return React.createElement(ResponsiveBlock37, {x: 469}); } }; var AdsPEManageAdsPaneContainer160 = function (props) { if (props.x === 473) { return React.createElement( 'div', null, React.createElement(AdsErrorBoundary10, {x: 65}), React.createElement( 'div', {className: '_2uty'}, React.createElement(AdsErrorBoundary10, {x: 125}) ), React.createElement( 'div', {className: '_2utx _21oc'}, React.createElement(AdsErrorBoundary10, {x: 171}), React.createElement( 'div', {className: '_41tu'}, React.createElement(AdsErrorBoundary10, {x: 176}), React.createElement(AdsErrorBoundary10, {x: 194}) ) ), React.createElement( 'div', {className: '_2utz', style: {height: 25}}, React.createElement(AdsErrorBoundary10, {x: 302}), React.createElement( 'div', {className: '_2ut-'}, React.createElement(AdsErrorBoundary10, {x: 312}) ), React.createElement( 'div', {className: '_2ut_'}, React.createElement(AdsErrorBoundary10, {x: 472}) ) ) ); } }; var AdsPEContentContainer161 = function (props) { if (props.x === 474) { return React.createElement(AdsPEManageAdsPaneContainer160, {x: 473}); } }; var FluxContainer_AdsPEWorkspaceContainer_162 = function (props) { if (props.x === 477) { return React.createElement( 'div', {className: '_49wu', style: {height: 177, top: 43, width: 1306}}, React.createElement(ResponsiveBlock37, {x: 62, key: '0'}), React.createElement(AdsErrorBoundary10, {x: 476, key: '1'}), null ); } }; var FluxContainer_AdsSessionExpiredDialogContainer_163 = function (props) { if (props.x === 478) { return null; } }; var FluxContainer_AdsPEUploadDialogLazyContainer_164 = function (props) { if (props.x === 479) { return null; } }; var FluxContainer_DialogContainer_165 = function (props) { if (props.x === 480) { return null; } }; var AdsBugReportContainer166 = function (props) { if (props.x === 481) { return React.createElement('span', null); } }; var AdsPEAudienceSplittingDialog167 = function (props) { if (props.x === 482) { return null; } }; var AdsPEAudienceSplittingDialogContainer168 = function (props) { if (props.x === 483) { return React.createElement( 'div', null, React.createElement(AdsPEAudienceSplittingDialog167, {x: 482}) ); } }; var FluxContainer_AdsRuleDialogBootloadContainer_169 = function (props) { if (props.x === 484) { return null; } }; var FluxContainer_AdsPECFTrayContainer_170 = function (props) { if (props.x === 485) { return null; } }; var FluxContainer_AdsPEDeleteDraftContainer_171 = function (props) { if (props.x === 486) { return null; } }; var FluxContainer_AdsPEInitialDraftPublishDialogContainer_172 = function ( props ) { if (props.x === 487) { return null; } }; var FluxContainer_AdsPEReachFrequencyStatusTransitionDialogBootloadContainer_173 = function (props) { if (props.x === 488) { return null; } }; var FluxContainer_AdsPEPurgeArchiveDialogContainer_174 = function (props) { if (props.x === 489) { return null; } }; var AdsPECreateDialogContainer175 = function (props) { if (props.x === 490) { return React.createElement('span', null); } }; var FluxContainer_AdsPEModalStatusContainer_176 = function (props) { if (props.x === 491) { return null; } }; var FluxContainer_AdsBrowserExtensionErrorDialogContainer_177 = function ( props ) { if (props.x === 492) { return null; } }; var FluxContainer_AdsPESortByErrorTipContainer_178 = function (props) { if (props.x === 493) { return null; } }; var LeadDownloadDialogSelector179 = function (props) { if (props.x === 494) { return null; } }; var FluxContainer_AdsPELeadDownloadDialogContainerClass_180 = function ( props ) { if (props.x === 495) { return React.createElement(LeadDownloadDialogSelector179, {x: 494}); } }; var AdsPEContainer181 = function (props) { if (props.x === 496) { return React.createElement( 'div', {id: 'ads_pe_container'}, React.createElement(FluxContainer_AdsPETopNavContainer_26, {x: 41}), null, React.createElement(FluxContainer_AdsPEWorkspaceContainer_162, { x: 477, }), React.createElement( FluxContainer_AdsSessionExpiredDialogContainer_163, {x: 478} ), React.createElement(FluxContainer_AdsPEUploadDialogLazyContainer_164, { x: 479, }), React.createElement(FluxContainer_DialogContainer_165, {x: 480}), React.createElement(AdsBugReportContainer166, {x: 481}), React.createElement(AdsPEAudienceSplittingDialogContainer168, {x: 483}), React.createElement(FluxContainer_AdsRuleDialogBootloadContainer_169, { x: 484, }), React.createElement(FluxContainer_AdsPECFTrayContainer_170, {x: 485}), React.createElement( 'span', null, React.createElement(FluxContainer_AdsPEDeleteDraftContainer_171, { x: 486, }), React.createElement( FluxContainer_AdsPEInitialDraftPublishDialogContainer_172, {x: 487} ), React.createElement( FluxContainer_AdsPEReachFrequencyStatusTransitionDialogBootloadContainer_173, {x: 488} ) ), React.createElement( FluxContainer_AdsPEPurgeArchiveDialogContainer_174, {x: 489} ), React.createElement(AdsPECreateDialogContainer175, {x: 490}), React.createElement(FluxContainer_AdsPEModalStatusContainer_176, { x: 491, }), React.createElement( FluxContainer_AdsBrowserExtensionErrorDialogContainer_177, {x: 492} ), React.createElement(FluxContainer_AdsPESortByErrorTipContainer_178, { x: 493, }), React.createElement( FluxContainer_AdsPELeadDownloadDialogContainerClass_180, {x: 495} ), React.createElement('div', {id: 'web_ads_guidance_tips'}) ); } }; var Benchmark = function (props) { if (props.x === undefined) { return React.createElement(AdsPEContainer181, {x: 496}); } }; var app = document.getElementById('app'); window.render = function render() { ReactDOM.render(React.createElement(Benchmark, null), app); }; })();
25.982819
89
0.502876
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 const DPR: number = window.devicePixelRatio || 1; export const LABEL_SIZE = 80; export const MARKER_HEIGHT = 20; export const MARKER_TICK_HEIGHT = 8; export const FONT_SIZE = 10; export const MARKER_TEXT_PADDING = 8; export const COLOR_HOVER_DIM_DELTA = 5; export const TOP_ROW_PADDING = 4; export const NATIVE_EVENT_HEIGHT = 14; export const SUSPENSE_EVENT_HEIGHT = 14; export const PENDING_SUSPENSE_EVENT_SIZE = 8; export const REACT_EVENT_DIAMETER = 6; export const USER_TIMING_MARK_SIZE = 8; export const REACT_MEASURE_HEIGHT = 14; export const BORDER_SIZE = 1 / DPR; export const FLAMECHART_FRAME_HEIGHT = 14; export const TEXT_PADDING = 3; export const SNAPSHOT_SCRUBBER_SIZE = 3; export const INTERVAL_TIMES = [ 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, ]; export const MIN_INTERVAL_SIZE_PX = 70; // TODO Replace this with "export let" vars export let COLORS: { BACKGROUND: string, INTERNAL_MODULE_FRAME: string, INTERNAL_MODULE_FRAME_HOVER: string, INTERNAL_MODULE_FRAME_TEXT: string, NATIVE_EVENT: string, NATIVE_EVENT_HOVER: string, NETWORK_PRIMARY: string, NETWORK_PRIMARY_HOVER: string, NETWORK_SECONDARY: string, NETWORK_SECONDARY_HOVER: string, PRIORITY_BACKGROUND: string, PRIORITY_BORDER: string, PRIORITY_LABEL: string, REACT_COMMIT: string, REACT_COMMIT_HOVER: string, REACT_COMMIT_TEXT: string, REACT_IDLE: string, REACT_IDLE_HOVER: string, REACT_LAYOUT_EFFECTS: string, REACT_LAYOUT_EFFECTS_HOVER: string, REACT_LAYOUT_EFFECTS_TEXT: string, REACT_PASSIVE_EFFECTS: string, REACT_PASSIVE_EFFECTS_HOVER: string, REACT_PASSIVE_EFFECTS_TEXT: string, REACT_RENDER: string, REACT_RENDER_HOVER: string, REACT_RENDER_TEXT: string, REACT_RESIZE_BAR: string, REACT_RESIZE_BAR_ACTIVE: string, REACT_RESIZE_BAR_BORDER: string, REACT_RESIZE_BAR_DOT: string, REACT_SCHEDULE: string, REACT_SCHEDULE_HOVER: string, REACT_SUSPENSE_REJECTED_EVENT: string, REACT_SUSPENSE_REJECTED_EVENT_HOVER: string, REACT_SUSPENSE_RESOLVED_EVENT: string, REACT_SUSPENSE_RESOLVED_EVENT_HOVER: string, REACT_SUSPENSE_UNRESOLVED_EVENT: string, REACT_SUSPENSE_UNRESOLVED_EVENT_HOVER: string, REACT_THROWN_ERROR: string, REACT_THROWN_ERROR_HOVER: string, REACT_WORK_BORDER: string, SCROLL_CARET: string, SCRUBBER_BACKGROUND: string, SCRUBBER_BORDER: string, SEARCH_RESULT_FILL: string, TEXT_COLOR: string, TEXT_DIM_COLOR: string, TIME_MARKER_LABEL: string, USER_TIMING: string, USER_TIMING_HOVER: string, WARNING_BACKGROUND: string, WARNING_BACKGROUND_HOVER: string, WARNING_TEXT: string, WARNING_TEXT_INVERED: string, } = { BACKGROUND: '', INTERNAL_MODULE_FRAME: '', INTERNAL_MODULE_FRAME_HOVER: '', INTERNAL_MODULE_FRAME_TEXT: '', NATIVE_EVENT: '', NATIVE_EVENT_HOVER: '', NETWORK_PRIMARY: '', NETWORK_PRIMARY_HOVER: '', NETWORK_SECONDARY: '', NETWORK_SECONDARY_HOVER: '', PRIORITY_BACKGROUND: '', PRIORITY_BORDER: '', PRIORITY_LABEL: '', USER_TIMING: '', USER_TIMING_HOVER: '', REACT_IDLE: '', REACT_IDLE_HOVER: '', REACT_RENDER: '', REACT_RENDER_HOVER: '', REACT_RENDER_TEXT: '', REACT_COMMIT: '', REACT_COMMIT_HOVER: '', REACT_COMMIT_TEXT: '', REACT_LAYOUT_EFFECTS: '', REACT_LAYOUT_EFFECTS_HOVER: '', REACT_LAYOUT_EFFECTS_TEXT: '', REACT_PASSIVE_EFFECTS: '', REACT_PASSIVE_EFFECTS_HOVER: '', REACT_PASSIVE_EFFECTS_TEXT: '', REACT_RESIZE_BAR: '', REACT_RESIZE_BAR_ACTIVE: '', REACT_RESIZE_BAR_BORDER: '', REACT_RESIZE_BAR_DOT: '', REACT_SCHEDULE: '', REACT_SCHEDULE_HOVER: '', REACT_SUSPENSE_REJECTED_EVENT: '', REACT_SUSPENSE_REJECTED_EVENT_HOVER: '', REACT_SUSPENSE_RESOLVED_EVENT: '', REACT_SUSPENSE_RESOLVED_EVENT_HOVER: '', REACT_SUSPENSE_UNRESOLVED_EVENT: '', REACT_SUSPENSE_UNRESOLVED_EVENT_HOVER: '', REACT_THROWN_ERROR: '', REACT_THROWN_ERROR_HOVER: '', REACT_WORK_BORDER: '', SCROLL_CARET: '', SCRUBBER_BACKGROUND: '', SCRUBBER_BORDER: '', SEARCH_RESULT_FILL: '', TEXT_COLOR: '', TEXT_DIM_COLOR: '', TIME_MARKER_LABEL: '', WARNING_BACKGROUND: '', WARNING_BACKGROUND_HOVER: '', WARNING_TEXT: '', WARNING_TEXT_INVERED: '', }; export function updateColorsToMatchTheme(element: Element): boolean { const computedStyle = getComputedStyle(element); // Check to see if styles have been initialized... if (computedStyle.getPropertyValue('--color-background') == null) { return false; } COLORS = { BACKGROUND: computedStyle.getPropertyValue('--color-background'), INTERNAL_MODULE_FRAME: computedStyle.getPropertyValue( '--color-timeline-internal-module', ), INTERNAL_MODULE_FRAME_HOVER: computedStyle.getPropertyValue( '--color-timeline-internal-module-hover', ), INTERNAL_MODULE_FRAME_TEXT: computedStyle.getPropertyValue( '--color-timeline-internal-module-text', ), NATIVE_EVENT: computedStyle.getPropertyValue( '--color-timeline-native-event', ), NATIVE_EVENT_HOVER: computedStyle.getPropertyValue( '--color-timeline-native-event-hover', ), NETWORK_PRIMARY: computedStyle.getPropertyValue( '--color-timeline-network-primary', ), NETWORK_PRIMARY_HOVER: computedStyle.getPropertyValue( '--color-timeline-network-primary-hover', ), NETWORK_SECONDARY: computedStyle.getPropertyValue( '--color-timeline-network-secondary', ), NETWORK_SECONDARY_HOVER: computedStyle.getPropertyValue( '--color-timeline-network-secondary-hover', ), PRIORITY_BACKGROUND: computedStyle.getPropertyValue( '--color-timeline-priority-background', ), PRIORITY_BORDER: computedStyle.getPropertyValue( '--color-timeline-priority-border', ), PRIORITY_LABEL: computedStyle.getPropertyValue('--color-text'), USER_TIMING: computedStyle.getPropertyValue('--color-timeline-user-timing'), USER_TIMING_HOVER: computedStyle.getPropertyValue( '--color-timeline-user-timing-hover', ), REACT_IDLE: computedStyle.getPropertyValue('--color-timeline-react-idle'), REACT_IDLE_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-idle-hover', ), REACT_RENDER: computedStyle.getPropertyValue( '--color-timeline-react-render', ), REACT_RENDER_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-render-hover', ), REACT_RENDER_TEXT: computedStyle.getPropertyValue( '--color-timeline-react-render-text', ), REACT_COMMIT: computedStyle.getPropertyValue( '--color-timeline-react-commit', ), REACT_COMMIT_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-commit-hover', ), REACT_COMMIT_TEXT: computedStyle.getPropertyValue( '--color-timeline-react-commit-text', ), REACT_LAYOUT_EFFECTS: computedStyle.getPropertyValue( '--color-timeline-react-layout-effects', ), REACT_LAYOUT_EFFECTS_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-layout-effects-hover', ), REACT_LAYOUT_EFFECTS_TEXT: computedStyle.getPropertyValue( '--color-timeline-react-layout-effects-text', ), REACT_PASSIVE_EFFECTS: computedStyle.getPropertyValue( '--color-timeline-react-passive-effects', ), REACT_PASSIVE_EFFECTS_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-passive-effects-hover', ), REACT_PASSIVE_EFFECTS_TEXT: computedStyle.getPropertyValue( '--color-timeline-react-passive-effects-text', ), REACT_RESIZE_BAR: computedStyle.getPropertyValue('--color-resize-bar'), REACT_RESIZE_BAR_ACTIVE: computedStyle.getPropertyValue( '--color-resize-bar-active', ), REACT_RESIZE_BAR_BORDER: computedStyle.getPropertyValue( '--color-resize-bar-border', ), REACT_RESIZE_BAR_DOT: computedStyle.getPropertyValue( '--color-resize-bar-dot', ), REACT_SCHEDULE: computedStyle.getPropertyValue( '--color-timeline-react-schedule', ), REACT_SCHEDULE_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-schedule-hover', ), REACT_SUSPENSE_REJECTED_EVENT: computedStyle.getPropertyValue( '--color-timeline-react-suspense-rejected', ), REACT_SUSPENSE_REJECTED_EVENT_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-suspense-rejected-hover', ), REACT_SUSPENSE_RESOLVED_EVENT: computedStyle.getPropertyValue( '--color-timeline-react-suspense-resolved', ), REACT_SUSPENSE_RESOLVED_EVENT_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-suspense-resolved-hover', ), REACT_SUSPENSE_UNRESOLVED_EVENT: computedStyle.getPropertyValue( '--color-timeline-react-suspense-unresolved', ), REACT_SUSPENSE_UNRESOLVED_EVENT_HOVER: computedStyle.getPropertyValue( '--color-timeline-react-suspense-unresolved-hover', ), REACT_THROWN_ERROR: computedStyle.getPropertyValue( '--color-timeline-thrown-error', ), REACT_THROWN_ERROR_HOVER: computedStyle.getPropertyValue( '--color-timeline-thrown-error-hover', ), REACT_WORK_BORDER: computedStyle.getPropertyValue( '--color-timeline-react-work-border', ), SCROLL_CARET: computedStyle.getPropertyValue('--color-scroll-caret'), SCRUBBER_BACKGROUND: computedStyle.getPropertyValue( '--color-timeline-react-suspense-rejected', ), SEARCH_RESULT_FILL: computedStyle.getPropertyValue( '--color-timeline-react-suspense-rejected', ), SCRUBBER_BORDER: computedStyle.getPropertyValue( '--color-timeline-text-color', ), TEXT_COLOR: computedStyle.getPropertyValue('--color-timeline-text-color'), TEXT_DIM_COLOR: computedStyle.getPropertyValue( '--color-timeline-text-dim-color', ), TIME_MARKER_LABEL: computedStyle.getPropertyValue('--color-text'), WARNING_BACKGROUND: computedStyle.getPropertyValue( '--color-warning-background', ), WARNING_BACKGROUND_HOVER: computedStyle.getPropertyValue( '--color-warning-background-hover', ), WARNING_TEXT: computedStyle.getPropertyValue('--color-warning-text-color'), WARNING_TEXT_INVERED: computedStyle.getPropertyValue( '--color-warning-text-color-inverted', ), }; return true; }
32.89644
80
0.702569
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 {Source} from 'shared/ReactElementType'; import type { RefObject, ReactContext, StartTransitionOptions, Wakeable, Usable, ReactFormState, Awaited, } from 'shared/ReactTypes'; import type {WorkTag} from './ReactWorkTags'; import type {TypeOfMode} from './ReactTypeOfMode'; import type {Flags} from './ReactFiberFlags'; import type {Lane, Lanes, LaneMap} from './ReactFiberLane'; import type {RootTag} from './ReactRootTags'; import type { Container, TimeoutHandle, NoTimeout, SuspenseInstance, TransitionStatus, } from './ReactFiberConfig'; import type {Cache} from './ReactFiberCacheComponent'; import type { TracingMarkerInstance, Transition, } from './ReactFiberTracingMarkerComponent'; import type {ConcurrentUpdate} from './ReactFiberConcurrentUpdates'; // Unwind Circular: moved from ReactFiberHooks.old export type HookType = | 'useState' | 'useReducer' | 'useContext' | 'useRef' | 'useEffect' | 'useEffectEvent' | 'useInsertionEffect' | 'useLayoutEffect' | 'useCallback' | 'useMemo' | 'useImperativeHandle' | 'useDebugValue' | 'useDeferredValue' | 'useTransition' | 'useSyncExternalStore' | 'useId' | 'useCacheRefresh' | 'useOptimistic' | 'useFormState'; export type ContextDependency<T> = { context: ReactContext<T>, next: ContextDependency<mixed> | null, memoizedValue: T, ... }; export type Dependencies = { lanes: Lanes, firstContext: ContextDependency<mixed> | null, ... }; export type MemoCache = { data: Array<Array<any>>, index: number, }; // A Fiber is work on a Component that needs to be done or was done. There can // be more than one per component. export type Fiber = { // These first fields are conceptually members of an Instance. This used to // be split into a separate type and intersected with the other Fiber fields, // but until Flow fixes its intersection bugs, we've merged them into a // single type. // An Instance is shared between all versions of a component. We can easily // break this out into a separate object to avoid copying so much to the // alternate versions of the tree. We put this on a single object for now to // minimize the number of objects created during the initial render. // Tag identifying the type of fiber. tag: WorkTag, // Unique identifier of this child. key: null | string, // The value of element.type which is used to preserve the identity during // reconciliation of this child. elementType: any, // The resolved function/class/ associated with this fiber. type: any, // The local state associated with this fiber. stateNode: any, // Conceptual aliases // parent : Instance -> return The parent happens to be the same as the // return fiber since we've merged the fiber and instance. // Remaining fields belong to Fiber // The Fiber to return to after finishing processing this one. // This is effectively the parent, but there can be multiple parents (two) // so this is only the parent of the thing we're currently processing. // It is conceptually the same as the return address of a stack frame. return: Fiber | null, // Singly Linked List Tree Structure. child: Fiber | null, sibling: Fiber | null, index: number, // The ref last used to attach this node. // I'll avoid adding an owner field for prod and model that as functions. ref: | null | (((handle: mixed) => void) & {_stringRef: ?string, ...}) | RefObject, refCleanup: null | (() => void), // Input is the data coming into process this fiber. Arguments. Props. pendingProps: any, // This type will be more specific once we overload the tag. memoizedProps: any, // The props used to create the output. // A queue of state updates and callbacks. updateQueue: mixed, // The state used to create the output memoizedState: any, // Dependencies (contexts, events) for this fiber, if it has any dependencies: Dependencies | null, // Bitfield that describes properties about the fiber and its subtree. E.g. // the ConcurrentMode flag indicates whether the subtree should be async-by- // default. When a fiber is created, it inherits the mode of its // parent. Additional flags can be set at creation time, but after that the // value should remain unchanged throughout the fiber's lifetime, particularly // before its child fibers are created. mode: TypeOfMode, // Effect flags: Flags, subtreeFlags: Flags, deletions: Array<Fiber> | null, // Singly linked list fast path to the next fiber with side-effects. nextEffect: Fiber | null, // The first and last fiber with side-effect within this subtree. This allows // us to reuse a slice of the linked list when we reuse the work done within // this fiber. firstEffect: Fiber | null, lastEffect: Fiber | null, lanes: Lanes, childLanes: Lanes, // This is a pooled version of a Fiber. Every fiber that gets updated will // eventually have a pair. There are cases when we can clean up pairs to save // memory if we need to. alternate: Fiber | null, // Time spent rendering this Fiber and its descendants for the current update. // This tells us how well the tree makes use of sCU for memoization. // It is reset to 0 each time we render and only updated when we don't bailout. // This field is only set when the enableProfilerTimer flag is enabled. actualDuration?: number, // If the Fiber is currently active in the "render" phase, // This marks the time at which the work began. // This field is only set when the enableProfilerTimer flag is enabled. actualStartTime?: number, // Duration of the most recent render time for this Fiber. // This value is not updated when we bailout for memoization purposes. // This field is only set when the enableProfilerTimer flag is enabled. selfBaseDuration?: number, // Sum of base times for all descendants of this Fiber. // This value bubbles up during the "complete" phase. // This field is only set when the enableProfilerTimer flag is enabled. treeBaseDuration?: number, // Conceptual aliases // workInProgress : Fiber -> alternate The alternate used for reuse happens // to be the same as work in progress. // __DEV__ only _debugSource?: Source | null, _debugOwner?: Fiber | null, _debugIsCurrentlyTiming?: boolean, _debugNeedsRemount?: boolean, // Used to verify that the order of hooks does not change between renders. _debugHookTypes?: Array<HookType> | null, }; type BaseFiberRootProperties = { // The type of root (legacy, batched, concurrent, etc.) tag: RootTag, // Any additional information from the host associated with this root. containerInfo: Container, // Used only by persistent updates. pendingChildren: any, // The currently active root fiber. This is the mutable root of the tree. current: Fiber, pingCache: WeakMap<Wakeable, Set<mixed>> | Map<Wakeable, Set<mixed>> | null, // A finished work-in-progress HostRoot that's ready to be committed. finishedWork: Fiber | null, // Timeout handle returned by setTimeout. Used to cancel a pending timeout, if // it's superseded by a new one. timeoutHandle: TimeoutHandle | NoTimeout, // When a root has a pending commit scheduled, calling this function will // cancel it. // TODO: Can this be consolidated with timeoutHandle? cancelPendingCommit: null | (() => void), // Top context object, used by renderSubtreeIntoContainer context: Object | null, pendingContext: Object | null, // Used to create a linked list that represent all the roots that have // pending work scheduled on them. next: FiberRoot | null, // Node returned by Scheduler.scheduleCallback. Represents the next rendering // task that the root will work on. callbackNode: any, callbackPriority: Lane, expirationTimes: LaneMap<number>, hiddenUpdates: LaneMap<Array<ConcurrentUpdate> | null>, pendingLanes: Lanes, suspendedLanes: Lanes, pingedLanes: Lanes, expiredLanes: Lanes, errorRecoveryDisabledLanes: Lanes, shellSuspendCounter: number, finishedLanes: Lanes, entangledLanes: Lanes, entanglements: LaneMap<Lanes>, pooledCache: Cache | null, pooledCacheLanes: Lanes, // TODO: In Fizz, id generation is specific to each server config. Maybe we // should do this in Fiber, too? Deferring this decision for now because // there's no other place to store the prefix except for an internal field on // the public createRoot object, which the fiber tree does not currently have // a reference to. identifierPrefix: string, onRecoverableError: ( error: mixed, errorInfo: {digest?: ?string, componentStack?: ?string}, ) => void, formState: ReactFormState<any, any> | null, }; // The following attributes are only used by DevTools and are only present in DEV builds. // They enable DevTools Profiler UI to show which Fiber(s) scheduled a given commit. type UpdaterTrackingOnlyFiberRootProperties = { memoizedUpdaters: Set<Fiber>, pendingUpdatersLaneMap: LaneMap<Set<Fiber>>, }; export type SuspenseHydrationCallbacks = { onHydrated?: (suspenseInstance: SuspenseInstance) => void, onDeleted?: (suspenseInstance: SuspenseInstance) => void, ... }; // The follow fields are only used by enableSuspenseCallback for hydration. type SuspenseCallbackOnlyFiberRootProperties = { hydrationCallbacks: null | SuspenseHydrationCallbacks, }; export type TransitionTracingCallbacks = { onTransitionStart?: (transitionName: string, startTime: number) => void, onTransitionProgress?: ( transitionName: string, startTime: number, currentTime: number, pending: Array<{name: null | string}>, ) => void, onTransitionIncomplete?: ( transitionName: string, startTime: number, deletions: Array<{ type: string, name?: string | null, endTime: number, }>, ) => void, onTransitionComplete?: ( transitionName: string, startTime: number, endTime: number, ) => void, onMarkerProgress?: ( transitionName: string, marker: string, startTime: number, currentTime: number, pending: Array<{name: null | string}>, ) => void, onMarkerIncomplete?: ( transitionName: string, marker: string, startTime: number, deletions: Array<{ type: string, name?: string | null, endTime: number, }>, ) => void, onMarkerComplete?: ( transitionName: string, marker: string, startTime: number, endTime: number, ) => void, }; // The following fields are only used in transition tracing in Profile builds type TransitionTracingOnlyFiberRootProperties = { transitionCallbacks: null | TransitionTracingCallbacks, transitionLanes: Array<Set<Transition> | null>, // Transitions on the root can be represented as a bunch of tracing markers. // Each entangled group of transitions can be treated as a tracing marker. // It will have a set of pending suspense boundaries. These transitions // are considered complete when the pending suspense boundaries set is // empty. We can represent this as a Map of transitions to suspense // boundary sets incompleteTransitions: Map<Transition, TracingMarkerInstance>, }; // Exported FiberRoot type includes all properties, // To avoid requiring potentially error-prone :any casts throughout the project. // The types are defined separately within this file to ensure they stay in sync. export type FiberRoot = { ...BaseFiberRootProperties, ...SuspenseCallbackOnlyFiberRootProperties, ...UpdaterTrackingOnlyFiberRootProperties, ...TransitionTracingOnlyFiberRootProperties, ... }; type BasicStateAction<S> = (S => S) | S; type Dispatch<A> = A => void; export type Dispatcher = { use: <T>(Usable<T>) => T, readContext<T>(context: ReactContext<T>): T, useState<S>(initialState: (() => S) | S): [S, Dispatch<BasicStateAction<S>>], useReducer<S, I, A>( reducer: (S, A) => S, initialArg: I, init?: (I) => S, ): [S, Dispatch<A>], useContext<T>(context: ReactContext<T>): T, useRef<T>(initialValue: T): {current: T}, useEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void, useEffectEvent?: <Args, F: (...Array<Args>) => mixed>(callback: F) => F, useInsertionEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void, useLayoutEffect( create: () => (() => void) | void, deps: Array<mixed> | void | null, ): void, useCallback<T>(callback: T, deps: Array<mixed> | void | null): T, useMemo<T>(nextCreate: () => T, deps: Array<mixed> | void | null): T, useImperativeHandle<T>( ref: {current: T | null} | ((inst: T | null) => mixed) | null | void, create: () => T, deps: Array<mixed> | void | null, ): void, useDebugValue<T>(value: T, formatterFn: ?(value: T) => mixed): void, useDeferredValue<T>(value: T, initialValue?: T): T, useTransition(): [ boolean, (callback: () => void, options?: StartTransitionOptions) => void, ], useSyncExternalStore<T>( subscribe: (() => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T, ): T, useId(): string, useCacheRefresh?: () => <T>(?() => T, ?T) => void, useMemoCache?: (size: number) => Array<any>, useHostTransitionStatus?: () => TransitionStatus, useOptimistic?: <S, A>( passthrough: S, reducer: ?(S, A) => S, ) => [S, (A) => void], useFormState?: <S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ) => [Awaited<S>, (P) => void], }; export type CacheDispatcher = { getCacheSignal: () => AbortSignal, getCacheForType: <T>(resourceType: () => T) => T, };
31.233796
89
0.696208
Ethical-Hacking-Scripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Fragment, useDebugValue, useState} from 'react'; const div = document.createElement('div'); const exampleFunction = () => {}; const typedArray = new Uint8Array(3); typedArray[0] = 1; typedArray[1] = 2; typedArray[2] = 3; const arrayOfArrays = [ [ ['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j'], ], [ ['k', 'l', 'm'], ['n', 'o', 'p'], ['q', 'r', 's'], ], [['t', 'u', 'v'], ['w', 'x', 'y'], ['z']], [], ]; const objectOfObjects = { foo: { a: 1, b: 2, c: 3, }, bar: { e: 4, f: 5, g: 6, }, baz: { h: 7, i: 8, j: 9, }, qux: {}, }; function useOuterFoo() { useDebugValue({ debugA: { debugB: { debugC: 'abc', }, }, }); useState({ valueA: { valueB: { valueC: 'abc', }, }, }); return useInnerFoo(); } function useInnerFoo() { const [value] = useState([[['a', 'b', 'c']]]); return value; } function useOuterBar() { useDebugValue({ debugA: { debugB: { debugC: 'abc', }, }, }); return useInnerBar(); } function useInnerBar() { useDebugValue({ debugA: { debugB: { debugC: 'abc', }, }, }); const [count] = useState(123); return count; } function useOuterBaz() { return useInnerBaz(); } function useInnerBaz() { const [count] = useState(123); return count; } export default function Hydration(): React.Node { return ( <Fragment> <h1>Hydration</h1> <DehydratableProps html_element={div} fn={exampleFunction} symbol={Symbol('symbol')} react_element={<span />} array_buffer={typedArray.buffer} typed_array={typedArray} date={new Date()} array={arrayOfArrays} object={objectOfObjects} /> <DeepHooks /> </Fragment> ); } function DehydratableProps({array, object}: any) { return ( <ul> <li>array: {JSON.stringify(array, null, 2)}</li> <li>object: {JSON.stringify(object, null, 2)}</li> </ul> ); } function DeepHooks(props: any) { const foo = useOuterFoo(); const bar = useOuterBar(); const baz = useOuterBaz(); return ( <ul> <li>foo: {foo}</li> <li>bar: {bar}</li> <li>baz: {baz}</li> </ul> ); }
15.9
66
0.515785
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {useCallback, useContext, useEffect, useMemo, useRef} from 'react'; import {SettingsModalContext} from './SettingsModalContext'; import Button from '../Button'; import ButtonIcon from '../ButtonIcon'; import TabBar from '../TabBar'; import {StoreContext} from '../context'; import { useLocalStorage, useModalDismissSignal, useSubscription, } from '../hooks'; import ComponentsSettings from './ComponentsSettings'; import DebuggingSettings from './DebuggingSettings'; import GeneralSettings from './GeneralSettings'; import ProfilerSettings from './ProfilerSettings'; import styles from './SettingsModal.css'; type TabID = 'general' | 'components' | 'profiler'; export default function SettingsModal(_: {}): React.Node { const {isModalShowing, setIsModalShowing} = useContext(SettingsModalContext); const store = useContext(StoreContext); const {profilerStore} = store; // Updating preferences while profiling is in progress could break things (e.g. filtering) // Explicitly disallow it for now. const isProfilingSubscription = useMemo( () => ({ getCurrentValue: () => profilerStore.isProfiling, subscribe: (callback: Function) => { profilerStore.addListener('isProfiling', callback); return () => profilerStore.removeListener('isProfiling', callback); }, }), [profilerStore], ); const isProfiling = useSubscription<boolean>(isProfilingSubscription); if (isProfiling && isModalShowing) { setIsModalShowing(false); } if (!isModalShowing) { return null; } return <SettingsModalImpl />; } function SettingsModalImpl(_: {}) { const {setIsModalShowing} = useContext(SettingsModalContext); const dismissModal = useCallback( () => setIsModalShowing(false), [setIsModalShowing], ); const [selectedTabID, selectTab] = useLocalStorage<TabID>( 'React::DevTools::selectedSettingsTabID', 'general', ); const modalRef = useRef<HTMLDivElement | null>(null); useModalDismissSignal(modalRef, dismissModal); useEffect(() => { if (modalRef.current !== null) { modalRef.current.focus(); } }, [modalRef]); let view = null; switch (selectedTabID) { case 'components': view = <ComponentsSettings />; break; // $FlowFixMe[incompatible-type] is this missing in TabID? case 'debugging': view = <DebuggingSettings />; break; case 'general': view = <GeneralSettings />; break; case 'profiler': view = <ProfilerSettings />; break; default: break; } return ( <div className={styles.Background}> <div className={styles.Modal} ref={modalRef}> <div className={styles.Tabs}> <TabBar currentTab={selectedTabID} id="Settings" selectTab={selectTab} tabs={tabs} type="settings" /> <div className={styles.Spacer} /> <Button onClick={dismissModal} title="Close settings dialog"> <ButtonIcon type="close" /> </Button> </div> <div className={styles.Content}>{view}</div> </div> </div> ); } const tabs = [ { id: 'general', icon: 'settings', label: 'General', }, { id: 'debugging', icon: 'bug', label: 'Debugging', }, { id: 'components', icon: 'components', label: 'Components', }, { id: 'profiler', icon: 'profiler', label: 'Profiler', }, ];
24.743056
92
0.640043
Python-Penetration-Testing-Cookbook
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ const React = require('react'); const {useEffect} = React; function Component(props) { useEffect(() => {}); React.useLayoutEffect(() => () => {}); return null; } module.exports = {Component};
20.263158
66
0.655087
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 */ /* * The `'' + value` pattern (used in perf-sensitive code) throws for Symbol * and Temporal.* types. See https://github.com/facebook/react/pull/22064. * * The functions in this module will throw an easier-to-understand, * easier-to-debug exception with a clear errors message message explaining the * problem. (Instead of a confusing exception thrown inside the implementation * of the `value` object). */ // $FlowFixMe[incompatible-return] only called in DEV, so void return is not possible. function typeName(value: mixed): string { if (__DEV__) { // toStringTag is needed for namespaced types like Temporal.Instant const hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; const type = (hasToStringTag && (value: any)[Symbol.toStringTag]) || (value: any).constructor.name || 'Object'; // $FlowFixMe[incompatible-return] return type; } } // $FlowFixMe[incompatible-return] only called in DEV, so void return is not possible. function willCoercionThrow(value: mixed): boolean { if (__DEV__) { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value: mixed) { // If you ended up here by following an exception call stack, here's what's // happened: you supplied an object or symbol value to React (as a prop, key, // DOM attribute, CSS property, string ref, etc.) and when React tried to // coerce it to a string using `'' + value`, an exception was thrown. // // The most common types that will cause this exception are `Symbol` instances // and Temporal objects like `Temporal.Instant`. But any object that has a // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this // exception. (Library authors do this to prevent users from using built-in // numeric operators like `+` or comparison operators like `>=` because custom // methods are needed to perform accurate arithmetic or comparison.) // // To fix the problem, coerce this object or symbol value to a string before // passing it to React. The most reliable way is usually `String(value)`. // // To find which value is throwing, check the browser or debugger console. // Before this exception was thrown, there should be `console.error` output // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the // problem and how that type was used: key, atrribute, input value prop, etc. // In most cases, this console output also shows the component and its // ancestor components where the exception happened. // // eslint-disable-next-line react-internal/safe-string-coercion return '' + (value: any); } export function checkAttributeStringCoercion( value: mixed, attributeName: string, ): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', attributeName, typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } export function checkKeyStringCoercion(value: mixed): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'The provided key is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } export function checkPropStringCoercion( value: mixed, propName: string, ): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', propName, typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } export function checkOptionStringCoercion( value: mixed, propName: string, ): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'The provided `%s` option is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', propName, typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } export function checkCSSPropertyStringCoercion( value: mixed, propName: string, ): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before using it here.', propName, typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } export function checkHtmlStringCoercion(value: mixed): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before using it here.', typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } } export function checkFormFieldValueStringCoercion(value: mixed): void | string { if (__DEV__) { if (willCoercionThrow(value)) { console.error( 'Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before using it here.', typeName(value), ); return testStringCoercion(value); // throw (to help callers find troubleshooting comments) } } }
33.361111
96
0.666235
Ethical-Hacking-Scripts
const SUCCESSFUL_COMPILATION_MESSAGE = 'Compiled successfully.'; module.exports = { SUCCESSFUL_COMPILATION_MESSAGE, };
19.5
64
0.770492
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=InlineRequire.js.map?foo=bar&param=some_value
21.238095
66
0.701717
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-refresh-runtime.production.min.js'); } else { module.exports = require('./cjs/react-refresh-runtime.development.js'); }
26.875
76
0.693694
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 ReactTestRenderer; let Scheduler; let act; let assertLog; describe('StrictEffectsMode', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactTestRenderer = require('react-test-renderer'); Scheduler = require('scheduler'); act = require('internal-test-utils').act; const InternalTestUtils = require('internal-test-utils'); assertLog = InternalTestUtils.assertLog; }); function supportsDoubleInvokeEffects() { return gate( flags => flags.build === 'development' && flags.createRootStrictEffectsByDefault && flags.dfsEffectsRefactor, ); } it('should not double invoke effects in legacy mode', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } await act(() => { ReactTestRenderer.create(<App text={'mount'} />); }); assertLog(['useLayoutEffect mount', 'useEffect mount']); }); it('double invoking for effects works properly', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'useLayoutEffect mount', 'useEffect mount', 'useLayoutEffect unmount', 'useEffect unmount', 'useLayoutEffect mount', 'useEffect mount', ]); } else { assertLog(['useLayoutEffect mount', 'useEffect mount']); } await act(() => { renderer.update(<App text={'update'} />); }); assertLog([ 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); await act(() => { renderer.unmount(); }); assertLog(['useLayoutEffect unmount', 'useEffect unmount']); }); it('multiple effects are double invoked in the right order (all mounted, all unmounted, all remounted)', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect One mount'); return () => Scheduler.log('useEffect One unmount'); }); React.useEffect(() => { Scheduler.log('useEffect Two mount'); return () => Scheduler.log('useEffect Two unmount'); }); return text; } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'useEffect One mount', 'useEffect Two mount', 'useEffect One unmount', 'useEffect Two unmount', 'useEffect One mount', 'useEffect Two mount', ]); } else { assertLog(['useEffect One mount', 'useEffect Two mount']); } await act(() => { renderer.update(<App text={'update'} />); }); assertLog([ 'useEffect One unmount', 'useEffect Two unmount', 'useEffect One mount', 'useEffect Two mount', ]); await act(() => { renderer.unmount(null); }); assertLog(['useEffect One unmount', 'useEffect Two unmount']); }); it('multiple layout effects are double invoked in the right order (all mounted, all unmounted, all remounted)', async () => { function App({text}) { React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect One mount'); return () => Scheduler.log('useLayoutEffect One unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect Two mount'); return () => Scheduler.log('useLayoutEffect Two unmount'); }); return text; } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'useLayoutEffect One mount', 'useLayoutEffect Two mount', 'useLayoutEffect One unmount', 'useLayoutEffect Two unmount', 'useLayoutEffect One mount', 'useLayoutEffect Two mount', ]); } else { assertLog(['useLayoutEffect One mount', 'useLayoutEffect Two mount']); } await act(() => { renderer.update(<App text={'update'} />); }); assertLog([ 'useLayoutEffect One unmount', 'useLayoutEffect Two unmount', 'useLayoutEffect One mount', 'useLayoutEffect Two mount', ]); await act(() => { renderer.unmount(); }); assertLog(['useLayoutEffect One unmount', 'useLayoutEffect Two unmount']); }); it('useEffect and useLayoutEffect is called twice when there is no unmount', async () => { function App({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); }); return text; } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'useLayoutEffect mount', 'useEffect mount', 'useLayoutEffect mount', 'useEffect mount', ]); } else { assertLog(['useLayoutEffect mount', 'useEffect mount']); } await act(() => { renderer.update(<App text={'update'} />); }); assertLog(['useLayoutEffect mount', 'useEffect mount']); await act(() => { renderer.unmount(); }); assertLog([]); }); it('passes the right context to class component lifecycles', async () => { class App extends React.PureComponent { test() {} componentDidMount() { this.test(); Scheduler.log('componentDidMount'); } componentDidUpdate() { this.test(); Scheduler.log('componentDidUpdate'); } componentWillUnmount() { this.test(); Scheduler.log('componentWillUnmount'); } render() { return null; } } await act(() => { ReactTestRenderer.create(<App />, {isConcurrent: true}); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'componentDidMount', 'componentWillUnmount', 'componentDidMount', ]); } else { assertLog(['componentDidMount']); } }); it('double invoking works for class components', async () => { class App extends React.PureComponent { componentDidMount() { Scheduler.log('componentDidMount'); } componentDidUpdate() { Scheduler.log('componentDidUpdate'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'componentDidMount', 'componentWillUnmount', 'componentDidMount', ]); } else { assertLog(['componentDidMount']); } await act(() => { renderer.update(<App text={'update'} />); }); assertLog(['componentDidUpdate']); await act(() => { renderer.unmount(); }); assertLog(['componentWillUnmount']); }); it('invokes componentWillUnmount for class components without componentDidMount', async () => { class App extends React.PureComponent { componentDidUpdate() { Scheduler.log('componentDidUpdate'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog(['componentWillUnmount']); } else { assertLog([]); } await act(() => { renderer.update(<App text={'update'} />); }); assertLog(['componentDidUpdate']); await act(() => { renderer.unmount(); }); assertLog(['componentWillUnmount']); }); it('should not double invoke class lifecycles in legacy mode', async () => { class App extends React.PureComponent { componentDidMount() { Scheduler.log('componentDidMount'); } componentDidUpdate() { Scheduler.log('componentDidUpdate'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } await act(() => { ReactTestRenderer.create(<App text={'mount'} />); }); assertLog(['componentDidMount']); }); it('double flushing passive effects only results in one double invoke', async () => { function App({text}) { const [state, setState] = React.useState(0); React.useEffect(() => { if (state !== 1) { setState(1); } Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); Scheduler.log(text); return text; } await act(() => { ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'mount', 'useLayoutEffect mount', 'useEffect mount', 'useLayoutEffect unmount', 'useEffect unmount', 'useLayoutEffect mount', 'useEffect mount', 'mount', 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); } else { assertLog([ 'mount', 'useLayoutEffect mount', 'useEffect mount', 'mount', 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); } }); it('newly mounted components after initial mount get double invoked', async () => { let _setShowChild; function Child() { React.useEffect(() => { Scheduler.log('Child useEffect mount'); return () => Scheduler.log('Child useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('Child useLayoutEffect mount'); return () => Scheduler.log('Child useLayoutEffect unmount'); }); return null; } function App() { const [showChild, setShowChild] = React.useState(false); _setShowChild = setShowChild; React.useEffect(() => { Scheduler.log('App useEffect mount'); return () => Scheduler.log('App useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('App useLayoutEffect mount'); return () => Scheduler.log('App useLayoutEffect unmount'); }); return showChild && <Child />; } await act(() => { ReactTestRenderer.create(<App />, {isConcurrent: true}); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'App useLayoutEffect mount', 'App useEffect mount', 'App useLayoutEffect unmount', 'App useEffect unmount', 'App useLayoutEffect mount', 'App useEffect mount', ]); } else { assertLog(['App useLayoutEffect mount', 'App useEffect mount']); } await act(() => { _setShowChild(true); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'App useLayoutEffect unmount', 'Child useLayoutEffect mount', 'App useLayoutEffect mount', 'App useEffect unmount', 'Child useEffect mount', 'App useEffect mount', 'Child useLayoutEffect unmount', 'Child useEffect unmount', 'Child useLayoutEffect mount', 'Child useEffect mount', ]); } else { assertLog([ 'App useLayoutEffect unmount', 'Child useLayoutEffect mount', 'App useLayoutEffect mount', 'App useEffect unmount', 'Child useEffect mount', 'App useEffect mount', ]); } }); it('classes and functions are double invoked together correctly', async () => { class ClassChild extends React.PureComponent { componentDidMount() { Scheduler.log('componentDidMount'); } componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } function FunctionChild({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } function App({text}) { return ( <> <ClassChild text={text} /> <FunctionChild text={text} /> </> ); } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'componentDidMount', 'useLayoutEffect mount', 'useEffect mount', 'componentWillUnmount', 'useLayoutEffect unmount', 'useEffect unmount', 'componentDidMount', 'useLayoutEffect mount', 'useEffect mount', ]); } else { assertLog([ 'componentDidMount', 'useLayoutEffect mount', 'useEffect mount', ]); } await act(() => { renderer.update(<App text={'mount'} />); }); assertLog([ 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); await act(() => { renderer.unmount(); }); assertLog([ 'componentWillUnmount', 'useLayoutEffect unmount', 'useEffect unmount', ]); }); it('classes without componentDidMount and functions are double invoked together correctly', async () => { class ClassChild extends React.PureComponent { componentWillUnmount() { Scheduler.log('componentWillUnmount'); } render() { return this.props.text; } } function FunctionChild({text}) { React.useEffect(() => { Scheduler.log('useEffect mount'); return () => Scheduler.log('useEffect unmount'); }); React.useLayoutEffect(() => { Scheduler.log('useLayoutEffect mount'); return () => Scheduler.log('useLayoutEffect unmount'); }); return text; } function App({text}) { return ( <> <ClassChild text={text} /> <FunctionChild text={text} /> </> ); } let renderer; await act(() => { renderer = ReactTestRenderer.create(<App text={'mount'} />, { isConcurrent: true, }); }); if (supportsDoubleInvokeEffects()) { assertLog([ 'useLayoutEffect mount', 'useEffect mount', 'componentWillUnmount', 'useLayoutEffect unmount', 'useEffect unmount', 'useLayoutEffect mount', 'useEffect mount', ]); } else { assertLog(['useLayoutEffect mount', 'useEffect mount']); } await act(() => { renderer.update(<App text={'mount'} />); }); assertLog([ 'useLayoutEffect unmount', 'useLayoutEffect mount', 'useEffect unmount', 'useEffect mount', ]); await act(() => { renderer.unmount(); }); assertLog([ 'componentWillUnmount', 'useLayoutEffect unmount', 'useEffect unmount', ]); }); });
22.930986
127
0.56033
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 type {ReactContext} from 'shared/ReactTypes'; import * as React from 'react'; import { createContext, Component, forwardRef, Fragment, memo, useCallback, useDebugValue, useEffect, useReducer, useState, } from 'react'; const initialData = {foo: 'FOO', bar: 'BAR'}; // $FlowFixMe[missing-local-annot] function reducer(state, action: {type: string}) { switch (action.type) { case 'swap': return {foo: state.bar, bar: state.foo}; default: throw new Error(); } } type StatefulFunctionProps = {name: string}; function StatefulFunction({name}: StatefulFunctionProps) { const [count, updateCount] = useState(0); const debouncedCount = useDebounce(count, 1000); const handleUpdateCountClick = useCallback( () => updateCount(count + 1), [count], ); const [data, dispatch] = useReducer(reducer, initialData); const handleUpdateReducerClick = useCallback( () => dispatch({type: 'swap'}), [], ); return ( <ul> <li>Name: {name}</li> <li> <button onClick={handleUpdateCountClick}> Debounced count: {debouncedCount} </button> </li> <li> Reducer state: foo "{data.foo}", bar "{data.bar}" </li> <li> <button onClick={handleUpdateReducerClick}>Swap reducer values</button> </li> </ul> ); } const BoolContext = createContext(true); BoolContext.displayName = 'BoolContext'; type Props = {name: string, toggle: boolean}; type State = {cities: Array<string>, state: string}; class StatefulClass extends Component<Props, State> { static contextType: ReactContext<boolean> = BoolContext; state: State = { cities: ['San Francisco', 'San Jose'], state: 'California', }; // $FlowFixMe[missing-local-annot] handleChange = ({target}): any => this.setState({ state: target.value, }); render(): any { return ( <ul> <li>Name: {this.props.name}</li> <li>Toggle: {this.props.toggle ? 'true' : 'false'}</li> <li> State: <input value={this.state.state} onChange={this.handleChange} /> </li> <li>Cities: {this.state.cities.join(', ')}</li> <li>Context: {this.context ? 'true' : 'false'}</li> </ul> ); } } const MemoizedStatefulClass = memo(StatefulClass); const MemoizedStatefulFunction = memo(StatefulFunction); const ForwardRef = forwardRef<{name: string}, HTMLUListElement>( ({name}, ref) => { const [count, updateCount] = useState(0); const debouncedCount = useDebounce(count, 1000); const handleUpdateCountClick = useCallback( () => updateCount(count + 1), [count], ); return ( <ul ref={ref}> <li>Name: {name}</li> <li> <button onClick={handleUpdateCountClick}> Debounced count: {debouncedCount} </button> </li> </ul> ); }, ); export default function EditableProps(): React.Node { return ( <Fragment> <h1>Editable props</h1> <strong>Class</strong> <StatefulClass name="Brian" toggle={true} /> <strong>Function</strong> <StatefulFunction name="Brian" /> <strong>Memoized Class</strong> <MemoizedStatefulClass name="Brian" toggle={true} /> <strong>Memoized Function</strong> <MemoizedStatefulFunction name="Brian" /> <strong>Forward Ref</strong> <ForwardRef name="Brian" /> </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/
24.772727
85
0.623815
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {REACT_PROVIDER_TYPE, REACT_CONTEXT_TYPE} from 'shared/ReactSymbols'; import type {ReactProviderType} from 'shared/ReactTypes'; import type {ReactContext} from 'shared/ReactTypes'; export function createContext<T>(defaultValue: T): ReactContext<T> { // TODO: Second argument used to be an optional `calculateChangedBits` // function. Warn to reserve for future use? const context: ReactContext<T> = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: (null: any), Consumer: (null: any), // Add these to use same hidden class in VM as ServerContext _defaultValue: (null: any), _globalName: (null: any), }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context, }; let hasWarnedAboutUsingNestedContextConsumers = false; let hasWarnedAboutUsingConsumerProvider = false; let hasWarnedAboutDisplayNameOnConsumer = false; if (__DEV__) { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. const Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context, }; // $FlowFixMe[prop-missing]: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get() { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; console.error( 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?', ); } return context.Provider; }, set(_Provider: ReactProviderType<T>) { context.Provider = _Provider; }, }, _currentValue: { get() { return context._currentValue; }, set(_currentValue: T) { context._currentValue = _currentValue; }, }, _currentValue2: { get() { return context._currentValue2; }, set(_currentValue2: T) { context._currentValue2 = _currentValue2; }, }, _threadCount: { get() { return context._threadCount; }, set(_threadCount: number) { context._threadCount = _threadCount; }, }, Consumer: { get() { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; console.error( 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?', ); } return context.Consumer; }, }, displayName: { get() { return context.displayName; }, set(displayName: void | string) { if (!hasWarnedAboutDisplayNameOnConsumer) { console.warn( 'Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName, ); hasWarnedAboutDisplayNameOnConsumer = true; } }, }, }); // $FlowFixMe[prop-missing]: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } else { context.Consumer = context; } if (__DEV__) { context._currentRenderer = null; context._currentRenderer2 = null; } return context; }
32.208633
117
0.621235
Penetration-Testing-Study-Notes
'use strict'; // TODO: this doesn't make sense for an ESLint rule. // We need to fix our build process to not create bundles for "raw" packages like this. if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/eslint-plugin-react-hooks.production.min.js'); } else { module.exports = require('./cjs/eslint-plugin-react-hooks.development.js'); }
36.2
87
0.71159
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-dom-bindings/src/shared/ReactFlightClientConfigDOM'; export type Response = any; export opaque type ModuleLoading = mixed; export opaque type SSRModuleMap = mixed; export opaque type ServerManifest = mixed; export opaque type ServerReferenceId = string; export opaque type ClientReferenceMetadata = mixed; export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars export const resolveClientReference: any = null; export const resolveServerReference: any = null; export const preloadModule: any = null; export const requireModule: any = null; export const prepareDestinationForModule: any = null; export const usedWithSSR = true;
35.461538
84
0.781415
owtf
/** @license React v15.7.0 * react-jsx-dev-runtime.production.min.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';require("react");exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var a=Symbol.for;exports.Fragment=a("react.fragment")}exports.jsxDEV=void 0;
42.4
172
0.734411
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './src/dom/create-event-handle/Focus';
22.454545
66
0.692607
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 path = require('path'); const semver = require('semver'); function resolveRelatively(importee, importer) { if (semver.gte(process.version, '8.9.0')) { return require.resolve(importee, { paths: [path.dirname(importer)], }); } else { // `paths` argument is not available in older Node. // This works though. // https://github.com/nodejs/node/issues/5963 const Module = require('module'); return Module._findPath(importee, [ path.dirname(importer), ...module.paths, ]); } } let resolveCache = new Map(); function useForks(forks) { let resolvedForks = new Map(); Object.keys(forks).forEach(srcModule => { // Fork paths are relative to the project root. They must include the full // path, including the extension. We intentionally don't use Node's module // resolution algorithm because 1) require.resolve doesn't work with ESM // modules, and 2) the behavior is easier to predict. const targetModule = forks[srcModule]; resolvedForks.set( path.resolve(process.cwd(), srcModule), // targetModule could be a string (a file path), // or an error (which we'd throw if it gets used). // Don't try to "resolve" errors, but cache // resolved file paths. typeof targetModule === 'string' ? path.resolve(process.cwd(), targetModule) : targetModule ); }); return { name: 'scripts/rollup/plugins/use-forks-plugin', resolveId(importee, importer) { if (!importer || !importee) { return null; } if (importee.startsWith('\u0000')) { // Internal Rollup reference, ignore. // Passing that to Node file functions can fatal. return null; } let resolvedImportee = null; let cacheKey = `${importer}:::${importee}`; if (resolveCache.has(cacheKey)) { // Avoid hitting file system if possible. resolvedImportee = resolveCache.get(cacheKey); } else { try { resolvedImportee = resolveRelatively(importee, importer); } catch (err) { // Not our fault, let Rollup fail later. } if (resolvedImportee) { resolveCache.set(cacheKey, resolvedImportee); } } if (resolvedImportee && resolvedForks.has(resolvedImportee)) { // We found a fork! const fork = resolvedForks.get(resolvedImportee); if (fork instanceof Error) { throw fork; } return fork; } return null; }, }; } module.exports = useForks;
30.157303
78
0.621212
cybersecurity-penetration-testing
'use strict'; // This file is used as temporary storage for modules generated in Flight tests. var moduleIdx = 0; var modules = new Map(); // This simulates what the compiler will do when it replaces render functions with server blocks. exports.saveModule = function saveModule(render) { var idx = '' + moduleIdx++; modules.set(idx, render); return idx; }; exports.readModule = function readModule(idx) { return modules.get(idx); };
25.176471
97
0.725225
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('ReactCompositeComponentNestedState-state', () => { beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); }); it('should provide up to date values for props', () => { class ParentComponent extends React.Component { state = {color: 'blue'}; handleColor = color => { this.props.logger('parent-handleColor', this.state.color); this.setState({color: color}, function () { this.props.logger('parent-after-setState', this.state.color); }); }; render() { this.props.logger('parent-render', this.state.color); return ( <ChildComponent logger={this.props.logger} color={this.state.color} onSelectColor={this.handleColor} /> ); } } class ChildComponent extends React.Component { constructor(props) { super(props); props.logger('getInitialState', props.color); this.state = {hue: 'dark ' + props.color}; } handleHue = (shade, color) => { this.props.logger('handleHue', this.state.hue, this.props.color); this.props.onSelectColor(color); this.setState( function (state, props) { this.props.logger( 'setState-this', this.state.hue, this.props.color, ); this.props.logger('setState-args', state.hue, props.color); return {hue: shade + ' ' + props.color}; }, function () { this.props.logger( 'after-setState', this.state.hue, this.props.color, ); }, ); }; render() { this.props.logger('render', this.state.hue, this.props.color); return ( <div> <button onClick={this.handleHue.bind(this, 'dark', 'blue')}> Dark Blue </button> <button onClick={this.handleHue.bind(this, 'light', 'blue')}> Light Blue </button> <button onClick={this.handleHue.bind(this, 'dark', 'green')}> Dark Green </button> <button onClick={this.handleHue.bind(this, 'light', 'green')}> Light Green </button> </div> ); } } const container = document.createElement('div'); document.body.appendChild(container); const logger = jest.fn(); void ReactDOM.render(<ParentComponent logger={logger} />, container); // click "light green" container.childNodes[0].childNodes[3].click(); expect(logger.mock.calls).toEqual([ ['parent-render', 'blue'], ['getInitialState', 'blue'], ['render', 'dark blue', 'blue'], ['handleHue', 'dark blue', 'blue'], ['parent-handleColor', 'blue'], ['parent-render', 'green'], ['setState-this', 'dark blue', 'blue'], ['setState-args', 'dark blue', 'green'], ['render', 'light green', 'green'], ['after-setState', 'light green', 'green'], ['parent-after-setState', 'green'], ]); }); });
27.5
74
0.535829
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('events', () => { let dispatcher; beforeEach(() => { const EventEmitter = require('../events').default; dispatcher = new EventEmitter(); }); // @reactVersion >=16 it('can dispatch an event with no listeners', () => { dispatcher.emit('event', 123); }); // @reactVersion >=16 it('handles a listener being attached multiple times', () => { const callback = jest.fn(); dispatcher.addListener('event', callback); dispatcher.addListener('event', callback); dispatcher.emit('event', 123); expect(callback).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledWith(123); }); // @reactVersion >=16 it('notifies all attached listeners of events', () => { const callback1 = jest.fn(); const callback2 = jest.fn(); const callback3 = jest.fn(); dispatcher.addListener('event', callback1); dispatcher.addListener('event', callback2); dispatcher.addListener('other-event', callback3); dispatcher.emit('event', 123); expect(callback1).toHaveBeenCalledTimes(1); expect(callback1).toHaveBeenCalledWith(123); expect(callback2).toHaveBeenCalledTimes(1); expect(callback2).toHaveBeenCalledWith(123); expect(callback3).not.toHaveBeenCalled(); }); // @reactVersion >= 16.0 it('calls later listeners before re-throwing if an earlier one throws', () => { const callbackThatThrows = jest.fn(() => { throw Error('expected'); }); const callback = jest.fn(); dispatcher.addListener('event', callbackThatThrows); dispatcher.addListener('event', callback); expect(() => { dispatcher.emit('event', 123); }).toThrow('expected'); expect(callbackThatThrows).toHaveBeenCalledTimes(1); expect(callbackThatThrows).toHaveBeenCalledWith(123); expect(callback).toHaveBeenCalledTimes(1); expect(callback).toHaveBeenCalledWith(123); }); // @reactVersion >= 16.0 it('removes attached listeners', () => { const callback1 = jest.fn(); const callback2 = jest.fn(); dispatcher.addListener('event', callback1); dispatcher.addListener('other-event', callback2); dispatcher.removeListener('event', callback1); dispatcher.emit('event', 123); expect(callback1).not.toHaveBeenCalled(); dispatcher.emit('other-event', 123); expect(callback2).toHaveBeenCalledTimes(1); expect(callback2).toHaveBeenCalledWith(123); }); // @reactVersion >= 16.0 it('removes all listeners', () => { const callback1 = jest.fn(); const callback2 = jest.fn(); const callback3 = jest.fn(); dispatcher.addListener('event', callback1); dispatcher.addListener('event', callback2); dispatcher.addListener('other-event', callback3); dispatcher.removeAllListeners(); dispatcher.emit('event', 123); dispatcher.emit('other-event', 123); expect(callback1).not.toHaveBeenCalled(); expect(callback2).not.toHaveBeenCalled(); expect(callback3).not.toHaveBeenCalled(); }); // @reactVersion >= 16.0 it('should call the initial listeners even if others are added or removed during a dispatch', () => { const callback1 = jest.fn(() => { dispatcher.removeListener('event', callback2); dispatcher.addListener('event', callback3); }); const callback2 = jest.fn(); const callback3 = jest.fn(); dispatcher.addListener('event', callback1); dispatcher.addListener('event', callback2); dispatcher.emit('event', 123); expect(callback1).toHaveBeenCalledTimes(1); expect(callback1).toHaveBeenCalledWith(123); expect(callback2).toHaveBeenCalledTimes(1); expect(callback2).toHaveBeenCalledWith(123); expect(callback3).not.toHaveBeenCalled(); dispatcher.emit('event', 456); expect(callback1).toHaveBeenCalledTimes(2); expect(callback1).toHaveBeenCalledWith(456); expect(callback2).toHaveBeenCalledTimes(1); expect(callback3).toHaveBeenCalledTimes(1); expect(callback3).toHaveBeenCalledWith(456); }); });
30.30597
103
0.679065
Python-Penetration-Testing-Cookbook
"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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJyZXF1aXJlIiwidXNlU3RhdGUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFBQTs7Ozs7Ozs7QUFTTyxTQUFTQSxTQUFULEdBQXFCO0FBQzFCLFFBQU0sQ0FBQ0MsS0FBRCxJQUFVQyxPQUFPLENBQUMsT0FBRCxDQUFQLENBQWlCQyxRQUFqQixDQUEwQixDQUExQixDQUFoQjs7QUFFQSxTQUFPRixLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50XSA9IHJlcXVpcmUoJ3JlYWN0JykudXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIGNvdW50O1xufVxuIl0sInhfcmVhY3Rfc291cmNlcyI6W1t7Im5hbWVzIjpbIjxuby1ob29rPiJdLCJtYXBwaW5ncyI6IkNBQUQifV1dfQ==
62.47619
932
0.894144
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 */ module.exports = require('./src/ReactFlightTurbopackNodeRegister');
23.818182
67
0.716912
null
'use strict'; const RELEASE_CHANNEL = process.env.RELEASE_CHANNEL; const __EXPERIMENTAL__ = typeof RELEASE_CHANNEL === 'string' ? RELEASE_CHANNEL === 'experimental' : true; const bundleTypes = { NODE_ES2015: 'NODE_ES2015', ESM_DEV: 'ESM_DEV', ESM_PROD: 'ESM_PROD', UMD_DEV: 'UMD_DEV', UMD_PROD: 'UMD_PROD', UMD_PROFILING: 'UMD_PROFILING', NODE_DEV: 'NODE_DEV', NODE_PROD: 'NODE_PROD', NODE_PROFILING: 'NODE_PROFILING', BUN_DEV: 'BUN_DEV', BUN_PROD: 'BUN_PROD', FB_WWW_DEV: 'FB_WWW_DEV', FB_WWW_PROD: 'FB_WWW_PROD', FB_WWW_PROFILING: 'FB_WWW_PROFILING', RN_OSS_DEV: 'RN_OSS_DEV', RN_OSS_PROD: 'RN_OSS_PROD', RN_OSS_PROFILING: 'RN_OSS_PROFILING', RN_FB_DEV: 'RN_FB_DEV', RN_FB_PROD: 'RN_FB_PROD', RN_FB_PROFILING: 'RN_FB_PROFILING', BROWSER_SCRIPT: 'BROWSER_SCRIPT', }; const { NODE_ES2015, ESM_DEV, ESM_PROD, UMD_DEV, UMD_PROD, UMD_PROFILING, NODE_DEV, NODE_PROD, NODE_PROFILING, BUN_DEV, BUN_PROD, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, BROWSER_SCRIPT, } = bundleTypes; const moduleTypes = { // React ISOMORPHIC: 'ISOMORPHIC', // Individual renderers. They bundle the reconciler. (e.g. ReactDOM) RENDERER: 'RENDERER', // Helper packages that access specific renderer's internals. (e.g. TestUtils) RENDERER_UTILS: 'RENDERER_UTILS', // Standalone reconciler for third-party renderers. RECONCILER: 'RECONCILER', }; const {ISOMORPHIC, RENDERER, RENDERER_UTILS, RECONCILER} = moduleTypes; const bundles = [ /******* Isomorphic *******/ { bundleTypes: [ UMD_DEV, UMD_PROD, UMD_PROFILING, NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, ], moduleType: ISOMORPHIC, entry: 'react', global: 'React', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, externals: ['ReactNativeInternalFeatureFlags'], }, /******* Isomorphic Shared Subset *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'react/src/ReactSharedSubset.js', name: 'react.shared-subset', global: 'React', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: [], }, /******* Isomorphic Shared Subset for FB *******/ { bundleTypes: __EXPERIMENTAL__ ? [FB_WWW_DEV, FB_WWW_PROD] : [], moduleType: ISOMORPHIC, entry: 'react/src/ReactSharedSubsetFB.js', global: 'ReactSharedSubset', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: [], }, /******* React JSX Runtime *******/ { bundleTypes: [ NODE_DEV, NODE_PROD, NODE_PROFILING, // TODO: use on WWW. RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, ], moduleType: ISOMORPHIC, entry: 'react/jsx-runtime', global: 'JSXRuntime', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react', 'ReactNativeInternalFeatureFlags'], }, /******* React JSX DEV Runtime *******/ { bundleTypes: [ NODE_DEV, NODE_PROD, NODE_PROFILING, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, ], moduleType: ISOMORPHIC, entry: 'react/jsx-dev-runtime', global: 'JSXDEVRuntime', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'ReactNativeInternalFeatureFlags'], }, /******* React DOM *******/ { bundleTypes: [ UMD_DEV, UMD_PROD, UMD_PROFILING, NODE_DEV, NODE_PROD, NODE_PROFILING, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, ], moduleType: RENDERER, entry: 'react-dom', global: 'ReactDOM', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: true, externals: ['react'], }, /******* React DOM Shared Subset *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-dom/src/ReactDOMSharedSubset.js', name: 'react-dom.shared-subset', global: 'ReactDOM', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* Test Utils *******/ { moduleType: RENDERER_UTILS, bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], entry: 'react-dom/test-utils', global: 'ReactTestUtils', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React DOM - www - Testing *******/ { moduleType: RENDERER, bundleTypes: __EXPERIMENTAL__ ? [FB_WWW_DEV, FB_WWW_PROD, NODE_DEV, NODE_PROD] : [FB_WWW_DEV, FB_WWW_PROD], entry: 'react-dom/unstable_testing', global: 'ReactDOMTesting', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* React DOM Server *******/ { bundleTypes: [ UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, ], moduleType: RENDERER, entry: 'react-dom/src/server/ReactDOMLegacyServerBrowser.js', name: 'react-dom-server-legacy.browser', global: 'ReactDOMServer', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-dom/src/server/ReactDOMLegacyServerNode.js', name: 'react-dom-server-legacy.node', externals: ['react', 'stream', 'react-dom'], minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, /******* React DOM Fizz Server *******/ { bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], moduleType: RENDERER, entry: 'react-dom/src/server/react-dom-server.browser.js', name: 'react-dom-server.browser', global: 'ReactDOMServer', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-dom/src/server/react-dom-server.node.js', name: 'react-dom-server.node', global: 'ReactDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'crypto', 'async_hooks', 'react-dom'], }, { bundleTypes: __EXPERIMENTAL__ ? [FB_WWW_DEV, FB_WWW_PROD] : [], moduleType: RENDERER, entry: 'react-server-dom-fb/src/ReactDOMServerFB.js', global: 'ReactDOMServerStreaming', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React DOM Fizz Server Edge *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-dom/src/server/react-dom-server.edge.js', name: 'react-dom-server.edge', // 'node_modules/react/*.js', global: 'ReactDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React DOM Fizz Server Bun *******/ { bundleTypes: [BUN_DEV, BUN_PROD], moduleType: RENDERER, entry: 'react-dom/src/server/react-dom-server.bun.js', name: 'react-dom-server.bun', // 'node_modules/react/*.js', global: 'ReactDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React DOM Fizz Server External Runtime *******/ { bundleTypes: [BROWSER_SCRIPT], moduleType: RENDERER, entry: 'react-dom/unstable_server-external-runtime', outputPath: 'unstable_server-external-runtime.js', global: 'ReactDOMServerExternalRuntime', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [], }, /******* React DOM Server Render Stub *******/ { bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], moduleType: RENDERER, entry: 'react-dom/server-rendering-stub', name: 'react-dom-server-rendering-stub', global: 'ReactDOMServerRenderingStub', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* React Server DOM Webpack Server *******/ { bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/server.browser', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/server.node', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'crypto', 'async_hooks', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/server.node.unbundled', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'crypto', 'async_hooks', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/server.edge', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'crypto', 'async_hooks', 'react-dom'], }, /******* React Server DOM Webpack Client *******/ { bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/client.browser', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/client.node', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom', 'util', 'crypto'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/client.node.unbundled', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom', 'util', 'crypto'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-webpack/client.edge', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React Server DOM Webpack Plugin *******/ { bundleTypes: [NODE_ES2015], moduleType: RENDERER_UTILS, entry: 'react-server-dom-webpack/plugin', global: 'ReactServerWebpackPlugin', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['fs', 'path', 'url', 'neo-async'], }, /******* React Server DOM Webpack Node.js Loader *******/ { bundleTypes: [ESM_PROD], moduleType: RENDERER_UTILS, entry: 'react-server-dom-webpack/node-loader', global: 'ReactServerWebpackNodeLoader', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['acorn'], }, /******* React Server DOM Webpack Node.js CommonJS Loader *******/ { bundleTypes: [NODE_ES2015], moduleType: RENDERER_UTILS, entry: 'react-server-dom-webpack/src/ReactFlightWebpackNodeRegister', name: 'react-server-dom-webpack-node-register', global: 'ReactFlightWebpackNodeRegister', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['url', 'module', 'react-server-dom-webpack/server'], }, /******* React Server DOM Turbopack Server *******/ { bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/server.browser', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/server.node', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'async_hooks', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/server.node.unbundled', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'async_hooks', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/server.edge', global: 'ReactServerDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'async_hooks', 'react-dom'], }, /******* React Server DOM Turbopack Client *******/ { bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/client.browser', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/client.node', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom', 'util'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/client.node.unbundled', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom', 'util'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-turbopack/client.edge', global: 'ReactServerDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React Server DOM Turbopack Plugin *******/ // There is no plugin the moment because Turbopack // does not expose a plugin interface yet. /******* React Server DOM Turbopack Node.js Loader *******/ { bundleTypes: [ESM_PROD], moduleType: RENDERER_UTILS, entry: 'react-server-dom-turbopack/node-loader', global: 'ReactServerTurbopackNodeLoader', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['acorn'], }, /******* React Server DOM Turbopack Node.js CommonJS Loader *******/ { bundleTypes: [NODE_ES2015], moduleType: RENDERER_UTILS, entry: 'react-server-dom-turbopack/src/ReactFlightTurbopackNodeRegister', name: 'react-server-dom-turbopack-node-register', global: 'ReactFlightWebpackNodeRegister', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['url', 'module', 'react-server-dom-turbopack/server'], }, /******* React Server DOM ESM Server *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-esm/server.node', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'util', 'crypto', 'async_hooks', 'react-dom'], }, /******* React Server DOM ESM Client *******/ { bundleTypes: [NODE_DEV, NODE_PROD, ESM_DEV, ESM_PROD], moduleType: RENDERER, entry: 'react-server-dom-esm/client.browser', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-server-dom-esm/client.node', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom', 'util', 'crypto'], }, /******* React Server DOM ESM Node.js Loader *******/ { bundleTypes: [ESM_PROD], moduleType: RENDERER_UTILS, entry: 'react-server-dom-esm/node-loader', global: 'ReactServerESMNodeLoader', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['acorn'], }, /******* React Server DOM FB Server *******/ { bundleTypes: __EXPERIMENTAL__ ? [FB_WWW_DEV, FB_WWW_PROD] : [], moduleType: RENDERER, entry: 'react-server-dom-fb/src/ReactFlightDOMServerFB.js', global: 'ReactFlightDOMServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React Server DOM FB Client *******/ { bundleTypes: __EXPERIMENTAL__ ? [FB_WWW_DEV, FB_WWW_PROD] : [], moduleType: RENDERER, entry: 'react-server-dom-fb/src/ReactFlightDOMClientFB.js', global: 'ReactFlightDOMClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'react-dom'], }, /******* React Suspense Test Utils *******/ { bundleTypes: [NODE_ES2015], moduleType: RENDERER_UTILS, entry: 'react-suspense-test-utils', global: 'ReactSuspenseTestUtils', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* React ART *******/ { bundleTypes: [ UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, ], moduleType: RENDERER, entry: 'react-art', global: 'ReactART', externals: ['react'], minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: true, babel: opts => Object.assign({}, opts, { // Include JSX presets: opts.presets.concat([ require.resolve('@babel/preset-react'), require.resolve('@babel/preset-flow'), ]), plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, /******* React Native *******/ { bundleTypes: __EXPERIMENTAL__ ? [] : [RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING], moduleType: RENDERER, entry: 'react-native-renderer', global: 'ReactNativeRenderer', externals: ['react-native', 'ReactNativeInternalFeatureFlags'], minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, { bundleTypes: [RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING], moduleType: RENDERER, entry: 'react-native-renderer', global: 'ReactNativeRenderer', externals: ['react-native'], minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, /******* React Native Fabric *******/ { bundleTypes: __EXPERIMENTAL__ ? [] : [RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING], moduleType: RENDERER, entry: 'react-native-renderer/fabric', global: 'ReactFabric', externals: ['react-native', 'ReactNativeInternalFeatureFlags'], minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, { bundleTypes: [RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING], moduleType: RENDERER, entry: 'react-native-renderer/fabric', global: 'ReactFabric', externals: ['react-native'], minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, /******* React Test Renderer *******/ { bundleTypes: [ FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, ], moduleType: RENDERER, entry: 'react-test-renderer', global: 'ReactTestRenderer', externals: [ 'react', 'scheduler', 'scheduler/unstable_mock', 'ReactNativeInternalFeatureFlags', ], minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, babel: opts => Object.assign({}, opts, { plugins: opts.plugins.concat([ [require.resolve('@babel/plugin-transform-classes'), {loose: true}], ]), }), }, /******* React Noop Renderer (used for tests) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-noop-renderer', global: 'ReactNoopRenderer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'scheduler', 'scheduler/unstable_mock', 'expect'], }, /******* React Noop Persistent Renderer (used for tests) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-noop-renderer/persistent', global: 'ReactNoopRendererPersistent', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'scheduler', 'expect'], }, /******* React Noop Server Renderer (used for tests) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-noop-renderer/server', global: 'ReactNoopRendererServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'scheduler', 'expect'], }, /******* React Noop Flight Server (used for tests) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-noop-renderer/flight-server', global: 'ReactNoopFlightServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [ 'react', 'scheduler', 'expect', 'react-noop-renderer/flight-modules', ], }, /******* React Noop Flight Client (used for tests) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RENDERER, entry: 'react-noop-renderer/flight-client', global: 'ReactNoopFlightClient', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [ 'react', 'scheduler', 'expect', 'react-noop-renderer/flight-modules', ], }, /******* React Reconciler *******/ { bundleTypes: [NODE_DEV, NODE_PROD, NODE_PROFILING], moduleType: RECONCILER, entry: 'react-reconciler', global: 'ReactReconciler', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* React Server *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RECONCILER, entry: 'react-server', global: 'ReactServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* React Flight Server *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RECONCILER, entry: 'react-server/flight', global: 'ReactFlightServer', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* React Flight Client *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: RECONCILER, entry: 'react-client/flight', global: 'ReactFlightClient', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['react'], }, /******* Reconciler Reflection *******/ { moduleType: RENDERER_UTILS, bundleTypes: [NODE_DEV, NODE_PROD], entry: 'react-reconciler/reflection', global: 'ReactFiberTreeReflection', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: [], }, /******* Reconciler Constants *******/ { moduleType: RENDERER_UTILS, bundleTypes: [NODE_DEV, NODE_PROD], entry: 'react-reconciler/constants', global: 'ReactReconcilerConstants', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: [], }, /******* React Is *******/ { bundleTypes: [ NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, UMD_DEV, UMD_PROD, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, ], moduleType: ISOMORPHIC, entry: 'react-is', global: 'ReactIs', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: ['ReactNativeInternalFeatureFlags'], }, /******* React Debug Tools *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'react-debug-tools', global: 'ReactDebugTools', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [], }, /******* React Cache (experimental, old) *******/ { // This is only used by our own tests. // We can delete it later. bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'react-cache', global: 'ReactCacheOld', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'scheduler'], }, /******* Hook for managing subscriptions safely *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'use-subscription', global: 'useSubscription', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: true, externals: ['react'], }, /******* useSyncExternalStore *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'use-sync-external-store', global: 'useSyncExternalStore', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: true, externals: ['react'], }, /******* useSyncExternalStore (shim) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'use-sync-external-store/shim', global: 'useSyncExternalStore', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, externals: ['react'], }, /******* useSyncExternalStore (shim, native) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'use-sync-external-store/shim/index.native', global: 'useSyncExternalStore', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, externals: ['react'], }, /******* useSyncExternalStoreWithSelector *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'use-sync-external-store/with-selector', global: 'useSyncExternalStoreWithSelector', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, externals: ['react'], }, /******* useSyncExternalStoreWithSelector (shim) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'use-sync-external-store/shim/with-selector', global: 'useSyncExternalStoreWithSelector', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: true, externals: ['react', 'use-sync-external-store/shim'], }, /******* React Scheduler (experimental) *******/ { bundleTypes: [ NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING, ], moduleType: ISOMORPHIC, entry: 'scheduler', global: 'Scheduler', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: true, externals: ['ReactNativeInternalFeatureFlags'], }, /******* React Scheduler Mock (experimental) *******/ { bundleTypes: [ UMD_DEV, UMD_PROD, NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, RN_FB_DEV, RN_FB_PROD, ], moduleType: ISOMORPHIC, entry: 'scheduler/unstable_mock', global: 'SchedulerMock', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['ReactNativeInternalFeatureFlags'], }, /******* React Scheduler Native *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'scheduler/index.native', global: 'SchedulerNative', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['ReactNativeInternalFeatureFlags'], }, /******* React Scheduler Post Task (experimental) *******/ { bundleTypes: [ NODE_DEV, NODE_PROD, FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING, ], moduleType: ISOMORPHIC, entry: 'scheduler/unstable_post_task', global: 'SchedulerPostTask', minifyWithProdErrorCodes: true, wrapWithModuleBoundaries: false, externals: [], }, /******* Jest React (experimental) *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'jest-react', global: 'JestReact', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: ['react', 'scheduler', 'scheduler/unstable_mock'], }, /******* ESLint Plugin for Hooks *******/ { // TODO: it's awkward to create a bundle for this but if we don't, the package // won't get copied. We also can't create just DEV bundle because it contains a // NODE_ENV check inside. We should probably tweak our build process to allow // "raw" packages that don't get bundled. bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'eslint-plugin-react-hooks', global: 'ESLintPluginReactHooks', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [], }, /******* React Fresh *******/ { bundleTypes: [NODE_DEV, NODE_PROD], moduleType: ISOMORPHIC, entry: 'react-refresh/babel', global: 'ReactFreshBabelPlugin', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [], }, { bundleTypes: [NODE_DEV, NODE_PROD, FB_WWW_DEV], moduleType: ISOMORPHIC, entry: 'react-refresh/runtime', global: 'ReactFreshRuntime', minifyWithProdErrorCodes: false, wrapWithModuleBoundaries: false, externals: [], }, ]; // Based on deep-freeze by substack (public domain) function deepFreeze(o) { Object.freeze(o); Object.getOwnPropertyNames(o).forEach(function (prop) { if ( o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop]) ) { deepFreeze(o[prop]); } }); return o; } // Don't accidentally mutate config as part of the build deepFreeze(bundles); deepFreeze(bundleTypes); deepFreeze(moduleTypes); function getFilename(bundle, bundleType) { let name = bundle.name || bundle.entry; const globalName = bundle.global; // we do this to replace / to -, for react-dom/server name = name.replace('/index.', '.').replace('/', '-'); switch (bundleType) { case NODE_ES2015: return `${name}.js`; case BUN_DEV: return `${name}.development.js`; case BUN_PROD: return `${name}.production.min.js`; case ESM_DEV: return `${name}.development.js`; case ESM_PROD: return `${name}.production.min.js`; case UMD_DEV: return `${name}.development.js`; case UMD_PROD: return `${name}.production.min.js`; case UMD_PROFILING: return `${name}.profiling.min.js`; case NODE_DEV: return `${name}.development.js`; case NODE_PROD: return `${name}.production.min.js`; case NODE_PROFILING: return `${name}.profiling.min.js`; case FB_WWW_DEV: case RN_OSS_DEV: case RN_FB_DEV: return `${globalName}-dev.js`; case FB_WWW_PROD: case RN_OSS_PROD: case RN_FB_PROD: return `${globalName}-prod.js`; case FB_WWW_PROFILING: case RN_FB_PROFILING: case RN_OSS_PROFILING: return `${globalName}-profiling.js`; case BROWSER_SCRIPT: return `${name}.js`; } } module.exports = { bundleTypes, moduleTypes, bundles, getFilename, };
27.033135
83
0.632206
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 */ // TODO: direct imports like some-package/src/* are bad. Fix me. import {getCurrentFiberOwnerNameInDevOrNull} from 'react-reconciler/src/ReactCurrentFiber'; import {getFiberCurrentPropsFromNode} from './ReactDOMComponentTree'; import {getToStringValue, toString} from './ToStringValue'; import {updateValueIfChanged} from './inputValueTracking'; import getActiveElement from './getActiveElement'; import {disableInputAttributeSyncing} from 'shared/ReactFeatureFlags'; import {checkAttributeStringCoercion} from 'shared/CheckStringCoercion'; import type {ToStringValue} from './ToStringValue'; import escapeSelectorAttributeValueInsideDoubleQuotes from './escapeSelectorAttributeValueInsideDoubleQuotes'; let didWarnValueDefaultValue = false; let didWarnCheckedDefaultChecked = false; /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ export function validateInputProps(element: Element, props: Object) { if (__DEV__) { // Normally we check for undefined and null the same, but explicitly specifying both // properties, at all is probably worth warning for. We could move this either direction // and just make it ok to pass null or just check hasOwnProperty. if ( props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked ) { console.error( '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type, ); didWarnCheckedDefaultChecked = true; } if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue ) { console.error( '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type, ); didWarnValueDefaultValue = true; } } } export function updateInput( element: Element, value: ?string, defaultValue: ?string, lastDefaultValue: ?string, checked: ?boolean, defaultChecked: ?boolean, type: ?string, name: ?string, ) { const node: HTMLInputElement = (element: any); // Temporarily disconnect the input from any radio buttons. // Changing the type or name as the same time as changing the checked value // needs to be atomically applied. We can only ensure that by disconnecting // the name while do the mutations and then reapply the name after that's done. node.name = ''; if ( type != null && typeof type !== 'function' && typeof type !== 'symbol' && typeof type !== 'boolean' ) { if (__DEV__) { checkAttributeStringCoercion(type, 'type'); } node.type = type; } else { node.removeAttribute('type'); } if (value != null) { if (type === 'number') { if ( // $FlowFixMe[incompatible-type] (value === 0 && node.value === '') || // We explicitly want to coerce to number here if possible. // eslint-disable-next-line node.value != (value: any) ) { node.value = toString(getToStringValue(value)); } } else if (node.value !== toString(getToStringValue(value))) { node.value = toString(getToStringValue(value)); } } else if (type === 'submit' || type === 'reset') { // Submit/reset inputs need the attribute removed completely to avoid // blank-text buttons. node.removeAttribute('value'); } if (disableInputAttributeSyncing) { // When not syncing the value attribute, React only assigns a new value // whenever the defaultValue React prop has changed. When not present, // React does nothing if (defaultValue != null) { setDefaultValue(node, type, getToStringValue(defaultValue)); } else if (lastDefaultValue != null) { node.removeAttribute('value'); } } else { // When syncing the value attribute, the value comes from a cascade of // properties: // 1. The value React property // 2. The defaultValue React property // 3. Otherwise there should be no change if (value != null) { setDefaultValue(node, type, getToStringValue(value)); } else if (defaultValue != null) { setDefaultValue(node, type, getToStringValue(defaultValue)); } else if (lastDefaultValue != null) { node.removeAttribute('value'); } } if (disableInputAttributeSyncing) { // When not syncing the checked attribute, the attribute is directly // controllable from the defaultValue React property. It needs to be // updated as new props come in. if (defaultChecked == null) { node.removeAttribute('checked'); } else { node.defaultChecked = !!defaultChecked; } } else { // When syncing the checked attribute, it only changes when it needs // to be removed, such as transitioning from a checkbox into a text input if (checked == null && defaultChecked != null) { node.defaultChecked = !!defaultChecked; } } if (checked != null) { // Important to set this even if it's not a change in order to update input // value tracking with radio buttons // TODO: Should really update input value tracking for the whole radio // button group in an effect or something (similar to #27024) node.checked = checked && typeof checked !== 'function' && typeof checked !== 'symbol'; } if ( name != null && typeof name !== 'function' && typeof name !== 'symbol' && typeof name !== 'boolean' ) { if (__DEV__) { checkAttributeStringCoercion(name, 'name'); } node.name = toString(getToStringValue(name)); } else { node.removeAttribute('name'); } } export function initInput( element: Element, value: ?string, defaultValue: ?string, checked: ?boolean, defaultChecked: ?boolean, type: ?string, name: ?string, isHydrating: boolean, ) { const node: HTMLInputElement = (element: any); if ( type != null && typeof type !== 'function' && typeof type !== 'symbol' && typeof type !== 'boolean' ) { if (__DEV__) { checkAttributeStringCoercion(type, 'type'); } node.type = type; } if (value != null || defaultValue != null) { const isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the // default value provided by the browser. See: #12872 if (isButton && (value === undefined || value === null)) { return; } const defaultValueStr = defaultValue != null ? toString(getToStringValue(defaultValue)) : ''; const initialValue = value != null ? toString(getToStringValue(value)) : defaultValueStr; // Do not assign value if it is already set. This prevents user text input // from being lost during SSR hydration. if (!isHydrating) { if (disableInputAttributeSyncing) { // When not syncing the value attribute, the value property points // directly to the React prop. Only assign it if it exists. if (value != null) { // Always assign on buttons so that it is possible to assign an // empty string to clear button text. // // Otherwise, do not re-assign the value property if is empty. This // potentially avoids a DOM write and prevents Firefox (~60.0.1) from // prematurely marking required inputs as invalid. Equality is compared // to the current value in case the browser provided value is not an // empty string. if (isButton || toString(getToStringValue(value)) !== node.value) { node.value = toString(getToStringValue(value)); } } } else { // When syncing the value attribute, the value property should use // the wrapperState._initialValue property. This uses: // // 1. The value React property when present // 2. The defaultValue React property when present // 3. An empty string if (initialValue !== node.value) { node.value = initialValue; } } } if (disableInputAttributeSyncing) { // When not syncing the value attribute, assign the value attribute // directly from the defaultValue React property (when present) if (defaultValue != null) { node.defaultValue = defaultValueStr; } } else { // Otherwise, the value attribute is synchronized to the property, // so we assign defaultValue to the same thing as the value property // assignment step above. node.defaultValue = initialValue; } } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. const checkedOrDefault = checked != null ? checked : defaultChecked; // TODO: This 'function' or 'symbol' check isn't replicated in other places // so this semantic is inconsistent. const initialChecked = typeof checkedOrDefault !== 'function' && typeof checkedOrDefault !== 'symbol' && !!checkedOrDefault; if (isHydrating) { // Detach .checked from .defaultChecked but leave user input alone node.checked = node.checked; } else { node.checked = !!initialChecked; } if (disableInputAttributeSyncing) { // Only assign the checked attribute if it is defined. This saves // a DOM write when controlling the checked attribute isn't needed // (text inputs, submit/reset) if (defaultChecked != null) { node.defaultChecked = !node.defaultChecked; node.defaultChecked = !!defaultChecked; } } else { // When syncing the checked attribute, both the checked property and // attribute are assigned at the same time using defaultChecked. This uses: // // 1. The checked React property when present // 2. The defaultChecked React property when present // 3. Otherwise, false node.defaultChecked = !node.defaultChecked; node.defaultChecked = !!initialChecked; } // Name needs to be set at the end so that it applies atomically to connected radio buttons. if ( name != null && typeof name !== 'function' && typeof name !== 'symbol' && typeof name !== 'boolean' ) { if (__DEV__) { checkAttributeStringCoercion(name, 'name'); } node.name = name; } } export function restoreControlledInputState(element: Element, props: Object) { const rootNode: HTMLInputElement = (element: any); updateInput( rootNode, props.value, props.defaultValue, props.defaultValue, props.checked, props.defaultChecked, props.type, props.name, ); const name = props.name; if (props.type === 'radio' && name != null) { let queryRoot: Element = rootNode; while (queryRoot.parentNode) { queryRoot = ((queryRoot.parentNode: any): Element); } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form. It might not even be in the // document. Let's just use the local `querySelectorAll` to ensure we don't // miss anything. if (__DEV__) { checkAttributeStringCoercion(name, 'name'); } const group = queryRoot.querySelectorAll( 'input[name="' + escapeSelectorAttributeValueInsideDoubleQuotes('' + name) + '"][type="radio"]', ); for (let i = 0; i < group.length; i++) { const otherNode = ((group[i]: any): HTMLInputElement); if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. const otherProps: any = getFiberCurrentPropsFromNode(otherNode); if (!otherProps) { throw new Error( 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.', ); } // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. updateInput( otherNode, otherProps.value, otherProps.defaultValue, otherProps.defaultValue, otherProps.checked, otherProps.defaultChecked, otherProps.type, otherProps.name, ); } // If any updateInput() call set .checked to true, an input in this group // (often, `rootNode` itself) may have become unchecked for (let i = 0; i < group.length; i++) { const otherNode = ((group[i]: any): HTMLInputElement); if (otherNode.form !== rootNode.form) { continue; } updateValueIfChanged(otherNode); } } } // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 export function setDefaultValue( node: HTMLInputElement, type: ?string, value: ToStringValue, ) { if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js type !== 'number' || getActiveElement(node.ownerDocument) !== node ) { if (node.defaultValue !== toString(value)) { node.defaultValue = toString(value); } } }
34.731982
110
0.657905
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactContext} from 'shared/ReactTypes'; import {createContext} from 'react'; import Store from '../store'; import type {ViewAttributeSource} from 'react-devtools-shared/src/devtools/views/DevTools'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; export const BridgeContext: ReactContext<FrontendBridge> = createContext<FrontendBridge>(((null: any): FrontendBridge)); BridgeContext.displayName = 'BridgeContext'; export const StoreContext: ReactContext<Store> = createContext<Store>( ((null: any): Store), ); StoreContext.displayName = 'StoreContext'; export type ContextMenuContextType = { isEnabledForInspectedElement: boolean, viewAttributeSourceFunction: ViewAttributeSource | null, }; export const ContextMenuContext: ReactContext<ContextMenuContextType> = createContext<ContextMenuContextType>({ isEnabledForInspectedElement: false, viewAttributeSourceFunction: null, }); ContextMenuContext.displayName = 'ContextMenuContext'; export type OptionsContextType = { readOnly: boolean, hideSettings: boolean, hideToggleErrorAction: boolean, hideToggleSuspenseAction: boolean, hideLogAction: boolean, hideViewSourceAction: boolean, }; export const OptionsContext: ReactContext<OptionsContextType> = createContext<OptionsContextType>({ readOnly: false, hideSettings: false, hideToggleErrorAction: false, hideToggleSuspenseAction: false, hideLogAction: false, hideViewSourceAction: false, });
29.321429
91
0.771951
owtf
import TestCase from '../../TestCase'; import Iframe from '../../Iframe'; const React = window.React; class OnSelectIframe extends React.Component { state = {count: 0, value: 'Select Me!'}; _onSelect = event => { this.setState(({count}) => ({count: count + 1})); }; _onChange = event => { this.setState({value: event.target.value}); }; render() { const {count, value} = this.state; return ( <Iframe height={60}> Selection Event Count: {count} <input type="text" onSelect={this._onSelect} value={value} onChange={this._onChange} /> </Iframe> ); } } export default class OnSelectEventTestCase extends React.Component { render() { return ( <TestCase title="onSelect events within iframes" description="onSelect events should fire for elements rendered inside iframes"> <TestCase.Steps> <li>Highlight some of the text in the input below</li> <li>Move the cursor around using the arrow keys</li> </TestCase.Steps> <TestCase.ExpectedResult> The displayed count should increase as you highlight or move the cursor </TestCase.ExpectedResult> <OnSelectIframe /> </TestCase> ); } }
24.647059
87
0.592961
owtf
import TestCase from '../../TestCase'; import DragBox from './drag-box'; const React = window.React; class Drag extends React.Component { render() { return ( <TestCase title="Drag" description=""> <TestCase.Steps> <li>Drag the circle below with any pointer tool</li> </TestCase.Steps> <TestCase.ExpectedResult> While dragging, the circle must have turn blue to indicate that a pointer capture was received. </TestCase.ExpectedResult> <DragBox /> </TestCase> ); } } export default Drag;
21.538462
75
0.617094
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 {PriorityLevel} from './SchedulerPriorities'; import {enableProfiling} from './SchedulerFeatureFlags'; let runIdCounter: number = 0; let mainThreadIdCounter: number = 0; // Bytes per element is 4 const INITIAL_EVENT_LOG_SIZE = 131072; const MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes let eventLogSize = 0; let eventLogBuffer = null; let eventLog = null; let eventLogIndex = 0; const TaskStartEvent = 1; const TaskCompleteEvent = 2; const TaskErrorEvent = 3; const TaskCancelEvent = 4; const TaskRunEvent = 5; const TaskYieldEvent = 6; const SchedulerSuspendEvent = 7; const SchedulerResumeEvent = 8; function logEvent(entries: Array<number | PriorityLevel>) { if (eventLog !== null) { const offset = eventLogIndex; eventLogIndex += entries.length; if (eventLogIndex + 1 > eventLogSize) { eventLogSize *= 2; if (eventLogSize > MAX_EVENT_LOG_SIZE) { // Using console['error'] to evade Babel and ESLint console['error']( "Scheduler Profiling: Event log exceeded maximum size. Don't " + 'forget to call `stopLoggingProfilingEvents()`.', ); stopLoggingProfilingEvents(); return; } const newEventLog = new Int32Array(eventLogSize * 4); // $FlowFixMe[incompatible-call] found when upgrading Flow newEventLog.set(eventLog); eventLogBuffer = newEventLog.buffer; eventLog = newEventLog; } eventLog.set(entries, offset); } } export function startLoggingProfilingEvents(): void { eventLogSize = INITIAL_EVENT_LOG_SIZE; eventLogBuffer = new ArrayBuffer(eventLogSize * 4); eventLog = new Int32Array(eventLogBuffer); eventLogIndex = 0; } export function stopLoggingProfilingEvents(): ArrayBuffer | null { const buffer = eventLogBuffer; eventLogSize = 0; eventLogBuffer = null; eventLog = null; eventLogIndex = 0; return buffer; } export function markTaskStart( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: number, ) { if (enableProfiling) { if (eventLog !== null) { // performance.now returns a float, representing milliseconds. When the // event is logged, it's coerced to an int. Convert to microseconds to // maintain extra degrees of precision. logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]); } } } export function markTaskCompleted( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: number, ) { if (enableProfiling) { if (eventLog !== null) { logEvent([TaskCompleteEvent, ms * 1000, task.id]); } } } export function markTaskCanceled( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: number, ) { if (enableProfiling) { if (eventLog !== null) { logEvent([TaskCancelEvent, ms * 1000, task.id]); } } } export function markTaskErrored( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: number, ) { if (enableProfiling) { if (eventLog !== null) { logEvent([TaskErrorEvent, ms * 1000, task.id]); } } } export function markTaskRun( task: { id: number, priorityLevel: PriorityLevel, ... }, ms: number, ) { if (enableProfiling) { runIdCounter++; if (eventLog !== null) { logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]); } } } export function markTaskYield(task: {id: number, ...}, ms: number) { if (enableProfiling) { if (eventLog !== null) { logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]); } } } export function markSchedulerSuspended(ms: number) { if (enableProfiling) { mainThreadIdCounter++; if (eventLog !== null) { logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]); } } } export function markSchedulerUnsuspended(ms: number) { if (enableProfiling) { if (eventLog !== null) { logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]); } } }
22.372222
77
0.655492
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. * */ // Do not require this module directly! Use normal `invariant` calls with // template literal strings. The messages will be replaced with error codes // during build. function formatProdErrorMessage(code) { let url = 'https://reactjs.org/docs/error-decoder.html?invariant=' + code; for (let i = 1; i < arguments.length; i++) { url += '&args[]=' + encodeURIComponent(arguments[i]); } return ( `Minified React error #${code}; visit ${url} for the full message or ` + 'use the non-minified dev environment for full errors and additional ' + 'helpful warnings.' ); } export default formatProdErrorMessage;
30.769231
76
0.69697
cybersecurity-penetration-testing
import {completeBoundaryWithStyles} from './ReactDOMFizzInstructionSetInlineSource'; // This is a string so Closure's advanced compilation mode doesn't mangle it. // eslint-disable-next-line dot-notation window['$RM'] = new Map(); // eslint-disable-next-line dot-notation window['$RR'] = completeBoundaryWithStyles;
38.75
84
0.776025
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'; function evalStringConcat(ast) { switch (ast.type) { case 'StringLiteral': case 'Literal': // ESLint return ast.value; case 'BinaryExpression': // `+` if (ast.operator !== '+') { throw new Error('Unsupported binary operator ' + ast.operator); } return evalStringConcat(ast.left) + evalStringConcat(ast.right); default: throw new Error('Unsupported type ' + ast.type); } } exports.evalStringConcat = evalStringConcat; function evalStringAndTemplateConcat(ast, args) { switch (ast.type) { case 'StringLiteral': return ast.value; case 'BinaryExpression': // `+` if (ast.operator !== '+') { throw new Error('Unsupported binary operator ' + ast.operator); } return ( evalStringAndTemplateConcat(ast.left, args) + evalStringAndTemplateConcat(ast.right, args) ); case 'TemplateLiteral': { let elements = []; for (let i = 0; i < ast.quasis.length; i++) { const elementNode = ast.quasis[i]; if (elementNode.type !== 'TemplateElement') { throw new Error('Unsupported type ' + ast.type); } elements.push(elementNode.value.cooked); } args.push(...ast.expressions); return elements.join('%s'); } default: // Anything that's not a string is interpreted as an argument. args.push(ast); return '%s'; } } exports.evalStringAndTemplateConcat = evalStringAndTemplateConcat;
29.160714
71
0.626185
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('forwardRef', () => { let React; let ReactFeatureFlags; let ReactNoop; let Scheduler; let waitForAll; beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; }); it('should work without a ref to be forwarded', async () => { class Child extends React.Component { render() { Scheduler.log(this.props.value); return null; } } function Wrapper(props) { return <Child {...props} ref={props.forwardedRef} />; } const RefForwardingComponent = React.forwardRef((props, ref) => ( <Wrapper {...props} forwardedRef={ref} /> )); ReactNoop.render(<RefForwardingComponent value={123} />); await waitForAll([123]); }); it('should forward a ref for a single child', async () => { class Child extends React.Component { render() { Scheduler.log(this.props.value); return null; } } function Wrapper(props) { return <Child {...props} ref={props.forwardedRef} />; } const RefForwardingComponent = React.forwardRef((props, ref) => ( <Wrapper {...props} forwardedRef={ref} /> )); const ref = React.createRef(); ReactNoop.render(<RefForwardingComponent ref={ref} value={123} />); await waitForAll([123]); expect(ref.current instanceof Child).toBe(true); }); it('should forward a ref for multiple children', async () => { class Child extends React.Component { render() { Scheduler.log(this.props.value); return null; } } function Wrapper(props) { return <Child {...props} ref={props.forwardedRef} />; } const RefForwardingComponent = React.forwardRef((props, ref) => ( <Wrapper {...props} forwardedRef={ref} /> )); const ref = React.createRef(); ReactNoop.render( <div> <div /> <RefForwardingComponent ref={ref} value={123} /> <div /> </div>, ); await waitForAll([123]); expect(ref.current instanceof Child).toBe(true); }); it('should maintain child instance and ref through updates', async () => { class Child extends React.Component { constructor(props) { super(props); } render() { Scheduler.log(this.props.value); return null; } } function Wrapper(props) { return <Child {...props} ref={props.forwardedRef} />; } const RefForwardingComponent = React.forwardRef((props, ref) => ( <Wrapper {...props} forwardedRef={ref} /> )); let setRefCount = 0; let ref; const setRef = r => { setRefCount++; ref = r; }; ReactNoop.render(<RefForwardingComponent ref={setRef} value={123} />); await waitForAll([123]); expect(ref instanceof Child).toBe(true); expect(setRefCount).toBe(1); ReactNoop.render(<RefForwardingComponent ref={setRef} value={456} />); await waitForAll([456]); expect(ref instanceof Child).toBe(true); expect(setRefCount).toBe(1); }); it('should not break lifecycle error handling', async () => { class ErrorBoundary extends React.Component { state = {error: null}; componentDidCatch(error) { Scheduler.log('ErrorBoundary.componentDidCatch'); this.setState({error}); } render() { if (this.state.error) { Scheduler.log('ErrorBoundary.render: catch'); return null; } Scheduler.log('ErrorBoundary.render: try'); return this.props.children; } } class BadRender extends React.Component { render() { Scheduler.log('BadRender throw'); throw new Error('oops!'); } } function Wrapper(props) { const forwardedRef = props.forwardedRef; Scheduler.log('Wrapper'); return <BadRender {...props} ref={forwardedRef} />; } const RefForwardingComponent = React.forwardRef((props, ref) => ( <Wrapper {...props} forwardedRef={ref} /> )); const ref = React.createRef(); ReactNoop.render( <ErrorBoundary> <RefForwardingComponent ref={ref} /> </ErrorBoundary>, ); await waitForAll([ 'ErrorBoundary.render: try', 'Wrapper', 'BadRender throw', // React retries one more time 'ErrorBoundary.render: try', 'Wrapper', 'BadRender throw', // Errored again on retry. Now handle it. 'ErrorBoundary.componentDidCatch', 'ErrorBoundary.render: catch', ]); expect(ref.current).toBe(null); }); it('should not re-run the render callback on a deep setState', async () => { let inst; class Inner extends React.Component { render() { Scheduler.log('Inner'); inst = this; return <div ref={this.props.forwardedRef} />; } } function Middle(props) { Scheduler.log('Middle'); return <Inner {...props} />; } const Forward = React.forwardRef((props, ref) => { Scheduler.log('Forward'); return <Middle {...props} forwardedRef={ref} />; }); function App() { Scheduler.log('App'); return <Forward />; } ReactNoop.render(<App />); await waitForAll(['App', 'Forward', 'Middle', 'Inner']); inst.setState({}); await waitForAll(['Inner']); }); });
24.310345
78
0.599216
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. */ const instanceCache = new Map(); const instanceProps = new Map(); export function precacheFiberNode(hostInst, tag) { instanceCache.set(tag, hostInst); } export function uncacheFiberNode(tag) { instanceCache.delete(tag); instanceProps.delete(tag); } function getInstanceFromTag(tag) { return instanceCache.get(tag) || null; } function getTagFromInstance(inst) { let nativeInstance = inst.stateNode; let tag = nativeInstance._nativeTag; if (tag === undefined && nativeInstance.canonical != null) { // For compatibility with Fabric tag = nativeInstance.canonical.nativeTag; nativeInstance = nativeInstance.canonical.publicInstance; } if (!tag) { throw new Error('All native instances should have a tag.'); } return nativeInstance; } export { getInstanceFromTag as getClosestInstanceFromNode, getInstanceFromTag as getInstanceFromNode, getTagFromInstance as getNodeFromInstance, }; export function getFiberCurrentPropsFromNode(stateNode) { return instanceProps.get(stateNode._nativeTag) || null; } export function updateFiberProps(tag, props) { instanceProps.set(tag, props); }
23.981132
66
0.746032
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type WorkTag = | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27; export const FunctionComponent = 0; export const ClassComponent = 1; export const IndeterminateComponent = 2; // Before we know whether it is function or class export const HostRoot = 3; // Root of a host tree. Could be nested inside another node. export const HostPortal = 4; // A subtree. Could be an entry point to a different renderer. export const HostComponent = 5; export const HostText = 6; export const Fragment = 7; export const Mode = 8; export const ContextConsumer = 9; export const ContextProvider = 10; export const ForwardRef = 11; export const Profiler = 12; export const SuspenseComponent = 13; export const MemoComponent = 14; export const SimpleMemoComponent = 15; export const LazyComponent = 16; export const IncompleteClassComponent = 17; export const DehydratedFragment = 18; export const SuspenseListComponent = 19; export const ScopeComponent = 21; export const OffscreenComponent = 22; export const LegacyHiddenComponent = 23; export const CacheComponent = 24; export const TracingMarkerComponent = 25; export const HostHoistable = 26; export const HostSingleton = 27;
21.552239
91
0.70596
owtf
/** * Copyright (c) Facebook, Inc. and its affiliates. */ // To do: Make this ESM. // To do: properly check heading numbers (headings with the same text get // numbered, this script doesn’t check that). const assert = require('assert'); const fs = require('fs'); const GithubSlugger = require('github-slugger'); const walk = require('./walk'); let modules; function stripLinks(line) { return line.replace(/\[([^\]]+)\]\([^)]+\)/, (match, p1) => p1); } function addHeaderID(line, slugger) { // check if we're a header at all if (!line.startsWith('#')) { return line; } const match = /^(#+\s+)(.+?)(\s*\{(?:\/\*|#)([^\}\*\/]+)(?:\*\/)?\}\s*)?$/.exec(line); const before = match[1] + match[2]; const proc = modules .unified() .use(modules.remarkParse) .use(modules.remarkSlug); const tree = proc.runSync(proc.parse(before)); const head = tree.children[0]; assert( head && head.type === 'heading', 'expected `' + before + '` to be a heading, is it using a normal space after `#`?' ); const autoId = head.data.id; const existingId = match[4]; const id = existingId || autoId; // Ignore numbers: const cleanExisting = existingId ? existingId.replace(/-\d+$/, '') : undefined; const cleanAuto = autoId.replace(/-\d+$/, ''); if (cleanExisting && cleanExisting !== cleanAuto) { console.log( 'Note: heading `%s` has a different ID (`%s`) than what GH generates for it: `%s`:', before, existingId, autoId ); } return match[1] + match[2] + ' {/*' + id + '*/}'; } function addHeaderIDs(lines) { // Sluggers should be per file const slugger = new GithubSlugger(); let inCode = false; const results = []; lines.forEach((line) => { // Ignore code blocks if (line.startsWith('```')) { inCode = !inCode; results.push(line); return; } if (inCode) { results.push(line); return; } results.push(addHeaderID(line, slugger)); }); return results; } async function main(paths) { paths = paths.length === 0 ? ['src/content'] : paths; const [unifiedMod, remarkParseMod, remarkSlugMod] = await Promise.all([ import('unified'), import('remark-parse'), import('remark-slug'), ]); const unified = unifiedMod.unified; const remarkParse = remarkParseMod.default; const remarkSlug = remarkSlugMod.default; modules = {unified, remarkParse, remarkSlug}; const files = paths.map((path) => [...walk(path)]).flat(); files.forEach((file) => { if (!(file.endsWith('.md') || file.endsWith('.mdx'))) { return; } const content = fs.readFileSync(file, 'utf8'); const lines = content.split('\n'); const updatedLines = addHeaderIDs(lines); fs.writeFileSync(file, updatedLines.join('\n')); }); } module.exports = main;
24.567568
90
0.600634
null
'use strict'; module.exports = { env: { browser: true, }, globals: { // ES6 BigInt: 'readonly', Map: 'readonly', Set: 'readonly', Symbol: 'readonly', Proxy: 'readonly', WeakMap: 'readonly', WeakSet: 'readonly', Int8Array: 'readonly', Uint8Array: 'readonly', Uint8ClampedArray: 'readonly', Int16Array: 'readonly', Uint16Array: 'readonly', Int32Array: 'readonly', Uint32Array: 'readonly', Float32Array: 'readonly', Float64Array: 'readonly', BigInt64Array: 'readonly', BigUint64Array: 'readonly', DataView: 'readonly', ArrayBuffer: 'readonly', Reflect: 'readonly', globalThis: 'readonly', FinalizationRegistry: 'readonly', // Vendor specific MSApp: 'readonly', __REACT_DEVTOOLS_GLOBAL_HOOK__: 'readonly', // UMD wrapper code // TODO: this is too permissive. // Ideally we should only allow these *inside* the UMD wrapper. exports: 'readonly', module: 'readonly', define: 'readonly', require: 'readonly', global: 'readonly', // Internet Explorer setImmediate: 'readonly', // Trusted Types trustedTypes: 'readonly', // Scheduler profiling TaskController: 'readonly', reportError: 'readonly', AggregateError: 'readonly', // Flight Promise: 'readonly', // Temp AsyncLocalStorage: 'readonly', async_hooks: 'readonly', // Flight Webpack __webpack_chunk_load__: 'readonly', __webpack_require__: 'readonly', // Flight Turbopack __turbopack_load__: 'readonly', __turbopack_require__: 'readonly', // jest jest: 'readonly', // act IS_REACT_ACT_ENVIRONMENT: 'readonly', }, parserOptions: { ecmaVersion: 5, sourceType: 'script', }, rules: { 'no-undef': 'error', 'no-shadow-restricted-names': 'error', }, // These plugins aren't used, but eslint complains if an eslint-ignore comment // references unused plugins. An alternate approach could be to strip // eslint-ignore comments as part of the build. plugins: ['ft-flow', 'jest', 'no-for-of-loops', 'react', 'react-internal'], };
22.413043
80
0.621458
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from './client.browser';
20.727273
66
0.684874
Python-Penetration-Testing-for-Developers
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-server-dom-turbopack-server.edge.production.min.js'); } else { module.exports = require('./cjs/react-server-dom-turbopack-server.edge.development.js'); }
31.125
93
0.710938
null
'use strict'; const Table = require('cli-table'); const filesize = require('filesize'); const chalk = require('chalk'); const join = require('path').join; const fs = require('fs'); const mkdirp = require('mkdirp'); const BUNDLE_SIZES_FILE_NAME = join(__dirname, '../../build/bundle-sizes.json'); const prevBuildResults = fs.existsSync(BUNDLE_SIZES_FILE_NAME) ? require(BUNDLE_SIZES_FILE_NAME) : {bundleSizes: []}; const currentBuildResults = { // Mutated inside build.js during a build run. bundleSizes: [], }; function saveResults() { if (process.env.CIRCLE_NODE_TOTAL) { // In CI, write the bundle sizes to a subdirectory and append the node index // to the filename. A downstream job will consolidate these into a // single file. const nodeIndex = process.env.CIRCLE_NODE_INDEX; mkdirp.sync('build/sizes'); fs.writeFileSync( join('build', 'sizes', `bundle-sizes-${nodeIndex}.json`), JSON.stringify(currentBuildResults, null, 2) ); } else { // Write all the bundle sizes to a single JSON file. fs.writeFileSync( BUNDLE_SIZES_FILE_NAME, JSON.stringify(currentBuildResults, null, 2) ); } } function fractionalChange(prev, current) { return (current - prev) / prev; } function percentChangeString(change) { if (!isFinite(change)) { // When a new package is created return 'n/a'; } const formatted = (change * 100).toFixed(1); if (/^-|^0(?:\.0+)$/.test(formatted)) { return `${formatted}%`; } else { return `+${formatted}%`; } } const resultsHeaders = [ 'Bundle', 'Prev Size', 'Current Size', 'Diff', 'Prev Gzip', 'Current Gzip', 'Diff', ]; function generateResultsArray(current, prevResults) { return current.bundleSizes .map(result => { const prev = prevResults.bundleSizes.filter( res => res.filename === result.filename && res.bundleType === result.bundleType )[0]; if (result === prev) { // We didn't rebuild this bundle. return; } const size = result.size; const gzip = result.gzip; let prevSize = prev ? prev.size : 0; let prevGzip = prev ? prev.gzip : 0; return { filename: result.filename, bundleType: result.bundleType, packageName: result.packageName, prevSize: filesize(prevSize), prevFileSize: filesize(size), prevFileSizeChange: fractionalChange(prevSize, size), prevFileSizeAbsoluteChange: size - prevSize, prevGzip: filesize(prevGzip), prevGzipSize: filesize(gzip), prevGzipSizeChange: fractionalChange(prevGzip, gzip), prevGzipSizeAbsoluteChange: gzip - prevGzip, }; // Strip any nulls }) .filter(f => f); } function printResults() { const table = new Table({ head: resultsHeaders.map(label => chalk.gray.yellow(label)), }); const results = generateResultsArray(currentBuildResults, prevBuildResults); results.forEach(result => { table.push([ chalk.white.bold(`${result.filename} (${result.bundleType})`), chalk.gray.bold(result.prevSize), chalk.white.bold(result.prevFileSize), percentChangeString(result.prevFileSizeChange), chalk.gray.bold(result.prevGzip), chalk.white.bold(result.prevGzipSize), percentChangeString(result.prevGzipSizeChange), ]); }); return table.toString(); } module.exports = { currentBuildResults, generateResultsArray, printResults, saveResults, resultsHeaders, };
25.961832
80
0.647692