forked from facebook/lexical
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate-flowconfig.js
85 lines (78 loc) · 2.63 KB
/
update-flowconfig.js
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
/**
* 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
'use strict';
const fs = require('fs-extra');
const path = require('node:path');
const {packagesManager} = require('./shared/packagesManager');
const npmToWwwName = require('./www/npmToWwwName');
const headerTemplate = fs.readFileSync(
path.resolve(__dirname, 'www', 'headerTemplate.js'),
'utf8',
);
const BLOCK_REGEX =
/^([\s\S]+?\n;; \[generated-start update-flowconfig\]\n)([\s\S]*?)(;; \[generated-end update-flowconfig\][\s\S]+)$/;
function flowTemplate(wwwName) {
return (
headerTemplate.replace(/^( \*\/)$/m, ' * @flow strict\n$1') +
`
/**
* ${wwwName}
*/` +
'\n'
);
}
/**
* @param {string} configContents
* @param {string} generatedCode
*/
function replaceBlock(configContents, generatedCode) {
const m = configContents.match(BLOCK_REGEX);
if (!m) {
throw new Error(
`update-flowconfig block not found in .flowconfig, expecting ';; [generated-start update-flowconfig]' followed by ';; [generated-end update-flowconfig]`,
);
}
return `${m[1]}${generatedCode}${m[3]}`;
}
function updateFlowconfig(flowconfigPath = './.flowconfig') {
const prevConfig = fs.readFileSync(flowconfigPath, 'utf8');
const configDir = path.resolve(path.dirname(flowconfigPath));
/** @type {Array<string>} */
const generatedBlock = [];
const emit = (moduleName, flowFilename) =>
generatedBlock.push(
`module.name_mapper='^${moduleName}$' -> '${flowFilename}'\n`,
);
for (const pkg of packagesManager.getPackages()) {
const resolveRelative = (...subPaths) =>
'<PROJECT_ROOT>/' +
path.relative(configDir, pkg.resolve(...subPaths)).replace(/^(?!\.)/, '');
if (!pkg.isPrivate()) {
for (const name of pkg.getExportedNpmModuleNames()) {
const wwwName = npmToWwwName(name);
const flowFile = `${wwwName}.js.flow`;
const resolvedFlowFile = resolveRelative('flow', flowFile);
emit(name, resolveRelative('flow', flowFile));
const flowFilePath = pkg.resolve('flow', flowFile);
if (!fs.existsSync(flowFilePath)) {
console.log(
`Creating boilerplate ${resolvedFlowFile.replace(/^[^/]+\//, '')}`,
);
fs.mkdirsSync(path.dirname(flowFilePath));
fs.writeFileSync(flowFilePath, flowTemplate(wwwName));
}
}
}
}
const nextConfig = replaceBlock(prevConfig, generatedBlock.join(''));
if (prevConfig !== nextConfig) {
fs.writeFileSync(flowconfigPath, nextConfig);
}
}
updateFlowconfig();