Flow: implicit-inexact-object=error (#25210)

* implicit-inexact-object=error
* default everything ambiguous to exact object
* inexact where exact causes errors
This commit is contained in:
Jan Kassens 2022-09-09 10:13:58 -04:00 committed by GitHub
parent 37cc6bf124
commit 8a9e7b6cef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
83 changed files with 323 additions and 292 deletions

View File

@ -34,7 +34,7 @@ export type JSONValue =
| null
| boolean
| string
| {+[key: string]: JSONValue}
| {|+[key: string]: JSONValue|}
| $ReadOnlyArray<JSONValue>;
const PENDING = 0;
@ -43,36 +43,36 @@ const RESOLVED_MODULE = 2;
const INITIALIZED = 3;
const ERRORED = 4;
type PendingChunk = {
type PendingChunk = {|
_status: 0,
_value: null | Array<() => mixed>,
_response: Response,
then(resolve: () => mixed): void,
};
type ResolvedModelChunk = {
|};
type ResolvedModelChunk = {|
_status: 1,
_value: UninitializedModel,
_response: Response,
then(resolve: () => mixed): void,
};
type ResolvedModuleChunk<T> = {
|};
type ResolvedModuleChunk<T> = {|
_status: 2,
_value: ModuleReference<T>,
_response: Response,
then(resolve: () => mixed): void,
};
type InitializedChunk<T> = {
|};
type InitializedChunk<T> = {|
_status: 3,
_value: T,
_response: Response,
then(resolve: () => mixed): void,
};
type ErroredChunk = {
|};
type ErroredChunk = {|
_status: 4,
_value: Error,
_response: Response,
then(resolve: () => mixed): void,
};
|};
type SomeChunk<T> =
| PendingChunk
| ResolvedModelChunk
@ -129,10 +129,12 @@ function readRoot<T>(): T {
}
function createPendingChunk(response: Response): PendingChunk {
// $FlowFixMe Flow doesn't support functions as constructors
return new Chunk(PENDING, null, response);
}
function createErrorChunk(response: Response, error: Error): ErroredChunk {
// $FlowFixMe Flow doesn't support functions as constructors
return new Chunk(ERRORED, error, response);
}
@ -140,6 +142,7 @@ function createInitializedChunk<T>(
response: Response,
value: T,
): InitializedChunk<T> {
// $FlowFixMe Flow doesn't support functions as constructors
return new Chunk(INITIALIZED, value, response);
}
@ -168,6 +171,7 @@ function createResolvedModelChunk(
response: Response,
value: UninitializedModel,
): ResolvedModelChunk {
// $FlowFixMe Flow doesn't support functions as constructors
return new Chunk(RESOLVED_MODEL, value, response);
}
@ -175,6 +179,7 @@ function createResolvedModuleChunk<T>(
response: Response,
value: ModuleReference<T>,
): ResolvedModuleChunk<T> {
// $FlowFixMe Flow doesn't support functions as constructors
return new Chunk(RESOLVED_MODULE, value, response);
}
@ -333,7 +338,7 @@ export function parseModelString(
export function parseModelTuple(
response: Response,
value: {+[key: string]: JSONValue} | $ReadOnlyArray<JSONValue>,
value: {|+[key: string]: JSONValue|} | $ReadOnlyArray<JSONValue>,
): any {
const tuple: [mixed, mixed, mixed, mixed] = (value: any);

View File

@ -10,11 +10,11 @@
import type {ResponseBase} from './ReactFlightClient';
import type {StringDecoder} from './ReactFlightClientHostConfig';
export type Response = ResponseBase & {
export type Response = ResponseBase & {|
_partialRow: string,
_fromJSON: (key: string, value: JSONValue) => any,
_stringDecoder: StringDecoder,
};
|};
export type UninitializedModel = string;

View File

@ -51,10 +51,10 @@ type Dispatch<A> = A => void;
let primitiveStackCache: null | Map<string, Array<any>> = null;
type Hook = {
type Hook = {|
memoizedState: any,
next: Hook | null,
};
|};
function getPrimitiveStackCache(): Map<string, Array<any>> {
// This initializes a cache of all primitive hooks so that the top
@ -371,12 +371,12 @@ const DispatcherProxy = new Proxy(Dispatcher, DispatcherProxyHandler);
// Inspect
export type HookSource = {
export type HookSource = {|
lineNumber: number | null,
columnNumber: number | null,
fileName: string | null,
functionName: string | null,
};
|};
export type HooksNode = {
id: number | null,

View File

@ -34,24 +34,24 @@ export type LoggerEvent =
|}
| {|
+event_name: 'select-element',
+metadata: {
+metadata: {|
+source: string,
},
|},
|}
| {|
+event_name: 'inspect-element-button-clicked',
|}
| {|
+event_name: 'profiling-start',
+metadata: {
+metadata: {|
+current_tab: string,
},
|},
|}
| {|
+event_name: 'profiler-tab-changed',
+metadata: {
+metadata: {|
+tabId: string,
},
|},
|}
| {|
+event_name: 'settings-changed',

View File

@ -151,13 +151,13 @@ export function patch({
showInlineWarningsAndErrors,
hideConsoleLogsInStrictMode,
browserTheme,
}: {
}: {|
appendComponentStack: boolean,
breakOnConsoleErrors: boolean,
showInlineWarningsAndErrors: boolean,
hideConsoleLogsInStrictMode: boolean,
browserTheme: BrowserTheme,
}): void {
|}): void {
// Settings may change after we've patched the console.
// Using a shared ref allows the patch function to read the latest values.
consoleSettingsRef.appendComponentStack = appendComponentStack;

View File

@ -79,7 +79,7 @@ import type {
DisplayDensity,
} from './devtools/views/Settings/SettingsContext';
export const THEME_STYLES: {[style: Theme | DisplayDensity]: any} = {
export const THEME_STYLES: {[style: Theme | DisplayDensity]: any, ...} = {
light: {
'--color-attribute-name': '#ef6632',
'--color-attribute-name-not-editable': '#23272f',

View File

@ -22,7 +22,7 @@ export default function useContextMenu({
data: Object,
id: string,
onChange?: OnChangeFn,
ref: {current: ElementRef<*> | null},
ref: {|current: ElementRef<*> | null|},
|}) {
const {showMenu} = useContext<RegistryContextType>(RegistryContext);

View File

@ -119,7 +119,7 @@ type TreeProps = {|
badgeClassName: string,
actions: React$Node,
className: string,
clearMessages: () => {},
clearMessages: () => void,
entries: Array<[string, number]>,
isTransitionPending: boolean,
label: string,

View File

@ -23,9 +23,9 @@ export type TooltipFiberData = {|
name: string,
|};
export type Props = {
export type Props = {|
fiberData: ChartNode,
};
|};
export default function HoveredFiberInfo({fiberData}: Props) {
const {profilerStore} = useContext(StoreContext);

View File

@ -82,11 +82,11 @@ type ListProps = {|
width: number,
|};
type DragState = {
type DragState = {|
commitIndex: number,
left: number,
sizeIncrement: number,
};
|};
function List({
commitData,

View File

@ -224,10 +224,10 @@ export function installHook(target: any): DevToolsHook | null {
function patchConsoleForInitialRenderInStrictMode({
hideConsoleLogsInStrictMode,
browserTheme,
}: {
}: {|
hideConsoleLogsInStrictMode: boolean,
browserTheme: BrowserTheme,
}) {
|}) {
const overrideConsoleMethods = [
'error',
'group',

View File

@ -18,11 +18,11 @@ export type Position = {|
column: number,
|};
export type SourceFileASTWithHookDetails = {
export type SourceFileASTWithHookDetails = {|
sourceFileAST: File,
line: number,
source: string,
};
|};
export const NO_HOOK_NAME = '<no-hook>';

View File

@ -168,12 +168,12 @@ export function checkForUpdate({
element,
refresh,
store,
}: {
}: {|
bridge: FrontendBridge,
element: Element,
refresh: RefreshFunction,
store: Store,
}): void {
|}): void {
const {id} = element;
const rendererID = store.getRendererIDForElement(id);
if (rendererID != null) {

View File

@ -19,7 +19,7 @@ type ItemMetadata = {|
offset: number,
size: number,
|};
type ItemMetadataMap = { [index: number]: ItemMetadata };
type ItemMetadataMap = { [index: number]: ItemMetadata, ... };
type InstanceProps = {|
columnMetadataMap: ItemMetadataMap,
estimatedColumnWidth: number,

View File

@ -18,7 +18,7 @@ type ItemMetadata = {|
size: number,
|};
type InstanceProps = {|
itemMetadataMap: { [index: number]: ItemMetadata },
itemMetadataMap: { [index: number]: ItemMetadata, ... },
estimatedItemSize: number,
lastMeasuredIndex: number,
|};

View File

@ -80,7 +80,7 @@ function CanvasPage({profilerData, viewState}: Props) {
className={styles.CanvasPage}
style={{backgroundColor: COLORS.BACKGROUND}}>
<AutoSizer>
{({height, width}: {height: number, width: number}) => (
{({height, width}: {|height: number, width: number|}) => (
<AutoSizedCanvas
data={profilerData}
height={height}

View File

@ -17,11 +17,11 @@ export type Return<T> = Return_<*, T>;
// Project types
export type ErrorStackFrame = {
export type ErrorStackFrame = {|
fileName: string,
lineNumber: number,
columnNumber: number,
};
|};
export type Milliseconds = number;

View File

@ -16,11 +16,11 @@ export default function useSmartTooltip({
canvasRef,
mouseX,
mouseY,
}: {
}: {|
canvasRef: {|current: HTMLCanvasElement | null|},
mouseX: number,
mouseY: number,
}) {
|}) {
const ref = useRef<HTMLElement | null>(null);
// HACK: Browser extension reports window.innerHeight of 0,

View File

@ -47,7 +47,7 @@ const HIDDEN_RECT = {
};
export class ResizableView extends View {
_canvasRef: {current: HTMLCanvasElement | null};
_canvasRef: {|current: HTMLCanvasElement | null|};
_layoutState: LayoutState;
_mutableViewStateKey: string;
_resizeBar: ResizeBarView;
@ -60,7 +60,7 @@ export class ResizableView extends View {
frame: Rect,
subview: View,
viewState: ViewState,
canvasRef: {current: HTMLCanvasElement | null},
canvasRef: {|current: HTMLCanvasElement | null|},
label: string,
) {
super(surface, frame, noopLayout);

View File

@ -35,12 +35,12 @@ function clampLength({
minContentLength,
maxContentLength,
containerLength,
}: {
}: {|
state: ScrollState,
minContentLength: number,
maxContentLength: number,
containerLength: number,
}): ScrollState {
|}): ScrollState {
return {
offset: state.offset,
length: clamp(
@ -62,12 +62,12 @@ export function clampState({
minContentLength,
maxContentLength,
containerLength,
}: {
}: {|
state: ScrollState,
minContentLength: number,
maxContentLength: number,
containerLength: number,
}): ScrollState {
|}): ScrollState {
return clampOffset(
clampLength({
state,
@ -83,11 +83,11 @@ export function translateState({
state,
delta,
containerLength,
}: {
}: {|
state: ScrollState,
delta: number,
containerLength: number,
}): ScrollState {
|}): ScrollState {
return clampOffset(
{
offset: state.offset + delta,
@ -119,7 +119,7 @@ export function zoomState({
minContentLength,
maxContentLength,
containerLength,
}: {
}: {|
state: ScrollState,
multiplier: number,
fixedPoint: number,
@ -127,7 +127,7 @@ export function zoomState({
minContentLength: number,
maxContentLength: number,
containerLength: number,
}): ScrollState {
|}): ScrollState {
// Length and offset must be computed separately, so that if the length is
// clamped the offset will still be correct (unless it gets clamped too).
@ -164,7 +164,7 @@ export function moveStateToRange({
minContentLength,
maxContentLength,
containerLength,
}: {
}: {|
state: ScrollState,
rangeStart: number,
rangeEnd: number,
@ -173,7 +173,7 @@ export function moveStateToRange({
minContentLength: number,
maxContentLength: number,
containerLength: number,
}): ScrollState {
|}): ScrollState {
// Length and offset must be computed separately, so that if the length is
// clamped the offset will still be correct (unless it gets clamped too).

View File

@ -733,7 +733,7 @@ export function isSuspenseInstanceFallback(instance: SuspenseInstance) {
export function getSuspenseInstanceFallbackErrorDetails(
instance: SuspenseInstance,
): {digest: ?string, message?: string, stack?: string} {
): {|digest: ?string, message?: string, stack?: string|} {
const dataset =
instance.nextSibling && ((instance.nextSibling: any): HTMLElement).dataset;
let digest, message, stack;
@ -1320,10 +1320,10 @@ export function setFocusIfFocusable(node: Instance): boolean {
return didFocus;
}
type RectRatio = {
type RectRatio = {|
ratio: number,
rect: BoundingRect,
};
|};
export function setupIntersectionObserver(
targets: Array<Instance>,

View File

@ -20,7 +20,7 @@ export type DispatchConfig = {|
registrationName?: string,
|};
type BaseSyntheticEvent = {
type BaseSyntheticEvent = {|
isPersistent: () => boolean,
isPropagationStopped: () => boolean,
_dispatchInstances?: null | Array<Fiber | null> | Fiber,
@ -31,14 +31,14 @@ type BaseSyntheticEvent = {
relatedTarget?: mixed,
type: string,
currentTarget: null | EventTarget,
};
|};
export type KnownReactSyntheticEvent = BaseSyntheticEvent & {
export type KnownReactSyntheticEvent = BaseSyntheticEvent & {|
_reactName: string,
};
export type UnknownReactSyntheticEvent = BaseSyntheticEvent & {
|};
export type UnknownReactSyntheticEvent = BaseSyntheticEvent & {|
_reactName: null,
};
|};
export type ReactSyntheticEvent =
| KnownReactSyntheticEvent

View File

@ -13,7 +13,8 @@ import assign from 'shared/assign';
import getEventCharCode from './getEventCharCode';
type EventInterfaceType = {
[propName: string]: 0 | ((event: {[propName: string]: mixed}) => mixed),
[propName: string]: 0 | ((event: {[propName: string]: mixed, ...}) => mixed),
...,
};
function functionThatReturnsTrue() {
@ -44,7 +45,7 @@ function createSyntheticEvent(Interface: EventInterfaceType) {
reactName: string | null,
reactEventType: string,
targetInst: Fiber,
nativeEvent: {[propName: string]: mixed},
nativeEvent: {[propName: string]: mixed, ...},
nativeEventTarget: null | EventTarget,
) {
this._reactName = reactName;

View File

@ -37,9 +37,9 @@ type Options = {|
|};
// TODO: Move to sub-classing ReadableStream.
type ReactDOMServerReadableStream = ReadableStream & {
type ReactDOMServerReadableStream = ReadableStream & {|
allReady: Promise<void>,
};
|};
function renderToReadableStream(
children: ReactNodeList,

View File

@ -11,9 +11,9 @@ import type {ReactNodeList} from 'shared/ReactTypes';
import {version, renderToStringImpl} from './ReactDOMLegacyServerImpl';
type ServerOptions = {
type ServerOptions = {|
identifierPrefix?: string,
};
|};
function renderToString(
children: ReactNodeList,

View File

@ -23,9 +23,9 @@ import {
createRootFormatContext,
} from './ReactDOMServerLegacyFormatConfig';
type ServerOptions = {
type ServerOptions = {|
identifierPrefix?: string,
};
|};
function onError() {
// Non-fatal errors are ignored.

View File

@ -15,9 +15,9 @@ import {
renderToStaticNodeStream,
} from './ReactDOMLegacyServerNodeStream';
type ServerOptions = {
type ServerOptions = {|
identifierPrefix?: string,
};
|};
function renderToString(
children: ReactNodeList,

View File

@ -25,9 +25,9 @@ import {
import {Readable} from 'stream';
type ServerOptions = {
type ServerOptions = {|
identifierPrefix?: string,
};
|};
class ReactMarkupReadableStream extends Readable {
request: Request;

View File

@ -105,10 +105,10 @@ const scriptRegex = /(<\/|<)(s)(cript)/gi;
const scriptReplacer = (match, prefix, s, suffix) =>
`${prefix}${s === 's' ? '\\u0073' : '\\u0053'}${suffix}`;
export type BootstrapScriptDescriptor = {
export type BootstrapScriptDescriptor = {|
src: string,
integrity?: string,
};
|};
// Allows us to keep track of what we've already written so we can refer back to it.
export function createResponseState(
identifierPrefix: string | void,
@ -203,10 +203,10 @@ const HTML_COLGROUP_MODE = 7;
type InsertionMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
// Lets us keep track of contextual state and pick it back up after suspending.
export type FormatContext = {
export type FormatContext = {|
insertionMode: InsertionMode, // root/svg/html/mathml/table
selectedValue: null | string | Array<string>, // the selected value(s) inside a <select>, or null outside <select>
};
|};
function createFormatContext(
insertionMode: InsertionMode,

View File

@ -28,7 +28,7 @@ import type {
export const isPrimaryRenderer = false;
export type ResponseState = {
export type ResponseState = {|
// Keep this in sync with ReactDOMServerFormatConfig
bootstrapChunks: Array<Chunk | PrecomputedChunk>,
startInlineScript: PrecomputedChunk,
@ -42,7 +42,7 @@ export type ResponseState = {
sentClientRenderFunction: boolean,
// This is an extra field for the legacy renderer
generateStaticMarkup: boolean,
};
|};
export function createResponseState(
generateStaticMarkup: boolean,

View File

@ -128,7 +128,7 @@ function createLstatMap(): Map<string, Array<boolean | Record<mixed>>> {
return new Map();
}
export function lstat(path: string, options?: {bigint?: boolean}): mixed {
export function lstat(path: string, options?: {|bigint?: boolean|}): mixed {
checkPathInDev(path);
let bigint = false;
if (options && options.bigint) {
@ -167,7 +167,7 @@ function createReaddirMap(): Map<
export function readdir(
path: string,
options?: string | {encoding?: string, withFileTypes?: boolean},
options?: string | {|encoding?: string, withFileTypes?: boolean|},
): mixed {
checkPathInDev(path);
let encoding = 'utf8';
@ -215,12 +215,12 @@ export function readFile(
path: string,
options:
| string
| {
| {|
encoding?: string | null,
// Unsupported:
flag?: string, // Doesn't make sense except "r"
signal?: mixed, // We'll have our own signal
},
|},
): string | Buffer {
checkPathInDev(path);
const map = unstable_getCacheForType(createReadFileMap);
@ -270,7 +270,7 @@ function createReadlinkMap(): Map<string, Array<string | Record<mixed>>> {
export function readlink(
path: string,
options?: string | {encoding?: string},
options?: string | {|encoding?: string|},
): mixed {
checkPathInDev(path);
let encoding = 'utf8';
@ -311,7 +311,7 @@ function createRealpathMap(): Map<string, Array<string | Record<mixed>>> {
export function realpath(
path: string,
options?: string | {encoding?: string},
options?: string | {|encoding?: string|},
): mixed {
checkPathInDev(path);
let encoding = 'utf8';
@ -350,7 +350,7 @@ function createStatMap(): Map<string, Array<boolean | Record<mixed>>> {
return new Map();
}
export function stat(path: string, options?: {bigint?: boolean}): mixed {
export function stat(path: string, options?: {|bigint?: boolean|}): mixed {
checkPathInDev(path);
let bigint = false;
if (options && options.bigint) {

View File

@ -14,15 +14,15 @@ const {useCallback, useEffect, useLayoutEffect, useRef} = React;
type FocusEvent = SyntheticEvent<EventTarget>;
type UseFocusOptions = {
type UseFocusOptions = {|
disabled?: boolean,
onBlur?: ?(FocusEvent) => void,
onFocus?: ?(FocusEvent) => void,
onFocusChange?: ?(boolean) => void,
onFocusVisibleChange?: ?(boolean) => void,
};
|};
type UseFocusWithinOptions = {
type UseFocusWithinOptions = {|
disabled?: boolean,
onAfterBlurWithin?: FocusEvent => void,
onBeforeBlurWithin?: FocusEvent => void,
@ -30,7 +30,7 @@ type UseFocusWithinOptions = {
onFocusWithin?: FocusEvent => void,
onFocusWithinChange?: boolean => void,
onFocusWithinVisibleChange?: boolean => void,
};
|};
const isMac =
typeof window !== 'undefined' && window.navigator != null
@ -154,7 +154,7 @@ function useFocusLifecycles() {
}
export function useFocus(
focusTargetRef: {current: null | Node},
focusTargetRef: {|current: null | Node|},
{
disabled,
onBlur,
@ -164,9 +164,10 @@ export function useFocus(
}: UseFocusOptions,
): void {
// Setup controlled state for this useFocus hook
const stateRef = useRef<null | {isFocused: boolean, isFocusVisible: boolean}>(
{isFocused: false, isFocusVisible: false},
);
const stateRef = useRef<null | {|
isFocused: boolean,
isFocusVisible: boolean,
|}>({isFocused: false, isFocusVisible: false});
const focusHandle = useEvent('focusin');
const blurHandle = useEvent('focusout');
const focusVisibleHandles = useFocusVisibleInputHandles();
@ -248,7 +249,7 @@ export function useFocus(
export function useFocusWithin<T>(
focusWithinTargetRef:
| {current: null | T}
| {|current: null | T|}
| ((focusWithinTarget: null | T) => void),
{
disabled,
@ -261,9 +262,10 @@ export function useFocusWithin<T>(
}: UseFocusWithinOptions,
): (focusWithinTarget: null | T) => void {
// Setup controlled state for this useFocus hook
const stateRef = useRef<null | {isFocused: boolean, isFocusVisible: boolean}>(
{isFocused: false, isFocusVisible: false},
);
const stateRef = useRef<null | {|
isFocused: boolean,
isFocusVisible: boolean,
|}>({isFocused: false, isFocusVisible: false});
const focusHandle = useEvent('focusin');
const blurHandle = useEvent('focusout');
const afterBlurHandle = useEvent('afterblur');

View File

@ -108,13 +108,13 @@ export type EventListenerRemoveOptions = $ReadOnly<{|
// TODO?: this will be changed in the future to be w3c-compatible and allow "EventListener" objects as well as functions.
export type EventListener = Function;
type InternalEventListeners = {
type InternalEventListeners = {|
[string]: {|
listener: EventListener,
options: EventListenerOptions,
invalidated: boolean,
|}[],
};
|};
// TODO: Remove this conditional once all changes have propagated.
if (registerEventHandler) {
@ -255,6 +255,8 @@ class ReactFabricHostComponent {
const passive = optionsObj.passive || false;
const signal = null; // TODO: implement signal/AbortSignal
/* $FlowFixMe the old version of Flow doesn't have a good way to define an
* empty exact object. */
const eventListeners: InternalEventListeners = this._eventListeners || {};
if (this._eventListeners == null) {
this._eventListeners = eventListeners;

View File

@ -62,38 +62,38 @@ export type PartialAttributeConfiguration = $ReadOnly<{
...
}>;
export type ViewConfig = $ReadOnly<{
export type ViewConfig = $ReadOnly<{|
Commands?: $ReadOnly<{[commandName: string]: number, ...}>,
Constants?: $ReadOnly<{[name: string]: mixed, ...}>,
Manager?: string,
NativeProps?: $ReadOnly<{[propName: string]: string, ...}>,
baseModuleName?: ?string,
bubblingEventTypes?: $ReadOnly<{
[eventName: string]: $ReadOnly<{
phasedRegistrationNames: $ReadOnly<{
[eventName: string]: $ReadOnly<{|
phasedRegistrationNames: $ReadOnly<{|
captured: string,
bubbled: string,
skipBubbling?: ?boolean,
}>,
}>,
|}>,
|}>,
...,
}>,
directEventTypes?: $ReadOnly<{
[eventName: string]: $ReadOnly<{
[eventName: string]: $ReadOnly<{|
registrationName: string,
}>,
|}>,
...,
}>,
uiViewClassName: string,
validAttributes: AttributeConfiguration,
}>;
|}>;
export type PartialViewConfig = $ReadOnly<{
export type PartialViewConfig = $ReadOnly<{|
bubblingEventTypes?: $PropertyType<ViewConfig, 'bubblingEventTypes'>,
directEventTypes?: $PropertyType<ViewConfig, 'directEventTypes'>,
uiViewClassName: string,
validAttributes?: PartialAttributeConfiguration,
}>;
|}>;
export type NativeMethods = $ReadOnly<{|
blur(): void,

View File

@ -22,7 +22,7 @@ export type PluginName = string;
export type EventSystemFlags = number;
export type LegacyPluginModule<NativeEvent> = {
export type LegacyPluginModule<NativeEvent> = {|
eventTypes: EventTypes,
extractEvents: (
topLevelType: TopLevelType,
@ -33,4 +33,4 @@ export type LegacyPluginModule<NativeEvent> = {
container?: null | EventTarget,
) => ?ReactSyntheticEvent,
tapMoveThreshold?: number,
};
|};

View File

@ -58,9 +58,9 @@ const SUSPENSE_UPDATE_TO_CLIENT_RENDER = new Uint8Array(1);
SUSPENSE_UPDATE_TO_CLIENT_RENDER[0] = SUSPENSE_UPDATE_TO_CLIENT_RENDER_TAG;
// Per response,
export type ResponseState = {
export type ResponseState = {|
nextSuspenseID: number,
};
|};
// Allows us to keep track of what we've already written so we can refer back to it.
export function createResponseState(): ResponseState {

View File

@ -33,14 +33,14 @@ import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
import {HostRoot, OffscreenComponent} from './ReactWorkTags';
import {OffscreenVisible} from './ReactFiberOffscreenComponent';
export type ConcurrentUpdate = {
export type ConcurrentUpdate = {|
next: ConcurrentUpdate,
lane: Lane,
};
|};
type ConcurrentQueue = {
type ConcurrentQueue = {|
pending: ConcurrentUpdate | null,
};
|};
// If a render is in progress, and we receive an update from a concurrent event,
// we wait until the current render is over (either finished or interrupted)

View File

@ -33,14 +33,14 @@ import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
import {HostRoot, OffscreenComponent} from './ReactWorkTags';
import {OffscreenVisible} from './ReactFiberOffscreenComponent';
export type ConcurrentUpdate = {
export type ConcurrentUpdate = {|
next: ConcurrentUpdate,
lane: Lane,
};
|};
type ConcurrentQueue = {
type ConcurrentQueue = {|
pending: ConcurrentUpdate | null,
};
|};
// If a render is in progress, and we receive an update from a concurrent event,
// we wait until the current render is over (either finished or interrupted)

View File

@ -22,6 +22,7 @@ type HiddenContext = {
// order to reveal the hidden content.
// TODO: Remove `subtreeLanes` context from work loop in favor of this one.
baseLanes: number,
...
};
// TODO: This isn't being used yet, but it's intended to replace the

View File

@ -22,6 +22,7 @@ type HiddenContext = {
// order to reveal the hidden content.
// TODO: Remove `subtreeLanes` context from work loop in favor of this one.
baseLanes: number,
...
};
// TODO: This isn't being used yet, but it's intended to replace the

View File

@ -1032,10 +1032,10 @@ function rerenderReducer<S, I, A>(
}
type MutableSourceMemoizedState<Source, Snapshot> = {|
refs: {
refs: {|
getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
setSnapshot: Snapshot => void,
},
|},
source: MutableSource<any>,
subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
|};

View File

@ -1032,10 +1032,10 @@ function rerenderReducer<S, I, A>(
}
type MutableSourceMemoizedState<Source, Snapshot> = {|
refs: {
refs: {|
getSnapshot: MutableSourceGetSnapshotFn<Source, Snapshot>,
setSnapshot: Snapshot => void,
},
|},
source: MutableSource<any>,
subscribe: MutableSourceSubscribeFn<Source, Snapshot>,
|};

View File

@ -38,11 +38,11 @@ import {initializeUpdateQueue} from './ReactFiberClassUpdateQueue.new';
import {LegacyRoot, ConcurrentRoot} from './ReactRootTags';
import {createCache, retainCache} from './ReactFiberCacheComponent.new';
export type RootState = {
export type RootState = {|
element: any,
isDehydrated: boolean,
cache: Cache,
};
|};
function FiberRootNode(
containerInfo,

View File

@ -38,11 +38,11 @@ import {initializeUpdateQueue} from './ReactFiberClassUpdateQueue.old';
import {LegacyRoot, ConcurrentRoot} from './ReactRootTags';
import {createCache, retainCache} from './ReactFiberCacheComponent.old';
export type RootState = {
export type RootState = {|
element: any,
isDehydrated: boolean,
cache: Cache,
};
|};
function FiberRootNode(
containerInfo,

View File

@ -19,33 +19,33 @@ import {enableTransitionTracing} from 'shared/ReactFeatureFlags';
import {createCursor, push, pop} from './ReactFiberStack.new';
import {getWorkInProgressTransitions} from './ReactFiberWorkLoop.new';
export type SuspenseInfo = {name: string | null};
export type SuspenseInfo = {|name: string | null|};
export type PendingTransitionCallbacks = {
export type PendingTransitionCallbacks = {|
transitionStart: Array<Transition> | null,
transitionProgress: Map<Transition, PendingBoundaries> | null,
transitionComplete: Array<Transition> | null,
markerProgress: Map<
string,
{pendingBoundaries: PendingBoundaries, transitions: Set<Transition>},
{|pendingBoundaries: PendingBoundaries, transitions: Set<Transition>|},
> | null,
markerIncomplete: Map<
string,
{aborts: Array<TransitionAbort>, transitions: Set<Transition>},
{|aborts: Array<TransitionAbort>, transitions: Set<Transition>|},
> | null,
markerComplete: Map<string, Set<Transition>> | null,
};
|};
export type Transition = {
export type Transition = {|
name: string,
startTime: number,
};
|};
export type BatchConfigTransition = {
export type BatchConfigTransition = {|
name?: string,
startTime?: number,
_updatedFibers?: Set<Fiber>,
};
|};
// TODO: Is there a way to not include the tag or name here?
export type TracingMarkerInstance = {|

View File

@ -19,33 +19,33 @@ import {enableTransitionTracing} from 'shared/ReactFeatureFlags';
import {createCursor, push, pop} from './ReactFiberStack.old';
import {getWorkInProgressTransitions} from './ReactFiberWorkLoop.old';
export type SuspenseInfo = {name: string | null};
export type SuspenseInfo = {|name: string | null|};
export type PendingTransitionCallbacks = {
export type PendingTransitionCallbacks = {|
transitionStart: Array<Transition> | null,
transitionProgress: Map<Transition, PendingBoundaries> | null,
transitionComplete: Array<Transition> | null,
markerProgress: Map<
string,
{pendingBoundaries: PendingBoundaries, transitions: Set<Transition>},
{|pendingBoundaries: PendingBoundaries, transitions: Set<Transition>|},
> | null,
markerIncomplete: Map<
string,
{aborts: Array<TransitionAbort>, transitions: Set<Transition>},
{|aborts: Array<TransitionAbort>, transitions: Set<Transition>|},
> | null,
markerComplete: Map<string, Set<Transition>> | null,
};
|};
export type Transition = {
export type Transition = {|
name: string,
startTime: number,
};
|};
export type BatchConfigTransition = {
export type BatchConfigTransition = {|
name?: string,
startTime?: number,
_updatedFibers?: Set<Fiber>,
};
|};
// TODO: Is there a way to not include the tag or name here?
export type TracingMarkerInstance = {|

View File

@ -64,10 +64,10 @@ import {getIsHydrating} from './ReactFiberHydrationContext.new';
import {clz32} from './clz32';
import {Forked, NoFlags} from './ReactFiberFlags';
export type TreeContext = {
export type TreeContext = {|
id: number,
overflow: string,
};
|};
// TODO: Use the unified fiber stack module instead of this local one?
// Intentionally not using it yet to derisk the initial implementation, because

View File

@ -64,10 +64,10 @@ import {getIsHydrating} from './ReactFiberHydrationContext.old';
import {clz32} from './clz32';
import {Forked, NoFlags} from './ReactFiberFlags';
export type TreeContext = {
export type TreeContext = {|
id: number,
overflow: string,
};
|};
// TODO: Use the unified fiber stack module instead of this local one?
// Intentionally not using it yet to derisk the initial implementation, because

View File

@ -258,7 +258,7 @@ type BaseFiberRootProperties = {|
onRecoverableError: (
error: mixed,
errorInfo: {digest?: ?string, componentStack?: ?string},
errorInfo: {|digest?: ?string, componentStack?: ?string|},
) => void,
|};
@ -280,22 +280,22 @@ type SuspenseCallbackOnlyFiberRootProperties = {|
hydrationCallbacks: null | SuspenseHydrationCallbacks,
|};
export type TransitionTracingCallbacks = {
export type TransitionTracingCallbacks = {|
onTransitionStart?: (transitionName: string, startTime: number) => void,
onTransitionProgress?: (
transitionName: string,
startTime: number,
currentTime: number,
pending: Array<{name: null | string}>,
pending: Array<{|name: null | string|}>,
) => void,
onTransitionIncomplete?: (
transitionName: string,
startTime: number,
deletions: Array<{
deletions: Array<{|
type: string,
name?: string | null,
endTime: number,
}>,
|}>,
) => void,
onTransitionComplete?: (
transitionName: string,
@ -307,17 +307,17 @@ export type TransitionTracingCallbacks = {
marker: string,
startTime: number,
currentTime: number,
pending: Array<{name: null | string}>,
pending: Array<{|name: null | string|}>,
) => void,
onMarkerIncomplete?: (
transitionName: string,
marker: string,
startTime: number,
deletions: Array<{
deletions: Array<{|
type: string,
name?: string | null,
endTime: number,
}>,
|}>,
) => void,
onMarkerComplete?: (
transitionName: string,
@ -325,7 +325,7 @@ export type TransitionTracingCallbacks = {
startTime: number,
endTime: number,
) => void,
};
|};
// The following fields are only used in transition tracing in Profile builds
type TransitionTracingOnlyFiberRootProperties = {|

View File

@ -506,13 +506,15 @@ export function onCommitRoot(): void {
export type IntersectionObserverOptions = Object;
export type ObserveVisibleRectsCallback = (
intersections: Array<{ratio: number, rect: BoundingRect}>,
intersections: Array<{|ratio: number, rect: BoundingRect|}>,
) => void;
export function observeVisibleRects(
hostRoot: Instance,
selectors: Array<Selector>,
callback: (intersections: Array<{ratio: number, rect: BoundingRect}>) => void,
callback: (
intersections: Array<{|ratio: number, rect: BoundingRect|}>,
) => void,
options?: IntersectionObserverOptions,
): {|disconnect: () => void|} {
if (!supportsTestSelectors) {

View File

@ -26,19 +26,19 @@ import {
createRootFormatContext,
} from 'react-server/src/ReactServerFormatConfig';
type Options = {
type Options = {|
identifierPrefix?: string,
bootstrapScriptContent?: string,
bootstrapScripts: Array<string>,
bootstrapModules: Array<string>,
progressiveChunkSize?: number,
onError: (error: mixed) => void,
};
|};
opaque type Stream = {
opaque type Stream = {|
destination: Destination,
request: Request,
};
|};
function renderToStream(children: ReactNodeList, options: Options): Stream {
const destination = {

View File

@ -24,8 +24,10 @@ export {createResponse, close};
export function resolveRow(response: Response, chunk: RowEncoding): void {
if (chunk[0] === 'J') {
// $FlowFixMe unable to refine on array indices
resolveModel(response, chunk[1], chunk[2]);
} else if (chunk[0] === 'M') {
// $FlowFixMe unable to refine on array indices
resolveModule(response, chunk[1], chunk[2]);
} else if (chunk[0] === 'S') {
// $FlowFixMe: Flow doesn't support disjoint unions on tuples.

View File

@ -14,8 +14,8 @@ export type JSONValue =
| number
| boolean
| null
| {+[key: string]: JSONValue}
| Array<JSONValue>;
| {|+[key: string]: JSONValue|}
| $ReadOnlyArray<JSONValue>;
export type RowEncoding =
| ['J', number, JSONValue]

View File

@ -19,10 +19,10 @@ import {
startFlowing,
} from 'react-server/src/ReactFlightServer';
type Options = {
type Options = {|
onError?: (error: mixed) => void,
identifierPrefix?: string,
};
|};
function render(
model: ReactModel,

View File

@ -78,7 +78,7 @@ export function processErrorChunk(
function convertModelToJSON(
request: Request,
parent: {+[key: string]: ReactModel} | $ReadOnlyArray<ReactModel>,
parent: {|+[key: string]: ReactModel|} | $ReadOnlyArray<ReactModel>,
key: string,
model: ReactModel,
): JSONValue {
@ -91,7 +91,9 @@ function convertModelToJSON(
}
return jsonArray;
} else {
const jsonObj: {[key: string]: JSONValue} = {};
/* $FlowFixMe the old version of Flow doesn't have a good way to define
* an empty exact object. */
const jsonObj: {|[key: string]: JSONValue|} = {};
for (const nextKey in json) {
if (hasOwnProperty.call(json, nextKey)) {
jsonObj[nextKey] = convertModelToJSON(
@ -113,6 +115,7 @@ export function processModelChunk(
id: number,
model: ReactModel,
): Chunk {
// $FlowFixMe no good way to define an empty exact object
const json = convertModelToJSON(request, {}, '', model);
return ['J', id, json];
}
@ -159,6 +162,7 @@ export function flushBuffered(destination: Destination) {}
export function beginWriting(destination: Destination) {}
export function writeChunk(destination: Destination, chunk: Chunk): void {
// $FlowFixMe `Chunk` doesn't flow into `JSONValue` because of the `E` row type.
emitRow(destination, chunk);
}
@ -166,6 +170,7 @@ export function writeChunkAndReturn(
destination: Destination,
chunk: Chunk,
): boolean {
// $FlowFixMe `Chunk` doesn't flow into `JSONValue` because of the `E` row type.
emitRow(destination, chunk);
return true;
}

View File

@ -7,12 +7,12 @@
* @flow
*/
export type Destination = {
export type Destination = {|
buffer: string,
done: boolean,
fatal: boolean,
error: mixed,
};
|};
export type PrecomputedChunk = string;
export type Chunk = string;

View File

@ -9,20 +9,20 @@
import type {Thenable} from 'shared/ReactTypes';
export type WebpackSSRMap = {
[clientId: string]: {
export type WebpackSSRMap = {|
[clientId: string]: {|
[clientExportName: string]: ModuleMetaData,
},
};
|},
|};
export type BundlerConfig = null | WebpackSSRMap;
export opaque type ModuleMetaData = {
export opaque type ModuleMetaData = {|
id: string,
chunks: Array<string>,
name: string,
async: boolean,
};
|};
// eslint-disable-next-line no-unused-vars
export opaque type ModuleReference<T> = ModuleMetaData;

View File

@ -19,9 +19,9 @@ import {
close,
} from 'react-client/src/ReactFlightClientStream';
export type Options = {
export type Options = {|
moduleMap?: BundlerConfig,
};
|};
function startReadingFromStream(
response: FlightResponse,

View File

@ -18,12 +18,12 @@ import {
abort,
} from 'react-server/src/ReactFlightServer';
type Options = {
type Options = {|
identifierPrefix?: string,
signal?: AbortSignal,
context?: Array<[string, ServerContextJSONValue]>,
onError?: (error: mixed) => void,
};
|};
function renderToReadableStream(
model: ReactModel,

View File

@ -23,11 +23,11 @@ function createDrainHandler(destination, request) {
return () => startFlowing(request, destination);
}
type Options = {
type Options = {|
onError?: (error: mixed) => void,
context?: Array<[string, ServerContextJSONValue]>,
identifierPrefix?: string,
};
|};
type PipeableStream = {|
abort(reason: mixed): void,

View File

@ -7,28 +7,28 @@
* @flow
*/
type WebpackMap = {
[filepath: string]: {
type WebpackMap = {|
[filepath: string]: {|
[name: string]: ModuleMetaData,
},
};
|},
|};
export type BundlerConfig = WebpackMap;
// eslint-disable-next-line no-unused-vars
export type ModuleReference<T> = {
export type ModuleReference<T> = {|
$$typeof: symbol,
filepath: string,
name: string,
async: boolean,
};
|};
export type ModuleMetaData = {
export type ModuleMetaData = {|
id: string,
chunks: Array<string>,
name: string,
async: boolean,
};
|};
export type ModuleKey = string;

View File

@ -9,37 +9,37 @@
import {acorn} from 'acorn';
type ResolveContext = {
type ResolveContext = {|
conditions: Array<string>,
parentURL: string | void,
};
|};
type ResolveFunction = (
string,
ResolveContext,
ResolveFunction,
) => {url: string} | Promise<{url: string}>;
) => {|url: string|} | Promise<{|url: string|}>;
type GetSourceContext = {
type GetSourceContext = {|
format: string,
};
|};
type GetSourceFunction = (
string,
GetSourceContext,
GetSourceFunction,
) => Promise<{source: Source}>;
) => Promise<{|source: Source|}>;
type TransformSourceContext = {
type TransformSourceContext = {|
format: string,
url: string,
};
|};
type TransformSourceFunction = (
Source,
TransformSourceContext,
TransformSourceFunction,
) => Promise<{source: Source}>;
) => Promise<{|source: Source|}>;
type Source = string | ArrayBuffer | Uint8Array;
@ -52,7 +52,7 @@ export async function resolve(
specifier: string,
context: ResolveContext,
defaultResolve: ResolveFunction,
): Promise<{url: string}> {
): Promise<{|url: string|}> {
// We stash this in case we end up needing to resolve export * statements later.
stashedResolve = defaultResolve;
@ -133,7 +133,7 @@ function addExportNames(names, node) {
function resolveClientImport(
specifier: string,
parentURL: string,
): {url: string} | Promise<{url: string}> {
): {|url: string|} | Promise<{|url: string|}> {
// Resolve an import specifier as if it was loaded by the client. This doesn't use
// the overrides that this loader does but instead reverts to the default.
// This resolution algorithm will not necessarily have the same configuration
@ -151,7 +151,7 @@ function resolveClientImport(
async function loadClientImport(
url: string,
defaultTransformSource: TransformSourceFunction,
): Promise<{source: Source}> {
): Promise<{|source: Source|}> {
if (stashedGetSource === null) {
throw new Error(
'Expected getSource to have been called before transformSource',
@ -225,7 +225,7 @@ export async function transformSource(
source: Source,
context: TransformSourceContext,
defaultTransformSource: TransformSourceFunction,
): Promise<{source: Source}> {
): Promise<{|source: Source|}> {
const transformed = await defaultTransformSource(
source,
context,

View File

@ -52,7 +52,7 @@ module.exports = function register() {
// we should resolve that with a client reference that unwraps the Promise on
// the client.
const then = function then(resolve, reject) {
const moduleReference: {[string]: any} = {
const moduleReference: {[string]: any, ...} = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: '*', // Represents the whole object instead of a particular import.
@ -93,7 +93,7 @@ module.exports = function register() {
Module._extensions['.client.js'] = function(module, path) {
const moduleId = url.pathToFileURL(path).href;
const moduleReference: {[string]: any} = {
const moduleReference: {[string]: any, ...} = {
$$typeof: MODULE_REFERENCE,
filepath: moduleId,
name: '*', // Represents the whole object instead of a particular import.

View File

@ -42,21 +42,21 @@ class ClientReferenceDependency extends ModuleDependency {
const clientImportName = 'react-server-dom-webpack';
const clientFileName = require.resolve('../');
type ClientReferenceSearchPath = {
type ClientReferenceSearchPath = {|
directory: string,
recursive?: boolean,
include: RegExp,
exclude?: RegExp,
};
|};
type ClientReferencePath = string | ClientReferenceSearchPath;
type Options = {
type Options = {|
isServer: boolean,
clientReferences?: ClientReferencePath | $ReadOnlyArray<ClientReferencePath>,
chunkName?: string,
manifestFilename?: string,
};
|};
const PLUGIN_NAME = 'React Server Plugin';

View File

@ -24,8 +24,10 @@ export {createResponse, close};
export function resolveRow(response: Response, chunk: RowEncoding): void {
if (chunk[0] === 'J') {
// $FlowFixMe `Chunk` doesn't flow into `JSONValue` because of the `E` row type.
resolveModel(response, chunk[1], chunk[2]);
} else if (chunk[0] === 'M') {
// $FlowFixMe `Chunk` doesn't flow into `JSONValue` because of the `E` row type.
resolveModule(response, chunk[1], chunk[2]);
} else if (chunk[0] === 'S') {
// $FlowFixMe: Flow doesn't support disjoint unions on tuples.

View File

@ -14,7 +14,7 @@ export type JSONValue =
| number
| boolean
| null
| {+[key: string]: JSONValue}
| {|+[key: string]: JSONValue|}
| Array<JSONValue>;
export type RowEncoding =

View File

@ -75,7 +75,7 @@ export function processErrorChunk(
function convertModelToJSON(
request: Request,
parent: {+[key: string]: ReactModel} | $ReadOnlyArray<ReactModel>,
parent: {|+[key: string]: ReactModel|} | $ReadOnlyArray<ReactModel>,
key: string,
model: ReactModel,
): JSONValue {
@ -88,7 +88,8 @@ function convertModelToJSON(
}
return jsonArray;
} else {
const jsonObj: {[key: string]: JSONValue} = {};
// $FlowFixMe no good way to define an empty exact object
const jsonObj: {|[key: string]: JSONValue|} = {};
for (const nextKey in json) {
if (hasOwnProperty.call(json, nextKey)) {
jsonObj[nextKey] = convertModelToJSON(
@ -110,6 +111,7 @@ export function processModelChunk(
id: number,
model: ReactModel,
): Chunk {
// $FlowFixMe no good way to define an empty exact object
const json = convertModelToJSON(request, {}, '', model);
return ['J', id, json];
}
@ -156,6 +158,7 @@ export function flushBuffered(destination: Destination) {}
export function beginWriting(destination: Destination) {}
export function writeChunk(destination: Destination, chunk: Chunk): void {
// $FlowFixMe `Chunk` doesn't flow into `JSONValue` because of the `E` row type.
emitRow(destination, chunk);
}
@ -163,6 +166,7 @@ export function writeChunkAndReturn(
destination: Destination,
chunk: Chunk,
): boolean {
// $FlowFixMe `Chunk` doesn't flow into `JSONValue` because of the `E` row type.
emitRow(destination, chunk);
return true;
}

View File

@ -100,10 +100,10 @@ function warnNoop(
}
}
type InternalInstance = {
type InternalInstance = {|
queue: null | Array<Object>,
replace: boolean,
};
|};
const classComponentUpdater = {
isMounted(inst) {

View File

@ -14,21 +14,21 @@ import {
} from 'shared/ReactComponentStackFrame';
// DEV-only reverse linked list representing the current component stack
type BuiltInComponentStackNode = {
type BuiltInComponentStackNode = {|
tag: 0,
parent: null | ComponentStackNode,
type: string,
};
type FunctionComponentStackNode = {
|};
type FunctionComponentStackNode = {|
tag: 1,
parent: null | ComponentStackNode,
type: Function,
};
type ClassComponentStackNode = {
|};
type ClassComponentStackNode = {|
tag: 2,
parent: null | ComponentStackNode,
type: Function,
};
|};
export type ComponentStackNode =
| BuiltInComponentStackNode
| FunctionComponentStackNode

View File

@ -20,13 +20,13 @@ if (__DEV__) {
// Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.
type ContextNode<T> = {
type ContextNode<T> = {|
parent: null | ContextNode<any>,
depth: number, // Short hand to compute the depth of the tree at this node.
context: ReactContext<T>,
parentValue: T,
value: T,
};
|};
// The structure of a context snapshot is an implementation of this file.
// Currently, it's implemented as tracking the current active node.

View File

@ -131,11 +131,11 @@ import {trackSuspendedWakeable} from './ReactFizzWakeable';
const ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
const ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
type LegacyContext = {
type LegacyContext = {|
[key: string]: any,
};
|};
type SuspenseBoundary = {
type SuspenseBoundary = {|
id: SuspenseBoundaryID,
rootSegmentID: number,
errorDigest: ?string, // the error hash if it errors
@ -147,9 +147,9 @@ type SuspenseBoundary = {
completedSegments: Array<Segment>, // completed but not yet flushed segments.
byteSize: number, // used to determine whether to inline children boundaries.
fallbackAbortableTasks: Set<Task>, // used to cancel task on the fallback if the boundary completes or gets canceled.
};
|};
export type Task = {
export type Task = {|
node: ReactNodeList,
ping: () => void,
blockedBoundary: Root | SuspenseBoundary,
@ -160,7 +160,7 @@ export type Task = {
treeContext: TreeContext, // the current tree context that this task is executing in
componentStack: null | ComponentStackNode, // DEV-only component stack
thenableState: null | ThenableState,
};
|};
const PENDING = 0;
const COMPLETED = 1;
@ -170,7 +170,7 @@ const ERRORED = 4;
type Root = null;
type Segment = {
type Segment = {|
status: 0 | 1 | 2 | 3 | 4,
parentFlushed: boolean, // typically a segment will be flushed by its parent, except if its parent was already flushed
id: number, // starts as 0 and is lazily assigned if the parent flushes early
@ -184,13 +184,13 @@ type Segment = {
// used to discern when text separator boundaries are needed
lastPushedText: boolean,
textEmbedded: boolean,
};
|};
const OPEN = 0;
const CLOSING = 1;
const CLOSED = 2;
export opaque type Request = {
export opaque type Request = {|
destination: null | Destination,
+responseState: ResponseState,
+progressiveChunkSize: number,
@ -223,7 +223,7 @@ export opaque type Request = {
// emit a different response to the stream instead.
onShellError: (error: mixed) => void,
onFatalError: (error: mixed) => void,
};
|};
// This is a default heuristic for how to split up the HTML content into progressive
// loading. Our goal is to be able to display additional new content about every 500ms.

View File

@ -60,10 +60,10 @@
// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
// affecting the final result.
export type TreeContext = {
export type TreeContext = {|
+id: number,
+overflow: string,
};
|};
export const emptyTreeContext = {
id: 1,

View File

@ -23,13 +23,13 @@ if (__DEV__) {
// Used to store the parent path of all context overrides in a shared linked list.
// Forming a reverse tree.
type ContextNode<T: ServerContextJSONValue> = {
type ContextNode<T: ServerContextJSONValue> = {|
parent: null | ContextNode<any>,
depth: number, // Short hand to compute the depth of the tree at this node.
context: ReactServerContext<T>,
parentValue: T,
value: T,
};
|};
// The structure of a context snapshot is an implementation of this file.
// Currently, it's implemented as tracking the current active node.

View File

@ -91,23 +91,23 @@ export type ReactModel =
| Iterable<ReactModel>
| ReactModelObject;
type ReactModelObject = {+[key: string]: ReactModel};
type ReactModelObject = {|+[key: string]: ReactModel|};
const PENDING = 0;
const COMPLETED = 1;
const ABORTED = 3;
const ERRORED = 4;
type Task = {
type Task = {|
id: number,
status: 0 | 1 | 3 | 4,
model: ReactModel,
ping: () => void,
context: ContextSnapshot,
thenableState: ThenableState | null,
};
|};
export type Request = {
export type Request = {|
status: 0 | 1 | 2,
fatalError: mixed,
destination: null | Destination,
@ -127,7 +127,7 @@ export type Request = {
identifierCount: number,
onError: (error: mixed) => void,
toJSON: (key: string, value: ReactModel) => ReactJSONValue,
};
|};
const ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
@ -272,6 +272,7 @@ function attemptResolveElement(
);
}
}
// $FlowFixMe issue discovered when updating Flow
return [
REACT_ELEMENT_TYPE,
type,
@ -324,7 +325,7 @@ function serializeByRefID(id: number): string {
function serializeModuleReference(
request: Request,
parent: {+[key: string | number]: ReactModel} | $ReadOnlyArray<ReactModel>,
parent: {|+[key: string | number]: ReactModel|} | $ReadOnlyArray<ReactModel>,
key: string,
moduleReference: ModuleReference<any>,
): string {
@ -465,7 +466,7 @@ function describeValueForErrorMessage(value: ReactModel): string {
function describeObjectForErrorMessage(
objectOrArray:
| {+[key: string | number]: ReactModel}
| {+[key: string | number]: ReactModel, ...}
| $ReadOnlyArray<ReactModel>,
expandedName?: string,
): string {
@ -495,7 +496,7 @@ function describeObjectForErrorMessage(
return str;
} else {
let str = '{';
const object: {+[key: string | number]: ReactModel} = objectOrArray;
const object: {+[key: string | number]: ReactModel, ...} = objectOrArray;
const names = Object.keys(object);
for (let i = 0; i < names.length; i++) {
if (i > 0) {
@ -528,7 +529,7 @@ let isInsideContextValue = false;
export function resolveModelToJSON(
request: Request,
parent: {+[key: string | number]: ReactModel} | $ReadOnlyArray<ReactModel>,
parent: {|+[key: string | number]: ReactModel|} | $ReadOnlyArray<ReactModel>,
key: string,
value: ReactModel,
): ReactJSONValue {
@ -698,6 +699,7 @@ export function resolveModelToJSON(
}
}
// $FlowFixMe
return value;
}
@ -839,6 +841,7 @@ function emitModuleChunk(
id: number,
moduleMetaData: ModuleMetaData,
): void {
// $FlowFixMe ModuleMetaData is not a ReactModel
const processedChunk = processModuleChunk(request, id, moduleMetaData);
request.completedModuleChunks.push(processedChunk);
}

View File

@ -173,9 +173,9 @@ function mapIntoArray(
} else {
const iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
const iterableChildren: Iterable<React$Node> & {
const iterableChildren: Iterable<React$Node> & {|
entries: any,
} = (children: any);
|} = (children: any);
if (__DEV__) {
// Warn about using Maps as children

View File

@ -9,9 +9,9 @@
import type {BatchConfigTransition} from 'react-reconciler/src/ReactFiberTracingMarkerComponent.new';
type BatchConfig = {
type BatchConfig = {|
transition: BatchConfigTransition | null,
};
|};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.

View File

@ -16,25 +16,25 @@ const Pending = 0;
const Resolved = 1;
const Rejected = 2;
type UninitializedPayload<T> = {
type UninitializedPayload<T> = {|
_status: -1,
_result: () => Thenable<{default: T, ...}>,
};
|};
type PendingPayload = {
type PendingPayload = {|
_status: 0,
_result: Wakeable,
};
|};
type ResolvedPayload<T> = {
type ResolvedPayload<T> = {|
_status: 1,
_result: {default: T},
};
_result: {default: T, ...},
|};
type RejectedPayload = {
type RejectedPayload = {|
_status: 2,
_result: mixed,
};
|};
type Payload<T> =
| UninitializedPayload<T>
@ -42,11 +42,11 @@ type Payload<T> =
| ResolvedPayload<T>
| RejectedPayload;
export type LazyComponent<T, P> = {
export type LazyComponent<T, P> = {|
$$typeof: symbol | number,
_payload: P,
_init: (payload: P) => T,
};
|};
function lazyInitializer<T>(payload: Payload<T>): T {
if (payload._status === Uninitialized) {

View File

@ -77,7 +77,7 @@ type SchedulerCallback<T> = (
export function unstable_scheduleCallback<T>(
priorityLevel: PriorityLevel,
callback: SchedulerCallback<T>,
options?: {delay?: number},
options?: {|delay?: number|},
): CallbackNode {
let postTaskPriority;
switch (priorityLevel) {

View File

@ -80,7 +80,7 @@ export type ServerContextJSONValue =
| number
| null
| $ReadOnlyArray<ServerContextJSONValue>
| {+[key: string]: ServerContextJSONValue};
| {|+[key: string]: ServerContextJSONValue|};
export type ReactServerContext<T: any> = ReactContext<T>;
@ -209,9 +209,9 @@ export type OffscreenMode =
| 'unstable-defer-without-hiding'
| 'visible';
export type StartTransitionOptions = {
export type StartTransitionOptions = {|
name?: string,
};
|};
// TODO: Add Context support
export type Usable<T> = Thenable<T> | ReactContext<T>;

View File

@ -37,6 +37,7 @@
[lints]
untyped-type-import=error
implicit-inexact-object=error
[options]
server.max_workers=4

View File

@ -77,52 +77,52 @@ declare module 'fs/promises' {
declare var access: (path: string, mode?: number) => Promise<void>;
declare var lstat: (
path: string,
options?: ?{bigint?: boolean},
options?: ?{|bigint?: boolean|},
) => Promise<mixed>;
declare var readdir: (
path: string,
options?:
| ?string
| {
| {|
encoding?: ?string,
withFileTypes?: ?boolean,
},
|},
) => Promise<Buffer>;
declare var readFile: (
path: string,
options?:
| ?string
| {
| {|
encoding?: ?string,
},
|},
) => Promise<Buffer>;
declare var readlink: (
path: string,
options?:
| ?string
| {
| {|
encoding?: ?string,
},
|},
) => Promise<mixed>;
declare var realpath: (
path: string,
options?:
| ?string
| {
| {|
encoding?: ?string,
},
|},
) => Promise<mixed>;
declare var stat: (
path: string,
options?: ?{bigint?: boolean},
options?: ?{|bigint?: boolean|},
) => Promise<mixed>;
}
declare module 'pg' {
declare var Pool: (
options: mixed,
) => {
) => {|
query: (query: string, values?: Array<mixed>) => void,
};
|};
}
declare module 'util' {
@ -147,13 +147,13 @@ declare module 'util' {
encodeInto(
buffer: string,
dest: Uint8Array,
): {read: number, written: number};
): {|read: number, written: number|};
encoding: string;
}
}
declare module 'pg/lib/utils' {
declare module.exports: {
declare module.exports: {|
prepareValue(val: any): mixed,
};
|};
}

View File

@ -26,7 +26,7 @@ type RawEventEmitterEvent = $ReadOnly<{|
// We expect, but do not/cannot require, that nativeEvent is an object
// with the properties: key, elementType (string), type (string), tag (numeric),
// and a stateNode of the native element/Fiber the event was emitted to.
nativeEvent: {[string]: mixed},
nativeEvent: {[string]: mixed, ...},
|}>;
declare module 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface' {

View File

@ -12,7 +12,7 @@ type JSONValue =
| boolean
| number
| null
| {+[key: string]: JSONValue}
| {|+[key: string]: JSONValue|}
| $ReadOnlyArray<JSONValue>;
declare module 'JSResourceReference' {