-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathlint-flow-types.mjs
More file actions
199 lines (188 loc) · 5.78 KB
/
Copy pathlint-flow-types.mjs
File metadata and controls
199 lines (188 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// @ts-check
import fs from 'fs-extra';
import * as hermesParser from 'hermes-parser';
import * as tsMorph from 'ts-morph';
import ts from 'typescript';
import {packagesManager} from './shared/packagesManager.mjs';
/** @typedef {import('./shared/PackageMetadata.mjs').PackageMetadata} PackageMetadata */
/**
* The subset of a hermes-estree `Identifier` node that this script reads. The
* full node is an untyped AST value (hermes-estree ships no types), so only the
* fields consumed when reporting missing TypeScript declarations are described.
*
* @typedef {Object} FlowIdentifier
* @property {string} name
* @property {{source: string, start: {line: number, column: number}}} loc
*/
const pretty = process.env.CI !== 'true';
/** @type {ts.FormatDiagnosticsHost} */
const diagnosticsHost = {
getCanonicalFileName: fn => fn,
getCurrentDirectory: () => './',
getNewLine: () => '\n',
};
/**
* Validate that the manually maintained .flow types have the same exports as
* the corresponding .d.ts types produced by the build.
*
* `process.exit(1)` on failure.
*/
function lintFlowTypes() {
let didError = false;
const project = new tsMorph.Project({tsConfigFilePath: './tsconfig.json'});
for (const pkg of packagesManager.getPublicPackages()) {
didError = lintFlowTypesForPackage(project, pkg) || didError;
}
if (didError) {
process.exit(1);
}
}
/**
* Collect the names and identifier nodes of every export declared in a parsed
* .flow AST.
*
* @param {any} flowAst the untyped hermes-parser AST of a .flow file
* @returns {Map<string, FlowIdentifier>}
*/
function collectFlowExports(flowAst) {
/** @type {Map<string, FlowIdentifier>} */
const exportNames = new Map();
/** @param {any} node an untyped hermes-estree AST node */
const exportId = node => {
const identifier =
node.type === 'Identifier'
? node
: 'id' in node && node.id.type === 'Identifier'
? node.id
: null;
if (identifier) {
exportNames.set(identifier.name, identifier);
return true;
}
return false;
};
hermesParser.SimpleTraverser.traverse(flowAst, {
/**
* @param {any} node an untyped hermes-estree AST node
* @param {any} parent the untyped parent AST node, if any
*/
enter: (node, parent) => {
if (
parent &&
(parent.type === 'DeclareExportDeclaration' ||
parent.type === 'ExportNamedDeclaration')
) {
if (exportId(node)) {
// ok
} else if (node.type === 'VariableDeclaration') {
for (const declaration of node.declarations) {
if (!exportId(declaration)) {
// debugger;
}
}
} else if (node.type === 'ExportSpecifier') {
if (!exportId(node.exported)) {
// debugger;
}
} else {
// debugger;
}
}
},
leave: () => {},
});
return exportNames;
}
function compareFlowDts(
/** @type {PackageMetadata} */ pkg,
/** @type {string} */ flowFilePath,
/** @type {tsMorph.SourceFile} */ entrypoint,
/** @type {ts.Diagnostic[]} */ diagnostics,
/** @type {FlowIdentifier[]} */ flowDiagnostics,
) {
const flowAst = hermesParser.parse(fs.readFileSync(flowFilePath, 'utf-8'), {
enableExperimentalComponentSyntax: true,
flow: 'all',
sourceFilename: flowFilePath,
sourceType: 'module',
});
const flowMap = collectFlowExports(flowAst);
const symbols = entrypoint.getExportSymbols();
const tsMap = new Map(symbols.map(sym => [sym.getName(), sym]));
for (const [name, symbol] of tsMap) {
if (flowMap.has(name)) {
continue;
}
for (const decl of symbol.getDeclarations()) {
const start = decl.getStart();
const end = decl.getEnd();
diagnostics.push({
category: ts.DiagnosticCategory.Warning,
code: Infinity,
file: entrypoint.compilerNode,
length: end - start,
messageText: `Missing flow export for TypeScript export '${name}'`,
start,
});
break;
}
// debugger;
}
for (const [name, flowToken] of flowMap) {
if (tsMap.has(name)) {
continue;
}
flowDiagnostics.push(flowToken);
}
}
function lintFlowTypesForPackage(
/** @type {tsMorph.Project} */ project,
/** @type {PackageMetadata} */ pkg,
) {
const def = pkg.getPackageBuildDefinition({consolidateBrowserSource: true});
if (def.packageName === 'lexical-eslint-plugin') {
return false;
}
/** @type {ts.Diagnostic[]} */
const diagnostics = [];
/** @type {FlowIdentifier[]} */
const flowDiagnostics = [];
for (const {outputFileName, sourceFileName} of def.modules) {
const entrypoint = project.addSourceFileAtPath(
pkg.resolve('src', sourceFileName),
);
const flowFilePath = pkg.resolve('flow', `${outputFileName}.js.flow`);
if (!fs.existsSync(flowFilePath)) {
console.error(`Missing ${flowFilePath}`);
process.exit(1);
}
compareFlowDts(pkg, flowFilePath, entrypoint, diagnostics, flowDiagnostics);
}
if (diagnostics.length > 0 || flowDiagnostics.length > 0) {
const msg = (
pretty ? ts.formatDiagnosticsWithColorAndContext : ts.formatDiagnostics
)(diagnostics, diagnosticsHost);
if (msg) {
console.error(msg.replace(/ TSInfinity:/g, ':'));
}
const flowMsg = flowDiagnostics
.map(
ident =>
`${ident.loc.source}:${ident.loc.start.line}:${ident.loc.start.column} - warning: Flow export '${ident.name}' does not have a TypeScript declaration`,
)
.join('\n');
if (flowMsg) {
console.error(flowMsg);
}
return true;
}
return false;
}
lintFlowTypes();