-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathgenerateTypeScriptDefinitions.js
More file actions
273 lines (245 loc) Β· 8.47 KB
/
generateTypeScriptDefinitions.js
File metadata and controls
273 lines (245 loc) Β· 8.47 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/
// $FlowFixMe[untyped-import] in OSS only
import {ESLint} from 'eslint';
import {
translateFlowDefToTSDef,
translateFlowToFlowDef,
} from 'flow-api-translator';
import fs from 'fs';
import nullthrows from 'nullthrows';
import path from 'path';
import * as prettier from 'prettier';
// $FlowFixMe[untyped-import] in OSS only
import SignedSource from 'signedsource';
// $FlowFixMe[untyped-import] in OSS only
import {globSync} from 'tinyglobby';
const WORKSPACE_ROOT = path.resolve(__dirname, '..');
const TYPES_DIR = 'types';
const SRC_DIR = 'src';
export const AUTO_GENERATED_PATTERNS: ReadonlyArray<string> = ['packages/**'];
// Globs of paths for which we do not generate TypeScript definitions,
// matched against candidate .js files
const IGNORED_PATTERNS = [
'**/__tests__/**',
'**/__flowtests__/**',
'**/__mocks__/**',
'**/__fixtures__/**',
'**/node_modules/**',
'packages/metro-babel-register/**',
'packages/*/build/**',
'packages/metro/src/cli.js',
'packages/**/third-party/**',
'packages/metro/src/integration_tests/**',
'packages/metro-runtime/**/!(types*).js',
];
function isSourceTSDeclaration(filePath: string): boolean {
const parts = filePath.split(path.sep);
return filePath.endsWith('.d.ts') && parts[2] === SRC_DIR;
}
function isExistingTSDeclaration(filePath: string): boolean {
const parts = filePath.split(path.sep);
return filePath.endsWith('.d.ts') && parts[2] === TYPES_DIR;
}
export async function generateTsDefsForJsGlobs(
globPattern: string | ReadonlyArray<string>,
opts: Readonly<{
verifyOnly: boolean,
}> = {verifyOnly: false},
) {
const linter = new ESLint({
fix: true,
cwd: WORKSPACE_ROOT,
});
const prettierConfig = await resolvePrettierConfig();
const globPatterns = Array.isArray(globPattern) ? globPattern : [globPattern];
const existingDefs = new Set<string>();
const sourceDefs = new Set<string>();
const filesToProcess: Array<[jsFile: string, flowSourceFile: string]> =
Array.from(
globPatterns
.flatMap(pattern =>
globSync(pattern, {
ignore: IGNORED_PATTERNS,
cwd: WORKSPACE_ROOT,
}),
)
.reduce((toProcess, posixFilePath) => {
const filePath = path.normalize(posixFilePath);
if (filePath.endsWith('.flow.js')) {
// For .flow.js files, record the `.flow.js` as the source for the
// corresponding `.js` file, which is enforced to be a transparent
// entry file that only registers Babel and re-exports the module.
toProcess.set(filePath.replace(/\.flow\.js$/, '.js'), filePath);
} else if (filePath.endsWith('.js') && !toProcess.has(filePath)) {
toProcess.set(filePath, filePath);
} else if (isSourceTSDeclaration(filePath)) {
sourceDefs.add(path.resolve(WORKSPACE_ROOT, filePath));
} else if (isExistingTSDeclaration(filePath)) {
existingDefs.add(path.resolve(WORKSPACE_ROOT, filePath));
}
return toProcess;
}, new Map<string, string>())
.entries(),
);
const errors = [];
async function writeOutputFile(
sourceContent: string,
absoluteTsFile: string,
sourceFile: string,
) {
// Lint and fix the generated output
const [lintResult] = await linter.lintText(sourceContent, {
filePath: absoluteTsFile,
});
if (lintResult.messages.length > 0) {
console.warn(sourceFile, lintResult.messages);
}
const formattedOutput = await prettier.format(
lintResult.output ?? sourceContent,
prettierConfig,
);
// Add signedsource (generated) token to the header
const withToken = formattedOutput
.replace(
'\n */\n',
`\n * ${SignedSource.getSigningToken()}\n *` +
`\n * This file was translated from Flow by ${path.relative(WORKSPACE_ROOT, __filename).replaceAll(path.sep, '/')}` +
`\n * Original file: ${sourceFile.replaceAll(path.sep, '/')}` +
'\n * To regenerate, run:' +
'\n * js1 build metro-ts-defs (internal) OR' +
'\n * yarn run build-ts-defs (OSS) ' +
'\n */\n',
)
// format -> noformat
.replace(`\n * ${'@'}format\n`, `\n * ${'@'}noformat\n`);
// Sign the file
const finalOutput = SignedSource.signFile(withToken);
existingDefs.delete(absoluteTsFile);
if (opts.verifyOnly) {
let existingFile = null;
try {
existingFile = await fs.promises.readFile(absoluteTsFile, 'utf-8');
if (finalOutput !== existingFile) {
errors.push({
sourceFile,
error: new Error('.d.ts file is out of sync'),
});
}
} catch {
errors.push({sourceFile, error: new Error('.d.ts file missing')});
}
} else {
await fs.promises.mkdir(path.dirname(absoluteTsFile), {
recursive: true,
});
await fs.promises.writeFile(absoluteTsFile, finalOutput);
}
}
await Promise.all(
filesToProcess.map(async ([jsFile, sourceFile]) => {
const absoluteTsFile = getTSDeclAbsolutePath(jsFile);
const sourceTSDeclationPath = absoluteTsFile.replace(TYPES_DIR, SRC_DIR);
const absoluteSourceFile = path.resolve(WORKSPACE_ROOT, sourceFile);
// If a source .d.ts file exists, copy it directly.
if (sourceDefs.has(sourceTSDeclationPath)) {
const source = await fs.promises.readFile(
sourceTSDeclationPath,
'utf-8',
);
await writeOutputFile(source, absoluteTsFile, sourceFile);
return;
}
const source = await fs.promises.readFile(absoluteSourceFile, 'utf-8');
if (!source.includes('@flow')) {
errors.push({
sourceFile,
error: new Error('Expected @flow directive'),
});
return;
}
try {
const flowDef = await translateFlowToFlowDef(source);
if (flowDef.includes('declare module.exports')) {
errors.push({
sourceFile,
error: new Error(
'module.exports is not supported by TypeScript auto-generation',
),
});
} else {
const tsDef = await translateFlowDefToTSDef(flowDef);
const beforeLint = tsDef
// Fix up gap left in license header by removal of atflow
.replace('\n *\n *\n', '\n *\n')
// TypeScript has no analogue for __proto__: null
.replace(/__proto__: null[,;]?/g, '');
await writeOutputFile(beforeLint, absoluteTsFile, sourceFile);
}
} catch (error) {
errors.push({sourceFile, error});
}
}),
);
if (existingDefs.size > 0) {
const orphanedDefs = Array.from(existingDefs);
if (opts.verifyOnly) {
orphanedDefs.forEach(sourceFile => {
errors.push({
error: new Error('.d.ts appears to be orphaned'),
sourceFile,
});
});
} else {
// Delete .d.ts files under a generated location that were not generated.
await Promise.all(
orphanedDefs.map(sourceFile => fs.promises.unlink(sourceFile)),
);
}
}
if (errors.length > 0) {
errors.sort((a, b) => a.sourceFile.localeCompare(b.sourceFile));
throw new AggregateError(
errors,
'Errors encountered while generating TypeScript definitions',
);
}
}
function getTSDeclAbsolutePath(jsRelativePath: string) {
const parts = jsRelativePath.split(path.sep);
if (parts[2] !== 'src') {
throw new Error(
'Expected relative path of the form packages/<pkg>/src/...',
);
}
parts[2] = TYPES_DIR;
const basename = nullthrows(parts.pop());
parts.push(basename.slice(0, -3) + '.d.ts');
return path.resolve(WORKSPACE_ROOT, parts.join(path.sep));
}
async function resolvePrettierConfig() {
const fakeTsDecl = path.resolve(__dirname, './dummy.d.ts');
return {
...(await prettier.resolveConfig(fakeTsDecl)),
filepath: fakeTsDecl,
};
}
// When run as a script, execute pattern from argv
if (process.mainModule === module) {
// Usage: node scripts/generateTypeScriptDefinitions.js [glob...]
// Omit globs to use hardcoded defaults.
generateTsDefsForJsGlobs(
process.argv.length >= 3 ? process.argv.slice(2) : AUTO_GENERATED_PATTERNS,
).catch(error => {
process.exitCode = 1;
console.error(error);
});
}