From 6ddcbd4f96cb103de3978617a53c200baf5b546c Mon Sep 17 00:00:00 2001 From: Jan Kassens Date: Thu, 9 Feb 2023 17:07:39 -0500 Subject: [PATCH] [flow] enable LTI inference mode (#26104) This is the next generation inference mode for Flow. --- package.json | 2 +- packages/jest-react/src/internalAct.js | 4 +- packages/react-cache/src/ReactCacheOld.js | 4 +- .../react-client/src/ReactFlightClient.js | 11 +++-- .../react-debug-tools/src/ReactDebugHooks.js | 6 +-- packages/react-devtools-core/src/backend.js | 6 +-- packages/react-devtools-core/src/editor.js | 2 +- .../react-devtools-core/src/standalone.js | 8 ++-- .../react-devtools-extensions/src/backend.js | 5 +-- packages/react-devtools-inline/src/backend.js | 6 +-- .../backend/DevToolsComponentStackFrame.js | 2 +- .../src/backend/StyleX/utils.js | 2 +- .../src/backend/legacy/renderer.js | 2 +- .../src/backend/profilingHooks.js | 13 +++--- .../src/backend/renderer.js | 10 ++--- .../src/backend/utils.js | 2 +- .../src/backend/views/utils.js | 2 +- .../src/devtools/ProfilerStore.js | 2 +- .../src/devtools/store.js | 4 +- .../devtools/views/Components/EditableName.js | 4 +- .../Components/InspectedElementContext.js | 2 +- .../NativeStyleEditor/StyleEditor.js | 2 +- .../Components/NativeStyleEditor/context.js | 4 +- .../views/Components/OwnersListContext.js | 2 +- .../src/devtools/views/Components/Tree.js | 6 +-- .../src/devtools/views/ErrorBoundary/cache.js | 4 +- .../views/Profiler/CommitFlamegraph.js | 4 +- .../devtools/views/Profiler/CommitRanked.js | 4 +- .../views/Profiler/CommitRankedListItem.js | 2 +- .../views/Profiler/CommitTreeBuilder.js | 4 +- .../views/Profiler/FlamegraphChartBuilder.js | 12 ++++- .../devtools/views/Profiler/RootSelector.js | 2 +- .../views/Profiler/SnapshotSelector.js | 2 +- .../views/Settings/ComponentsSettings.js | 4 +- .../views/Settings/ProfilerSettings.js | 2 +- .../src/devtools/views/TabBar.js | 4 +- .../views/WarnIfLegacyBackendDetected.js | 2 +- .../src/devtools/views/hooks.js | 2 +- .../src/dynamicImportCache.js | 5 ++- packages/react-devtools-shared/src/hook.js | 15 ++++--- .../src/hookNamesCache.js | 6 +-- .../src/hooks/SourceMapMetadataConsumer.js | 4 +- .../src/hooks/generateHookMap.js | 2 +- .../src/hooks/parseHookNames/index.js | 2 +- .../parseHookNames/loadSourceAndMetadata.js | 4 +- .../react-devtools-shared/src/hydration.js | 8 ++++ .../src/inspectedElementCache.js | 4 +- packages/react-devtools-shared/src/utils.js | 4 +- .../src/app/ElementTypes/index.js | 2 +- .../InspectableElements/CircularReferences.js | 4 +- .../src/app/InspectableElements/Contexts.js | 38 +++++++++++----- .../src/app/InspectableElements/SymbolKeys.js | 4 ++ .../src/app/SuspenseTree/index.js | 4 +- .../src/app/ToDoList/List.js | 9 ++-- .../react-devtools-timeline/src/CanvasPage.js | 24 +++++----- .../src/content-views/utils/text.js | 2 +- .../src/import-worker/preprocessData.js | 6 +-- .../src/timelineCache.js | 4 +- packages/react-devtools/app.js | 11 +++-- .../src/client/ReactDOMEventHandle.js | 2 +- .../src/client/setInnerHTML.js | 4 +- .../src/events/DOMPluginEventSystem.js | 1 + .../src/events/plugins/ChangeEventPlugin.js | 5 +-- .../server/ReactDOMServerExternalRuntime.js | 1 + .../src/server/ReactDOMServerFormatConfig.js | 2 +- .../src/shared/ReactDOMResourceValidation.js | 44 ++++++++++++------- .../react-dom/src/client/ReactDOMLegacy.js | 2 +- .../src/server/ReactDOMFizzServerBrowser.js | 2 +- .../src/server/ReactDOMFizzServerBun.js | 2 +- .../src/server/ReactDOMFizzServerEdge.js | 2 +- .../src/server/ReactDOMFizzStaticNode.js | 2 +- .../src/dom/create-event-handle/useEvent.js | 2 +- .../react-native-renderer/src/ReactFabric.js | 3 +- .../src/ReactFabricEventEmitter.js | 2 +- .../src/ReactNativeAttributePayload.js | 2 +- .../src/ReactNativeEventEmitter.js | 2 +- .../src/ReactNativeFiberInspector.js | 6 +-- .../src/ReactNativeRenderer.js | 3 +- .../react-reconciler/src/ReactChildFiber.js | 4 +- .../src/ReactFiberBeginWork.js | 8 ++-- .../src/ReactFiberClassComponent.js | 20 ++++----- .../src/ReactFiberClassUpdateQueue.js | 2 +- .../src/ReactFiberCompleteWork.js | 7 ++- .../react-reconciler/src/ReactFiberHooks.js | 6 +-- .../src/ReactFiberHotReloading.js | 4 +- .../src/ReactFiberReconciler.js | 6 +-- .../src/ReactFiberTreeReflection.js | 4 +- .../src/ReactFiberWorkLoop.js | 15 ++++--- .../src/ReactProfilerTimer.js | 1 - .../src/ReactStrictModeWarnings.js | 18 ++++---- .../react-refresh/src/ReactFreshRuntime.js | 10 ++--- .../ReactFlightDOMRelayClientHostConfig.js | 10 +++-- .../src/ReactFlightDOMClient.js | 9 +++- .../src/ReactFlightWebpackNodeRegister.js | 14 +++--- .../ReactFlightNativeRelayClientHostConfig.js | 10 +++-- .../src/ReactFizzClassComponent.js | 18 ++++---- packages/react-server/src/ReactFizzHooks.js | 4 +- packages/react-server/src/ReactFizzServer.js | 14 +++--- packages/react-server/src/ReactFlightHooks.js | 2 +- .../react-server/src/ReactFlightServer.js | 12 ++--- .../src/ReactServerStreamConfigNode.js | 2 +- .../src/ReactTestHostConfig.js | 2 +- .../src/ReactTestRenderer.js | 9 ++-- packages/react/src/ReactAct.js | 4 +- packages/react/src/ReactCache.js | 4 +- packages/react/src/ReactHooks.js | 1 - packages/shared/ReactComponentStackFrame.js | 2 +- .../src/useSyncExternalStoreWithSelector.js | 16 ++++++- scripts/flow/config/flowconfig | 3 +- yarn.lock | 8 ++-- 110 files changed, 378 insertions(+), 283 deletions(-) diff --git a/package.json b/package.json index dc1c903370d94..b10894522b309 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "eslint-plugin-react-internal": "link:./scripts/eslint-rules", "fbjs-scripts": "^3.0.1", "filesize": "^6.0.1", - "flow-bin": "^0.199.0", + "flow-bin": "^0.199.1", "flow-remove-types": "^2.198.2", "glob": "^7.1.6", "glob-stream": "^6.1.0", diff --git a/packages/jest-react/src/internalAct.js b/packages/jest-react/src/internalAct.js index 97ce6a655ec63..5d87891e7109e 100644 --- a/packages/jest-react/src/internalAct.js +++ b/packages/jest-react/src/internalAct.js @@ -77,7 +77,7 @@ export function act(scope: () => Thenable | T): Thenable { ) { const thenableResult: Thenable = (result: any); return { - then(resolve, reject) { + then(resolve: T => mixed, reject: mixed => mixed) { thenableResult.then( returnValue => { flushActWork( @@ -108,7 +108,7 @@ export function act(scope: () => Thenable | T): Thenable { didFlushWork = Scheduler.unstable_flushAllWithoutAsserting(); } while (didFlushWork); return { - then(resolve, reject) { + then(resolve: T => mixed, reject: mixed => mixed) { resolve(returnValue); }, }; diff --git a/packages/react-cache/src/ReactCacheOld.js b/packages/react-cache/src/ReactCacheOld.js index db316c7422db7..523a9f48c1cd5 100644 --- a/packages/react-cache/src/ReactCacheOld.js +++ b/packages/react-cache/src/ReactCacheOld.js @@ -85,11 +85,11 @@ function identityHashFn(input) { } const CACHE_LIMIT = 500; -const lru = createLRU(CACHE_LIMIT); +const lru = createLRU<$FlowFixMe>(CACHE_LIMIT); const entries: Map, Map> = new Map(); -const CacheContext = React.createContext(null); +const CacheContext = React.createContext(null); function accessResult( resource: any, diff --git a/packages/react-client/src/ReactFlightClient.js b/packages/react-client/src/ReactFlightClient.js index 624efb7428008..615ab130dff35 100644 --- a/packages/react-client/src/ReactFlightClient.js +++ b/packages/react-client/src/ReactFlightClient.js @@ -129,13 +129,13 @@ Chunk.prototype.then = function ( case BLOCKED: if (resolve) { if (chunk.value === null) { - chunk.value = []; + chunk.value = ([]: Array<(T) => mixed>); } chunk.value.push(resolve); } if (reject) { if (chunk.reason === null) { - chunk.reason = []; + chunk.reason = ([]: Array<(mixed) => mixed>); } chunk.reason.push(reject); } @@ -435,7 +435,7 @@ function createModelResolver( chunk: SomeChunk, parentObject: Object, key: string, -) { +): (value: any) => void { let blocked; if (initializingChunkBlockedModel) { blocked = initializingChunkBlockedModel; @@ -446,7 +446,6 @@ function createModelResolver( value: null, }; } - // $FlowFixMe[missing-local-annot] return value => { parentObject[key] = value; blocked.deps--; @@ -465,7 +464,7 @@ function createModelResolver( }; } -function createModelReject(chunk: SomeChunk) { +function createModelReject(chunk: SomeChunk): (error: mixed) => void { return (error: mixed) => triggerErrorOnChunk(chunk, error); } @@ -583,7 +582,7 @@ export function resolveModule( const chunks = response._chunks; const chunk = chunks.get(id); const moduleMetaData: ModuleMetaData = parseModel(response, model); - const moduleReference = resolveClientReference( + const moduleReference = resolveClientReference<$FlowFixMe>( response._bundlerConfig, moduleMetaData, ); diff --git a/packages/react-debug-tools/src/ReactDebugHooks.js b/packages/react-debug-tools/src/ReactDebugHooks.js index 56c6e376dabb6..c6ee8a6d25192 100644 --- a/packages/react-debug-tools/src/ReactDebugHooks.js +++ b/packages/react-debug-tools/src/ReactDebugHooks.js @@ -60,13 +60,13 @@ function getPrimitiveStackCache(): Map> { // This initializes a cache of all primitive hooks so that the top // most stack frames added by calling the primitive hook can be removed. if (primitiveStackCache === null) { - const cache = new Map(); + const cache = new Map>(); let readHookLog; try { // Use all hooks here to add them to the hook log. Dispatcher.useContext(({_currentValue: null}: any)); Dispatcher.useState(null); - Dispatcher.useReducer((s, a) => s, null); + Dispatcher.useReducer((s: mixed, a: mixed) => s, null); Dispatcher.useRef(null); if (typeof Dispatcher.useCacheRefresh === 'function') { // This type check is for Flow only. @@ -809,7 +809,7 @@ export function inspectHooksOfFiber( // Set up the current hook so that we can step through and read the // current state from them. currentHook = (fiber.memoizedState: Hook); - const contextMap = new Map(); + const contextMap = new Map, $FlowFixMe>(); try { setupContexts(contextMap, fiber); if (fiber.tag === ForwardRef) { diff --git a/packages/react-devtools-core/src/backend.js b/packages/react-devtools-core/src/backend.js index 3a43c9bef70e8..27faa9f15db2e 100644 --- a/packages/react-devtools-core/src/backend.js +++ b/packages/react-devtools-core/src/backend.js @@ -67,7 +67,7 @@ export function connectToDevTools(options: ?ConnectOptions) { useHttps = false, port = 8097, websocket, - resolveRNStyle = null, + resolveRNStyle = (null: $FlowFixMe), retryConnectionDelay = 2000, isAppActive = () => true, devToolsSettingsManager, @@ -230,7 +230,7 @@ export function connectToDevTools(options: ?ConnectOptions) { get() { return lazyResolveRNStyle; }, - set(value) { + set(value: $FlowFixMe) { lazyResolveRNStyle = value; initAfterTick(); }, @@ -246,7 +246,7 @@ export function connectToDevTools(options: ?ConnectOptions) { get() { return lazyNativeStyleEditorValidAttributes; }, - set(value) { + set(value: $FlowFixMe) { lazyNativeStyleEditorValidAttributes = value; initAfterTick(); }, diff --git a/packages/react-devtools-core/src/editor.js b/packages/react-devtools-core/src/editor.js index 0172d0a1568df..50728c941cf4a 100644 --- a/packages/react-devtools-core/src/editor.js +++ b/packages/react-devtools-core/src/editor.js @@ -188,7 +188,7 @@ export function launchEditor( } childProcess.on('error', function () {}); // $FlowFixMe[incompatible-use] found when upgrading Flow - childProcess.on('exit', function (errorCode) { + childProcess.on('exit', function () { childProcess = null; }); } diff --git a/packages/react-devtools-core/src/standalone.js b/packages/react-devtools-core/src/standalone.js index 12b76dae9034a..eba5b89be5c39 100644 --- a/packages/react-devtools-core/src/standalone.js +++ b/packages/react-devtools-core/src/standalone.js @@ -168,7 +168,7 @@ function onDisconnected() { } // $FlowFixMe[missing-local-annot] -function onError({code, message}) { +function onError({code, message}: $FlowFixMe) { safeUnmount(); if (code === 'EADDRINUSE') { @@ -335,13 +335,13 @@ function startServer( initialize(socket); }); - server.on('error', event => { + server.on('error', (event: $FlowFixMe) => { onError(event); log.error('Failed to start the DevTools server', event); startServerTimeoutID = setTimeout(() => startServer(port), 1000); }); - httpServer.on('request', (request, response) => { + httpServer.on('request', (request: $FlowFixMe, response: $FlowFixMe) => { // Serve a file that immediately sets up the connection. const backendFile = readFileSync(join(__dirname, 'backend.js')); @@ -377,7 +377,7 @@ function startServer( ); }); - httpServer.on('error', event => { + httpServer.on('error', (event: $FlowFixMe) => { onError(event); statusListener('Failed to start the server.', 'error'); startServerTimeoutID = setTimeout(() => startServer(port), 1000); diff --git a/packages/react-devtools-extensions/src/backend.js b/packages/react-devtools-extensions/src/backend.js index acfead859d4e4..cbd4600e9875f 100644 --- a/packages/react-devtools-extensions/src/backend.js +++ b/packages/react-devtools-extensions/src/backend.js @@ -9,7 +9,7 @@ let welcomeHasInitialized = false; // $FlowFixMe[missing-local-annot] -function welcome(event) { +function welcome(event: $FlowFixMe) { if ( event.source !== window || event.data.source !== 'react-devtools-content-script' @@ -56,8 +56,7 @@ function setup(hook: any) { const bridge = new Bridge({ listen(fn) { - // $FlowFixMe[missing-local-annot] - const listener = event => { + const listener = (event: $FlowFixMe) => { if ( event.source !== window || !event.data || diff --git a/packages/react-devtools-inline/src/backend.js b/packages/react-devtools-inline/src/backend.js index 8f949fbc8c8b4..eb70e9d15b811 100644 --- a/packages/react-devtools-inline/src/backend.js +++ b/packages/react-devtools-inline/src/backend.js @@ -10,8 +10,7 @@ import type {BackendBridge} from 'react-devtools-shared/src/bridge'; import type {Wall} from 'react-devtools-shared/src/types'; function startActivation(contentWindow: any, bridge: BackendBridge) { - // $FlowFixMe[missing-local-annot] - const onSavedPreferences = data => { + const onSavedPreferences = (data: $FlowFixMe) => { // This is the only message we're listening for, // so it's safe to cleanup after we've received it. bridge.removeListener('savedPreferences', onSavedPreferences); @@ -102,8 +101,7 @@ export function createBridge(contentWindow: any, wall?: Wall): BackendBridge { if (wall == null) { wall = { listen(fn) { - // $FlowFixMe[missing-local-annot] - const onMessage = ({data}) => { + const onMessage = ({data}: $FlowFixMe) => { fn(data); }; contentWindow.addEventListener('message', onMessage); diff --git a/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js b/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js index 3473b230cde1b..a6aacaeec8955 100644 --- a/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js +++ b/packages/react-devtools-shared/src/backend/DevToolsComponentStackFrame.js @@ -54,7 +54,7 @@ let reentry = false; let componentFrameCache; if (__DEV__) { const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); + componentFrameCache = new PossiblyWeakMap<$FlowFixMe, string>(); } export function describeNativeComponentFrame( diff --git a/packages/react-devtools-shared/src/backend/StyleX/utils.js b/packages/react-devtools-shared/src/backend/StyleX/utils.js index 05a986b5c71a7..d99362766f4ce 100644 --- a/packages/react-devtools-shared/src/backend/StyleX/utils.js +++ b/packages/react-devtools-shared/src/backend/StyleX/utils.js @@ -13,7 +13,7 @@ import isArray from 'react-devtools-shared/src/isArray'; const cachedStyleNameToValueMap: Map = new Map(); export function getStyleXData(data: any): StyleXPlugin { - const sources = new Set(); + const sources = new Set(); const resolvedStyles = {}; crawlData(data, sources, resolvedStyles); diff --git a/packages/react-devtools-shared/src/backend/legacy/renderer.js b/packages/react-devtools-shared/src/backend/legacy/renderer.js index 80619eb70e946..92e7d91c37b24 100644 --- a/packages/react-devtools-shared/src/backend/legacy/renderer.js +++ b/packages/react-devtools-shared/src/backend/legacy/renderer.js @@ -503,7 +503,7 @@ export function attach( const numUnmountIDs = pendingUnmountedIDs.length + (pendingUnmountedRootID === null ? 0 : 1); - const operations = new Array( + const operations = new Array( // Identify which renderer this update is coming from. 2 + // [rendererID, rootFiberID] // How big is the string table? diff --git a/packages/react-devtools-shared/src/backend/profilingHooks.js b/packages/react-devtools-shared/src/backend/profilingHooks.js index e68f60450af44..95ebb50734949 100644 --- a/packages/react-devtools-shared/src/backend/profilingHooks.js +++ b/packages/react-devtools-shared/src/backend/profilingHooks.js @@ -18,14 +18,16 @@ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {Wakeable} from 'shared/ReactTypes'; import type { BatchUID, + InternalModuleSourceToRanges, LaneToLabelMap, ReactComponentMeasure, + ReactLane, ReactMeasure, ReactMeasureType, - TimelineData, - SuspenseEvent, - SchedulingEvent, ReactScheduleStateUpdateEvent, + SchedulingEvent, + SuspenseEvent, + TimelineData, } from 'react-devtools-timeline/src/types'; import isArray from 'shared/isArray'; @@ -837,7 +839,8 @@ export function createProfilingHooks({ isProfiling = value; if (isProfiling) { - const internalModuleSourceToRanges = new Map(); + const internalModuleSourceToRanges: InternalModuleSourceToRanges = + new Map(); if (supportsUserTimingV3) { const ranges = getInternalModuleRanges(); @@ -856,7 +859,7 @@ export function createProfilingHooks({ } } - const laneToReactMeasureMap = new Map(); + const laneToReactMeasureMap = new Map(); let lane = 1; for (let index = 0; index < REACT_TOTAL_NUM_LANES; index++) { laneToReactMeasureMap.set(lane, []); diff --git a/packages/react-devtools-shared/src/backend/renderer.js b/packages/react-devtools-shared/src/backend/renderer.js index cf2660fc690f3..4d71e6e9f0d67 100644 --- a/packages/react-devtools-shared/src/backend/renderer.js +++ b/packages/react-devtools-shared/src/backend/renderer.js @@ -415,7 +415,7 @@ export function getInternalReactConstants(version: string): { TracingMarkerComponent, } = ReactTypeOfWork; - function resolveFiberType(type: any) { + function resolveFiberType(type: any): $FlowFixMe { const typeSymbol = getTypeSymbol(type); switch (typeSymbol) { case MEMO_NUMBER: @@ -1627,7 +1627,7 @@ export function attach( } } - let flushPendingErrorsAndWarningsAfterDelayTimeoutID = null; + let flushPendingErrorsAndWarningsAfterDelayTimeoutID: null | TimeoutID = null; function clearPendingErrorsAndWarningsAfterDelay() { if (flushPendingErrorsAndWarningsAfterDelayTimeoutID !== null) { @@ -1790,7 +1790,7 @@ export function attach( pendingSimulatedUnmountedIDs.length + (pendingUnmountedRootID === null ? 0 : 1); - const operations = new Array( + const operations = new Array( // Identify which renderer this update is coming from. 2 + // [rendererID, rootFiberID] // How big is the string table? @@ -4144,7 +4144,7 @@ export function attach( // Map of id and its force error status: true (error), false (toggled off), // null (do nothing) - const forceErrorForFiberIDs = new Map(); + const forceErrorForFiberIDs = new Map(); function shouldErrorFiberAccordingToMap(fiber: any) { if (typeof setErrorHandler !== 'function') { @@ -4209,7 +4209,7 @@ export function attach( return false; } - const forceFallbackForSuspenseIDs = new Set(); + const forceFallbackForSuspenseIDs = new Set(); function shouldSuspendFiberAccordingToSet(fiber: any) { const maybeID = getFiberIDUnsafe(((fiber: any): Fiber)); diff --git a/packages/react-devtools-shared/src/backend/utils.js b/packages/react-devtools-shared/src/backend/utils.js index 7ae15e173dfbb..f5979a9d5836d 100644 --- a/packages/react-devtools-shared/src/backend/utils.js +++ b/packages/react-devtools-shared/src/backend/utils.js @@ -144,7 +144,7 @@ export function getEffectDurations(root: Object): { } export function serializeToString(data: any): string { - const cache = new Set(); + const cache = new Set(); // Use a custom replacer function to protect against circular references. return JSON.stringify(data, (key, value) => { if (typeof value === 'object' && value !== null) { diff --git a/packages/react-devtools-shared/src/backend/views/utils.js b/packages/react-devtools-shared/src/backend/views/utils.js index 47808a4b27b6b..989a0d7b6c900 100644 --- a/packages/react-devtools-shared/src/backend/views/utils.js +++ b/packages/react-devtools-shared/src/backend/views/utils.js @@ -83,7 +83,7 @@ export function getNestedBoundingClientRect( ): Rect { const ownerIframe = getOwnerIframe(node); if (ownerIframe && ownerIframe !== boundaryWindow) { - const rects = [node.getBoundingClientRect()]; + const rects: Array = [node.getBoundingClientRect()]; let currentIframe: null | HTMLElement = ownerIframe; let onlyOneMore = false; while (currentIframe) { diff --git a/packages/react-devtools-shared/src/devtools/ProfilerStore.js b/packages/react-devtools-shared/src/devtools/ProfilerStore.js index 0f9caaabc5a14..4f530939f0fc3 100644 --- a/packages/react-devtools-shared/src/devtools/ProfilerStore.js +++ b/packages/react-devtools-shared/src/devtools/ProfilerStore.js @@ -308,7 +308,7 @@ export default class ProfilerStore extends EventEmitter<{ // Record snapshot of tree at the time profiling is started. // This info is required to handle cases of e.g. nodes being removed during profiling. this._store.roots.forEach(rootID => { - const profilingSnapshots = new Map(); + const profilingSnapshots = new Map(); this._initialSnapshotsByRootID.set(rootID, profilingSnapshots); this._takeProfilingSnapshotRecursive(rootID, profilingSnapshots); }); diff --git a/packages/react-devtools-shared/src/devtools/store.js b/packages/react-devtools-shared/src/devtools/store.js index 93251b839f81f..ba7ae80953409 100644 --- a/packages/react-devtools-shared/src/devtools/store.js +++ b/packages/react-devtools-shared/src/devtools/store.js @@ -642,7 +642,7 @@ export default class Store extends EventEmitter<{ } getOwnersListForElement(ownerID: number): Array { - const list = []; + const list: Array = []; const element = this._idToElement.get(ownerID); if (element != null) { list.push({ @@ -900,7 +900,7 @@ export default class Store extends EventEmitter<{ let i = 2; // Reassemble the string table. - const stringTable = [ + const stringTable: Array = [ null, // ID = 0 corresponds to the null string. ]; const stringTableSize = operations[i++]; diff --git a/packages/react-devtools-shared/src/devtools/views/Components/EditableName.js b/packages/react-devtools-shared/src/devtools/views/Components/EditableName.js index 3c6d537b47a36..54ac2f561d8e6 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/EditableName.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/EditableName.js @@ -43,7 +43,7 @@ export default function EditableName({ const [isValid, setIsValid] = useState(false); const handleChange = useCallback( - ({target}) => { + ({target}: $FlowFixMe) => { let value = target.value; if (!allowWhiteSpace) { value = value.trim(); @@ -61,7 +61,7 @@ export default function EditableName({ ); const handleKeyDown = useCallback( - event => { + (event: $FlowFixMe) => { // Prevent keydown events from e.g. change selected element in the tree event.stopPropagation(); diff --git a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js index 19c950f96ad33..ad17311d5e656 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/InspectedElementContext.js @@ -177,7 +177,7 @@ export function InspectedElementContextController({ [setState, state], ); - const inspectedElementRef = useRef(null); + const inspectedElementRef = useRef(null); useEffect(() => { if ( inspectedElement !== null && diff --git a/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/StyleEditor.js b/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/StyleEditor.js index 5b7cdf8563412..8967ea68c913f 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/StyleEditor.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/StyleEditor.js @@ -288,7 +288,7 @@ function Field({ onChange(event.target.value)} + onChange={(event: $FlowFixMe) => onChange(event.target.value)} onKeyDown={onKeyDown} placeholder={placeholder} value={value} diff --git a/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js b/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js index 62d3cbce6315c..d405dc1d54a4a 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/NativeStyleEditor/context.js @@ -72,9 +72,9 @@ const resource: Resource = resolveFn = resolve; }); - inProgressRequests.set(element, {promise, resolveFn}); + inProgressRequests.set(element, ({promise, resolveFn}: $FlowFixMe)); - return promise; + return (promise: $FlowFixMe); }, (element: Element) => element, {useWeakMap: true}, diff --git a/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js b/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js index 36d818a26b540..53590321741a4 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/OwnersListContext.js @@ -61,7 +61,7 @@ const resource: Resource< // $FlowFixMe[incompatible-call] found when upgrading Flow inProgressRequests.set(element, {promise, resolveFn}); - return promise; + return (promise: $FlowFixMe); }, (element: Element) => element, {useWeakMap: true}, diff --git a/packages/react-devtools-shared/src/devtools/views/Components/Tree.js b/packages/react-devtools-shared/src/devtools/views/Components/Tree.js index 57f01ca4d719c..c9f13068593a2 100644 --- a/packages/react-devtools-shared/src/devtools/views/Components/Tree.js +++ b/packages/react-devtools-shared/src/devtools/views/Components/Tree.js @@ -87,7 +87,7 @@ export default function Tree(props: Props): React.Node { // meaning the scroll action would be skipped (since ref updates don't re-run effects). // Using a callback ref accounts for this case... const listCallbackRef = useCallback( - list => { + (list: $FlowFixMe) => { if (list != null && selectedElementIndex !== null) { list.scrollToItem(selectedElementIndex, 'smart'); } @@ -226,7 +226,7 @@ export default function Tree(props: Props): React.Node { }, [dispatch, numElements, selectedElementIndex]); const handleKeyPress = useCallback( - event => { + (event: $FlowFixMe) => { switch (event.key) { case 'Enter': case ' ': @@ -272,7 +272,7 @@ export default function Tree(props: Props): React.Node { // Highlight last hovered element. const handleElementMouseEnter = useCallback( - id => { + (id: $FlowFixMe) => { // Ignore hover while we're navigating with keyboard. // This avoids flicker from the hovered nodes under the mouse. if (!isNavigatingWithKeyboard) { diff --git a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js index 9890b6402f327..eca76be605bed 100644 --- a/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js +++ b/packages/react-devtools-shared/src/devtools/views/ErrorBoundary/cache.js @@ -65,9 +65,9 @@ export function findGitHubIssue(errorMessage: string): GitHubIssue | null { let record = map.get(errorMessage); if (!record) { - const callbacks = new Set(); + const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { - then(callback) { + then(callback: () => mixed) { callbacks.add(callback); }, diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js index f552964e0ca2e..b1dceb9286112 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitFlamegraph.js @@ -45,7 +45,7 @@ export default function CommitFlamegraphAutoSizer(_: {}): React.Node { const {profilingCache} = profilerStore; const deselectCurrentFiber = useCallback( - event => { + (event: $FlowFixMe) => { event.stopPropagation(); selectFiber(null, null); }, @@ -126,7 +126,7 @@ function CommitFlamegraph({chartData, commitTree, height, width}: Props) { }, [chartData, selectedFiberID, selectedChartNodeIndex]); const handleElementMouseEnter = useCallback( - ({id, name}) => { + ({id, name}: $FlowFixMe) => { highlightNativeElement(id); // Highlight last hovered element. setHoveredFiberData({id, name}); // Set hovered fiber data for tooltip }, diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js index ad72920477c79..28d507e1f48aa 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRanked.js @@ -45,7 +45,7 @@ export default function CommitRankedAutoSizer(_: {}): React.Node { const {profilingCache} = profilerStore; const deselectCurrentFiber = useCallback( - event => { + (event: $FlowFixMe) => { event.stopPropagation(); selectFiber(null, null); }, @@ -108,7 +108,7 @@ function CommitRanked({chartData, commitTree, height, width}: Props) { ); const handleElementMouseEnter = useCallback( - ({id, name}) => { + ({id, name}: $FlowFixMe) => { highlightNativeElement(id); // Highlight last hovered element. setHoveredFiberData({id, name}); // Set hovered fiber data for tooltip }, diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js index 6f2d598dc4e5a..f1aafecb7eada 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitRankedListItem.js @@ -40,7 +40,7 @@ function CommitRankedListItem({data, index, style}: Props) { const {lineHeight} = useContext(SettingsContext); const handleClick = useCallback( - event => { + (event: $FlowFixMe) => { event.stopPropagation(); const {id, name} = node; selectFiber(id, name); diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js index 100815a5ad566..4ff09adee7450 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/CommitTreeBuilder.js @@ -84,7 +84,7 @@ export function getCommitTree({ // If this is the very first commit, start with the cached snapshot and apply the first mutation. // Otherwise load (or generate) the previous commit and append a mutation to it. if (index === 0) { - const nodes = new Map(); + const nodes = new Map(); // Construct the initial tree. recursivelyInitializeTree(rootID, 0, nodes, dataForRoot); @@ -163,7 +163,7 @@ function updateTree( let id: number = ((null: any): number); // Reassemble the string table. - const stringTable = [ + const stringTable: Array = [ null, // ID = 0 corresponds to the null string. ]; const stringTableSize = operations[i++]; diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js b/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js index 4b04e4118ac27..d64bb74648162 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/FlamegraphChartBuilder.js @@ -63,7 +63,11 @@ export function getChartData({ let maxSelfDuration = 0; // Generate flame graph structure using tree base durations. - const walkTree = (id: number, rightOffset: number, currentDepth: number) => { + const walkTree = ( + id: number, + rightOffset: number, + currentDepth: number, + ): ChartNode => { idToDepthMap.set(id, currentDepth); const node = nodes.get(id); @@ -115,7 +119,11 @@ export function getChartData({ for (let i = children.length - 1; i >= 0; i--) { const childID = children[i]; - const childChartNode = walkTree(childID, rightOffset, currentDepth + 1); + const childChartNode: $FlowFixMe = walkTree( + childID, + rightOffset, + currentDepth + 1, + ); rightOffset -= childChartNode.treeBaseDuration; } diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/RootSelector.js b/packages/react-devtools-shared/src/devtools/views/Profiler/RootSelector.js index 3939f9ccdbe1e..00e8952fedf02 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/RootSelector.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/RootSelector.js @@ -28,7 +28,7 @@ export default function RootSelector(_: {}): React.Node { } const handleChange = useCallback( - ({currentTarget}) => { + ({currentTarget}: $FlowFixMe) => { setRootID(parseInt(currentTarget.value, 10)); }, [setRootID], diff --git a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js index 57b26ce15fa3d..088ca0325d002 100644 --- a/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js +++ b/packages/react-devtools-shared/src/devtools/views/Profiler/SnapshotSelector.js @@ -45,7 +45,7 @@ export default function SnapshotSelector(_: Props): React.Node { const filteredCommitIndices = useMemo( () => - commitData.reduce((reduced, commitDatum, index) => { + commitData.reduce((reduced: $FlowFixMe, commitDatum, index) => { if ( !isCommitFilterEnabled || commitDatum.duration >= minCommitDuration diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js b/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js index d607041576542..023116060e62a 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/ComponentsSettings.js @@ -70,14 +70,14 @@ export default function ComponentsSettings(_: {}): React.Node { ); const updateCollapseNodesByDefault = useCallback( - ({currentTarget}) => { + ({currentTarget}: $FlowFixMe) => { store.collapseNodesByDefault = !currentTarget.checked; }, [store], ); const updateParseHookNames = useCallback( - ({currentTarget}) => { + ({currentTarget}: $FlowFixMe) => { setParseHookNames(currentTarget.checked); }, [setParseHookNames], diff --git a/packages/react-devtools-shared/src/devtools/views/Settings/ProfilerSettings.js b/packages/react-devtools-shared/src/devtools/views/Settings/ProfilerSettings.js index d61be3e102f91..25bc08d7ad128 100644 --- a/packages/react-devtools-shared/src/devtools/views/Settings/ProfilerSettings.js +++ b/packages/react-devtools-shared/src/devtools/views/Settings/ProfilerSettings.js @@ -39,7 +39,7 @@ export default function ProfilerSettings(_: {}): React.Node { ); const updateRecordChangeDescriptions = useCallback( - ({currentTarget}) => { + ({currentTarget}: $FlowFixMe) => { store.recordChangeDescriptions = currentTarget.checked; }, [store], diff --git a/packages/react-devtools-shared/src/devtools/views/TabBar.js b/packages/react-devtools-shared/src/devtools/views/TabBar.js index 078f28d8568b6..a277082ab2640 100644 --- a/packages/react-devtools-shared/src/devtools/views/TabBar.js +++ b/packages/react-devtools-shared/src/devtools/views/TabBar.js @@ -46,11 +46,11 @@ export default function TabBar({ } const onChange = useCallback( - ({currentTarget}) => selectTab(currentTarget.value), + ({currentTarget}: $FlowFixMe) => selectTab(currentTarget.value), [selectTab], ); - const handleKeyDown = useCallback(event => { + const handleKeyDown = useCallback((event: $FlowFixMe) => { switch (event.key) { case 'ArrowDown': case 'ArrowLeft': diff --git a/packages/react-devtools-shared/src/devtools/views/WarnIfLegacyBackendDetected.js b/packages/react-devtools-shared/src/devtools/views/WarnIfLegacyBackendDetected.js index 8f2adba86486a..13f093d2e762c 100644 --- a/packages/react-devtools-shared/src/devtools/views/WarnIfLegacyBackendDetected.js +++ b/packages/react-devtools-shared/src/devtools/views/WarnIfLegacyBackendDetected.js @@ -23,7 +23,7 @@ export default function WarnIfLegacyBackendDetected(_: {}): null { // In this case the frontend should show upgrade instructions. useEffect(() => { // Wall.listen returns a cleanup function - let unlisten = bridge.wall.listen(message => { + let unlisten: $FlowFixMe = bridge.wall.listen(message => { switch (message.type) { case 'call': case 'event': diff --git a/packages/react-devtools-shared/src/devtools/views/hooks.js b/packages/react-devtools-shared/src/devtools/views/hooks.js index c5ee3a3e83d7a..7189dd7acf94d 100644 --- a/packages/react-devtools-shared/src/devtools/views/hooks.js +++ b/packages/react-devtools-shared/src/devtools/views/hooks.js @@ -168,7 +168,7 @@ export function useLocalStorage( const [storedValue, setStoredValue] = useState(getValueFromLocalStorage); const setValue = useCallback( - value => { + (value: $FlowFixMe) => { try { const valueToStore = value instanceof Function ? (value: any)(storedValue) : value; diff --git a/packages/react-devtools-shared/src/dynamicImportCache.js b/packages/react-devtools-shared/src/dynamicImportCache.js index fa1c2e1728e31..8150b7fddf76c 100644 --- a/packages/react-devtools-shared/src/dynamicImportCache.js +++ b/packages/react-devtools-shared/src/dynamicImportCache.js @@ -66,9 +66,9 @@ export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { } if (!record) { - const callbacks = new Set(); + const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { - then(callback) { + then(callback: () => mixed) { callbacks.add(callback); }, @@ -155,6 +155,7 @@ export function loadModule(moduleLoaderFunction: ModuleLoaderFunction): Module { moduleLoaderFunctionToModuleMap.set(moduleLoaderFunction, record); } + // $FlowFixMe[underconstrained-implicit-instantiation] const response = readRecord(record).value; return response; } diff --git a/packages/react-devtools-shared/src/hook.js b/packages/react-devtools-shared/src/hook.js index b46959cbdda6c..d5e01779d69e7 100644 --- a/packages/react-devtools-shared/src/hook.js +++ b/packages/react-devtools-shared/src/hook.js @@ -8,13 +8,14 @@ * @flow */ -import type {BrowserTheme} from 'react-devtools-shared/src/devtools/views/DevTools'; +import type {BrowserTheme} from './devtools/views/DevTools'; import type { - RendererID, - ReactRenderer, - Handler, DevToolsHook, -} from 'react-devtools-shared/src/backend/types'; + Handler, + ReactRenderer, + RendererID, + RendererInterface, +} from './backend/types'; import { patchConsoleUsingWindowValues, @@ -519,9 +520,9 @@ export function installHook(target: any): DevToolsHook | null { // TODO: More meaningful names for "rendererInterfaces" and "renderers". const fiberRoots: {[RendererID]: Set} = {}; - const rendererInterfaces = new Map(); + const rendererInterfaces = new Map(); const listeners: {[string]: Array} = {}; - const renderers = new Map(); + const renderers = new Map(); const hook: DevToolsHook = { rendererInterfaces, diff --git a/packages/react-devtools-shared/src/hookNamesCache.js b/packages/react-devtools-shared/src/hookNamesCache.js index 2390c240632a3..0efa5e5f9a348 100644 --- a/packages/react-devtools-shared/src/hookNamesCache.js +++ b/packages/react-devtools-shared/src/hookNamesCache.js @@ -87,9 +87,9 @@ export function loadHookNames( } if (!record) { - const callbacks = new Set(); + const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { - then(callback) { + then(callback: () => mixed) { callbacks.add(callback); }, @@ -97,7 +97,7 @@ export function loadHookNames( displayName: `Loading hook names for ${element.displayName || 'Unknown'}`, }; - let timeoutID; + let timeoutID: $FlowFixMe | null; let didTimeout = false; let status = 'unknown'; let resolvedHookNames: HookNames | null = null; diff --git a/packages/react-devtools-shared/src/hooks/SourceMapMetadataConsumer.js b/packages/react-devtools-shared/src/hooks/SourceMapMetadataConsumer.js index 8bee45e799a9e..f6fe87fa245cd 100644 --- a/packages/react-devtools-shared/src/hooks/SourceMapMetadataConsumer.js +++ b/packages/react-devtools-shared/src/hooks/SourceMapMetadataConsumer.js @@ -131,7 +131,7 @@ export class SourceMapMetadataConsumer { _getMetadataObjectsBySourceNames(sourcemap: MixedSourceMap): MetadataMap { if (sourcemap.mappings === undefined) { const indexSourceMap: IndexSourceMap = sourcemap; - const metadataMap = new Map(); + const metadataMap = new Map(); indexSourceMap.sections.forEach(section => { const metadataMapForIndexMap = this._getMetadataObjectsBySourceNames( section.map, @@ -143,7 +143,7 @@ export class SourceMapMetadataConsumer { return metadataMap; } - const metadataMap = new Map(); + const metadataMap: MetadataMap = new Map(); const basicMap: BasicSourceMap = sourcemap; const updateMap = (metadata: ReactSourceMetadata, sourceIndex: number) => { let source = basicMap.sources[sourceIndex]; diff --git a/packages/react-devtools-shared/src/hooks/generateHookMap.js b/packages/react-devtools-shared/src/hooks/generateHookMap.js index be81581c92745..bd81d5e8ea146 100644 --- a/packages/react-devtools-shared/src/hooks/generateHookMap.js +++ b/packages/react-devtools-shared/src/hooks/generateHookMap.js @@ -65,7 +65,7 @@ export function generateHookMap(sourceAST: File): HookMap { const names = []; const mappings: Array = []; - let currentLine = null; + let currentLine: $FlowFixMe | null = null; hookNamesMapping.forEach(({name, start}) => { let nameIndex = namesMap.get(name); if (nameIndex == null) { diff --git a/packages/react-devtools-shared/src/hooks/parseHookNames/index.js b/packages/react-devtools-shared/src/hooks/parseHookNames/index.js index b893d8c09c7ab..13b437d08ca5d 100644 --- a/packages/react-devtools-shared/src/hooks/parseHookNames/index.js +++ b/packages/react-devtools-shared/src/hooks/parseHookNames/index.js @@ -32,7 +32,7 @@ export function parseSourceAndMetadata( export const purgeCachedMetadata = workerizedParseHookNames.purgeCachedMetadata; -const EMPTY_MAP = new Map(); +const EMPTY_MAP: HookNames = new Map(); export async function parseHookNames( hooksTree: HooksTree, diff --git a/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js b/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js index 1d2208a1575dd..9013ae4ff457d 100644 --- a/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js +++ b/packages/react-devtools-shared/src/hooks/parseHookNames/loadSourceAndMetadata.js @@ -136,7 +136,7 @@ function extractAndLoadSourceMapJSON( locationKeyToHookSourceAndMetadata: LocationKeyToHookSourceAndMetadata, ): Promise(p: Promise | T) => T, Promise>>> { // Deduplicate fetches, since there can be multiple location keys per source map. - const dedupedFetchPromises = new Map(); + const dedupedFetchPromises = new Map>(); if (__DEBUG__) { console.log( @@ -463,7 +463,7 @@ function loadSourceFiles( fetchFileWithCaching: FetchFileWithCaching | null, ): Promise(p: Promise | T) => T, Promise>>> { // Deduplicate fetches, since there can be multiple location keys per file. - const dedupedFetchPromises = new Map(); + const dedupedFetchPromises = new Map>(); const setterPromises = []; locationKeyToHookSourceAndMetadata.forEach(hookSourceAndMetadata => { diff --git a/packages/react-devtools-shared/src/hydration.js b/packages/react-devtools-shared/src/hydration.js index 15d841dae509a..610719c9db4e4 100644 --- a/packages/react-devtools-shared/src/hydration.js +++ b/packages/react-devtools-shared/src/hydration.js @@ -429,41 +429,49 @@ export function hydrate( function upgradeUnserializable(destination: Object, source: Object) { Object.defineProperties(destination, { + // $FlowFixMe[invalid-computed-prop] [meta.inspected]: { configurable: true, enumerable: false, value: !!source.inspected, }, + // $FlowFixMe[invalid-computed-prop] [meta.name]: { configurable: true, enumerable: false, value: source.name, }, + // $FlowFixMe[invalid-computed-prop] [meta.preview_long]: { configurable: true, enumerable: false, value: source.preview_long, }, + // $FlowFixMe[invalid-computed-prop] [meta.preview_short]: { configurable: true, enumerable: false, value: source.preview_short, }, + // $FlowFixMe[invalid-computed-prop] [meta.size]: { configurable: true, enumerable: false, value: source.size, }, + // $FlowFixMe[invalid-computed-prop] [meta.readonly]: { configurable: true, enumerable: false, value: !!source.readonly, }, + // $FlowFixMe[invalid-computed-prop] [meta.type]: { configurable: true, enumerable: false, value: source.type, }, + // $FlowFixMe[invalid-computed-prop] [meta.unserializable]: { configurable: true, enumerable: false, diff --git a/packages/react-devtools-shared/src/inspectedElementCache.js b/packages/react-devtools-shared/src/inspectedElementCache.js index 9754fac237230..f0fb6c542ef32 100644 --- a/packages/react-devtools-shared/src/inspectedElementCache.js +++ b/packages/react-devtools-shared/src/inspectedElementCache.js @@ -89,9 +89,9 @@ export function inspectElement( const map = getRecordMap(); let record = map.get(element); if (!record) { - const callbacks = new Set(); + const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { - then(callback) { + then(callback: () => mixed) { callbacks.add(callback); }, diff --git a/packages/react-devtools-shared/src/utils.js b/packages/react-devtools-shared/src/utils.js index dd76f4b723a70..3e675c3f60db1 100644 --- a/packages/react-devtools-shared/src/utils.js +++ b/packages/react-devtools-shared/src/utils.js @@ -84,7 +84,7 @@ export function alphaSortKeys( export function getAllEnumerableKeys( obj: Object, ): Set { - const keys = new Set(); + const keys = new Set(); let current = obj; while (current != null) { const currentKeys = [ @@ -203,7 +203,7 @@ export function printOperationsArray(operations: Array) { let i = 2; // Reassemble the string table. - const stringTable = [ + const stringTable: Array = [ null, // ID = 0 corresponds to the null string. ]; const stringTableSize = operations[i++]; diff --git a/packages/react-devtools-shell/src/app/ElementTypes/index.js b/packages/react-devtools-shell/src/app/ElementTypes/index.js index 3a5edef08e603..4450c5682d167 100644 --- a/packages/react-devtools-shell/src/app/ElementTypes/index.js +++ b/packages/react-devtools-shell/src/app/ElementTypes/index.js @@ -58,7 +58,7 @@ export default function ElementTypes(): React.Node { {}}> - {value => null} + {(value: $FlowFixMe) => null} diff --git a/packages/react-devtools-shell/src/app/InspectableElements/CircularReferences.js b/packages/react-devtools-shell/src/app/InspectableElements/CircularReferences.js index f75b31005610c..e918325eb1b9c 100644 --- a/packages/react-devtools-shell/src/app/InspectableElements/CircularReferences.js +++ b/packages/react-devtools-shell/src/app/InspectableElements/CircularReferences.js @@ -9,8 +9,8 @@ import * as React from 'react'; -const arrayOne = []; -const arrayTwo = []; +const arrayOne: $FlowFixMe = []; +const arrayTwo: $FlowFixMe = []; arrayTwo.push(arrayOne); arrayOne.push(arrayTwo); diff --git a/packages/react-devtools-shell/src/app/InspectableElements/Contexts.js b/packages/react-devtools-shell/src/app/InspectableElements/Contexts.js index fc76fc11c5476..256cd908518f2 100644 --- a/packages/react-devtools-shell/src/app/InspectableElements/Contexts.js +++ b/packages/react-devtools-shell/src/app/InspectableElements/Contexts.js @@ -259,7 +259,7 @@ class ModernClassContextConsumerWithUpdates extends Component { render(): any { return ( - {({string, setString}) => ( + {({string, setString}: {string: string, setString: string => void}) => ( <> {formatContextForDisplay( 'ModernClassContextConsumerWithUpdates', @@ -284,7 +284,9 @@ export default function Contexts(): React.Node { - {value => formatContextForDisplay('ModernContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('ModernContext.Consumer', value) + } @@ -292,28 +294,44 @@ export default function Contexts(): React.Node { - {value => formatContextForDisplay('ArrayContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('ArrayContext.Consumer', value) + } - {value => formatContextForDisplay('BoolContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('BoolContext.Consumer', value) + } - {value => formatContextForDisplay('FuncContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('FuncContext.Consumer', value) + } - {value => formatContextForDisplay('NumberContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('NumberContext.Consumer', value) + } - {value => formatContextForDisplay('StringContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('StringContext.Consumer', value) + } - {value => formatContextForDisplay('SymbolContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('SymbolContext.Consumer', value) + } - {value => formatContextForDisplay('NullContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('NullContext.Consumer', value) + } - {value => formatContextForDisplay('UndefinedContext.Consumer', value)} + {(value: $FlowFixMe) => + formatContextForDisplay('UndefinedContext.Consumer', value) + } diff --git a/packages/react-devtools-shell/src/app/InspectableElements/SymbolKeys.js b/packages/react-devtools-shell/src/app/InspectableElements/SymbolKeys.js index 5f8d1e0f5d94f..0bd1ee258c3a4 100644 --- a/packages/react-devtools-shell/src/app/InspectableElements/SymbolKeys.js +++ b/packages/react-devtools-shell/src/app/InspectableElements/SymbolKeys.js @@ -16,6 +16,7 @@ const base = Object.create(Object.prototype, { enumerable: true, configurable: true, }, + // $FlowFixMe[invalid-computed-prop] [Symbol('enumerableSymbolBase')]: { value: 1, writable: true, @@ -28,6 +29,7 @@ const base = Object.create(Object.prototype, { enumerable: false, configurable: true, }, + // $FlowFixMe[invalid-computed-prop] [Symbol('nonEnumerableSymbolBase')]: { value: 1, writable: true, @@ -55,12 +57,14 @@ const data = Object.create(base, { 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, diff --git a/packages/react-devtools-shell/src/app/SuspenseTree/index.js b/packages/react-devtools-shell/src/app/SuspenseTree/index.js index e5b46bc7c8904..88a56dc101631 100644 --- a/packages/react-devtools-shell/src/app/SuspenseTree/index.js +++ b/packages/react-devtools-shell/src/app/SuspenseTree/index.js @@ -54,12 +54,12 @@ function PrimaryFallbackTest({initialSuspend}) { function useTestSequence(label: string, T1: any => any, T2: any => any) { const [step, setStep] = useState(0); - const next = ( + const next: $FlowFixMe = ( ); - const allSteps = [ + const allSteps: $FlowFixMe = [ {next}, {next} mount diff --git a/packages/react-devtools-shell/src/app/ToDoList/List.js b/packages/react-devtools-shell/src/app/ToDoList/List.js index d5cdbe6c286a2..68f0b120ffdec 100644 --- a/packages/react-devtools-shell/src/app/ToDoList/List.js +++ b/packages/react-devtools-shell/src/app/ToDoList/List.js @@ -45,7 +45,7 @@ export default function List(props: Props): React.Node { }, [newItemText, items, uid]); const handleKeyPress = useCallback( - event => { + (event: $FlowFixMe) => { if (event.key === 'Enter') { handleClick(); } @@ -54,19 +54,20 @@ export default function List(props: Props): React.Node { ); const handleChange = useCallback( - event => { + (event: $FlowFixMe) => { setNewItemText(event.currentTarget.value); }, [setNewItemText], ); const removeItem = useCallback( - itemToRemove => setItems(items.filter(item => item !== itemToRemove)), + (itemToRemove: $FlowFixMe) => + setItems(items.filter(item => item !== itemToRemove)), [items], ); const toggleItem = useCallback( - itemToToggle => { + (itemToToggle: $FlowFixMe) => { // Dont use indexOf() // because editing props in DevTools creates a new Object. const index = items.findIndex(item => item.id === itemToToggle.id); diff --git a/packages/react-devtools-timeline/src/CanvasPage.js b/packages/react-devtools-timeline/src/CanvasPage.js index 4541098d5391c..5172b7d5d2b05 100644 --- a/packages/react-devtools-timeline/src/CanvasPage.js +++ b/packages/react-devtools-timeline/src/CanvasPage.js @@ -7,7 +7,7 @@ * @flow */ -import type {Point} from './view-base'; +import type {Interaction, Point} from './view-base'; import type { ReactEventInfo, TimelineData, @@ -199,16 +199,16 @@ function AutoSizedCanvas({ }, [searchIndex, searchRegExp, searchResults, viewState]); const surfaceRef = useRef(new Surface(resetHoveredEvent)); - const userTimingMarksViewRef = useRef(null); - const nativeEventsViewRef = useRef(null); - const schedulingEventsViewRef = useRef(null); - const suspenseEventsViewRef = useRef(null); - const componentMeasuresViewRef = useRef(null); - const reactMeasuresViewRef = useRef(null); - const flamechartViewRef = useRef(null); - const networkMeasuresViewRef = useRef(null); - const snapshotsViewRef = useRef(null); - const thrownErrorsViewRef = useRef(null); + const userTimingMarksViewRef = useRef(null); + const nativeEventsViewRef = useRef(null); + const schedulingEventsViewRef = useRef(null); + const suspenseEventsViewRef = useRef(null); + const componentMeasuresViewRef = useRef(null); + const reactMeasuresViewRef = useRef(null); + const flamechartViewRef = useRef(null); + const networkMeasuresViewRef = useRef(null); + const snapshotsViewRef = useRef(null); + const thrownErrorsViewRef = useRef(null); const {hideMenu: hideContextMenu} = useContext(RegistryContext); @@ -484,7 +484,7 @@ function AutoSizedCanvas({ } }, [width, height]); - const interactor = useCallback(interaction => { + const interactor = useCallback((interaction: Interaction) => { const canvas = canvasRef.current; if (canvas === null) { return; diff --git a/packages/react-devtools-timeline/src/content-views/utils/text.js b/packages/react-devtools-timeline/src/content-views/utils/text.js index b0b71639c93ee..2305975153c68 100644 --- a/packages/react-devtools-timeline/src/content-views/utils/text.js +++ b/packages/react-devtools-timeline/src/content-views/utils/text.js @@ -12,7 +12,7 @@ import type {Rect} from '../../view-base'; import {rectEqualToRect} from '../../view-base'; import {COLORS, FONT_SIZE, TEXT_PADDING} from '../constants'; -const cachedTextWidths = new Map(); +const cachedTextWidths = new Map(); export function getTextWidth( context: CanvasRenderingContext2D, diff --git a/packages/react-devtools-timeline/src/import-worker/preprocessData.js b/packages/react-devtools-timeline/src/import-worker/preprocessData.js index dedc6145555ab..af6e5d376a301 100644 --- a/packages/react-devtools-timeline/src/import-worker/preprocessData.js +++ b/packages/react-devtools-timeline/src/import-worker/preprocessData.js @@ -391,7 +391,7 @@ function processResourceSendRequest( const data = event.args.data; const requestId = data.requestId; - const availableDepths = new Array( + const availableDepths = new Array( state.requestIdToNetworkMeasureMap.size + 1, ).fill(true); state.requestIdToNetworkMeasureMap.forEach(({depth}) => { @@ -557,7 +557,7 @@ function processTimelineEvent( .split('-'); const lanes = getLanesFromTransportDecimalBitmask(laneBitmaskString); - const availableDepths = new Array( + const availableDepths = new Array( state.unresolvedSuspenseEvents.size + 1, ).fill(true); state.unresolvedSuspenseEvents.forEach(({depth}) => { @@ -1009,7 +1009,7 @@ export default async function preprocessData( ): Promise { const flamechart = preprocessFlamechart(timeline); - const laneToReactMeasureMap = new Map(); + const laneToReactMeasureMap: Map> = new Map(); for (let lane: ReactLane = 0; lane < REACT_TOTAL_NUM_LANES; lane++) { laneToReactMeasureMap.set(lane, []); } diff --git a/packages/react-devtools-timeline/src/timelineCache.js b/packages/react-devtools-timeline/src/timelineCache.js index afb9b960a2997..b6e7e6076e24e 100644 --- a/packages/react-devtools-timeline/src/timelineCache.js +++ b/packages/react-devtools-timeline/src/timelineCache.js @@ -55,9 +55,9 @@ export function importFile(file: File): TimelineData | Error { let record = fileNameToProfilerDataMap.get(fileName); if (!record) { - const callbacks = new Set(); + const callbacks = new Set<() => mixed>(); const wakeable: Wakeable = { - then(callback) { + then(callback: () => mixed) { callbacks.add(callback); }, diff --git a/packages/react-devtools/app.js b/packages/react-devtools/app.js index 5d26ca6449345..14304f2fdb1e4 100644 --- a/packages/react-devtools/app.js +++ b/packages/react-devtools/app.js @@ -41,10 +41,13 @@ app.on('ready', function () { // https://stackoverflow.com/questions/32402327/ // $FlowFixMe[incompatible-use] found when upgrading Flow - mainWindow.webContents.on('new-window', function (event, url) { - event.preventDefault(); - require('electron').shell.openExternal(url); - }); + mainWindow.webContents.on( + 'new-window', + function (event: $FlowFixMe, url: $FlowFixMe) { + event.preventDefault(); + require('electron').shell.openExternal(url); + }, + ); // and load the index.html of the app. // $FlowFixMe[incompatible-use] found when upgrading Flow diff --git a/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js b/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js index 9f76d79fc4b1b..79db99902d239 100644 --- a/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js +++ b/packages/react-dom-bindings/src/client/ReactDOMEventHandle.js @@ -109,7 +109,7 @@ export function createEventHandle( } } - const eventHandle = ( + const eventHandle: ReactDOMEventHandle = ( target: EventTarget | ReactScopeInstance, callback: (SyntheticEvent) => void, ) => { diff --git a/packages/react-dom-bindings/src/client/setInnerHTML.js b/packages/react-dom-bindings/src/client/setInnerHTML.js index 95be08266054a..e8a1b82f0f8c5 100644 --- a/packages/react-dom-bindings/src/client/setInnerHTML.js +++ b/packages/react-dom-bindings/src/client/setInnerHTML.js @@ -12,7 +12,7 @@ import createMicrosoftUnsafeLocalFunction from './createMicrosoftUnsafeLocalFunc import {enableTrustedTypesIntegration} from 'shared/ReactFeatureFlags'; // SVG temp container for IE lacking innerHTML -let reusableSVGContainer; +let reusableSVGContainer: HTMLElement; /** * Set the innerHTML property of a node @@ -57,6 +57,8 @@ const setInnerHTML: ( while (node.firstChild) { node.removeChild(node.firstChild); } + // $FlowFixMe[incompatible-use] + // $FlowFixMe[incompatible-type] while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } diff --git a/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js b/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js index 9abedde587e4e..73011e2192b72 100644 --- a/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js +++ b/packages/react-dom-bindings/src/events/DOMPluginEventSystem.js @@ -459,6 +459,7 @@ function addTrappedEventListener( if (enableLegacyFBSupport && isDeferredListenerForLegacyFBSupport) { const originalListener = listener; // $FlowFixMe[missing-this-annot] + // $FlowFixMe[definition-cycle] listener = function (...p) { removeEventListener( targetContainer, diff --git a/packages/react-dom-bindings/src/events/plugins/ChangeEventPlugin.js b/packages/react-dom-bindings/src/events/plugins/ChangeEventPlugin.js index cbfc872770d28..92e36b9171515 100644 --- a/packages/react-dom-bindings/src/events/plugins/ChangeEventPlugin.js +++ b/packages/react-dom-bindings/src/events/plugins/ChangeEventPlugin.js @@ -51,8 +51,7 @@ function registerEvents() { } function createAndAccumulateChangeEvent( - // $FlowFixMe[missing-local-annot] - dispatchQueue, + dispatchQueue: DispatchQueue, inst: null | Fiber, nativeEvent: AnyNativeEvent, target: null | EventTarget, @@ -89,7 +88,7 @@ function shouldUseChangeEvent(elem: Instance | TextInstance) { } function manualDispatchChangeEvent(nativeEvent: AnyNativeEvent) { - const dispatchQueue = []; + const dispatchQueue: DispatchQueue = []; createAndAccumulateChangeEvent( dispatchQueue, activeElementInst, diff --git a/packages/react-dom-bindings/src/server/ReactDOMServerExternalRuntime.js b/packages/react-dom-bindings/src/server/ReactDOMServerExternalRuntime.js index 57caab82159c8..638b653ef66c9 100644 --- a/packages/react-dom-bindings/src/server/ReactDOMServerExternalRuntime.js +++ b/packages/react-dom-bindings/src/server/ReactDOMServerExternalRuntime.js @@ -27,6 +27,7 @@ if (document.readyState === 'loading') { } else { // body may not exist yet if the fizz runtime is sent in // (e.g. as a preinit resource) + // $FlowFixMe[recursive-definition] const domBodyObserver = new MutationObserver(() => { // We expect the body node to be stable once parsed / created if (document.body) { diff --git a/packages/react-dom-bindings/src/server/ReactDOMServerFormatConfig.js b/packages/react-dom-bindings/src/server/ReactDOMServerFormatConfig.js index bd6df3df11f02..7abe78dbbd195 100644 --- a/packages/react-dom-bindings/src/server/ReactDOMServerFormatConfig.js +++ b/packages/react-dom-bindings/src/server/ReactDOMServerFormatConfig.js @@ -1878,7 +1878,7 @@ function pushStartPreformattedElement( // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name const VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset -const validatedTagCache = new Map(); +const validatedTagCache = new Map(); function startChunkForTag(tag: string): PrecomputedChunk { let tagStartChunk = validatedTagCache.get(tag); if (tagStartChunk === undefined) { diff --git a/packages/react-dom-bindings/src/shared/ReactDOMResourceValidation.js b/packages/react-dom-bindings/src/shared/ReactDOMResourceValidation.js index d52656e5a3966..52d9f5f52eaa4 100644 --- a/packages/react-dom-bindings/src/shared/ReactDOMResourceValidation.js +++ b/packages/react-dom-bindings/src/shared/ReactDOMResourceValidation.js @@ -104,9 +104,11 @@ export function validatePreloadResourceDifference( originalWarningName, ); } else { - let missingProps = null; - let extraProps = null; - let differentProps = null; + let missingProps: {[string]: $FlowFixMe} | null = null; + let extraProps: {[string]: $FlowFixMe} | null = null; + let differentProps: { + [string]: {latest: $FlowFixMe, original: $FlowFixMe}, + } | null = null; if (originalProps.media != null && latestProps.media == null) { missingProps = missingProps || ({}: {[string]: $FlowFixMe}); missingProps.media = originalProps.media; @@ -164,9 +166,11 @@ export function validateStyleResourceDifference( latestProps, false, ); - let missingProps = null; - let extraProps = null; - let differentProps = null; + let missingProps: {[string]: $FlowFixMe} | null = null; + let extraProps: {[string]: $FlowFixMe} | null = null; + let differentProps: { + [string]: {latest: $FlowFixMe, original: $FlowFixMe}, + } | null = null; if (originalProps.media != null && latestProps.media == null) { missingProps = missingProps || ({}: {[string]: $FlowFixMe}); missingProps.media = originalProps.media; @@ -224,8 +228,10 @@ export function validateScriptResourceDifference( latestProps, false, ); - let extraProps = null; - let differentProps = null; + let extraProps: {[string]: $FlowFixMe} | null = null; + let differentProps: { + [string]: {latest: $FlowFixMe, original: $FlowFixMe}, + } | null = null; for (const propName in latestProps) { const propValue = latestProps[propName]; @@ -291,9 +297,11 @@ export function validateStyleAndHintProps( ); } - let missingProps = null; - let extraProps = null; - let differentProps = null; + let missingProps: {[string]: $FlowFixMe} | null = null; + let extraProps: {[string]: $FlowFixMe} | null = null; + let differentProps: { + [string]: {latest: $FlowFixMe, original: $FlowFixMe}, + } | null = null; for (const propName in styleProps) { const styleValue = styleProps[propName]; @@ -373,9 +381,11 @@ export function validateScriptAndHintProps( ); } - let missingProps = null; - let extraProps = null; - let differentProps = null; + let missingProps: {[string]: $FlowFixMe} | null = null; + let extraProps: {[string]: $FlowFixMe} | null = null; + let differentProps: { + [string]: {latest: $FlowFixMe, original: $FlowFixMe}, + } | null = null; for (const propName in scriptProps) { const scriptValue = scriptProps[propName]; @@ -505,9 +515,9 @@ export function validateURLKeyedUpdatedProps( // Whether they are null or undefined if (pendingProps[urlPropKey] === currentProps[urlPropKey]) { // If we have the same href/src we need all other props to be the same - let missingProps; - let extraProps; - let differentProps; + let missingProps: ?{[string]: mixed}; + let extraProps: ?{[string]: mixed}; + let differentProps: ?{[string]: {latest: mixed, original: mixed}}; const allProps = Array.from( new Set(Object.keys(currentProps).concat(Object.keys(pendingProps))), ); diff --git a/packages/react-dom/src/client/ReactDOMLegacy.js b/packages/react-dom/src/client/ReactDOMLegacy.js index d2125b9adab02..01fac625b5fad 100644 --- a/packages/react-dom/src/client/ReactDOMLegacy.js +++ b/packages/react-dom/src/client/ReactDOMLegacy.js @@ -130,7 +130,7 @@ function legacyCreateRootFromDOMContainer( }; } - const root = createHydrationContainer( + const root: FiberRoot = createHydrationContainer( initialChildren, callback, container, diff --git a/packages/react-dom/src/server/ReactDOMFizzServerBrowser.js b/packages/react-dom/src/server/ReactDOMFizzServerBrowser.js index 59576a127ea78..ec40d7c717f02 100644 --- a/packages/react-dom/src/server/ReactDOMFizzServerBrowser.js +++ b/packages/react-dom/src/server/ReactDOMFizzServerBrowser.js @@ -49,7 +49,7 @@ function renderToReadableStream( return new Promise((resolve, reject) => { let onFatalError; let onAllReady; - const allReady = new Promise((res, rej) => { + const allReady = new Promise((res, rej) => { onAllReady = res; onFatalError = rej; }); diff --git a/packages/react-dom/src/server/ReactDOMFizzServerBun.js b/packages/react-dom/src/server/ReactDOMFizzServerBun.js index afa168c000ada..16b6e5fe1180e 100644 --- a/packages/react-dom/src/server/ReactDOMFizzServerBun.js +++ b/packages/react-dom/src/server/ReactDOMFizzServerBun.js @@ -49,7 +49,7 @@ function renderToReadableStream( return new Promise((resolve, reject) => { let onFatalError; let onAllReady; - const allReady = new Promise((res, rej) => { + const allReady = new Promise((res, rej) => { onAllReady = res; onFatalError = rej; }); diff --git a/packages/react-dom/src/server/ReactDOMFizzServerEdge.js b/packages/react-dom/src/server/ReactDOMFizzServerEdge.js index 59576a127ea78..ec40d7c717f02 100644 --- a/packages/react-dom/src/server/ReactDOMFizzServerEdge.js +++ b/packages/react-dom/src/server/ReactDOMFizzServerEdge.js @@ -49,7 +49,7 @@ function renderToReadableStream( return new Promise((resolve, reject) => { let onFatalError; let onAllReady; - const allReady = new Promise((res, rej) => { + const allReady = new Promise((res, rej) => { onAllReady = res; onFatalError = rej; }); diff --git a/packages/react-dom/src/server/ReactDOMFizzStaticNode.js b/packages/react-dom/src/server/ReactDOMFizzStaticNode.js index eb0228fa6d52c..beccc2e7b5feb 100644 --- a/packages/react-dom/src/server/ReactDOMFizzStaticNode.js +++ b/packages/react-dom/src/server/ReactDOMFizzStaticNode.js @@ -66,7 +66,7 @@ function prerenderToNodeStreams( const onFatalError = reject; function onAllReady() { - const readable = new Readable({ + const readable: Readable = new Readable({ read() { startFlowing(request, writable); }, diff --git a/packages/react-interactions/events/src/dom/create-event-handle/useEvent.js b/packages/react-interactions/events/src/dom/create-event-handle/useEvent.js index 3f91597a20c21..6092e858ff7ad 100644 --- a/packages/react-interactions/events/src/dom/create-event-handle/useEvent.js +++ b/packages/react-interactions/events/src/dom/create-event-handle/useEvent.js @@ -32,7 +32,7 @@ export default function useEvent( if (useEventHandle === null) { const setEventHandle = unstable_createEventHandle(event, options); - const clears = new Map(); + const clears = new Map void>(); useEventHandle = { setListener( target: EventTarget, diff --git a/packages/react-native-renderer/src/ReactFabric.js b/packages/react-native-renderer/src/ReactFabric.js index f45351ea12ba9..cdfb3f10bb77a 100644 --- a/packages/react-native-renderer/src/ReactFabric.js +++ b/packages/react-native-renderer/src/ReactFabric.js @@ -10,6 +10,7 @@ import type {HostComponent} from './ReactNativeTypes'; import type {ReactPortal, ReactNodeList} from 'shared/ReactTypes'; import type {ElementRef, Element, ElementType} from 'react'; +import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import './ReactFabricInjection'; @@ -257,7 +258,7 @@ function createPortal( setBatchingImplementation(batchedUpdatesImpl, discreteUpdates); -const roots = new Map(); +const roots = new Map(); export { // This is needed for implementation details of TouchableNativeFeedback diff --git a/packages/react-native-renderer/src/ReactFabricEventEmitter.js b/packages/react-native-renderer/src/ReactFabricEventEmitter.js index 39402c90616ac..4f9e4f5106ce7 100644 --- a/packages/react-native-renderer/src/ReactFabricEventEmitter.js +++ b/packages/react-native-renderer/src/ReactFabricEventEmitter.js @@ -45,7 +45,7 @@ function extractPluginEvents( nativeEvent: AnyNativeEvent, nativeEventTarget: null | EventTarget, ): Array | ReactSyntheticEvent | null { - let events = null; + let events: Array | ReactSyntheticEvent | null = null; const legacyPlugins = ((plugins: any): Array>); for (let i = 0; i < legacyPlugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. diff --git a/packages/react-native-renderer/src/ReactNativeAttributePayload.js b/packages/react-native-renderer/src/ReactNativeAttributePayload.js index ecfc19e359e7e..37bc8562f61b2 100644 --- a/packages/react-native-renderer/src/ReactNativeAttributePayload.js +++ b/packages/react-native-renderer/src/ReactNativeAttributePayload.js @@ -212,7 +212,7 @@ function addNestedProperty( updatePayload: null | Object, nextProp: NestedNode, validAttributes: AttributeConfiguration, -) { +): $FlowFixMe { if (!nextProp) { return updatePayload; } diff --git a/packages/react-native-renderer/src/ReactNativeEventEmitter.js b/packages/react-native-renderer/src/ReactNativeEventEmitter.js index 5d9acd98e19b6..cbb756bc49a79 100644 --- a/packages/react-native-renderer/src/ReactNativeEventEmitter.js +++ b/packages/react-native-renderer/src/ReactNativeEventEmitter.js @@ -130,7 +130,7 @@ function extractPluginEvents( nativeEvent: AnyNativeEvent, nativeEventTarget: null | EventTarget, ): Array | ReactSyntheticEvent | null { - let events = null; + let events: Array | ReactSyntheticEvent | null = null; const legacyPlugins = ((plugins: any): Array>); for (let i = 0; i < legacyPlugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. diff --git a/packages/react-native-renderer/src/ReactNativeFiberInspector.js b/packages/react-native-renderer/src/ReactNativeFiberInspector.js index 76c0d854808fc..7641e9314f00f 100644 --- a/packages/react-native-renderer/src/ReactNativeFiberInspector.js +++ b/packages/react-native-renderer/src/ReactNativeFiberInspector.js @@ -34,7 +34,7 @@ let getInspectorDataForInstance: ( closestInstance: Fiber | null, ) => InspectorData; let getOwnerHierarchy; -let traverseOwnerTreeUp; +let traverseOwnerTreeUp: (hierarchy: Array<$FlowFixMe>, instance: any) => void; if (__DEV__ || enableGetInspectorDataForInstanceInProduction) { // $FlowFixMe[missing-local-annot] @@ -124,7 +124,7 @@ if (__DEV__ || enableGetInspectorDataForInstanceInProduction) { }; getOwnerHierarchy = function (instance: any) { - const hierarchy = []; + const hierarchy: Array<$FlowFixMe> = []; traverseOwnerTreeUp(hierarchy, instance); return hierarchy; }; @@ -142,7 +142,7 @@ if (__DEV__ || enableGetInspectorDataForInstanceInProduction) { }; // $FlowFixMe[missing-local-annot] - traverseOwnerTreeUp = function (hierarchy, instance: any) { + traverseOwnerTreeUp = function (hierarchy, instance: any): void { if (instance) { hierarchy.unshift(instance); traverseOwnerTreeUp(hierarchy, instance._debugOwner); diff --git a/packages/react-native-renderer/src/ReactNativeRenderer.js b/packages/react-native-renderer/src/ReactNativeRenderer.js index faa854072eb87..8083d004bc941 100644 --- a/packages/react-native-renderer/src/ReactNativeRenderer.js +++ b/packages/react-native-renderer/src/ReactNativeRenderer.js @@ -10,6 +10,7 @@ import type {HostComponent} from './ReactNativeTypes'; import type {ReactPortal, ReactNodeList} from 'shared/ReactTypes'; import type {ElementRef, Element, ElementType} from 'react'; +import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import './ReactNativeInjection'; @@ -263,7 +264,7 @@ function computeComponentStackForErrorReporting(reactTag: number): string { return getStackByFiberInDevAndProd(fiber); } -const roots = new Map(); +const roots = new Map(); const Internals = { computeComponentStackForErrorReporting, diff --git a/packages/react-reconciler/src/ReactChildFiber.js b/packages/react-reconciler/src/ReactChildFiber.js index c052fcad14fce..b73d2668295f1 100644 --- a/packages/react-reconciler/src/ReactChildFiber.js +++ b/packages/react-reconciler/src/ReactChildFiber.js @@ -768,7 +768,7 @@ function createChildReconciler( if (__DEV__) { // First, validate keys. - let knownKeys = null; + let knownKeys: Set | null = null; for (let i = 0; i < newChildren.length; i++) { const child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber); @@ -961,7 +961,7 @@ function createChildReconciler( // We'll get a different iterator later for the main pass. const newChildren = iteratorFn.call(newChildrenIterable); if (newChildren) { - let knownKeys = null; + let knownKeys: Set | null = null; let step = newChildren.next(); for (; !step.done; step = newChildren.next()) { const child = step.value; diff --git a/packages/react-reconciler/src/ReactFiberBeginWork.js b/packages/react-reconciler/src/ReactFiberBeginWork.js index 3d6f2a83776b4..fc71f3be6d764 100644 --- a/packages/react-reconciler/src/ReactFiberBeginWork.js +++ b/packages/react-reconciler/src/ReactFiberBeginWork.js @@ -1492,7 +1492,7 @@ function updateHostRoot( if (workInProgress.flags & ForceClientRender) { // Something errored during a previous attempt to hydrate the shell, so we // forced a client render. - const recoverableError = createCapturedValueAtFiber( + const recoverableError = createCapturedValueAtFiber( new Error( 'There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + @@ -1508,7 +1508,7 @@ function updateHostRoot( recoverableError, ); } else if (nextChildren !== prevChildren) { - const recoverableError = createCapturedValueAtFiber( + const recoverableError = createCapturedValueAtFiber( new Error( 'This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.', @@ -2820,7 +2820,7 @@ function updateDehydratedSuspenseComponent( ); } (error: any).digest = digest; - const capturedValue = createCapturedValue(error, digest, stack); + const capturedValue = createCapturedValue(error, digest, stack); return retrySuspenseComponentWithoutHydrating( current, workInProgress, @@ -2955,7 +2955,7 @@ function updateDehydratedSuspenseComponent( pushPrimaryTreeSuspenseHandler(workInProgress); workInProgress.flags &= ~ForceClientRender; - const capturedValue = createCapturedValue( + const capturedValue = createCapturedValue( new Error( 'There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.', diff --git a/packages/react-reconciler/src/ReactFiberClassComponent.js b/packages/react-reconciler/src/ReactFiberClassComponent.js index 668a8d8862432..2b640bd4801db 100644 --- a/packages/react-reconciler/src/ReactFiberClassComponent.js +++ b/packages/react-reconciler/src/ReactFiberClassComponent.js @@ -92,16 +92,16 @@ let didWarnAboutContextTypeAndContextTypes; let didWarnAboutInvalidateContextType; if (__DEV__) { - didWarnAboutStateAssignmentForComponent = new Set(); - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - - const didWarnOnInvalidCallback = new Set(); + didWarnAboutStateAssignmentForComponent = new Set(); + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + + const didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function (callback: mixed, callerName: string) { if (callback === null || typeof callback === 'function') { diff --git a/packages/react-reconciler/src/ReactFiberClassUpdateQueue.js b/packages/react-reconciler/src/ReactFiberClassUpdateQueue.js index 1de2eae14881a..12b250a8d9a2c 100644 --- a/packages/react-reconciler/src/ReactFiberClassUpdateQueue.js +++ b/packages/react-reconciler/src/ReactFiberClassUpdateQueue.js @@ -536,7 +536,7 @@ export function processUpdateQueue( let newBaseState = null; let newFirstBaseUpdate = null; - let newLastBaseUpdate = null; + let newLastBaseUpdate: null | Update = null; let update: Update = firstBaseUpdate; do { diff --git a/packages/react-reconciler/src/ReactFiberCompleteWork.js b/packages/react-reconciler/src/ReactFiberCompleteWork.js index ffc6ceab73ba1..41039b5b65730 100644 --- a/packages/react-reconciler/src/ReactFiberCompleteWork.js +++ b/packages/react-reconciler/src/ReactFiberCompleteWork.js @@ -204,7 +204,12 @@ function hadNoMutationsEffects(current: null | Fiber, completedWork: Fiber) { return true; } -let appendAllChildren; +let appendAllChildren: ( + parent: Instance, + workInProgress: Fiber, + needsVisibilityToggle: boolean, + isHidden: boolean, +) => void; let updateHostContainer; let updateHostComponent; let updateHostText; diff --git a/packages/react-reconciler/src/ReactFiberHooks.js b/packages/react-reconciler/src/ReactFiberHooks.js index 439d204506d92..eb74663bf6814 100644 --- a/packages/react-reconciler/src/ReactFiberHooks.js +++ b/packages/react-reconciler/src/ReactFiberHooks.js @@ -168,8 +168,8 @@ let didWarnAboutMismatchedHooksForComponent; let didWarnUncachedGetSnapshot; let didWarnAboutUseWrappedInTryCatch; if (__DEV__) { - didWarnAboutMismatchedHooksForComponent = new Set(); - didWarnAboutUseWrappedInTryCatch = new Set(); + didWarnAboutMismatchedHooksForComponent = new Set(); + didWarnAboutUseWrappedInTryCatch = new Set(); } export type Hook = { @@ -1112,7 +1112,7 @@ function updateReducer( let newBaseState = null; let newBaseQueueFirst = null; - let newBaseQueueLast = null; + let newBaseQueueLast: Update | null = null; let update = first; do { // An extra OffscreenLane bit is added to updates that were made to diff --git a/packages/react-reconciler/src/ReactFiberHotReloading.js b/packages/react-reconciler/src/ReactFiberHotReloading.js index d82e130320c73..10d6bf6fa547a 100644 --- a/packages/react-reconciler/src/ReactFiberHotReloading.js +++ b/packages/react-reconciler/src/ReactFiberHotReloading.js @@ -274,7 +274,7 @@ function scheduleFibersWithFamiliesRecursively( fiber: Fiber, updatedFamilies: Set, staleFamilies: Set, -) { +): void { if (__DEV__) { const {alternate, child, sibling, tag, type} = fiber; @@ -353,7 +353,7 @@ export const findHostInstancesForRefresh: FindHostInstancesForRefresh = ( families: Array, ): Set => { if (__DEV__) { - const hostInstances = new Set(); + const hostInstances = new Set(); const types = new Set(families.map(family => family.current)); findHostInstancesForMatchingFibersRecursively( root.current, diff --git a/packages/react-reconciler/src/ReactFiberReconciler.js b/packages/react-reconciler/src/ReactFiberReconciler.js index d6e2b1c85dc23..fd80f0933b4c8 100644 --- a/packages/react-reconciler/src/ReactFiberReconciler.js +++ b/packages/react-reconciler/src/ReactFiberReconciler.js @@ -554,7 +554,7 @@ if (__DEV__) { obj: Object | Array, path: Array, index: number, - ) => { + ): $FlowFixMe => { const key = path[index]; const updated = isArray(obj) ? obj.slice() : {...obj}; if (index + 1 === path.length) { @@ -582,7 +582,7 @@ if (__DEV__) { oldPath: Array, newPath: Array, index: number, - ) => { + ): $FlowFixMe => { const oldKey = oldPath[index]; const updated = isArray(obj) ? obj.slice() : {...obj}; if (index + 1 === oldPath.length) { @@ -633,7 +633,7 @@ if (__DEV__) { path: Array, index: number, value: any, - ) => { + ): $FlowFixMe => { if (index >= path.length) { return value; } diff --git a/packages/react-reconciler/src/ReactFiberTreeReflection.js b/packages/react-reconciler/src/ReactFiberTreeReflection.js index 217a421248db4..d03bccc6a3047 100644 --- a/packages/react-reconciler/src/ReactFiberTreeReflection.js +++ b/packages/react-reconciler/src/ReactFiberTreeReflection.js @@ -275,7 +275,7 @@ export function findCurrentHostFiber(parent: Fiber): Fiber | null { : null; } -function findCurrentHostFiberImpl(node: Fiber) { +function findCurrentHostFiberImpl(node: Fiber): Fiber | null { // Next we'll drill down this component to find the first HostComponent/Text. const tag = node.tag; if ( @@ -306,7 +306,7 @@ export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null { : null; } -function findCurrentHostFiberWithNoPortalsImpl(node: Fiber) { +function findCurrentHostFiberWithNoPortalsImpl(node: Fiber): Fiber | null { // Next we'll drill down this component to find the first HostComponent/Text. const tag = node.tag; if ( diff --git a/packages/react-reconciler/src/ReactFiberWorkLoop.js b/packages/react-reconciler/src/ReactFiberWorkLoop.js index b760c65013227..6d29eb0212f26 100644 --- a/packages/react-reconciler/src/ReactFiberWorkLoop.js +++ b/packages/react-reconciler/src/ReactFiberWorkLoop.js @@ -404,7 +404,8 @@ export function addTransitionStartCallbackToPendingTransition( } if (currentPendingTransitionCallbacks.transitionStart === null) { - currentPendingTransitionCallbacks.transitionStart = []; + currentPendingTransitionCallbacks.transitionStart = + ([]: Array); } currentPendingTransitionCallbacks.transitionStart.push(transition); @@ -537,7 +538,8 @@ export function addTransitionCompleteCallbackToPendingTransition( } if (currentPendingTransitionCallbacks.transitionComplete === null) { - currentPendingTransitionCallbacks.transitionComplete = []; + currentPendingTransitionCallbacks.transitionComplete = + ([]: Array); } currentPendingTransitionCallbacks.transitionComplete.push(transition); @@ -1000,7 +1002,10 @@ function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { // This is the entry point for every concurrent task, i.e. anything that // goes through Scheduler. -function performConcurrentWorkOnRoot(root: FiberRoot, didTimeout: boolean) { +function performConcurrentWorkOnRoot( + root: FiberRoot, + didTimeout: boolean, +): $FlowFixMe { if (enableProfilerTimer && enableProfilerNestedUpdatePhase) { resetNestedUpdateFlag(); } @@ -3329,7 +3334,7 @@ export function attachPingListener( let threadIDs; if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap(); - threadIDs = new Set(); + threadIDs = new Set(); pingCache.set(wakeable, threadIDs); } else { threadIDs = pingCache.get(wakeable); @@ -3829,7 +3834,7 @@ if (__DEV__ && replayFailedUnitOfWorkWithInvokeGuardedCallback) { let didWarnAboutUpdateInRender = false; let didWarnAboutUpdateInRenderForAnotherComponent; if (__DEV__) { - didWarnAboutUpdateInRenderForAnotherComponent = new Set(); + didWarnAboutUpdateInRenderForAnotherComponent = new Set(); } function warnAboutRenderPhaseUpdatesInDEV(fiber: Fiber) { diff --git a/packages/react-reconciler/src/ReactProfilerTimer.js b/packages/react-reconciler/src/ReactProfilerTimer.js index 016e7c1e0dc03..283b0e1f6a920 100644 --- a/packages/react-reconciler/src/ReactProfilerTimer.js +++ b/packages/react-reconciler/src/ReactProfilerTimer.js @@ -122,7 +122,6 @@ function stopProfilerTimerIfRunningAndRecordDelta( if (profilerStartTime >= 0) { const elapsedTime = now() - profilerStartTime; - // $FlowFixMe[unsafe-addition] addition with possible null/undefined value fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; diff --git a/packages/react-reconciler/src/ReactStrictModeWarnings.js b/packages/react-reconciler/src/ReactStrictModeWarnings.js index 900fa68a6cd34..abaafddba382f 100644 --- a/packages/react-reconciler/src/ReactStrictModeWarnings.js +++ b/packages/react-reconciler/src/ReactStrictModeWarnings.js @@ -58,7 +58,7 @@ if (__DEV__) { let pendingUNSAFE_ComponentWillUpdateWarnings: Array = []; // Tracks components we have already warned about. - const didWarnAboutUnsafeLifecycles = new Set(); + const didWarnAboutUnsafeLifecycles = new Set(); ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = ( fiber: Fiber, @@ -115,7 +115,7 @@ if (__DEV__) { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = () => { // We do an initial pass to gather component names - const componentWillMountUniqueNames = new Set(); + const componentWillMountUniqueNames = new Set(); if (pendingComponentWillMountWarnings.length > 0) { pendingComponentWillMountWarnings.forEach(fiber => { componentWillMountUniqueNames.add( @@ -126,7 +126,7 @@ if (__DEV__) { pendingComponentWillMountWarnings = []; } - const UNSAFE_componentWillMountUniqueNames = new Set(); + const UNSAFE_componentWillMountUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) { pendingUNSAFE_ComponentWillMountWarnings.forEach(fiber => { UNSAFE_componentWillMountUniqueNames.add( @@ -137,7 +137,7 @@ if (__DEV__) { pendingUNSAFE_ComponentWillMountWarnings = []; } - const componentWillReceivePropsUniqueNames = new Set(); + const componentWillReceivePropsUniqueNames = new Set(); if (pendingComponentWillReceivePropsWarnings.length > 0) { pendingComponentWillReceivePropsWarnings.forEach(fiber => { componentWillReceivePropsUniqueNames.add( @@ -149,7 +149,7 @@ if (__DEV__) { pendingComponentWillReceivePropsWarnings = []; } - const UNSAFE_componentWillReceivePropsUniqueNames = new Set(); + const UNSAFE_componentWillReceivePropsUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) { pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(fiber => { UNSAFE_componentWillReceivePropsUniqueNames.add( @@ -161,7 +161,7 @@ if (__DEV__) { pendingUNSAFE_ComponentWillReceivePropsWarnings = []; } - const componentWillUpdateUniqueNames = new Set(); + const componentWillUpdateUniqueNames = new Set(); if (pendingComponentWillUpdateWarnings.length > 0) { pendingComponentWillUpdateWarnings.forEach(fiber => { componentWillUpdateUniqueNames.add( @@ -173,7 +173,7 @@ if (__DEV__) { pendingComponentWillUpdateWarnings = []; } - const UNSAFE_componentWillUpdateUniqueNames = new Set(); + const UNSAFE_componentWillUpdateUniqueNames = new Set(); if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) { pendingUNSAFE_ComponentWillUpdateWarnings.forEach(fiber => { UNSAFE_componentWillUpdateUniqueNames.add( @@ -288,7 +288,7 @@ if (__DEV__) { let pendingLegacyContextWarning: FiberToFiberComponentsMap = new Map(); // Tracks components we have already warned about. - const didWarnAboutLegacyContext = new Set(); + const didWarnAboutLegacyContext = new Set(); ReactStrictModeWarnings.recordLegacyContextWarning = ( fiber: Fiber, @@ -331,7 +331,7 @@ if (__DEV__) { } const firstFiber = fiberArray[0]; - const uniqueNames = new Set(); + const uniqueNames = new Set(); fiberArray.forEach(fiber => { uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component'); didWarnAboutLegacyContext.add(fiber.type); diff --git a/packages/react-refresh/src/ReactFreshRuntime.js b/packages/react-refresh/src/ReactFreshRuntime.js index e44dc7c380c1a..d81c1140cab95 100644 --- a/packages/react-refresh/src/ReactFreshRuntime.js +++ b/packages/react-refresh/src/ReactFreshRuntime.js @@ -162,14 +162,14 @@ function resolveFamily(type: any) { // If we didn't care about IE11, we could use new Map/Set(iterable). function cloneMap(map: Map): Map { - const clone = new Map(); + const clone = new Map(); map.forEach((value, key) => { clone.set(key, value); }); return clone; } function cloneSet(set: Set): Set { - const clone = new Set(); + const clone = new Set(); set.forEach(value => { clone.add(value); }); @@ -201,8 +201,8 @@ export function performReactRefresh(): RefreshUpdate | null { isPerformingRefresh = true; try { - const staleFamilies = new Set(); - const updatedFamilies = new Set(); + const staleFamilies = new Set(); + const updatedFamilies = new Set(); const updates = pendingUpdates; pendingUpdates = []; @@ -418,7 +418,7 @@ export function findAffectedHostInstances( families: Array, ): Set { if (__DEV__) { - const affectedInstances = new Set(); + const affectedInstances = new Set(); mountedRoots.forEach(root => { const helpers = helpersByRoot.get(root); if (helpers === undefined) { diff --git a/packages/react-server-dom-relay/src/ReactFlightDOMRelayClientHostConfig.js b/packages/react-server-dom-relay/src/ReactFlightDOMRelayClientHostConfig.js index a5f2b243f70cd..d17838bf3d70d 100644 --- a/packages/react-server-dom-relay/src/ReactFlightDOMRelayClientHostConfig.js +++ b/packages/react-server-dom-relay/src/ReactFlightDOMRelayClientHostConfig.js @@ -44,14 +44,18 @@ export function resolveClientReference( return resolveClientReferenceImpl(moduleData); } -// $FlowFixMe[missing-local-annot] -function parseModelRecursively(response: Response, parentObj, key, value) { +function parseModelRecursively( + response: Response, + parentObj: {+[key: string]: JSONValue} | $ReadOnlyArray, + key: string, + value: JSONValue, +): $FlowFixMe { if (typeof value === 'string') { return parseModelString(response, parentObj, key, value); } if (typeof value === 'object' && value !== null) { if (isArray(value)) { - const parsedValue = []; + const parsedValue: Array<$FlowFixMe> = []; for (let i = 0; i < value.length; i++) { (parsedValue: any)[i] = parseModelRecursively( response, diff --git a/packages/react-server-dom-webpack/src/ReactFlightDOMClient.js b/packages/react-server-dom-webpack/src/ReactFlightDOMClient.js index 67bb9fad6f06d..1c4f53a0aa438 100644 --- a/packages/react-server-dom-webpack/src/ReactFlightDOMClient.js +++ b/packages/react-server-dom-webpack/src/ReactFlightDOMClient.js @@ -31,7 +31,14 @@ function startReadingFromStream( stream: ReadableStream, ): void { const reader = stream.getReader(); - function progress({done, value}: {done: boolean, value: ?any, ...}) { + function progress({ + done, + value, + }: { + done: boolean, + value: ?any, + ... + }): void | Promise { if (done) { close(response); return; diff --git a/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js b/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js index 5899ba52c1b5e..b4bc8663887a8 100644 --- a/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js +++ b/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js @@ -74,7 +74,11 @@ module.exports = function register() { }; const proxyHandlers = { - get: function (target: Function, name: string, receiver: Proxy) { + get: function ( + target: Function, + name: string, + receiver: Proxy, + ): $FlowFixMe { switch (name) { // These names are read by the Flight runtime if you end up using the exports object. case '$$typeof': @@ -143,14 +147,10 @@ module.exports = function register() { target.status = 'fulfilled'; target.value = proxy; - // $FlowFixMe[missing-local-annot] const then = (target.then = Object.defineProperties( (function then(resolve, reject: any) { // Expose to React. - return Promise.resolve( - // $FlowFixMe[incompatible-call] found when upgrading Flow - resolve(proxy), - ); + return Promise.resolve(resolve(proxy)); }: any), // If this is not used as a Promise but is treated as a reference to a `.then` // export then we should treat it as a reference to that name. @@ -200,7 +200,7 @@ module.exports = function register() { // Pretend to be a Promise in case anyone asks. return PROMISE_PROTOTYPE; }, - set: function () { + set: function (): empty { throw new Error('Cannot assign to a client module from a server module.'); }, }; diff --git a/packages/react-server-native-relay/src/ReactFlightNativeRelayClientHostConfig.js b/packages/react-server-native-relay/src/ReactFlightNativeRelayClientHostConfig.js index 981b351f18433..f76b9ba817357 100644 --- a/packages/react-server-native-relay/src/ReactFlightNativeRelayClientHostConfig.js +++ b/packages/react-server-native-relay/src/ReactFlightNativeRelayClientHostConfig.js @@ -44,14 +44,18 @@ export function resolveClientReference( return resolveClientReferenceImpl(moduleData); } -// $FlowFixMe[missing-local-annot] -function parseModelRecursively(response: Response, parentObj, key, value) { +function parseModelRecursively( + response: Response, + parentObj: {+[key: string]: JSONValue} | $ReadOnlyArray, + key: string, + value: JSONValue, +): $FlowFixMe { if (typeof value === 'string') { return parseModelString(response, parentObj, key, value); } if (typeof value === 'object' && value !== null) { if (isArray(value)) { - const parsedValue = []; + const parsedValue: Array<$FlowFixMe> = []; for (let i = 0; i < value.length; i++) { (parsedValue: any)[i] = parseModelRecursively( response, diff --git a/packages/react-server/src/ReactFizzClassComponent.js b/packages/react-server/src/ReactFizzClassComponent.js index 14b18288f14b6..818bc6672fe89 100644 --- a/packages/react-server/src/ReactFizzClassComponent.js +++ b/packages/react-server/src/ReactFizzClassComponent.js @@ -31,15 +31,15 @@ let didWarnAboutContextTypeAndContextTypes; let didWarnAboutInvalidateContextType; if (__DEV__) { - didWarnAboutUninitializedState = new Set(); - didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); - didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); - didWarnAboutDirectlyAssigningPropsToState = new Set(); - didWarnAboutUndefinedDerivedState = new Set(); - didWarnAboutContextTypeAndContextTypes = new Set(); - didWarnAboutInvalidateContextType = new Set(); - - const didWarnOnInvalidCallback = new Set(); + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + + const didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback = function (callback: mixed, callerName: string) { if (callback === null || typeof callback === 'function') { diff --git a/packages/react-server/src/ReactFizzHooks.js b/packages/react-server/src/ReactFizzHooks.js index 5a2305eb62899..2517e5ef02425 100644 --- a/packages/react-server/src/ReactFizzHooks.js +++ b/packages/react-server/src/ReactFizzHooks.js @@ -461,7 +461,7 @@ function dispatchAction( componentIdentity: Object, queue: UpdateQueue, action: A, -) { +): void { if (numberOfReRenders >= RE_RENDER_LIMIT) { throw new Error( 'Too many re-renders. React limits the number of renders to prevent ' + @@ -615,7 +615,7 @@ function useCacheRefresh(): (?() => T, ?T) => void { } function useMemoCache(size: number): Array { - const data = new Array(size); + const data = new Array(size); for (let i = 0; i < size; i++) { data[i] = REACT_MEMO_CACHE_SENTINEL; } diff --git a/packages/react-server/src/ReactFizzServer.js b/packages/react-server/src/ReactFizzServer.js index 281e8bf342a58..775bf3cacecac 100644 --- a/packages/react-server/src/ReactFizzServer.js +++ b/packages/react-server/src/ReactFizzServer.js @@ -275,10 +275,10 @@ export function createRequest( onShellError: void | ((error: mixed) => void), onFatalError: void | ((error: mixed) => void), ): Request { - const pingedTasks = []; + const pingedTasks: Array = []; const abortSet: Set = new Set(); const resources: Resources = createResources(); - const request = { + const request: Request = { destination: null, responseState, progressiveChunkSize: @@ -294,11 +294,11 @@ export function createRequest( completedRootSegment: null, abortableTasks: abortSet, pingedTasks: pingedTasks, - clientRenderedBoundaries: ([]: Array), - completedBoundaries: ([]: Array), - partialBoundaries: ([]: Array), - preamble: ([]: Array), - postamble: ([]: Array), + clientRenderedBoundaries: [], + completedBoundaries: [], + partialBoundaries: [], + preamble: [], + postamble: [], onError: onError === undefined ? defaultErrorHandler : onError, onAllReady: onAllReady === undefined ? noop : onAllReady, onShellReady: onShellReady === undefined ? noop : onShellReady, diff --git a/packages/react-server/src/ReactFlightHooks.js b/packages/react-server/src/ReactFlightHooks.js index a6f13d6900fce..270e1f24007b2 100644 --- a/packages/react-server/src/ReactFlightHooks.js +++ b/packages/react-server/src/ReactFlightHooks.js @@ -94,7 +94,7 @@ export const HooksDispatcher: Dispatcher = { return unsupportedRefresh; }, useMemoCache(size: number): Array { - const data = new Array(size); + const data = new Array(size); for (let i = 0; i < size; i++) { data[i] = REACT_MEMO_CACHE_SENTINEL; } diff --git a/packages/react-server/src/ReactFlightServer.js b/packages/react-server/src/ReactFlightServer.js index 7baa76220265a..b6d395fa7e13b 100644 --- a/packages/react-server/src/ReactFlightServer.js +++ b/packages/react-server/src/ReactFlightServer.js @@ -171,8 +171,8 @@ export function createRequest( ReactCurrentCache.current = DefaultCacheDispatcher; const abortSet: Set = new Set(); - const pingedTasks = []; - const request = { + const pingedTasks: Array = []; + const request: Request = { status: OPEN, fatalError: null, destination: null, @@ -182,9 +182,9 @@ export function createRequest( pendingChunks: 0, abortableTasks: abortSet, pingedTasks: pingedTasks, - completedModuleChunks: ([]: Array), - completedJSONChunks: ([]: Array), - completedErrorChunks: ([]: Array), + completedModuleChunks: [], + completedJSONChunks: [], + completedErrorChunks: [], writtenSymbols: new Map(), writtenModules: new Map(), writtenProviders: new Map(), @@ -485,7 +485,7 @@ function createTask( abortSet: Set, ): Task { const id = request.nextChunkId++; - const task = { + const task: Task = { id, status: PENDING, model, diff --git a/packages/react-server/src/ReactServerStreamConfigNode.js b/packages/react-server/src/ReactServerStreamConfigNode.js index 6485861818dd2..807dafe5edf6e 100644 --- a/packages/react-server/src/ReactServerStreamConfigNode.js +++ b/packages/react-server/src/ReactServerStreamConfigNode.js @@ -195,7 +195,7 @@ export function stringToChunk(content: string): Chunk { return content; } -const precomputedChunkSet = __DEV__ ? new Set() : null; +const precomputedChunkSet = __DEV__ ? new Set() : null; export function stringToPrecomputedChunk(content: string): PrecomputedChunk { const precomputedChunk = textEncoder.encode(content); diff --git a/packages/react-test-renderer/src/ReactTestHostConfig.js b/packages/react-test-renderer/src/ReactTestHostConfig.js index a3230a541aa36..8d08e033faf7d 100644 --- a/packages/react-test-renderer/src/ReactTestHostConfig.js +++ b/packages/react-test-renderer/src/ReactTestHostConfig.js @@ -51,7 +51,7 @@ export * from 'react-reconciler/src/ReactFiberHostConfigWithNoSingletons'; const NO_CONTEXT = {}; const UPDATE_SIGNAL = {}; -const nodeToInstanceMap = new WeakMap(); +const nodeToInstanceMap = new WeakMap(); if (__DEV__) { Object.freeze(NO_CONTEXT); diff --git a/packages/react-test-renderer/src/ReactTestRenderer.js b/packages/react-test-renderer/src/ReactTestRenderer.js index 43316ea1762b4..e267df329f81c 100644 --- a/packages/react-test-renderer/src/ReactTestRenderer.js +++ b/packages/react-test-renderer/src/ReactTestRenderer.js @@ -133,8 +133,7 @@ function toJSON(inst: Instance | TextInstance): ReactTestRendererNode | null { } } -// $FlowFixMe[missing-local-annot] -function childrenToTree(node) { +function childrenToTree(node: null | Fiber) { if (!node) { return null; } @@ -178,7 +177,7 @@ function flatten(arr) { return result; } -function toTree(node: ?Fiber) { +function toTree(node: null | Fiber): $FlowFixMe { if (node == null) { return null; } @@ -495,7 +494,7 @@ function create( } } let container = { - children: [], + children: ([]: Array), createNodeMock, tag: 'CONTAINER', }; @@ -615,7 +614,7 @@ function create( return entry; } -const fiberToWrapper = new WeakMap(); +const fiberToWrapper = new WeakMap(); function wrapFiber(fiber: Fiber): ReactTestInstance { let wrapper = fiberToWrapper.get(fiber); if (wrapper === undefined && fiber.alternate !== null) { diff --git a/packages/react/src/ReactAct.js b/packages/react/src/ReactAct.js index a967562d088d7..e28ecef8ad7df 100644 --- a/packages/react/src/ReactAct.js +++ b/packages/react/src/ReactAct.js @@ -106,7 +106,7 @@ export function act(callback: () => T | Thenable): Thenable { }); return { - then(resolve, reject) { + then(resolve: T => mixed, reject: mixed => mixed) { didAwaitActCall = true; thenable.then( returnValue => { @@ -184,7 +184,7 @@ export function act(callback: () => T | Thenable): Thenable { ReactCurrentActQueue.current = null; } return { - then(resolve, reject) { + then(resolve: T => mixed, reject: mixed => mixed) { didAwaitActCall = true; if (prevActScopeDepth === 0) { // If the `act` call is awaited, restore the queue we were diff --git a/packages/react/src/ReactCache.js b/packages/react/src/ReactCache.js index 5c6884db51cba..d01cb3e65129d 100644 --- a/packages/react/src/ReactCache.js +++ b/packages/react/src/ReactCache.js @@ -60,7 +60,9 @@ export function cache, T>(fn: (...A) => T): (...A) => T { // $FlowFixMe: We don't want to use rest arguments since we transpile the code. return fn.apply(null, arguments); } - const fnMap = dispatcher.getCacheForType(createCacheRoot); + const fnMap: WeakMap> = dispatcher.getCacheForType( + createCacheRoot, + ); const fnNode = fnMap.get(fn); let cacheNode: CacheNode; if (fnNode === undefined) { diff --git a/packages/react/src/ReactHooks.js b/packages/react/src/ReactHooks.js index 716e40b4f7ad8..7f1bc8d5e133b 100644 --- a/packages/react/src/ReactHooks.js +++ b/packages/react/src/ReactHooks.js @@ -57,7 +57,6 @@ export function getCacheSignal(): AbortSignal { 'This CacheSignal was requested outside React which means that it is ' + 'immediately aborted.', ); - // $FlowFixMe Flow doesn't yet know about this argument. controller.abort(reason); return controller.signal; } diff --git a/packages/shared/ReactComponentStackFrame.js b/packages/shared/ReactComponentStackFrame.js index a0d6f28ad56f8..4271d5ea10930 100644 --- a/packages/shared/ReactComponentStackFrame.js +++ b/packages/shared/ReactComponentStackFrame.js @@ -60,7 +60,7 @@ let reentry = false; let componentFrameCache; if (__DEV__) { const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); + componentFrameCache = new PossiblyWeakMap(); } export function describeNativeComponentFrame( diff --git a/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js b/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js index 57935329f1e6f..5b04ae892c875 100644 --- a/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js +++ b/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js @@ -24,12 +24,22 @@ export function useSyncExternalStoreWithSelector( isEqual?: (a: Selection, b: Selection) => boolean, ): Selection { // Use this to track the rendered snapshot. - const instRef = useRef(null); + const instRef = useRef< + | { + hasValue: true, + value: Selection, + } + | { + hasValue: false, + value: null, + } + | null, + >(null); let inst; if (instRef.current === null) { inst = { hasValue: false, - value: (null: Selection | null), + value: null, }; instRef.current = inst; } else { @@ -108,7 +118,9 @@ export function useSyncExternalStoreWithSelector( ); useEffect(() => { + // $FlowFixMe[incompatible-type] changing the variant using mutation isn't supported inst.hasValue = true; + // $FlowFixMe[incompatible-type] inst.value = value; }, [value]); diff --git a/scripts/flow/config/flowconfig b/scripts/flow/config/flowconfig index 4f27c1c552abc..7adcc3aa5822a 100644 --- a/scripts/flow/config/flowconfig +++ b/scripts/flow/config/flowconfig @@ -44,9 +44,10 @@ untyped-type-import=error %CI_MAX_WORKERS% exact_by_default=true munge_underscores=false +inference_mode=experimental.lti # Substituted by createFlowConfig.js: %REACT_RENDERER_FLOW_OPTIONS% [version] -^0.199.0 +^0.199.1 diff --git a/yarn.lock b/yarn.lock index 58e75cf7a6ff7..ae3c1d47f3b40 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8170,10 +8170,10 @@ flatted@^3.1.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.7.tgz#609f39207cb614b89d0765b477cb2d437fbf9787" integrity sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ== -flow-bin@^0.199.0: - version "0.199.0" - resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.199.0.tgz#e710c0834d4e1032529a633e0cf32d89a102fcfb" - integrity sha512-8N8jn59ghgtDSogFoy1Ld1P8NlfdlVUcXSRADDf8WyX3SMMA6b1SbqraTRXxJDNn0F3WdVBHKdufdUg73y4Nhw== +flow-bin@^0.199.1: + version "0.199.1" + resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.199.1.tgz#678eac2303fa898227f4d103264b6ce49f4430c1" + integrity sha512-Ic0Mp9iZ2exbH0mNj/XhzUWPZa9JylHb6uQARZnnYCTRwumOpjNOP0qwyRTltWrbCpfHjnWngNO9VLaVKHz2aQ== flow-parser@^0.198.2: version "0.198.2"