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. * * @flow */ import type {Node, HostComponent} from './ReactNativeTypes'; import type {ElementRef, ElementType} from 'react'; // Modules provided by RN: import { UIManager, legacySendAccessibilityEvent, getNodeFromPublicInstance, getNativeTagFromPublicInstance, getInternalInstanceHandleFromPublicInstance, } from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import { findHostInstance, findHostInstanceWithWarning, } from 'react-reconciler/src/ReactFiberReconciler'; import {doesFiberContain} from 'react-reconciler/src/ReactFiberTreeReflection'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import getComponentNameFromType from 'shared/getComponentNameFromType'; const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; export function findHostInstance_DEPRECATED<TElementType: ElementType>( componentOrHandle: ?(ElementRef<TElementType> | number), ): ?ElementRef<HostComponent<mixed>> { if (__DEV__) { const owner = ReactCurrentOwner.current; if (owner !== null && owner.stateNode !== null) { if (!owner.stateNode._warnedAboutRefsInRender) { console.error( '%s is accessing findNodeHandle inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component', ); } owner.stateNode._warnedAboutRefsInRender = true; } } if (componentOrHandle == null) { return null; } // For compatibility with Fabric instances if ( componentOrHandle.canonical && componentOrHandle.canonical.publicInstance ) { // $FlowExpectedError[incompatible-return] Can't refine componentOrHandle as a Fabric instance return componentOrHandle.canonical.publicInstance; } // For compatibility with legacy renderer instances if (componentOrHandle._nativeTag) { // $FlowFixMe[incompatible-exact] Necessary when running Flow on Fabric // $FlowFixMe[incompatible-return] return componentOrHandle; } let hostInstance; if (__DEV__) { hostInstance = findHostInstanceWithWarning( componentOrHandle, 'findHostInstance_DEPRECATED', ); } else { hostInstance = findHostInstance(componentOrHandle); } // findHostInstance handles legacy vs. Fabric differences correctly // $FlowFixMe[incompatible-exact] we need to fix the definition of `HostComponent` to use NativeMethods as an interface, not as a type. // $FlowFixMe[incompatible-return] return hostInstance; } export function findNodeHandle(componentOrHandle: any): ?number { if (__DEV__) { const owner = ReactCurrentOwner.current; if (owner !== null && owner.stateNode !== null) { if (!owner.stateNode._warnedAboutRefsInRender) { console.error( '%s is accessing findNodeHandle inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromType(owner.type) || 'A component', ); } owner.stateNode._warnedAboutRefsInRender = true; } } if (componentOrHandle == null) { return null; } if (typeof componentOrHandle === 'number') { // Already a node handle return componentOrHandle; } // For compatibility with legacy renderer instances if (componentOrHandle._nativeTag) { return componentOrHandle._nativeTag; } // For compatibility with Fabric instances if ( componentOrHandle.canonical != null && componentOrHandle.canonical.nativeTag != null ) { return componentOrHandle.canonical.nativeTag; } // For compatibility with Fabric public instances const nativeTag = getNativeTagFromPublicInstance(componentOrHandle); if (nativeTag) { return nativeTag; } let hostInstance; if (__DEV__) { hostInstance = findHostInstanceWithWarning( componentOrHandle, 'findNodeHandle', ); } else { hostInstance = findHostInstance(componentOrHandle); } if (hostInstance == null) { // $FlowFixMe[incompatible-return] Flow limitation in refining an opaque type return hostInstance; } if (hostInstance._nativeTag != null) { // $FlowFixMe[incompatible-return] For compatibility with legacy renderer instances return hostInstance._nativeTag; } // $FlowFixMe[incompatible-call] Necessary when running Flow on the legacy renderer return getNativeTagFromPublicInstance(hostInstance); } export function dispatchCommand( handle: any, command: string, args: Array<any>, ) { const nativeTag = handle._nativeTag != null ? handle._nativeTag : getNativeTagFromPublicInstance(handle); if (nativeTag == null) { if (__DEV__) { console.error( "dispatchCommand was called with a ref that isn't a " + 'native component. Use React.forwardRef to get access to the underlying native component', ); } return; } const node = getNodeFromPublicInstance(handle); if (node != null) { nativeFabricUIManager.dispatchCommand(node, command, args); } else { UIManager.dispatchViewManagerCommand(nativeTag, command, args); } } export function sendAccessibilityEvent(handle: any, eventType: string) { const nativeTag = handle._nativeTag != null ? handle._nativeTag : getNativeTagFromPublicInstance(handle); if (nativeTag == null) { if (__DEV__) { console.error( "sendAccessibilityEvent was called with a ref that isn't a " + 'native component. Use React.forwardRef to get access to the underlying native component', ); } return; } const node = getNodeFromPublicInstance(handle); if (node != null) { nativeFabricUIManager.sendAccessibilityEvent(node, eventType); } else { legacySendAccessibilityEvent(nativeTag, eventType); } } export function getNodeFromInternalInstanceHandle( internalInstanceHandle: mixed, ): ?Node { return ( // $FlowExpectedError[incompatible-return] internalInstanceHandle is opaque but we need to make an exception here. internalInstanceHandle && // $FlowExpectedError[incompatible-return] internalInstanceHandle.stateNode && // $FlowExpectedError[incompatible-use] internalInstanceHandle.stateNode.node ); } // Should have been PublicInstance from ReactFiberConfigFabric type FabricPublicInstance = mixed; // Should have been PublicInstance from ReactFiberConfigNative type PaperPublicInstance = HostComponent<mixed>; // Remove this once Paper is no longer supported and DOM Node API are enabled by default in RN. export function isChildPublicInstance( parentInstance: FabricPublicInstance | PaperPublicInstance, childInstance: FabricPublicInstance | PaperPublicInstance, ): boolean { if (__DEV__) { // Paper if ( // $FlowExpectedError[incompatible-type] // $FlowExpectedError[prop-missing] Don't check via `instanceof ReactNativeFiberHostComponent`, so it won't be leaked to Fabric. parentInstance._internalFiberInstanceHandleDEV && // $FlowExpectedError[incompatible-type] // $FlowExpectedError[prop-missing] Don't check via `instanceof ReactNativeFiberHostComponent`, so it won't be leaked to Fabric. childInstance._internalFiberInstanceHandleDEV ) { return doesFiberContain( // $FlowExpectedError[incompatible-call] parentInstance._internalFiberInstanceHandleDEV, // $FlowExpectedError[incompatible-call] childInstance._internalFiberInstanceHandleDEV, ); } const parentInternalInstanceHandle = // $FlowExpectedError[incompatible-call] Type for parentInstance should have been PublicInstance from ReactFiberConfigFabric. getInternalInstanceHandleFromPublicInstance(parentInstance); const childInternalInstanceHandle = // $FlowExpectedError[incompatible-call] Type for childInstance should have been PublicInstance from ReactFiberConfigFabric. getInternalInstanceHandleFromPublicInstance(childInstance); // Fabric if ( parentInternalInstanceHandle != null && childInternalInstanceHandle != null ) { return doesFiberContain( parentInternalInstanceHandle, childInternalInstanceHandle, ); } // Means that one instance is from Fabric and other is from Paper. return false; } else { throw new Error('isChildPublicInstance() is not available in production.'); } }
31.764493
137
0.714001
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import useEvent from './useEvent'; const {useCallback, useEffect, useLayoutEffect, useRef} = React; type FocusEvent = SyntheticEvent<EventTarget>; type UseFocusOptions = { disabled?: boolean, onBlur?: ?(FocusEvent) => void, onFocus?: ?(FocusEvent) => void, onFocusChange?: ?(boolean) => void, onFocusVisibleChange?: ?(boolean) => void, }; type UseFocusWithinOptions = { disabled?: boolean, onAfterBlurWithin?: FocusEvent => void, onBeforeBlurWithin?: FocusEvent => void, onBlurWithin?: FocusEvent => void, onFocusWithin?: FocusEvent => void, onFocusWithinChange?: boolean => void, onFocusWithinVisibleChange?: boolean => void, }; const isMac = typeof window !== 'undefined' && window.navigator != null ? /^Mac/.test(window.navigator.platform) : false; const hasPointerEvents = typeof window !== 'undefined' && window.PointerEvent != null; const globalFocusVisibleEvents = hasPointerEvents ? ['keydown', 'pointermove', 'pointerdown', 'pointerup'] : [ 'keydown', 'mousedown', 'mousemove', 'mouseup', 'touchmove', 'touchstart', 'touchend', ]; // Global state for tracking focus visible and emulation of mouse let isGlobalFocusVisible = true; let hasTrackedGlobalFocusVisible = false; function trackGlobalFocusVisible() { globalFocusVisibleEvents.forEach(type => { window.addEventListener(type, handleGlobalFocusVisibleEvent, true); }); } function isValidKey(nativeEvent: KeyboardEvent): boolean { const {metaKey, altKey, ctrlKey} = nativeEvent; return !(metaKey || (!isMac && altKey) || ctrlKey); } function isTextInput(nativeEvent: KeyboardEvent): boolean { const {key, target} = nativeEvent; if (key === 'Tab' || key === 'Escape') { return false; } const {isContentEditable, tagName} = (target: any); return tagName === 'INPUT' || tagName === 'TEXTAREA' || isContentEditable; } function handleGlobalFocusVisibleEvent( nativeEvent: MouseEvent | TouchEvent | KeyboardEvent, ): void { if (nativeEvent.type === 'keydown') { if (isValidKey(((nativeEvent: any): KeyboardEvent))) { isGlobalFocusVisible = true; } } else { const nodeName = (nativeEvent.target: any).nodeName; // Safari calls mousemove/pointermove events when you tab out of the active // Safari frame. if (nodeName === 'HTML') { return; } // Handle all the other mouse/touch/pointer events isGlobalFocusVisible = false; } } function handleFocusVisibleTargetEvents( event: SyntheticEvent<EventTarget>, callback: boolean => void, ): void { if (event.type === 'keydown') { const {nativeEvent} = (event: any); if (isValidKey(nativeEvent) && !isTextInput(nativeEvent)) { callback(true); } } else { callback(false); } } function isRelatedTargetWithin( focusWithinTarget: Object, relatedTarget: null | EventTarget, ): boolean { if (relatedTarget == null) { return false; } // As the focusWithinTarget can be a Scope Instance (experimental API), // we need to use the containsNode() method. Otherwise, focusWithinTarget // must be a Node, which means we can use the contains() method. return typeof focusWithinTarget.containsNode === 'function' ? focusWithinTarget.containsNode(relatedTarget) : focusWithinTarget.contains(relatedTarget); } function setFocusVisibleListeners( // $FlowFixMe[missing-local-annot] focusVisibleHandles, focusTarget: EventTarget, callback: boolean => void, ) { focusVisibleHandles.forEach(focusVisibleHandle => { focusVisibleHandle.setListener(focusTarget, event => handleFocusVisibleTargetEvents(event, callback), ); }); } function useFocusVisibleInputHandles() { return [ useEvent('mousedown'), useEvent(hasPointerEvents ? 'pointerdown' : 'touchstart'), useEvent('keydown'), ]; } function useFocusLifecycles() { useEffect(() => { if (!hasTrackedGlobalFocusVisible) { hasTrackedGlobalFocusVisible = true; trackGlobalFocusVisible(); } }, []); } export function useFocus( focusTargetRef: {current: null | Node}, { disabled, onBlur, onFocus, onFocusChange, onFocusVisibleChange, }: UseFocusOptions, ): void { // Setup controlled state for this useFocus hook const stateRef = useRef<null | { isFocused: boolean, isFocusVisible: boolean, }>({isFocused: false, isFocusVisible: false}); const focusHandle = useEvent('focusin'); const blurHandle = useEvent('focusout'); const focusVisibleHandles = useFocusVisibleInputHandles(); useLayoutEffect(() => { const focusTarget = focusTargetRef.current; const state = stateRef.current; if (focusTarget !== null && state !== null && focusTarget.nodeType === 1) { // Handle focus visible setFocusVisibleListeners( focusVisibleHandles, focusTarget, isFocusVisible => { if (state.isFocused && state.isFocusVisible !== isFocusVisible) { state.isFocusVisible = isFocusVisible; if (onFocusVisibleChange) { onFocusVisibleChange(isFocusVisible); } } }, ); // Handle focus focusHandle.setListener(focusTarget, (event: FocusEvent) => { if (disabled === true) { return; } if (!state.isFocused && focusTarget === event.target) { state.isFocused = true; state.isFocusVisible = isGlobalFocusVisible; if (onFocus) { onFocus(event); } if (onFocusChange) { onFocusChange(true); } if (state.isFocusVisible && onFocusVisibleChange) { onFocusVisibleChange(true); } } }); // Handle blur blurHandle.setListener(focusTarget, (event: FocusEvent) => { if (disabled === true) { return; } if (state.isFocused) { state.isFocused = false; state.isFocusVisible = isGlobalFocusVisible; if (onBlur) { onBlur(event); } if (onFocusChange) { onFocusChange(false); } if (state.isFocusVisible && onFocusVisibleChange) { onFocusVisibleChange(false); } } }); } }, [ blurHandle, disabled, focusHandle, focusTargetRef, focusVisibleHandles, onBlur, onFocus, onFocusChange, onFocusVisibleChange, ]); // Mount/Unmount logic useFocusLifecycles(); } export function useFocusWithin<T>( focusWithinTargetRef: | {current: null | T} | ((focusWithinTarget: null | T) => void), { disabled, onAfterBlurWithin, onBeforeBlurWithin, onBlurWithin, onFocusWithin, onFocusWithinChange, onFocusWithinVisibleChange, }: UseFocusWithinOptions, ): (focusWithinTarget: null | T) => void { // Setup controlled state for this useFocus hook const stateRef = useRef<null | { isFocused: boolean, isFocusVisible: boolean, }>({isFocused: false, isFocusVisible: false}); const focusHandle = useEvent('focusin'); const blurHandle = useEvent('focusout'); const afterBlurHandle = useEvent('afterblur'); const beforeBlurHandle = useEvent('beforeblur'); const focusVisibleHandles = useFocusVisibleInputHandles(); const useFocusWithinRef = useCallback( (focusWithinTarget: null | T) => { // Handle the incoming focusTargetRef. It can be either a function ref // or an object ref. if (typeof focusWithinTargetRef === 'function') { focusWithinTargetRef(focusWithinTarget); } else { focusWithinTargetRef.current = focusWithinTarget; } const state = stateRef.current; if (focusWithinTarget !== null && state !== null) { // Handle focus visible setFocusVisibleListeners( focusVisibleHandles, // $FlowFixMe[incompatible-call] focusWithinTarget is not null here focusWithinTarget, isFocusVisible => { if (state.isFocused && state.isFocusVisible !== isFocusVisible) { state.isFocusVisible = isFocusVisible; if (onFocusWithinVisibleChange) { onFocusWithinVisibleChange(isFocusVisible); } } }, ); // Handle focus // $FlowFixMe[incompatible-call] focusWithinTarget is not null here focusHandle.setListener(focusWithinTarget, (event: FocusEvent) => { if (disabled) { return; } if (!state.isFocused) { state.isFocused = true; state.isFocusVisible = isGlobalFocusVisible; if (onFocusWithinChange) { onFocusWithinChange(true); } if (state.isFocusVisible && onFocusWithinVisibleChange) { onFocusWithinVisibleChange(true); } } if (!state.isFocusVisible && isGlobalFocusVisible) { state.isFocusVisible = isGlobalFocusVisible; if (onFocusWithinVisibleChange) { onFocusWithinVisibleChange(true); } } if (onFocusWithin) { onFocusWithin(event); } }); // Handle blur // $FlowFixMe[incompatible-call] focusWithinTarget is not null here blurHandle.setListener(focusWithinTarget, (event: FocusEvent) => { if (disabled) { return; } const {relatedTarget} = (event.nativeEvent: any); if ( state.isFocused && !isRelatedTargetWithin(focusWithinTarget, relatedTarget) ) { state.isFocused = false; if (onFocusWithinChange) { onFocusWithinChange(false); } if (state.isFocusVisible && onFocusWithinVisibleChange) { onFocusWithinVisibleChange(false); } if (onBlurWithin) { onBlurWithin(event); } } }); // Handle before blur. This is a special // React provided event. // $FlowFixMe[incompatible-call] focusWithinTarget is not null here beforeBlurHandle.setListener(focusWithinTarget, (event: FocusEvent) => { if (disabled) { return; } if (onBeforeBlurWithin) { onBeforeBlurWithin(event); // Add an "afterblur" listener on document. This is a special // React provided event. afterBlurHandle.setListener( document, (afterBlurEvent: FocusEvent) => { if (onAfterBlurWithin) { onAfterBlurWithin(afterBlurEvent); } // Clear listener on document afterBlurHandle.setListener(document, null); }, ); } }); } }, [ afterBlurHandle, beforeBlurHandle, blurHandle, disabled, focusHandle, focusWithinTargetRef, onAfterBlurWithin, onBeforeBlurWithin, onBlurWithin, onFocusWithin, onFocusWithinChange, onFocusWithinVisibleChange, ], ); // Mount/Unmount logic useFocusLifecycles(); return useFocusWithinRef; }
27.758105
80
0.619287
PenetrationTestingScripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import typeof ReactTestRenderer from 'react-test-renderer'; import type {Element} from 'react-devtools-shared/src/frontend/types'; import type {FrontendBridge} from 'react-devtools-shared/src/bridge'; import type Store from 'react-devtools-shared/src/devtools/store'; describe('OwnersListContext', () => { let React; let TestRenderer: ReactTestRenderer; let bridge: FrontendBridge; let legacyRender; let store: Store; let utils; let BridgeContext; let OwnersListContext; let OwnersListContextController; let StoreContext; let TreeContextController; beforeEach(() => { utils = require('./utils'); utils.beforeEachProfiling(); legacyRender = utils.legacyRender; bridge = global.bridge; store = global.store; store.collapseNodesByDefault = false; React = require('react'); TestRenderer = utils.requireTestRenderer(); BridgeContext = require('react-devtools-shared/src/devtools/views/context').BridgeContext; OwnersListContext = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext').OwnersListContext; OwnersListContextController = require('react-devtools-shared/src/devtools/views/Components/OwnersListContext').OwnersListContextController; StoreContext = require('react-devtools-shared/src/devtools/views/context').StoreContext; TreeContextController = require('react-devtools-shared/src/devtools/views/Components/TreeContext').TreeContextController; }); const Contexts = ({children, defaultOwnerID = null}) => ( <BridgeContext.Provider value={bridge}> <StoreContext.Provider value={store}> <TreeContextController defaultOwnerID={defaultOwnerID}> <OwnersListContextController>{children}</OwnersListContextController> </TreeContextController> </StoreContext.Provider> </BridgeContext.Provider> ); async function getOwnersListForOwner(owner) { let ownerDisplayNames = null; function Suspender() { const read = React.useContext(OwnersListContext); const owners = read(owner.id); ownerDisplayNames = owners.map(({displayName}) => displayName); return null; } await utils.actAsync(() => TestRenderer.create( <Contexts defaultOwnerID={owner.id}> <React.Suspense fallback={null}> <Suspender owner={owner} /> </React.Suspense> </Contexts>, ), ); expect(ownerDisplayNames).not.toBeNull(); return ownerDisplayNames; } it('should fetch the owners list for the selected element', async () => { const Grandparent = () => <Parent />; const Parent = () => { return ( <React.Fragment> <Child /> <Child /> </React.Fragment> ); }; const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] β–Ύ <Grandparent> β–Ύ <Parent> <Child> <Child> `); const parent = ((store.getElementAtIndex(1): any): Element); const firstChild = ((store.getElementAtIndex(2): any): Element); expect(await getOwnersListForOwner(parent)).toMatchInlineSnapshot(` [ "Grandparent", "Parent", ] `); expect(await getOwnersListForOwner(firstChild)).toMatchInlineSnapshot(` [ "Grandparent", "Parent", "Child", ] `); }); it('should fetch the owners list for the selected element that includes filtered components', async () => { store.componentFilters = [utils.createDisplayNameFilter('^Parent$')]; const Grandparent = () => <Parent />; const Parent = () => { return ( <React.Fragment> <Child /> <Child /> </React.Fragment> ); }; const Child = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] β–Ύ <Grandparent> <Child> <Child> `); const firstChild = ((store.getElementAtIndex(1): any): Element); expect(await getOwnersListForOwner(firstChild)).toMatchInlineSnapshot(` [ "Grandparent", "Parent", "Child", ] `); }); it('should include the current element even if there are no other owners', async () => { store.componentFilters = [utils.createDisplayNameFilter('^Parent$')]; const Grandparent = () => <Parent />; const Parent = () => null; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] <Grandparent> `); const grandparent = ((store.getElementAtIndex(0): any): Element); expect(await getOwnersListForOwner(grandparent)).toMatchInlineSnapshot(` [ "Grandparent", ] `); }); it('should include all owners for a component wrapped in react memo', async () => { const InnerComponent = (props, ref) => <div ref={ref} />; const ForwardRef = React.forwardRef(InnerComponent); const Memo = React.memo(ForwardRef); const Grandparent = () => { const ref = React.createRef(); return <Memo ref={ref} />; }; utils.act(() => legacyRender(<Grandparent />, document.createElement('div')), ); expect(store).toMatchInlineSnapshot(` [root] β–Ύ <Grandparent> β–Ύ <InnerComponent> [Memo] <InnerComponent> [ForwardRef] `); const wrapped = ((store.getElementAtIndex(2): any): Element); expect(await getOwnersListForOwner(wrapped)).toMatchInlineSnapshot(` [ "Grandparent", "InnerComponent", "InnerComponent", ] `); }); });
26.2287
115
0.625927
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 {useState} = React; function Component(props) { const [foo] = useState(true); const bar = useState(true); const [baz] = React.useState(true); const [, forceUpdate] = useState(); return `${foo}-${bar}-${baz}`; } module.exports = {Component};
21.545455
66
0.662626
owtf
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-jsx-dev-runtime.production.min.js'); } else { module.exports = require('./cjs/react-jsx-dev-runtime.development.js'); }
26.875
76
0.684685
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} from 'shared/ReactTypes'; import {createContext} from 'react'; export type ShowFn = ({data: Object, pageX: number, pageY: number}) => void; export type HideFn = () => void; export type OnChangeFn = boolean => void; const idToShowFnMap = new Map<string, ShowFn>(); const idToHideFnMap = new Map<string, HideFn>(); let currentHide: ?HideFn = null; let currentOnChange: ?OnChangeFn = null; function hideMenu() { if (typeof currentHide === 'function') { currentHide(); if (typeof currentOnChange === 'function') { currentOnChange(false); } } currentHide = null; currentOnChange = null; } function showMenu({ data, id, onChange, pageX, pageY, }: { data: Object, id: string, onChange?: OnChangeFn, pageX: number, pageY: number, }) { const showFn = idToShowFnMap.get(id); if (typeof showFn === 'function') { // Prevent open menus from being left hanging. hideMenu(); currentHide = idToHideFnMap.get(id); showFn({data, pageX, pageY}); if (typeof onChange === 'function') { currentOnChange = onChange; onChange(true); } } } function registerMenu(id: string, showFn: ShowFn, hideFn: HideFn): () => void { if (idToShowFnMap.has(id)) { throw Error(`Context menu with id "${id}" already registered.`); } idToShowFnMap.set(id, showFn); idToHideFnMap.set(id, hideFn); return function unregisterMenu() { idToShowFnMap.delete(id); idToHideFnMap.delete(id); }; } export type RegistryContextType = { hideMenu: typeof hideMenu, showMenu: typeof showMenu, registerMenu: typeof registerMenu, }; export const RegistryContext: ReactContext<RegistryContextType> = createContext<RegistryContextType>({ hideMenu, showMenu, registerMenu, });
20.695652
79
0.67218
Hands-On-Penetration-Testing-with-Python
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Fragment, useContext, useEffect} from 'react'; import {ModalDialogContext} from './ModalDialog'; import {StoreContext} from './context'; import {currentBridgeProtocol} from 'react-devtools-shared/src/bridge'; import Button from './Button'; import ButtonIcon from './ButtonIcon'; import {copy} from 'clipboard-js'; import styles from './UnsupportedBridgeProtocolDialog.css'; import type {BridgeProtocol} from 'react-devtools-shared/src/bridge'; const DEVTOOLS_VERSION = process.env.DEVTOOLS_VERSION; const INSTRUCTIONS_FB_URL = 'https://fb.me/devtools-unsupported-bridge-protocol'; const MODAL_DIALOG_ID = 'UnsupportedBridgeProtocolDialog'; export default function UnsupportedBridgeProtocolDialog(_: {}): null { const {dialogs, dispatch} = useContext(ModalDialogContext); const store = useContext(StoreContext); const isVisible = !!dialogs.find(dialog => dialog.id === MODAL_DIALOG_ID); useEffect(() => { const updateDialog = () => { if (!isVisible) { if (store.unsupportedBridgeProtocolDetected) { dispatch({ canBeDismissed: false, id: MODAL_DIALOG_ID, type: 'SHOW', content: ( <DialogContent unsupportedBridgeProtocol={store.bridgeProtocol} /> ), }); } } else { if (!store.unsupportedBridgeProtocolDetected) { dispatch({ type: 'HIDE', id: MODAL_DIALOG_ID, }); } } }; updateDialog(); store.addListener('unsupportedBridgeProtocolDetected', updateDialog); return () => { store.removeListener('unsupportedBridgeProtocolDetected', updateDialog); }; }, [isVisible, store]); return null; } function DialogContent({ unsupportedBridgeProtocol, }: { unsupportedBridgeProtocol: BridgeProtocol, }) { const {version, minNpmVersion, maxNpmVersion} = unsupportedBridgeProtocol; let instructions; if (maxNpmVersion === null) { const upgradeInstructions = `npm i -g react-devtools@^${minNpmVersion}`; instructions = ( <> <p className={styles.Paragraph}> To fix this, upgrade the DevTools NPM package: </p> <pre className={styles.NpmCommand}> {upgradeInstructions} <Button onClick={() => copy(upgradeInstructions)} title="Copy upgrade command to clipboard"> <ButtonIcon type="copy" /> </Button> </pre> </> ); } else { const downgradeInstructions = `npm i -g react-devtools@${maxNpmVersion}`; instructions = ( <> <p className={styles.Paragraph}> To fix this, downgrade the DevTools NPM package: </p> <pre className={styles.NpmCommand}> {downgradeInstructions} <Button onClick={() => copy(downgradeInstructions)} title="Copy downgrade command to clipboard"> <ButtonIcon type="copy" /> </Button> </pre> </> ); } return ( <Fragment> <div className={styles.Column}> <div className={styles.Title}>Unsupported DevTools backend version</div> <p className={styles.Paragraph}> You are running <code>react-devtools</code> version{' '} <span className={styles.Version}>{DEVTOOLS_VERSION}</span>. </p> <p className={styles.Paragraph}> This requires bridge protocol{' '} <span className={styles.Version}> version {currentBridgeProtocol.version} </span> . However the current backend version uses bridge protocol{' '} <span className={styles.Version}>version {version}</span>. </p> {instructions} <p className={styles.Paragraph}> Or{' '} <a className={styles.Link} href={INSTRUCTIONS_FB_URL} target="_blank"> click here </a>{' '} for more information. </p> </div> </Fragment> ); }
29.482014
80
0.610718
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 */ export * from './src/ReactFlightClient';
21.363636
66
0.693878
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {useData} from './data'; export default function Comments() { const comments = useData(); return ( <> {comments.map((comment, i) => ( <p className="comment" key={i}> {comment} </p> ))} </> ); }
18.565217
66
0.579065
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const [count, setCount] = (0, _react.useState)(0); const isDarkMode = useIsDarkMode(); const { foo } = useFoo(); (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 25, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 26, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 27, columnNumber: 7 } }, "Foo: ", foo), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const [isDarkMode] = (0, _react.useState)(false); (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return isDarkMode; } function useFoo() { (0, _react.useDebugValue)('foo'); return { foo: true }; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhDdXN0b21Ib29rLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50Iiwic2V0Q291bnQiLCJpc0RhcmtNb2RlIiwidXNlSXNEYXJrTW9kZSIsImZvbyIsInVzZUZvbyIsImhhbmRsZUNsaWNrIiwidXNlRWZmZWN0Q3JlYXRlIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7Ozs7Ozs7O0FBRU8sU0FBU0EsU0FBVCxHQUFxQjtBQUMxQixRQUFNLENBQUNDLEtBQUQsRUFBUUMsUUFBUixJQUFvQixxQkFBUyxDQUFULENBQTFCO0FBQ0EsUUFBTUMsVUFBVSxHQUFHQyxhQUFhLEVBQWhDO0FBQ0EsUUFBTTtBQUFDQyxJQUFBQTtBQUFELE1BQVFDLE1BQU0sRUFBcEI7QUFFQSx3QkFBVSxNQUFNLENBQ2Q7QUFDRCxHQUZELEVBRUcsRUFGSDs7QUFJQSxRQUFNQyxXQUFXLEdBQUcsTUFBTUwsUUFBUSxDQUFDRCxLQUFLLEdBQUcsQ0FBVCxDQUFsQzs7QUFFQSxzQkFDRSx5RUFDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFBaUJFLFVBQWpCLENBREYsZUFFRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxnQkFBYUYsS0FBYixDQUZGLGVBR0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsY0FBV0ksR0FBWCxDQUhGLGVBSUU7QUFBUSxJQUFBLE9BQU8sRUFBRUUsV0FBakI7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsb0JBSkYsQ0FERjtBQVFEOztBQUVELFNBQVNILGFBQVQsR0FBeUI7QUFDdkIsUUFBTSxDQUFDRCxVQUFELElBQWUscUJBQVMsS0FBVCxDQUFyQjtBQUVBLHdCQUFVLFNBQVNLLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU9MLFVBQVA7QUFDRDs7QUFFRCxTQUFTRyxNQUFULEdBQWtCO0FBQ2hCLDRCQUFjLEtBQWQ7QUFDQSxTQUFPO0FBQUNELElBQUFBLEdBQUcsRUFBRTtBQUFOLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QsIHt1c2VEZWJ1Z1ZhbHVlLCB1c2VFZmZlY3QsIHVzZVN0YXRlfSBmcm9tICdyZWFjdCc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IFtjb3VudCwgc2V0Q291bnRdID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGlzRGFya01vZGUgPSB1c2VJc0RhcmtNb2RlKCk7XG4gIGNvbnN0IHtmb299ID0gdXNlRm9vKCk7XG5cbiAgdXNlRWZmZWN0KCgpID0+IHtcbiAgICAvLyAuLi5cbiAgfSwgW10pO1xuXG4gIGNvbnN0IGhhbmRsZUNsaWNrID0gKCkgPT4gc2V0Q291bnQoY291bnQgKyAxKTtcblxuICByZXR1cm4gKFxuICAgIDw+XG4gICAgICA8ZGl2PkRhcmsgbW9kZT8ge2lzRGFya01vZGV9PC9kaXY+XG4gICAgICA8ZGl2PkNvdW50OiB7Y291bnR9PC9kaXY+XG4gICAgICA8ZGl2PkZvbzoge2Zvb308L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSB1c2VTdGF0ZShmYWxzZSk7XG5cbiAgdXNlRWZmZWN0KGZ1bmN0aW9uIHVzZUVmZmVjdENyZWF0ZSgpIHtcbiAgICAvLyBIZXJlIGlzIHdoZXJlIHdlIG1heSBsaXN0ZW4gdG8gYSBcInRoZW1lXCIgZXZlbnQuLi5cbiAgfSwgW10pO1xuXG4gIHJldHVybiBpc0RhcmtNb2RlO1xufVxuXG5mdW5jdGlvbiB1c2VGb28oKSB7XG4gIHVzZURlYnVnVmFsdWUoJ2ZvbycpO1xuICByZXR1cm4ge2ZvbzogdHJ1ZX07XG59XG4iXX19XX0=
76.264706
2,772
0.822006
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ // Renderers that don't support microtasks // can re-export everything from this module. function shim(...args: any): empty { throw new Error( 'The current renderer does not support microtasks. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.', ); } // Test selectors (when unsupported) export const supportsMicrotasks = false; export const scheduleMicrotask = shim;
25
66
0.698234
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/ReactNoop';
20.636364
66
0.683544
owtf
import {parse, stringify} from 'query-string'; import VersionPicker from './VersionPicker'; const React = window.React; class Header extends React.Component { constructor(props, context) { super(props, context); const query = parse(window.location.search); const version = query.version || 'local'; const production = query.production || false; const versions = [version]; this.state = {version, versions, production}; } handleVersionChange(version) { const query = parse(window.location.search); query.version = version; if (query.version === 'local') { delete query.version; } window.location.search = stringify(query); } handleProductionChange(event) { const query = parse(window.location.search); query.production = event.target.checked; if (!query.production) { delete query.production; } window.location.search = stringify(query); } handleFixtureChange(event) { window.location.pathname = event.target.value; } render() { return ( <header className="header"> <div className="header__inner"> <span className="header__logo"> <img src={process.env.PUBLIC_URL + '/react-logo.svg'} alt="React" width="20" height="20" /> <a href="/"> DOM Test Fixtures (v {React.version}) </a> </span> <div className="header-controls"> <input id="react_production" className="header__checkbox" type="checkbox" checked={this.state.production} onChange={this.handleProductionChange} /> <label htmlFor="react_production" className="header__label"> Production </label> <label htmlFor="example"> <span className="sr-only">Select an example</span> <select value={window.location.pathname} onChange={this.handleFixtureChange}> <option value="/">Home</option> <option value="/hydration">Hydration</option> <option value="/range-inputs">Range Inputs</option> <option value="/text-inputs">Text Inputs</option> <option value="/number-inputs">Number Input</option> <option value="/password-inputs">Password Input</option> <option value="/email-inputs">Email Input</option> <option value="/selects">Selects</option> <option value="/textareas">Textareas</option> <option value="/progress">Progress</option> <option value="/input-change-events"> Input change events </option> <option value="/buttons">Buttons</option> <option value="/date-inputs">Date Inputs</option> <option value="/error-handling">Error Handling</option> <option value="/event-pooling">Event Pooling</option> <option value="/custom-elements">Custom Elements</option> <option value="/media-events">Media Events</option> <option value="/pointer-events">Pointer Events</option> <option value="/mouse-events">Mouse Events</option> <option value="/selection-events">Selection Events</option> <option value="/suspense">Suspense</option> <option value="/form-state">Form State</option> </select> </label> <label htmlFor="global_version"> <span className="sr-only">Select a version to test</span> <VersionPicker id="global_version" name="global_version" version={this.state.version} onChange={this.handleVersionChange} /> </label> </div> </div> </header> ); } } export default Header;
35.702703
75
0.552664
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 ReactVersion from 'shared/ReactVersion'; import { REACT_FRAGMENT_TYPE, REACT_DEBUG_TRACING_MODE_TYPE, REACT_PROFILER_TYPE, REACT_STRICT_MODE_TYPE, REACT_SUSPENSE_TYPE, REACT_SUSPENSE_LIST_TYPE, REACT_LEGACY_HIDDEN_TYPE, REACT_OFFSCREEN_TYPE, REACT_SCOPE_TYPE, REACT_CACHE_TYPE, REACT_TRACING_MARKER_TYPE, } from 'shared/ReactSymbols'; import {Component, PureComponent} from './ReactBaseClasses'; import {createRef} from './ReactCreateRef'; import {forEach, map, count, toArray, only} from './ReactChildren'; import { createElement as createElementProd, createFactory as createFactoryProd, cloneElement as cloneElementProd, isValidElement, } from './ReactElement'; import {createContext} from './ReactContext'; import {lazy} from './ReactLazy'; import {forwardRef} from './ReactForwardRef'; import {memo} from './ReactMemo'; import {cache} from './ReactCache'; import {postpone} from './ReactPostpone'; import { getCacheSignal, getCacheForType, useCallback, useContext, useEffect, useEffectEvent, useImperativeHandle, useDebugValue, useInsertionEffect, useLayoutEffect, useMemo, useSyncExternalStore, useReducer, useRef, useState, useTransition, useDeferredValue, useId, useCacheRefresh, use, useMemoCache, useOptimistic, } from './ReactHooks'; import { createElementWithValidation, createFactoryWithValidation, cloneElementWithValidation, } from './ReactElementValidator'; import {createServerContext} from './ReactServerContext'; import ReactSharedInternals from './ReactSharedInternalsClient'; import {startTransition} from './ReactStartTransition'; import {act} from './ReactAct'; // TODO: Move this branching into the other module instead and just re-export. const createElement: any = __DEV__ ? createElementWithValidation : createElementProd; const cloneElement: any = __DEV__ ? cloneElementWithValidation : cloneElementProd; const createFactory: any = __DEV__ ? createFactoryWithValidation : createFactoryProd; const Children = { map, forEach, count, toArray, only, }; export { Children, createRef, Component, PureComponent, createContext, createServerContext, forwardRef, lazy, memo, cache, postpone as unstable_postpone, useCallback, useContext, useEffect, useEffectEvent as experimental_useEffectEvent, useImperativeHandle, useDebugValue, useInsertionEffect, useLayoutEffect, useMemo, useOptimistic, useSyncExternalStore, useReducer, useRef, useState, REACT_FRAGMENT_TYPE as Fragment, REACT_PROFILER_TYPE as Profiler, REACT_STRICT_MODE_TYPE as StrictMode, REACT_DEBUG_TRACING_MODE_TYPE as unstable_DebugTracingMode, REACT_SUSPENSE_TYPE as Suspense, createElement, cloneElement, isValidElement, ReactVersion as version, ReactSharedInternals as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, // Deprecated behind disableCreateFactory createFactory, // Concurrent Mode useTransition, startTransition, useDeferredValue, REACT_SUSPENSE_LIST_TYPE as unstable_SuspenseList, REACT_LEGACY_HIDDEN_TYPE as unstable_LegacyHidden, REACT_OFFSCREEN_TYPE as unstable_Activity, getCacheSignal as unstable_getCacheSignal, getCacheForType as unstable_getCacheForType, useCacheRefresh as unstable_useCacheRefresh, REACT_CACHE_TYPE as unstable_Cache, use, useMemoCache as unstable_useMemoCache, // enableScopeAPI REACT_SCOPE_TYPE as unstable_Scope, // enableTransitionTracing REACT_TRACING_MARKER_TYPE as unstable_TracingMarker, useId, act, };
23.953642
78
0.757898
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-Second-Edition
import _extends from '@babel/runtime/helpers/esm/extends'; import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose'; import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized'; import memoizeOne from 'memoize-one'; import { createElement, PureComponent } from 'react'; import { flushSync } from 'react-dom'; import _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose'; // Animation frame based implementation of setTimeout. // Inspired by Joe Lambert, https://gist.github.com/joelambert/1002116#file-requesttimeout-js var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; var now = hasNativePerformanceNow ? function () { return performance.now(); } : function () { return Date.now(); }; function cancelTimeout(timeoutID) { cancelAnimationFrame(timeoutID.id); } function requestTimeout(callback, delay) { var start = now(); function tick() { if (now() - start >= delay) { callback.call(null); } else { timeoutID.id = requestAnimationFrame(tick); } } var timeoutID = { id: requestAnimationFrame(tick) }; return timeoutID; } var size = -1; // This utility copied from "dom-helpers" package. function getScrollbarSize(recalculate) { if (recalculate === void 0) { recalculate = false; } if (size === -1 || recalculate) { var div = document.createElement('div'); var style = div.style; style.width = '50px'; style.height = '50px'; style.overflow = 'scroll'; document.body.appendChild(div); size = div.offsetWidth - div.clientWidth; document.body.removeChild(div); } return size; } var cachedRTLResult = null; // TRICKY According to the spec, scrollLeft should be negative for RTL aligned elements. // Chrome does not seem to adhere; its scrollLeft values are positive (measured relative to the left). // Safari's elastic bounce makes detecting this even more complicated wrt potential false positives. // The safest way to check this is to intentionally set a negative offset, // and then verify that the subsequent "scroll" event matches the negative offset. // If it does not match, then we can assume a non-standard RTL scroll implementation. function getRTLOffsetType(recalculate) { if (recalculate === void 0) { recalculate = false; } if (cachedRTLResult === null || recalculate) { var outerDiv = document.createElement('div'); var outerStyle = outerDiv.style; outerStyle.width = '50px'; outerStyle.height = '50px'; outerStyle.overflow = 'scroll'; outerStyle.direction = 'rtl'; var innerDiv = document.createElement('div'); var innerStyle = innerDiv.style; innerStyle.width = '100px'; innerStyle.height = '100px'; outerDiv.appendChild(innerDiv); document.body.appendChild(outerDiv); if (outerDiv.scrollLeft > 0) { cachedRTLResult = 'positive-descending'; } else { outerDiv.scrollLeft = 1; if (outerDiv.scrollLeft === 0) { cachedRTLResult = 'negative'; } else { cachedRTLResult = 'positive-ascending'; } } document.body.removeChild(outerDiv); return cachedRTLResult; } return cachedRTLResult; } var IS_SCROLLING_DEBOUNCE_INTERVAL = 150; var defaultItemKey = function defaultItemKey(_ref) { var columnIndex = _ref.columnIndex, data = _ref.data, rowIndex = _ref.rowIndex; return 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. var devWarningsOverscanCount = null; var devWarningsOverscanRowsColumnsCount = null; var devWarningsTagName = null; if (process.env.NODE_ENV !== 'production') { if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') { devWarningsOverscanCount = /*#__PURE__*/ new WeakSet(); devWarningsOverscanRowsColumnsCount = /*#__PURE__*/ new WeakSet(); devWarningsTagName = /*#__PURE__*/ new WeakSet(); } } function createGridComponent(_ref2) { var _class, _temp; var getColumnOffset = _ref2.getColumnOffset, getColumnStartIndexForOffset = _ref2.getColumnStartIndexForOffset, getColumnStopIndexForStartIndex = _ref2.getColumnStopIndexForStartIndex, getColumnWidth = _ref2.getColumnWidth, getEstimatedTotalHeight = _ref2.getEstimatedTotalHeight, getEstimatedTotalWidth = _ref2.getEstimatedTotalWidth, getOffsetForColumnAndAlignment = _ref2.getOffsetForColumnAndAlignment, getOffsetForRowAndAlignment = _ref2.getOffsetForRowAndAlignment, getRowHeight = _ref2.getRowHeight, getRowOffset = _ref2.getRowOffset, getRowStartIndexForOffset = _ref2.getRowStartIndexForOffset, getRowStopIndexForStartIndex = _ref2.getRowStopIndexForStartIndex, initInstanceProps = _ref2.initInstanceProps, shouldResetStyleCacheOnItemSizeChange = _ref2.shouldResetStyleCacheOnItemSizeChange, validateProps = _ref2.validateProps; return _temp = _class = /*#__PURE__*/ function (_PureComponent) { _inheritsLoose(Grid, _PureComponent); // Always use explicit constructor for React components. // It produces less code after transpilation. (#26) // eslint-disable-next-line no-useless-constructor function Grid(props) { var _this; _this = _PureComponent.call(this, props) || this; _this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_assertThisInitialized(_this))); _this._resetIsScrollingTimeoutId = null; _this._outerRef = void 0; _this.state = { instance: _assertThisInitialized(_assertThisInitialized(_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' }; _this._callOnItemsRendered = void 0; _this._callOnItemsRendered = memoizeOne(function (overscanColumnStartIndex, overscanColumnStopIndex, overscanRowStartIndex, overscanRowStopIndex, visibleColumnStartIndex, visibleColumnStopIndex, visibleRowStartIndex, visibleRowStopIndex) { return _this.props.onItemsRendered({ overscanColumnStartIndex: overscanColumnStartIndex, overscanColumnStopIndex: overscanColumnStopIndex, overscanRowStartIndex: overscanRowStartIndex, overscanRowStopIndex: overscanRowStopIndex, visibleColumnStartIndex: visibleColumnStartIndex, visibleColumnStopIndex: visibleColumnStopIndex, visibleRowStartIndex: visibleRowStartIndex, visibleRowStopIndex: visibleRowStopIndex }); }); _this._callOnScroll = void 0; _this._callOnScroll = memoizeOne(function (scrollLeft, scrollTop, horizontalScrollDirection, verticalScrollDirection, scrollUpdateWasRequested) { return _this.props.onScroll({ horizontalScrollDirection: horizontalScrollDirection, scrollLeft: scrollLeft, scrollTop: scrollTop, verticalScrollDirection: verticalScrollDirection, scrollUpdateWasRequested: scrollUpdateWasRequested }); }); _this._getItemStyle = void 0; _this._getItemStyle = function (rowIndex, columnIndex) { var _this$props = _this.props, columnWidth = _this$props.columnWidth, direction = _this$props.direction, rowHeight = _this$props.rowHeight; var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && columnWidth, shouldResetStyleCacheOnItemSizeChange && direction, shouldResetStyleCacheOnItemSizeChange && rowHeight); var key = rowIndex + ":" + columnIndex; var style; if (itemStyleCache.hasOwnProperty(key)) { style = itemStyleCache[key]; } else { var _style; itemStyleCache[key] = style = (_style = { position: 'absolute' }, _style[direction === 'rtl' ? 'right' : 'left'] = getColumnOffset(_this.props, columnIndex, _this._instanceProps), _style.top = getRowOffset(_this.props, rowIndex, _this._instanceProps), _style.height = getRowHeight(_this.props, rowIndex, _this._instanceProps), _style.width = getColumnWidth(_this.props, columnIndex, _this._instanceProps), _style); } return style; }; _this._getItemStyleCache = void 0; _this._getItemStyleCache = memoizeOne(function (_, __, ___) { return {}; }); _this._onScroll = function (event) { var _event$currentTarget = event.currentTarget, clientHeight = _event$currentTarget.clientHeight, clientWidth = _event$currentTarget.clientWidth, scrollLeft = _event$currentTarget.scrollLeft, scrollTop = _event$currentTarget.scrollTop, scrollHeight = _event$currentTarget.scrollHeight, scrollWidth = _event$currentTarget.scrollWidth; // Force flush sync for scroll updates to reduce visual checkerboarding. flushSync(() => { _this.setState(function (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; } var direction = _this.props.direction; // 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. var 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)); var 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); }); }; _this._outerRefSetter = function (ref) { var outerRef = _this.props.outerRef; _this._outerRef = ref; if (typeof outerRef === 'function') { outerRef(ref); } else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) { outerRef.current = ref; } }; _this._resetIsScrollingDebounced = function () { if (_this._resetIsScrollingTimeoutId !== null) { cancelTimeout(_this._resetIsScrollingTimeoutId); } _this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL); }; _this._resetIsScrolling = function () { _this._resetIsScrollingTimeoutId = null; _this.setState({ isScrolling: false }, function () { // 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); }); }; return _this; } Grid.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) { validateSharedProps(nextProps, prevState); validateProps(nextProps); return null; }; var _proto = Grid.prototype; _proto.scrollTo = function scrollTo(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop; if (scrollLeft !== undefined) { scrollLeft = Math.max(0, scrollLeft); } if (scrollTop !== undefined) { scrollTop = Math.max(0, scrollTop); } this.setState(function (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); }; _proto.scrollToItem = function scrollToItem(_ref4) { var _ref4$align = _ref4.align, align = _ref4$align === void 0 ? 'auto' : _ref4$align, columnIndex = _ref4.columnIndex, rowIndex = _ref4.rowIndex; var _this$props2 = this.props, columnCount = _this$props2.columnCount, height = _this$props2.height, rowCount = _this$props2.rowCount, width = _this$props2.width; var _this$state = this.state, scrollLeft = _this$state.scrollLeft, scrollTop = _this$state.scrollTop; var 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)); } var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps); var 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. var horizontalScrollbarSize = estimatedTotalWidth > width ? scrollbarSize : 0; var 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 }); }; _proto.componentDidMount = function componentDidMount() { var _this$props3 = this.props, initialScrollLeft = _this$props3.initialScrollLeft, initialScrollTop = _this$props3.initialScrollTop; if (this._outerRef != null) { var outerRef = this._outerRef; if (typeof initialScrollLeft === 'number') { outerRef.scrollLeft = initialScrollLeft; } if (typeof initialScrollTop === 'number') { outerRef.scrollTop = initialScrollTop; } } this._callPropsCallbacks(); }; _proto.componentDidUpdate = function componentDidUpdate() { var direction = this.props.direction; var _this$state2 = this.state, scrollLeft = _this$state2.scrollLeft, scrollTop = _this$state2.scrollTop, scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested; 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. var outerRef = this._outerRef; if (direction === 'rtl') { switch (getRTLOffsetType()) { case 'negative': outerRef.scrollLeft = -scrollLeft; break; case 'positive-ascending': outerRef.scrollLeft = scrollLeft; break; default: var clientWidth = outerRef.clientWidth, scrollWidth = outerRef.scrollWidth; outerRef.scrollLeft = scrollWidth - clientWidth - scrollLeft; break; } } else { outerRef.scrollLeft = Math.max(0, scrollLeft); } outerRef.scrollTop = Math.max(0, scrollTop); } this._callPropsCallbacks(); }; _proto.componentWillUnmount = function componentWillUnmount() { if (this._resetIsScrollingTimeoutId !== null) { cancelTimeout(this._resetIsScrollingTimeoutId); } }; _proto.render = function render() { var _this$props4 = this.props, children = _this$props4.children, className = _this$props4.className, columnCount = _this$props4.columnCount, direction = _this$props4.direction, height = _this$props4.height, innerRef = _this$props4.innerRef, innerElementType = _this$props4.innerElementType, innerTagName = _this$props4.innerTagName, itemData = _this$props4.itemData, _this$props4$itemKey = _this$props4.itemKey, itemKey = _this$props4$itemKey === void 0 ? defaultItemKey : _this$props4$itemKey, outerElementType = _this$props4.outerElementType, outerTagName = _this$props4.outerTagName, rowCount = _this$props4.rowCount, style = _this$props4.style, useIsScrolling = _this$props4.useIsScrolling, width = _this$props4.width; var isScrolling = this.state.isScrolling; var _this$_getHorizontalR = this._getHorizontalRangeToRender(), columnStartIndex = _this$_getHorizontalR[0], columnStopIndex = _this$_getHorizontalR[1]; var _this$_getVerticalRan = this._getVerticalRangeToRender(), rowStartIndex = _this$_getVerticalRan[0], rowStopIndex = _this$_getVerticalRan[1]; var items = []; if (columnCount > 0 && rowCount) { for (var _rowIndex = rowStartIndex; _rowIndex <= rowStopIndex; _rowIndex++) { for (var _columnIndex = columnStartIndex; _columnIndex <= columnStopIndex; _columnIndex++) { items.push(createElement(children, { columnIndex: _columnIndex, data: itemData, isScrolling: useIsScrolling ? isScrolling : undefined, key: itemKey({ columnIndex: _columnIndex, data: itemData, rowIndex: _rowIndex }), 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. var estimatedTotalHeight = getEstimatedTotalHeight(this.props, this._instanceProps); var estimatedTotalWidth = getEstimatedTotalWidth(this.props, this._instanceProps); return createElement(outerElementType || outerTagName || 'div', { className: className, onScroll: this._onScroll, ref: this._outerRefSetter, style: _extends({ position: 'relative', height: height, width: width, overflow: 'auto', WebkitOverflowScrolling: 'touch', willChange: 'transform', direction: direction }, style) }, createElement(innerElementType || innerTagName || 'div', { children: items, ref: innerRef, style: { height: estimatedTotalHeight, pointerEvents: isScrolling ? 'none' : undefined, width: estimatedTotalWidth } })); }; _proto._callPropsCallbacks = function _callPropsCallbacks() { var _this$props5 = this.props, columnCount = _this$props5.columnCount, onItemsRendered = _this$props5.onItemsRendered, onScroll = _this$props5.onScroll, rowCount = _this$props5.rowCount; if (typeof onItemsRendered === 'function') { if (columnCount > 0 && rowCount > 0) { var _this$_getHorizontalR2 = this._getHorizontalRangeToRender(), _overscanColumnStartIndex = _this$_getHorizontalR2[0], _overscanColumnStopIndex = _this$_getHorizontalR2[1], _visibleColumnStartIndex = _this$_getHorizontalR2[2], _visibleColumnStopIndex = _this$_getHorizontalR2[3]; var _this$_getVerticalRan2 = this._getVerticalRangeToRender(), _overscanRowStartIndex = _this$_getVerticalRan2[0], _overscanRowStopIndex = _this$_getVerticalRan2[1], _visibleRowStartIndex = _this$_getVerticalRan2[2], _visibleRowStopIndex = _this$_getVerticalRan2[3]; this._callOnItemsRendered(_overscanColumnStartIndex, _overscanColumnStopIndex, _overscanRowStartIndex, _overscanRowStopIndex, _visibleColumnStartIndex, _visibleColumnStopIndex, _visibleRowStartIndex, _visibleRowStopIndex); } } if (typeof onScroll === 'function') { var _this$state3 = this.state, _horizontalScrollDirection = _this$state3.horizontalScrollDirection, _scrollLeft = _this$state3.scrollLeft, _scrollTop = _this$state3.scrollTop, _scrollUpdateWasRequested = _this$state3.scrollUpdateWasRequested, _verticalScrollDirection = _this$state3.verticalScrollDirection; 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. _proto._getHorizontalRangeToRender = function _getHorizontalRangeToRender() { var _this$props6 = this.props, columnCount = _this$props6.columnCount, overscanColumnCount = _this$props6.overscanColumnCount, overscanColumnsCount = _this$props6.overscanColumnsCount, overscanCount = _this$props6.overscanCount, rowCount = _this$props6.rowCount; var _this$state4 = this.state, horizontalScrollDirection = _this$state4.horizontalScrollDirection, isScrolling = _this$state4.isScrolling, scrollLeft = _this$state4.scrollLeft; var overscanCountResolved = overscanColumnCount || overscanColumnsCount || overscanCount || 1; if (columnCount === 0 || rowCount === 0) { return [0, 0, 0, 0]; } var startIndex = getColumnStartIndexForOffset(this.props, scrollLeft, this._instanceProps); var 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. var overscanBackward = !isScrolling || horizontalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1; var 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]; }; _proto._getVerticalRangeToRender = function _getVerticalRangeToRender() { var _this$props7 = this.props, columnCount = _this$props7.columnCount, overscanCount = _this$props7.overscanCount, overscanRowCount = _this$props7.overscanRowCount, overscanRowsCount = _this$props7.overscanRowsCount, rowCount = _this$props7.rowCount; var _this$state5 = this.state, isScrolling = _this$state5.isScrolling, verticalScrollDirection = _this$state5.verticalScrollDirection, scrollTop = _this$state5.scrollTop; var overscanCountResolved = overscanRowCount || overscanRowsCount || overscanCount || 1; if (columnCount === 0 || rowCount === 0) { return [0, 0, 0, 0]; } var startIndex = getRowStartIndexForOffset(this.props, scrollTop, this._instanceProps); var 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. var overscanBackward = !isScrolling || verticalScrollDirection === 'backward' ? Math.max(1, overscanCountResolved) : 1; var 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]; }; return Grid; }(PureComponent), _class.defaultProps = { direction: 'ltr', itemData: undefined, useIsScrolling: false }, _temp; } var validateSharedProps = function validateSharedProps(_ref5, _ref6) { var children = _ref5.children, direction = _ref5.direction, height = _ref5.height, innerTagName = _ref5.innerTagName, outerTagName = _ref5.outerTagName, overscanColumnsCount = _ref5.overscanColumnsCount, overscanCount = _ref5.overscanCount, overscanRowsCount = _ref5.overscanRowsCount, width = _ref5.width; var instance = _ref6.instance; 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.")); } } }; var DEFAULT_ESTIMATED_ITEM_SIZE = 50; var getEstimatedTotalHeight = function getEstimatedTotalHeight(_ref, _ref2) { var rowCount = _ref.rowCount; var rowMetadataMap = _ref2.rowMetadataMap, estimatedRowHeight = _ref2.estimatedRowHeight, lastMeasuredRowIndex = _ref2.lastMeasuredRowIndex; var totalSizeOfMeasuredRows = 0; // Edge case check for when the number of items decreases while a scroll is in progress. // https://github.com/bvaughn/react-window/pull/138 if (lastMeasuredRowIndex >= rowCount) { lastMeasuredRowIndex = rowCount - 1; } if (lastMeasuredRowIndex >= 0) { var itemMetadata = rowMetadataMap[lastMeasuredRowIndex]; totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size; } var numUnmeasuredItems = rowCount - lastMeasuredRowIndex - 1; var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedRowHeight; return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems; }; var getEstimatedTotalWidth = function getEstimatedTotalWidth(_ref3, _ref4) { var columnCount = _ref3.columnCount; var columnMetadataMap = _ref4.columnMetadataMap, estimatedColumnWidth = _ref4.estimatedColumnWidth, lastMeasuredColumnIndex = _ref4.lastMeasuredColumnIndex; var totalSizeOfMeasuredRows = 0; // Edge case check for when the number of items decreases while a scroll is in progress. // https://github.com/bvaughn/react-window/pull/138 if (lastMeasuredColumnIndex >= columnCount) { lastMeasuredColumnIndex = columnCount - 1; } if (lastMeasuredColumnIndex >= 0) { var itemMetadata = columnMetadataMap[lastMeasuredColumnIndex]; totalSizeOfMeasuredRows = itemMetadata.offset + itemMetadata.size; } var numUnmeasuredItems = columnCount - lastMeasuredColumnIndex - 1; var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedColumnWidth; return totalSizeOfMeasuredRows + totalSizeOfUnmeasuredItems; }; var getItemMetadata = function getItemMetadata(itemType, props, index, instanceProps) { var itemMetadataMap, itemSize, lastMeasuredIndex; if (itemType === 'column') { itemMetadataMap = instanceProps.columnMetadataMap; itemSize = props.columnWidth; lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex; } else { itemMetadataMap = instanceProps.rowMetadataMap; itemSize = props.rowHeight; lastMeasuredIndex = instanceProps.lastMeasuredRowIndex; } if (index > lastMeasuredIndex) { var offset = 0; if (lastMeasuredIndex >= 0) { var itemMetadata = itemMetadataMap[lastMeasuredIndex]; offset = itemMetadata.offset + itemMetadata.size; } for (var i = lastMeasuredIndex + 1; i <= index; i++) { var size = itemSize(i); itemMetadataMap[i] = { offset: offset, size: size }; offset += size; } if (itemType === 'column') { instanceProps.lastMeasuredColumnIndex = index; } else { instanceProps.lastMeasuredRowIndex = index; } } return itemMetadataMap[index]; }; var findNearestItem = function findNearestItem(itemType, props, instanceProps, offset) { var itemMetadataMap, lastMeasuredIndex; if (itemType === 'column') { itemMetadataMap = instanceProps.columnMetadataMap; lastMeasuredIndex = instanceProps.lastMeasuredColumnIndex; } else { itemMetadataMap = instanceProps.rowMetadataMap; lastMeasuredIndex = instanceProps.lastMeasuredRowIndex; } var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0; if (lastMeasuredItemOffset >= offset) { // If we've already measured items within this range just use a binary search as it's faster. return findNearestItemBinarySearch(itemType, props, instanceProps, lastMeasuredIndex, 0, offset); } else { // If we haven't yet measured this high, fallback to an exponential search with an inner binary search. // The exponential search avoids pre-computing sizes for the full set of items as a binary search would. // The overall complexity for this approach is O(log n). return findNearestItemExponentialSearch(itemType, props, instanceProps, Math.max(0, lastMeasuredIndex), offset); } }; var findNearestItemBinarySearch = function findNearestItemBinarySearch(itemType, props, instanceProps, high, low, offset) { while (low <= high) { var middle = low + Math.floor((high - low) / 2); var currentOffset = getItemMetadata(itemType, props, middle, instanceProps).offset; if (currentOffset === offset) { return middle; } else if (currentOffset < offset) { low = middle + 1; } else if (currentOffset > offset) { high = middle - 1; } } if (low > 0) { return low - 1; } else { return 0; } }; var findNearestItemExponentialSearch = function findNearestItemExponentialSearch(itemType, props, instanceProps, index, offset) { var itemCount = itemType === 'column' ? props.columnCount : props.rowCount; var interval = 1; while (index < itemCount && getItemMetadata(itemType, props, index, instanceProps).offset < offset) { index += interval; interval *= 2; } return findNearestItemBinarySearch(itemType, props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset); }; var getOffsetForIndexAndAlignment = function getOffsetForIndexAndAlignment(itemType, props, index, align, scrollOffset, instanceProps, scrollbarSize) { var size = itemType === 'column' ? props.width : props.height; var itemMetadata = getItemMetadata(itemType, props, index, instanceProps); // Get estimated total size after ItemMetadata is computed, // To ensure it reflects actual measurements instead of just estimates. var estimatedTotalSize = itemType === 'column' ? getEstimatedTotalWidth(props, instanceProps) : getEstimatedTotalHeight(props, instanceProps); var maxOffset = Math.max(0, Math.min(estimatedTotalSize - size, itemMetadata.offset)); var minOffset = Math.max(0, itemMetadata.offset - size + scrollbarSize + itemMetadata.size); if (align === 'smart') { if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': return Math.round(minOffset + (maxOffset - minOffset) / 2); case 'auto': default: if (scrollOffset >= minOffset && scrollOffset <= maxOffset) { return scrollOffset; } else if (minOffset > maxOffset) { // Because we only take into account the scrollbar size when calculating minOffset // this value can be larger than maxOffset when at the end of the list return minOffset; } else if (scrollOffset < minOffset) { return minOffset; } else { return maxOffset; } } }; var VariableSizeGrid = /*#__PURE__*/ createGridComponent({ getColumnOffset: function getColumnOffset(props, index, instanceProps) { return getItemMetadata('column', props, index, instanceProps).offset; }, getColumnStartIndexForOffset: function getColumnStartIndexForOffset(props, scrollLeft, instanceProps) { return findNearestItem('column', props, instanceProps, scrollLeft); }, getColumnStopIndexForStartIndex: function getColumnStopIndexForStartIndex(props, startIndex, scrollLeft, instanceProps) { var columnCount = props.columnCount, width = props.width; var itemMetadata = getItemMetadata('column', props, startIndex, instanceProps); var maxOffset = scrollLeft + width; var offset = itemMetadata.offset + itemMetadata.size; var stopIndex = startIndex; while (stopIndex < columnCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata('column', props, stopIndex, instanceProps).size; } return stopIndex; }, getColumnWidth: function getColumnWidth(props, index, instanceProps) { return instanceProps.columnMetadataMap[index].size; }, getEstimatedTotalHeight: getEstimatedTotalHeight, getEstimatedTotalWidth: getEstimatedTotalWidth, getOffsetForColumnAndAlignment: function getOffsetForColumnAndAlignment(props, index, align, scrollOffset, instanceProps, scrollbarSize) { return getOffsetForIndexAndAlignment('column', props, index, align, scrollOffset, instanceProps, scrollbarSize); }, getOffsetForRowAndAlignment: function getOffsetForRowAndAlignment(props, index, align, scrollOffset, instanceProps, scrollbarSize) { return getOffsetForIndexAndAlignment('row', props, index, align, scrollOffset, instanceProps, scrollbarSize); }, getRowOffset: function getRowOffset(props, index, instanceProps) { return getItemMetadata('row', props, index, instanceProps).offset; }, getRowHeight: function getRowHeight(props, index, instanceProps) { return instanceProps.rowMetadataMap[index].size; }, getRowStartIndexForOffset: function getRowStartIndexForOffset(props, scrollTop, instanceProps) { return findNearestItem('row', props, instanceProps, scrollTop); }, getRowStopIndexForStartIndex: function getRowStopIndexForStartIndex(props, startIndex, scrollTop, instanceProps) { var rowCount = props.rowCount, height = props.height; var itemMetadata = getItemMetadata('row', props, startIndex, instanceProps); var maxOffset = scrollTop + height; var offset = itemMetadata.offset + itemMetadata.size; var stopIndex = startIndex; while (stopIndex < rowCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata('row', props, stopIndex, instanceProps).size; } return stopIndex; }, initInstanceProps: function initInstanceProps(props, instance) { var _ref5 = props, estimatedColumnWidth = _ref5.estimatedColumnWidth, estimatedRowHeight = _ref5.estimatedRowHeight; var instanceProps = { columnMetadataMap: {}, estimatedColumnWidth: estimatedColumnWidth || DEFAULT_ESTIMATED_ITEM_SIZE, estimatedRowHeight: estimatedRowHeight || DEFAULT_ESTIMATED_ITEM_SIZE, lastMeasuredColumnIndex: -1, lastMeasuredRowIndex: -1, rowMetadataMap: {} }; instance.resetAfterColumnIndex = function (columnIndex, shouldForceUpdate) { if (shouldForceUpdate === void 0) { shouldForceUpdate = true; } instance.resetAfterIndices({ columnIndex: columnIndex, shouldForceUpdate: shouldForceUpdate }); }; instance.resetAfterRowIndex = function (rowIndex, shouldForceUpdate) { if (shouldForceUpdate === void 0) { shouldForceUpdate = true; } instance.resetAfterIndices({ rowIndex: rowIndex, shouldForceUpdate: shouldForceUpdate }); }; instance.resetAfterIndices = function (_ref6) { var columnIndex = _ref6.columnIndex, rowIndex = _ref6.rowIndex, _ref6$shouldForceUpda = _ref6.shouldForceUpdate, shouldForceUpdate = _ref6$shouldForceUpda === void 0 ? true : _ref6$shouldForceUpda; if (typeof columnIndex === 'number') { instanceProps.lastMeasuredColumnIndex = Math.min(instanceProps.lastMeasuredColumnIndex, columnIndex - 1); } if (typeof rowIndex === 'number') { instanceProps.lastMeasuredRowIndex = Math.min(instanceProps.lastMeasuredRowIndex, rowIndex - 1); } // We could potentially optimize further by only evicting styles after this index, // But since styles are only cached while scrolling is in progress- // It seems an unnecessary optimization. // It's unlikely that resetAfterIndex() will be called while a user is scrolling. instance._getItemStyleCache(-1); if (shouldForceUpdate) { instance.forceUpdate(); } }; return instanceProps; }, shouldResetStyleCacheOnItemSizeChange: false, validateProps: function validateProps(_ref7) { var columnWidth = _ref7.columnWidth, rowHeight = _ref7.rowHeight; if (process.env.NODE_ENV !== 'production') { if (typeof columnWidth !== 'function') { throw Error('An invalid "columnWidth" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (columnWidth === null ? 'null' : typeof columnWidth) + "\" was specified.")); } else if (typeof rowHeight !== 'function') { throw Error('An invalid "rowHeight" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (rowHeight === null ? 'null' : typeof rowHeight) + "\" was specified.")); } } } }); var IS_SCROLLING_DEBOUNCE_INTERVAL$1 = 150; var defaultItemKey$1 = function defaultItemKey(index, data) { return index; }; // 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. var devWarningsDirection = null; var devWarningsTagName$1 = null; if (process.env.NODE_ENV !== 'production') { if (typeof window !== 'undefined' && typeof window.WeakSet !== 'undefined') { devWarningsDirection = /*#__PURE__*/ new WeakSet(); devWarningsTagName$1 = /*#__PURE__*/ new WeakSet(); } } function createListComponent(_ref) { var _class, _temp; var getItemOffset = _ref.getItemOffset, getEstimatedTotalSize = _ref.getEstimatedTotalSize, getItemSize = _ref.getItemSize, getOffsetForIndexAndAlignment = _ref.getOffsetForIndexAndAlignment, getStartIndexForOffset = _ref.getStartIndexForOffset, getStopIndexForStartIndex = _ref.getStopIndexForStartIndex, initInstanceProps = _ref.initInstanceProps, shouldResetStyleCacheOnItemSizeChange = _ref.shouldResetStyleCacheOnItemSizeChange, validateProps = _ref.validateProps; return _temp = _class = /*#__PURE__*/ function (_PureComponent) { _inheritsLoose(List, _PureComponent); // Always use explicit constructor for React components. // It produces less code after transpilation. (#26) // eslint-disable-next-line no-useless-constructor function List(props) { var _this; _this = _PureComponent.call(this, props) || this; _this._instanceProps = initInstanceProps(_this.props, _assertThisInitialized(_assertThisInitialized(_this))); _this._outerRef = void 0; _this._resetIsScrollingTimeoutId = null; _this.state = { instance: _assertThisInitialized(_assertThisInitialized(_this)), isScrolling: false, scrollDirection: 'forward', scrollOffset: typeof _this.props.initialScrollOffset === 'number' ? _this.props.initialScrollOffset : 0, scrollUpdateWasRequested: false }; _this._callOnItemsRendered = void 0; _this._callOnItemsRendered = memoizeOne(function (overscanStartIndex, overscanStopIndex, visibleStartIndex, visibleStopIndex) { return _this.props.onItemsRendered({ overscanStartIndex: overscanStartIndex, overscanStopIndex: overscanStopIndex, visibleStartIndex: visibleStartIndex, visibleStopIndex: visibleStopIndex }); }); _this._callOnScroll = void 0; _this._callOnScroll = memoizeOne(function (scrollDirection, scrollOffset, scrollUpdateWasRequested) { return _this.props.onScroll({ scrollDirection: scrollDirection, scrollOffset: scrollOffset, scrollUpdateWasRequested: scrollUpdateWasRequested }); }); _this._getItemStyle = void 0; _this._getItemStyle = function (index) { var _this$props = _this.props, direction = _this$props.direction, itemSize = _this$props.itemSize, layout = _this$props.layout; var itemStyleCache = _this._getItemStyleCache(shouldResetStyleCacheOnItemSizeChange && itemSize, shouldResetStyleCacheOnItemSizeChange && layout, shouldResetStyleCacheOnItemSizeChange && direction); var style; if (itemStyleCache.hasOwnProperty(index)) { style = itemStyleCache[index]; } else { var _style; var _offset = getItemOffset(_this.props, index, _this._instanceProps); var size = getItemSize(_this.props, index, _this._instanceProps); // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; itemStyleCache[index] = style = (_style = { position: 'absolute' }, _style[direction === 'rtl' ? 'right' : 'left'] = isHorizontal ? _offset : 0, _style.top = !isHorizontal ? _offset : 0, _style.height = !isHorizontal ? size : '100%', _style.width = isHorizontal ? size : '100%', _style); } return style; }; _this._getItemStyleCache = void 0; _this._getItemStyleCache = memoizeOne(function (_, __, ___) { return {}; }); _this._onScrollHorizontal = function (event) { var _event$currentTarget = event.currentTarget, clientWidth = _event$currentTarget.clientWidth, scrollLeft = _event$currentTarget.scrollLeft, scrollWidth = _event$currentTarget.scrollWidth; // Force flush sync for scroll updates to reduce visual checkerboarding. flushSync(() => { _this.setState(function (prevState) { if (prevState.scrollOffset === scrollLeft) { // 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; } var direction = _this.props.direction; var scrollOffset = scrollLeft; if (direction === 'rtl') { // 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. switch (getRTLOffsetType()) { case 'negative': scrollOffset = -scrollLeft; break; case 'positive-descending': scrollOffset = scrollWidth - clientWidth - scrollLeft; break; } } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds. scrollOffset = Math.max(0, Math.min(scrollOffset, scrollWidth - clientWidth)); return { isScrolling: true, scrollDirection: prevState.scrollOffset < scrollLeft ? 'forward' : 'backward', scrollOffset: scrollOffset, scrollUpdateWasRequested: false }; }, _this._resetIsScrollingDebounced); }); }; _this._onScrollVertical = function (event) { var _event$currentTarget2 = event.currentTarget, clientHeight = _event$currentTarget2.clientHeight, scrollHeight = _event$currentTarget2.scrollHeight, scrollTop = _event$currentTarget2.scrollTop; // Force flush sync for scroll updates to reduce visual checkerboarding. flushSync(() => { _this.setState(function (prevState) { if (prevState.scrollOffset === 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; } // Prevent Safari's elastic scrolling from causing visual shaking when scrolling past bounds. var scrollOffset = Math.max(0, Math.min(scrollTop, scrollHeight - clientHeight)); return { isScrolling: true, scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward', scrollOffset: scrollOffset, scrollUpdateWasRequested: false }; }, _this._resetIsScrollingDebounced); }); }; _this._outerRefSetter = function (ref) { var outerRef = _this.props.outerRef; _this._outerRef = ref; if (typeof outerRef === 'function') { outerRef(ref); } else if (outerRef != null && typeof outerRef === 'object' && outerRef.hasOwnProperty('current')) { outerRef.current = ref; } }; _this._resetIsScrollingDebounced = function () { if (_this._resetIsScrollingTimeoutId !== null) { cancelTimeout(_this._resetIsScrollingTimeoutId); } _this._resetIsScrollingTimeoutId = requestTimeout(_this._resetIsScrolling, IS_SCROLLING_DEBOUNCE_INTERVAL$1); }; _this._resetIsScrolling = function () { _this._resetIsScrollingTimeoutId = null; _this.setState({ isScrolling: false }, function () { // 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, null); }); }; return _this; } List.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, prevState) { validateSharedProps$1(nextProps, prevState); validateProps(nextProps); return null; }; var _proto = List.prototype; _proto.scrollTo = function scrollTo(scrollOffset) { scrollOffset = Math.max(0, scrollOffset); this.setState(function (prevState) { if (prevState.scrollOffset === scrollOffset) { return null; } return { scrollDirection: prevState.scrollOffset < scrollOffset ? 'forward' : 'backward', scrollOffset: scrollOffset, scrollUpdateWasRequested: true }; }, this._resetIsScrollingDebounced); }; _proto.scrollToItem = function scrollToItem(index, align) { if (align === void 0) { align = 'auto'; } var itemCount = this.props.itemCount; var scrollOffset = this.state.scrollOffset; index = Math.max(0, Math.min(index, itemCount - 1)); this.scrollTo(getOffsetForIndexAndAlignment(this.props, index, align, scrollOffset, this._instanceProps)); }; _proto.componentDidMount = function componentDidMount() { var _this$props2 = this.props, direction = _this$props2.direction, initialScrollOffset = _this$props2.initialScrollOffset, layout = _this$props2.layout; if (typeof initialScrollOffset === 'number' && this._outerRef != null) { var outerRef = this._outerRef; // TODO Deprecate direction "horizontal" if (direction === 'horizontal' || layout === 'horizontal') { outerRef.scrollLeft = initialScrollOffset; } else { outerRef.scrollTop = initialScrollOffset; } } this._callPropsCallbacks(); }; _proto.componentDidUpdate = function componentDidUpdate() { var _this$props3 = this.props, direction = _this$props3.direction, layout = _this$props3.layout; var _this$state = this.state, scrollOffset = _this$state.scrollOffset, scrollUpdateWasRequested = _this$state.scrollUpdateWasRequested; if (scrollUpdateWasRequested && this._outerRef != null) { var outerRef = this._outerRef; // TODO Deprecate direction "horizontal" if (direction === 'horizontal' || layout === 'horizontal') { if (direction === 'rtl') { // 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. switch (getRTLOffsetType()) { case 'negative': outerRef.scrollLeft = -scrollOffset; break; case 'positive-ascending': outerRef.scrollLeft = scrollOffset; break; default: var clientWidth = outerRef.clientWidth, scrollWidth = outerRef.scrollWidth; outerRef.scrollLeft = scrollWidth - clientWidth - scrollOffset; break; } } else { outerRef.scrollLeft = scrollOffset; } } else { outerRef.scrollTop = scrollOffset; } } this._callPropsCallbacks(); }; _proto.componentWillUnmount = function componentWillUnmount() { if (this._resetIsScrollingTimeoutId !== null) { cancelTimeout(this._resetIsScrollingTimeoutId); } }; _proto.render = function render() { var _this$props4 = this.props, children = _this$props4.children, className = _this$props4.className, direction = _this$props4.direction, height = _this$props4.height, innerRef = _this$props4.innerRef, innerElementType = _this$props4.innerElementType, innerTagName = _this$props4.innerTagName, itemCount = _this$props4.itemCount, itemData = _this$props4.itemData, _this$props4$itemKey = _this$props4.itemKey, itemKey = _this$props4$itemKey === void 0 ? defaultItemKey$1 : _this$props4$itemKey, layout = _this$props4.layout, outerElementType = _this$props4.outerElementType, outerTagName = _this$props4.outerTagName, style = _this$props4.style, useIsScrolling = _this$props4.useIsScrolling, width = _this$props4.width; var isScrolling = this.state.isScrolling; // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; var onScroll = isHorizontal ? this._onScrollHorizontal : this._onScrollVertical; var _this$_getRangeToRend = this._getRangeToRender(), startIndex = _this$_getRangeToRend[0], stopIndex = _this$_getRangeToRend[1]; var items = []; if (itemCount > 0) { for (var _index = startIndex; _index <= stopIndex; _index++) { items.push(createElement(children, { data: itemData, key: itemKey(_index, itemData), index: _index, isScrolling: useIsScrolling ? isScrolling : undefined, style: this._getItemStyle(_index) })); } } // Read this value AFTER items have been created, // So their actual sizes (if variable) are taken into consideration. var estimatedTotalSize = getEstimatedTotalSize(this.props, this._instanceProps); return createElement(outerElementType || outerTagName || 'div', { className: className, onScroll: onScroll, ref: this._outerRefSetter, style: _extends({ position: 'relative', height: height, width: width, overflow: 'auto', WebkitOverflowScrolling: 'touch', willChange: 'transform', direction: direction }, style) }, createElement(innerElementType || innerTagName || 'div', { children: items, ref: innerRef, style: { height: isHorizontal ? '100%' : estimatedTotalSize, pointerEvents: isScrolling ? 'none' : undefined, width: isHorizontal ? estimatedTotalSize : '100%' } })); }; _proto._callPropsCallbacks = function _callPropsCallbacks() { if (typeof this.props.onItemsRendered === 'function') { var itemCount = this.props.itemCount; if (itemCount > 0) { var _this$_getRangeToRend2 = this._getRangeToRender(), _overscanStartIndex = _this$_getRangeToRend2[0], _overscanStopIndex = _this$_getRangeToRend2[1], _visibleStartIndex = _this$_getRangeToRend2[2], _visibleStopIndex = _this$_getRangeToRend2[3]; this._callOnItemsRendered(_overscanStartIndex, _overscanStopIndex, _visibleStartIndex, _visibleStopIndex); } } if (typeof this.props.onScroll === 'function') { var _this$state2 = this.state, _scrollDirection = _this$state2.scrollDirection, _scrollOffset = _this$state2.scrollOffset, _scrollUpdateWasRequested = _this$state2.scrollUpdateWasRequested; this._callOnScroll(_scrollDirection, _scrollOffset, _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. _proto._getRangeToRender = function _getRangeToRender() { var _this$props5 = this.props, itemCount = _this$props5.itemCount, overscanCount = _this$props5.overscanCount; var _this$state3 = this.state, isScrolling = _this$state3.isScrolling, scrollDirection = _this$state3.scrollDirection, scrollOffset = _this$state3.scrollOffset; if (itemCount === 0) { return [0, 0, 0, 0]; } var startIndex = getStartIndexForOffset(this.props, scrollOffset, this._instanceProps); var stopIndex = getStopIndexForStartIndex(this.props, startIndex, scrollOffset, 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. var overscanBackward = !isScrolling || scrollDirection === 'backward' ? Math.max(1, overscanCount) : 1; var overscanForward = !isScrolling || scrollDirection === 'forward' ? Math.max(1, overscanCount) : 1; return [Math.max(0, startIndex - overscanBackward), Math.max(0, Math.min(itemCount - 1, stopIndex + overscanForward)), startIndex, stopIndex]; }; return List; }(PureComponent), _class.defaultProps = { direction: 'ltr', itemData: undefined, layout: 'vertical', overscanCount: 2, useIsScrolling: false }, _temp; } // NOTE: I considered further wrapping individual items with a pure ListItem component. // This would avoid ever calling the render function for the same index more than once, // But it would also add the overhead of a lot of components/fibers. // I assume people already do this (render function returning a class component), // So my doing it would just unnecessarily double the wrappers. var validateSharedProps$1 = function validateSharedProps(_ref2, _ref3) { var children = _ref2.children, direction = _ref2.direction, height = _ref2.height, layout = _ref2.layout, innerTagName = _ref2.innerTagName, outerTagName = _ref2.outerTagName, width = _ref2.width; var instance = _ref3.instance; if (process.env.NODE_ENV !== 'production') { if (innerTagName != null || outerTagName != null) { if (devWarningsTagName$1 && !devWarningsTagName$1.has(instance)) { devWarningsTagName$1.add(instance); console.warn('The innerTagName and outerTagName props have been deprecated. ' + 'Please use the innerElementType and outerElementType props instead.'); } } // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; switch (direction) { case 'horizontal': case 'vertical': if (devWarningsDirection && !devWarningsDirection.has(instance)) { devWarningsDirection.add(instance); console.warn('The direction prop should be either "ltr" (default) or "rtl". ' + 'Please use the layout prop to specify "vertical" (default) or "horizontal" orientation.'); } break; case 'ltr': case 'rtl': // Valid values break; default: throw Error('An invalid "direction" prop has been specified. ' + 'Value should be either "ltr" or "rtl". ' + ("\"" + direction + "\" was specified.")); } switch (layout) { case 'horizontal': case 'vertical': // Valid values break; default: throw Error('An invalid "layout" prop has been specified. ' + 'Value should be either "horizontal" or "vertical". ' + ("\"" + layout + "\" was specified.")); } 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.")); } if (isHorizontal && typeof width !== 'number') { throw Error('An invalid "width" prop has been specified. ' + 'Horizontal lists must specify a number for width. ' + ("\"" + (width === null ? 'null' : typeof width) + "\" was specified.")); } else if (!isHorizontal && typeof height !== 'number') { throw Error('An invalid "height" prop has been specified. ' + 'Vertical lists must specify a number for height. ' + ("\"" + (height === null ? 'null' : typeof height) + "\" was specified.")); } } }; var DEFAULT_ESTIMATED_ITEM_SIZE$1 = 50; var getItemMetadata$1 = function getItemMetadata(props, index, instanceProps) { var _ref = props, itemSize = _ref.itemSize; var itemMetadataMap = instanceProps.itemMetadataMap, lastMeasuredIndex = instanceProps.lastMeasuredIndex; if (index > lastMeasuredIndex) { var offset = 0; if (lastMeasuredIndex >= 0) { var itemMetadata = itemMetadataMap[lastMeasuredIndex]; offset = itemMetadata.offset + itemMetadata.size; } for (var i = lastMeasuredIndex + 1; i <= index; i++) { var size = itemSize(i); itemMetadataMap[i] = { offset: offset, size: size }; offset += size; } instanceProps.lastMeasuredIndex = index; } return itemMetadataMap[index]; }; var findNearestItem$1 = function findNearestItem(props, instanceProps, offset) { var itemMetadataMap = instanceProps.itemMetadataMap, lastMeasuredIndex = instanceProps.lastMeasuredIndex; var lastMeasuredItemOffset = lastMeasuredIndex > 0 ? itemMetadataMap[lastMeasuredIndex].offset : 0; if (lastMeasuredItemOffset >= offset) { // If we've already measured items within this range just use a binary search as it's faster. return findNearestItemBinarySearch$1(props, instanceProps, lastMeasuredIndex, 0, offset); } else { // If we haven't yet measured this high, fallback to an exponential search with an inner binary search. // The exponential search avoids pre-computing sizes for the full set of items as a binary search would. // The overall complexity for this approach is O(log n). return findNearestItemExponentialSearch$1(props, instanceProps, Math.max(0, lastMeasuredIndex), offset); } }; var findNearestItemBinarySearch$1 = function findNearestItemBinarySearch(props, instanceProps, high, low, offset) { while (low <= high) { var middle = low + Math.floor((high - low) / 2); var currentOffset = getItemMetadata$1(props, middle, instanceProps).offset; if (currentOffset === offset) { return middle; } else if (currentOffset < offset) { low = middle + 1; } else if (currentOffset > offset) { high = middle - 1; } } if (low > 0) { return low - 1; } else { return 0; } }; var findNearestItemExponentialSearch$1 = function findNearestItemExponentialSearch(props, instanceProps, index, offset) { var itemCount = props.itemCount; var interval = 1; while (index < itemCount && getItemMetadata$1(props, index, instanceProps).offset < offset) { index += interval; interval *= 2; } return findNearestItemBinarySearch$1(props, instanceProps, Math.min(index, itemCount - 1), Math.floor(index / 2), offset); }; var getEstimatedTotalSize = function getEstimatedTotalSize(_ref2, _ref3) { var itemCount = _ref2.itemCount; var itemMetadataMap = _ref3.itemMetadataMap, estimatedItemSize = _ref3.estimatedItemSize, lastMeasuredIndex = _ref3.lastMeasuredIndex; var totalSizeOfMeasuredItems = 0; // Edge case check for when the number of items decreases while a scroll is in progress. // https://github.com/bvaughn/react-window/pull/138 if (lastMeasuredIndex >= itemCount) { lastMeasuredIndex = itemCount - 1; } if (lastMeasuredIndex >= 0) { var itemMetadata = itemMetadataMap[lastMeasuredIndex]; totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size; } var numUnmeasuredItems = itemCount - lastMeasuredIndex - 1; var totalSizeOfUnmeasuredItems = numUnmeasuredItems * estimatedItemSize; return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems; }; var VariableSizeList = /*#__PURE__*/ createListComponent({ getItemOffset: function getItemOffset(props, index, instanceProps) { return getItemMetadata$1(props, index, instanceProps).offset; }, getItemSize: function getItemSize(props, index, instanceProps) { return instanceProps.itemMetadataMap[index].size; }, getEstimatedTotalSize: getEstimatedTotalSize, getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(props, index, align, scrollOffset, instanceProps) { var direction = props.direction, height = props.height, layout = props.layout, width = props.width; // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; var size = isHorizontal ? width : height; var itemMetadata = getItemMetadata$1(props, index, instanceProps); // Get estimated total size after ItemMetadata is computed, // To ensure it reflects actual measurements instead of just estimates. var estimatedTotalSize = getEstimatedTotalSize(props, instanceProps); var maxOffset = Math.max(0, Math.min(estimatedTotalSize - size, itemMetadata.offset)); var minOffset = Math.max(0, itemMetadata.offset - size + itemMetadata.size); if (align === 'smart') { if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': return Math.round(minOffset + (maxOffset - minOffset) / 2); case 'auto': default: if (scrollOffset >= minOffset && scrollOffset <= maxOffset) { return scrollOffset; } else if (scrollOffset < minOffset) { return minOffset; } else { return maxOffset; } } }, getStartIndexForOffset: function getStartIndexForOffset(props, offset, instanceProps) { return findNearestItem$1(props, instanceProps, offset); }, getStopIndexForStartIndex: function getStopIndexForStartIndex(props, startIndex, scrollOffset, instanceProps) { var direction = props.direction, height = props.height, itemCount = props.itemCount, layout = props.layout, width = props.width; // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; var size = isHorizontal ? width : height; var itemMetadata = getItemMetadata$1(props, startIndex, instanceProps); var maxOffset = scrollOffset + size; var offset = itemMetadata.offset + itemMetadata.size; var stopIndex = startIndex; while (stopIndex < itemCount - 1 && offset < maxOffset) { stopIndex++; offset += getItemMetadata$1(props, stopIndex, instanceProps).size; } return stopIndex; }, initInstanceProps: function initInstanceProps(props, instance) { var _ref4 = props, estimatedItemSize = _ref4.estimatedItemSize; var instanceProps = { itemMetadataMap: {}, estimatedItemSize: estimatedItemSize || DEFAULT_ESTIMATED_ITEM_SIZE$1, lastMeasuredIndex: -1 }; instance.resetAfterIndex = function (index, shouldForceUpdate) { if (shouldForceUpdate === void 0) { shouldForceUpdate = true; } instanceProps.lastMeasuredIndex = Math.min(instanceProps.lastMeasuredIndex, index - 1); // We could potentially optimize further by only evicting styles after this index, // But since styles are only cached while scrolling is in progress- // It seems an unnecessary optimization. // It's unlikely that resetAfterIndex() will be called while a user is scrolling. instance._getItemStyleCache(-1); if (shouldForceUpdate) { instance.forceUpdate(); } }; return instanceProps; }, shouldResetStyleCacheOnItemSizeChange: false, validateProps: function validateProps(_ref5) { var itemSize = _ref5.itemSize; if (process.env.NODE_ENV !== 'production') { if (typeof itemSize !== 'function') { throw Error('An invalid "itemSize" prop has been specified. ' + 'Value should be a function. ' + ("\"" + (itemSize === null ? 'null' : typeof itemSize) + "\" was specified.")); } } } }); var FixedSizeGrid = /*#__PURE__*/ createGridComponent({ getColumnOffset: function getColumnOffset(_ref, index) { var columnWidth = _ref.columnWidth; return index * columnWidth; }, getColumnWidth: function getColumnWidth(_ref2, index) { var columnWidth = _ref2.columnWidth; return columnWidth; }, getRowOffset: function getRowOffset(_ref3, index) { var rowHeight = _ref3.rowHeight; return index * rowHeight; }, getRowHeight: function getRowHeight(_ref4, index) { var rowHeight = _ref4.rowHeight; return rowHeight; }, getEstimatedTotalHeight: function getEstimatedTotalHeight(_ref5) { var rowCount = _ref5.rowCount, rowHeight = _ref5.rowHeight; return rowHeight * rowCount; }, getEstimatedTotalWidth: function getEstimatedTotalWidth(_ref6) { var columnCount = _ref6.columnCount, columnWidth = _ref6.columnWidth; return columnWidth * columnCount; }, getOffsetForColumnAndAlignment: function getOffsetForColumnAndAlignment(_ref7, columnIndex, align, scrollLeft, instanceProps, scrollbarSize) { var columnCount = _ref7.columnCount, columnWidth = _ref7.columnWidth, width = _ref7.width; var lastColumnOffset = Math.max(0, columnCount * columnWidth - width); var maxOffset = Math.min(lastColumnOffset, columnIndex * columnWidth); var minOffset = Math.max(0, columnIndex * columnWidth - width + scrollbarSize + columnWidth); if (align === 'smart') { if (scrollLeft >= minOffset - width && scrollLeft <= maxOffset + width) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': // "Centered" offset is usually the average of the min and max. // But near the edges of the list, this doesn't hold true. var middleOffset = Math.round(minOffset + (maxOffset - minOffset) / 2); if (middleOffset < Math.ceil(width / 2)) { return 0; // near the beginning } else if (middleOffset > lastColumnOffset + Math.floor(width / 2)) { return lastColumnOffset; // near the end } else { return middleOffset; } case 'auto': default: if (scrollLeft >= minOffset && scrollLeft <= maxOffset) { return scrollLeft; } else if (minOffset > maxOffset) { // Because we only take into account the scrollbar size when calculating minOffset // this value can be larger than maxOffset when at the end of the list return minOffset; } else if (scrollLeft < minOffset) { return minOffset; } else { return maxOffset; } } }, getOffsetForRowAndAlignment: function getOffsetForRowAndAlignment(_ref8, rowIndex, align, scrollTop, instanceProps, scrollbarSize) { var rowHeight = _ref8.rowHeight, height = _ref8.height, rowCount = _ref8.rowCount; var lastRowOffset = Math.max(0, rowCount * rowHeight - height); var maxOffset = Math.min(lastRowOffset, rowIndex * rowHeight); var minOffset = Math.max(0, rowIndex * rowHeight - height + scrollbarSize + rowHeight); if (align === 'smart') { if (scrollTop >= minOffset - height && scrollTop <= maxOffset + height) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': // "Centered" offset is usually the average of the min and max. // But near the edges of the list, this doesn't hold true. var middleOffset = Math.round(minOffset + (maxOffset - minOffset) / 2); if (middleOffset < Math.ceil(height / 2)) { return 0; // near the beginning } else if (middleOffset > lastRowOffset + Math.floor(height / 2)) { return lastRowOffset; // near the end } else { return middleOffset; } case 'auto': default: if (scrollTop >= minOffset && scrollTop <= maxOffset) { return scrollTop; } else if (minOffset > maxOffset) { // Because we only take into account the scrollbar size when calculating minOffset // this value can be larger than maxOffset when at the end of the list return minOffset; } else if (scrollTop < minOffset) { return minOffset; } else { return maxOffset; } } }, getColumnStartIndexForOffset: function getColumnStartIndexForOffset(_ref9, scrollLeft) { var columnWidth = _ref9.columnWidth, columnCount = _ref9.columnCount; return Math.max(0, Math.min(columnCount - 1, Math.floor(scrollLeft / columnWidth))); }, getColumnStopIndexForStartIndex: function getColumnStopIndexForStartIndex(_ref10, startIndex, scrollLeft) { var columnWidth = _ref10.columnWidth, columnCount = _ref10.columnCount, width = _ref10.width; var left = startIndex * columnWidth; var numVisibleColumns = Math.ceil((width + scrollLeft - left) / columnWidth); return Math.max(0, Math.min(columnCount - 1, startIndex + numVisibleColumns - 1 // -1 is because stop index is inclusive )); }, getRowStartIndexForOffset: function getRowStartIndexForOffset(_ref11, scrollTop) { var rowHeight = _ref11.rowHeight, rowCount = _ref11.rowCount; return Math.max(0, Math.min(rowCount - 1, Math.floor(scrollTop / rowHeight))); }, getRowStopIndexForStartIndex: function getRowStopIndexForStartIndex(_ref12, startIndex, scrollTop) { var rowHeight = _ref12.rowHeight, rowCount = _ref12.rowCount, height = _ref12.height; var top = startIndex * rowHeight; var numVisibleRows = Math.ceil((height + scrollTop - top) / rowHeight); return Math.max(0, Math.min(rowCount - 1, startIndex + numVisibleRows - 1 // -1 is because stop index is inclusive )); }, initInstanceProps: function initInstanceProps(props) {// Noop }, shouldResetStyleCacheOnItemSizeChange: true, validateProps: function validateProps(_ref13) { var columnWidth = _ref13.columnWidth, rowHeight = _ref13.rowHeight; if (process.env.NODE_ENV !== 'production') { if (typeof columnWidth !== 'number') { throw Error('An invalid "columnWidth" prop has been specified. ' + 'Value should be a number. ' + ("\"" + (columnWidth === null ? 'null' : typeof columnWidth) + "\" was specified.")); } if (typeof rowHeight !== 'number') { throw Error('An invalid "rowHeight" prop has been specified. ' + 'Value should be a number. ' + ("\"" + (rowHeight === null ? 'null' : typeof rowHeight) + "\" was specified.")); } } } }); var FixedSizeList = /*#__PURE__*/ createListComponent({ getItemOffset: function getItemOffset(_ref, index) { var itemSize = _ref.itemSize; return index * itemSize; }, getItemSize: function getItemSize(_ref2, index) { var itemSize = _ref2.itemSize; return itemSize; }, getEstimatedTotalSize: function getEstimatedTotalSize(_ref3) { var itemCount = _ref3.itemCount, itemSize = _ref3.itemSize; return itemSize * itemCount; }, getOffsetForIndexAndAlignment: function getOffsetForIndexAndAlignment(_ref4, index, align, scrollOffset) { var direction = _ref4.direction, height = _ref4.height, itemCount = _ref4.itemCount, itemSize = _ref4.itemSize, layout = _ref4.layout, width = _ref4.width; // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; var size = isHorizontal ? width : height; var lastItemOffset = Math.max(0, itemCount * itemSize - size); var maxOffset = Math.min(lastItemOffset, index * itemSize); var minOffset = Math.max(0, index * itemSize - size + itemSize); if (align === 'smart') { if (scrollOffset >= minOffset - size && scrollOffset <= maxOffset + size) { align = 'auto'; } else { align = 'center'; } } switch (align) { case 'start': return maxOffset; case 'end': return minOffset; case 'center': { // "Centered" offset is usually the average of the min and max. // But near the edges of the list, this doesn't hold true. var middleOffset = Math.round(minOffset + (maxOffset - minOffset) / 2); if (middleOffset < Math.ceil(size / 2)) { return 0; // near the beginning } else if (middleOffset > lastItemOffset + Math.floor(size / 2)) { return lastItemOffset; // near the end } else { return middleOffset; } } case 'auto': default: if (scrollOffset >= minOffset && scrollOffset <= maxOffset) { return scrollOffset; } else if (scrollOffset < minOffset) { return minOffset; } else { return maxOffset; } } }, getStartIndexForOffset: function getStartIndexForOffset(_ref5, offset) { var itemCount = _ref5.itemCount, itemSize = _ref5.itemSize; return Math.max(0, Math.min(itemCount - 1, Math.floor(offset / itemSize))); }, getStopIndexForStartIndex: function getStopIndexForStartIndex(_ref6, startIndex, scrollOffset) { var direction = _ref6.direction, height = _ref6.height, itemCount = _ref6.itemCount, itemSize = _ref6.itemSize, layout = _ref6.layout, width = _ref6.width; // TODO Deprecate direction "horizontal" var isHorizontal = direction === 'horizontal' || layout === 'horizontal'; var offset = startIndex * itemSize; var size = isHorizontal ? width : height; var numVisibleItems = Math.ceil((size + scrollOffset - offset) / itemSize); return Math.max(0, Math.min(itemCount - 1, startIndex + numVisibleItems - 1 // -1 is because stop index is inclusive )); }, initInstanceProps: function initInstanceProps(props) {// Noop }, shouldResetStyleCacheOnItemSizeChange: true, validateProps: function validateProps(_ref7) { var itemSize = _ref7.itemSize; if (process.env.NODE_ENV !== 'production') { if (typeof itemSize !== 'number') { throw Error('An invalid "itemSize" prop has been specified. ' + 'Value should be a number. ' + ("\"" + (itemSize === null ? 'null' : typeof itemSize) + "\" was specified.")); } } } }); // Pulled from react-compat // https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349 function shallowDiffers(prev, next) { for (var attribute in prev) { if (!(attribute in next)) { return true; } } for (var _attribute in next) { if (prev[_attribute] !== next[_attribute]) { return true; } } return false; } // It knows to compare individual style props and ignore the wrapper object. // See https://reactjs.org/docs/react-api.html#reactmemo function areEqual(prevProps, nextProps) { var prevStyle = prevProps.style, prevRest = _objectWithoutPropertiesLoose(prevProps, ["style"]); var nextStyle = nextProps.style, nextRest = _objectWithoutPropertiesLoose(nextProps, ["style"]); return !shallowDiffers(prevStyle, nextStyle) && !shallowDiffers(prevRest, nextRest); } // It knows to compare individual style props and ignore the wrapper object. // See https://reactjs.org/docs/react-component.html#shouldcomponentupdate function shouldComponentUpdate(nextProps, nextState) { return !areEqual(this.props, nextProps) || shallowDiffers(this.state, nextState); } export { VariableSizeGrid, VariableSizeList, FixedSizeGrid, FixedSizeList, areEqual, shouldComponentUpdate }; //# sourceMappingURL=index.esm.js.map
38.547379
361
0.657301
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const React = require('react'); const ReactDOM = require('react-dom'); describe('dangerouslySetInnerHTML', () => { describe('when the node has innerHTML property', () => { it('sets innerHTML on it', () => { const container = document.createElement('div'); const node = ReactDOM.render( <div dangerouslySetInnerHTML={{__html: '<h1>Hello</h1>'}} />, container, ); expect(node.innerHTML).toBe('<h1>Hello</h1>'); }); }); describe('when the node does not have an innerHTML property', () => { let innerHTMLDescriptor; // In some versions of IE (TODO: which ones?) SVG nodes don't have // innerHTML. To simulate this, we will take it off the Element prototype // and put it onto the HTMLDivElement prototype. We expect that the logic // checks for existence of innerHTML on SVG, and if one doesn't exist, falls // back to using appendChild and removeChild. beforeEach(() => { innerHTMLDescriptor = Object.getOwnPropertyDescriptor( Element.prototype, 'innerHTML', ); delete Element.prototype.innerHTML; Object.defineProperty( HTMLDivElement.prototype, 'innerHTML', innerHTMLDescriptor, ); }); afterEach(() => { delete HTMLDivElement.prototype.innerHTML; Object.defineProperty( Element.prototype, 'innerHTML', innerHTMLDescriptor, ); }); // @gate !disableIEWorkarounds it('sets innerHTML on it', () => { const html = '<circle></circle>'; const container = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg', ); ReactDOM.render( <g dangerouslySetInnerHTML={{__html: html}} />, container, ); const circle = container.firstChild.firstChild; expect(circle.tagName).toBe('circle'); }); // @gate !disableIEWorkarounds it('clears previous children', () => { const firstHtml = '<rect></rect>'; const secondHtml = '<circle></circle>'; const container = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg', ); ReactDOM.render( <g dangerouslySetInnerHTML={{__html: firstHtml}} />, container, ); const rect = container.firstChild.firstChild; expect(rect.tagName).toBe('rect'); ReactDOM.render( <g dangerouslySetInnerHTML={{__html: secondHtml}} />, container, ); const circle = container.firstChild.firstChild; expect(circle.tagName).toBe('circle'); }); }); });
28.154639
80
0.608419
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 {renderToPipeableStream, version} from './ReactDOMFizzServerNode.js';
24.636364
76
0.72242
owtf
module.exports = { baseUrl: '.', name: 'input', out: 'output.js', optimize: 'none', paths: { react: '../../../../build/oss-experimental/react/umd/react.development', 'react-dom': '../../../../build/oss-experimental/react-dom/umd/react-dom.development', schedule: '../../../../build/oss-experimental/scheduler/umd/schedule.development', }, };
26.071429
79
0.589947
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 waitForThrow; describe('ReactIncrementalErrorLogging', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactNoop = require('react-noop-renderer'); Scheduler = require('scheduler'); const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitForThrow = InternalTestUtils.waitForThrow; }); // Note: in this test file we won't be using toErrorDev() matchers // because they filter out precisely the messages we want to test for. let oldConsoleError; beforeEach(() => { oldConsoleError = console.error; console.error = jest.fn(); }); afterEach(() => { console.error = oldConsoleError; oldConsoleError = null; }); it('should log errors that occur during the begin phase', async () => { class ErrorThrowingComponent extends React.Component { constructor(props) { super(props); throw new Error('constructor error'); } render() { return <div />; } } ReactNoop.render( <div> <span> <ErrorThrowingComponent /> </span> </div>, ); await waitForThrow('constructor error'); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error).toHaveBeenCalledWith( __DEV__ ? expect.stringMatching( new RegExp( 'The above error occurred in the <ErrorThrowingComponent> component:\n' + '\\s+(in|at) ErrorThrowingComponent (.*)\n' + '\\s+(in|at) span(.*)\n' + '\\s+(in|at) div(.*)\n\n' + 'Consider adding an error boundary to your tree ' + 'to customize error handling behavior\\.', ), ) : expect.objectContaining({ message: 'constructor error', }), ); }); it('should log errors that occur during the commit phase', async () => { class ErrorThrowingComponent extends React.Component { componentDidMount() { throw new Error('componentDidMount error'); } render() { return <div />; } } ReactNoop.render( <div> <span> <ErrorThrowingComponent /> </span> </div>, ); await waitForThrow('componentDidMount error'); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error).toHaveBeenCalledWith( __DEV__ ? expect.stringMatching( new RegExp( 'The above error occurred in the <ErrorThrowingComponent> component:\n' + '\\s+(in|at) ErrorThrowingComponent (.*)\n' + '\\s+(in|at) span(.*)\n' + '\\s+(in|at) div(.*)\n\n' + 'Consider adding an error boundary to your tree ' + 'to customize error handling behavior\\.', ), ) : expect.objectContaining({ message: 'componentDidMount error', }), ); }); it('should ignore errors thrown in log method to prevent cycle', async () => { const logCapturedErrorCalls = []; console.error.mockImplementation(error => { // Test what happens when logging itself is buggy. logCapturedErrorCalls.push(error); throw new Error('logCapturedError error'); }); class ErrorThrowingComponent extends React.Component { render() { throw new Error('render error'); } } ReactNoop.render( <div> <span> <ErrorThrowingComponent /> </span> </div>, ); await waitForThrow('render error'); expect(logCapturedErrorCalls.length).toBe(1); expect(logCapturedErrorCalls[0]).toEqual( __DEV__ ? expect.stringMatching( new RegExp( 'The above error occurred in the <ErrorThrowingComponent> component:\n' + '\\s+(in|at) ErrorThrowingComponent (.*)\n' + '\\s+(in|at) span(.*)\n' + '\\s+(in|at) div(.*)\n\n' + 'Consider adding an error boundary to your tree ' + 'to customize error handling behavior\\.', ), ) : expect.objectContaining({ message: 'render error', }), ); // The error thrown in logCapturedError should be rethrown with a clean stack expect(() => { jest.runAllTimers(); }).toThrow('logCapturedError error'); }); it('resets instance variables before unmounting failed node', async () => { class ErrorBoundary extends React.Component { state = {error: null}; componentDidCatch(error) { this.setState({error}); } render() { return this.state.error ? null : this.props.children; } } class Foo extends React.Component { state = {step: 0}; componentDidMount() { this.setState({step: 1}); } componentWillUnmount() { Scheduler.log('componentWillUnmount: ' + this.state.step); } render() { Scheduler.log('render: ' + this.state.step); if (this.state.step > 0) { throw new Error('oops'); } return null; } } ReactNoop.render( <ErrorBoundary> <Foo /> </ErrorBoundary>, ); await waitForAll( [ 'render: 0', 'render: 1', __DEV__ && 'render: 1', // replay due to invokeGuardedCallback // Retry one more time before handling error 'render: 1', __DEV__ && 'render: 1', // replay due to invokeGuardedCallback 'componentWillUnmount: 0', ].filter(Boolean), ); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error).toHaveBeenCalledWith( __DEV__ ? expect.stringMatching( new RegExp( 'The above error occurred in the <Foo> component:\n' + '\\s+(in|at) Foo (.*)\n' + '\\s+(in|at) ErrorBoundary (.*)\n\n' + 'React will try to recreate this component tree from scratch ' + 'using the error boundary you provided, ErrorBoundary.', ), ) : expect.objectContaining({ message: 'oops', }), ); }); });
28.24
87
0.558528
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core * @jest-environment ./scripts/jest/ReactDOMServerIntegrationEnvironment */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOM; let ReactFeatureFlags; 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'); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.disableLegacyContext = true; // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); function formatValue(val) { if (val === null) { return 'null'; } if (val === undefined) { return 'undefined'; } if (typeof val === 'string') { return val; } return JSON.stringify(val); } describe('ReactDOMServerIntegrationLegacyContextDisabled', () => { beforeEach(() => { resetModules(); }); itRenders('undefined legacy context with warning', async render => { class LegacyProvider extends React.Component { static childContextTypes = { foo() {}, }; getChildContext() { return {foo: 10}; } render() { return this.props.children; } } const lifecycleContextLog = []; class LegacyClsConsumer extends React.Component { static contextTypes = { foo() {}, }; shouldComponentUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); return true; } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { lifecycleContextLog.push(nextContext); } UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); } render() { return formatValue(this.context); } } function LegacyFnConsumer(props, context) { return formatValue(context); } LegacyFnConsumer.contextTypes = {foo() {}}; function RegularFn(props, context) { return formatValue(context); } const e = await render( <LegacyProvider> <span> <LegacyClsConsumer /> <LegacyFnConsumer /> <RegularFn /> </span> </LegacyProvider>, 3, ); expect(e.textContent).toBe('{}undefinedundefined'); expect(lifecycleContextLog).toEqual([]); }); itRenders('modern context', async render => { const Ctx = React.createContext(); class Provider extends React.Component { render() { return ( <Ctx.Provider value={this.props.value}> {this.props.children} </Ctx.Provider> ); } } class RenderPropConsumer extends React.Component { render() { return <Ctx.Consumer>{value => formatValue(value)}</Ctx.Consumer>; } } const lifecycleContextLog = []; class ContextTypeConsumer extends React.Component { static contextType = Ctx; shouldComponentUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); return true; } UNSAFE_componentWillReceiveProps(nextProps, nextContext) { lifecycleContextLog.push(nextContext); } UNSAFE_componentWillUpdate(nextProps, nextState, nextContext) { lifecycleContextLog.push(nextContext); } render() { return formatValue(this.context); } } function FnConsumer() { return formatValue(React.useContext(Ctx)); } const e = await render( <Provider value="a"> <span> <RenderPropConsumer /> <ContextTypeConsumer /> <FnConsumer /> </span> </Provider>, ); expect(e.textContent).toBe('aaa'); expect(lifecycleContextLog).toEqual([]); }); });
23.994118
93
0.63371
PenetrationTestingScripts
/* global chrome */ function fetchResource(url) { const reject = value => { chrome.runtime.sendMessage({ source: 'react-devtools-fetch-resource-content-script', payload: { type: 'fetch-file-with-cache-error', url, value, }, }); }; const resolve = value => { chrome.runtime.sendMessage({ source: 'react-devtools-fetch-resource-content-script', payload: { type: 'fetch-file-with-cache-complete', url, value, }, }); }; fetch(url, {cache: 'force-cache'}).then( response => { if (response.ok) { response .text() .then(text => resolve(text)) .catch(error => reject(null)); } else { reject(null); } }, error => reject(null), ); } chrome.runtime.onMessage.addListener(message => { if ( message?.source === 'devtools-page' && message?.payload?.type === 'fetch-file-with-cache' ) { fetchResource(message.payload.url); } });
19.918367
61
0.541016
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 './VerticalScrollBarView'; export * from './VerticalScrollOverflowView';
23.333333
66
0.71134
Hands-On-Bug-Hunting-for-Penetration-Testers
'use strict'; module.exports = require('./cjs/react-server-dom-webpack-plugin.js');
20.5
69
0.717647
owtf
import Fixture from '../../Fixture'; import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; const React = window.React; class ProgressFixture extends React.Component { state = {value: 0, max: 1, enabled: false, backwards: false}; startTest = () => { this.setState({enabled: true}, () => { this.progressIntervalId = setInterval(() => { if (this.state.backwards) { if (this.state.value > 0) { this.setState({value: this.state.value - this.state.max / 100}); } else { if (this.state.max === 10000) { this.resetTest(); } else { this.setState({max: this.state.max * 100, backwards: false}); } } } else { if (this.state.value < this.state.max) { this.setState({value: this.state.value + this.state.max / 100}); } else { this.setState({backwards: true}); } } }, 10); }); }; resetTest = () => { clearInterval(this.progressIntervalId); this.setState({value: 0, max: 1, enabled: false, backwards: false}); }; render() { return ( <FixtureSet title="Progress"> <TestCase title="Fill and reset progress bar"> <TestCase.Steps> <li>Press enable button</li> </TestCase.Steps> <TestCase.ExpectedResult> When enabled, bar value should increase from 0% to 100% and backwards during three step loop: 0-1, 0-100, 0-10000. Reset button stops loop, sets value to 0 and max to 1. </TestCase.ExpectedResult> <Fixture> <div className="control-box"> <fieldset> <legend>Controlled</legend> <progress value={this.state.value} max={this.state.max}></progress> <button onClick={ this.state.enabled ? this.resetTest : this.startTest }> {this.state.enabled ? 'Reset' : 'Enable'} </button> <br /> <span className="hint"> {' '} max: {JSON.stringify(this.state.max)} </span> <span className="hint"> {' '} value:{' '} {JSON.stringify( Math.round((this.state.value + Number.EPSILON) * 100) / 100 )} </span> </fieldset> </div> </Fixture> </TestCase> </FixtureSet> ); } } export default ProgressFixture;
29.727273
79
0.480207
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 { Thenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; export type ModuleLoading = mixed; type ResolveClientReferenceFn<T> = ClientReferenceMetadata => ClientReference<T>; export type SSRModuleMap = { resolveClientReference?: ResolveClientReferenceFn<any>, }; export type ServerManifest = string; export type { ClientManifest, ServerReferenceId, ClientReferenceMetadata, } from './ReactFlightReferencesFB'; import type { ServerReferenceId, ClientReferenceMetadata, } from './ReactFlightReferencesFB'; export type ClientReference<T> = { getModuleId: () => string, load: () => Thenable<T>, }; export function prepareDestinationForModule( moduleLoading: ModuleLoading, nonce: ?string, metadata: ClientReferenceMetadata, ) { return; } export function resolveClientReference<T>( moduleMap: SSRModuleMap, metadata: ClientReferenceMetadata, ): ClientReference<T> { if (typeof moduleMap.resolveClientReference === 'function') { return moduleMap.resolveClientReference(metadata); } else { throw new Error( 'Expected `resolveClientReference` to be defined on the moduleMap.', ); } } export function resolveServerReference<T>( config: ServerManifest, id: ServerReferenceId, ): ClientReference<T> { throw new Error('Not implemented'); } const asyncModuleCache: Map<string, Thenable<any>> = new Map(); export function preloadModule<T>( clientReference: ClientReference<T>, ): null | Thenable<any> { const existingPromise = asyncModuleCache.get(clientReference.getModuleId()); if (existingPromise) { if (existingPromise.status === 'fulfilled') { return null; } return existingPromise; } else { const modulePromise: Thenable<T> = clientReference.load(); modulePromise.then( value => { const fulfilledThenable: FulfilledThenable<mixed> = (modulePromise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, reason => { const rejectedThenable: RejectedThenable<mixed> = (modulePromise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = reason; }, ); asyncModuleCache.set(clientReference.getModuleId(), modulePromise); return modulePromise; } } export function requireModule<T>(clientReference: ClientReference<T>): T { let module; // We assume that preloadModule has been called before, which // should have added something to the module cache. const promise: any = asyncModuleCache.get(clientReference.getModuleId()); if (promise.status === 'fulfilled') { module = promise.value; } else { throw promise.reason; } // We are currently only support default exports for client components return module; }
25.60177
79
0.713145
Ethical-Hacking-Scripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; const base = Object.create(Object.prototype, { enumerableStringBase: { value: 1, writable: true, enumerable: true, configurable: true, }, // $FlowFixMe[invalid-computed-prop] [Symbol('enumerableSymbolBase')]: { value: 1, writable: true, enumerable: true, configurable: true, }, nonEnumerableStringBase: { value: 1, writable: true, enumerable: false, configurable: true, }, // $FlowFixMe[invalid-computed-prop] [Symbol('nonEnumerableSymbolBase')]: { value: 1, writable: true, enumerable: false, configurable: true, }, }); const data = Object.create(base, { enumerableString: { value: 2, writable: true, enumerable: true, configurable: true, }, nonEnumerableString: { value: 3, writable: true, enumerable: false, configurable: true, }, [123]: { value: 3, writable: true, enumerable: true, configurable: true, }, // $FlowFixMe[invalid-computed-prop] [Symbol('nonEnumerableSymbol')]: { value: 2, writable: true, enumerable: false, configurable: true, }, // $FlowFixMe[invalid-computed-prop] [Symbol('enumerableSymbol')]: { value: 3, writable: true, enumerable: true, configurable: true, }, }); export default function SymbolKeys(): React.Node { return <ChildComponent data={data} />; } function ChildComponent(props: any) { return null; }
19.096386
66
0.637073
Python-Penetration-Testing-for-Developers
'use strict'; module.exports = require('./cjs/react-server-dom-turbopack-node-register.js');
22.75
78
0.734043
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-4E
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local */ import type {LoggerEvent} from 'react-devtools-shared/src/Logger'; import {registerEventLogger} from 'react-devtools-shared/src/Logger'; import {enableLogger} from 'react-devtools-feature-flags'; let currentLoggingIFrame = null; let currentSessionId = null; let missedEvents: Array<LoggerEvent> = []; type LoggerContext = { page_url: ?string, }; export function registerDevToolsEventLogger( surface: string, fetchAdditionalContext?: | (() => LoggerContext) | (() => Promise<LoggerContext>), ): void { async function logEvent(event: LoggerEvent) { if (enableLogger) { if (currentLoggingIFrame != null && currentSessionId != null) { const {metadata, ...eventWithoutMetadata} = event; const additionalContext: LoggerContext | {} = fetchAdditionalContext != null ? await fetchAdditionalContext() : {}; currentLoggingIFrame?.contentWindow?.postMessage( { source: 'react-devtools-logging', event: eventWithoutMetadata, context: { ...additionalContext, metadata: metadata != null ? JSON.stringify(metadata) : '', session_id: currentSessionId, surface, version: process.env.DEVTOOLS_VERSION, }, }, '*', ); } else { missedEvents.push(event); } } } function handleLoggingIFrameLoaded(iframe: HTMLIFrameElement) { currentLoggingIFrame = iframe; if (missedEvents.length > 0) { missedEvents.forEach(event => logEvent(event)); missedEvents = []; } } // If logger is enabled, register a logger that captures logged events // and render iframe where the logged events will be reported to if (enableLogger) { const loggingUrl = process.env.LOGGING_URL; const body = document.body; if ( typeof loggingUrl === 'string' && loggingUrl.length > 0 && body != null && currentLoggingIFrame == null ) { registerEventLogger(logEvent); currentSessionId = window.crypto.randomUUID(); const iframe = document.createElement('iframe'); iframe.onload = () => handleLoggingIFrameLoaded(iframe); iframe.src = loggingUrl; body.appendChild(iframe); } } }
27.157303
79
0.635529
owtf
/** @license React v17.0.0-rc.3 * react-jsx-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("object-assign");var f=require("react"),g=60103;exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var h=Symbol.for;g=h("react.element");exports.Fragment=h("react.fragment")}var m=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0}; function q(c,a,k){var b,d={},e=null,l=null;void 0!==k&&(e=""+k);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(l=a.ref);for(b in a)n.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:g,type:c,key:e,ref:l,props:d,_owner:m.current}}exports.jsx=q;exports.jsxs=q;
87.181818
361
0.68937
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 {checkFormFieldValueStringCoercion} from 'shared/CheckStringCoercion'; type ValueTracker = { getValue(): string, setValue(value: string): void, stopTracking(): void, }; interface ElementWithValueTracker extends HTMLInputElement { _valueTracker?: ?ValueTracker; } function isCheckable(elem: HTMLInputElement) { const type = elem.type; const nodeName = elem.nodeName; return ( nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio') ); } function getTracker(node: ElementWithValueTracker) { return node._valueTracker; } function detachTracker(node: ElementWithValueTracker) { node._valueTracker = null; } function getValueFromNode(node: HTMLInputElement): string { let value = ''; if (!node) { return value; } if (isCheckable(node)) { value = node.checked ? 'true' : 'false'; } else { value = node.value; } return value; } function trackValueOnNode(node: any): ?ValueTracker { const valueField = isCheckable(node) ? 'checked' : 'value'; const descriptor = Object.getOwnPropertyDescriptor( node.constructor.prototype, valueField, ); if (__DEV__) { checkFormFieldValueStringCoercion(node[valueField]); } let currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) if ( node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function' ) { return; } const {get, set} = descriptor; Object.defineProperty(node, valueField, { configurable: true, // $FlowFixMe[missing-this-annot] get: function () { return get.call(this); }, // $FlowFixMe[missing-local-annot] // $FlowFixMe[missing-this-annot] set: function (value) { if (__DEV__) { checkFormFieldValueStringCoercion(value); } currentValue = '' + value; set.call(this, value); }, }); // We could've passed this the first time // but it triggers a bug in IE11 and Edge 14/15. // Calling defineProperty() again should be equivalent. // https://github.com/facebook/react/issues/11768 Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable, }); const tracker = { getValue() { return currentValue; }, setValue(value: string) { if (__DEV__) { checkFormFieldValueStringCoercion(value); } currentValue = '' + value; }, stopTracking() { detachTracker(node); delete node[valueField]; }, }; return tracker; } export function track(node: ElementWithValueTracker) { if (getTracker(node)) { return; } node._valueTracker = trackValueOnNode(node); } export function updateValueIfChanged(node: ElementWithValueTracker): boolean { if (!node) { return false; } const tracker = getTracker(node); // if there is no tracker at this point it's unlikely // that trying again will succeed if (!tracker) { return true; } const lastValue = tracker.getValue(); const nextValue = getValueFromNode(node); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; } export function stopTracking(node: ElementWithValueTracker) { const tracker = getTracker(node); if (tracker) { tracker.stopTracking(); } }
23.166667
78
0.664102
cybersecurity-penetration-testing
'use strict'; var m = require('react-dom'); if (process.env.NODE_ENV === 'production') { exports.createRoot = m.createRoot; exports.hydrateRoot = m.hydrateRoot; } else { var i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; exports.createRoot = function (c, o) { i.usingClientEntryPoint = true; try { return m.createRoot(c, o); } finally { i.usingClientEntryPoint = false; } }; exports.hydrateRoot = function (c, h, o) { i.usingClientEntryPoint = true; try { return m.hydrateRoot(c, h, o); } finally { i.usingClientEntryPoint = false; } }; }
22.923077
63
0.619968
null
#!/usr/bin/env node 'use strict'; const {exec} = require('child-process-promise'); const chalk = require('chalk'); const {join} = require('path'); const semver = require('semver'); const yargs = require('yargs'); const fs = require('fs'); const INSTALL_PACKAGES = ['react-dom', 'react', 'react-test-renderer']; const REGRESSION_FOLDER = 'build-regression'; const ROOT_PATH = join(__dirname, '..', '..'); const buildPath = join(ROOT_PATH, `build`, 'oss-experimental'); const regressionBuildPath = join(ROOT_PATH, REGRESSION_FOLDER); const argv = yargs(process.argv.slice(2)).argv; const version = process.argv[2]; const shouldReplaceBuild = !!argv.replaceBuild; async function downloadRegressionBuild() { console.log(chalk.bold.white(`Downloading React v${version}\n`)); // Make build directory for temporary modules we're going to download // from NPM console.log( chalk.white( `Make Build directory at ${chalk.underline.blue(regressionBuildPath)}\n` ) ); await exec(`mkdir ${regressionBuildPath}`); // Install all necessary React packages that have the same version const downloadPackagesStr = INSTALL_PACKAGES.reduce( (str, name) => `${str} ${name}@${version}`, '' ); await exec( `npm install --prefix ${REGRESSION_FOLDER} ${downloadPackagesStr}` ); // If we shouldn't replace the build folder, we can stop here now // before we modify anything if (!shouldReplaceBuild) { return; } // Remove all the packages that we downloaded in the original build folder // so we can move the modules from the regression build over const removePackagesStr = INSTALL_PACKAGES.reduce( (str, name) => `${str} ${join(buildPath, name)}`, '' ); console.log( chalk.white( `Removing ${removePackagesStr .split(' ') .map(str => chalk.underline.blue(str) + '\n') .join(' ')}\n` ) ); await exec(`rm -r ${removePackagesStr}`); // Move all packages that we downloaded to the original build folder // We need to separately move the scheduler package because it might // be called schedule const movePackageString = INSTALL_PACKAGES.reduce( (str, name) => `${str} ${join(regressionBuildPath, 'node_modules', name)}`, '' ); console.log( chalk.white( `Moving ${movePackageString .split(' ') .map(str => chalk.underline.blue(str) + '\n') .join(' ')} to ${chalk.underline.blue(buildPath)}\n` ) ); await exec(`mv ${movePackageString} ${buildPath}`); // For React versions earlier than 18.0.0, we explicitly scheduler v0.20.1, which // is the first version that has unstable_mock, which DevTools tests need, but also // has Scheduler.unstable_trace, which, although we don't use in DevTools tests // is imported by older React versions and will break if it's not there if (semver.lte(semver.coerce(version).version, '18.0.0')) { await exec(`npm install --prefix ${REGRESSION_FOLDER} [email protected]`); } // In v16.5, scheduler is called schedule. We need to make sure we also move // this over. Otherwise the code will break. if (fs.existsSync(join(regressionBuildPath, 'node_modules', 'schedule'))) { console.log(chalk.white(`Downloading schedule\n`)); await exec( `mv ${join(regressionBuildPath, 'node_modules', 'schedule')} ${buildPath}` ); } else { console.log(chalk.white(`Downloading scheduler\n`)); await exec(`rm -r ${join(buildPath, 'scheduler')}`); await exec( `mv ${join( regressionBuildPath, 'node_modules', 'scheduler' )} ${buildPath}` ); } } async function main() { try { if (!version) { console.log(chalk.red('Must specify React version to download')); return; } await downloadRegressionBuild(); } catch (e) { console.log(chalk.red(e)); } finally { // We shouldn't remove the regression-build folder unless we're using // it to replace the build folder if (shouldReplaceBuild) { console.log(chalk.bold.white(`Removing regression build`)); await exec(`rm -r ${regressionBuildPath}`); } } } main();
30.12782
85
0.655472
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {hydrateRoot} from 'react-dom/client'; import App from './App'; hydrateRoot(document, <App assets={window.assetManifest} />);
24.384615
66
0.711246
owtf
/** * Copyright (c) Facebook, Inc. and its affiliates. */ const fs = require('fs'); const walk = require('./walk'); /** * Validate if there is a custom heading id and exit if there isn't a heading * @param {string} line * @returns */ function validateHeaderId(line) { if (!line.startsWith('#')) { return; } const match = /\{\/\*(.*?)\*\/}/.exec(line); const id = match; if (!id) { console.error('Run yarn fix-headings to generate headings.'); process.exit(1); } } /** * Loops through the lines to skip code blocks * @param {Array<string>} lines */ function validateHeaderIds(lines) { 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; } validateHeaderId(line); }); } /** * paths are basically array of path for which we have to validate heading IDs * @param {Array<string>} paths */ async function main(paths) { paths = paths.length === 0 ? ['src/content'] : paths; 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'); validateHeaderIds(lines); }); } module.exports = main;
20.656716
78
0.593793
owtf
var Builder = require('systemjs-builder'); var builder = new Builder('/', './config.js'); builder .buildStatic('./input.js', './output.js') .then(function () { console.log('Build complete'); }) .catch(function (err) { console.log('Build error'); console.log(err); });
21.461538
46
0.608247
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; describe('ReactMultiChild', () => { let React; let ReactDOM; beforeEach(() => { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); }); describe('reconciliation', () => { it('should update children when possible', () => { const container = document.createElement('div'); const mockMount = jest.fn(); const mockUpdate = jest.fn(); const mockUnmount = jest.fn(); class MockComponent extends React.Component { componentDidMount = mockMount; componentDidUpdate = mockUpdate; componentWillUnmount = mockUnmount; render() { return <span />; } } expect(mockMount).toHaveBeenCalledTimes(0); expect(mockUpdate).toHaveBeenCalledTimes(0); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <div> <MockComponent /> </div>, container, ); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUpdate).toHaveBeenCalledTimes(0); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <div> <MockComponent /> </div>, container, ); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUpdate).toHaveBeenCalledTimes(1); expect(mockUnmount).toHaveBeenCalledTimes(0); }); it('should replace children with different constructors', () => { const container = document.createElement('div'); const mockMount = jest.fn(); const mockUnmount = jest.fn(); class MockComponent extends React.Component { componentDidMount = mockMount; componentWillUnmount = mockUnmount; render() { return <span />; } } expect(mockMount).toHaveBeenCalledTimes(0); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <div> <MockComponent /> </div>, container, ); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <div> <span /> </div>, container, ); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUnmount).toHaveBeenCalledTimes(1); }); it('should NOT replace children with different owners', () => { const container = document.createElement('div'); const mockMount = jest.fn(); const mockUnmount = jest.fn(); class MockComponent extends React.Component { componentDidMount = mockMount; componentWillUnmount = mockUnmount; render() { return <span />; } } class WrapperComponent extends React.Component { render() { return this.props.children || <MockComponent />; } } expect(mockMount).toHaveBeenCalledTimes(0); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render(<WrapperComponent />, container); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <WrapperComponent> <MockComponent /> </WrapperComponent>, container, ); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUnmount).toHaveBeenCalledTimes(0); }); it('should replace children with different keys', () => { const container = document.createElement('div'); const mockMount = jest.fn(); const mockUnmount = jest.fn(); class MockComponent extends React.Component { componentDidMount = mockMount; componentWillUnmount = mockUnmount; render() { return <span />; } } expect(mockMount).toHaveBeenCalledTimes(0); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <div> <MockComponent key="A" /> </div>, container, ); expect(mockMount).toHaveBeenCalledTimes(1); expect(mockUnmount).toHaveBeenCalledTimes(0); ReactDOM.render( <div> <MockComponent key="B" /> </div>, container, ); expect(mockMount).toHaveBeenCalledTimes(2); expect(mockUnmount).toHaveBeenCalledTimes(1); }); it('should warn for duplicated array keys with component stack info', () => { const container = document.createElement('div'); class WrapperComponent extends React.Component { render() { return <div>{this.props.children}</div>; } } class Parent extends React.Component { render() { return ( <div> <WrapperComponent>{this.props.children}</WrapperComponent> </div> ); } } ReactDOM.render(<Parent>{[<div key="1" />]}</Parent>, container); expect(() => ReactDOM.render( <Parent>{[<div key="1" />, <div key="1" />]}</Parent>, container, ), ).toErrorDev( 'Encountered two children with the same key, `1`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted β€” the behavior is unsupported and ' + 'could change in a future version.\n' + ' in div (at **)\n' + ' in WrapperComponent (at **)\n' + ' in div (at **)\n' + ' in Parent (at **)', ); }); it('should warn for duplicated iterable keys with component stack info', () => { const container = document.createElement('div'); class WrapperComponent extends React.Component { render() { return <div>{this.props.children}</div>; } } class Parent extends React.Component { render() { return ( <div> <WrapperComponent>{this.props.children}</WrapperComponent> </div> ); } } function createIterable(array) { return { '@@iterator': function () { let i = 0; return { next() { const next = { value: i < array.length ? array[i] : undefined, done: i === array.length, }; i++; return next; }, }; }, }; } ReactDOM.render( <Parent>{createIterable([<div key="1" />])}</Parent>, container, ); expect(() => ReactDOM.render( <Parent>{createIterable([<div key="1" />, <div key="1" />])}</Parent>, container, ), ).toErrorDev( 'Encountered two children with the same key, `1`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted β€” the behavior is unsupported and ' + 'could change in a future version.\n' + ' in div (at **)\n' + ' in WrapperComponent (at **)\n' + ' in div (at **)\n' + ' in Parent (at **)', ); }); }); it('should warn for using maps as children with owner info', () => { class Parent extends React.Component { render() { return ( <div> { new Map([ ['foo', 0], ['bar', 1], ]) } </div> ); } } const container = document.createElement('div'); expect(() => ReactDOM.render(<Parent />, container)).toErrorDev( 'Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.\n' + ' in div (at **)\n' + ' in Parent (at **)', ); }); it('should warn for using generators as children', () => { function* Foo() { yield <h1 key="1">Hello</h1>; yield <h1 key="2">World</h1>; } const div = document.createElement('div'); expect(() => { ReactDOM.render(<Foo />, div); }).toErrorDev( 'Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. You may ' + 'convert it to an array with `Array.from()` or the `[...spread]` operator ' + 'before rendering. Keep in mind you might need to polyfill these features for older browsers.\n' + ' in Foo (at **)', ); // Test de-duplication ReactDOM.render(<Foo />, div); }); it('should not warn for using generators in legacy iterables', () => { const fooIterable = { '@@iterator': function* () { yield <h1 key="1">Hello</h1>; yield <h1 key="2">World</h1>; }, }; function Foo() { return fooIterable; } const div = document.createElement('div'); ReactDOM.render(<Foo />, div); expect(div.textContent).toBe('HelloWorld'); ReactDOM.render(<Foo />, div); expect(div.textContent).toBe('HelloWorld'); }); it('should not warn for using generators in modern iterables', () => { const fooIterable = { [Symbol.iterator]: function* () { yield <h1 key="1">Hello</h1>; yield <h1 key="2">World</h1>; }, }; function Foo() { return fooIterable; } const div = document.createElement('div'); ReactDOM.render(<Foo />, div); expect(div.textContent).toBe('HelloWorld'); ReactDOM.render(<Foo />, div); expect(div.textContent).toBe('HelloWorld'); }); it('should reorder bailed-out children', () => { class LetterInner extends React.Component { render() { return <div>{this.props.char}</div>; } } class Letter extends React.Component { render() { return <LetterInner char={this.props.char} />; } shouldComponentUpdate() { return false; } } class Letters extends React.Component { render() { const letters = this.props.letters.split(''); return ( <div> {letters.map(c => ( <Letter key={c} char={c} /> ))} </div> ); } } const container = document.createElement('div'); // Two random strings -- some additions, some removals, some moves ReactDOM.render(<Letters letters="XKwHomsNjIkBcQWFbiZU" />, container); expect(container.textContent).toBe('XKwHomsNjIkBcQWFbiZU'); ReactDOM.render(<Letters letters="EHCjpdTUuiybDvhRJwZt" />, container); expect(container.textContent).toBe('EHCjpdTUuiybDvhRJwZt'); }); it('prepares new children before unmounting old', () => { const log = []; class Spy extends React.Component { UNSAFE_componentWillMount() { log.push(this.props.name + ' componentWillMount'); } render() { log.push(this.props.name + ' render'); return <div />; } componentDidMount() { log.push(this.props.name + ' componentDidMount'); } componentWillUnmount() { log.push(this.props.name + ' componentWillUnmount'); } } // These are reference-unequal so they will be swapped even if they have // matching keys const SpyA = props => <Spy {...props} />; const SpyB = props => <Spy {...props} />; const container = document.createElement('div'); ReactDOM.render( <div> <SpyA key="one" name="oneA" /> <SpyA key="two" name="twoA" /> </div>, container, ); ReactDOM.render( <div> <SpyB key="one" name="oneB" /> <SpyB key="two" name="twoB" /> </div>, container, ); expect(log).toEqual([ 'oneA componentWillMount', 'oneA render', 'twoA componentWillMount', 'twoA render', 'oneA componentDidMount', 'twoA componentDidMount', 'oneB componentWillMount', 'oneB render', 'twoB componentWillMount', 'twoB render', 'oneA componentWillUnmount', 'twoA componentWillUnmount', 'oneB componentDidMount', 'twoB componentDidMount', ]); }); });
25.991379
106
0.555218
PenetrationTestingScripts
/* globals chrome */ 'use strict'; document.addEventListener('DOMContentLoaded', function () { // Make links work const links = document.getElementsByTagName('a'); for (let i = 0; i < links.length; i++) { (function () { const ln = links[i]; const location = ln.href; ln.onclick = function () { chrome.tabs.create({active: true, url: location}); return false; }; })(); } // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=428044 document.body.style.opacity = 0; document.body.style.transition = 'opacity ease-out .4s'; requestAnimationFrame(function () { document.body.style.opacity = 1; }); });
25.423077
77
0.625364
PenetrationTestingScripts
import hasOwnProperty from 'shared/hasOwnProperty'; const FILTERED_VERSION_STRING = '<filtered-version>'; // test() is part of Jest's serializer API export function test(maybeProfile) { if ( maybeProfile != null && typeof maybeProfile === 'object' && hasOwnProperty.call(maybeProfile, 'reactVersion') && maybeProfile.reactVersion !== FILTERED_VERSION_STRING ) { return true; } return false; } // print() is part of Jest's serializer API export function print(profile, serialize, indent) { return serialize({ ...profile, reactVersion: FILTERED_VERSION_STRING, }); }
22.461538
57
0.692939
owtf
'use strict'; const { es5Paths, esNextPaths, } = require('./scripts/shared/pathsByLanguageVersion'); const restrictedGlobals = require('confusing-browser-globals'); const OFF = 0; const WARNING = 1; const ERROR = 2; module.exports = { extends: ['prettier'], // Stop ESLint from looking for a configuration file in parent folders root: true, plugins: [ 'babel', 'ft-flow', 'jest', 'no-for-of-loops', 'no-function-declare-after-return', 'react', 'react-internal', ], parser: 'hermes-eslint', parserOptions: { ecmaVersion: 9, sourceType: 'script', }, // We're stricter than the default config, mostly. We'll override a few rules // and then enable some React specific ones. rules: { 'ft-flow/array-style-complex-type': [OFF, 'verbose'], 'ft-flow/array-style-simple-type': [OFF, 'verbose'], // TODO should be WARNING 'ft-flow/boolean-style': ERROR, 'ft-flow/no-dupe-keys': ERROR, 'ft-flow/no-primitive-constructor-types': ERROR, 'ft-flow/no-types-missing-file-annotation': OFF, // TODO should be ERROR 'ft-flow/no-unused-expressions': ERROR, // 'ft-flow/no-weak-types': WARNING, // 'ft-flow/require-valid-file-annotation': ERROR, 'no-cond-assign': OFF, 'no-constant-condition': OFF, 'no-control-regex': OFF, 'no-debugger': ERROR, 'no-dupe-args': ERROR, 'no-dupe-keys': ERROR, 'no-duplicate-case': WARNING, 'no-empty-character-class': WARNING, 'no-empty': OFF, 'no-ex-assign': WARNING, 'no-extra-boolean-cast': WARNING, 'no-func-assign': ERROR, 'no-invalid-regexp': WARNING, 'no-irregular-whitespace': WARNING, 'no-negated-in-lhs': ERROR, 'no-obj-calls': ERROR, 'no-regex-spaces': WARNING, 'no-sparse-arrays': ERROR, 'no-unreachable': ERROR, 'use-isnan': ERROR, 'valid-jsdoc': OFF, 'block-scoped-var': OFF, complexity: OFF, 'default-case': OFF, 'guard-for-in': OFF, 'no-alert': OFF, 'no-caller': ERROR, 'no-case-declarations': OFF, 'no-div-regex': OFF, 'no-else-return': OFF, 'no-empty-pattern': WARNING, 'no-eq-null': OFF, 'no-eval': ERROR, 'no-extend-native': WARNING, 'no-extra-bind': WARNING, 'no-fallthrough': WARNING, 'no-implicit-coercion': OFF, 'no-implied-eval': ERROR, 'no-invalid-this': OFF, 'no-iterator': OFF, 'no-labels': [ERROR, {allowLoop: true, allowSwitch: true}], 'no-lone-blocks': WARNING, 'no-loop-func': OFF, 'no-magic-numbers': OFF, 'no-multi-str': ERROR, 'no-native-reassign': [ERROR, {exceptions: ['Map', 'Set']}], 'no-new-func': ERROR, 'no-new': WARNING, 'no-new-wrappers': WARNING, 'no-octal-escape': WARNING, 'no-octal': WARNING, 'no-param-reassign': OFF, 'no-process-env': OFF, 'no-proto': ERROR, 'no-redeclare': OFF, // TODO should be WARNING? 'no-return-assign': OFF, 'no-script-url': ERROR, 'no-self-compare': WARNING, 'no-sequences': WARNING, 'no-throw-literal': ERROR, 'no-useless-call': WARNING, 'no-void': OFF, 'no-warning-comments': OFF, 'no-with': OFF, radix: WARNING, 'vars-on-top': OFF, yoda: OFF, 'init-declarations': OFF, 'no-catch-shadow': ERROR, 'no-delete-var': ERROR, 'no-label-var': WARNING, 'no-shadow-restricted-names': WARNING, 'no-undef-init': OFF, 'no-undef': ERROR, 'no-undefined': OFF, 'callback-return': OFF, 'global-require': OFF, 'handle-callback-err': OFF, 'no-mixed-requires': OFF, 'no-new-require': OFF, 'no-path-concat': OFF, 'no-process-exit': OFF, 'no-restricted-modules': OFF, 'no-sync': OFF, camelcase: [OFF, {properties: 'always'}], 'consistent-this': [OFF, 'self'], 'func-names': OFF, 'func-style': [OFF, 'declaration'], 'id-length': OFF, 'id-match': OFF, 'max-depth': OFF, 'max-nested-callbacks': OFF, 'max-params': OFF, 'max-statements': OFF, 'new-cap': OFF, 'newline-after-var': OFF, 'no-array-constructor': ERROR, 'no-continue': OFF, 'no-inline-comments': OFF, 'no-lonely-if': OFF, 'no-negated-condition': OFF, 'no-nested-ternary': OFF, 'no-new-object': WARNING, 'no-plusplus': OFF, 'no-ternary': OFF, 'no-underscore-dangle': OFF, 'no-unneeded-ternary': WARNING, 'one-var': [WARNING, {initialized: 'never'}], 'operator-assignment': [WARNING, 'always'], 'require-jsdoc': OFF, 'sort-vars': OFF, 'spaced-comment': [ OFF, 'always', {exceptions: ['jshint', 'jslint', 'eslint', 'global']}, ], 'constructor-super': ERROR, 'no-class-assign': WARNING, 'no-const-assign': ERROR, 'no-dupe-class-members': ERROR, 'no-this-before-super': ERROR, 'object-shorthand': OFF, 'prefer-const': OFF, 'prefer-spread': OFF, 'prefer-reflect': OFF, 'prefer-template': OFF, 'require-yield': OFF, 'babel/generator-star-spacing': OFF, 'babel/new-cap': OFF, 'babel/array-bracket-spacing': OFF, 'babel/object-curly-spacing': OFF, 'babel/object-shorthand': OFF, 'babel/arrow-parens': OFF, 'babel/no-await-in-loop': OFF, 'babel/flow-object-type': OFF, 'react/display-name': OFF, 'react/forbid-prop-types': OFF, 'react/jsx-closing-bracket-location': OFF, 'react/jsx-curly-spacing': OFF, 'react/jsx-equals-spacing': WARNING, 'react/jsx-filename-extension': OFF, 'react/jsx-first-prop-new-line': OFF, 'react/jsx-handler-names': OFF, 'react/jsx-indent': OFF, 'react/jsx-indent-props': OFF, 'react/jsx-key': OFF, 'react/jsx-max-props-per-line': OFF, 'react/jsx-no-bind': OFF, 'react/jsx-no-duplicate-props': ERROR, 'react/jsx-no-literals': OFF, 'react/jsx-no-target-blank': OFF, 'react/jsx-pascal-case': OFF, 'react/jsx-sort-props': OFF, 'react/jsx-uses-vars': ERROR, 'react/no-comment-textnodes': OFF, 'react/no-danger': OFF, 'react/no-deprecated': OFF, 'react/no-did-mount-set-state': OFF, 'react/no-did-update-set-state': OFF, 'react/no-direct-mutation-state': OFF, 'react/no-multi-comp': OFF, 'react/no-render-return-value': OFF, 'react/no-set-state': OFF, 'react/no-string-refs': OFF, 'react/no-unknown-property': OFF, 'react/prefer-es6-class': OFF, 'react/prefer-stateless-function': OFF, 'react/prop-types': OFF, 'react/require-extension': OFF, 'react/require-optimization': OFF, 'react/require-render-return': OFF, 'react/sort-comp': OFF, 'react/sort-prop-types': OFF, 'accessor-pairs': OFF, 'brace-style': [ERROR, '1tbs'], 'consistent-return': OFF, 'dot-location': [ERROR, 'property'], // We use console['error']() as a signal to not transform it: 'dot-notation': [ERROR, {allowPattern: '^(error|warn)$'}], 'eol-last': ERROR, eqeqeq: [ERROR, 'allow-null'], indent: OFF, 'jsx-quotes': [ERROR, 'prefer-double'], 'keyword-spacing': [ERROR, {after: true, before: true}], 'no-bitwise': OFF, 'no-console': OFF, 'no-inner-declarations': [ERROR, 'functions'], 'no-multi-spaces': ERROR, 'no-restricted-globals': [ERROR].concat(restrictedGlobals), 'no-restricted-syntax': [ ERROR, 'WithStatement', { selector: 'MemberExpression[property.name=/^(?:substring|substr)$/]', message: 'Prefer string.slice() over .substring() and .substr().', }, ], 'no-shadow': ERROR, 'no-unused-vars': [ERROR, {args: 'none'}], 'no-use-before-define': OFF, 'no-useless-concat': OFF, quotes: [ERROR, 'single', {avoidEscape: true, allowTemplateLiterals: true}], 'space-before-blocks': ERROR, 'space-before-function-paren': OFF, 'valid-typeof': [ERROR, {requireStringLiterals: true}], // Flow fails with non-string literal keys 'no-useless-computed-key': OFF, // We apply these settings to files that should run on Node. // They can't use JSX or ES6 modules, and must be in strict mode. // They can, however, use other ES6 features. // (Note these rules are overridden later for source files.) 'no-var': ERROR, strict: ERROR, // Enforced by Prettier // TODO: Prettier doesn't handle long strings or long comments. Not a big // deal. But I turned it off because loading the plugin causes some obscure // syntax error and it didn't seem worth investigating. 'max-len': OFF, // React & JSX // Our transforms set this automatically 'react/jsx-boolean-value': [ERROR, 'always'], 'react/jsx-no-undef': ERROR, // We don't care to do this 'react/jsx-sort-prop-types': OFF, 'react/jsx-space-before-closing': ERROR, 'react/jsx-uses-react': ERROR, 'react/no-is-mounted': OFF, // This isn't useful in our test code 'react/react-in-jsx-scope': ERROR, 'react/self-closing-comp': ERROR, // We don't care to do this 'react/jsx-wrap-multilines': [ ERROR, {declaration: false, assignment: false}, ], // Prevent for...of loops because they require a Symbol polyfill. // You can disable this rule for code that isn't shipped (e.g. build scripts and tests). 'no-for-of-loops/no-for-of-loops': ERROR, // Prevent function declarations after return statements 'no-function-declare-after-return/no-function-declare-after-return': ERROR, // CUSTOM RULES // the second argument of warning/invariant should be a literal string 'react-internal/no-primitive-constructors': ERROR, 'react-internal/safe-string-coercion': [ ERROR, {isProductionUserAppCode: true}, ], 'react-internal/no-to-warn-dev-within-to-throw': ERROR, 'react-internal/warning-args': ERROR, 'react-internal/no-production-logging': ERROR, }, overrides: [ { // By default, anything error message that appears the packages directory // must have a corresponding error code. The exceptions are defined // in the next override entry. files: ['packages/**/*.js'], rules: { 'react-internal/prod-error-codes': ERROR, }, }, { // These are files where it's OK to have unminified error messages. These // are environments where bundle size isn't a concern, like tests // or Node. files: [ 'packages/react-dom/src/test-utils/**/*.js', 'packages/react-devtools-shared/**/*.js', 'packages/react-noop-renderer/**/*.js', 'packages/react-refresh/**/*.js', 'packages/react-server-dom-esm/**/*.js', 'packages/react-server-dom-webpack/**/*.js', 'packages/react-server-dom-turbopack/**/*.js', 'packages/react-server-dom-fb/**/*.js', 'packages/react-test-renderer/**/*.js', 'packages/react-debug-tools/**/*.js', 'packages/react-devtools-extensions/**/*.js', 'packages/react-devtools-timeline/**/*.js', 'packages/react-native-renderer/**/*.js', 'packages/eslint-plugin-react-hooks/**/*.js', 'packages/jest-react/**/*.js', 'packages/internal-test-utils/**/*.js', 'packages/**/__tests__/*.js', 'packages/**/npm/*.js', ], rules: { 'react-internal/prod-error-codes': OFF, }, }, { // We apply these settings to files that we ship through npm. // They must be ES5. files: es5Paths, parser: 'espree', parserOptions: { ecmaVersion: 5, sourceType: 'script', }, rules: { 'no-var': OFF, strict: ERROR, }, }, { // We apply these settings to the source files that get compiled. // They can use all features including JSX (but shouldn't use `var`). files: esNextPaths, parser: 'hermes-eslint', parserOptions: { ecmaVersion: 8, sourceType: 'module', }, rules: { 'no-var': ERROR, 'prefer-const': ERROR, strict: OFF, }, }, { files: ['**/__tests__/*.js'], rules: { // https://github.com/jest-community/eslint-plugin-jest 'jest/no-focused-tests': ERROR, 'jest/valid-expect': ERROR, 'jest/valid-expect-in-promise': ERROR, }, }, { files: [ '**/__tests__/**/*.js', 'scripts/**/*.js', 'packages/*/npm/**/*.js', 'packages/dom-event-testing-library/**/*.js', 'packages/react-devtools*/**/*.js', 'dangerfile.js', 'fixtures', 'packages/react-dom/src/test-utils/*.js', ], rules: { 'react-internal/no-production-logging': OFF, 'react-internal/warning-args': OFF, 'react-internal/safe-string-coercion': [ ERROR, {isProductionUserAppCode: false}, ], }, }, { files: [ 'scripts/eslint-rules/*.js', 'packages/eslint-plugin-react-hooks/src/*.js', ], plugins: ['eslint-plugin'], rules: { 'eslint-plugin/prefer-object-rule': ERROR, 'eslint-plugin/require-meta-fixable': [ ERROR, {catchNoFixerButFixableProperty: true}, ], 'eslint-plugin/require-meta-has-suggestions': ERROR, }, }, { files: ['packages/react-native-renderer/**/*.js'], globals: { nativeFabricUIManager: 'readonly', }, }, { files: ['packages/react-server-dom-webpack/**/*.js'], globals: { __webpack_chunk_load__: 'readonly', __webpack_require__: 'readonly', }, }, { files: ['packages/react-server-dom-turbopack/**/*.js'], globals: { __turbopack_load__: 'readonly', __turbopack_require__: 'readonly', }, }, { files: ['packages/scheduler/**/*.js'], globals: { TaskController: 'readonly', }, }, { files: ['packages/react-devtools-extensions/**/*.js'], globals: { __IS_CHROME__: 'readonly', __IS_FIREFOX__: 'readonly', __IS_EDGE__: 'readonly', }, }, ], env: { browser: true, es6: true, node: true, jest: true, }, globals: { $Call: 'readonly', $ElementType: 'readonly', $Flow$ModuleRef: 'readonly', $FlowFixMe: 'readonly', $Keys: 'readonly', $NonMaybeType: 'readonly', $PropertyType: 'readonly', $ReadOnly: 'readonly', $ReadOnlyArray: 'readonly', $ArrayBufferView: 'readonly', $Shape: 'readonly', ReturnType: 'readonly', AnimationFrameID: 'readonly', // For Flow type annotation. Only `BigInt` is valid at runtime. bigint: 'readonly', BigInt: 'readonly', BigInt64Array: 'readonly', BigUint64Array: 'readonly', Class: 'readonly', ClientRect: 'readonly', CopyInspectedElementPath: 'readonly', DOMHighResTimeStamp: 'readonly', EventListener: 'readonly', Iterable: 'readonly', Iterator: 'readonly', JSONValue: 'readonly', JSResourceReference: 'readonly', MouseEventHandler: 'readonly', PropagationPhases: 'readonly', PropertyDescriptor: 'readonly', React$AbstractComponent: 'readonly', React$Component: 'readonly', React$ComponentType: 'readonly', React$Config: 'readonly', React$Context: 'readonly', React$Element: 'readonly', React$ElementConfig: 'readonly', React$ElementProps: 'readonly', React$ElementRef: 'readonly', React$ElementType: 'readonly', React$Key: 'readonly', React$Node: 'readonly', React$Portal: 'readonly', React$Ref: 'readonly', ReadableStreamController: 'readonly', RequestInfo: 'readonly', RequestOptions: 'readonly', StoreAsGlobal: 'readonly', symbol: 'readonly', SyntheticEvent: 'readonly', SyntheticMouseEvent: 'readonly', Thenable: 'readonly', TimeoutID: 'readonly', WheelEventHandler: 'readonly', FinalizationRegistry: 'readonly', spyOnDev: 'readonly', spyOnDevAndProd: 'readonly', spyOnProd: 'readonly', __DEV__: 'readonly', __EXPERIMENTAL__: 'readonly', __EXTENSION__: 'readonly', __PROFILE__: 'readonly', __TEST__: 'readonly', __UMD__: 'readonly', __VARIANT__: 'readonly', __unmockReact: 'readonly', gate: 'readonly', trustedTypes: 'readonly', IS_REACT_ACT_ENVIRONMENT: 'readonly', AsyncLocalStorage: 'readonly', async_hooks: 'readonly', globalThis: 'readonly', }, };
29.579926
92
0.597532
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {hydrateRoot} from 'react-dom/client'; import App from './App'; hydrateRoot(document, <App assets={window.assetManifest} />);
24.384615
66
0.711246
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {Writable} from 'stream'; import * as React from 'react'; import {renderToPipeableStream} from 'react-dom/server'; import App from '../src/App'; import {ABORT_DELAY} from './delays'; // In a real setup, you'd read it from webpack build stats. let assets = { 'main.js': '/main.js', 'main.css': '/main.css', }; function HtmlWritable(options) { Writable.call(this, options); this.chunks = []; this.html = ''; } HtmlWritable.prototype = Object.create(Writable.prototype); HtmlWritable.prototype.getHtml = function getHtml() { return this.html; }; HtmlWritable.prototype._write = function _write(chunk, encoding, callback) { this.chunks.push(chunk); callback(); }; HtmlWritable.prototype._final = function _final(callback) { this.html = Buffer.concat(this.chunks).toString(); callback(); }; module.exports = function render(url, res) { let writable = new HtmlWritable(); res.socket.on('error', error => { console.error('Fatal', error); }); let didError = false; let didFinish = false; writable.on('finish', () => { // If something errored before we started streaming, we set the error code appropriately. res.statusCode = didError ? 500 : 200; res.setHeader('Content-type', 'text/html'); res.send(writable.getHtml()); }); const {pipe, abort} = renderToPipeableStream(<App assets={assets} />, { bootstrapScripts: [assets['main.js']], onAllReady() { // Full completion. // You can use this for SSG or crawlers. didFinish = true; }, onShellReady() { // If something errored before we started streaming, we set the error code appropriately. pipe(writable); }, onShellError(x) { // Something errored before we could complete the shell so we emit an alternative shell. res.statusCode = 500; res.send('<!doctype><p>Error</p>'); }, onError(x) { didError = true; console.error(x); }, }); // Abandon and switch to client rendering if enough time passes. // Try lowering this to see the client recover. setTimeout(() => { if (!didFinish) { abort(); } }, ABORT_DELAY); };
26.857143
95
0.652843
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 */ // test() is part of Jest's serializer API export function test(maybeDehydratedValue) { const {meta} = require('react-devtools-shared/src/hydration'); const hasOwnProperty = Object.prototype.hasOwnProperty.bind(maybeDehydratedValue); return ( maybeDehydratedValue !== null && typeof maybeDehydratedValue === 'object' && hasOwnProperty(meta.inspectable) && maybeDehydratedValue[meta.inspected] !== true ); } // print() is part of Jest's serializer API export function print(dehydratedValue, serialize, indent) { const {meta} = require('react-devtools-shared/src/hydration'); const indentation = Math.max(indent('.').indexOf('.') - 2, 0); const paddingLeft = ' '.repeat(indentation); return ( 'Dehydrated {\n' + paddingLeft + ' "preview_short": ' + dehydratedValue[meta.preview_short] + ',\n' + paddingLeft + ' "preview_long": ' + dehydratedValue[meta.preview_long] + ',\n' + paddingLeft + '}' ); }
26.627907
66
0.664701
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 */ /* eslint-disable no-script-url */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOM; let ReactDOMServer; let ReactTestUtils; const EXPECTED_SAFE_URL = "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')"; describe('ReactDOMServerIntegration - Untrusted URLs', () => { // The `itRenders` helpers don't work with the gate pragma, so we have to do // this instead. if (gate(flags => flags.disableJavaScriptURLs)) { it("empty test so Jest doesn't complain", () => {}); return; } function initModules() { jest.resetModules(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); ReactTestUtils = require('react-dom/test-utils'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, ReactTestUtils, }; } const {resetModules, itRenders} = ReactDOMServerIntegrationUtils(initModules); beforeEach(() => { resetModules(); }); itRenders('a http link with the word javascript in it', async render => { const e = await render( <a href="http://javascript:0/thisisfine">Click me</a>, ); expect(e.tagName).toBe('A'); expect(e.href).toBe('http://javascript:0/thisisfine'); }); itRenders('a javascript protocol href', async render => { // Only the first one warns. The second warning is deduped. const e = await render( <div> <a href="javascript:notfine">p0wned</a> <a href="javascript:notfineagain">p0wned again</a> </div>, 1, ); expect(e.firstChild.href).toBe('javascript:notfine'); expect(e.lastChild.href).toBe('javascript:notfineagain'); }); itRenders('a javascript protocol with leading spaces', async render => { const e = await render( <a href={' \t \u0000\u001F\u0003javascript\n: notfine'}>p0wned</a>, 1, ); // We use an approximate comparison here because JSDOM might not parse // \u0000 in HTML properly. expect(e.href).toContain('notfine'); }); itRenders( 'a javascript protocol with intermediate new lines and mixed casing', async render => { const e = await render( <a href={'\t\r\n Jav\rasCr\r\niP\t\n\rt\n:notfine'}>p0wned</a>, 1, ); expect(e.href).toBe('javascript:notfine'); }, ); itRenders('a javascript protocol area href', async render => { const e = await render( <map> <area href="javascript:notfine" /> </map>, 1, ); expect(e.firstChild.href).toBe('javascript:notfine'); }); itRenders('a javascript protocol form action', async render => { const e = await render(<form action="javascript:notfine">p0wned</form>, 1); expect(e.action).toBe('javascript:notfine'); }); itRenders('a javascript protocol input formAction', async render => { const e = await render( <input type="submit" formAction="javascript:notfine" />, 1, ); expect(e.getAttribute('formAction')).toBe('javascript:notfine'); }); itRenders('a javascript protocol button formAction', async render => { const e = await render( <button formAction="javascript:notfine">p0wned</button>, 1, ); expect(e.getAttribute('formAction')).toBe('javascript:notfine'); }); itRenders('a javascript protocol iframe src', async render => { const e = await render(<iframe src="javascript:notfine" />, 1); expect(e.src).toBe('javascript:notfine'); }); itRenders('a javascript protocol frame src', async render => { const e = await render( <html> <head /> <frameset> <frame src="javascript:notfine" /> </frameset> </html>, 1, ); expect(e.lastChild.firstChild.src).toBe('javascript:notfine'); }); itRenders('a javascript protocol in an SVG link', async render => { const e = await render( <svg> <a href="javascript:notfine" /> </svg>, 1, ); expect(e.firstChild.getAttribute('href')).toBe('javascript:notfine'); }); itRenders( 'a javascript protocol in an SVG link with a namespace', async render => { const e = await render( <svg> <a xlinkHref="javascript:notfine" /> </svg>, 1, ); expect( e.firstChild.getAttributeNS('http://www.w3.org/1999/xlink', 'href'), ).toBe('javascript:notfine'); }, ); it('rejects a javascript protocol href if it is added during an update', () => { const container = document.createElement('div'); ReactDOM.render(<a href="thisisfine">click me</a>, container); expect(() => { ReactDOM.render(<a href="javascript:notfine">click me</a>, container); }).toErrorDev( 'Warning: A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try using ' + 'dangerouslySetInnerHTML instead. React was passed "javascript:notfine".\n' + ' in a (at **)', ); }); }); describe('ReactDOMServerIntegration - Untrusted URLs - disableJavaScriptURLs', () => { // The `itRenders` helpers don't work with the gate pragma, so we have to do // this instead. if (gate(flags => !flags.disableJavaScriptURLs)) { it("empty test so Jest doesn't complain", () => {}); return; } function initModules() { jest.resetModules(); const ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.disableJavaScriptURLs = true; 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, clientRenderOnBadMarkup, clientRenderOnServerString, } = ReactDOMServerIntegrationUtils(initModules); beforeEach(() => { resetModules(); }); itRenders('a http link with the word javascript in it', async render => { const e = await render( <a href="http://javascript:0/thisisfine">Click me</a>, ); expect(e.tagName).toBe('A'); expect(e.href).toBe('http://javascript:0/thisisfine'); }); itRenders('a javascript protocol href', async render => { // Only the first one warns. The second warning is deduped. const e = await render( <div> <a href="javascript:notfine">p0wned</a> <a href="javascript:notfineagain">p0wned again</a> </div>, ); expect(e.firstChild.href).toBe(EXPECTED_SAFE_URL); expect(e.lastChild.href).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol with leading spaces', async render => { const e = await render( <a href={' \t \u0000\u001F\u0003javascript\n: notfine'}>p0wned</a>, ); // We use an approximate comparison here because JSDOM might not parse // \u0000 in HTML properly. expect(e.href).toBe(EXPECTED_SAFE_URL); }); itRenders( 'a javascript protocol with intermediate new lines and mixed casing', async render => { const e = await render( <a href={'\t\r\n Jav\rasCr\r\niP\t\n\rt\n:notfine'}>p0wned</a>, ); expect(e.href).toBe(EXPECTED_SAFE_URL); }, ); itRenders('a javascript protocol area href', async render => { const e = await render( <map> <area href="javascript:notfine" /> </map>, ); expect(e.firstChild.href).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol form action', async render => { const e = await render(<form action="javascript:notfine">p0wned</form>); expect(e.action).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol input formAction', async render => { const e = await render( <input type="submit" formAction="javascript:notfine" />, ); expect(e.getAttribute('formAction')).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol button formAction', async render => { const e = await render( <button formAction="javascript:notfine">p0wned</button>, ); expect(e.getAttribute('formAction')).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol iframe src', async render => { const e = await render(<iframe src="javascript:notfine" />); expect(e.src).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol frame src', async render => { const e = await render( <html> <head /> <frameset> <frame src="javascript:notfine" /> </frameset> </html>, ); expect(e.lastChild.firstChild.src).toBe(EXPECTED_SAFE_URL); }); itRenders('a javascript protocol in an SVG link', async render => { const e = await render( <svg> <a href="javascript:notfine" /> </svg>, ); expect(e.firstChild.getAttribute('href')).toBe(EXPECTED_SAFE_URL); }); itRenders( 'a javascript protocol in an SVG link with a namespace', async render => { const e = await render( <svg> <a xlinkHref="javascript:notfine" /> </svg>, ); expect( e.firstChild.getAttributeNS('http://www.w3.org/1999/xlink', 'href'), ).toBe(EXPECTED_SAFE_URL); }, ); it('rejects a javascript protocol href if it is added during an update', () => { const container = document.createElement('div'); ReactDOM.render(<a href="http://thisisfine/">click me</a>, container); expect(container.firstChild.href).toBe('http://thisisfine/'); ReactDOM.render(<a href="javascript:notfine">click me</a>, container); expect(container.firstChild.href).toBe(EXPECTED_SAFE_URL); }); itRenders('only the first invocation of toString', async render => { let expectedToStringCalls = 1; if (render === clientRenderOnBadMarkup) { // It gets called once on the server and once on the client // which happens to share the same object in our test runner. expectedToStringCalls = 2; } if (render === clientRenderOnServerString && __DEV__) { // The hydration validation calls it one extra time. // TODO: It would be good if we only called toString once for // consistency but the code structure makes that hard right now. expectedToStringCalls = 4; } else if (__DEV__) { // Checking for string coercion problems results in double the // toString calls in DEV expectedToStringCalls *= 2; } let toStringCalls = 0; const firstIsSafe = { toString() { // This tries to avoid the validation by pretending to be safe // the first times it is called and then becomes dangerous. toStringCalls++; if (toStringCalls <= expectedToStringCalls) { return 'https://reactjs.org/'; } return 'javascript:notfine'; }, }; const e = await render(<a href={firstIsSafe} />); expect(toStringCalls).toBe(expectedToStringCalls); expect(e.href).toBe('https://reactjs.org/'); }); it('rejects a javascript protocol href if it is added during an update twice', () => { const container = document.createElement('div'); ReactDOM.render(<a href="http://thisisfine/">click me</a>, container); expect(container.firstChild.href).toBe('http://thisisfine/'); ReactDOM.render(<a href="javascript:notfine">click me</a>, container); expect(container.firstChild.href).toBe(EXPECTED_SAFE_URL); // The second update ensures that a global flag hasn't been added to the regex // which would fail to match the second time it is called. ReactDOM.render(<a href="javascript:notfine">click me</a>, container); expect(container.firstChild.href).toBe(EXPECTED_SAFE_URL); }); });
30.84375
99
0.63736
GWT-Penetration-Testing-Toolset
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import styles from './shared.css'; type Props = { callStack: string | null, children: React$Node, info: React$Node | null, componentStack: string | null, errorMessage: string, }; export default function CaughtErrorView({ callStack, children, info, componentStack, errorMessage, }: Props): React.Node { return ( <div className={styles.ErrorBoundary}> {children} <div className={styles.ErrorInfo}> <div className={styles.HeaderRow}> <div className={styles.ErrorHeader}>{errorMessage}</div> </div> {!!info && <div className={styles.InfoBox}>{info}</div>} {!!callStack && ( <div className={styles.ErrorStack}> The error was thrown {callStack.trim()} </div> )} </div> </div> ); }
22.244444
66
0.618182
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 {SchedulingEvent} from '../types'; import prettyMilliseconds from 'pretty-ms'; export function formatTimestamp(ms: number): string { return ( ms.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1, }) + 'ms' ); } export function formatDuration(ms: number): string { return prettyMilliseconds(ms, {millisecondsDecimalDigits: 1}); } export function trimString(string: string, length: number): string { if (string.length > length) { return `${string.slice(0, length - 1)}…`; } return string; } export function getSchedulingEventLabel(event: SchedulingEvent): string | null { switch (event.type) { case 'schedule-render': return 'render scheduled'; case 'schedule-state-update': return 'state update scheduled'; case 'schedule-force-update': return 'force update scheduled'; default: return null; } }
23.478261
80
0.685333
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Request} from 'react-server/src/ReactFizzServer'; export * from 'react-dom-bindings/src/server/ReactFizzConfigDOMLegacy'; export const supportsRequestStorage = false; export const requestStorage: AsyncLocalStorage<Request> = (null: any);
29.466667
71
0.752193
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 { needsStateRestore, restoreStateIfNeeded, } from './ReactDOMControlledComponent'; import { batchedUpdates as batchedUpdatesImpl, discreteUpdates as discreteUpdatesImpl, flushSync as flushSyncImpl, } from 'react-reconciler/src/ReactFiberReconciler'; // Used as a way to call batchedUpdates when we don't have a reference to // the renderer. Such as when we're dispatching events or if third party // libraries need to call batchedUpdates. Eventually, this API will go away when // everything is batched by default. We'll then have a similar API to opt-out of // scheduled work and instead do synchronous work. let isInsideEventHandler = false; function finishEventHandler() { // Here we wait until all updates have propagated, which is important // when using controlled components within layers: // https://github.com/facebook/react/issues/1698 // Then we restore state of any controlled component. const controlledComponentsHavePendingUpdates = needsStateRestore(); if (controlledComponentsHavePendingUpdates) { // If a controlled event was fired, we may need to restore the state of // the DOM node back to the controlled value. This is necessary when React // bails out of the update without touching the DOM. // TODO: Restore state in the microtask, after the discrete updates flush, // instead of early flushing them here. flushSyncImpl(); restoreStateIfNeeded(); } } export function batchedUpdates(fn, a, b) { if (isInsideEventHandler) { // If we are currently inside another batch, we need to wait until it // fully completes before restoring state. return fn(a, b); } isInsideEventHandler = true; try { return batchedUpdatesImpl(fn, a, b); } finally { isInsideEventHandler = false; finishEventHandler(); } } // TODO: Replace with flushSync export function discreteUpdates(fn, a, b, c, d) { return discreteUpdatesImpl(fn, a, b, c, d); }
32.984127
80
0.736916
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'); // Set by `yarn test-fire`. const {disableInputAttributeSyncing} = require('shared/ReactFeatureFlags'); 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); // TODO: Run this in React Fire mode after we figure out the SSR behavior. const desc = disableInputAttributeSyncing ? xdescribe : describe; desc('ReactDOMServerIntegrationCheckbox', () => { beforeEach(() => { resetModules(); }); itRenders('a checkbox that is checked with an onChange', async render => { const e = await render( <input type="checkbox" checked={true} onChange={() => {}} />, ); expect(e.checked).toBe(true); }); itRenders('a checkbox that is checked with readOnly', async render => { const e = await render( <input type="checkbox" checked={true} readOnly={true} />, ); expect(e.checked).toBe(true); }); itRenders( 'a checkbox that is checked and no onChange/readOnly', async render => { // this configuration should raise a dev warning that checked without // onChange or readOnly is a mistake. const e = await render(<input type="checkbox" checked={true} />, 1); expect(e.checked).toBe(true); }, ); itRenders('a checkbox with defaultChecked', async render => { const e = await render(<input type="checkbox" defaultChecked={true} />); expect(e.checked).toBe(true); expect(e.getAttribute('defaultChecked')).toBe(null); }); itRenders('a checkbox checked overriding defaultChecked', async render => { const e = await render( <input type="checkbox" checked={true} defaultChecked={false} readOnly={true} />, 1, ); expect(e.checked).toBe(true); expect(e.getAttribute('defaultChecked')).toBe(null); }); itRenders( 'a checkbox checked overriding defaultChecked no matter the prop order', async render => { const e = await render( <input type="checkbox" defaultChecked={false} checked={true} readOnly={true} />, 1, ); expect(e.checked).toBe(true); expect(e.getAttribute('defaultChecked')).toBe(null); }, ); });
26.861111
93
0.65492
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 {canUseDOM} from 'shared/ExecutionEnvironment'; export const isServerEnvironment = !canUseDOM;
22.692308
66
0.729642
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 { getInstanceFromNode, getFiberCurrentPropsFromNode, } from '../client/ReactDOMComponentTree'; import {restoreControlledState} from 'react-dom-bindings/src/client/ReactDOMComponent'; // Use to restore controlled state after a change event has fired. let restoreTarget = null; let restoreQueue = null; function restoreStateOfTarget(target: Node) { // We perform this translation at the end of the event loop so that we // always receive the correct fiber here const internalInstance = getInstanceFromNode(target); if (!internalInstance) { // Unmounted return; } const stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted. if (stateNode) { const props = getFiberCurrentPropsFromNode(stateNode); restoreControlledState( internalInstance.stateNode, internalInstance.type, props, ); } } export function enqueueStateRestore(target: Node): void { if (restoreTarget) { if (restoreQueue) { restoreQueue.push(target); } else { restoreQueue = [target]; } } else { restoreTarget = target; } } export function needsStateRestore(): boolean { return restoreTarget !== null || restoreQueue !== null; } export function restoreStateIfNeeded() { if (!restoreTarget) { return; } const target = restoreTarget; const queuedTargets = restoreQueue; restoreTarget = null; restoreQueue = null; restoreStateOfTarget(target); if (queuedTargets) { for (let i = 0; i < queuedTargets.length; i++) { restoreStateOfTarget(queuedTargets[i]); } } }
22.906667
87
0.702009
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {DOMEventName} from '../../events/DOMEventNames'; import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {AnyNativeEvent} from '../../events/PluginModuleType'; import type {DispatchQueue} from '../DOMPluginEventSystem'; import type {EventSystemFlags} from '../EventSystemFlags'; import type {ReactSyntheticEvent} from '../ReactSyntheticEventType'; import { SyntheticEvent, SyntheticKeyboardEvent, SyntheticFocusEvent, SyntheticMouseEvent, SyntheticDragEvent, SyntheticTouchEvent, SyntheticAnimationEvent, SyntheticTransitionEvent, SyntheticUIEvent, SyntheticWheelEvent, SyntheticClipboardEvent, SyntheticPointerEvent, } from '../../events/SyntheticEvent'; import { ANIMATION_END, ANIMATION_ITERATION, ANIMATION_START, TRANSITION_END, } from '../DOMEventNames'; import { topLevelEventsToReactNames, registerSimpleEvents, } from '../DOMEventProperties'; import { accumulateSinglePhaseListeners, accumulateEventHandleNonManagedNodeListeners, } from '../DOMPluginEventSystem'; import { IS_EVENT_HANDLE_NON_MANAGED_NODE, IS_CAPTURE_PHASE, } from '../EventSystemFlags'; import getEventCharCode from '../getEventCharCode'; import {enableCreateEventHandleAPI} from 'shared/ReactFeatureFlags'; function extractEvents( dispatchQueue: DispatchQueue, domEventName: DOMEventName, targetInst: null | Fiber, nativeEvent: AnyNativeEvent, nativeEventTarget: null | EventTarget, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, ): void { const reactName = topLevelEventsToReactNames.get(domEventName); if (reactName === undefined) { return; } let SyntheticEventCtor = SyntheticEvent; let reactEventType: string = domEventName; switch (domEventName) { case 'keypress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). // TODO: Fixed in https://bugzilla.mozilla.org/show_bug.cgi?id=968056. Can // probably remove. if (getEventCharCode(((nativeEvent: any): KeyboardEvent)) === 0) { return; } /* falls through */ case 'keydown': case 'keyup': SyntheticEventCtor = SyntheticKeyboardEvent; break; case 'focusin': reactEventType = 'focus'; SyntheticEventCtor = SyntheticFocusEvent; break; case 'focusout': reactEventType = 'blur'; SyntheticEventCtor = SyntheticFocusEvent; break; case 'beforeblur': case 'afterblur': SyntheticEventCtor = SyntheticFocusEvent; break; case 'click': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. // TODO: Fixed in https://phabricator.services.mozilla.com/D26793. Can // probably remove. if (nativeEvent.button === 2) { return; } /* falls through */ case 'auxclick': case 'dblclick': case 'mousedown': case 'mousemove': case 'mouseup': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'mouseout': case 'mouseover': case 'contextmenu': SyntheticEventCtor = SyntheticMouseEvent; break; case 'drag': case 'dragend': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'dragstart': case 'drop': SyntheticEventCtor = SyntheticDragEvent; break; case 'touchcancel': case 'touchend': case 'touchmove': case 'touchstart': SyntheticEventCtor = SyntheticTouchEvent; break; case ANIMATION_END: case ANIMATION_ITERATION: case ANIMATION_START: SyntheticEventCtor = SyntheticAnimationEvent; break; case TRANSITION_END: SyntheticEventCtor = SyntheticTransitionEvent; break; case 'scroll': case 'scrollend': SyntheticEventCtor = SyntheticUIEvent; break; case 'wheel': SyntheticEventCtor = SyntheticWheelEvent; break; case 'copy': case 'cut': case 'paste': SyntheticEventCtor = SyntheticClipboardEvent; break; case 'gotpointercapture': case 'lostpointercapture': case 'pointercancel': case 'pointerdown': case 'pointermove': case 'pointerout': case 'pointerover': case 'pointerup': SyntheticEventCtor = SyntheticPointerEvent; break; default: // Unknown event. This is used by createEventHandle. break; } const inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; if ( enableCreateEventHandleAPI && eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE ) { const listeners = accumulateEventHandleNonManagedNodeListeners( // TODO: this cast may not make sense for events like // "focus" where React listens to e.g. "focusin". ((reactEventType: any): DOMEventName), targetContainer, inCapturePhase, ); if (listeners.length > 0) { // Intentionally create event lazily. const event: ReactSyntheticEvent = new SyntheticEventCtor( reactName, reactEventType, null, nativeEvent, nativeEventTarget, ); dispatchQueue.push({event, listeners}); } } else { // Some events don't bubble in the browser. // In the past, React has always bubbled them, but this can be surprising. // We're going to try aligning closer to the browser behavior by not bubbling // them in React either. We'll start by not bubbling onScroll, and then expand. const accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from // nonDelegatedEvents list in DOMPluginEventSystem. // Then we can remove this special list. // This is a breaking change that can wait until React 18. (domEventName === 'scroll' || domEventName === 'scrollend'); const listeners = accumulateSinglePhaseListeners( targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly, nativeEvent, ); if (listeners.length > 0) { // Intentionally create event lazily. const event: ReactSyntheticEvent = new SyntheticEventCtor( reactName, reactEventType, null, nativeEvent, nativeEventTarget, ); dispatchQueue.push({event, listeners}); } } } export {registerSimpleEvents as registerEvents, extractEvents};
28.701754
83
0.679073
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} from 'shared/ReactTypes'; import * as React from 'react'; import { createContext, startTransition, unstable_useCacheRefresh as useCacheRefresh, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react'; import {TreeStateContext} from './TreeContext'; import {BridgeContext, StoreContext} from '../context'; import { inspectElement, startElementUpdatesPolling, } from 'react-devtools-shared/src/inspectedElementCache'; import { clearHookNamesCache, hasAlreadyLoadedHookNames, loadHookNames, } from 'react-devtools-shared/src/hookNamesCache'; import {loadModule} from 'react-devtools-shared/src/dynamicImportCache'; import FetchFileWithCachingContext from 'react-devtools-shared/src/devtools/views/Components/FetchFileWithCachingContext'; import HookNamesModuleLoaderContext from 'react-devtools-shared/src/devtools/views/Components/HookNamesModuleLoaderContext'; import {SettingsContext} from '../Settings/SettingsContext'; import type {HookNames} from 'react-devtools-shared/src/frontend/types'; import type {ReactNodeList} from 'shared/ReactTypes'; import type { Element, InspectedElement, } from 'react-devtools-shared/src/frontend/types'; type Path = Array<string | number>; type InspectPathFunction = (path: Path) => void; export type ToggleParseHookNames = () => void; type Context = { hookNames: HookNames | null, inspectedElement: InspectedElement | null, inspectPaths: InspectPathFunction, parseHookNames: boolean, toggleParseHookNames: ToggleParseHookNames, }; export const InspectedElementContext: ReactContext<Context> = createContext<Context>(((null: any): Context)); export type Props = { children: ReactNodeList, }; export function InspectedElementContextController({ children, }: Props): React.Node { const {selectedElementID} = useContext(TreeStateContext); const fetchFileWithCaching = useContext(FetchFileWithCachingContext); const bridge = useContext(BridgeContext); const store = useContext(StoreContext); const {parseHookNames: parseHookNamesByDefault} = useContext(SettingsContext); // parseHookNames has a lot of code. // Embedding it into a build makes the build large. // This function enables DevTools to make use of Suspense to lazily import() it only if the feature will be used. // TODO (Webpack 5) Hopefully we can remove this indirection once the Webpack 5 upgrade is completed. const hookNamesModuleLoader = useContext(HookNamesModuleLoaderContext); const refresh = useCacheRefresh(); // Temporarily stores most recently-inspected (hydrated) path. // The transition that updates this causes the component to re-render and ask the cache->backend for the new path. // When a path is sent along with an "inspectElement" request, // the backend knows to send its dehydrated data even if the element hasn't updated since the last request. const [state, setState] = useState<{ element: Element | null, path: Array<number | string> | null, }>({ element: null, path: null, }); const element = selectedElementID !== null ? store.getElementByID(selectedElementID) : null; const alreadyLoadedHookNames = element != null && hasAlreadyLoadedHookNames(element); // Parse the currently inspected element's hook names. // This may be enabled by default (for all elements) // or it may be opted into on a per-element basis (if it's too slow to be on by default). const [parseHookNames, setParseHookNames] = useState<boolean>( parseHookNamesByDefault || alreadyLoadedHookNames, ); const [bridgeIsAlive, setBridgeIsAliveStatus] = useState<boolean>(true); const elementHasChanged = element !== null && element !== state.element; // Reset the cached inspected paths when a new element is selected. if (elementHasChanged) { setState({ element, path: null, }); setParseHookNames(parseHookNamesByDefault || alreadyLoadedHookNames); } const purgeCachedMetadataRef = useRef(null); // Don't load a stale element from the backend; it wastes bridge bandwidth. let hookNames: HookNames | null = null; let inspectedElement = null; if (!elementHasChanged && element !== null) { inspectedElement = inspectElement(element, state.path, store, bridge); if (typeof hookNamesModuleLoader === 'function') { if (parseHookNames || alreadyLoadedHookNames) { const hookNamesModule = loadModule(hookNamesModuleLoader); if (hookNamesModule !== null) { const {parseHookNames: loadHookNamesFunction, purgeCachedMetadata} = hookNamesModule; purgeCachedMetadataRef.current = purgeCachedMetadata; if ( inspectedElement !== null && inspectedElement.hooks !== null && loadHookNamesFunction !== null ) { hookNames = loadHookNames( element, inspectedElement.hooks, loadHookNamesFunction, fetchFileWithCaching, ); } } } } } const toggleParseHookNames: ToggleParseHookNames = useCallback<ToggleParseHookNames>(() => { startTransition(() => { setParseHookNames(value => !value); refresh(); }); }, [setParseHookNames]); const inspectPaths: InspectPathFunction = useCallback<InspectPathFunction>( (path: Path) => { startTransition(() => { setState({ element: state.element, path, }); refresh(); }); }, [setState, state], ); const inspectedElementRef = useRef<null | InspectedElement>(null); useEffect(() => { if ( inspectedElement !== null && inspectedElement.hooks !== null && inspectedElementRef.current !== inspectedElement ) { inspectedElementRef.current = inspectedElement; } }, [inspectedElement]); useEffect(() => { const purgeCachedMetadata = purgeCachedMetadataRef.current; if (typeof purgeCachedMetadata === 'function') { // When Fast Refresh updates a component, any cached AST metadata may be invalid. const fastRefreshScheduled = () => { startTransition(() => { clearHookNamesCache(); purgeCachedMetadata(); refresh(); }); }; bridge.addListener('fastRefreshScheduled', fastRefreshScheduled); return () => bridge.removeListener('fastRefreshScheduled', fastRefreshScheduled); } }, [bridge]); // Reset path now that we've asked the backend to hydrate it. // The backend is stateful, so we don't need to remember this path the next time we inspect. useEffect(() => { if (state.path !== null) { setState({ element: state.element, path: null, }); } }, [state]); useEffect(() => { // Assuming that new bridge is always alive at this moment setBridgeIsAliveStatus(true); const listener = () => setBridgeIsAliveStatus(false); bridge.addListener('shutdown', listener); return () => bridge.removeListener('shutdown', listener); }, [bridge]); // Periodically poll the selected element for updates. useEffect(() => { if (element !== null && bridgeIsAlive) { const {abort, pause, resume} = startElementUpdatesPolling({ bridge, element, refresh, store, }); bridge.addListener('resumeElementPolling', resume); bridge.addListener('pauseElementPolling', pause); return () => { bridge.removeListener('resumeElementPolling', resume); bridge.removeListener('pauseElementPolling', pause); abort(); }; } }, [ element, hookNames, // Reset this timer any time the element we're inspecting gets a new response. // No sense to ping right away after e.g. inspecting/hydrating a path. inspectedElement, state, bridgeIsAlive, ]); const value = useMemo<Context>( () => ({ hookNames, inspectedElement, inspectPaths, parseHookNames, toggleParseHookNames, }), [ hookNames, inspectedElement, inspectPaths, parseHookNames, toggleParseHookNames, ], ); return ( <InspectedElementContext.Provider value={value}> {children} </InspectedElementContext.Provider> ); }
29.648746
124
0.679298
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'; // NOTE: We're explicitly not using JSX in this file. This is intended to test // classic JS without JSX. let PropTypes; let React; let ReactDOM; let ReactTestUtils; let ReactFeatureFlags = require('shared/ReactFeatureFlags'); describe('ReactElementValidator', () => { let ComponentClass; beforeEach(() => { jest.resetModules(); PropTypes = require('prop-types'); ReactFeatureFlags = require('shared/ReactFeatureFlags'); ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false; React = require('react'); ReactDOM = require('react-dom'); ReactTestUtils = require('react-dom/test-utils'); ComponentClass = class extends React.Component { render() { return React.createElement('div'); } }; }); it('warns for keys for arrays of elements in rest args', () => { expect(() => { React.createElement(ComponentClass, null, [ React.createElement(ComponentClass), React.createElement(ComponentClass), ]); }).toErrorDev('Each child in a list should have a unique "key" prop.'); }); it('warns for keys for arrays of elements with owner info', () => { class InnerClass extends React.Component { render() { return React.createElement(ComponentClass, null, this.props.childSet); } } class ComponentWrapper extends React.Component { render() { return React.createElement(InnerClass, { childSet: [ React.createElement(ComponentClass), React.createElement(ComponentClass), ], }); } } expect(() => { ReactTestUtils.renderIntoDocument(React.createElement(ComponentWrapper)); }).toErrorDev( 'Each child in a list should have a unique "key" prop.' + '\n\nCheck the render method of `InnerClass`. ' + 'It was passed a child from ComponentWrapper. ', ); }); it('warns for keys for arrays with no owner or parent info', () => { function Anonymous() { return <div />; } Object.defineProperty(Anonymous, 'name', {value: undefined}); const divs = [<div />, <div />]; expect(() => { ReactTestUtils.renderIntoDocument(<Anonymous>{divs}</Anonymous>); }).toErrorDev( 'Warning: Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for more information.\n' + ' in div (at **)', ); }); it('warns for keys for arrays of elements with no owner info', () => { const divs = [<div />, <div />]; expect(() => { ReactTestUtils.renderIntoDocument(<div>{divs}</div>); }).toErrorDev( 'Warning: Each child in a list should have a unique ' + '"key" prop.\n\nCheck the top-level render call using <div>. See ' + 'https://reactjs.org/link/warning-keys for more information.\n' + ' in div (at **)', ); }); it('warns for keys with component stack info', () => { function Component() { return <div>{[<div />, <div />]}</div>; } function Parent(props) { return React.cloneElement(props.child); } function GrandParent() { return <Parent child={<Component />} />; } expect(() => ReactTestUtils.renderIntoDocument(<GrandParent />)).toErrorDev( 'Warning: Each child in a list should have a unique ' + '"key" prop.\n\nCheck the render method of `Component`. See ' + 'https://reactjs.org/link/warning-keys for more information.\n' + ' in div (at **)\n' + ' in Component (at **)\n' + ' in Parent (at **)\n' + ' in GrandParent (at **)', ); }); it('does not warn for keys when passing children down', () => { function Wrapper(props) { return ( <div> {props.children} <footer /> </div> ); } ReactTestUtils.renderIntoDocument( <Wrapper> <span /> <span /> </Wrapper>, ); }); it('warns for keys for iterables of elements in rest args', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return { value: done ? undefined : React.createElement(ComponentClass), done: done, }; }, }; }, }; expect(() => React.createElement(ComponentClass, null, iterable), ).toErrorDev('Each child in a list should have a unique "key" prop.'); }); it('does not warns for arrays of elements with keys', () => { React.createElement(ComponentClass, null, [ React.createElement(ComponentClass, {key: '#1'}), React.createElement(ComponentClass, {key: '#2'}), ]); }); it('does not warns for iterable elements with keys', () => { const iterable = { '@@iterator': function () { let i = 0; return { next: function () { const done = ++i > 2; return { value: done ? undefined : React.createElement(ComponentClass, {key: '#' + i}), done: done, }; }, }; }, }; React.createElement(ComponentClass, null, iterable); }); it('does not warn when the element is directly in rest args', () => { React.createElement( ComponentClass, null, React.createElement(ComponentClass), React.createElement(ComponentClass), ); }); it('does not warn when the array contains a non-element', () => { React.createElement(ComponentClass, null, [{}, {}]); }); it('should give context for PropType errors in nested components.', () => { // In this test, we're making sure that if a proptype error is found in a // component, we give a small hint as to which parent instantiated that // component as per warnings about key usage in ReactElementValidator. function MyComp(props) { return React.createElement('div', null, 'My color is ' + props.color); } MyComp.propTypes = { color: PropTypes.string, }; function ParentComp() { return React.createElement(MyComp, {color: 123}); } expect(() => { ReactTestUtils.renderIntoDocument(React.createElement(ParentComp)); }).toErrorDev( 'Warning: Failed prop type: ' + 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + 'expected `string`.\n' + ' in MyComp (at **)\n' + ' in ParentComp (at **)', ); }); it('gives a helpful error when passing invalid types', () => { function Foo() {} expect(() => { React.createElement(undefined); React.createElement(null); React.createElement(true); React.createElement({x: 17}); React.createElement({}); React.createElement(React.createElement('div')); React.createElement(React.createElement(Foo)); React.createElement(React.createElement(React.createContext().Consumer)); React.createElement({$$typeof: 'non-react-thing'}); }).toErrorDev( [ 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: undefined. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: boolean.', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: object.', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: object. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: <div />. Did you accidentally export a JSX literal ' + 'instead of a component?', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: <Foo />. Did you accidentally export a JSX literal ' + 'instead of a component?', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: <Context.Consumer />. Did you accidentally ' + 'export a JSX literal instead of a component?', 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: object.', ], {withoutStack: true}, ); // Should not log any additional warnings React.createElement('div'); }); it('includes the owner name when passing null, undefined, boolean, or number', () => { function ParentComp() { return React.createElement(null); } expect(() => { expect(() => { ReactTestUtils.renderIntoDocument(React.createElement(ParentComp)); }).toThrowError( 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: null.' + (__DEV__ ? '\n\nCheck the render method of `ParentComp`.' : ''), ); }).toErrorDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.' + '\n\nCheck the render method of `ParentComp`.\n in ParentComp', ); }); it('should check default prop values', () => { class Component extends React.Component { static propTypes = {prop: PropTypes.string.isRequired}; static defaultProps = {prop: null}; render() { return React.createElement('span', null, this.props.prop); } } expect(() => ReactTestUtils.renderIntoDocument(React.createElement(Component)), ).toErrorDev( 'Warning: Failed prop type: The prop `prop` is marked as required in ' + '`Component`, but its value is `null`.\n' + ' in Component', ); }); it('should not check the default for explicit null', () => { class Component extends React.Component { static propTypes = {prop: PropTypes.string.isRequired}; static defaultProps = {prop: 'text'}; render() { return React.createElement('span', null, this.props.prop); } } expect(() => { ReactTestUtils.renderIntoDocument( React.createElement(Component, {prop: null}), ); }).toErrorDev( 'Warning: Failed prop type: The prop `prop` is marked as required in ' + '`Component`, but its value is `null`.\n' + ' in Component', ); }); it('should check declared prop types', () => { class Component extends React.Component { static propTypes = { prop: PropTypes.string.isRequired, }; render() { return React.createElement('span', null, this.props.prop); } } expect(() => { ReactTestUtils.renderIntoDocument(React.createElement(Component)); ReactTestUtils.renderIntoDocument( React.createElement(Component, {prop: 42}), ); }).toErrorDev([ 'Warning: Failed prop type: ' + 'The prop `prop` is marked as required in `Component`, but its value ' + 'is `undefined`.\n' + ' in Component', 'Warning: Failed prop type: ' + 'Invalid prop `prop` of type `number` supplied to ' + '`Component`, expected `string`.\n' + ' in Component', ]); // Should not error for strings ReactTestUtils.renderIntoDocument( React.createElement(Component, {prop: 'string'}), ); }); it('should warn if a PropType creator is used as a PropType', () => { class Component extends React.Component { static propTypes = { myProp: PropTypes.shape, }; render() { return React.createElement('span', null, this.props.myProp.value); } } expect(() => { ReactTestUtils.renderIntoDocument( React.createElement(Component, {myProp: {value: 'hi'}}), ); }).toErrorDev( 'Warning: Component: type specification of prop `myProp` is invalid; ' + 'the type checker function must return `null` or an `Error` but ' + 'returned a function. You may have forgotten to pass an argument to ' + 'the type checker creator (arrayOf, instanceOf, objectOf, oneOf, ' + 'oneOfType, and shape all require an argument).', ); }); it('should warn if component declares PropTypes instead of propTypes', () => { class MisspelledPropTypesComponent extends React.Component { static PropTypes = { prop: PropTypes.string, }; render() { return React.createElement('span', null, this.props.prop); } } expect(() => { ReactTestUtils.renderIntoDocument( React.createElement(MisspelledPropTypesComponent, {prop: 'Hi'}), ); }).toErrorDev( 'Warning: Component MisspelledPropTypesComponent declared `PropTypes` ' + 'instead of `propTypes`. Did you misspell the property assignment?', {withoutStack: true}, ); }); it('warns for fragments with illegal attributes', () => { class Foo extends React.Component { render() { return React.createElement(React.Fragment, {a: 1}, '123'); } } expect(() => { ReactTestUtils.renderIntoDocument(React.createElement(Foo)); }).toErrorDev( 'Invalid prop `a` supplied to `React.Fragment`. React.Fragment ' + 'can only have `key` and `children` props.', ); }); if (!__EXPERIMENTAL__) { it('should warn when accessing .type on an element factory', () => { function TestComponent() { return <div />; } let TestFactory; expect(() => { TestFactory = React.createFactory(TestComponent); }).toWarnDev( 'Warning: React.createFactory() is deprecated and will be removed in a ' + 'future major release. Consider using JSX or use React.createElement() ' + 'directly instead.', {withoutStack: true}, ); expect(() => TestFactory.type).toWarnDev( 'Warning: Factory.type is deprecated. Access the class directly before ' + 'passing it to createFactory.', {withoutStack: true}, ); // Warn once, not again expect(TestFactory.type).toBe(TestComponent); }); } it('does not warn when using DOM node as children', () => { class DOMContainer extends React.Component { render() { return <div />; } componentDidMount() { ReactDOM.findDOMNode(this).appendChild(this.props.children); } } const node = document.createElement('div'); // This shouldn't cause a stack overflow or any other problems (#3883) ReactTestUtils.renderIntoDocument(<DOMContainer>{node}</DOMContainer>); }); it('should not enumerate enumerable numbers (#4776)', () => { /*eslint-disable no-extend-native */ Number.prototype['@@iterator'] = function () { throw new Error('number iterator called'); }; /*eslint-enable no-extend-native */ try { void ( <div> {5} {12} {13} </div> ); } finally { delete Number.prototype['@@iterator']; } }); it('does not blow up with inlined children', () => { // We don't suggest this since it silences all sorts of warnings, but we // shouldn't blow up either. const child = { $$typeof: (<div />).$$typeof, type: 'span', key: null, ref: null, props: {}, _owner: null, }; void (<div>{[child]}</div>); }); it('does not blow up on key warning with undefined type', () => { const Foo = undefined; expect(() => { void (<Foo>{[<div />]}</Foo>); }).toErrorDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: undefined. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.\n\nCheck your code at **.', {withoutStack: true}, ); }); it('does not call lazy initializers eagerly', () => { let didCall = false; const Lazy = React.lazy(() => { didCall = true; return {then() {}}; }); React.createElement(Lazy); expect(didCall).toBe(false); }); });
31.705882
89
0.592378
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 {FiberRoot} from './ReactInternalTypes'; import type {Lane} from './ReactFiberLane'; import type {PriorityLevel} from 'scheduler/src/SchedulerPriorities'; import {enableDeferRootSchedulingToMicrotask} from 'shared/ReactFeatureFlags'; import { NoLane, NoLanes, SyncLane, getHighestPriorityLane, getNextLanes, includesSyncLane, markStarvedLanesAsExpired, upgradePendingLaneToSync, claimNextTransitionLane, } from './ReactFiberLane'; import { CommitContext, NoContext, RenderContext, getExecutionContext, getWorkInProgressRoot, getWorkInProgressRootRenderLanes, isWorkLoopSuspendedOnData, performConcurrentWorkOnRoot, performSyncWorkOnRoot, } from './ReactFiberWorkLoop'; import {LegacyRoot} from './ReactRootTags'; import { ImmediatePriority as ImmediateSchedulerPriority, UserBlockingPriority as UserBlockingSchedulerPriority, NormalPriority as NormalSchedulerPriority, IdlePriority as IdleSchedulerPriority, cancelCallback as Scheduler_cancelCallback, scheduleCallback as Scheduler_scheduleCallback, now, } from './Scheduler'; import { DiscreteEventPriority, ContinuousEventPriority, DefaultEventPriority, IdleEventPriority, lanesToEventPriority, } from './ReactEventPriorities'; import { supportsMicrotasks, scheduleMicrotask, shouldAttemptEagerTransition, } from './ReactFiberConfig'; import ReactSharedInternals from 'shared/ReactSharedInternals'; const {ReactCurrentActQueue} = ReactSharedInternals; // A linked list of all the roots with pending work. In an idiomatic app, // there's only a single root, but we do support multi root apps, hence this // extra complexity. But this module is optimized for the single root case. let firstScheduledRoot: FiberRoot | null = null; let lastScheduledRoot: FiberRoot | null = null; // Used to prevent redundant mircotasks from being scheduled. let didScheduleMicrotask: boolean = false; // `act` "microtasks" are scheduled on the `act` queue instead of an actual // microtask, so we have to dedupe those separately. This wouldn't be an issue // if we required all `act` calls to be awaited, which we might in the future. let didScheduleMicrotask_act: boolean = false; // Used to quickly bail out of flushSync if there's no sync work to do. let mightHavePendingSyncWork: boolean = false; let isFlushingWork: boolean = false; let currentEventTransitionLane: Lane = NoLane; export function ensureRootIsScheduled(root: FiberRoot): void { // This function is called whenever a root receives an update. It does two // things 1) it ensures the root is in the root schedule, and 2) it ensures // there's a pending microtask to process the root schedule. // // Most of the actual scheduling logic does not happen until // `scheduleTaskForRootDuringMicrotask` runs. // Add the root to the schedule if (root === lastScheduledRoot || root.next !== null) { // Fast path. This root is already scheduled. } else { if (lastScheduledRoot === null) { firstScheduledRoot = lastScheduledRoot = root; } else { lastScheduledRoot.next = root; lastScheduledRoot = root; } } // Any time a root received an update, we set this to true until the next time // we process the schedule. If it's false, then we can quickly exit flushSync // without consulting the schedule. mightHavePendingSyncWork = true; // At the end of the current event, go through each of the roots and ensure // there's a task scheduled for each one at the correct priority. if (__DEV__ && ReactCurrentActQueue.current !== null) { // We're inside an `act` scope. if (!didScheduleMicrotask_act) { didScheduleMicrotask_act = true; scheduleImmediateTask(processRootScheduleInMicrotask); } } else { if (!didScheduleMicrotask) { didScheduleMicrotask = true; scheduleImmediateTask(processRootScheduleInMicrotask); } } if (!enableDeferRootSchedulingToMicrotask) { // While this flag is disabled, we schedule the render task immediately // instead of waiting a microtask. // TODO: We need to land enableDeferRootSchedulingToMicrotask ASAP to // unblock additional features we have planned. scheduleTaskForRootDuringMicrotask(root, now()); } if ( __DEV__ && ReactCurrentActQueue.isBatchingLegacy && root.tag === LegacyRoot ) { // Special `act` case: Record whenever a legacy update is scheduled. ReactCurrentActQueue.didScheduleLegacyUpdate = true; } } export function flushSyncWorkOnAllRoots() { // This is allowed to be called synchronously, but the caller should check // the execution context first. flushSyncWorkAcrossRoots_impl(false); } export function flushSyncWorkOnLegacyRootsOnly() { // This is allowed to be called synchronously, but the caller should check // the execution context first. flushSyncWorkAcrossRoots_impl(true); } function flushSyncWorkAcrossRoots_impl(onlyLegacy: boolean) { if (isFlushingWork) { // Prevent reentrancy. // TODO: Is this overly defensive? The callers must check the execution // context first regardless. return; } if (!mightHavePendingSyncWork) { // Fast path. There's no sync work to do. return; } // There may or may not be synchronous work scheduled. Let's check. let didPerformSomeWork; let errors: Array<mixed> | null = null; isFlushingWork = true; do { didPerformSomeWork = false; let root = firstScheduledRoot; while (root !== null) { if (onlyLegacy && root.tag !== LegacyRoot) { // Skip non-legacy roots. } else { const workInProgressRoot = getWorkInProgressRoot(); const workInProgressRootRenderLanes = getWorkInProgressRootRenderLanes(); const nextLanes = getNextLanes( root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes, ); if (includesSyncLane(nextLanes)) { // This root has pending sync work. Flush it now. try { didPerformSomeWork = true; performSyncWorkOnRoot(root, nextLanes); } catch (error) { // Collect errors so we can rethrow them at the end if (errors === null) { errors = [error]; } else { errors.push(error); } } } } root = root.next; } } while (didPerformSomeWork); isFlushingWork = false; // If any errors were thrown, rethrow them right before exiting. // TODO: Consider returning these to the caller, to allow them to decide // how/when to rethrow. if (errors !== null) { if (errors.length > 1) { if (typeof AggregateError === 'function') { // eslint-disable-next-line no-undef throw new AggregateError(errors); } else { for (let i = 1; i < errors.length; i++) { scheduleImmediateTask(throwError.bind(null, errors[i])); } const firstError = errors[0]; throw firstError; } } else { const error = errors[0]; throw error; } } } function throwError(error: mixed) { throw error; } function processRootScheduleInMicrotask() { // This function is always called inside a microtask. It should never be // called synchronously. didScheduleMicrotask = false; if (__DEV__) { didScheduleMicrotask_act = false; } // We'll recompute this as we iterate through all the roots and schedule them. mightHavePendingSyncWork = false; const currentTime = now(); let prev = null; let root = firstScheduledRoot; while (root !== null) { const next = root.next; if ( currentEventTransitionLane !== NoLane && shouldAttemptEagerTransition() ) { // A transition was scheduled during an event, but we're going to try to // render it synchronously anyway. We do this during a popstate event to // preserve the scroll position of the previous page. upgradePendingLaneToSync(root, currentEventTransitionLane); } const nextLanes = scheduleTaskForRootDuringMicrotask(root, currentTime); if (nextLanes === NoLane) { // This root has no more pending work. Remove it from the schedule. To // guard against subtle reentrancy bugs, this microtask is the only place // we do this β€” you can add roots to the schedule whenever, but you can // only remove them here. // Null this out so we know it's been removed from the schedule. root.next = null; if (prev === null) { // This is the new head of the list firstScheduledRoot = next; } else { prev.next = next; } if (next === null) { // This is the new tail of the list lastScheduledRoot = prev; } } else { // This root still has work. Keep it in the list. prev = root; if (includesSyncLane(nextLanes)) { mightHavePendingSyncWork = true; } } root = next; } currentEventTransitionLane = NoLane; // At the end of the microtask, flush any pending synchronous work. This has // to come at the end, because it does actual rendering work that might throw. flushSyncWorkOnAllRoots(); } function scheduleTaskForRootDuringMicrotask( root: FiberRoot, currentTime: number, ): Lane { // This function is always called inside a microtask, or at the very end of a // rendering task right before we yield to the main thread. It should never be // called synchronously. // // TODO: Unless enableDeferRootSchedulingToMicrotask is off. We need to land // that ASAP to unblock additional features we have planned. // // This function also never performs React work synchronously; it should // only schedule work to be performed later, in a separate task or microtask. // Check if any lanes are being starved by other work. If so, mark them as // expired so we know to work on those next. markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority. const workInProgressRoot = getWorkInProgressRoot(); const workInProgressRootRenderLanes = getWorkInProgressRootRenderLanes(); const nextLanes = getNextLanes( root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes, ); const existingCallbackNode = root.callbackNode; if ( // Check if there's nothing to work on nextLanes === NoLanes || // If this root is currently suspended and waiting for data to resolve, don't // schedule a task to render it. We'll either wait for a ping, or wait to // receive an update. // // Suspended render phase (root === workInProgressRoot && isWorkLoopSuspendedOnData()) || // Suspended commit phase root.cancelPendingCommit !== null ) { // Fast path: There's nothing to work on. if (existingCallbackNode !== null) { cancelCallback(existingCallbackNode); } root.callbackNode = null; root.callbackPriority = NoLane; return NoLane; } // Schedule a new callback in the host environment. if (includesSyncLane(nextLanes)) { // Synchronous work is always flushed at the end of the microtask, so we // don't need to schedule an additional task. if (existingCallbackNode !== null) { cancelCallback(existingCallbackNode); } root.callbackPriority = SyncLane; root.callbackNode = null; return SyncLane; } else { // We use the highest priority lane to represent the priority of the callback. const existingCallbackPriority = root.callbackPriority; const newCallbackPriority = getHighestPriorityLane(nextLanes); if ( newCallbackPriority === existingCallbackPriority && // Special case related to `act`. If the currently scheduled task is a // Scheduler task, rather than an `act` task, cancel it and re-schedule // on the `act` queue. !( __DEV__ && ReactCurrentActQueue.current !== null && existingCallbackNode !== fakeActCallbackNode ) ) { // The priority hasn't changed. We can reuse the existing task. return newCallbackPriority; } else { // Cancel the existing callback. We'll schedule a new one below. cancelCallback(existingCallbackNode); } let schedulerPriorityLevel; switch (lanesToEventPriority(nextLanes)) { case DiscreteEventPriority: schedulerPriorityLevel = ImmediateSchedulerPriority; break; case ContinuousEventPriority: schedulerPriorityLevel = UserBlockingSchedulerPriority; break; case DefaultEventPriority: schedulerPriorityLevel = NormalSchedulerPriority; break; case IdleEventPriority: schedulerPriorityLevel = IdleSchedulerPriority; break; default: schedulerPriorityLevel = NormalSchedulerPriority; break; } const newCallbackNode = scheduleCallback( schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root), ); root.callbackPriority = newCallbackPriority; root.callbackNode = newCallbackNode; return newCallbackPriority; } } export type RenderTaskFn = (didTimeout: boolean) => RenderTaskFn | null; export function getContinuationForRoot( root: FiberRoot, originalCallbackNode: mixed, ): RenderTaskFn | null { // This is called at the end of `performConcurrentWorkOnRoot` to determine // if we need to schedule a continuation task. // // Usually `scheduleTaskForRootDuringMicrotask` only runs inside a microtask; // however, since most of the logic for determining if we need a continuation // versus a new task is the same, we cheat a bit and call it here. This is // only safe to do because we know we're at the end of the browser task. // So although it's not an actual microtask, it might as well be. scheduleTaskForRootDuringMicrotask(root, now()); if (root.callbackNode === originalCallbackNode) { // The task node scheduled for this root is the same one that's // currently executed. Need to return a continuation. return performConcurrentWorkOnRoot.bind(null, root); } return null; } const fakeActCallbackNode = {}; function scheduleCallback( priorityLevel: PriorityLevel, callback: RenderTaskFn, ) { if (__DEV__ && ReactCurrentActQueue.current !== null) { // Special case: We're inside an `act` scope (a testing utility). // Instead of scheduling work in the host environment, add it to a // fake internal queue that's managed by the `act` implementation. ReactCurrentActQueue.current.push(callback); return fakeActCallbackNode; } else { return Scheduler_scheduleCallback(priorityLevel, callback); } } function cancelCallback(callbackNode: mixed) { if (__DEV__ && callbackNode === fakeActCallbackNode) { // Special `act` case: check if this is the fake callback node used by // the `act` implementation. } else if (callbackNode !== null) { Scheduler_cancelCallback(callbackNode); } } function scheduleImmediateTask(cb: () => mixed) { if (__DEV__ && ReactCurrentActQueue.current !== null) { // Special case: Inside an `act` scope, we push microtasks to the fake `act` // callback queue. This is because we currently support calling `act` // without awaiting the result. The plan is to deprecate that, and require // that you always await the result so that the microtasks have a chance to // run. But it hasn't happened yet. ReactCurrentActQueue.current.push(() => { cb(); return null; }); } // TODO: Can we land supportsMicrotasks? Which environments don't support it? // Alternatively, can we move this check to the host config? if (supportsMicrotasks) { scheduleMicrotask(() => { // In Safari, appending an iframe forces microtasks to run. // https://github.com/facebook/react/issues/22459 // We don't support running callbacks in the middle of render // or commit so we need to check against that. const executionContext = getExecutionContext(); if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { // Note that this would still prematurely flush the callbacks // if this happens outside render or commit phase (e.g. in an event). // Intentionally using a macrotask instead of a microtask here. This is // wrong semantically but it prevents an infinite loop. The bug is // Safari's, not ours, so we just do our best to not crash even though // the behavior isn't completely correct. Scheduler_scheduleCallback(ImmediateSchedulerPriority, cb); return; } cb(); }); } else { // If microtasks are not supported, use Scheduler. Scheduler_scheduleCallback(ImmediateSchedulerPriority, cb); } } export function requestTransitionLane(): Lane { // The algorithm for assigning an update to a lane should be stable for all // updates at the same priority within the same event. To do this, the // inputs to the algorithm must be the same. // // The trick we use is to cache the first of each of these inputs within an // event. Then reset the cached values once we can be sure the event is // over. Our heuristic for that is whenever we enter a concurrent work loop. if (currentEventTransitionLane === NoLane) { // All transitions within the same event are assigned the same lane. currentEventTransitionLane = claimNextTransitionLane(); } return currentEventTransitionLane; }
33.842829
82
0.69612
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 act; let PropTypes; let React; let ReactDOMClient; let ReactTestUtils; let createReactClass; describe('create-react-class-integration', () => { beforeEach(() => { jest.resetModules(); ({act} = require('internal-test-utils')); PropTypes = require('prop-types'); React = require('react'); ReactDOMClient = require('react-dom/client'); ReactTestUtils = require('react-dom/test-utils'); createReactClass = require('create-react-class/factory')( React.Component, React.isValidElement, new React.Component().updater, ); }); it('should throw when `render` is not specified', () => { expect(function () { createReactClass({}); }).toThrowError( 'createClass(...): Class specification must implement a `render` method.', ); }); it('should copy prop types onto the Constructor', () => { const propValidator = jest.fn(); const TestComponent = createReactClass({ propTypes: { value: propValidator, }, render: function () { return <div />; }, }); expect(TestComponent.propTypes).toBeDefined(); expect(TestComponent.propTypes.value).toBe(propValidator); }); it('should warn on invalid prop types', () => { expect(() => createReactClass({ displayName: 'Component', propTypes: { prop: null, }, render: function () { return <span>{this.props.prop}</span>; }, }), ).toErrorDev( 'Warning: Component: prop type `prop` is invalid; ' + 'it must be a function, usually from React.PropTypes.', {withoutStack: true}, ); }); it('should warn on invalid context types', () => { expect(() => createReactClass({ displayName: 'Component', contextTypes: { prop: null, }, render: function () { return <span>{this.props.prop}</span>; }, }), ).toErrorDev( 'Warning: Component: context type `prop` is invalid; ' + 'it must be a function, usually from React.PropTypes.', {withoutStack: true}, ); }); it('should throw on invalid child context types', () => { expect(() => createReactClass({ displayName: 'Component', childContextTypes: { prop: null, }, render: function () { return <span>{this.props.prop}</span>; }, }), ).toErrorDev( 'Warning: Component: child context type `prop` is invalid; ' + 'it must be a function, usually from React.PropTypes.', {withoutStack: true}, ); }); it('should warn when misspelling shouldComponentUpdate', () => { expect(() => createReactClass({ componentShouldUpdate: function () { return false; }, render: function () { return <div />; }, }), ).toErrorDev( 'Warning: A component has a method called componentShouldUpdate(). Did you ' + 'mean shouldComponentUpdate()? The name is phrased as a question ' + 'because the function is expected to return a value.', {withoutStack: true}, ); expect(() => createReactClass({ displayName: 'NamedComponent', componentShouldUpdate: function () { return false; }, render: function () { return <div />; }, }), ).toErrorDev( 'Warning: NamedComponent has a method called componentShouldUpdate(). Did you ' + 'mean shouldComponentUpdate()? The name is phrased as a question ' + 'because the function is expected to return a value.', {withoutStack: true}, ); }); it('should warn when misspelling componentWillReceiveProps', () => { expect(() => createReactClass({ componentWillRecieveProps: function () { return false; }, render: function () { return <div />; }, }), ).toErrorDev( 'Warning: A component has a method called componentWillRecieveProps(). Did you ' + 'mean componentWillReceiveProps()?', {withoutStack: true}, ); }); it('should warn when misspelling UNSAFE_componentWillReceiveProps', () => { expect(() => createReactClass({ UNSAFE_componentWillRecieveProps: function () { return false; }, render: function () { return <div />; }, }), ).toErrorDev( 'Warning: A component has a method called UNSAFE_componentWillRecieveProps(). ' + 'Did you mean UNSAFE_componentWillReceiveProps()?', {withoutStack: true}, ); }); it('should throw if a reserved property is in statics', () => { expect(function () { createReactClass({ statics: { getDefaultProps: function () { return { foo: 0, }; }, }, render: function () { return <span />; }, }); }).toThrowError( 'ReactClass: You are attempting to define a reserved property, ' + '`getDefaultProps`, that shouldn\'t be on the "statics" key. Define ' + 'it as an instance property instead; it will still be accessible on ' + 'the constructor.', ); }); // TODO: Consider actually moving these to statics or drop this unit test. xit('should warn when using deprecated non-static spec keys', () => { expect(() => createReactClass({ mixins: [{}], propTypes: { foo: PropTypes.string, }, contextTypes: { foo: PropTypes.string, }, childContextTypes: { foo: PropTypes.string, }, render: function () { return <div />; }, }), ).toErrorDev([ 'createClass(...): `mixins` is now a static property and should ' + 'be defined inside "statics".', 'createClass(...): `propTypes` is now a static property and should ' + 'be defined inside "statics".', 'createClass(...): `contextTypes` is now a static property and ' + 'should be defined inside "statics".', 'createClass(...): `childContextTypes` is now a static property and ' + 'should be defined inside "statics".', ]); }); it('should support statics', () => { const Component = createReactClass({ statics: { abc: 'def', def: 0, ghi: null, jkl: 'mno', pqr: function () { return this; }, }, render: function () { return <span />; }, }); let instance = <Component />; instance = ReactTestUtils.renderIntoDocument(instance); expect(instance.constructor.abc).toBe('def'); expect(Component.abc).toBe('def'); expect(instance.constructor.def).toBe(0); expect(Component.def).toBe(0); expect(instance.constructor.ghi).toBe(null); expect(Component.ghi).toBe(null); expect(instance.constructor.jkl).toBe('mno'); expect(Component.jkl).toBe('mno'); expect(instance.constructor.pqr()).toBe(Component); expect(Component.pqr()).toBe(Component); }); it('should work with object getInitialState() return values', () => { const Component = createReactClass({ getInitialState: function () { return { occupation: 'clown', }; }, render: function () { return <span />; }, }); let instance = <Component />; instance = ReactTestUtils.renderIntoDocument(instance); expect(instance.state.occupation).toEqual('clown'); }); it('should work with getDerivedStateFromProps() return values', () => { const Component = createReactClass({ getInitialState() { return {}; }, render: function () { return <span />; }, }); Component.getDerivedStateFromProps = () => { return {occupation: 'clown'}; }; let instance = <Component />; instance = ReactTestUtils.renderIntoDocument(instance); expect(instance.state.occupation).toEqual('clown'); }); // @gate !disableLegacyContext it('renders based on context getInitialState', async () => { const Foo = createReactClass({ contextTypes: { className: PropTypes.string, }, getInitialState() { return {className: this.context.className}; }, render() { return <span className={this.state.className} />; }, }); const Outer = createReactClass({ childContextTypes: { className: PropTypes.string, }, getChildContext() { return {className: 'foo'}; }, render() { return <Foo />; }, }); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render(<Outer />); }); expect(container.firstChild.className).toBe('foo'); }); it('should throw with non-object getInitialState() return values', () => { [['an array'], 'a string', 1234].forEach(function (state) { const Component = createReactClass({ getInitialState: function () { return state; }, render: function () { return <span />; }, }); let instance = <Component />; expect(function () { instance = ReactTestUtils.renderIntoDocument(instance); }).toThrowError( 'Component.getInitialState(): must return an object or null', ); }); }); it('should work with a null getInitialState() return value', () => { const Component = createReactClass({ getInitialState: function () { return null; }, render: function () { return <span />; }, }); expect(() => ReactTestUtils.renderIntoDocument(<Component />), ).not.toThrow(); }); it('should throw when using legacy factories', () => { const Component = createReactClass({ render() { return <div />; }, }); expect(() => expect(() => Component()).toThrow()).toErrorDev( 'Warning: Something is calling a React component directly. Use a ' + 'factory or JSX instead. See: https://fb.me/react-legacyfactory', {withoutStack: true}, ); }); it('replaceState and callback works', () => { const ops = []; const Component = createReactClass({ getInitialState() { return {step: 0}; }, render() { ops.push('Render: ' + this.state.step); return <div />; }, }); const instance = ReactTestUtils.renderIntoDocument(<Component />); instance.replaceState({step: 1}, () => { ops.push('Callback: ' + instance.state.step); }); expect(ops).toEqual(['Render: 0', 'Render: 1', 'Callback: 1']); }); it('getDerivedStateFromProps updates state when props change', async () => { const Component = createReactClass({ getInitialState() { return { count: 1, }; }, render() { return <div>count:{this.state.count}</div>; }, }); Component.getDerivedStateFromProps = (nextProps, prevState) => ({ count: prevState.count + nextProps.incrementBy, }); const container = document.createElement('div'); const root = ReactDOMClient.createRoot(container); await act(() => { root.render( <div> <Component incrementBy={0} /> </div>, ); }); expect(container.firstChild.textContent).toEqual('count:1'); await act(() => { root.render( <div> <Component incrementBy={2} /> </div>, ); }); expect(container.firstChild.textContent).toEqual('count:3'); }); it('should support the new static getDerivedStateFromProps method', async () => { let instance; const Component = createReactClass({ statics: { getDerivedStateFromProps: function () { return {foo: 'bar'}; }, }, getInitialState() { return {}; }, render: function () { instance = this; return null; }, }); const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Component />); }); expect(instance.state.foo).toBe('bar'); }); it('warns if getDerivedStateFromProps is not static', async () => { const Foo = createReactClass({ displayName: 'Foo', getDerivedStateFromProps() { return {}; }, render() { return <div />; }, }); await expect(async () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Foo foo="foo" />); }); }).toErrorDev( 'Foo: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', ); }); it('warns if getDerivedStateFromError is not static', async () => { const Foo = createReactClass({ displayName: 'Foo', getDerivedStateFromError() { return {}; }, render() { return <div />; }, }); await expect(async () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Foo foo="foo" />); }); }).toErrorDev( 'Foo: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', ); }); it('warns if getSnapshotBeforeUpdate is static', async () => { const Foo = createReactClass({ displayName: 'Foo', statics: { getSnapshotBeforeUpdate: function () { return null; }, }, render() { return <div />; }, }); await expect(async () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Foo foo="foo" />); }); }).toErrorDev( 'Foo: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', ); }); it('should warn if state is not properly initialized before getDerivedStateFromProps', async () => { const Component = createReactClass({ displayName: 'Component', statics: { getDerivedStateFromProps: function () { return null; }, }, render: function () { return null; }, }); await expect(async () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Component />); }); }).toErrorDev( '`Component` uses `getDerivedStateFromProps` but its initial state is ' + 'null. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `Component`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', ); }); it('should not invoke deprecated lifecycles (cWM/cWRP/cWU) if new static gDSFP is present', async () => { const Component = createReactClass({ statics: { getDerivedStateFromProps: function () { return null; }, }, componentWillMount: function () { throw Error('unexpected'); }, componentWillReceiveProps: function () { throw Error('unexpected'); }, componentWillUpdate: function () { throw Error('unexpected'); }, getInitialState: function () { return {}; }, render: function () { return null; }, }); await expect(async () => { await expect(async () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Component />); }); }).toErrorDev( 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + 'Component uses getDerivedStateFromProps() but also contains the following legacy lifecycles:\n' + ' componentWillMount\n' + ' componentWillReceiveProps\n' + ' componentWillUpdate\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', ); }).toWarnDev( [ 'componentWillMount has been renamed', 'componentWillReceiveProps has been renamed', 'componentWillUpdate has been renamed', ], {withoutStack: true}, ); const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Component foo={1} />); }); }); it('should not invoke deprecated lifecycles (cWM/cWRP/cWU) if new getSnapshotBeforeUpdate is present', async () => { const Component = createReactClass({ getSnapshotBeforeUpdate: function () { return null; }, componentWillMount: function () { throw Error('unexpected'); }, componentWillReceiveProps: function () { throw Error('unexpected'); }, componentWillUpdate: function () { throw Error('unexpected'); }, componentDidUpdate: function () {}, render: function () { return null; }, }); await expect(async () => { await expect(async () => { const root = ReactDOMClient.createRoot(document.createElement('div')); await act(() => { root.render(<Component />); }); }).toErrorDev( 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + 'Component uses getSnapshotBeforeUpdate() but also contains the following legacy lifecycles:\n' + ' componentWillMount\n' + ' componentWillReceiveProps\n' + ' componentWillUpdate\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', ); }).toWarnDev( [ 'componentWillMount has been renamed', 'componentWillReceiveProps has been renamed', 'componentWillUpdate has been renamed', ], {withoutStack: true}, ); await act(() => { const root2 = ReactDOMClient.createRoot(document.createElement('div')); root2.render(<Component foo={1} />); }); }); it('should invoke both deprecated and new lifecycles if both are present', async () => { const log = []; const Component = createReactClass({ mixins: [ { componentWillMount: function () { log.push('componentWillMount'); }, componentWillReceiveProps: function () { log.push('componentWillReceiveProps'); }, componentWillUpdate: function () { log.push('componentWillUpdate'); }, }, ], UNSAFE_componentWillMount: function () { log.push('UNSAFE_componentWillMount'); }, UNSAFE_componentWillReceiveProps: function () { log.push('UNSAFE_componentWillReceiveProps'); }, UNSAFE_componentWillUpdate: function () { log.push('UNSAFE_componentWillUpdate'); }, render: function () { return null; }, }); const root = ReactDOMClient.createRoot(document.createElement('div')); await expect(async () => { await act(() => { root.render(<Component foo="bar" />); }); }).toWarnDev( [ 'componentWillMount has been renamed', 'componentWillReceiveProps has been renamed', 'componentWillUpdate has been renamed', ], {withoutStack: true}, ); expect(log).toEqual(['componentWillMount', 'UNSAFE_componentWillMount']); log.length = 0; await act(() => { root.render(<Component foo="baz" />); }); expect(log).toEqual([ 'componentWillReceiveProps', 'UNSAFE_componentWillReceiveProps', 'componentWillUpdate', 'UNSAFE_componentWillUpdate', ]); }); it('isMounted works', async () => { const ops = []; let instance; const Component = createReactClass({ displayName: 'MyComponent', mixins: [ { UNSAFE_componentWillMount() { this.log('mixin.componentWillMount'); }, componentDidMount() { this.log('mixin.componentDidMount'); }, UNSAFE_componentWillUpdate() { this.log('mixin.componentWillUpdate'); }, componentDidUpdate() { this.log('mixin.componentDidUpdate'); }, componentWillUnmount() { this.log('mixin.componentWillUnmount'); }, }, ], log(name) { ops.push(`${name}: ${this.isMounted()}`); }, getInitialState() { this.log('getInitialState'); return {}; }, UNSAFE_componentWillMount() { this.log('componentWillMount'); }, componentDidMount() { this.log('componentDidMount'); }, UNSAFE_componentWillUpdate() { this.log('componentWillUpdate'); }, componentDidUpdate() { this.log('componentDidUpdate'); }, componentWillUnmount() { this.log('componentWillUnmount'); }, render() { instance = this; this.log('render'); return <div />; }, }); const root = ReactDOMClient.createRoot(document.createElement('div')); await expect(async () => { await act(() => { root.render(<Component />); }); }).toErrorDev( 'Warning: MyComponent: isMounted is deprecated. Instead, make sure to ' + 'clean up subscriptions and pending requests in componentWillUnmount ' + 'to prevent memory leaks.', {withoutStack: true}, ); // Dedupe await act(() => { root.render(<Component />); }); await act(() => { root.unmount(); }); instance.log('after unmount'); expect(ops).toEqual([ 'getInitialState: false', 'mixin.componentWillMount: false', 'componentWillMount: false', 'render: false', 'mixin.componentDidMount: true', 'componentDidMount: true', 'mixin.componentWillUpdate: true', 'componentWillUpdate: true', 'render: true', 'mixin.componentDidUpdate: true', 'componentDidUpdate: true', 'mixin.componentWillUnmount: true', 'componentWillUnmount: true', 'after unmount: false', ]); }); });
27.648817
118
0.56651
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 {enableTaint, enableBinaryFlight} from 'shared/ReactFeatureFlags'; import getPrototypeOf from 'shared/getPrototypeOf'; import binaryToComparableString from 'shared/binaryToComparableString'; import ReactServerSharedInternals from './ReactServerSharedInternals'; const { TaintRegistryObjects, TaintRegistryValues, TaintRegistryByteLengths, TaintRegistryPendingRequests, } = ReactServerSharedInternals; interface Reference {} // This is the shared constructor of all typed arrays. const TypedArrayConstructor = getPrototypeOf(Uint32Array.prototype).constructor; const defaultMessage = 'A tainted value was attempted to be serialized to a Client Component or Action closure. ' + 'This would leak it to the client.'; function cleanup(entryValue: string | bigint): void { const entry = TaintRegistryValues.get(entryValue); if (entry !== undefined) { TaintRegistryPendingRequests.forEach(function (requestQueue) { requestQueue.push(entryValue); entry.count++; }); if (entry.count === 1) { TaintRegistryValues.delete(entryValue); } else { entry.count--; } } } // If FinalizationRegistry doesn't exist, we assume that objects life forever. // E.g. the whole VM is just the lifetime of a request. const finalizationRegistry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(cleanup) : null; export function taintUniqueValue( message: ?string, lifetime: Reference, value: string | bigint | $ArrayBufferView, ): void { if (!enableTaint) { throw new Error('Not implemented.'); } // eslint-disable-next-line react-internal/safe-string-coercion message = '' + (message || defaultMessage); if ( lifetime === null || (typeof lifetime !== 'object' && typeof lifetime !== 'function') ) { throw new Error( 'To taint a value, a lifetime must be defined by passing an object that holds ' + 'the value.', ); } let entryValue: string | bigint; if (typeof value === 'string' || typeof value === 'bigint') { // Use as is. entryValue = value; } else if ( enableBinaryFlight && (value instanceof TypedArrayConstructor || value instanceof DataView) ) { // For now, we just convert binary data to a string so that we can just use the native // hashing in the Map implementation. It doesn't really matter what form the string // take as long as it's the same when we look it up. // We're not too worried about collisions since this should be a high entropy value. TaintRegistryByteLengths.add(value.byteLength); entryValue = binaryToComparableString(value); } else { const kind = value === null ? 'null' : typeof value; if (kind === 'object' || kind === 'function') { throw new Error( 'taintUniqueValue cannot taint objects or functions. Try taintObjectReference instead.', ); } throw new Error( 'Cannot taint a ' + kind + ' because the value is too general and not unique enough to block globally.', ); } const existingEntry = TaintRegistryValues.get(entryValue); if (existingEntry === undefined) { TaintRegistryValues.set(entryValue, { message, count: 1, }); } else { existingEntry.count++; } if (finalizationRegistry !== null) { finalizationRegistry.register(lifetime, entryValue); } } export function taintObjectReference( message: ?string, object: Reference, ): void { if (!enableTaint) { throw new Error('Not implemented.'); } // eslint-disable-next-line react-internal/safe-string-coercion message = '' + (message || defaultMessage); if (typeof object === 'string' || typeof object === 'bigint') { throw new Error( 'Only objects or functions can be passed to taintObjectReference. Try taintUniqueValue instead.', ); } if ( object === null || (typeof object !== 'object' && typeof object !== 'function') ) { throw new Error( 'Only objects or functions can be passed to taintObjectReference.', ); } TaintRegistryObjects.set(object, message); }
29.985612
103
0.684162
owtf
import React, {Component} from 'react'; import Theme from './Theme'; import Suspend from './Suspend'; import './Page.css'; const autofocusedInputs = [ <input key="0" autoFocus placeholder="Has auto focus" />, <input key="1" autoFocus placeholder="Has auto focus" />, ]; export default class Page extends Component { state = {active: false}; handleClick = e => { this.setState({active: true}); }; render() { const link = ( <a className="link" onClick={this.handleClick}> Click Here </a> ); return ( <div className={this.context + '-box'}> <Suspend> <p suppressHydrationWarning={true}> A random number: {Math.random()} </p> <p>Autofocus on page load: {autofocusedInputs}</p> <p>{!this.state.active ? link : 'Thanks!'}</p> {this.state.active && <p>Autofocus on update: {autofocusedInputs}</p>} </Suspend> </div> ); } } Page.contextType = Theme;
24.410256
80
0.582828
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 */ // Helpers to patch console.logs to avoid logging during side-effect free // replaying on render function. This currently only patches the object // lazily which won't cover if the log function was extracted eagerly. // We could also eagerly patch the method. let disabledDepth = 0; let prevLog; let prevInfo; let prevWarn; let prevError; let prevGroup; let prevGroupCollapsed; let prevGroupEnd; function disabledLog() {} disabledLog.__reactDisabledLog = true; export function disableLogs(): void { if (__DEV__) { if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 const props = { configurable: true, enumerable: true, value: disabledLog, writable: true, }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props, }); /* eslint-enable react-internal/no-production-logging */ } disabledDepth++; } } export function reenableLogs(): void { if (__DEV__) { disabledDepth--; if (disabledDepth === 0) { /* eslint-disable react-internal/no-production-logging */ const props = { configurable: true, enumerable: true, writable: true, }; // $FlowFixMe[cannot-write] Flow thinks console is immutable. Object.defineProperties(console, { log: {...props, value: prevLog}, info: {...props, value: prevInfo}, warn: {...props, value: prevWarn}, error: {...props, value: prevError}, group: {...props, value: prevGroup}, groupCollapsed: {...props, value: prevGroupCollapsed}, groupEnd: {...props, value: prevGroupEnd}, }); /* eslint-enable react-internal/no-production-logging */ } if (disabledDepth < 0) { console.error( 'disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.', ); } } }
27.692308
73
0.62567
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const countState = (0, _react.useState)(0); const count = countState[0]; const setCount = countState[1]; const darkMode = useIsDarkMode(); const [isDarkMode] = darkMode; (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 29, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 30, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const darkModeState = (0, _react.useState)(false); const [isDarkMode] = darkModeState; (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return [isDarkMode, () => {}]; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5LmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50U3RhdGUiLCJjb3VudCIsInNldENvdW50IiwiZGFya01vZGUiLCJ1c2VJc0RhcmtNb2RlIiwiaXNEYXJrTW9kZSIsImhhbmRsZUNsaWNrIiwiZGFya01vZGVTdGF0ZSIsInVzZUVmZmVjdENyZWF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsVUFBVSxHQUFHLHFCQUFTLENBQVQsQ0FBbkI7QUFDQSxRQUFNQyxLQUFLLEdBQUdELFVBQVUsQ0FBQyxDQUFELENBQXhCO0FBQ0EsUUFBTUUsUUFBUSxHQUFHRixVQUFVLENBQUMsQ0FBRCxDQUEzQjtBQUVBLFFBQU1HLFFBQVEsR0FBR0MsYUFBYSxFQUE5QjtBQUNBLFFBQU0sQ0FBQ0MsVUFBRCxJQUFlRixRQUFyQjtBQUVBLHdCQUFVLE1BQU0sQ0FDZDtBQUNELEdBRkQsRUFFRyxFQUZIOztBQUlBLFFBQU1HLFdBQVcsR0FBRyxNQUFNSixRQUFRLENBQUNELEtBQUssR0FBRyxDQUFULENBQWxDOztBQUVBLHNCQUNFLHlFQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLG9CQUFpQkksVUFBakIsQ0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUFhSixLQUFiLENBRkYsZUFHRTtBQUFRLElBQUEsT0FBTyxFQUFFSyxXQUFqQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFIRixDQURGO0FBT0Q7O0FBRUQsU0FBU0YsYUFBVCxHQUF5QjtBQUN2QixRQUFNRyxhQUFhLEdBQUcscUJBQVMsS0FBVCxDQUF0QjtBQUNBLFFBQU0sQ0FBQ0YsVUFBRCxJQUFlRSxhQUFyQjtBQUVBLHdCQUFVLFNBQVNDLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU8sQ0FBQ0gsVUFBRCxFQUFhLE1BQU0sQ0FBRSxDQUFyQixDQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlRWZmZWN0LCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBjb3VudFN0YXRlID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGNvdW50ID0gY291bnRTdGF0ZVswXTtcbiAgY29uc3Qgc2V0Q291bnQgPSBjb3VudFN0YXRlWzFdO1xuXG4gIGNvbnN0IGRhcmtNb2RlID0gdXNlSXNEYXJrTW9kZSgpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZTtcblxuICB1c2VFZmZlY3QoKCkgPT4ge1xuICAgIC8vIC4uLlxuICB9LCBbXSk7XG5cbiAgY29uc3QgaGFuZGxlQ2xpY2sgPSAoKSA9PiBzZXRDb3VudChjb3VudCArIDEpO1xuXG4gIHJldHVybiAoXG4gICAgPD5cbiAgICAgIDxkaXY+RGFyayBtb2RlPyB7aXNEYXJrTW9kZX08L2Rpdj5cbiAgICAgIDxkaXY+Q291bnQ6IHtjb3VudH08L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBkYXJrTW9kZVN0YXRlID0gdXNlU3RhdGUoZmFsc2UpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZVN0YXRlO1xuXG4gIHVzZUVmZmVjdChmdW5jdGlvbiB1c2VFZmZlY3RDcmVhdGUoKSB7XG4gICAgLy8gSGVyZSBpcyB3aGVyZSB3ZSBtYXkgbGlzdGVuIHRvIGEgXCJ0aGVtZVwiIGV2ZW50Li4uXG4gIH0sIFtdKTtcblxuICByZXR1cm4gW2lzRGFya01vZGUsICgpID0+IHt9XTtcbn1cbiJdfQ==
88.857143
2,700
0.832638
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export function addEventBubbleListener( target: EventTarget, eventType: string, listener: Function, ): Function { target.addEventListener(eventType, listener, false); return listener; } export function addEventCaptureListener( target: EventTarget, eventType: string, listener: Function, ): Function { target.addEventListener(eventType, listener, true); return listener; } export function addEventCaptureListenerWithPassiveFlag( target: EventTarget, eventType: string, listener: Function, passive: boolean, ): Function { target.addEventListener(eventType, listener, { capture: true, passive, }); return listener; } export function addEventBubbleListenerWithPassiveFlag( target: EventTarget, eventType: string, listener: Function, passive: boolean, ): Function { target.addEventListener(eventType, listener, { passive, }); return listener; } export function removeEventListener( target: EventTarget, eventType: string, listener: Function, capture: boolean, ): void { target.removeEventListener(eventType, listener, capture); }
20.377049
66
0.738296
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const countState = (0, _react.useState)(0); const count = countState[0]; const setCount = countState[1]; const darkMode = useIsDarkMode(); const [isDarkMode] = darkMode; (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 29, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 30, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const darkModeState = (0, _react.useState)(false); const [isDarkMode] = darkModeState; (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return [isDarkMode, () => {}]; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFVzaW5nSG9va3NJbmRpcmVjdGx5LmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsImNvdW50U3RhdGUiLCJjb3VudCIsInNldENvdW50IiwiZGFya01vZGUiLCJ1c2VJc0RhcmtNb2RlIiwiaXNEYXJrTW9kZSIsImhhbmRsZUNsaWNrIiwiZGFya01vZGVTdGF0ZSIsInVzZUVmZmVjdENyZWF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQVNBOzs7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsVUFBVSxHQUFHLHFCQUFTLENBQVQsQ0FBbkI7QUFDQSxRQUFNQyxLQUFLLEdBQUdELFVBQVUsQ0FBQyxDQUFELENBQXhCO0FBQ0EsUUFBTUUsUUFBUSxHQUFHRixVQUFVLENBQUMsQ0FBRCxDQUEzQjtBQUVBLFFBQU1HLFFBQVEsR0FBR0MsYUFBYSxFQUE5QjtBQUNBLFFBQU0sQ0FBQ0MsVUFBRCxJQUFlRixRQUFyQjtBQUVBLHdCQUFVLE1BQU0sQ0FDZDtBQUNELEdBRkQsRUFFRyxFQUZIOztBQUlBLFFBQU1HLFdBQVcsR0FBRyxNQUFNSixRQUFRLENBQUNELEtBQUssR0FBRyxDQUFULENBQWxDOztBQUVBLHNCQUNFLHlFQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLG9CQUFpQkksVUFBakIsQ0FERixlQUVFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGdCQUFhSixLQUFiLENBRkYsZUFHRTtBQUFRLElBQUEsT0FBTyxFQUFFSyxXQUFqQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxvQkFIRixDQURGO0FBT0Q7O0FBRUQsU0FBU0YsYUFBVCxHQUF5QjtBQUN2QixRQUFNRyxhQUFhLEdBQUcscUJBQVMsS0FBVCxDQUF0QjtBQUNBLFFBQU0sQ0FBQ0YsVUFBRCxJQUFlRSxhQUFyQjtBQUVBLHdCQUFVLFNBQVNDLGVBQVQsR0FBMkIsQ0FDbkM7QUFDRCxHQUZELEVBRUcsRUFGSDtBQUlBLFNBQU8sQ0FBQ0gsVUFBRCxFQUFhLE1BQU0sQ0FBRSxDQUFyQixDQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IFJlYWN0LCB7dXNlRWZmZWN0LCB1c2VTdGF0ZX0gZnJvbSAncmVhY3QnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCBjb3VudFN0YXRlID0gdXNlU3RhdGUoMCk7XG4gIGNvbnN0IGNvdW50ID0gY291bnRTdGF0ZVswXTtcbiAgY29uc3Qgc2V0Q291bnQgPSBjb3VudFN0YXRlWzFdO1xuXG4gIGNvbnN0IGRhcmtNb2RlID0gdXNlSXNEYXJrTW9kZSgpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZTtcblxuICB1c2VFZmZlY3QoKCkgPT4ge1xuICAgIC8vIC4uLlxuICB9LCBbXSk7XG5cbiAgY29uc3QgaGFuZGxlQ2xpY2sgPSAoKSA9PiBzZXRDb3VudChjb3VudCArIDEpO1xuXG4gIHJldHVybiAoXG4gICAgPD5cbiAgICAgIDxkaXY+RGFyayBtb2RlPyB7aXNEYXJrTW9kZX08L2Rpdj5cbiAgICAgIDxkaXY+Q291bnQ6IHtjb3VudH08L2Rpdj5cbiAgICAgIDxidXR0b24gb25DbGljaz17aGFuZGxlQ2xpY2t9PlVwZGF0ZSBjb3VudDwvYnV0dG9uPlxuICAgIDwvPlxuICApO1xufVxuXG5mdW5jdGlvbiB1c2VJc0RhcmtNb2RlKCkge1xuICBjb25zdCBkYXJrTW9kZVN0YXRlID0gdXNlU3RhdGUoZmFsc2UpO1xuICBjb25zdCBbaXNEYXJrTW9kZV0gPSBkYXJrTW9kZVN0YXRlO1xuXG4gIHVzZUVmZmVjdChmdW5jdGlvbiB1c2VFZmZlY3RDcmVhdGUoKSB7XG4gICAgLy8gSGVyZSBpcyB3aGVyZSB3ZSBtYXkgbGlzdGVuIHRvIGEgXCJ0aGVtZVwiIGV2ZW50Li4uXG4gIH0sIFtdKTtcblxuICByZXR1cm4gW2lzRGFya01vZGUsICgpID0+IHt9XTtcbn1cbiJdfX1dfQ==
90.428571
2,788
0.835515
Ethical-Hacking-Scripts
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import { createContext, forwardRef, lazy, memo, Component, Fragment, Profiler, StrictMode, Suspense, unstable_Cache as Cache, } from 'react'; const Context = createContext('abc'); Context.displayName = 'ExampleContext'; class ClassComponent extends Component<any> { render(): null { return null; } } function FunctionComponent() { return null; } const MemoFunctionComponent = memo(FunctionComponent); const ForwardRefComponentWithAnonymousFunction = forwardRef((props, ref) => ( <ClassComponent ref={ref} {...props} /> )); const ForwardRefComponent = forwardRef(function NamedInnerFunction(props, ref) { return <ClassComponent ref={ref} {...props} />; }); const ForwardRefComponentWithCustomDisplayName = forwardRef((props, ref) => ( <ClassComponent ref={ref} {...props} /> )); ForwardRefComponentWithCustomDisplayName.displayName = 'Custom'; const LazyComponent = lazy(() => Promise.resolve({ default: FunctionComponent, }), ); export default function ElementTypes(): React.Node { return ( <Profiler id="test" onRender={() => {}}> <Fragment> <Context.Provider value={'def'}> <Context.Consumer>{(value: $FlowFixMe) => null}</Context.Consumer> </Context.Provider> <StrictMode> <Cache> <Suspense fallback={<div>Loading...</div>}> <ClassComponent /> <FunctionComponent /> <MemoFunctionComponent /> <ForwardRefComponent /> <ForwardRefComponentWithAnonymousFunction /> <ForwardRefComponentWithCustomDisplayName /> <LazyComponent /> </Suspense> </Cache> </StrictMode> </Fragment> </Profiler> ); }
23.8375
80
0.64149
Penetration-Testing-Study-Notes
export * from './ReactInternalTestUtils';
20.5
41
0.761905
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. * * @flow */ export * from '../ReactServerStreamConfigBun';
21.909091
66
0.701195
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 */ /* eslint-disable no-for-of-loops/no-for-of-loops */ 'use strict'; let Scheduler; let runtime; let performance; let cancelCallback; let scheduleCallback; let NormalPriority; let UserBlockingPriority; // The Scheduler implementation uses browser APIs like `MessageChannel` and // `setTimeout` to schedule work on the main thread. Most of our tests treat // these as implementation details; however, the sequence and timing of these // APIs are not precisely specified, and can vary across browsers. // // To prevent regressions, we need the ability to simulate specific edge cases // that we may encounter in various browsers. // // This test suite mocks all browser methods used in our implementation. It // assumes as little as possible about the order and timing of events. describe('SchedulerDOMSetImmediate', () => { beforeEach(() => { jest.resetModules(); runtime = installMockBrowserRuntime(); jest.unmock('scheduler'); performance = global.performance; Scheduler = require('scheduler'); cancelCallback = Scheduler.unstable_cancelCallback; scheduleCallback = Scheduler.unstable_scheduleCallback; NormalPriority = Scheduler.unstable_NormalPriority; UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; }); afterEach(() => { delete global.performance; if (!runtime.isLogEmpty()) { throw Error('Test exited without clearing log.'); } }); function installMockBrowserRuntime() { let timerIDCounter = 0; // let timerIDs = new Map(); let eventLog = []; let currentTime = 0; global.performance = { now() { return currentTime; }, }; global.setTimeout = (cb, delay) => { const id = timerIDCounter++; log(`Set Timer`); return id; }; global.clearTimeout = id => { // TODO }; // Unused: we expect setImmediate to be preferred. global.MessageChannel = function () { return { port1: {}, port2: { postMessage() { throw Error('Should be unused'); }, }, }; }; let pendingSetImmediateCallback = null; global.setImmediate = function (cb) { if (pendingSetImmediateCallback) { throw Error('Message event already scheduled'); } log('Set Immediate'); pendingSetImmediateCallback = cb; }; function ensureLogIsEmpty() { if (eventLog.length !== 0) { throw Error('Log is not empty. Call assertLog before continuing.'); } } function advanceTime(ms) { currentTime += ms; } function fireSetImmediate() { ensureLogIsEmpty(); if (!pendingSetImmediateCallback) { throw Error('No setImmediate was scheduled'); } const cb = pendingSetImmediateCallback; pendingSetImmediateCallback = null; log('setImmediate Callback'); cb(); } function log(val) { eventLog.push(val); } function isLogEmpty() { return eventLog.length === 0; } function assertLog(expected) { const actual = eventLog; eventLog = []; expect(actual).toEqual(expected); } return { advanceTime, fireSetImmediate, log, isLogEmpty, assertLog, }; } it('does not use setImmediate override', () => { global.setImmediate = () => { throw new Error('Should not throw'); }; scheduleCallback(NormalPriority, () => { runtime.log('Task'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'Task']); }); it('task that finishes before deadline', () => { scheduleCallback(NormalPriority, () => { runtime.log('Task'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'Task']); }); it('task with continuation', () => { scheduleCallback(NormalPriority, () => { runtime.log('Task'); while (!Scheduler.unstable_shouldYield()) { runtime.advanceTime(1); } runtime.log(`Yield at ${performance.now()}ms`); return () => { runtime.log('Continuation'); }; }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog([ 'setImmediate Callback', 'Task', 'Yield at 5ms', 'Set Immediate', ]); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'Continuation']); }); it('multiple tasks', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); }); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'A', 'B']); }); it('multiple tasks at different priority', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); }); scheduleCallback(UserBlockingPriority, () => { runtime.log('B'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'B', 'A']); }); it('multiple tasks with a yield in between', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); runtime.advanceTime(4999); }); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog([ 'setImmediate Callback', 'A', // Ran out of time. Post a continuation event. 'Set Immediate', ]); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'B']); }); it('cancels tasks', () => { const task = scheduleCallback(NormalPriority, () => { runtime.log('Task'); }); runtime.assertLog(['Set Immediate']); cancelCallback(task); runtime.assertLog([]); }); it('throws when a task errors then continues in a new event', () => { scheduleCallback(NormalPriority, () => { runtime.log('Oops!'); throw Error('Oops!'); }); scheduleCallback(NormalPriority, () => { runtime.log('Yay'); }); runtime.assertLog(['Set Immediate']); expect(() => runtime.fireSetImmediate()).toThrow('Oops!'); runtime.assertLog(['setImmediate Callback', 'Oops!', 'Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'Yay']); }); it('schedule new task after queue has emptied', () => { scheduleCallback(NormalPriority, () => { runtime.log('A'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'A']); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'B']); }); it('schedule new task after a cancellation', () => { const handle = scheduleCallback(NormalPriority, () => { runtime.log('A'); }); runtime.assertLog(['Set Immediate']); cancelCallback(handle); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback']); scheduleCallback(NormalPriority, () => { runtime.log('B'); }); runtime.assertLog(['Set Immediate']); runtime.fireSetImmediate(); runtime.assertLog(['setImmediate Callback', 'B']); }); }); it('does not crash if setImmediate is undefined', () => { jest.resetModules(); const originalSetImmediate = global.setImmediate; try { delete global.setImmediate; jest.unmock('scheduler'); expect(() => { require('scheduler'); }).not.toThrow(); } finally { global.setImmediate = originalSetImmediate; } });
25.6875
78
0.619329
owtf
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ export default function Html({assets, children, title}) { return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="shortcut icon" href="favicon.ico" /> <link rel="stylesheet" href={assets['main.css']} /> <title>{title}</title> </head> <body> <noscript dangerouslySetInnerHTML={{ __html: `<b>Enable JavaScript to run this app.</b>`, }} /> {children} <script dangerouslySetInnerHTML={{ __html: `assetManifest = ${JSON.stringify(assets)};`, }} /> </body> </html> ); }
25.4
78
0.544962
Python-Penetration-Testing-for-Developers
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export * from '../src/ReactFlightESMNodeLoader.js';
22.363636
66
0.699219
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireWildcard(require("react")); var _jsxFileName = ""; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function Component() { const countState = (0, _react.useState)(0); const count = countState[0]; const setCount = countState[1]; const darkMode = useIsDarkMode(); const [isDarkMode] = darkMode; (0, _react.useEffect)(() => {// ... }, []); const handleClick = () => setCount(count + 1); return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 28, columnNumber: 7 } }, "Dark mode? ", isDarkMode), /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 29, columnNumber: 7 } }, "Count: ", count), /*#__PURE__*/_react.default.createElement("button", { onClick: handleClick, __source: { fileName: _jsxFileName, lineNumber: 30, columnNumber: 7 } }, "Update count")); } function useIsDarkMode() { const darkModeState = (0, _react.useState)(false); const [isDarkMode] = darkModeState; (0, _react.useEffect)(function useEffectCreate() {// Here is where we may listen to a "theme" event... }, []); return [isDarkMode, () => {}]; } //# sourceMappingURL=ComponentUsingHooksIndirectly.js.map?foo=bar&param=some_value
42.107143
743
0.653129
thieves-tools
/** * Copyright (c) Meta Platforms, Inc. 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 chunkMap: Map<string, string> = new Map(); /** * We patch the chunk filename function in webpack to insert our own resolution * of chunks that come from Flight and may not be known to the webpack runtime */ const webpackGetChunkFilename = __webpack_require__.u; __webpack_require__.u = function (chunkId: string) { const flightChunk = chunkMap.get(chunkId); if (flightChunk !== undefined) { return flightChunk; } return webpackGetChunkFilename(chunkId); }; export function loadChunk(chunkId: string, filename: string): Promise<mixed> { chunkMap.set(chunkId, filename); return __webpack_chunk_load__(chunkId); }
28.068966
79
0.71734
diff-droid
"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,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhNdWx0aXBsZUhvb2tzUGVyTGluZS5qcyJdLCJuYW1lcyI6WyJBIiwiQiIsIkNvbXBvbmVudCIsImEiLCJiIiwiYyIsImQiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFTQTs7QUFUQTs7Ozs7Ozs7QUFXQSxNQUFNQSxDQUFDLGdCQUFHLDBCQUFjLENBQWQsQ0FBVjtBQUNBLE1BQU1DLENBQUMsZ0JBQUcsMEJBQWMsQ0FBZCxDQUFWOztBQUVPLFNBQVNDLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsQ0FBQyxHQUFHLHVCQUFXSCxDQUFYLENBQVY7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdILENBQVgsQ0FBVixDQUYwQixDQUkxQjs7QUFDQSxRQUFNSSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBVjtBQUFBLFFBQXlCTSxDQUFDLEdBQUcsdUJBQVdMLENBQVgsQ0FBN0IsQ0FMMEIsQ0FLa0I7O0FBRTVDLFNBQU9FLENBQUMsR0FBR0MsQ0FBSixHQUFRQyxDQUFSLEdBQVlDLENBQW5CO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuaW1wb3J0IHtjcmVhdGVDb250ZXh0LCB1c2VDb250ZXh0fSBmcm9tICdyZWFjdCc7XG5cbmNvbnN0IEEgPSBjcmVhdGVDb250ZXh0KDEpO1xuY29uc3QgQiA9IGNyZWF0ZUNvbnRleHQoMik7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IGEgPSB1c2VDb250ZXh0KEEpO1xuICBjb25zdCBiID0gdXNlQ29udGV4dChCKTtcblxuICAvLyBwcmV0dGllci1pZ25vcmVcbiAgY29uc3QgYyA9IHVzZUNvbnRleHQoQSksIGQgPSB1c2VDb250ZXh0KEIpOyAvLyBlc2xpbnQtZGlzYWJsZS1saW5lIG9uZS12YXJcblxuICByZXR1cm4gYSArIGIgKyBjICsgZDtcbn1cbiJdLCJ4X3JlYWN0X3NvdXJjZXMiOltbeyJuYW1lcyI6WyI8bm8taG9vaz4iLCJhIiwiYiIsImMiLCJkIl0sIm1hcHBpbmdzIjoiQ0FBRDtnQllDQSxBYURBO2lCYkVBLEFhRkE7b0JiR0EsQWFIQSxBTUlBLEFhSkEifV1dfQ==
76.833333
1,628
0.882177
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export {default as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED} from './src/ReactDOMSharedInternals'; export { createPortal, createRoot, hydrateRoot, findDOMNode, flushSync, hydrate, render, unmountComponentAtNode, unstable_batchedUpdates, unstable_renderSubtreeIntoContainer, unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority. useFormStatus, useFormState, prefetchDNS, preconnect, preload, preloadModule, preinit, preinitModule, version, } from './src/client/ReactDOM'; import type {Awaited} from 'shared/ReactTypes'; import type {FormStatus} from 'react-dom-bindings/src/shared/ReactDOMFormActions'; import {useFormStatus, useFormState} from './src/client/ReactDOM'; export function experimental_useFormStatus(): FormStatus { if (__DEV__) { console.error( 'useFormStatus is now in canary. Remove the experimental_ prefix. ' + 'The prefixed alias will be removed in an upcoming release.', ); } return useFormStatus(); } export function experimental_useFormState<S, P>( action: (Awaited<S>, P) => S, initialState: Awaited<S>, permalink?: string, ): [Awaited<S>, (P) => void] { if (__DEV__) { console.error( 'useFormState is now in canary. Remove the experimental_ prefix. ' + 'The prefixed alias will be removed in an upcoming release.', ); } return useFormState(action, initialState, permalink); }
26.393443
108
0.708982
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; describe('ReactCreateRef', () => { beforeEach(() => { jest.resetModules(); React = require('react'); ReactTestRenderer = require('react-test-renderer'); }); it('should warn in dev if an invalid ref object is provided', () => { function Wrapper({children}) { return children; } class ExampleComponent extends React.Component { render() { return null; } } expect(() => ReactTestRenderer.create( <Wrapper> <div ref={{}} /> </Wrapper>, ), ).toErrorDev( 'Unexpected ref object provided for div. ' + 'Use either a ref-setter function or React.createRef().\n' + ' in div (at **)\n' + ' in Wrapper (at **)', ); expect(() => ReactTestRenderer.create( <Wrapper> <ExampleComponent ref={{}} /> </Wrapper>, ), ).toErrorDev( 'Unexpected ref object provided for ExampleComponent. ' + 'Use either a ref-setter function or React.createRef().\n' + ' in ExampleComponent (at **)\n' + ' in Wrapper (at **)', ); }); });
22.04918
71
0.558719
owtf
/** * Copyright (c) Facebook, Inc. and its affiliates. */ /*! * Based on 'gatsby-remark-autolink-headers' * Original Author: Kyle Mathews <[email protected]> * Updated by Jared Palmer; * Copyright (c) 2015 Gatsbyjs */ const toString = require('mdast-util-to-string'); const visit = require('unist-util-visit'); const toSlug = require('github-slugger').slug; function patch(context, key, value) { if (!context[key]) { context[key] = value; } return context[key]; } const svgIcon = `<svg aria-hidden="true" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg>`; module.exports = ({icon = svgIcon, className = `anchor`} = {}) => { return function transformer(tree) { const ids = new Set(); visit(tree, 'heading', (node) => { let children = [...node.children]; let id; if (children[children.length - 1].type === 'mdxTextExpression') { // # My header {/*my-header*/} id = children.pop().value; const isValidCustomId = id.startsWith('/*') && id.endsWith('*/'); if (!isValidCustomId) { throw Error( 'Expected header ID to be like: {/*some-header*/}. ' + 'Instead, received: ' + id ); } id = id.slice(2, id.length - 2); if (id !== toSlug(id)) { throw Error( 'Expected header ID to be a valid slug. You specified: {/*' + id + '*/}. Replace it with: {/*' + toSlug(id) + '*/}' ); } } else { // # My header id = toSlug(toString(node)); } if (ids.has(id)) { throw Error( 'Cannot have a duplicate header with id "' + id + '" on the page. ' + 'Rename the section or give it an explicit unique ID. ' + 'For example: #### Arguments {/*setstate-arguments*/}' ); } ids.add(id); const data = patch(node, 'data', {}); patch(data, 'id', id); patch(data, 'htmlAttributes', {}); patch(data, 'hProperties', {}); patch(data.htmlAttributes, 'id', id); patch(data.hProperties, 'id', id); }); }; };
32.558442
477
0.535037
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function Component() { const [count] = require('react').useState(0); return count; } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIklubGluZVJlcXVpcmUuanMiXSwibmFtZXMiOlsiQ29tcG9uZW50IiwiY291bnQiLCJyZXF1aXJlIiwidXNlU3RhdGUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFBQTs7Ozs7Ozs7QUFTTyxTQUFTQSxTQUFULEdBQXFCO0FBQzFCLFFBQU0sQ0FBQ0MsS0FBRCxJQUFVQyxPQUFPLENBQUMsT0FBRCxDQUFQLENBQWlCQyxRQUFqQixDQUEwQixDQUExQixDQUFoQjs7QUFFQSxTQUFPRixLQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIENvcHlyaWdodCAoYykgRmFjZWJvb2ssIEluYy4gYW5kIGl0cyBhZmZpbGlhdGVzLlxuICpcbiAqIFRoaXMgc291cmNlIGNvZGUgaXMgbGljZW5zZWQgdW5kZXIgdGhlIE1JVCBsaWNlbnNlIGZvdW5kIGluIHRoZVxuICogTElDRU5TRSBmaWxlIGluIHRoZSByb290IGRpcmVjdG9yeSBvZiB0aGlzIHNvdXJjZSB0cmVlLlxuICpcbiAqIEBmbG93XG4gKi9cblxuZXhwb3J0IGZ1bmN0aW9uIENvbXBvbmVudCgpIHtcbiAgY29uc3QgW2NvdW50XSA9IHJlcXVpcmUoJ3JlYWN0JykudXNlU3RhdGUoMCk7XG5cbiAgcmV0dXJuIGNvdW50O1xufVxuIl19fV19
62.47619
932
0.895646
Hands-On-Penetration-Testing-with-Python
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Component = Component; var _react = _interopRequireDefault(require("react")); var _useTheme = _interopRequireDefault(require("./useTheme")); var _jsxFileName = ""; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Component() { const theme = (0, _useTheme.default)(); return /*#__PURE__*/_react.default.createElement("div", { __source: { fileName: _jsxFileName, lineNumber: 16, columnNumber: 10 } }, "theme: ", theme); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzZWN0aW9ucyI6W3sib2Zmc2V0Ijp7ImxpbmUiOjAsImNvbHVtbiI6MH0sIm1hcCI6eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7OztBQUVPLFNBQVNBLFNBQVQsR0FBcUI7QUFDMUIsUUFBTUMsS0FBSyxHQUFHLHdCQUFkO0FBRUEsc0JBQU87QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsZ0JBQWFBLEtBQWIsQ0FBUDtBQUNEIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgKGMpIEZhY2Vib29rLCBJbmMuIGFuZCBpdHMgYWZmaWxpYXRlcy5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBNSVQgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS5cbiAqXG4gKiBAZmxvd1xuICovXG5cbmltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgdXNlVGhlbWUgZnJvbSAnLi91c2VUaGVtZSc7XG5cbmV4cG9ydCBmdW5jdGlvbiBDb21wb25lbnQoKSB7XG4gIGNvbnN0IHRoZW1lID0gdXNlVGhlbWUoKTtcblxuICByZXR1cm4gPGRpdj50aGVtZToge3RoZW1lfTwvZGl2Pjtcbn1cbiJdfX1dfQ==
61.076923
1,012
0.858648
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 gzip = require('gzip-size'); module.exports = function sizes(options) { return { name: 'scripts/rollup/plugins/sizes-plugin', generateBundle(outputOptions, bundle, isWrite) { Object.keys(bundle).forEach(id => { const chunk = bundle[id]; if (chunk) { const size = Buffer.byteLength(chunk.code); const gzipSize = gzip.sync(chunk.code); options.getSize(size, gzipSize); } }); }, }; };
25.076923
66
0.624815
null
/* eslint-disable */ const NODE_ENV = process.env.NODE_ENV; if (NODE_ENV !== 'development' && NODE_ENV !== 'production') { throw new Error('NODE_ENV must either be set to development or production.'); } global.__DEV__ = NODE_ENV === 'development'; global.__EXTENSION__ = false; global.__TEST__ = NODE_ENV === 'test'; global.__PROFILE__ = NODE_ENV === 'development'; global.__UMD__ = false; const RELEASE_CHANNEL = process.env.RELEASE_CHANNEL; // Default to running tests in experimental mode. If the release channel is // set via an environment variable, then check if it's "experimental". global.__EXPERIMENTAL__ = typeof RELEASE_CHANNEL === 'string' ? RELEASE_CHANNEL === 'experimental' : true; global.__VARIANT__ = !!process.env.VARIANT; if (typeof window !== 'undefined') { global.requestIdleCallback = function (callback) { return setTimeout(() => { callback({ timeRemaining() { return Infinity; }, }); }); }; global.cancelIdleCallback = function (callbackID) { clearTimeout(callbackID); }; } else { global.AbortController = require('abortcontroller-polyfill/dist/cjs-ponyfill').AbortController; }
27.238095
79
0.654852
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const ESLintTester = require('eslint').RuleTester; const ReactHooksESLintPlugin = require('eslint-plugin-react-hooks'); const ReactHooksESLintRule = ReactHooksESLintPlugin.rules['rules-of-hooks']; ESLintTester.setDefaultConfig({ parser: require.resolve('babel-eslint'), parserOptions: { ecmaVersion: 6, sourceType: 'module', }, }); /** * A string template tag that removes padding from the left side of multi-line strings * @param {Array} strings array of code strings (only one expected) */ function normalizeIndent(strings) { const codeLines = strings[0].split('\n'); const leftPadding = codeLines[1].match(/\s+/)[0]; return codeLines.map(line => line.slice(leftPadding.length)).join('\n'); } // *************************************************** // For easier local testing, you can add to any case: // { // skip: true, // --or-- // only: true, // ... // } // *************************************************** const tests = { valid: [ { code: normalizeIndent` // Valid because components can use hooks. function ComponentWithHook() { useHook(); } `, }, { code: normalizeIndent` // Valid because components can use hooks. function createComponentWithHook() { return function ComponentWithHook() { useHook(); }; } `, }, { code: normalizeIndent` // Valid because hooks can use hooks. function useHookWithHook() { useHook(); } `, }, { code: normalizeIndent` // Valid because hooks can use hooks. function createHook() { return function useHookWithHook() { useHook(); } } `, }, { code: normalizeIndent` // Valid because components can call functions. function ComponentWithNormalFunction() { doSomething(); } `, }, { code: normalizeIndent` // Valid because functions can call functions. function normalFunctionWithNormalFunction() { doSomething(); } `, }, { code: normalizeIndent` // Valid because functions can call functions. function normalFunctionWithConditionalFunction() { if (cond) { doSomething(); } } `, }, { code: normalizeIndent` // Valid because functions can call functions. function functionThatStartsWithUseButIsntAHook() { if (cond) { userFetch(); } } `, }, { code: normalizeIndent` // Valid although unconditional return doesn't make sense and would fail other rules. // We could make it invalid but it doesn't matter. function useUnreachable() { return; useHook(); } `, }, { code: normalizeIndent` // Valid because hooks can call hooks. function useHook() { useState(); } const whatever = function useHook() { useState(); }; const useHook1 = () => { useState(); }; let useHook2 = () => useState(); useHook2 = () => { useState(); }; ({useHook: () => { useState(); }}); ({useHook() { useState(); }}); const {useHook3 = () => { useState(); }} = {}; ({useHook = () => { useState(); }} = {}); Namespace.useHook = () => { useState(); }; `, }, { code: normalizeIndent` // Valid because hooks can call hooks. function useHook() { useHook1(); useHook2(); } `, }, { code: normalizeIndent` // Valid because hooks can call hooks. function createHook() { return function useHook() { useHook1(); useHook2(); }; } `, }, { code: normalizeIndent` // Valid because hooks can call hooks. function useHook() { useState() && a; } `, }, { code: normalizeIndent` // Valid because hooks can call hooks. function useHook() { return useHook1() + useHook2(); } `, }, { code: normalizeIndent` // Valid because hooks can call hooks. function useHook() { return useHook1(useHook2()); } `, }, { code: normalizeIndent` // Valid because hooks can be used in anonymous arrow-function arguments // to forwardRef. const FancyButton = React.forwardRef((props, ref) => { useHook(); return <button {...props} ref={ref} /> }); `, }, { code: normalizeIndent` // Valid because hooks can be used in anonymous function arguments to // forwardRef. const FancyButton = React.forwardRef(function (props, ref) { useHook(); return <button {...props} ref={ref} /> }); `, }, { code: normalizeIndent` // Valid because hooks can be used in anonymous function arguments to // forwardRef. const FancyButton = forwardRef(function (props, ref) { useHook(); return <button {...props} ref={ref} /> }); `, }, { code: normalizeIndent` // Valid because hooks can be used in anonymous function arguments to // React.memo. const MemoizedFunction = React.memo(props => { useHook(); return <button {...props} /> }); `, }, { code: normalizeIndent` // Valid because hooks can be used in anonymous function arguments to // memo. const MemoizedFunction = memo(function (props) { useHook(); return <button {...props} /> }); `, }, { code: normalizeIndent` // Valid because classes can call functions. // We don't consider these to be hooks. class C { m() { this.useHook(); super.useHook(); } } `, }, { code: normalizeIndent` // Valid -- this is a regression test. jest.useFakeTimers(); beforeEach(() => { jest.useRealTimers(); }) `, }, { code: normalizeIndent` // Valid because they're not matching use[A-Z]. fooState(); _use(); _useState(); use_hook(); // also valid because it's not matching the PascalCase namespace jest.useFakeTimer() `, }, { code: normalizeIndent` // Regression test for some internal code. // This shows how the "callback rule" is more relaxed, // and doesn't kick in unless we're confident we're in // a component or a hook. function makeListener(instance) { each(pixelsWithInferredEvents, pixel => { if (useExtendedSelector(pixel.id) && extendedButton) { foo(); } }); } `, }, { code: normalizeIndent` // This is valid because "use"-prefixed functions called in // unnamed function arguments are not assumed to be hooks. React.unknownFunction((foo, bar) => { if (foo) { useNotAHook(bar) } }); `, }, { code: normalizeIndent` // This is valid because "use"-prefixed functions called in // unnamed function arguments are not assumed to be hooks. unknownFunction(function(foo, bar) { if (foo) { useNotAHook(bar) } }); `, }, { code: normalizeIndent` // Regression test for incorrectly flagged valid code. function RegressionTest() { const foo = cond ? a : b; useState(); } `, }, { code: normalizeIndent` // Valid because exceptions abort rendering function RegressionTest() { if (page == null) { throw new Error('oh no!'); } useState(); } `, }, { code: normalizeIndent` // Valid because the loop doesn't change the order of hooks calls. function RegressionTest() { const res = []; const additionalCond = true; for (let i = 0; i !== 10 && additionalCond; ++i ) { res.push(i); } React.useLayoutEffect(() => {}); } `, }, { code: normalizeIndent` // Is valid but hard to compute by brute-forcing function MyComponent() { // 40 conditions if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} if (c) {} else {} // 10 hooks useHook(); useHook(); useHook(); useHook(); useHook(); useHook(); useHook(); useHook(); useHook(); useHook(); } `, }, { code: normalizeIndent` // Valid because the neither the conditions before or after the hook affect the hook call // Failed prior to implementing BigInt because pathsFromStartToEnd and allPathsFromStartToEnd were too big and had rounding errors const useSomeHook = () => {}; const SomeName = () => { const filler = FILLER ?? FILLER ?? FILLER; const filler2 = FILLER ?? FILLER ?? FILLER; const filler3 = FILLER ?? FILLER ?? FILLER; const filler4 = FILLER ?? FILLER ?? FILLER; const filler5 = FILLER ?? FILLER ?? FILLER; const filler6 = FILLER ?? FILLER ?? FILLER; const filler7 = FILLER ?? FILLER ?? FILLER; const filler8 = FILLER ?? FILLER ?? FILLER; useSomeHook(); if (anyConditionCanEvenBeFalse) { return null; } return ( <React.Fragment> {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} {FILLER ? FILLER : FILLER} </React.Fragment> ); }; `, }, { code: normalizeIndent` // Valid because the neither the condition nor the loop affect the hook call. function App(props) { const someObject = {propA: true}; for (const propName in someObject) { if (propName === true) { } else { } } const [myState, setMyState] = useState(null); } `, }, { code: normalizeIndent` function App() { const text = use(Promise.resolve('A')); return <Text text={text} /> } `, }, { code: normalizeIndent` import * as React from 'react'; function App() { if (shouldShowText) { const text = use(query); const data = React.use(thing); const data2 = react.use(thing2); return <Text text={text} /> } return <Text text={shouldFetchBackupText ? use(backupQuery) : "Nothing to see here"} /> } `, }, { code: normalizeIndent` function App() { let data = []; for (const query of queries) { const text = use(item); data.push(text); } return <Child data={data} /> } `, }, { code: normalizeIndent` function App() { const data = someCallback((x) => use(x)); return <Child data={data} /> } `, }, ], invalid: [ { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function ComponentWithConditionalHook() { if (cond) { useConditionalHook(); } } `, errors: [conditionalError('useConditionalHook')], }, { code: normalizeIndent` Hook.useState(); Hook._useState(); Hook.use42(); Hook.useHook(); Hook.use_hook(); `, errors: [ topLevelError('Hook.useState'), topLevelError('Hook.use42'), topLevelError('Hook.useHook'), ], }, { code: normalizeIndent` class C { m() { This.useHook(); Super.useHook(); } } `, errors: [classError('This.useHook'), classError('Super.useHook')], }, { code: normalizeIndent` // This is a false positive (it's valid) that unfortunately // we cannot avoid. Prefer to rename it to not start with "use" class Foo extends Component { render() { if (cond) { FooStore.useFeatureFlag(); } } } `, errors: [classError('FooStore.useFeatureFlag')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function ComponentWithConditionalHook() { if (cond) { Namespace.useConditionalHook(); } } `, errors: [conditionalError('Namespace.useConditionalHook')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function createComponent() { return function ComponentWithConditionalHook() { if (cond) { useConditionalHook(); } } } `, errors: [conditionalError('useConditionalHook')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHookWithConditionalHook() { if (cond) { useConditionalHook(); } } `, errors: [conditionalError('useConditionalHook')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function createHook() { return function useHookWithConditionalHook() { if (cond) { useConditionalHook(); } } } `, errors: [conditionalError('useConditionalHook')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function ComponentWithTernaryHook() { cond ? useTernaryHook() : null; } `, errors: [conditionalError('useTernaryHook')], }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. // We *could* make it valid but the runtime error could be confusing. function ComponentWithHookInsideCallback() { useEffect(() => { useHookInsideCallback(); }); } `, errors: [genericError('useHookInsideCallback')], }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. // We *could* make it valid but the runtime error could be confusing. function createComponent() { return function ComponentWithHookInsideCallback() { useEffect(() => { useHookInsideCallback(); }); } } `, errors: [genericError('useHookInsideCallback')], }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. // We *could* make it valid but the runtime error could be confusing. const ComponentWithHookInsideCallback = React.forwardRef((props, ref) => { useEffect(() => { useHookInsideCallback(); }); return <button {...props} ref={ref} /> }); `, errors: [genericError('useHookInsideCallback')], }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. // We *could* make it valid but the runtime error could be confusing. const ComponentWithHookInsideCallback = React.memo(props => { useEffect(() => { useHookInsideCallback(); }); return <button {...props} /> }); `, errors: [genericError('useHookInsideCallback')], }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. // We *could* make it valid but the runtime error could be confusing. function ComponentWithHookInsideCallback() { function handleClick() { useState(); } } `, errors: [functionError('useState', 'handleClick')], }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. // We *could* make it valid but the runtime error could be confusing. function createComponent() { return function ComponentWithHookInsideCallback() { function handleClick() { useState(); } } } `, errors: [functionError('useState', 'handleClick')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function ComponentWithHookInsideLoop() { while (cond) { useHookInsideLoop(); } } `, errors: [loopError('useHookInsideLoop')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function renderItem() { useState(); } function List(props) { return props.items.map(renderItem); } `, errors: [functionError('useState', 'renderItem')], }, { code: normalizeIndent` // Currently invalid because it violates the convention and removes the "taint" // from a hook. We *could* make it valid to avoid some false positives but let's // ensure that we don't break the "renderItem" and "normalFunctionWithConditionalHook" // cases which must remain invalid. function normalFunctionWithHook() { useHookInsideNormalFunction(); } `, errors: [ functionError('useHookInsideNormalFunction', 'normalFunctionWithHook'), ], }, { code: normalizeIndent` // These are neither functions nor hooks. function _normalFunctionWithHook() { useHookInsideNormalFunction(); } function _useNotAHook() { useHookInsideNormalFunction(); } `, errors: [ functionError('useHookInsideNormalFunction', '_normalFunctionWithHook'), functionError('useHookInsideNormalFunction', '_useNotAHook'), ], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function normalFunctionWithConditionalHook() { if (cond) { useHookInsideNormalFunction(); } } `, errors: [ functionError( 'useHookInsideNormalFunction', 'normalFunctionWithConditionalHook' ), ], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHookInLoops() { while (a) { useHook1(); if (b) return; useHook2(); } while (c) { useHook3(); if (d) return; useHook4(); } } `, errors: [ loopError('useHook1'), loopError('useHook2'), loopError('useHook3'), loopError('useHook4'), ], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHookInLoops() { while (a) { useHook1(); if (b) continue; useHook2(); } } `, errors: [loopError('useHook1'), loopError('useHook2', true)], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useLabeledBlock() { label: { if (a) break label; useHook(); } } `, errors: [conditionalError('useHook')], }, { code: normalizeIndent` // Currently invalid. // These are variations capturing the current heuristic-- // we only allow hooks in PascalCase or useFoo functions. // We *could* make some of these valid. But before doing it, // consider specific cases documented above that contain reasoning. function a() { useState(); } const whatever = function b() { useState(); }; const c = () => { useState(); }; let d = () => useState(); e = () => { useState(); }; ({f: () => { useState(); }}); ({g() { useState(); }}); const {j = () => { useState(); }} = {}; ({k = () => { useState(); }} = {}); `, errors: [ functionError('useState', 'a'), functionError('useState', 'b'), functionError('useState', 'c'), functionError('useState', 'd'), functionError('useState', 'e'), functionError('useState', 'f'), functionError('useState', 'g'), functionError('useState', 'j'), functionError('useState', 'k'), ], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHook() { if (a) return; useState(); } `, errors: [conditionalError('useState', true)], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHook() { if (a) return; if (b) { console.log('true'); } else { console.log('false'); } useState(); } `, errors: [conditionalError('useState', true)], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHook() { if (b) { console.log('true'); } else { console.log('false'); } if (a) return; useState(); } `, errors: [conditionalError('useState', true)], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHook() { a && useHook1(); b && useHook2(); } `, errors: [conditionalError('useHook1'), conditionalError('useHook2')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHook() { try { f(); useState(); } catch {} } `, errors: [ // NOTE: This is an error since `f()` could possibly throw. conditionalError('useState'), ], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. function useHook({ bar }) { let foo1 = bar && useState(); let foo2 = bar || useState(); let foo3 = bar ?? useState(); } `, errors: [ conditionalError('useState'), conditionalError('useState'), conditionalError('useState'), ], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. const FancyButton = React.forwardRef((props, ref) => { if (props.fancy) { useCustomHook(); } return <button ref={ref}>{props.children}</button>; }); `, errors: [conditionalError('useCustomHook')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. const FancyButton = forwardRef(function(props, ref) { if (props.fancy) { useCustomHook(); } return <button ref={ref}>{props.children}</button>; }); `, errors: [conditionalError('useCustomHook')], }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. // This *must* be invalid. const MemoizedButton = memo(function(props) { if (props.fancy) { useCustomHook(); } return <button>{props.children}</button>; }); `, errors: [conditionalError('useCustomHook')], }, { code: normalizeIndent` // This is invalid because "use"-prefixed functions used in named // functions are assumed to be hooks. React.unknownFunction(function notAComponent(foo, bar) { useProbablyAHook(bar) }); `, errors: [functionError('useProbablyAHook', 'notAComponent')], }, { code: normalizeIndent` // Invalid because it's dangerous. // Normally, this would crash, but not if you use inline requires. // This *must* be invalid. // It's expected to have some false positives, but arguably // they are confusing anyway due to the use*() convention // already being associated with Hooks. useState(); if (foo) { const foo = React.useCallback(() => {}); } useCustomHook(); `, errors: [ topLevelError('useState'), topLevelError('React.useCallback'), topLevelError('useCustomHook'), ], }, { code: normalizeIndent` // Technically this is a false positive. // We *could* make it valid (and it used to be). // // However, top-level Hook-like calls can be very dangerous // in environments with inline requires because they can mask // the runtime error by accident. // So we prefer to disallow it despite the false positive. const {createHistory, useBasename} = require('history-2.1.2'); const browserHistory = useBasename(createHistory)({ basename: '/', }); `, errors: [topLevelError('useBasename')], }, { code: normalizeIndent` class ClassComponentWithFeatureFlag extends React.Component { render() { if (foo) { useFeatureFlag(); } } } `, errors: [classError('useFeatureFlag')], }, { code: normalizeIndent` class ClassComponentWithHook extends React.Component { render() { React.useState(); } } `, errors: [classError('React.useState')], }, { code: normalizeIndent` (class {useHook = () => { useState(); }}); `, errors: [classError('useState')], }, { code: normalizeIndent` (class {useHook() { useState(); }}); `, errors: [classError('useState')], }, { code: normalizeIndent` (class {h = () => { useState(); }}); `, errors: [classError('useState')], }, { code: normalizeIndent` (class {i() { useState(); }}); `, errors: [classError('useState')], }, { code: normalizeIndent` async function AsyncComponent() { useState(); } `, errors: [asyncComponentHookError('useState')], }, { code: normalizeIndent` async function useAsyncHook() { useState(); } `, errors: [asyncComponentHookError('useState')], }, { code: normalizeIndent` Hook.use(); Hook._use(); Hook.useState(); Hook._useState(); Hook.use42(); Hook.useHook(); Hook.use_hook(); `, errors: [ topLevelError('Hook.use'), topLevelError('Hook.useState'), topLevelError('Hook.use42'), topLevelError('Hook.useHook'), ], }, { code: normalizeIndent` function notAComponent() { use(promise); } `, errors: [functionError('use', 'notAComponent')], }, { code: normalizeIndent` const text = use(promise); function App() { return <Text text={text} /> } `, errors: [topLevelError('use')], }, { code: normalizeIndent` class C { m() { use(promise); } } `, errors: [classError('use')], }, { code: normalizeIndent` async function AsyncComponent() { use(); } `, errors: [asyncComponentHookError('use')], }, ], }; if (__EXPERIMENTAL__) { tests.valid = [ ...tests.valid, { code: normalizeIndent` // Valid because functions created with useEffectEvent can be called in a useEffect. function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(theme); }); useEffect(() => { onClick(); }); } `, }, { code: normalizeIndent` // Valid because functions created with useEffectEvent can be called in closures. function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(theme); }); return <Child onClick={() => onClick()}></Child>; } `, }, { code: normalizeIndent` // Valid because functions created with useEffectEvent can be called in closures. function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(theme); }); const onClick2 = () => { onClick() }; const onClick3 = useCallback(() => onClick(), []); return <> <Child onClick={onClick2}></Child> <Child onClick={onClick3}></Child> </>; } `, }, { code: normalizeIndent` // Valid because functions created with useEffectEvent can be passed by reference in useEffect // and useEffectEvent. function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(theme); }); const onClick2 = useEffectEvent(() => { debounce(onClick); }); useEffect(() => { let id = setInterval(onClick, 100); return () => clearInterval(onClick); }, []); return <Child onClick={() => onClick2()} /> } `, }, { code: normalizeIndent` const MyComponent = ({theme}) => { const onClick = useEffectEvent(() => { showNotification(theme); }); return <Child onClick={() => onClick()}></Child>; }; `, }, { code: normalizeIndent` function MyComponent({ theme }) { const notificationService = useNotifications(); const showNotification = useEffectEvent((text) => { notificationService.notify(theme, text); }); const onClick = useEffectEvent((text) => { showNotification(text); }); return <Child onClick={(text) => onClick(text)} /> } `, }, { code: normalizeIndent` function MyComponent({ theme }) { useEffect(() => { onClick(); }); const onClick = useEffectEvent(() => { showNotification(theme); }); } `, }, ]; tests.invalid = [ ...tests.invalid, { code: normalizeIndent` function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(theme); }); return <Child onClick={onClick}></Child>; } `, errors: [useEffectEventError('onClick')], }, { code: normalizeIndent` // This should error even though it shares an identifier name with the below function MyComponent({theme}) { const onClick = useEffectEvent(() => { showNotification(theme) }); return <Child onClick={onClick} /> } // The useEffectEvent function shares an identifier name with the above function MyOtherComponent({theme}) { const onClick = useEffectEvent(() => { showNotification(theme) }); return <Child onClick={() => onClick()} /> } `, errors: [{...useEffectEventError('onClick'), line: 7}], }, { code: normalizeIndent` const MyComponent = ({ theme }) => { const onClick = useEffectEvent(() => { showNotification(theme); }); return <Child onClick={onClick}></Child>; } `, errors: [useEffectEventError('onClick')], }, { code: normalizeIndent` // Invalid because onClick is being aliased to foo but not invoked function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(theme); }); let foo = onClick; return <Bar onClick={foo} /> } `, errors: [{...useEffectEventError('onClick'), line: 7}], }, { code: normalizeIndent` // Should error because it's being passed down to JSX, although it's been referenced once // in an effect function MyComponent({ theme }) { const onClick = useEffectEvent(() => { showNotification(them); }); useEffect(() => { setTimeout(onClick, 100); }); return <Child onClick={onClick} /> } `, errors: [useEffectEventError('onClick')], }, ]; } function conditionalError(hook, hasPreviousFinalizer = false) { return { message: `React Hook "${hook}" is called conditionally. React Hooks must be ` + 'called in the exact same order in every component render.' + (hasPreviousFinalizer ? ' Did you accidentally call a React Hook after an early return?' : ''), }; } function loopError(hook) { return { message: `React Hook "${hook}" may be executed more than once. Possibly ` + 'because it is called in a loop. React Hooks must be called in the ' + 'exact same order in every component render.', }; } function functionError(hook, fn) { return { message: `React Hook "${hook}" is called in function "${fn}" that is neither ` + 'a React function component nor a custom React Hook function.' + ' React component names must start with an uppercase letter.' + ' React Hook names must start with the word "use".', }; } function genericError(hook) { return { message: `React Hook "${hook}" cannot be called inside a callback. React Hooks ` + 'must be called in a React function component or a custom React ' + 'Hook function.', }; } function topLevelError(hook) { return { message: `React Hook "${hook}" cannot be called at the top level. React Hooks ` + 'must be called in a React function component or a custom React ' + 'Hook function.', }; } function classError(hook) { return { message: `React Hook "${hook}" cannot be called in a class component. React Hooks ` + 'must be called in a React function component or a custom React ' + 'Hook function.', }; } function useEffectEventError(fn) { return { message: `\`${fn}\` is a function created with React Hook "useEffectEvent", and can only be called from ` + 'the same component. They cannot be assigned to variables or passed down.', }; } function asyncComponentHookError(fn) { return { message: `React Hook "${fn}" cannot be called in an async function.`, }; } // For easier local testing if (!process.env.CI) { let only = []; let skipped = []; [...tests.valid, ...tests.invalid].forEach(t => { if (t.skip) { delete t.skip; skipped.push(t); } if (t.only) { delete t.only; only.push(t); } }); const predicate = t => { if (only.length > 0) { return only.indexOf(t) !== -1; } if (skipped.length > 0) { return skipped.indexOf(t) === -1; } return true; }; tests.valid = tests.valid.filter(predicate); tests.invalid = tests.invalid.filter(predicate); } const eslintTester = new ESLintTester(); eslintTester.run('react-hooks', ReactHooksESLintRule, tests);
27.186322
138
0.50973
null
'use strict'; const {join} = require('path'); const PACKAGE_PATHS = [ 'packages/react-devtools/package.json', 'packages/react-devtools-core/package.json', 'packages/react-devtools-inline/package.json', 'packages/react-devtools-timeline/package.json', ]; const MANIFEST_PATHS = [ 'packages/react-devtools-extensions/chrome/manifest.json', 'packages/react-devtools-extensions/edge/manifest.json', 'packages/react-devtools-extensions/firefox/manifest.json', ]; const NPM_PACKAGES = [ 'react-devtools', 'react-devtools-core', 'react-devtools-inline', ]; const CHANGELOG_PATH = 'packages/react-devtools/CHANGELOG.md'; const PULL_REQUEST_BASE_URL = 'https://github.com/facebook/react/pull/'; const RELEASE_SCRIPT_TOKEN = '<!-- RELEASE_SCRIPT_TOKEN -->'; const ROOT_PATH = join(__dirname, '..', '..'); const DRY_RUN = process.argv.includes('--dry'); const BUILD_METADATA_TEMP_DIRECTORY = join(__dirname, '.build-metadata'); module.exports = { BUILD_METADATA_TEMP_DIRECTORY, CHANGELOG_PATH, DRY_RUN, MANIFEST_PATHS, NPM_PACKAGES, PACKAGE_PATHS, PULL_REQUEST_BASE_URL, RELEASE_SCRIPT_TOKEN, ROOT_PATH, };
23.382979
73
0.712664
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import type {StackCursor} from './ReactFiberStack'; import type {Lanes} from './ReactFiberLane'; import {createCursor, push, pop} from './ReactFiberStack'; import { getEntangledRenderLanes, setEntangledRenderLanes, } from './ReactFiberWorkLoop'; import {NoLanes, mergeLanes} from './ReactFiberLane'; // TODO: Remove `renderLanes` context in favor of hidden context type HiddenContext = { // Represents the lanes that must be included when processing updates in // order to reveal the hidden content. // TODO: Remove `subtreeLanes` context from work loop in favor of this one. baseLanes: number, ... }; // TODO: This isn't being used yet, but it's intended to replace the // InvisibleParentContext that is currently managed by SuspenseContext. export const currentTreeHiddenStackCursor: StackCursor<HiddenContext | null> = createCursor(null); export const prevEntangledRenderLanesCursor: StackCursor<Lanes> = createCursor(NoLanes); export function pushHiddenContext(fiber: Fiber, context: HiddenContext): void { const prevEntangledRenderLanes = getEntangledRenderLanes(); push(prevEntangledRenderLanesCursor, prevEntangledRenderLanes, fiber); push(currentTreeHiddenStackCursor, context, fiber); // When rendering a subtree that's currently hidden, we must include all // lanes that would have rendered if the hidden subtree hadn't been deferred. // That is, in order to reveal content from hidden -> visible, we must commit // all the updates that we skipped when we originally hid the tree. setEntangledRenderLanes( mergeLanes(prevEntangledRenderLanes, context.baseLanes), ); } export function reuseHiddenContextOnStack(fiber: Fiber): void { // This subtree is not currently hidden, so we don't need to add any lanes // to the render lanes. But we still need to push something to avoid a // context mismatch. Reuse the existing context on the stack. push(prevEntangledRenderLanesCursor, getEntangledRenderLanes(), fiber); push( currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current, fiber, ); } export function popHiddenContext(fiber: Fiber): void { // Restore the previous render lanes from the stack setEntangledRenderLanes(prevEntangledRenderLanesCursor.current); pop(currentTreeHiddenStackCursor, fiber); pop(prevEntangledRenderLanesCursor, fiber); } export function isCurrentTreeHidden(): boolean { return currentTreeHiddenStackCursor.current !== null; }
35.146667
79
0.76679
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; // Intentionally not using named imports because Rollup uses dynamic // dispatch for CommonJS interop named imports. import * as React from 'react'; export const useSyncExternalStore = React.useSyncExternalStore;
24.529412
68
0.743649
null
'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/scheduler-unstable_post_task.production.min.js'); } else { module.exports = require('./cjs/scheduler-unstable_post_task.development.js'); }
28.625
83
0.70339
Penetration-Testing-Study-Notes
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import * as SchedulerMock from 'scheduler/unstable_mock'; import {diff} from 'jest-diff'; import {equals} from '@jest/expect-utils'; import enqueueTask from './enqueueTask'; export {act} from './internalAct'; function assertYieldsWereCleared(caller) { const actualYields = SchedulerMock.unstable_clearLog(); if (actualYields.length !== 0) { const error = Error( 'The event log is not empty. Call assertLog(...) first.', ); Error.captureStackTrace(error, caller); throw error; } } export async function waitForMicrotasks() { return new Promise(resolve => { enqueueTask(() => resolve()); }); } export async function waitFor(expectedLog, options) { assertYieldsWereCleared(waitFor); // Create the error object before doing any async work, to get a better // stack trace. const error = new Error(); Error.captureStackTrace(error, waitFor); const stopAfter = expectedLog.length; const actualLog = []; do { // Wait until end of current task/microtask. await waitForMicrotasks(); if (SchedulerMock.unstable_hasPendingWork()) { SchedulerMock.unstable_flushNumberOfYields(stopAfter - actualLog.length); actualLog.push(...SchedulerMock.unstable_clearLog()); if (stopAfter > actualLog.length) { // Continue flushing until we've logged the expected number of items. } else { // Once we've reached the expected sequence, wait one more microtask to // flush any remaining synchronous work. await waitForMicrotasks(); actualLog.push(...SchedulerMock.unstable_clearLog()); break; } } else { // There's no pending work, even after a microtask. break; } } while (true); if (options && options.additionalLogsAfterAttemptingToYield) { expectedLog = expectedLog.concat( options.additionalLogsAfterAttemptingToYield, ); } if (equals(actualLog, expectedLog)) { return; } error.message = ` Expected sequence of events did not occur. ${diff(expectedLog, actualLog)} `; throw error; } export async function waitForAll(expectedLog) { assertYieldsWereCleared(waitForAll); // Create the error object before doing any async work, to get a better // stack trace. const error = new Error(); Error.captureStackTrace(error, waitForAll); do { // Wait until end of current task/microtask. await waitForMicrotasks(); if (!SchedulerMock.unstable_hasPendingWork()) { // There's no pending work, even after a microtask. Stop flushing. break; } SchedulerMock.unstable_flushAllWithoutAsserting(); } while (true); const actualLog = SchedulerMock.unstable_clearLog(); if (equals(actualLog, expectedLog)) { return; } error.message = ` Expected sequence of events did not occur. ${diff(expectedLog, actualLog)} `; throw error; } export async function waitForThrow(expectedError: mixed): mixed { assertYieldsWereCleared(waitForThrow); // Create the error object before doing any async work, to get a better // stack trace. const error = new Error(); Error.captureStackTrace(error, waitForThrow); do { // Wait until end of current task/microtask. await waitForMicrotasks(); if (!SchedulerMock.unstable_hasPendingWork()) { // There's no pending work, even after a microtask. Stop flushing. error.message = 'Expected something to throw, but nothing did.'; throw error; } try { SchedulerMock.unstable_flushAllWithoutAsserting(); } catch (x) { if (expectedError === undefined) { // If no expected error was provided, then assume the caller is OK with // any error being thrown. We're returning the error so they can do // their own checks, if they wish. return x; } if (equals(x, expectedError)) { return x; } if ( typeof expectedError === 'string' && typeof x === 'object' && x !== null && typeof x.message === 'string' ) { if (x.message.includes(expectedError)) { return x; } else { error.message = ` Expected error was not thrown. ${diff(expectedError, x.message)} `; throw error; } } error.message = ` Expected error was not thrown. ${diff(expectedError, x)} `; throw error; } } while (true); } // This is prefixed with `unstable_` because you should almost always try to // avoid using it in tests. It's really only for testing a particular // implementation detail (update starvation prevention). export async function unstable_waitForExpired(expectedLog): mixed { assertYieldsWereCleared(unstable_waitForExpired); // Create the error object before doing any async work, to get a better // stack trace. const error = new Error(); Error.captureStackTrace(error, unstable_waitForExpired); // Wait until end of current task/microtask. await waitForMicrotasks(); SchedulerMock.unstable_flushExpired(); const actualLog = SchedulerMock.unstable_clearLog(); if (equals(actualLog, expectedLog)) { return; } error.message = ` Expected sequence of events did not occur. ${diff(expectedLog, actualLog)} `; throw error; } // TODO: This name is a bit misleading currently because it will stop as soon as // React yields for any reason, not just for a paint. I've left it this way for // now because that's how untable_flushUntilNextPaint already worked, but maybe // we should split these use cases into separate APIs. export async function waitForPaint(expectedLog) { assertYieldsWereCleared(waitForPaint); // Create the error object before doing any async work, to get a better // stack trace. const error = new Error(); Error.captureStackTrace(error, waitForPaint); // Wait until end of current task/microtask. await waitForMicrotasks(); if (SchedulerMock.unstable_hasPendingWork()) { // Flush until React yields. SchedulerMock.unstable_flushUntilNextPaint(); // Wait one more microtask to flush any remaining synchronous work. await waitForMicrotasks(); } const actualLog = SchedulerMock.unstable_clearLog(); if (equals(actualLog, expectedLog)) { return; } error.message = ` Expected sequence of events did not occur. ${diff(expectedLog, actualLog)} `; throw error; } export async function waitForDiscrete(expectedLog) { assertYieldsWereCleared(waitForDiscrete); // Create the error object before doing any async work, to get a better // stack trace. const error = new Error(); Error.captureStackTrace(error, waitForDiscrete); // Wait until end of current task/microtask. await waitForMicrotasks(); const actualLog = SchedulerMock.unstable_clearLog(); if (equals(actualLog, expectedLog)) { return; } error.message = ` Expected sequence of events did not occur. ${diff(expectedLog, actualLog)} `; throw error; } export function assertLog(expectedLog) { const actualLog = SchedulerMock.unstable_clearLog(); if (equals(actualLog, expectedLog)) { return; } const error = new Error(` Expected sequence of events did not occur. ${diff(expectedLog, actualLog)} `); Error.captureStackTrace(error, assertLog); throw error; }
26.782772
80
0.690036
null
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Request} from 'react-server/src/ReactFlightServer'; export * from 'react-server-dom-webpack/src/ReactFlightServerConfigWebpackBundler'; export * from 'react-dom-bindings/src/server/ReactFlightServerConfigDOM'; // For now, we get this from the global scope, but this will likely move to a module. export const supportsRequestStorage = typeof AsyncLocalStorage === 'function'; export const requestStorage: AsyncLocalStorage<Request> = supportsRequestStorage ? new AsyncLocalStorage() : (null: any); // We use the Node version but get access to async_hooks from a global. import type {HookCallbacks, AsyncHook} from 'async_hooks'; export const createAsyncHook: HookCallbacks => AsyncHook = typeof async_hooks === 'object' ? async_hooks.createHook : function () { return ({ enable() {}, disable() {}, }: any); }; export const executionAsyncId: () => number = typeof async_hooks === 'object' ? async_hooks.executionAsyncId : (null: any); export * from '../ReactFlightServerConfigDebugNode';
36.176471
85
0.711797
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import {NoMode, ConcurrentMode} from './ReactTypeOfMode'; import type { Instance, TextInstance, HydratableInstance, SuspenseInstance, Container, HostContext, } from './ReactFiberConfig'; import type {SuspenseState} from './ReactFiberSuspenseComponent'; import type {TreeContext} from './ReactFiberTreeContext'; import type {CapturedValue} from './ReactCapturedValue'; import { HostComponent, HostSingleton, HostText, HostRoot, SuspenseComponent, } from './ReactWorkTags'; import { ChildDeletion, Placement, Hydrating, NoFlags, DidCapture, } from './ReactFiberFlags'; import {enableClientRenderFallbackOnTextMismatch} from 'shared/ReactFeatureFlags'; import { createFiberFromHostInstanceForDeletion, createFiberFromDehydratedFragment, } from './ReactFiber'; import { shouldSetTextContent, supportsHydration, supportsSingletons, getNextHydratableSibling, getFirstHydratableChild, getFirstHydratableChildWithinContainer, getFirstHydratableChildWithinSuspenseInstance, hydrateInstance, hydrateTextInstance, hydrateSuspenseInstance, getNextHydratableInstanceAfterSuspenseInstance, shouldDeleteUnhydratedTailInstances, didNotMatchHydratedContainerTextInstance, didNotMatchHydratedTextInstance, didNotHydrateInstanceWithinContainer, didNotHydrateInstanceWithinSuspenseInstance, didNotHydrateInstance, didNotFindHydratableInstanceWithinContainer, didNotFindHydratableTextInstanceWithinContainer, didNotFindHydratableSuspenseInstanceWithinContainer, didNotFindHydratableInstanceWithinSuspenseInstance, didNotFindHydratableTextInstanceWithinSuspenseInstance, didNotFindHydratableSuspenseInstanceWithinSuspenseInstance, didNotFindHydratableInstance, didNotFindHydratableTextInstance, didNotFindHydratableSuspenseInstance, resolveSingletonInstance, canHydrateInstance, canHydrateTextInstance, canHydrateSuspenseInstance, canHydrateFormStateMarker, isFormStateMarkerMatching, isHydratableText, } from './ReactFiberConfig'; import {OffscreenLane} from './ReactFiberLane'; import { getSuspendedTreeContext, restoreSuspendedTreeContext, } from './ReactFiberTreeContext'; import {queueRecoverableErrors} from './ReactFiberWorkLoop'; import {getRootHostContainer, getHostContext} from './ReactFiberHostContext'; // The deepest Fiber on the stack involved in a hydration context. // This may have been an insertion or a hydration. let hydrationParentFiber: null | Fiber = null; let nextHydratableInstance: null | HydratableInstance = null; let isHydrating: boolean = false; // This flag allows for warning supression when we expect there to be mismatches // due to earlier mismatches or a suspended fiber. let didSuspendOrErrorDEV: boolean = false; // Hydration errors that were thrown inside this boundary let hydrationErrors: Array<CapturedValue<mixed>> | null = null; let rootOrSingletonContext = false; function warnIfHydrating() { if (__DEV__) { if (isHydrating) { console.error( 'We should not be hydrating here. This is a bug in React. Please file a bug.', ); } } } export function markDidThrowWhileHydratingDEV() { if (__DEV__) { didSuspendOrErrorDEV = true; } } export function didSuspendOrErrorWhileHydratingDEV(): boolean { if (__DEV__) { return didSuspendOrErrorDEV; } return false; } function enterHydrationState(fiber: Fiber): boolean { if (!supportsHydration) { return false; } const parentInstance: Container = fiber.stateNode.containerInfo; nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); hydrationParentFiber = fiber; isHydrating = true; hydrationErrors = null; didSuspendOrErrorDEV = false; rootOrSingletonContext = true; return true; } function reenterHydrationStateFromDehydratedSuspenseInstance( fiber: Fiber, suspenseInstance: SuspenseInstance, treeContext: TreeContext | null, ): boolean { if (!supportsHydration) { return false; } nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); hydrationParentFiber = fiber; isHydrating = true; hydrationErrors = null; didSuspendOrErrorDEV = false; rootOrSingletonContext = false; if (treeContext !== null) { restoreSuspendedTreeContext(fiber, treeContext); } return true; } function warnUnhydratedInstance( returnFiber: Fiber, instance: HydratableInstance, ) { if (__DEV__) { switch (returnFiber.tag) { case HostRoot: { didNotHydrateInstanceWithinContainer( returnFiber.stateNode.containerInfo, instance, ); break; } case HostSingleton: case HostComponent: { const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotHydrateInstance( returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode, ); break; } case SuspenseComponent: { const suspenseState: SuspenseState = returnFiber.memoizedState; if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance( suspenseState.dehydrated, instance, ); break; } } } } function deleteHydratableInstance( returnFiber: Fiber, instance: HydratableInstance, ) { warnUnhydratedInstance(returnFiber, instance); const childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; const deletions = returnFiber.deletions; if (deletions === null) { returnFiber.deletions = [childToDelete]; returnFiber.flags |= ChildDeletion; } else { deletions.push(childToDelete); } } function warnNonhydratedInstance(returnFiber: Fiber, fiber: Fiber) { if (__DEV__) { if (didSuspendOrErrorDEV) { // Inside a boundary that already suspended. We're currently rendering the // siblings of a suspended node. The mismatch may be due to the missing // data, so it's probably a false positive. return; } switch (returnFiber.tag) { case HostRoot: { const parentContainer = returnFiber.stateNode.containerInfo; switch (fiber.tag) { case HostSingleton: case HostComponent: const type = fiber.type; const props = fiber.pendingProps; didNotFindHydratableInstanceWithinContainer( parentContainer, type, props, ); break; case HostText: const text = fiber.pendingProps; didNotFindHydratableTextInstanceWithinContainer( parentContainer, text, ); break; case SuspenseComponent: didNotFindHydratableSuspenseInstanceWithinContainer( parentContainer, ); break; } break; } case HostSingleton: case HostComponent: { const parentType = returnFiber.type; const parentProps = returnFiber.memoizedProps; const parentInstance = returnFiber.stateNode; switch (fiber.tag) { case HostSingleton: case HostComponent: { const type = fiber.type; const props = fiber.pendingProps; const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotFindHydratableInstance( parentType, parentProps, parentInstance, type, props, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode, ); break; } case HostText: { const text = fiber.pendingProps; const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotFindHydratableTextInstance( parentType, parentProps, parentInstance, text, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode, ); break; } case SuspenseComponent: { didNotFindHydratableSuspenseInstance( parentType, parentProps, parentInstance, ); break; } } break; } case SuspenseComponent: { const suspenseState: SuspenseState = returnFiber.memoizedState; const parentInstance = suspenseState.dehydrated; if (parentInstance !== null) switch (fiber.tag) { case HostSingleton: case HostComponent: const type = fiber.type; const props = fiber.pendingProps; didNotFindHydratableInstanceWithinSuspenseInstance( parentInstance, type, props, ); break; case HostText: const text = fiber.pendingProps; didNotFindHydratableTextInstanceWithinSuspenseInstance( parentInstance, text, ); break; case SuspenseComponent: didNotFindHydratableSuspenseInstanceWithinSuspenseInstance( parentInstance, ); break; } break; } default: return; } } } function insertNonHydratedInstance(returnFiber: Fiber, fiber: Fiber) { fiber.flags = (fiber.flags & ~Hydrating) | Placement; warnNonhydratedInstance(returnFiber, fiber); } function tryHydrateInstance(fiber: Fiber, nextInstance: any) { // fiber is a HostComponent Fiber const instance = canHydrateInstance( nextInstance, fiber.type, fiber.pendingProps, rootOrSingletonContext, ); if (instance !== null) { fiber.stateNode = (instance: Instance); hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(instance); rootOrSingletonContext = false; return true; } return false; } function tryHydrateText(fiber: Fiber, nextInstance: any) { // fiber is a HostText Fiber const text = fiber.pendingProps; const textInstance = canHydrateTextInstance( nextInstance, text, rootOrSingletonContext, ); if (textInstance !== null) { fiber.stateNode = (textInstance: TextInstance); hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate. nextHydratableInstance = null; return true; } return false; } function tryHydrateSuspense(fiber: Fiber, nextInstance: any) { // fiber is a SuspenseComponent Fiber const suspenseInstance = canHydrateSuspenseInstance( nextInstance, rootOrSingletonContext, ); if (suspenseInstance !== null) { const suspenseState: SuspenseState = { dehydrated: suspenseInstance, treeContext: getSuspendedTreeContext(), retryLane: OffscreenLane, }; fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber. // This simplifies the code for getHostSibling and deleting nodes, // since it doesn't have to consider all Suspense boundaries and // check if they're dehydrated ones or not. const dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); dehydratedFragment.return = fiber; fiber.child = dehydratedFragment; hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into // it during the first pass. Instead, we'll reenter it later. nextHydratableInstance = null; return true; } return false; } function shouldClientRenderOnMismatch(fiber: Fiber) { return ( (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags ); } function throwOnHydrationMismatch(fiber: Fiber) { throw new Error( 'Hydration failed because the initial UI does not match what was ' + 'rendered on the server.', ); } function claimHydratableSingleton(fiber: Fiber): void { if (supportsSingletons) { if (!isHydrating) { return; } const currentRootContainer = getRootHostContainer(); const currentHostContext = getHostContext(); const instance = (fiber.stateNode = resolveSingletonInstance( fiber.type, fiber.pendingProps, currentRootContainer, currentHostContext, false, )); hydrationParentFiber = fiber; rootOrSingletonContext = true; nextHydratableInstance = getFirstHydratableChild(instance); } } function tryToClaimNextHydratableInstance(fiber: Fiber): void { if (!isHydrating) { return; } const initialInstance = nextHydratableInstance; const nextInstance = nextHydratableInstance; if (!nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance((hydrationParentFiber: any), fiber); throwOnHydrationMismatch(fiber); } // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance((hydrationParentFiber: any), fiber); isHydrating = false; hydrationParentFiber = fiber; nextHydratableInstance = initialInstance; return; } const firstAttemptedInstance = nextInstance; if (!tryHydrateInstance(fiber, nextInstance)) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance((hydrationParentFiber: any), fiber); throwOnHydrationMismatch(fiber); } // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextHydratableInstance = getNextHydratableSibling(nextInstance); const prevHydrationParentFiber: Fiber = (hydrationParentFiber: any); if ( !nextHydratableInstance || !tryHydrateInstance(fiber, nextHydratableInstance) ) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance((hydrationParentFiber: any), fiber); isHydrating = false; hydrationParentFiber = fiber; nextHydratableInstance = initialInstance; return; } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); } } function tryToClaimNextHydratableTextInstance(fiber: Fiber): void { if (!isHydrating) { return; } const text = fiber.pendingProps; const isHydratable = isHydratableText(text); const initialInstance = nextHydratableInstance; const nextInstance = nextHydratableInstance; if (!nextInstance || !isHydratable) { // We exclude non hydrabable text because we know there are no matching hydratables. // We either throw or insert depending on the render mode. if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance((hydrationParentFiber: any), fiber); throwOnHydrationMismatch(fiber); } // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance((hydrationParentFiber: any), fiber); isHydrating = false; hydrationParentFiber = fiber; nextHydratableInstance = initialInstance; return; } const firstAttemptedInstance = nextInstance; if (!tryHydrateText(fiber, nextInstance)) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance((hydrationParentFiber: any), fiber); throwOnHydrationMismatch(fiber); } // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextHydratableInstance = getNextHydratableSibling(nextInstance); const prevHydrationParentFiber: Fiber = (hydrationParentFiber: any); if ( !nextHydratableInstance || !tryHydrateText(fiber, nextHydratableInstance) ) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance((hydrationParentFiber: any), fiber); isHydrating = false; hydrationParentFiber = fiber; nextHydratableInstance = initialInstance; return; } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); } } function tryToClaimNextHydratableSuspenseInstance(fiber: Fiber): void { if (!isHydrating) { return; } const initialInstance = nextHydratableInstance; const nextInstance = nextHydratableInstance; if (!nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance((hydrationParentFiber: any), fiber); throwOnHydrationMismatch(fiber); } // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance((hydrationParentFiber: any), fiber); isHydrating = false; hydrationParentFiber = fiber; nextHydratableInstance = initialInstance; return; } const firstAttemptedInstance = nextInstance; if (!tryHydrateSuspense(fiber, nextInstance)) { if (shouldClientRenderOnMismatch(fiber)) { warnNonhydratedInstance((hydrationParentFiber: any), fiber); throwOnHydrationMismatch(fiber); } // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextHydratableInstance = getNextHydratableSibling(nextInstance); const prevHydrationParentFiber: Fiber = (hydrationParentFiber: any); if ( !nextHydratableInstance || !tryHydrateSuspense(fiber, nextHydratableInstance) ) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance((hydrationParentFiber: any), fiber); isHydrating = false; hydrationParentFiber = fiber; nextHydratableInstance = initialInstance; return; } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); } } export function tryToClaimNextHydratableFormMarkerInstance( fiber: Fiber, ): boolean { if (!isHydrating) { return false; } if (nextHydratableInstance) { const markerInstance = canHydrateFormStateMarker( nextHydratableInstance, rootOrSingletonContext, ); if (markerInstance) { // Found the marker instance. nextHydratableInstance = getNextHydratableSibling(markerInstance); // Return true if this marker instance should use the state passed // to hydrateRoot. // TODO: As an optimization, Fizz should only emit these markers if form // state is passed at the root. return isFormStateMarkerMatching(markerInstance); } } // Should have found a marker instance. Throw an error to trigger client // rendering. We don't bother to check if we're in a concurrent root because // useFormState is a new API, so backwards compat is not an issue. throwOnHydrationMismatch(fiber); return false; } function prepareToHydrateHostInstance( fiber: Fiber, hostContext: HostContext, ): void { if (!supportsHydration) { throw new Error( 'Expected prepareToHydrateHostInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } const instance: Instance = fiber.stateNode; const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; hydrateInstance( instance, fiber.type, fiber.memoizedProps, hostContext, fiber, shouldWarnIfMismatchDev, ); } function prepareToHydrateHostTextInstance(fiber: Fiber): boolean { if (!supportsHydration) { throw new Error( 'Expected prepareToHydrateHostTextInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } const textInstance: TextInstance = fiber.stateNode; const textContent: string = fiber.memoizedProps; const shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; const shouldUpdate = hydrateTextInstance( textInstance, textContent, fiber, shouldWarnIfMismatchDev, ); if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. const returnFiber = hydrationParentFiber; if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { const parentContainer = returnFiber.stateNode.containerInfo; const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedContainerTextInstance( parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode, shouldWarnIfMismatchDev, ); if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) { // In concurrent mode we never update the mismatched text, // even if the error was ignored. return false; } break; } case HostSingleton: case HostComponent: { const parentType = returnFiber.type; const parentProps = returnFiber.memoizedProps; const parentInstance = returnFiber.stateNode; const isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedTextInstance( parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode, shouldWarnIfMismatchDev, ); if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) { // In concurrent mode we never update the mismatched text, // even if the error was ignored. return false; } break; } } } } return shouldUpdate; } function prepareToHydrateHostSuspenseInstance(fiber: Fiber): void { if (!supportsHydration) { throw new Error( 'Expected prepareToHydrateHostSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } const suspenseState: null | SuspenseState = fiber.memoizedState; const suspenseInstance: null | SuspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; if (!suspenseInstance) { throw new Error( 'Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } hydrateSuspenseInstance(suspenseInstance, fiber); } function skipPastDehydratedSuspenseInstance( fiber: Fiber, ): null | HydratableInstance { if (!supportsHydration) { throw new Error( 'Expected skipPastDehydratedSuspenseInstance() to never be called. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } const suspenseState: null | SuspenseState = fiber.memoizedState; const suspenseInstance: null | SuspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null; if (!suspenseInstance) { throw new Error( 'Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); } return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber: Fiber): void { hydrationParentFiber = fiber.return; while (hydrationParentFiber) { switch (hydrationParentFiber.tag) { case HostRoot: case HostSingleton: rootOrSingletonContext = true; return; case HostComponent: case SuspenseComponent: rootOrSingletonContext = false; return; default: hydrationParentFiber = hydrationParentFiber.return; } } } function popHydrationState(fiber: Fiber): boolean { if (!supportsHydration) { return false; } if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our // siblings. popToNextHostParent(fiber); isHydrating = true; return false; } let shouldClear = false; if (supportsSingletons) { // With float we never clear the Root, or Singleton instances. We also do not clear Instances // that have singleton text content if ( fiber.tag !== HostRoot && fiber.tag !== HostSingleton && !( fiber.tag === HostComponent && (!shouldDeleteUnhydratedTailInstances(fiber.type) || shouldSetTextContent(fiber.type, fiber.memoizedProps)) ) ) { shouldClear = true; } } else { // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. We also don't delete anything inside the root container. if ( fiber.tag !== HostRoot && (fiber.tag !== HostComponent || (shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) ) { shouldClear = true; } } if (shouldClear) { let nextInstance = nextHydratableInstance; if (nextInstance) { if (shouldClientRenderOnMismatch(fiber)) { warnIfUnhydratedTailNodes(fiber); throwOnHydrationMismatch(fiber); } else { while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } } } popToNextHostParent(fiber); if (fiber.tag === SuspenseComponent) { nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber); } else { nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; } return true; } function hasUnhydratedTailNodes(): boolean { return isHydrating && nextHydratableInstance !== null; } function warnIfUnhydratedTailNodes(fiber: Fiber) { let nextInstance = nextHydratableInstance; while (nextInstance) { warnUnhydratedInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } function resetHydrationState(): void { if (!supportsHydration) { return; } hydrationParentFiber = null; nextHydratableInstance = null; isHydrating = false; didSuspendOrErrorDEV = false; } export function upgradeHydrationErrorsToRecoverable(): void { if (hydrationErrors !== null) { // Successfully completed a forced client render. The errors that occurred // during the hydration attempt are now recovered. We will log them in // commit phase, once the entire tree has finished. queueRecoverableErrors(hydrationErrors); hydrationErrors = null; } } function getIsHydrating(): boolean { return isHydrating; } export function queueHydrationError(error: CapturedValue<mixed>): void { if (hydrationErrors === null) { hydrationErrors = [error]; } else { hydrationErrors.push(error); } } export { warnIfHydrating, enterHydrationState, getIsHydrating, reenterHydrationStateFromDehydratedSuspenseInstance, resetHydrationState, claimHydratableSingleton, tryToClaimNextHydratableInstance, tryToClaimNextHydratableTextInstance, tryToClaimNextHydratableSuspenseInstance, prepareToHydrateHostInstance, prepareToHydrateHostTextInstance, prepareToHydrateHostSuspenseInstance, popHydrationState, hasUnhydratedTailNodes, warnIfUnhydratedTailNodes, };
30.706332
97
0.688382
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'; import type {Container, SuspenseInstance} from '../client/ReactFiberConfigDOM'; import type {DOMEventName} from '../events/DOMEventNames'; import type {EventSystemFlags} from './EventSystemFlags'; import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities'; import { unstable_scheduleCallback as scheduleCallback, unstable_NormalPriority as NormalPriority, } from 'scheduler'; import { getNearestMountedFiber, getContainerFromFiber, getSuspenseInstanceFromFiber, } from 'react-reconciler/src/ReactFiberTreeReflection'; import { findInstanceBlockingEvent, findInstanceBlockingTarget, } from './ReactDOMEventListener'; import {setReplayingEvent, resetReplayingEvent} from './CurrentReplayingEvent'; import { getInstanceFromNode, getClosestInstanceFromNode, getFiberCurrentPropsFromNode, } from '../client/ReactDOMComponentTree'; import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags'; import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities'; import {isRootDehydrated} from 'react-reconciler/src/ReactFiberShellHydration'; import {dispatchReplayedFormAction} from './plugins/FormActionEventPlugin'; import { attemptContinuousHydration, attemptHydrationAtCurrentPriority, } from 'react-reconciler/src/ReactFiberReconciler'; import { runWithPriority as attemptHydrationAtPriority, getCurrentUpdatePriority, } from 'react-reconciler/src/ReactEventPriorities'; import {enableFormActions} from 'shared/ReactFeatureFlags'; // TODO: Upgrade this definition once we're on a newer version of Flow that // has this definition built-in. type PointerEvent = Event & { pointerId: number, relatedTarget: EventTarget | null, ... }; type QueuedReplayableEvent = { blockedOn: null | Container | SuspenseInstance, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, nativeEvent: AnyNativeEvent, targetContainers: Array<EventTarget>, }; let hasScheduledReplayAttempt = false; // The last of each continuous event type. We only need to replay the last one // if the last target was dehydrated. let queuedFocus: null | QueuedReplayableEvent = null; let queuedDrag: null | QueuedReplayableEvent = null; let queuedMouse: null | QueuedReplayableEvent = null; // For pointer events there can be one latest event per pointerId. const queuedPointers: Map<number, QueuedReplayableEvent> = new Map(); const queuedPointerCaptures: Map<number, QueuedReplayableEvent> = new Map(); // We could consider replaying selectionchange and touchmoves too. type QueuedHydrationTarget = { blockedOn: null | Container | SuspenseInstance, target: Node, priority: EventPriority, }; const queuedExplicitHydrationTargets: Array<QueuedHydrationTarget> = []; const discreteReplayableEvents: Array<DOMEventName> = [ 'mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase 'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', // 'submit', // stopPropagation blocks the replay mechanism ]; export function isDiscreteEventThatRequiresHydration( eventType: DOMEventName, ): boolean { return discreteReplayableEvents.indexOf(eventType) > -1; } function createQueuedReplayableEvent( blockedOn: null | Container | SuspenseInstance, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, nativeEvent: AnyNativeEvent, ): QueuedReplayableEvent { return { blockedOn, domEventName, eventSystemFlags, nativeEvent, targetContainers: [targetContainer], }; } // Resets the replaying for this type of continuous event to no event. export function clearIfContinuousEvent( domEventName: DOMEventName, nativeEvent: AnyNativeEvent, ): void { switch (domEventName) { case 'focusin': case 'focusout': queuedFocus = null; break; case 'dragenter': case 'dragleave': queuedDrag = null; break; case 'mouseover': case 'mouseout': queuedMouse = null; break; case 'pointerover': case 'pointerout': { const pointerId = ((nativeEvent: any): PointerEvent).pointerId; queuedPointers.delete(pointerId); break; } case 'gotpointercapture': case 'lostpointercapture': { const pointerId = ((nativeEvent: any): PointerEvent).pointerId; queuedPointerCaptures.delete(pointerId); break; } } } function accumulateOrCreateContinuousQueuedReplayableEvent( existingQueuedEvent: null | QueuedReplayableEvent, blockedOn: null | Container | SuspenseInstance, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, nativeEvent: AnyNativeEvent, ): QueuedReplayableEvent { if ( existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent ) { const queuedEvent = createQueuedReplayableEvent( blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent, ); if (blockedOn !== null) { const fiber = getInstanceFromNode(blockedOn); if (fiber !== null) { // Attempt to increase the priority of this target. attemptContinuousHydration(fiber); } } return queuedEvent; } // If we have already queued this exact event, then it's because // the different event systems have different DOM event listeners. // We can accumulate the flags, and the targetContainers, and // store a single event to be replayed. existingQueuedEvent.eventSystemFlags |= eventSystemFlags; const targetContainers = existingQueuedEvent.targetContainers; if ( targetContainer !== null && targetContainers.indexOf(targetContainer) === -1 ) { targetContainers.push(targetContainer); } return existingQueuedEvent; } export function queueIfContinuousEvent( blockedOn: null | Container | SuspenseInstance, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, nativeEvent: AnyNativeEvent, ): boolean { // These set relatedTarget to null because the replayed event will be treated as if we // moved from outside the window (no target) onto the target once it hydrates. // Instead of mutating we could clone the event. switch (domEventName) { case 'focusin': { const focusEvent = ((nativeEvent: any): FocusEvent); queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent( queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent, ); return true; } case 'dragenter': { const dragEvent = ((nativeEvent: any): DragEvent); queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent( queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent, ); return true; } case 'mouseover': { const mouseEvent = ((nativeEvent: any): MouseEvent); queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent( queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent, ); return true; } case 'pointerover': { const pointerEvent = ((nativeEvent: any): PointerEvent); const pointerId = pointerEvent.pointerId; queuedPointers.set( pointerId, accumulateOrCreateContinuousQueuedReplayableEvent( queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent, ), ); return true; } case 'gotpointercapture': { const pointerEvent = ((nativeEvent: any): PointerEvent); const pointerId = pointerEvent.pointerId; queuedPointerCaptures.set( pointerId, accumulateOrCreateContinuousQueuedReplayableEvent( queuedPointerCaptures.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent, ), ); return true; } } return false; } // Check if this target is unblocked. Returns true if it's unblocked. function attemptExplicitHydrationTarget( queuedTarget: QueuedHydrationTarget, ): void { // TODO: This function shares a lot of logic with findInstanceBlockingEvent. // Try to unify them. It's a bit tricky since it would require two return // values. const targetInst = getClosestInstanceFromNode(queuedTarget.target); if (targetInst !== null) { const nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted !== null) { const tag = nearestMounted.tag; if (tag === SuspenseComponent) { const instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // We're blocked on hydrating this boundary. // Increase its priority. queuedTarget.blockedOn = instance; attemptHydrationAtPriority(queuedTarget.priority, () => { attemptHydrationAtCurrentPriority(nearestMounted); }); return; } } else if (tag === HostRoot) { const root: FiberRoot = nearestMounted.stateNode; if (isRootDehydrated(root)) { queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of // a root other than sync. return; } } } } queuedTarget.blockedOn = null; } export function queueExplicitHydrationTarget(target: Node): void { // TODO: This will read the priority if it's dispatched by the React // event system but not native events. Should read window.event.type, like // we do for updates (getCurrentEventPriority). const updatePriority = getCurrentUpdatePriority(); const queuedTarget: QueuedHydrationTarget = { blockedOn: null, target: target, priority: updatePriority, }; let i = 0; for (; i < queuedExplicitHydrationTargets.length; i++) { // Stop once we hit the first target with lower priority than if ( !isHigherEventPriority( updatePriority, queuedExplicitHydrationTargets[i].priority, ) ) { break; } } queuedExplicitHydrationTargets.splice(i, 0, queuedTarget); if (i === 0) { attemptExplicitHydrationTarget(queuedTarget); } } function attemptReplayContinuousQueuedEvent( queuedEvent: QueuedReplayableEvent, ): boolean { if (queuedEvent.blockedOn !== null) { return false; } const targetContainers = queuedEvent.targetContainers; while (targetContainers.length > 0) { const nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent); if (nextBlockedOn === null) { const nativeEvent = queuedEvent.nativeEvent; const nativeEventClone = new nativeEvent.constructor( nativeEvent.type, (nativeEvent: any), ); setReplayingEvent(nativeEventClone); nativeEvent.target.dispatchEvent(nativeEventClone); resetReplayingEvent(); } else { // We're still blocked. Try again later. const fiber = getInstanceFromNode(nextBlockedOn); if (fiber !== null) { attemptContinuousHydration(fiber); } queuedEvent.blockedOn = nextBlockedOn; return false; } // This target container was successfully dispatched. Try the next. targetContainers.shift(); } return true; } function attemptReplayContinuousQueuedEventInMap( queuedEvent: QueuedReplayableEvent, key: number, map: Map<number, QueuedReplayableEvent>, ): void { if (attemptReplayContinuousQueuedEvent(queuedEvent)) { map.delete(key); } } function replayUnblockedEvents() { hasScheduledReplayAttempt = false; // Replay any continuous events. if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) { queuedFocus = null; } if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) { queuedDrag = null; } if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) { queuedMouse = null; } queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap); queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap); } function scheduleCallbackIfUnblocked( queuedEvent: QueuedReplayableEvent, unblocked: Container | SuspenseInstance, ) { if (queuedEvent.blockedOn === unblocked) { queuedEvent.blockedOn = null; if (!hasScheduledReplayAttempt) { hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are // now unblocked. This first might not actually be unblocked yet. // We could check it early to avoid scheduling an unnecessary callback. scheduleCallback(NormalPriority, replayUnblockedEvents); } } } type FormAction = FormData => void | Promise<void>; type FormReplayingQueue = Array<any>; // [form, submitter or action, formData...] let lastScheduledReplayQueue: null | FormReplayingQueue = null; function replayUnblockedFormActions(formReplayingQueue: FormReplayingQueue) { if (lastScheduledReplayQueue === formReplayingQueue) { lastScheduledReplayQueue = null; } for (let i = 0; i < formReplayingQueue.length; i += 3) { const form: HTMLFormElement = formReplayingQueue[i]; const submitterOrAction: | null | HTMLInputElement | HTMLButtonElement | FormAction = formReplayingQueue[i + 1]; const formData: FormData = formReplayingQueue[i + 2]; if (typeof submitterOrAction !== 'function') { // This action is not hydrated yet. This might be because it's blocked on // a different React instance or higher up our tree. const blockedOn = findInstanceBlockingTarget(submitterOrAction || form); if (blockedOn === null) { // We're not blocked but we don't have an action. This must mean that // this is in another React instance. We'll just skip past it. continue; } else { // We're blocked on something in this React instance. We'll retry later. break; } } const formInst = getInstanceFromNode(form); if (formInst !== null) { // This is part of our instance. // We're ready to replay this. Let's delete it from the queue. formReplayingQueue.splice(i, 3); i -= 3; dispatchReplayedFormAction(formInst, form, submitterOrAction, formData); // Continue without incrementing the index. continue; } // This form must've been part of a different React instance. // If we want to preserve ordering between React instances on the same root // we'd need some way for the other instance to ping us when it's done. // We'll just skip this and let the other instance execute it. } } function scheduleReplayQueueIfNeeded(formReplayingQueue: FormReplayingQueue) { // Schedule a callback to execute any unblocked form actions in. // We only keep track of the last queue which means that if multiple React oscillate // commits, we could schedule more callbacks than necessary but it's not a big deal // and we only really except one instance. if (lastScheduledReplayQueue !== formReplayingQueue) { lastScheduledReplayQueue = formReplayingQueue; scheduleCallback(NormalPriority, () => replayUnblockedFormActions(formReplayingQueue), ); } } export function retryIfBlockedOn( unblocked: Container | SuspenseInstance, ): void { if (queuedFocus !== null) { scheduleCallbackIfUnblocked(queuedFocus, unblocked); } if (queuedDrag !== null) { scheduleCallbackIfUnblocked(queuedDrag, unblocked); } if (queuedMouse !== null) { scheduleCallbackIfUnblocked(queuedMouse, unblocked); } const unblock = (queuedEvent: QueuedReplayableEvent) => scheduleCallbackIfUnblocked(queuedEvent, unblocked); queuedPointers.forEach(unblock); queuedPointerCaptures.forEach(unblock); for (let i = 0; i < queuedExplicitHydrationTargets.length; i++) { const queuedTarget = queuedExplicitHydrationTargets[i]; if (queuedTarget.blockedOn === unblocked) { queuedTarget.blockedOn = null; } } while (queuedExplicitHydrationTargets.length > 0) { const nextExplicitTarget = queuedExplicitHydrationTargets[0]; if (nextExplicitTarget.blockedOn !== null) { // We're still blocked. break; } else { attemptExplicitHydrationTarget(nextExplicitTarget); if (nextExplicitTarget.blockedOn === null) { // We're unblocked. queuedExplicitHydrationTargets.shift(); } } } if (enableFormActions) { // Check the document if there are any queued form actions. const root = unblocked.getRootNode(); const formReplayingQueue: void | FormReplayingQueue = (root: any) .$$reactFormReplay; if (formReplayingQueue != null) { for (let i = 0; i < formReplayingQueue.length; i += 3) { const form: HTMLFormElement = formReplayingQueue[i]; const submitterOrAction: | null | HTMLInputElement | HTMLButtonElement | FormAction = formReplayingQueue[i + 1]; const formProps = getFiberCurrentPropsFromNode(form); if (typeof submitterOrAction === 'function') { // This action has already resolved. We're just waiting to dispatch it. if (!formProps) { // This was not part of this React instance. It might have been recently // unblocking us from dispatching our events. So let's make sure we schedule // a retry. scheduleReplayQueueIfNeeded(formReplayingQueue); } continue; } let target: Node = form; if (formProps) { // This form belongs to this React instance but the submitter might // not be done yet. let action: null | FormAction = null; const submitter = submitterOrAction; if (submitter && submitter.hasAttribute('formAction')) { // The submitter is the one that is responsible for the action. target = submitter; const submitterProps = getFiberCurrentPropsFromNode(submitter); if (submitterProps) { // The submitter is part of this instance. action = (submitterProps: any).formAction; } else { const blockedOn = findInstanceBlockingTarget(target); if (blockedOn !== null) { // The submitter is not hydrated yet. We'll wait for it. continue; } // The submitter must have been a part of a different React instance. // Except the form isn't. We don't dispatch actions in this scenario. } } else { action = (formProps: any).action; } if (typeof action === 'function') { formReplayingQueue[i + 1] = action; } else { // Something went wrong so let's just delete this action. formReplayingQueue.splice(i, 3); i -= 3; } // Schedule a replay in case this unblocked something. scheduleReplayQueueIfNeeded(formReplayingQueue); continue; } // Something above this target is still blocked so we can't continue yet. // We're not sure if this target is actually part of this React instance // yet. It could be a different React as a child but at least some parent is. // We must continue for any further queued actions. } } } }
32.407591
88
0.687562
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'; const path = require('path'); const {ESLint} = require('eslint'); function getESLintInstance(format) { return new ESLint({ useEslintrc: false, overrideConfigFile: __dirname + `../../../scripts/rollup/validate/eslintrc.${format}.js`, ignore: false, }); } const esLints = { cjs: getESLintInstance('cjs'), }; // Performs sanity checks on bundles *built* by Rollup. // Helps catch Rollup regressions. async function lint(folder) { console.log(`Linting ` + folder); const eslint = esLints.cjs; const results = await eslint.lintFiles([ __dirname + '/' + folder + '/cjs/react-jsx-dev-runtime.development.js', __dirname + '/' + folder + '/cjs/react-jsx-dev-runtime.production.min.js', __dirname + '/' + folder + '/cjs/react-jsx-runtime.development.js', __dirname + '/' + folder + '/cjs/react-jsx-runtime.production.min.js', ]); if ( results.some(result => result.errorCount > 0 || result.warningCount > 0) ) { process.exitCode = 1; console.log(`Failed`); const formatter = await eslint.loadFormatter('stylish'); const resultText = formatter.format(results); console.log(resultText); } } async function lintEverything() { console.log(`Linting known bundles...`); await lint('react-14'); await lint('react-15'); await lint('react-16'); await lint('react-17'); } lintEverything().catch(error => { process.exitCode = 1; console.error(error); });
25.03125
78
0.657057
owtf
'use strict'; const path = require('path'); const fs = require('fs'); const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); // Make sure any symlinks in the project folder are resolved: // https://github.com/facebook/create-react-app/issues/637 const appDirectory = fs.realpathSync(process.cwd()); const resolveApp = relativePath => path.resolve(appDirectory, relativePath); // We use `PUBLIC_URL` environment variable or "homepage" field to infer // "public path" at which the app is served. // webpack needs to know it to put the right <script> hrefs into HTML even in // single-page apps that may serve index.html for nested URLs like /todos/42. // We can't use a relative path in HTML because we don't want to load something // like /todos/42/static/js/bundle.7289d.js. We have to know the root. const publicUrlOrPath = getPublicUrlOrPath( process.env.NODE_ENV === 'development', require(resolveApp('package.json')).homepage, process.env.PUBLIC_URL ); const buildPath = process.env.BUILD_PATH || 'build'; const moduleFileExtensions = [ 'web.mjs', 'mjs', 'web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', ]; // Resolve file paths in the same order as webpack const resolveModule = (resolveFn, filePath) => { const extension = moduleFileExtensions.find(extension => fs.existsSync(resolveFn(`${filePath}.${extension}`)) ); if (extension) { return resolveFn(`${filePath}.${extension}`); } return resolveFn(`${filePath}.js`); }; // config after eject: we're in ./config/ module.exports = { dotenv: resolveApp('.env'), appPath: resolveApp('.'), appBuild: resolveApp(buildPath), appPublic: resolveApp('public'), appIndexJs: resolveModule(resolveApp, 'src/index'), appPackageJson: resolveApp('package.json'), appSrc: resolveApp('src'), appTsConfig: resolveApp('tsconfig.json'), appJsConfig: resolveApp('jsconfig.json'), yarnLockFile: resolveApp('yarn.lock'), testsSetup: resolveModule(resolveApp, 'src/setupTests'), appNodeModules: resolveApp('node_modules'), appWebpackCache: resolveApp('node_modules/.cache'), appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'), swSrc: resolveModule(resolveApp, 'src/service-worker'), publicUrlOrPath, }; module.exports.moduleFileExtensions = moduleFileExtensions;
30.824324
79
0.717502
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 {FiberRoot} from './ReactInternalTypes'; import type {RootState} from './ReactFiberRoot'; // This is imported by the event replaying implementation in React DOM. It's // in a separate file to break a circular dependency between the renderer and // the reconciler. export function isRootDehydrated(root: FiberRoot): boolean { const currentState: RootState = root.current.memoizedState; return currentState.isDehydrated; }
31.15
77
0.752336
PenetrationTestingScripts
/* global chrome */ import nullthrows from 'nullthrows'; // We run scripts on the page via the service worker (background/index.js) for // Manifest V3 extensions (Chrome & Edge). // We need to inject this code for Firefox only because it does not support ExecutionWorld.MAIN // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/ExecutionWorld // In this content script we have access to DOM, but don't have access to the webpage's window, // so we inject this inline script tag into the webpage (allowed in Manifest V2). function injectScriptSync(src) { let code = ''; const request = new XMLHttpRequest(); request.addEventListener('load', function () { code = this.responseText; }); request.open('GET', src, false); request.send(); const script = document.createElement('script'); script.textContent = code; // This script runs before the <head> element is created, // so we add the script to <html> instead. nullthrows(document.documentElement).appendChild(script); nullthrows(script.parentNode).removeChild(script); } let lastSentDevToolsHookMessage; // We want to detect when a renderer attaches, and notify the "background page" // (which is shared between tabs and can highlight the React icon). // Currently we are in "content script" context, so we can't listen to the hook directly // (it will be injected directly into the page). // So instead, the hook will use postMessage() to pass message to us here. // And when this happens, we'll send a message to the "background page". window.addEventListener('message', function onMessage({data, source}) { if (source !== window || !data) { return; } // We keep this logic here and not in `proxy.js`, because proxy content script is injected later at `document_end` if (data.source === 'react-devtools-hook') { const {source: messageSource, payload} = data; const message = {source: messageSource, payload}; lastSentDevToolsHookMessage = message; chrome.runtime.sendMessage(message); } }); // NOTE: Firefox WebExtensions content scripts are still alive and not re-injected // while navigating the history to a document that has not been destroyed yet, // replay the last detection result if the content script is active and the // document has been hidden and shown again. window.addEventListener('pageshow', function ({target}) { if (!lastSentDevToolsHookMessage || target !== window.document) { return; } chrome.runtime.sendMessage(lastSentDevToolsHookMessage); }); if (__IS_FIREFOX__) { injectScriptSync(chrome.runtime.getURL('build/renderer.js')); // Inject a __REACT_DEVTOOLS_GLOBAL_HOOK__ global for React to interact with. // Only do this for HTML documents though, to avoid e.g. breaking syntax highlighting for XML docs. switch (document.contentType) { case 'text/html': case 'application/xhtml+xml': { injectScriptSync(chrome.runtime.getURL('build/installHook.js')); break; } } }
37.87013
116
0.726939
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 {Thenable} from 'shared/ReactTypes.js'; import type {Response} from 'react-client/src/ReactFlightClient'; import type {Readable} from 'stream'; import { createResponse, getRoot, reportGlobalError, processBinaryChunk, close, } from 'react-client/src/ReactFlightClient'; import {createServerReference as createServerReferenceImpl} from 'react-client/src/ReactFlightReplyClient'; function noServerCall() { throw new Error( 'Server Functions cannot be called during initial render. ' + 'This would create a fetch waterfall. Try to use a Server Component ' + 'to pass data to Client Components instead.', ); } export function createServerReference<A: Iterable<any>, T>( id: any, callServer: any, ): (...A) => Promise<T> { return createServerReferenceImpl(id, noServerCall); } export type Options = { nonce?: string, }; function createFromNodeStream<T>( stream: Readable, moduleRootPath: string, moduleBaseURL: string, options?: Options, ): Thenable<T> { const response: Response = createResponse( moduleRootPath, moduleBaseURL, noServerCall, options && typeof options.nonce === 'string' ? options.nonce : undefined, ); stream.on('data', chunk => { processBinaryChunk(response, chunk); }); stream.on('error', error => { reportGlobalError(response, error); }); stream.on('end', () => close(response)); return getRoot(response); } export {createFromNodeStream};
23.5
107
0.704505
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 */ throw new Error( 'The React Server cannot be used outside a react-server environment. ' + 'You must configure Node.js using the `--conditions react-server` flag.', );
26
77
0.700265
cybersecurity-penetration-testing
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from './ReactInternalTypes'; import type {Lanes} from './ReactFiberLane'; import type {UpdateQueue} from './ReactFiberClassUpdateQueue'; import { LayoutStatic, Update, Snapshot, MountLayoutDev, } from './ReactFiberFlags'; import { debugRenderPhaseSideEffectsForStrictMode, disableLegacyContext, enableDebugTracing, enableSchedulingProfiler, enableLazyContextPropagation, } from 'shared/ReactFeatureFlags'; import ReactStrictModeWarnings from './ReactStrictModeWarnings'; import {isMounted} from './ReactFiberTreeReflection'; import {get as getInstance, set as setInstance} from 'shared/ReactInstanceMap'; import shallowEqual from 'shared/shallowEqual'; import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; import getComponentNameFromType from 'shared/getComponentNameFromType'; import assign from 'shared/assign'; import isArray from 'shared/isArray'; import {REACT_CONTEXT_TYPE, REACT_PROVIDER_TYPE} from 'shared/ReactSymbols'; import {resolveDefaultProps} from './ReactFiberLazyComponent'; import { DebugTracingMode, NoMode, StrictLegacyMode, StrictEffectsMode, } from './ReactTypeOfMode'; import { enqueueUpdate, entangleTransitions, processUpdateQueue, checkHasForceUpdateAfterProcessing, resetHasForceUpdateBeforeProcessing, createUpdate, ReplaceState, ForceUpdate, initializeUpdateQueue, cloneUpdateQueue, } from './ReactFiberClassUpdateQueue'; import {NoLanes} from './ReactFiberLane'; import { cacheContext, getMaskedContext, getUnmaskedContext, hasContextChanged, emptyContextObject, } from './ReactFiberContext'; import {readContext, checkIfContextChanged} from './ReactFiberNewContext'; import {requestUpdateLane, scheduleUpdateOnFiber} from './ReactFiberWorkLoop'; import {logForceUpdateScheduled, logStateUpdateScheduled} from './DebugTracing'; import { markForceUpdateScheduled, markStateUpdateScheduled, setIsStrictModeForDevtools, } from './ReactFiberDevToolsHook'; const fakeInternalInstance: { _processChildContext?: () => empty, } = {}; let didWarnAboutStateAssignmentForComponent; let didWarnAboutUninitializedState; let didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; let didWarnAboutLegacyLifecyclesAndDerivedState; let didWarnAboutUndefinedDerivedState; let didWarnAboutDirectlyAssigningPropsToState; let didWarnAboutContextTypeAndContextTypes; let didWarnAboutInvalidateContextType; let didWarnOnInvalidCallback; if (__DEV__) { didWarnAboutStateAssignmentForComponent = new Set<string>(); didWarnAboutUninitializedState = new Set<string>(); didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set<string>(); didWarnAboutLegacyLifecyclesAndDerivedState = new Set<string>(); didWarnAboutDirectlyAssigningPropsToState = new Set<string>(); didWarnAboutUndefinedDerivedState = new Set<string>(); didWarnAboutContextTypeAndContextTypes = new Set<string>(); didWarnAboutInvalidateContextType = new Set<string>(); didWarnOnInvalidCallback = new Set<string>(); // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. Object.defineProperty(fakeInternalInstance, '_processChildContext', { enumerable: false, value: function (): empty { throw new Error( '_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).', ); }, }); Object.freeze(fakeInternalInstance); } function warnOnInvalidCallback(callback: mixed, callerName: string) { if (__DEV__) { if (callback === null || typeof callback === 'function') { return; } const key = callerName + '_' + (callback: any); if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); console.error( '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback, ); } } } function warnOnUndefinedDerivedState(type: any, partialState: any) { if (__DEV__) { if (partialState === undefined) { const componentName = getComponentNameFromType(type) || 'Component'; if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); console.error( '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName, ); } } } } function applyDerivedStateFromProps( workInProgress: Fiber, ctor: any, getDerivedStateFromProps: (props: any, state: any) => any, nextProps: any, ) { const prevState = workInProgress.memoizedState; let partialState = getDerivedStateFromProps(nextProps, prevState); if (__DEV__) { if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { // Invoke the function an extra time to help detect side-effects. partialState = getDerivedStateFromProps(nextProps, prevState); } finally { setIsStrictModeForDevtools(false); } } warnOnUndefinedDerivedState(ctor, partialState); } // Merge the partial state and the previous state. const memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. if (workInProgress.lanes === NoLanes) { // Queue is always non-null for classes const updateQueue: UpdateQueue<any> = (workInProgress.updateQueue: any); updateQueue.baseState = memoizedState; } } const classComponentUpdater = { isMounted, // $FlowFixMe[missing-local-annot] enqueueSetState(inst: any, payload: any, callback) { const fiber = getInstance(inst); const lane = requestUpdateLane(fiber); const update = createUpdate(lane); update.payload = payload; if (callback !== undefined && callback !== null) { if (__DEV__) { warnOnInvalidCallback(callback, 'setState'); } update.callback = callback; } const root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane); entangleTransitions(root, fiber, lane); } if (__DEV__) { if (enableDebugTracing) { if (fiber.mode & DebugTracingMode) { const name = getComponentNameFromFiber(fiber) || 'Unknown'; logStateUpdateScheduled(name, lane, payload); } } } if (enableSchedulingProfiler) { markStateUpdateScheduled(fiber, lane); } }, enqueueReplaceState(inst: any, payload: any, callback: null) { const fiber = getInstance(inst); const lane = requestUpdateLane(fiber); const update = createUpdate(lane); update.tag = ReplaceState; update.payload = payload; if (callback !== undefined && callback !== null) { if (__DEV__) { warnOnInvalidCallback(callback, 'replaceState'); } update.callback = callback; } const root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane); entangleTransitions(root, fiber, lane); } if (__DEV__) { if (enableDebugTracing) { if (fiber.mode & DebugTracingMode) { const name = getComponentNameFromFiber(fiber) || 'Unknown'; logStateUpdateScheduled(name, lane, payload); } } } if (enableSchedulingProfiler) { markStateUpdateScheduled(fiber, lane); } }, // $FlowFixMe[missing-local-annot] enqueueForceUpdate(inst: any, callback) { const fiber = getInstance(inst); const lane = requestUpdateLane(fiber); const update = createUpdate(lane); update.tag = ForceUpdate; if (callback !== undefined && callback !== null) { if (__DEV__) { warnOnInvalidCallback(callback, 'forceUpdate'); } update.callback = callback; } const root = enqueueUpdate(fiber, update, lane); if (root !== null) { scheduleUpdateOnFiber(root, fiber, lane); entangleTransitions(root, fiber, lane); } if (__DEV__) { if (enableDebugTracing) { if (fiber.mode & DebugTracingMode) { const name = getComponentNameFromFiber(fiber) || 'Unknown'; logForceUpdateScheduled(name, lane); } } } if (enableSchedulingProfiler) { markForceUpdateScheduled(fiber, lane); } }, }; function checkShouldComponentUpdate( workInProgress: Fiber, ctor: any, oldProps: any, newProps: any, oldState: any, newState: any, nextContext: any, ) { const instance = workInProgress.stateNode; if (typeof instance.shouldComponentUpdate === 'function') { let shouldUpdate = instance.shouldComponentUpdate( newProps, newState, nextContext, ); if (__DEV__) { if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { // Invoke the function an extra time to help detect side-effects. shouldUpdate = instance.shouldComponentUpdate( newProps, newState, nextContext, ); } finally { setIsStrictModeForDevtools(false); } } if (shouldUpdate === undefined) { console.error( '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component', ); } } return shouldUpdate; } if (ctor.prototype && ctor.prototype.isPureReactComponent) { return ( !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) ); } return true; } function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) { const instance = workInProgress.stateNode; if (__DEV__) { const name = getComponentNameFromType(ctor) || 'Component'; const renderPresent = instance.render; if (!renderPresent) { if (ctor.prototype && typeof ctor.prototype.render === 'function') { console.error( '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name, ); } else { console.error( '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name, ); } } if ( instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state ) { console.error( 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name, ); } if ( instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved ) { console.error( 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name, ); } if (instance.propTypes) { console.error( 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name, ); } if (instance.contextType) { console.error( 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name, ); } if (disableLegacyContext) { if (ctor.childContextTypes) { console.error( '%s uses the legacy childContextTypes API which is no longer supported. ' + 'Use React.createContext() instead.', name, ); } if (ctor.contextTypes) { console.error( '%s uses the legacy contextTypes API which is no longer supported. ' + 'Use React.createContext() with static contextType instead.', name, ); } } else { if (instance.contextTypes) { console.error( 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name, ); } if ( ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor) ) { didWarnAboutContextTypeAndContextTypes.add(ctor); console.error( '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name, ); } } if (typeof instance.componentShouldUpdate === 'function') { console.error( '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name, ); } if ( ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined' ) { console.error( '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component', ); } if (typeof instance.componentDidUnmount === 'function') { console.error( '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name, ); } if (typeof instance.componentDidReceiveProps === 'function') { console.error( '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name, ); } if (typeof instance.componentWillRecieveProps === 'function') { console.error( '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name, ); } if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { console.error( '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name, ); } const hasMutatedProps = instance.props !== newProps; if (instance.props !== undefined && hasMutatedProps) { console.error( '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name, ); } if (instance.defaultProps) { console.error( 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name, ); } if ( typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor) ) { didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); console.error( '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor), ); } if (typeof instance.getDerivedStateFromProps === 'function') { console.error( '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name, ); } if (typeof instance.getDerivedStateFromError === 'function') { console.error( '%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name, ); } if (typeof ctor.getSnapshotBeforeUpdate === 'function') { console.error( '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name, ); } const state = instance.state; if (state && (typeof state !== 'object' || isArray(state))) { console.error('%s.state: must be set to an object or null', name); } if ( typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object' ) { console.error( '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name, ); } } } function adoptClassInstance(workInProgress: Fiber, instance: any): void { instance.updater = classComponentUpdater; workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates setInstance(instance, workInProgress); if (__DEV__) { instance._reactInternalInstance = fakeInternalInstance; } } function constructClassInstance( workInProgress: Fiber, ctor: any, props: any, ): any { let isLegacyContextConsumer = false; let unmaskedContext = emptyContextObject; let context = emptyContextObject; const contextType = ctor.contextType; if (__DEV__) { if ('contextType' in ctor) { const isValid = // Allow null for conditional declaration contextType === null || (contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined); // Not a <Context.Consumer> if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); let addendum = ''; if (contextType === undefined) { addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; } else if (typeof contextType !== 'object') { addendum = ' However, it is set to a ' + typeof contextType + '.'; } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { addendum = ' Did you accidentally pass the Context.Provider instead?'; } else if (contextType._context !== undefined) { // <Context.Consumer> addendum = ' Did you accidentally pass the Context.Consumer instead?'; } else { addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; } console.error( '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum, ); } } } if (typeof contextType === 'object' && contextType !== null) { context = readContext((contextType: any)); } else if (!disableLegacyContext) { unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); const contextTypes = ctor.contextTypes; isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; } let instance = new ctor(props, context); // Instantiate twice to help detect side-effects. if (__DEV__) { if ( debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictLegacyMode ) { setIsStrictModeForDevtools(true); try { instance = new ctor(props, context); // eslint-disable-line no-new } finally { setIsStrictModeForDevtools(false); } } } const state = (workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null); adoptClassInstance(workInProgress, instance); if (__DEV__) { if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { const componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); console.error( '`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName, ); } } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. if ( typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function' ) { let foundWillMountName = null; let foundWillReceivePropsName = null; let foundWillUpdateName = null; if ( typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true ) { foundWillMountName = 'componentWillMount'; } else if (typeof instance.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if ( typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true ) { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if ( typeof instance.UNSAFE_componentWillReceiveProps === 'function' ) { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if ( typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true ) { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if ( foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null ) { const componentName = getComponentNameFromType(ctor) || 'Component'; const newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(componentName); console.error( 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', componentName, newApiName, foundWillMountName !== null ? `\n ${foundWillMountName}` : '', foundWillReceivePropsName !== null ? `\n ${foundWillReceivePropsName}` : '', foundWillUpdateName !== null ? `\n ${foundWillUpdateName}` : '', ); } } } } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } return instance; } function callComponentWillMount(workInProgress: Fiber, instance: any) { const oldState = instance.state; if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } if (oldState !== instance.state) { if (__DEV__) { console.error( '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component', ); } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } function callComponentWillReceiveProps( workInProgress: Fiber, instance: any, newProps: any, nextContext: any, ) { const oldState = instance.state; if (typeof instance.componentWillReceiveProps === 'function') { instance.componentWillReceiveProps(newProps, nextContext); } if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } if (instance.state !== oldState) { if (__DEV__) { const componentName = getComponentNameFromFiber(workInProgress) || 'Component'; if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); console.error( '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName, ); } } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } // Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance( workInProgress: Fiber, ctor: any, newProps: any, renderLanes: Lanes, ): void { if (__DEV__) { checkClassInstance(workInProgress, ctor, newProps); } const instance = workInProgress.stateNode; instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = {}; initializeUpdateQueue(workInProgress); const contextType = ctor.contextType; if (typeof contextType === 'object' && contextType !== null) { instance.context = readContext(contextType); } else if (disableLegacyContext) { instance.context = emptyContextObject; } else { const unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); instance.context = getMaskedContext(workInProgress, unmaskedContext); } if (__DEV__) { if (instance.state === newProps) { const componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); console.error( '%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName, ); } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning( workInProgress, instance, ); } ReactStrictModeWarnings.recordUnsafeLifecycleWarnings( workInProgress, instance, ); } instance.state = workInProgress.memoizedState; const getDerivedStateFromProps = ctor.getDerivedStateFromProps; if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps( workInProgress, ctor, getDerivedStateFromProps, newProps, ); instance.state = workInProgress.memoizedState; } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if ( typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function') ) { callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. processUpdateQueue(workInProgress, newProps, instance, renderLanes); instance.state = workInProgress.memoizedState; } if (typeof instance.componentDidMount === 'function') { workInProgress.flags |= Update | LayoutStatic; } if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags |= MountLayoutDev; } } function resumeMountClassInstance( workInProgress: Fiber, ctor: any, newProps: any, renderLanes: Lanes, ): boolean { const instance = workInProgress.stateNode; const oldProps = workInProgress.memoizedProps; instance.props = oldProps; const oldContext = instance.context; const contextType = ctor.contextType; let nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { const nextLegacyUnmaskedContext = getUnmaskedContext( workInProgress, ctor, true, ); nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); } const getDerivedStateFromProps = ctor.getDerivedStateFromProps; const hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function') ) { if (oldProps !== newProps || oldContext !== nextContext) { callComponentWillReceiveProps( workInProgress, instance, newProps, nextContext, ); } } resetHasForceUpdateBeforeProcessing(); const oldState = workInProgress.memoizedState; let newState = (instance.state = oldState); processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if ( oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() ) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { workInProgress.flags |= Update | LayoutStatic; } if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags |= MountLayoutDev; } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps( workInProgress, ctor, getDerivedStateFromProps, newProps, ); newState = workInProgress.memoizedState; } const shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate( workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext, ); if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function') ) { if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } } if (typeof instance.componentDidMount === 'function') { workInProgress.flags |= Update | LayoutStatic; } if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags |= MountLayoutDev; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { workInProgress.flags |= Update | LayoutStatic; } if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) { workInProgress.flags |= MountLayoutDev; } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } // Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance( current: Fiber, workInProgress: Fiber, ctor: any, newProps: any, renderLanes: Lanes, ): boolean { const instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); const unresolvedOldProps = workInProgress.memoizedProps; const oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); instance.props = oldProps; const unresolvedNewProps = workInProgress.pendingProps; const oldContext = instance.context; const contextType = ctor.contextType; let nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else if (!disableLegacyContext) { const nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } const getDerivedStateFromProps = ctor.getDerivedStateFromProps; const hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function') ) { if ( unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext ) { callComponentWillReceiveProps( workInProgress, instance, newProps, nextContext, ); } } resetHasForceUpdateBeforeProcessing(); const oldState = workInProgress.memoizedState; let newState = (instance.state = oldState); processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if ( unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !( enableLazyContextPropagation && current !== null && current.dependencies !== null && checkIfContextChanged(current.dependencies) ) ) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if ( unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState ) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if ( unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState ) { workInProgress.flags |= Snapshot; } } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps( workInProgress, ctor, getDerivedStateFromProps, newProps, ); newState = workInProgress.memoizedState; } const shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate( workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext, ) || // TODO: In some cases, we'll end up checking if context has changed twice, // both before and after `shouldComponentUpdate` has been called. Not ideal, // but I'm loath to refactor this function. This only happens for memoized // components so it's not that common. (enableLazyContextPropagation && current !== null && current.dependencies !== null && checkIfContextChanged(current.dependencies)); if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if ( !hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function') ) { if (typeof instance.componentWillUpdate === 'function') { instance.componentWillUpdate(newProps, newState, nextContext); } if (typeof instance.UNSAFE_componentWillUpdate === 'function') { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } } if (typeof instance.componentDidUpdate === 'function') { workInProgress.flags |= Update; } if (typeof instance.getSnapshotBeforeUpdate === 'function') { workInProgress.flags |= Snapshot; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if ( unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState ) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if ( unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState ) { workInProgress.flags |= Snapshot; } } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } export { adoptClassInstance, constructClassInstance, mountClassInstance, resumeMountClassInstance, updateClassInstance, };
32.447581
104
0.662391
owtf
function getProperty(propertyName) { return el => el[propertyName]; } function getAttribute(attributeName) { return el => { if (el.namespaceURI === '') { throw new Error('Not an HTML element.'); } return el.getAttribute(attributeName); }; } function getSVGProperty(propertyName) { return el => el[propertyName]; } function getSVGAttribute(attributeName) { return el => { if (el.namespaceURI !== 'http://www.w3.org/2000/svg') { throw new Error('Not an SVG element.'); } return el.getAttribute(attributeName); }; } const attributes = [ {name: 'about', read: getAttribute('about')}, {name: 'aBoUt', read: getAttribute('about')}, { name: 'accent-Height', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('accent-height'), }, { name: 'accent-height', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('accent-height'), }, { name: 'accentHeight', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('accent-height'), }, {name: 'accept', tagName: 'input'}, {name: 'accept-charset', tagName: 'form', read: getProperty('acceptCharset')}, {name: 'accept-Charset', tagName: 'form', read: getProperty('acceptCharset')}, {name: 'acceptCharset', tagName: 'form'}, {name: 'accessKey'}, { name: 'accumulate', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('accumulate'), }, {name: 'action', tagName: 'form', overrideStringValue: 'https://reactjs.com'}, { name: 'additive', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('additive'), }, { name: 'alignment-baseline', containerTagName: 'svg', tagName: 'textPath', read: getSVGAttribute('alignment-baseline'), }, { name: 'alignmentBaseline', containerTagName: 'svg', tagName: 'textPath', read: getSVGAttribute('alignment-baseline'), }, { name: 'allowFullScreen', tagName: 'iframe', read: getProperty('allowFullscreen'), }, { name: 'allowfullscreen', tagName: 'iframe', read: getProperty('allowFullscreen'), }, {name: 'allowFullscreen', tagName: 'iframe'}, { name: 'allowReorder', containerTagName: 'svg', tagName: 'switch', read: getSVGAttribute('allowReorder'), }, { name: 'alphabetic', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('alphabetic'), }, {name: 'alt', tagName: 'img'}, { name: 'amplitude', containerTagName: 'svg', tagName: 'feFuncA', read: getSVGProperty('amplitude'), }, { name: 'arabic-form', containerTagName: 'svg', tagName: 'glyph', read: getSVGAttribute('arabic-form'), }, { name: 'arabicForm', containerTagName: 'svg', tagName: 'glyph', read: getSVGAttribute('arabic-form'), }, {name: 'aria', read: getAttribute('aria')}, {name: 'aria-', read: getAttribute('aria-')}, {name: 'aria-invalidattribute', read: getAttribute('aria-invalidattribute')}, {name: 'as', tagName: 'link'}, { name: 'ascent', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('ascent'), }, {name: 'async', tagName: 'script'}, { name: 'attributeName', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('attributeName'), }, { name: 'attributeType', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('attributeType'), }, { name: 'autoCapitalize', tagName: 'input', read: getProperty('autocapitalize'), overrideStringValue: 'words', }, { name: 'autoComplete', tagName: 'input', overrideStringValue: 'email', read: getProperty('autocomplete'), }, { name: 'autoCorrect', tagName: 'input', overrideStringValue: 'off', read: getAttribute('autocorrect'), }, {name: 'autoPlay', tagName: 'video', read: getProperty('autoplay')}, { name: 'autoReverse', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('autoreverse'), }, {name: 'autoSave', tagName: 'input', read: getAttribute('autosave')}, { name: 'azimuth', containerTagName: 'svg', tagName: 'feDistantLight', read: getSVGProperty('azimuth'), }, { name: 'baseFrequency', containerTagName: 'svg', tagName: 'feTurbulence', read: getSVGAttribute('baseFrequency'), }, { name: 'baseline-shift', containerTagName: 'svg', tagName: 'textPath', read: getSVGAttribute('baseline-shift'), }, { name: 'baselineShift', containerTagName: 'svg', tagName: 'textPath', read: getSVGAttribute('baseline-shift'), }, {name: 'baseProfile', tagName: 'svg', read: getSVGAttribute('baseProfile')}, { name: 'bbox', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('bbox'), }, { name: 'begin', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('begin'), }, { name: 'bias', containerTagName: 'svg', tagName: 'feConvolveMatrix', read: getSVGProperty('bias'), }, { name: 'by', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('by'), }, { name: 'calcMode', containerTagName: 'svg', tagName: 'animate', overrideStringValue: 'discrete', read: getSVGAttribute('calcMode'), }, { name: 'cap-height', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('cap-height'), }, { name: 'capHeight', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('cap-height'), }, { name: 'capture', tagName: 'input', overrideStringValue: 'environment', read: getAttribute('capture'), }, {name: 'cellPadding', tagName: 'table'}, {name: 'cellSpacing', tagName: 'table'}, { name: 'challenge', tagName: 'keygen', read: getAttribute('challenge'), // The property is not supported in Chrome. }, {name: 'charSet', tagName: 'script', read: getProperty('charset')}, {name: 'checked', tagName: 'input', extraProps: {onChange() {}}}, {name: 'Checked', tagName: 'input', read: getAttribute('Checked')}, {name: 'Children', read: getAttribute('children')}, {name: 'children'}, { name: 'cite', tagName: 'blockquote', overrideStringValue: 'https://reactjs.com/', }, {name: 'class', read: getAttribute('class')}, {name: 'classID', tagName: 'object', read: getAttribute('classid')}, {name: 'className'}, {name: 'clip', tagName: 'svg', read: getAttribute('clip')}, { name: 'clip-path', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('clip-path'), }, { name: 'clipPath', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('clip-path'), }, { name: 'clipPathUnits', containerTagName: 'svg', tagName: 'clipPath', overrideStringValue: 'objectBoundingBox', read: getSVGProperty('clipPathUnits'), }, { name: 'clip-rule', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('clip-rule'), }, { name: 'clipRule', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('clip-rule'), }, { name: 'color', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('color'), }, { name: 'color-interpolation', containerTagName: 'svg', tagName: 'animate', overrideStringValue: 'sRGB', read: getSVGAttribute('color-interpolation'), }, { name: 'colorInterpolation', containerTagName: 'svg', tagName: 'animate', overrideStringValue: 'sRGB', read: getSVGAttribute('color-interpolation'), }, { name: 'color-interpolation-filters', containerTagName: 'svg', tagName: 'feComposite', overrideStringValue: 'sRGB', read: getSVGAttribute('color-interpolation-filters'), }, { name: 'colorInterpolationFilters', containerTagName: 'svg', tagName: 'feComposite', overrideStringValue: 'sRGB', read: getSVGAttribute('color-interpolation-filters'), }, { name: 'color-profile', containerTagName: 'svg', tagName: 'image', overrideStringValue: 'sRGB', read: getSVGAttribute('color-profile'), }, { name: 'colorProfile', containerTagName: 'svg', tagName: 'image', overrideStringValue: 'sRGB', read: getSVGAttribute('color-profile'), }, { name: 'color-rendering', containerTagName: 'svg', tagName: 'animate', overrideStringValue: 'optimizeSpeed', read: getSVGAttribute('color-rendering'), }, { name: 'colorRendering', containerTagName: 'svg', tagName: 'animate', overrideStringValue: 'optimizeSpeed', read: getSVGAttribute('color-rendering'), }, {name: 'cols', tagName: 'textarea'}, {name: 'colSpan', containerTagName: 'tr', tagName: 'td'}, {name: 'content', containerTagName: 'head', tagName: 'meta'}, {name: 'contentEditable'}, { name: 'contentScriptType', tagName: 'svg', read: getSVGAttribute('contentScriptType'), }, { name: 'contentStyleType', tagName: 'svg', read: getSVGAttribute('contentStyleType'), }, {name: 'contextMenu', read: getAttribute('contextmenu')}, // TODO: Read the property by rendering a menu with the ID. {name: 'controls', tagName: 'video'}, {name: 'coords', tagName: 'a'}, {name: 'crossOrigin', tagName: 'script'}, {name: 'cursor', tag: 'svg', read: getAttribute('cursor')}, { name: 'cx', containerTagName: 'svg', tagName: 'circle', overrideStringValue: '10px', read: getSVGProperty('cx'), }, { name: 'cy', containerTagName: 'svg', tagName: 'circle', overrideStringValue: '10%', read: getSVGProperty('cy'), }, { name: 'd', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('d'), }, { name: 'dangerouslySetInnerHTML', read: getAttribute('dangerouslySetInnerHTML'), }, { name: 'DangerouslySetInnerHTML', read: getAttribute('DangerouslySetInnerHTML'), }, {name: 'data', read: getAttribute('data')}, {name: 'data-', read: getAttribute('data-')}, {name: 'data-unknownattribute', read: getAttribute('data-unknownattribute')}, {name: 'datatype', read: getAttribute('datatype')}, { name: 'dateTime', tagName: 'time', overrideStringValue: '2001-05-15T19:00', read: getAttribute('datetime'), }, { name: 'decelerate', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('decelerate'), }, {name: 'default', tagName: 'track'}, { name: 'defaultchecked', tagName: 'input', read: getAttribute('defaultchecked'), }, {name: 'defaultChecked', tagName: 'input'}, {name: 'defaultValue', tagName: 'input'}, {name: 'defaultValuE', tagName: 'input', read: getAttribute('defaultValuE')}, {name: 'defer', tagName: 'script'}, { name: 'descent', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('descent'), }, { name: 'diffuseConstant', containerTagName: 'svg', tagName: 'feDiffuseLighting', read: getSVGProperty('diffuseConstant'), }, {name: 'dir', overrideStringValue: 'rtl'}, { name: 'direction', containerTagName: 'svg', tagName: 'text', overrideStringValue: 'rtl', read: getSVGAttribute('direction'), }, {name: 'disabled', tagName: 'input'}, { name: 'disablePictureInPicture', tagName: 'video', read: getProperty('disablepictureinpicture'), }, { name: 'disableRemotePlayback', tagName: 'video', read: getProperty('disableremoteplayback'), }, { name: 'display', tagName: 'svg', overrideStringValue: 'list-item', read: getAttribute('display'), }, { name: 'divisor', containerTagName: 'svg', tagName: 'feConvolveMatrix', read: getSVGProperty('divisor'), }, { name: 'dominant-baseline', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('dominant-baseline'), }, { name: 'dominantBaseline', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('dominant-baseline'), }, {name: 'download', tagName: 'a'}, {name: 'dOwNlOaD', tagName: 'a', read: getAttribute('dOwNlOaD')}, {name: 'draggable'}, { name: 'dur', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('dur'), }, { name: 'dx', containerTagName: 'svg', tagName: 'text', overrideStringValue: '1pt 2px 3em', read: getSVGProperty('dx'), }, { name: 'dX', containerTagName: 'svg', tagName: 'text', overrideStringValue: '1pt 2px 3em', read: getSVGProperty('dx'), }, { name: 'dy', containerTagName: 'svg', tagName: 'text', overrideStringValue: '1 2 3', read: getSVGProperty('dy'), }, { name: 'dY', containerTagName: 'svg', tagName: 'text', overrideStringValue: '1 2 3', read: getSVGProperty('dy'), }, { name: 'edgeMode', containerTagName: 'svg', tagName: 'feConvolveMatrix', overrideStringValue: 'wrap', read: getSVGProperty('edgeMode'), }, { name: 'elevation', containerTagName: 'svg', tagName: 'feDistantLight', read: getSVGProperty('elevation'), }, { name: 'enable-background', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('enable-background'), }, { name: 'enableBackground', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('enable-background'), }, { name: 'encType', tagName: 'form', overrideStringValue: 'text/plain', read: getProperty('enctype'), }, { name: 'end', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('end'), }, { name: 'enterKeyHint', tagName: 'input', read: getProperty('enterKeyHint'), }, { name: 'exponent', read: getSVGProperty('exponent'), containerTagName: 'svg', tagName: 'feFuncA', }, { name: 'externalResourcesRequired', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('externalResourcesRequired'), }, { name: 'fetchPriority', overrideStringValue: 'high', tagName: 'img', read: getProperty('fetchPriority'), }, { name: 'fetchpriority', overrideStringValue: 'high', tagName: 'img', read: getProperty('fetchPriority'), }, { name: 'fetchPriority', overrideStringValue: 'high', tagName: 'link', read: getProperty('fetchPriority'), }, { name: 'fill', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('fill'), }, { name: 'fillOpacity', containerTagName: 'svg', tagName: 'circle', read: getSVGAttribute('fill-opacity'), }, { name: 'fill-opacity', containerTagName: 'svg', tagName: 'circle', read: getSVGAttribute('fill-opacity'), }, { name: 'fillRule', containerTagName: 'svg', tagName: 'circle', read: getSVGAttribute('fill-rule'), }, { name: 'fill-rule', containerTagName: 'svg', tagName: 'circle', read: getSVGAttribute('fill-rule'), }, { name: 'filter', containerTagName: 'svg', tagName: 'g', read: getSVGAttribute('filter'), }, { name: 'filterRes', containerTagName: 'svg', tagName: 'filter', read: getSVGAttribute('filterRes'), }, { name: 'filterUnits', containerTagName: 'svg', tagName: 'filter', overrideStringValue: 'userSpaceOnUse', read: getSVGProperty('filterUnits'), }, { name: 'flood-color', containerTagName: 'svg', tagName: 'feflood', overrideStringValue: 'currentColor', read: getSVGAttribute('flood-color'), }, { name: 'floodColor', containerTagName: 'svg', tagName: 'feflood', overrideStringValue: 'currentColor', read: getSVGAttribute('flood-color'), }, { name: 'flood-opacity', containerTagName: 'svg', tagName: 'feflood', overrideStringValue: 'inherit', read: getSVGAttribute('flood-opacity'), }, { name: 'floodOpacity', containerTagName: 'svg', tagName: 'feflood', overrideStringValue: 'inherit', read: getSVGAttribute('flood-opacity'), }, {name: 'focusable', tagName: 'p', read: getAttribute('focusable')}, { name: 'font-family', read: getSVGAttribute('font-family'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'font-size', read: getSVGAttribute('font-size'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'font-size-adjust', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('font-size-adjust'), }, { name: 'font-stretch', read: getSVGAttribute('font-stretch'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'font-style', read: getSVGAttribute('font-style'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'font-variant', read: getSVGAttribute('font-variant'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'font-weight', read: getSVGAttribute('font-weight'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'fontFamily', read: getSVGAttribute('font-family'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'fontSize', read: getSVGAttribute('font-size'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'fontSizeAdjust', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('font-size-adjust'), }, { name: 'fontStretch', read: getSVGAttribute('font-stretch'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'fontStyle', read: getSVGAttribute('font-style'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'fontVariant', read: getSVGAttribute('font-variant'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'fontWeight', read: getSVGAttribute('font-weight'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'for', tagName: 'label', read: getProperty('htmlFor')}, {name: 'fOr', tagName: 'label', read: getProperty('htmlFor')}, {name: 'form', read: getAttribute('form')}, // TODO: Read the property by rendering into a form with i { name: 'formAction', tagName: 'input', overrideStringValue: 'https://reactjs.com', }, { name: 'format', read: getSVGAttribute('format'), containerTagName: 'svg', tagName: 'altGlyph', }, {name: 'formEncType', tagName: 'input', read: getProperty('formEnctype')}, {name: 'formMethod', tagName: 'input', overrideStringValue: 'POST'}, {name: 'formNoValidate', tagName: 'input'}, {name: 'formTarget', tagName: 'input'}, {name: 'frameBorder', tagName: 'iframe'}, { name: 'from', read: getSVGAttribute('from'), containerTagName: 'svg', tagName: 'animate', }, { name: 'fx', read: getSVGProperty('fx'), containerTagName: 'svg', overrideStringValue: '10px', tagName: 'radialGradient', }, { name: 'fX', containerTagName: 'svg', tagName: 'radialGradient', overrideStringValue: '10px', read: getSVGProperty('fx'), }, { name: 'fY', containerTagName: 'svg', tagName: 'radialGradient', overrideStringValue: '20em', read: getSVGProperty('fy'), }, { name: 'fy', read: getSVGProperty('fy'), containerTagName: 'svg', overrideStringValue: '20em', tagName: 'radialGradient', }, { name: 'G1', containerTagName: 'svg', tagName: 'hkern', read: getSVGAttribute('g1'), }, { name: 'g1', read: getSVGAttribute('g1'), containerTagName: 'svg', tagName: 'hkern', }, { name: 'G2', containerTagName: 'svg', tagName: 'hkern', read: getSVGAttribute('g2'), }, { name: 'g2', read: getSVGAttribute('g2'), containerTagName: 'svg', tagName: 'hkern', }, { name: 'glyph-name', read: getSVGAttribute('glyph-name'), containerTagName: 'svg', tagName: 'glyph', }, { name: 'glyph-orientation-horizontal', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('glyph-orientation-horizontal'), }, { name: 'glyph-orientation-vertical', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('glyph-orientation-vertical'), }, { name: 'glyphName', read: getSVGAttribute('glyph-name'), containerTagName: 'svg', tagName: 'glyph', }, { name: 'glyphOrientationHorizontal', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('glyph-orientation-horizontal'), }, { name: 'glyphOrientationVertical', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('glyph-orientation-vertical'), }, { name: 'glyphRef', read: getSVGAttribute('glyph-ref'), containerTagName: 'svg', tagName: 'altGlyph', }, { name: 'gradientTransform', read: getSVGProperty('gradientTransform'), containerTagName: 'svg', overrideStringValue: 'translate(-10,-20) scale(2) rotate(45) translate(5,10)', tagName: 'linearGradient', }, { name: 'gradientUnits', read: getSVGProperty('gradientUnits'), containerTagName: 'svg', overrideStringValue: 'userSpaceOnUse', tagName: 'linearGradient', }, { name: 'hanging', read: getSVGAttribute('hanging'), containerTagName: 'svg', tagName: 'font-face', }, // Disabled because it crashes other tests with React 15. // TODO: re-enable when we no longer compare to 15. // {name: 'hasOwnProperty', read: getAttribute('hasOwnProperty')}, {name: 'headers', containerTagName: 'tr', tagName: 'td'}, {name: 'height', tagName: 'img'}, { name: 'height', containerTagName: 'svg', tagName: 'rect', read: getSVGProperty('height'), overrideStringValue: '100%', }, {name: 'hidden'}, {name: 'high', tagName: 'meter'}, { name: 'horiz-adv-x', read: getSVGAttribute('horiz-adv-x'), containerTagName: 'svg', tagName: 'font', }, { name: 'horiz-origin-x', read: getSVGAttribute('horiz-origin-x'), containerTagName: 'svg', tagName: 'font', }, { name: 'horizAdvX', read: getSVGAttribute('horiz-adv-x'), containerTagName: 'svg', tagName: 'font', }, { name: 'horizOriginX', read: getSVGAttribute('horiz-origin-x'), containerTagName: 'svg', tagName: 'font', }, {name: 'href', tagName: 'a', overrideStringValue: 'https://reactjs.com'}, {name: 'hrefLang', read: getAttribute('hreflang')}, {name: 'htmlFor', tagName: 'label'}, { name: 'http-equiv', containerTagName: 'head', tagName: 'meta', read: getProperty('httpEquiv'), }, {name: 'httpEquiv', containerTagName: 'head', tagName: 'meta'}, {name: 'icon', tagName: 'command', read: getAttribute('icon')}, {name: 'id'}, {name: 'ID', read: getProperty('id')}, { name: 'ideographic', read: getSVGAttribute('ideographic'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'image-rendering', tagName: 'svg', read: getSVGAttribute('image-rendering'), }, { name: 'imageRendering', tagName: 'svg', read: getSVGAttribute('image-rendering'), }, {name: 'imageSizes', tagName: 'link', read: getProperty('imageSizes')}, {name: 'imageSrcSet', tagName: 'link', read: getProperty('imageSrcset')}, { name: 'in', read: getSVGAttribute('in'), containerTagName: 'svg', tagName: 'feBlend', }, { name: 'in2', read: getSVGProperty('in2'), containerTagName: 'svg', tagName: 'feBlend', }, {name: 'initialChecked', read: getAttribute('initialchecked')}, {name: 'initialValue', read: getAttribute('initialvalue')}, {name: 'inlist', read: getAttribute('inlist')}, {name: 'inputMode', tagName: 'input', read: getAttribute('inputmode')}, // TODO: Should use property but it's not implemented in Chrome {name: 'integrity', tagName: 'script'}, { name: 'intercept', read: getSVGProperty('intercept'), containerTagName: 'svg', tagName: 'feFuncA', }, { name: 'is', tagName: 'button', overrideStringValue: 'x-test-element', read: getAttribute('is'), // TODO: This could check if this is an extended custom element but this is a controversial spec. }, {name: 'itemID', read: getAttribute('itemid')}, {name: 'itemProp', read: getAttribute('itemprop')}, {name: 'itemRef', read: getAttribute('itemref')}, {name: 'itemScope', read: getAttribute('itemscope')}, {name: 'itemType', read: getAttribute('itemtype')}, { name: 'k', read: getSVGAttribute('k'), containerTagName: 'svg', tagName: 'hkern', }, { name: 'K', containerTagName: 'svg', tagName: 'hkern', read: getSVGAttribute('k'), }, { name: 'K1', containerTagName: 'svg', tagName: 'feComposite', read: getSVGProperty('k1'), }, { name: 'k1', read: getSVGProperty('k1'), containerTagName: 'svg', tagName: 'feComposite', }, { name: 'k2', read: getSVGProperty('k2'), containerTagName: 'svg', tagName: 'feComposite', }, { name: 'k3', read: getSVGProperty('k3'), containerTagName: 'svg', tagName: 'feComposite', }, { name: 'k4', read: getSVGProperty('k4'), containerTagName: 'svg', tagName: 'feComposite', }, { name: 'kernelMatrix', read: getSVGProperty('kernelMatrix'), containerTagName: 'svg', tagName: 'feConvolveMatrix', overrideStringValue: '1 2 3,4', }, { name: 'kernelUnitLength', read: getSVGAttribute('kernelUnitLength'), containerTagName: 'svg', tagName: 'feConvolveMatrix', }, { name: 'kerning', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('kerning'), }, {name: 'keyParams', read: getAttribute('keyParams')}, { name: 'keyPoints', read: getSVGAttribute('keyPoints'), containerTagName: 'svg', tagName: 'animateMotion', }, { name: 'keySplines', read: getSVGAttribute('keySplines'), containerTagName: 'svg', tagName: 'animate', }, { name: 'keyTimes', read: getSVGAttribute('keyTimes'), containerTagName: 'svg', tagName: 'animate', }, {name: 'keyType', read: getAttribute('keyType')}, {name: 'kind', tagName: 'track', overrideStringValue: 'captions'}, {name: 'label', tagName: 'track'}, {name: 'LANG', read: getProperty('lang')}, {name: 'lang'}, {name: 'lang', containerTagName: 'document', tagName: 'html'}, {name: 'length', read: getAttribute('length')}, { name: 'lengthAdjust', read: getSVGProperty('lengthAdjust'), containerTagName: 'svg', tagName: 'text', overrideStringValue: 'spacingAndGlyphs', }, { name: 'letter-spacing', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('letter-spacing'), }, { name: 'letterSpacing', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('letter-spacing'), }, { name: 'lighting-color', containerTagName: 'svg', tagName: 'feDiffuseLighting', read: getSVGAttribute('lighting-color'), }, { name: 'lightingColor', containerTagName: 'svg', tagName: 'feDiffuseLighting', read: getSVGAttribute('lighting-color'), }, { name: 'limitingConeAngle', read: getSVGProperty('limitingConeAngle'), containerTagName: 'svg', tagName: 'feSpotLight', }, {name: 'list', read: getAttribute('list')}, // TODO: This should match the ID of a datalist element and then read property. { name: 'local', read: getSVGAttribute('local'), containerTagName: 'svg', tagName: 'color-profile', }, {name: 'loop', tagName: 'audio'}, {name: 'low', tagName: 'meter'}, {name: 'manifest', read: getAttribute('manifest')}, {name: 'marginHeight', containerTagName: 'frameset', tagName: 'frame'}, {name: 'marginWidth', containerTagName: 'frameset', tagName: 'frame'}, { name: 'marker-end', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('marker-end'), }, { name: 'marker-mid', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('marker-mid'), }, { name: 'marker-start', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('marker-start'), }, { name: 'markerEnd', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('marker-end'), }, { name: 'markerHeight', read: getSVGProperty('markerHeight'), containerTagName: 'svg', tagName: 'marker', }, { name: 'markerMid', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('marker-mid'), }, { name: 'markerStart', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('marker-start'), }, { name: 'markerUnits', read: getSVGProperty('markerUnits'), containerTagName: 'svg', tagName: 'marker', }, { name: 'markerWidth', read: getSVGProperty('markerWidth'), containerTagName: 'svg', tagName: 'marker', }, { name: 'mask', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('mask'), }, { name: 'maskContentUnits', read: getSVGProperty('maskContentUnits'), containerTagName: 'svg', tagName: 'mask', overrideStringValue: 'objectBoundingBox', }, { name: 'maskUnits', read: getSVGProperty('maskUnits'), containerTagName: 'svg', tagName: 'mask', overrideStringValue: 'userSpaceOnUse', }, { name: 'mathematical', read: getSVGAttribute('mathematical'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'max', tagName: 'input'}, {name: 'max', tagName: 'meter'}, {name: 'max', tagName: 'progress'}, { name: 'max', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('max'), }, {name: 'maxLength', tagName: 'textarea'}, {name: 'media', tagName: 'link'}, { name: 'media', containerTagName: 'svg', tagName: 'style', read: getSVGProperty('media'), }, {name: 'mediaGroup', tagName: 'video', read: getAttribute('mediagroup')}, // TODO: Not yet implemented in Chrome. {name: 'method', tagName: 'form', overrideStringValue: 'POST'}, { name: 'method', containerTagName: 'svg', tagName: 'textPath', read: getSVGProperty('method'), overrideStringValue: 'stretch', }, {name: 'min', tagName: 'input'}, {name: 'min', tagName: 'meter'}, { name: 'min', containerTagName: 'svg', tagName: 'animate', read: getSVGAttribute('min'), }, {name: 'minLength', tagName: 'input'}, { name: 'mode', read: getSVGProperty('mode'), containerTagName: 'svg', tagName: 'feBlend', overrideStringValue: 'multiply', }, {name: 'multiple', tagName: 'select'}, {name: 'muted', tagName: 'video'}, {name: 'name', tagName: 'input'}, { name: 'name', containerTagName: 'svg', tagName: 'color-profile', read: getSVGAttribute('color-profile'), }, {name: 'noModule', tagName: 'script'}, {name: 'nonce', read: getAttribute('nonce')}, {name: 'noValidate', tagName: 'form'}, { name: 'numOctaves', read: getSVGProperty('numOctaves'), containerTagName: 'svg', tagName: 'feTurbulence', }, { name: 'offset', read: getSVGProperty('offset'), containerTagName: 'svg', tagName: 'stop', }, {name: 'on-click'}, // TODO: Check for event subscriptions {name: 'on-unknownevent'}, // TODO: Check for event subscriptions {name: 'onclick'}, // TODO: Check for event subscriptions {name: 'onClick'}, // TODO: Check for event subscriptions {name: 'onunknownevent'}, // TODO: Check for event subscriptions {name: 'onUnknownEvent'}, // TODO: Check for event subscriptions { name: 'opacity', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('opacity'), }, {name: 'open', tagName: 'details'}, { name: 'operator', read: getSVGProperty('operator'), containerTagName: 'svg', tagName: 'feComposite', overrideStringValue: 'xor', }, {name: 'optimum', tagName: 'meter'}, { name: 'order', read: getSVGAttribute('order'), containerTagName: 'svg', tagName: 'feConvolveMatrix', }, { name: 'orient', read: getSVGAttribute('orient'), containerTagName: 'svg', tagName: 'marker', }, { name: 'orientation', read: getSVGAttribute('orientation'), containerTagName: 'svg', tagName: 'glyph', }, { name: 'origin', read: getSVGAttribute('origin'), containerTagName: 'svg', tagName: 'animateMotion', }, { name: 'overflow', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('overflow'), }, { name: 'overline-position', read: getSVGAttribute('overline-position'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'overline-thickness', read: getSVGAttribute('overline-thickness'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'overlinePosition', read: getSVGAttribute('overline-position'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'overlineThickness', read: getSVGAttribute('overline-thickness'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'paint-order', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('paint-order'), }, { name: 'paintOrder', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('paint-order'), }, { name: 'panose-1', read: getSVGAttribute('panose-1'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'panose1', containerTagName: 'svg', tagName: 'font-face', read: getSVGAttribute('panose-1'), }, { name: 'pathLength', read: getSVGProperty('pathLength'), containerTagName: 'svg', tagName: 'path', }, {name: 'pattern', tagName: 'input'}, { name: 'patternContentUnits', read: getSVGProperty('patternContentUnits'), containerTagName: 'svg', tagName: 'pattern', overrideStringValue: 'objectBoundingBox', }, { name: 'patternTransform', read: getSVGProperty('patternTransform'), containerTagName: 'svg', tagName: 'pattern', overrideStringValue: 'translate(-10,-20) scale(2) rotate(45) translate(5,10)', }, { name: 'patternUnits', read: getSVGProperty('patternUnits'), containerTagName: 'svg', tagName: 'pattern', overrideStringValue: 'userSpaceOnUse', }, {name: 'placeholder', tagName: 'input'}, {name: 'playsInline', read: getAttribute('playsinline')}, { name: 'pointer-events', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('pointer-events'), }, { name: 'pointerEvents', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('pointer-events'), }, { name: 'points', read: getSVGProperty('points'), containerTagName: 'svg', tagName: 'polygon', overrideStringValue: '350,75 379,161 469,161', }, { name: 'pointsAtX', read: getSVGProperty('pointsAtX'), containerTagName: 'svg', tagName: 'feSpotLight', }, { name: 'pointsAtY', read: getSVGProperty('pointsAtY'), containerTagName: 'svg', tagName: 'feSpotLight', }, { name: 'pointsAtZ', read: getSVGProperty('pointsAtZ'), containerTagName: 'svg', tagName: 'feSpotLight', }, { name: 'poster', tagName: 'video', overrideStringValue: 'https://reactjs.com', }, {name: 'prefix', read: getAttribute('prefix')}, {name: 'preload', tagName: 'video', overrideStringValue: 'none'}, { name: 'preserveAlpha', read: getSVGProperty('preserveAlpha'), containerTagName: 'svg', tagName: 'feConvolveMatrix', }, { name: 'preserveAspectRatio', read: getSVGProperty('preserveAspectRatio'), containerTagName: 'svg', tagName: 'feImage', overrideStringValue: 'xMinYMin slice', }, { name: 'primitiveUnits', read: getSVGProperty('primitiveUnits'), containerTagName: 'svg', tagName: 'filter', overrideStringValue: 'objectBoundingBox', }, {name: 'profile', read: getAttribute('profile')}, {name: 'property', read: getAttribute('property')}, {name: 'props', read: getAttribute('props')}, { name: 'r', read: getSVGProperty('r'), containerTagName: 'svg', tagName: 'circle', overrideStringValue: '10pt', }, {name: 'radioGroup', tagName: 'command', read: getAttribute('radiogroup')}, { name: 'radius', read: getSVGAttribute('radius'), containerTagName: 'svg', tagName: 'feMorphology', }, {name: 'readOnly', tagName: 'input'}, {name: 'referrerPolicy', tagName: 'iframe'}, { name: 'refX', read: getSVGProperty('refX'), containerTagName: 'svg', tagName: 'marker', overrideStringValue: '5em', }, { name: 'refY', read: getSVGProperty('refY'), containerTagName: 'svg', tagName: 'marker', overrideStringValue: '6em', }, {name: 'rel', tagName: 'a'}, { name: 'rendering-intent', read: getSVGAttribute('rendering-intent'), containerTagName: 'svg', tagName: 'color-profile', }, { name: 'renderingIntent', read: getSVGAttribute('rendering-intent'), containerTagName: 'svg', tagName: 'color-profile', }, { name: 'repeatCount', read: getSVGAttribute('repeatcount'), containerTagName: 'svg', tagName: 'animate', }, { name: 'repeatDur', read: getSVGAttribute('repeatdur'), containerTagName: 'svg', tagName: 'animate', }, {name: 'required', tagName: 'input'}, { name: 'requiredExtensions', read: getSVGProperty('requiredExtensions'), containerTagName: 'svg', tagName: 'a', }, { name: 'requiredFeatures', read: getSVGAttribute('requiredFeatures'), containerTagName: 'svg', tagName: 'a', }, {name: 'resource', read: getAttribute('resource')}, { name: 'restart', read: getSVGAttribute('resource'), containerTagName: 'svg', tagName: 'animate', }, { name: 'result', read: getSVGProperty('result'), containerTagName: 'svg', tagName: 'feBlend', }, {name: 'results', tagName: 'input', read: getAttribute('results')}, // TODO: Should use property but it's not supported in Chrome. {name: 'reversed', tagName: 'ol'}, {name: 'role', read: getAttribute('role')}, { name: 'rotate', read: getSVGAttribute('role'), containerTagName: 'svg', tagName: 'altGlyph', }, {name: 'rows', tagName: 'textarea'}, {name: 'rowSpan', containerTagName: 'tr', tagName: 'td'}, { name: 'rx', read: getSVGProperty('rx'), containerTagName: 'svg', tagName: 'ellipse', overrideStringValue: '1px', }, { name: 'ry', read: getSVGProperty('ry'), containerTagName: 'svg', tagName: 'ellipse', overrideStringValue: '2px', }, { name: 'sandbox', tagName: 'iframe', overrideStringValue: 'allow-forms allow-scripts', }, { name: 'scale', read: getSVGProperty('scale'), containerTagName: 'svg', tagName: 'feDisplacementMap', }, { name: 'scope', containerTagName: 'tr', tagName: 'th', overrideStringValue: 'row', }, {name: 'scoped', tagName: 'style', read: getAttribute('scoped')}, {name: 'scrolling', tagName: 'iframe', overrideStringValue: 'no'}, {name: 'seamless', tagName: 'iframe', read: getAttribute('seamless')}, {name: 'security', tagName: 'iframe', read: getAttribute('security')}, { name: 'seed', read: getSVGProperty('seed'), containerTagName: 'svg', tagName: 'feTurbulence', }, {name: 'selected', tagName: 'option', containerTagName: 'select'}, {name: 'selectedIndex', tagName: 'select'}, {name: 'shape', tagName: 'a'}, { name: 'shape-rendering', tagName: 'svg', read: getSVGAttribute('shape-rendering'), }, { name: 'shapeRendering', tagName: 'svg', read: getSVGAttribute('shape-rendering'), }, {name: 'size', tagName: 'input'}, {name: 'sizes', tagName: 'link'}, { name: 'slope', read: getSVGAttribute('slope'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'spacing', read: getSVGProperty('spacing'), containerTagName: 'svg', tagName: 'textPath', overrideStringValue: 'auto', }, {name: 'span', containerTagName: 'colgroup', tagName: 'col'}, { name: 'specularConstant', read: getSVGProperty('specularConstant'), containerTagName: 'svg', tagName: 'feSpecularLighting', }, { name: 'specularExponent', read: getSVGProperty('specularConstant'), containerTagName: 'svg', tagName: 'feSpecularLighting', }, {name: 'speed', read: getAttribute('speed')}, { name: 'spellCheck', overrideStringValue: 'false', tagName: 'input', read: getProperty('spellcheck'), }, { name: 'spellcheck', overrideStringValue: 'false', tagName: 'input', read: getProperty('spellcheck'), }, { name: 'spreadMethod', read: getSVGProperty('spreadMethod'), containerTagName: 'svg', tagName: 'linearGradient', overrideStringValue: 'reflect', }, {name: 'src', tagName: 'img', overrideStringValue: 'https://reactjs.com'}, { name: 'srcDoc', tagName: 'iframe', overrideStringValue: '<p>Hi</p>', read: getProperty('srcdoc'), }, { name: 'srcdoc', tagName: 'iframe', overrideStringValue: '<p>Hi</p>', read: getProperty('srcdoc'), }, { name: 'srcLang', containerTagName: 'audio', tagName: 'track', overrideStringValue: 'en', read: getProperty('srclang'), }, { name: 'srclang', containerTagName: 'audio', tagName: 'track', overrideStringValue: 'en', read: getProperty('srclang'), }, {name: 'srcSet', tagName: 'img'}, {name: 'srcset', tagName: 'img'}, {name: 'start', tagName: 'ol'}, { name: 'startOffset', read: getSVGProperty('startOffset'), containerTagName: 'svg', tagName: 'textPath', }, {name: 'state', read: getAttribute('state')}, { name: 'stdDeviation', read: getSVGAttribute('stdDeviation'), containerTagName: 'svg', tagName: 'feGaussianBlur', }, { name: 'stemh', read: getSVGAttribute('stemh'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'stemv', read: getSVGAttribute('stemv'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'step', read: getAttribute('step')}, { name: 'stitchTiles', read: getSVGProperty('stitchTiles'), containerTagName: 'svg', tagName: 'feTurbulence', overrideStringValue: 'stitch', }, { name: 'stop-color', containerTagName: 'svg', tagName: 'stop', read: getSVGAttribute('stop-color'), }, { name: 'stop-opacity', containerTagName: 'svg', tagName: 'stop', read: getSVGAttribute('stop-opacity'), }, { name: 'stopColor', containerTagName: 'svg', tagName: 'stop', read: getSVGAttribute('stop-color'), }, { name: 'stopOpacity', containerTagName: 'svg', tagName: 'stop', read: getSVGAttribute('stop-opacity'), }, { name: 'strikethrough-position', read: getSVGAttribute('strikethrough-position'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'strikethrough-thickness', read: getSVGAttribute('strikethrough-thickness'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'strikethroughPosition', read: getSVGAttribute('strikethrough-position'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'strikethroughThickness', read: getSVGAttribute('strikethrough-thickness'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'string', read: getSVGAttribute('string'), containerTagName: 'svg', tagName: 'font-face-format', }, { name: 'stroke', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke'), }, { name: 'stroke-dasharray', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-dasharray'), }, { name: 'stroke-Dasharray', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-dasharray'), }, { name: 'stroke-dashoffset', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-dashoffset'), }, { name: 'stroke-linecap', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-linecap'), }, { name: 'stroke-linejoin', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-linejoin'), }, { name: 'stroke-miterlimit', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-miterlimit'), }, { name: 'stroke-opacity', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-opacity'), }, { name: 'stroke-width', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-width'), }, { name: 'strokeDasharray', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-dasharray'), }, { name: 'strokeDashoffset', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-dashoffset'), }, { name: 'strokeLinecap', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-linecap'), }, { name: 'strokeLinejoin', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-linejoin'), }, { name: 'strokeMiterlimit', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-miterlimit'), }, { name: 'strokeOpacity', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-opacity'), }, { name: 'strokeWidth', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('stroke-width'), }, {name: 'style'}, {name: 'summary', tagName: 'table'}, { name: 'suppressContentEditableWarning', read: getAttribute('suppresscontenteditablewarning'), }, { name: 'surfaceScale', read: getSVGProperty('surfaceScale'), containerTagName: 'svg', tagName: 'feDiffuseLighting', }, { name: 'systemLanguage', overrideStringValue: 'en', read: getSVGProperty('systemLanguage'), containerTagName: 'svg', tagName: 'a', }, {name: 'tabIndex'}, { name: 'tabIndex', read: getSVGProperty('tabIndex'), tagName: 'svg', }, { name: 'tableValues', read: getSVGProperty('tableValues'), containerTagName: 'svg', tagName: 'feFuncA', overrideStringValue: '0 1 2 3', }, { name: 'target', read: getSVGProperty('target'), containerTagName: 'svg', tagName: 'a', }, { name: 'targetX', read: getSVGProperty('targetX'), containerTagName: 'svg', tagName: 'feConvolveMatrix', }, { name: 'targetY', read: getSVGProperty('targetY'), containerTagName: 'svg', tagName: 'feConvolveMatrix', }, { name: 'text-anchor', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('text-anchor'), }, { name: 'text-decoration', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('text-decoration'), }, { name: 'text-rendering', tagName: 'svg', read: getSVGAttribute('text-rendering'), }, { name: 'textAnchor', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('text-anchor'), }, { name: 'textDecoration', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('text-decoration'), }, { name: 'textLength', read: getSVGProperty('textLength'), containerTagName: 'svg', tagName: 'text', }, { name: 'textRendering', tagName: 'svg', read: getSVGAttribute('text-rendering'), }, {name: 'title'}, { name: 'to', read: getSVGAttribute('to'), containerTagName: 'svg', tagName: 'set', }, { name: 'transform', read: getSVGProperty('transform'), containerTagName: 'svg', tagName: 'a', overrideStringValue: 'translate(-10,-20) scale(2) rotate(45) translate(5,10)', }, { name: 'transform-origin', tagName: 'svg', read: getSVGAttribute('transform-origin'), }, { name: 'transformOrigin', tagName: 'svg', read: getSVGAttribute('transform-origin'), }, {name: 'type', tagName: 'button', overrideStringValue: 'reset'}, { name: 'type', containerTagName: 'svg', tagName: 'feFuncA', read: getSVGProperty('type'), overrideStringValue: 'discrete', }, {name: 'typeof', read: getAttribute('typeof')}, { name: 'u1', read: getSVGAttribute('u1'), containerTagName: 'svg', tagName: 'hkern', }, { name: 'u2', read: getSVGAttribute('u2'), containerTagName: 'svg', tagName: 'hkern', }, { name: 'underline-position', read: getSVGAttribute('underline-position'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'underline-thickness', read: getSVGAttribute('underline-thickness'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'underlinePosition', read: getSVGAttribute('underline-position'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'underlineThickness', read: getSVGAttribute('underline-thickness'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'unicode', read: getSVGAttribute('unicode'), containerTagName: 'svg', tagName: 'glyph', }, { name: 'unicode-bidi', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('unicode-bidi'), }, { name: 'unicode-range', read: getSVGAttribute('unicode-range'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'unicodeBidi', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('unicode-bidi'), }, { name: 'unicodeRange', read: getSVGAttribute('unicode-range'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'units-per-em', read: getSVGAttribute('units-per-em'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'unitsPerEm', read: getSVGAttribute('unites-per-em'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'unknown', read: getAttribute('unknown')}, { name: 'unselectable', read: getAttribute('unselectable'), tagName: 'span', overrideStringValue: 'on', }, {name: 'useMap', tagName: 'img'}, { name: 'v-alphabetic', read: getSVGAttribute('v-alphabetic'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'v-hanging', read: getSVGAttribute('v-hanging'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'v-ideographic', read: getSVGAttribute('v-ideographic'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'v-mathematical', read: getSVGAttribute('v-mathematical'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'vAlphabetic', read: getSVGAttribute('v-alphabetic'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'value', tagName: 'input', extraProps: {onChange() {}}}, {name: 'value', tagName: 'input', type: 'email', extraProps: {onChange() {}}}, { name: 'value', tagName: 'input', type: 'number', extraProps: {onChange() {}}, }, {name: 'value', tagName: 'textarea', extraProps: {onChange() {}}}, { name: 'value', containerTagName: 'select', tagName: 'option', extraProps: {onChange() {}}, }, { name: 'Value', containerTagName: 'select', tagName: 'option', read: getProperty('value'), }, { name: 'values', read: getSVGProperty('values'), containerTagName: 'svg', tagName: 'feColorMatrix', overrideStringValue: '1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0', }, { name: 'vector-effect', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('vector-effect'), }, { name: 'vectorEffect', containerTagName: 'svg', tagName: 'line', read: getSVGAttribute('vector-effect'), }, {name: 'version', containerTagName: 'document', tagName: 'html'}, {name: 'version', tagName: 'svg', read: getSVGAttribute('version')}, { name: 'vert-adv-y', read: getSVGAttribute('vert-origin-y'), containerTagName: 'svg', tagName: 'font', }, { name: 'vert-origin-x', read: getSVGAttribute('vert-origin-y'), containerTagName: 'svg', tagName: 'font', }, { name: 'vert-origin-y', read: getSVGAttribute('vert-origin-y'), containerTagName: 'svg', tagName: 'font', }, { name: 'vertAdvY', read: getSVGAttribute('vert-adv-y'), containerTagName: 'svg', tagName: 'font', }, { name: 'vertOriginX', read: getSVGAttribute('vert-origin-x'), containerTagName: 'svg', tagName: 'font', }, { name: 'vertOriginY', read: getSVGAttribute('vert-origin-y'), containerTagName: 'svg', tagName: 'font', }, { name: 'vHanging', read: getSVGAttribute('v-hanging'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'vIdeographic', read: getSVGAttribute('v-ideographic'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'viewBox', read: getSVGProperty('viewBox'), containerTagName: 'svg', tagName: 'marker', overrideStringValue: '0 0 1500 1000', }, { name: 'viewTarget', read: getSVGAttribute('viewTarget'), containerTagName: 'svg', tagName: 'view', }, {name: 'visibility', read: getAttribute('visibility')}, { name: 'visibility', containerTagName: 'svg', tagName: 'path', read: getSVGAttribute('visibility'), }, { name: 'vMathematical', read: getSVGAttribute('v-mathematical'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'vocab', read: getAttribute('vocab')}, {name: 'width', tagName: 'img'}, { name: 'width', containerTagName: 'svg', tagName: 'rect', read: getSVGProperty('width'), }, { name: 'widths', read: getSVGAttribute('widths'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'wmode', read: getAttribute('wmode'), tagName: 'embed'}, { name: 'word-spacing', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('word-spacing'), }, { name: 'wordSpacing', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('word-spacing'), }, {name: 'wrap', tagName: 'textarea'}, { name: 'writing-mode', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('writing-mode'), }, { name: 'writingMode', containerTagName: 'svg', tagName: 'text', read: getSVGAttribute('writing-mode'), }, { name: 'x', read: getSVGAttribute('x'), containerTagName: 'svg', tagName: 'altGlyph', }, { name: 'x-height', read: getSVGAttribute('x-height'), containerTagName: 'svg', tagName: 'font-face', }, { name: 'x1', read: getSVGProperty('x1'), containerTagName: 'svg', tagName: 'line', }, { name: 'x2', read: getSVGProperty('x2'), containerTagName: 'svg', tagName: 'line', }, { name: 'xChannelSelector', read: getSVGProperty('xChannelSelector'), containerTagName: 'svg', tagName: 'feDisplacementMap', overrideStringValue: 'R', }, { name: 'xHeight', read: getSVGAttribute('x-height'), containerTagName: 'svg', tagName: 'font-face', }, {name: 'XLink:Actuate', read: getAttribute('XLink:Actuate')}, {name: 'xlink:actuate', read: getAttribute('xlink:actuate')}, {name: 'xlink:arcrole', read: getAttribute('xlink:arcrole')}, {name: 'xlink:href', read: getAttribute('xlink:href')}, {name: 'xlink:role', read: getAttribute('xlink:role')}, {name: 'xlink:show', read: getAttribute('xlink:show')}, {name: 'xlink:title', read: getAttribute('xlink:title')}, {name: 'xlink:type', read: getAttribute('xlink:type')}, {name: 'xlinkActuate', read: getAttribute('xlink:actuate')}, {name: 'XlinkActuate', read: getAttribute('Xlink:actuate')}, {name: 'xlinkArcrole', read: getAttribute('xlink:arcrole')}, {name: 'xlinkHref', read: getAttribute('xlink:href')}, {name: 'xlinkRole', read: getAttribute('xlink:role')}, {name: 'xlinkShow', read: getAttribute('xlink:show')}, {name: 'xlinkTitle', read: getAttribute('xlink:title')}, {name: 'xlinkType', read: getAttribute('xlink:type')}, {name: 'xml:base', read: getAttribute('xml:base')}, {name: 'xml:lang', read: getAttribute('xml:lang')}, {name: 'xml:space', read: getAttribute('xml:space')}, {name: 'xmlBase', read: getAttribute('xml:base')}, {name: 'xmlLang', read: getAttribute('xml:lang')}, {name: 'xmlns', read: getProperty('namespaceURI'), tagName: 'svg'}, {name: 'xmlns:xlink', read: getAttribute('xmlns:xlink')}, {name: 'xmlnsXlink', read: getAttribute('xmlns:xlink')}, {name: 'xmlSpace', read: getAttribute('xml:space')}, { name: 'y', read: getSVGAttribute('y'), containerTagName: 'svg', tagName: 'altGlyph', }, { name: 'y1', read: getSVGProperty('y1'), containerTagName: 'svg', tagName: 'line', }, { name: 'y2', read: getSVGProperty('y2'), containerTagName: 'svg', tagName: 'line', }, { name: 'yChannelSelector', read: getSVGProperty('yChannelSelector'), containerTagName: 'svg', tagName: 'feDisplacementMap', overrideStringValue: 'B', }, { name: 'z', read: getSVGProperty('z'), containerTagName: 'svg', tagName: 'fePointLight', }, {name: 'zoomAndPan', read: getSVGProperty('zoomAndPan'), tagName: 'svg'}, ]; attributes.forEach(attr => { attr.read = attr.read || getProperty(attr.name); }); export default attributes;
23.548279
137
0.6084
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 */ /* eslint-disable no-for-of-loops/no-for-of-loops */ 'use strict'; let Scheduler; // let runWithPriority; let ImmediatePriority; let UserBlockingPriority; let NormalPriority; let LowPriority; let IdlePriority; let scheduleCallback; let cancelCallback; // let wrapCallback; // let getCurrentPriorityLevel; // let shouldYield; let waitForAll; let waitFor; let waitForThrow; function priorityLevelToString(priorityLevel) { switch (priorityLevel) { case ImmediatePriority: return 'Immediate'; case UserBlockingPriority: return 'User-blocking'; case NormalPriority: return 'Normal'; case LowPriority: return 'Low'; case IdlePriority: return 'Idle'; default: return null; } } describe('Scheduler', () => { const {enableProfiling} = require('scheduler/src/SchedulerFeatureFlags'); if (!enableProfiling) { // The tests in this suite only apply when profiling is on it('profiling APIs are not available', () => { Scheduler = require('scheduler'); expect(Scheduler.unstable_Profiling).toBe(null); }); return; } beforeEach(() => { jest.resetModules(); jest.mock('scheduler', () => require('scheduler/unstable_mock')); Scheduler = require('scheduler'); // runWithPriority = Scheduler.unstable_runWithPriority; ImmediatePriority = Scheduler.unstable_ImmediatePriority; UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; NormalPriority = Scheduler.unstable_NormalPriority; LowPriority = Scheduler.unstable_LowPriority; IdlePriority = Scheduler.unstable_IdlePriority; scheduleCallback = Scheduler.unstable_scheduleCallback; cancelCallback = Scheduler.unstable_cancelCallback; // wrapCallback = Scheduler.unstable_wrapCallback; // getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel; // shouldYield = Scheduler.unstable_shouldYield; const InternalTestUtils = require('internal-test-utils'); waitForAll = InternalTestUtils.waitForAll; waitFor = InternalTestUtils.waitFor; waitForThrow = InternalTestUtils.waitForThrow; }); 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 stopProfilingAndPrintFlamegraph() { const eventBuffer = Scheduler.unstable_Profiling.stopLoggingProfilingEvents(); if (eventBuffer === null) { return '(empty profile)'; } const eventLog = new Int32Array(eventBuffer); const tasks = new Map(); const mainThreadRuns = []; let isSuspended = true; let i = 0; processLog: while (i < eventLog.length) { const instruction = eventLog[i]; const time = eventLog[i + 1]; switch (instruction) { case 0: { break processLog; } case TaskStartEvent: { const taskId = eventLog[i + 2]; const priorityLevel = eventLog[i + 3]; const task = { id: taskId, priorityLevel, label: null, start: time, end: -1, exitStatus: null, runs: [], }; tasks.set(taskId, task); i += 4; break; } case TaskCompleteEvent: { if (isSuspended) { throw Error('Task cannot Complete outside the work loop.'); } const taskId = eventLog[i + 2]; const task = tasks.get(taskId); if (task === undefined) { throw Error('Task does not exist.'); } task.end = time; task.exitStatus = 'completed'; i += 3; break; } case TaskErrorEvent: { if (isSuspended) { throw Error('Task cannot Error outside the work loop.'); } const taskId = eventLog[i + 2]; const task = tasks.get(taskId); if (task === undefined) { throw Error('Task does not exist.'); } task.end = time; task.exitStatus = 'errored'; i += 3; break; } case TaskCancelEvent: { const taskId = eventLog[i + 2]; const task = tasks.get(taskId); if (task === undefined) { throw Error('Task does not exist.'); } task.end = time; task.exitStatus = 'canceled'; i += 3; break; } case TaskRunEvent: case TaskYieldEvent: { if (isSuspended) { throw Error('Task cannot Run or Yield outside the work loop.'); } const taskId = eventLog[i + 2]; const task = tasks.get(taskId); if (task === undefined) { throw Error('Task does not exist.'); } task.runs.push(time); i += 4; break; } case SchedulerSuspendEvent: { if (isSuspended) { throw Error('Scheduler cannot Suspend outside the work loop.'); } isSuspended = true; mainThreadRuns.push(time); i += 3; break; } case SchedulerResumeEvent: { if (!isSuspended) { throw Error('Scheduler cannot Resume inside the work loop.'); } isSuspended = false; mainThreadRuns.push(time); i += 3; break; } default: { throw Error('Unknown instruction type: ' + instruction); } } } // Now we can render the tasks as a flamegraph. const labelColumnWidth = 30; // Scheduler event times are in microseconds const microsecondsPerChar = 50000; let result = ''; const mainThreadLabelColumn = '!!! Main thread '; let mainThreadTimelineColumn = ''; let isMainThreadBusy = true; for (const time of mainThreadRuns) { const index = time / microsecondsPerChar; mainThreadTimelineColumn += (isMainThreadBusy ? 'β–ˆ' : 'β–‘').repeat( index - mainThreadTimelineColumn.length, ); isMainThreadBusy = !isMainThreadBusy; } result += `${mainThreadLabelColumn}β”‚${mainThreadTimelineColumn}\n`; const tasksByPriority = Array.from(tasks.values()).sort( (t1, t2) => t1.priorityLevel - t2.priorityLevel, ); for (const task of tasksByPriority) { let label = task.label; if (label === undefined) { label = 'Task'; } let labelColumn = `Task ${task.id} [${priorityLevelToString( task.priorityLevel, )}]`; labelColumn += ' '.repeat(labelColumnWidth - labelColumn.length - 1); // Add empty space up until the start mark let timelineColumn = ' '.repeat(task.start / microsecondsPerChar); let isRunning = false; for (const time of task.runs) { const index = time / microsecondsPerChar; timelineColumn += (isRunning ? 'β–ˆ' : 'β–‘').repeat( index - timelineColumn.length, ); isRunning = !isRunning; } const endIndex = task.end / microsecondsPerChar; timelineColumn += (isRunning ? 'β–ˆ' : 'β–‘').repeat( endIndex - timelineColumn.length, ); if (task.exitStatus !== 'completed') { timelineColumn += `👐 ${task.exitStatus}`; } result += `${labelColumn}β”‚${timelineColumn}\n`; } return '\n' + result; } it('creates a basic flamegraph', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); Scheduler.unstable_advanceTime(100); scheduleCallback( NormalPriority, () => { Scheduler.unstable_advanceTime(300); Scheduler.log('Yield 1'); scheduleCallback( UserBlockingPriority, () => { Scheduler.log('Yield 2'); Scheduler.unstable_advanceTime(300); }, {label: 'Bar'}, ); Scheduler.unstable_advanceTime(100); Scheduler.log('Yield 3'); return () => { Scheduler.log('Yield 4'); Scheduler.unstable_advanceTime(300); }; }, {label: 'Foo'}, ); await waitFor(['Yield 1', 'Yield 3']); Scheduler.unstable_advanceTime(100); await waitForAll(['Yield 2', 'Yield 4']); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ Task 2 [User-blocking] β”‚ β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Task 1 [Normal] β”‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ `, ); }); it('marks when a task is canceled', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); const task = scheduleCallback(NormalPriority, () => { Scheduler.log('Yield 1'); Scheduler.unstable_advanceTime(300); Scheduler.log('Yield 2'); return () => { Scheduler.log('Continuation'); Scheduler.unstable_advanceTime(200); }; }); await waitFor(['Yield 1', 'Yield 2']); Scheduler.unstable_advanceTime(100); cancelCallback(task); Scheduler.unstable_advanceTime(1000); await waitForAll([]); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Task 1 [Normal] β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘πŸ‘ canceled `, ); }); it('marks when a task errors', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); scheduleCallback(NormalPriority, () => { Scheduler.unstable_advanceTime(300); throw Error('Oops'); }); await waitForThrow('Oops'); Scheduler.unstable_advanceTime(100); Scheduler.unstable_advanceTime(1000); await waitForAll([]); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Task 1 [Normal] β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆπŸ‘ errored `, ); }); it('marks when multiple tasks are canceled', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); const task1 = scheduleCallback(NormalPriority, () => { Scheduler.log('Yield 1'); Scheduler.unstable_advanceTime(300); Scheduler.log('Yield 2'); return () => { Scheduler.log('Continuation'); Scheduler.unstable_advanceTime(200); }; }); const task2 = scheduleCallback(NormalPriority, () => { Scheduler.log('Yield 3'); Scheduler.unstable_advanceTime(300); Scheduler.log('Yield 4'); return () => { Scheduler.log('Continuation'); Scheduler.unstable_advanceTime(200); }; }); await waitFor(['Yield 1', 'Yield 2']); Scheduler.unstable_advanceTime(100); cancelCallback(task1); cancelCallback(task2); // Advance more time. This should not affect the size of the main // thread row, since the Scheduler queue is empty. Scheduler.unstable_advanceTime(1000); await waitForAll([]); // The main thread row should end when the callback is cancelled. expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Task 1 [Normal] β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘πŸ‘ canceled Task 2 [Normal] β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘πŸ‘ canceled `, ); }); it('handles cancelling a task that already finished', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); const task = scheduleCallback(NormalPriority, () => { Scheduler.log('A'); Scheduler.unstable_advanceTime(1000); }); await waitForAll(['A']); cancelCallback(task); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ Task 1 [Normal] β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ `, ); }); it('handles cancelling a task multiple times', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); scheduleCallback( NormalPriority, () => { Scheduler.log('A'); Scheduler.unstable_advanceTime(1000); }, {label: 'A'}, ); Scheduler.unstable_advanceTime(200); const task = scheduleCallback( NormalPriority, () => { Scheduler.log('B'); Scheduler.unstable_advanceTime(1000); }, {label: 'B'}, ); Scheduler.unstable_advanceTime(400); cancelCallback(task); cancelCallback(task); cancelCallback(task); await waitForAll(['A']); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ Task 1 [Normal] β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ Task 2 [Normal] β”‚ β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘πŸ‘ canceled `, ); }); it('handles delayed tasks', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); scheduleCallback( NormalPriority, () => { Scheduler.unstable_advanceTime(1000); Scheduler.log('A'); }, { delay: 1000, }, ); await waitForAll([]); Scheduler.unstable_advanceTime(1000); await waitForAll(['A']); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ Task 1 [Normal] β”‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ `, ); }); it('handles cancelling a delayed task', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); const task = scheduleCallback(NormalPriority, () => Scheduler.log('A'), { delay: 1000, }); cancelCallback(task); await waitForAll([]); expect(stopProfilingAndPrintFlamegraph()).toEqual( ` !!! Main thread β”‚ `, ); }); it('automatically stops profiling and warns if event log gets too big', async () => { Scheduler.unstable_Profiling.startLoggingProfilingEvents(); spyOnDevAndProd(console, 'error').mockImplementation(() => {}); // Increase infinite loop guard limit const originalMaxIterations = global.__MAX_ITERATIONS__; global.__MAX_ITERATIONS__ = 120000; let taskId = 1; while (console.error.mock.calls.length === 0) { taskId++; const task = scheduleCallback(NormalPriority, () => {}); cancelCallback(task); Scheduler.unstable_flushAll(); } expect(console.error).toHaveBeenCalledTimes(1); expect(console.error.mock.calls[0][0]).toBe( "Scheduler Profiling: Event log exceeded maximum size. Don't forget " + 'to call `stopLoggingProfilingEvents()`.', ); // Should automatically clear profile expect(stopProfilingAndPrintFlamegraph()).toEqual('(empty profile)'); // Test that we can start a new profile later Scheduler.unstable_Profiling.startLoggingProfilingEvents(); scheduleCallback(NormalPriority, () => { Scheduler.unstable_advanceTime(1000); }); await waitForAll([]); // Note: The exact task id is not super important. That just how many tasks // it happens to take before the array is resized. expect(stopProfilingAndPrintFlamegraph()).toEqual(` !!! Main thread β”‚β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ Task ${taskId} [Normal] β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ `); global.__MAX_ITERATIONS__ = originalMaxIterations; }); });
28.260377
87
0.581415
Python-for-Offensive-PenTest
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import * as React from 'react'; import {Fragment, useContext} from 'react'; import {ModalDialog} from '../ModalDialog'; import {ProfilerContext} from './ProfilerContext'; import TabBar from '../TabBar'; import ClearProfilingDataButton from './ClearProfilingDataButton'; import CommitFlamegraph from './CommitFlamegraph'; import CommitRanked from './CommitRanked'; import RootSelector from './RootSelector'; import {Timeline} from 'react-devtools-timeline/src/Timeline'; import SidebarEventInfo from './SidebarEventInfo'; import RecordToggle from './RecordToggle'; import ReloadAndProfileButton from './ReloadAndProfileButton'; import ProfilingImportExportButtons from './ProfilingImportExportButtons'; import SnapshotSelector from './SnapshotSelector'; import SidebarCommitInfo from './SidebarCommitInfo'; import NoProfilingData from './NoProfilingData'; import RecordingInProgress from './RecordingInProgress'; import ProcessingData from './ProcessingData'; import ProfilingNotSupported from './ProfilingNotSupported'; import SidebarSelectedFiberInfo from './SidebarSelectedFiberInfo'; import SettingsModal from 'react-devtools-shared/src/devtools/views/Settings/SettingsModal'; import SettingsModalContextToggle from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContextToggle'; import {SettingsModalContextController} from 'react-devtools-shared/src/devtools/views/Settings/SettingsModalContext'; import portaledContent from '../portaledContent'; import {StoreContext} from '../context'; import {TimelineContext} from 'react-devtools-timeline/src/TimelineContext'; import styles from './Profiler.css'; function Profiler(_: {}) { const { didRecordCommits, isProcessingData, isProfiling, selectedCommitIndex, selectedFiberID, selectedTabID, selectTab, supportsProfiling, } = useContext(ProfilerContext); const {file: timelineTraceEventData, searchInputContainerRef} = useContext(TimelineContext); const {supportsTimeline} = useContext(StoreContext); const isLegacyProfilerSelected = selectedTabID !== 'timeline'; let view = null; if (didRecordCommits || selectedTabID === 'timeline') { switch (selectedTabID) { case 'flame-chart': view = <CommitFlamegraph />; break; case 'ranked-chart': view = <CommitRanked />; break; case 'timeline': view = <Timeline />; break; default: break; } } else if (isProfiling) { view = <RecordingInProgress />; } else if (isProcessingData) { view = <ProcessingData />; } else if (timelineTraceEventData) { view = <OnlyTimelineData />; } else if (supportsProfiling) { view = <NoProfilingData />; } else { view = <ProfilingNotSupported />; } let sidebar = null; if (!isProfiling && !isProcessingData && didRecordCommits) { switch (selectedTabID) { case 'flame-chart': case 'ranked-chart': // TRICKY // Handle edge case where no commit is selected because of a min-duration filter update. // In that case, the selected commit index would be null. // We could still show a sidebar for the previously selected fiber, // but it would be an odd user experience. // TODO (ProfilerContext) This check should not be necessary. if (selectedCommitIndex !== null) { if (selectedFiberID !== null) { sidebar = <SidebarSelectedFiberInfo />; } else { sidebar = <SidebarCommitInfo />; } } break; case 'timeline': sidebar = <SidebarEventInfo />; break; default: break; } } return ( <SettingsModalContextController> <div className={styles.Profiler}> <div className={styles.LeftColumn}> <div className={styles.Toolbar}> <RecordToggle disabled={!supportsProfiling} /> <ReloadAndProfileButton disabled={!supportsProfiling} /> <ClearProfilingDataButton /> <ProfilingImportExportButtons /> <div className={styles.VRule} /> <TabBar currentTab={selectedTabID} id="Profiler" selectTab={selectTab} tabs={supportsTimeline ? tabsWithTimeline : tabs} type="profiler" /> <RootSelector /> <div className={styles.Spacer} /> {!isLegacyProfilerSelected && ( <div ref={searchInputContainerRef} className={styles.TimelineSearchInputContainer} /> )} <SettingsModalContextToggle /> {isLegacyProfilerSelected && didRecordCommits && ( <Fragment> <div className={styles.VRule} /> <SnapshotSelector /> </Fragment> )} </div> <div className={styles.Content}> {view} <ModalDialog /> </div> </div> <div className={styles.RightColumn}>{sidebar}</div> <SettingsModal /> </div> </SettingsModalContextController> ); } const OnlyTimelineData = () => ( <div className={styles.Column}> <div className={styles.Header}>Timeline only</div> <div className={styles.Row}> The current profile contains only Timeline data. </div> </div> ); const tabs = [ { id: 'flame-chart', icon: 'flame-chart', label: 'Flamegraph', title: 'Flamegraph chart', }, { id: 'ranked-chart', icon: 'ranked-chart', label: 'Ranked', title: 'Ranked chart', }, ]; const tabsWithTimeline = [ ...tabs, null, // Divider/separator { id: 'timeline', icon: 'timeline', label: 'Timeline', title: 'Timeline', }, ]; export default (portaledContent(Profiler): React.ComponentType<{}>);
30.309278
118
0.642845
owtf
'use client'; import * as React from 'react'; import {useFormStatus} from 'react-dom'; import ErrorBoundary from './ErrorBoundary.js'; const h = React.createElement; function ButtonDisabledWhilePending({action, children}) { const {pending} = useFormStatus(); return h( 'button', { disabled: pending, formAction: action, }, children ); } export default function Button({action, children}) { return h( ErrorBoundary, null, h( 'form', null, h( ButtonDisabledWhilePending, { action: action, }, children ) ) ); }
15.657895
57
0.585443
thieves-tools
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { Thenable, FulfilledThenable, RejectedThenable, } from 'shared/ReactTypes'; import type { ImportMetadata, ImportManifestEntry, } from './shared/ReactFlightImportMetadata'; import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig'; import { ID, CHUNKS, NAME, isAsyncImport, } from './shared/ReactFlightImportMetadata'; import {prepareDestinationWithChunks} from 'react-client/src/ReactFlightClientConfig'; import {loadChunk} from 'react-client/src/ReactFlightClientConfig'; export type SSRModuleMap = null | { [clientId: string]: { [clientExportName: string]: ClientReferenceManifestEntry, }, }; export type ServerManifest = { [id: string]: ImportManifestEntry, }; export type ServerReferenceId = string; export opaque type ClientReferenceManifestEntry = ImportManifestEntry; export opaque type ClientReferenceMetadata = ImportMetadata; // eslint-disable-next-line no-unused-vars export opaque type ClientReference<T> = ClientReferenceMetadata; // The reason this function needs to defined here in this file instead of just // being exported directly from the WebpackDestination... file is because the // ClientReferenceMetadata is opaque and we can't unwrap it there. // This should get inlined and we could also just implement an unwrapping function // though that risks it getting used in places it shouldn't be. This is unfortunate // but currently it seems to be the best option we have. export function prepareDestinationForModule( moduleLoading: ModuleLoading, nonce: ?string, metadata: ClientReferenceMetadata, ) { prepareDestinationWithChunks(moduleLoading, metadata[CHUNKS], nonce); } export function resolveClientReference<T>( bundlerConfig: SSRModuleMap, metadata: ClientReferenceMetadata, ): ClientReference<T> { if (bundlerConfig) { const moduleExports = bundlerConfig[metadata[ID]]; let resolvedModuleData = moduleExports[metadata[NAME]]; let name; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // If we don't have this specific name, we might have the full module. resolvedModuleData = moduleExports['*']; if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + metadata[ID] + '" in the React SSR Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } name = metadata[NAME]; } if (isAsyncImport(metadata)) { return [ resolvedModuleData.id, resolvedModuleData.chunks, name, 1 /* async */, ]; } else { return [resolvedModuleData.id, resolvedModuleData.chunks, name]; } } return metadata; } export function resolveServerReference<T>( bundlerConfig: ServerManifest, id: ServerReferenceId, ): ClientReference<T> { let name = ''; let resolvedModuleData = bundlerConfig[id]; if (resolvedModuleData) { // The potentially aliased name. name = resolvedModuleData.name; } else { // We didn't find this specific export name but we might have the * export // which contains this name as well. // TODO: It's unfortunate that we now have to parse this string. We should // probably go back to encoding path and name separately on the client reference. const idx = id.lastIndexOf('#'); if (idx !== -1) { name = id.slice(idx + 1); resolvedModuleData = bundlerConfig[id.slice(0, idx)]; } if (!resolvedModuleData) { throw new Error( 'Could not find the module "' + id + '" in the React Server Manifest. ' + 'This is probably a bug in the React Server Components bundler.', ); } } // TODO: This needs to return async: true if it's an async module. return [resolvedModuleData.id, resolvedModuleData.chunks, name]; } // The chunk cache contains all the chunks we've preloaded so far. // If they're still pending they're a thenable. This map also exists // in Webpack but unfortunately it's not exposed so we have to // replicate it in user space. null means that it has already loaded. const chunkCache: Map<string, null | Promise<any>> = new Map(); function requireAsyncModule(id: string): null | Thenable<any> { // We've already loaded all the chunks. We can require the module. const promise = __webpack_require__(id); if (typeof promise.then !== 'function') { // This wasn't a promise after all. return null; } else if (promise.status === 'fulfilled') { // This module was already resolved earlier. return null; } else { // Instrument the Promise to stash the result. promise.then( value => { const fulfilledThenable: FulfilledThenable<mixed> = (promise: any); fulfilledThenable.status = 'fulfilled'; fulfilledThenable.value = value; }, reason => { const rejectedThenable: RejectedThenable<mixed> = (promise: any); rejectedThenable.status = 'rejected'; rejectedThenable.reason = reason; }, ); return promise; } } function ignoreReject() { // We rely on rejected promises to be handled by another listener. } // Start preloading the modules since we might need them soon. // This function doesn't suspend. export function preloadModule<T>( metadata: ClientReference<T>, ): null | Thenable<any> { const chunks = metadata[CHUNKS]; const promises = []; let i = 0; while (i < chunks.length) { const chunkId = chunks[i++]; const chunkFilename = chunks[i++]; const entry = chunkCache.get(chunkId); if (entry === undefined) { const thenable = loadChunk(chunkId, chunkFilename); promises.push(thenable); // $FlowFixMe[method-unbinding] const resolve = chunkCache.set.bind(chunkCache, chunkId, null); thenable.then(resolve, ignoreReject); chunkCache.set(chunkId, thenable); } else if (entry !== null) { promises.push(entry); } } if (isAsyncImport(metadata)) { if (promises.length === 0) { return requireAsyncModule(metadata[ID]); } else { return Promise.all(promises).then(() => { return requireAsyncModule(metadata[ID]); }); } } else if (promises.length > 0) { return Promise.all(promises); } else { return null; } } // Actually require the module or suspend if it's not yet ready. // Increase priority if necessary. export function requireModule<T>(metadata: ClientReference<T>): T { let moduleExports = __webpack_require__(metadata[ID]); if (isAsyncImport(metadata)) { if (typeof moduleExports.then !== 'function') { // This wasn't a promise after all. } else if (moduleExports.status === 'fulfilled') { // This Promise should've been instrumented by preloadModule. moduleExports = moduleExports.value; } else { throw moduleExports.reason; } } if (metadata[NAME] === '*') { // This is a placeholder value that represents that the caller imported this // as a CommonJS module as is. return moduleExports; } if (metadata[NAME] === '') { // This is a placeholder value that represents that the caller accessed the // default property of this if it was an ESM interop module. return moduleExports.__esModule ? moduleExports.default : moduleExports; } return moduleExports[metadata[NAME]]; }
31.438298
86
0.680661
Hands-On-Penetration-Testing-with-Python
"use strict"; /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const { useMemo, useState } = require('react'); function Component(props) { const InnerComponent = useMemo(() => () => { const [state] = useState(0); return state; }); props.callback(InnerComponent); return null; } module.exports = { Component }; //# sourceMappingURL=ComponentWithNestedHooks.js.map?foo=bar&param=some_value
19.071429
77
0.675579