-
-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathgenerateProptypes.ts
262 lines (229 loc) · 8.33 KB
/
generateProptypes.ts
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
/* eslint-disable no-console */
import * as path from 'path';
import * as fse from 'fs-extra';
import * as prettier from 'prettier';
import glob from 'fast-glob';
import * as _ from 'lodash';
import * as yargs from 'yargs';
import * as ts from 'typescript';
import { fixBabelGeneratorIssues, fixLineEndings } from '@mui/internal-docs-utils';
import {
getPropTypesFromFile,
injectPropTypesInFile,
InjectPropTypesInFileOptions,
} from '@mui/internal-scripts/typescript-to-proptypes';
import {
createTypeScriptProjectBuilder,
TypeScriptProject,
} from '@mui-internal/api-docs-builder/utils/createTypeScriptProject';
import CORE_TYPESCRIPT_PROJECTS from './coreTypescriptProjects';
function sortSizeByScaleAscending(a: ts.LiteralType, b: ts.LiteralType) {
const sizeOrder: readonly unknown[] = ['"small"', '"medium"', '"large"'];
return sizeOrder.indexOf(a.value) - sizeOrder.indexOf(b.value);
}
// Custom order of literal unions by component
const getSortLiteralUnions: InjectPropTypesInFileOptions['getSortLiteralUnions'] = (
component,
propType,
) => {
if (propType.name === 'size') {
return sortSizeByScaleAscending;
}
return undefined;
};
async function generateProptypes(
project: TypeScriptProject,
sourceFile: string,
tsFile: string,
): Promise<void> {
const sourceContent = await fse.readFile(sourceFile, 'utf8');
if (
sourceContent.match(/@ignore - internal component\./) ||
sourceContent.match(/@ignore - internal hook\./) ||
sourceContent.match(/@ignore - do not document\./)
) {
return;
}
const components = getPropTypesFromFile({
filePath: tsFile,
project,
shouldResolveObject: ({ name }) => {
if (
name.toLowerCase().endsWith('classes') ||
name === 'theme' ||
name === 'ownerState' ||
(name.endsWith('Props') && name !== 'componentsProps' && name !== 'slotProps')
) {
return false;
}
return undefined;
},
checkDeclarations: true,
});
if (components.length === 0) {
return;
}
// exclude internal slot components, for example ButtonRoot
const cleanComponents = components.filter((component) => {
if (component.propsFilename?.endsWith('.tsx')) {
// only check for .tsx
const match = component.propsFilename.match(/.*\/([A-Z][a-zA-Z]+)\.tsx/);
if (match) {
return component.name === match[1];
}
}
return true;
});
cleanComponents.forEach((component) => {
component.types.forEach((prop) => {
if (!prop.jsDoc) {
prop.jsDoc = '@ignore';
}
});
});
const isTsFile = /(\.(ts|tsx))/.test(sourceFile);
// TODO remove, should only have .types.ts
const propsFile = tsFile.replace(/(\.d\.ts|\.tsx|\.ts)/g, 'Props.ts');
const propsFileAlternative = tsFile.replace(/(\.d\.ts|\.tsx|\.ts)/g, '.types.ts');
const generatedForTypeScriptFile = sourceFile === tsFile;
const result = injectPropTypesInFile({
components,
target: sourceContent,
options: {
disablePropTypesTypeChecking: generatedForTypeScriptFile,
babelOptions: {
filename: sourceFile,
},
comment: [
'┌────────────────────────────── Warning ──────────────────────────────┐',
'│ These PropTypes are generated from the TypeScript type definitions. │',
isTsFile
? '│ To update them, edit the TypeScript types and run `pnpm proptypes`. │'
: '│ To update them, edit the d.ts file and run `pnpm proptypes`. │',
'└─────────────────────────────────────────────────────────────────────┘',
].join('\n'),
ensureBabelPluginTransformReactRemovePropTypesIntegration: true,
getSortLiteralUnions,
reconcilePropTypes: (prop, previous, generated) => {
const usedCustomValidator = previous !== undefined && !previous.startsWith('PropTypes');
const ignoreGenerated =
previous !== undefined &&
previous.startsWith('PropTypes /* @typescript-to-proptypes-ignore */');
if (
ignoreGenerated &&
// `ignoreGenerated` implies that `previous !== undefined`
previous!
.replace('PropTypes /* @typescript-to-proptypes-ignore */', 'PropTypes')
.replace(/\s/g, '') === generated.replace(/\s/g, '')
) {
throw new Error(
`Unused \`@typescript-to-proptypes-ignore\` directive for prop '${prop.name}'.`,
);
}
if (usedCustomValidator || ignoreGenerated) {
// `usedCustomValidator` and `ignoreGenerated` narrow `previous` to `string`
return previous!;
}
return generated;
},
shouldInclude: ({ prop }) => {
if (prop.name === 'children') {
return true;
}
let shouldDocument;
prop.filenames.forEach((filename) => {
const isExternal = filename !== tsFile;
const implementedBySelfPropsFile =
filename === propsFile || filename === propsFileAlternative;
if (!isExternal || implementedBySelfPropsFile) {
shouldDocument = true;
}
});
return shouldDocument;
},
},
});
if (!result) {
throw new Error('Unable to produce inject propTypes into code.');
}
const prettierConfig = await prettier.resolveConfig(process.cwd(), {
config: path.join(__dirname, '../prettier.config.js'),
});
const prettified = await prettier.format(result, { ...prettierConfig, filepath: sourceFile });
const formatted = fixBabelGeneratorIssues(prettified);
const correctedLineEndings = fixLineEndings(sourceContent, formatted);
await fse.writeFile(sourceFile, correctedLineEndings);
}
interface HandlerArgv {
pattern: string;
}
async function run(argv: HandlerArgv) {
const { pattern } = argv;
const filePattern = new RegExp(pattern);
if (pattern.length > 0) {
console.log(`Only considering declaration files matching ${filePattern}`);
}
const buildProject = createTypeScriptProjectBuilder(CORE_TYPESCRIPT_PROJECTS);
// Matches files where the folder and file both start with uppercase letters
// Example: AppBar/AppBar.d.ts
const allFiles = await Promise.all(
[path.resolve(__dirname, '../packages/toolpad-core/src')].map((folderPath) =>
glob('+([A-Z])*/+([A-Z])*.*@(d.ts|ts|tsx)', {
absolute: true,
cwd: folderPath,
}),
),
);
const files = _.flatten(allFiles)
.filter((filePath) => {
// Filter out files where the directory name and filename doesn't match
// Example: Modal/ModalManager.d.ts
let folderName = path.basename(path.dirname(filePath));
const fileName = path.basename(filePath).replace(/(\.d\.ts|\.tsx|\.ts)/g, '');
// An exception is if the folder name starts with Unstable_/unstable_
// Example: Unstable_Grid2/Grid2.tsx
if (/(u|U)nstable_/g.test(folderName)) {
folderName = folderName.slice(9);
}
return !fileName.endsWith('.test');
})
.filter((filePath) => filePattern.test(filePath));
const promises = files.map<Promise<void>>(async (tsFile) => {
const sourceFile = tsFile.includes('.d.ts') ? tsFile.replace('.d.ts', '.js') : tsFile;
try {
const projectName = tsFile.match(/packages\/([a-zA-Z-]+)\/src/)![1];
const project = buildProject(projectName);
await generateProptypes(project, sourceFile, tsFile);
} catch (error: any) {
error.message = `${tsFile}: ${error.message}`;
throw error;
}
});
const results = await Promise.allSettled(promises);
const fails = results.filter((result): result is PromiseRejectedResult => {
return result.status === 'rejected';
});
fails.forEach((result) => {
console.error(result.reason);
});
if (fails.length > 0) {
process.exit(1);
}
}
yargs
.command<HandlerArgv>({
command: '$0',
describe: 'Generates Component.propTypes from TypeScript declarations',
builder: (command) => {
return command.option('pattern', {
default: '',
describe: 'Only considers declaration files matching this pattern.',
type: 'string',
});
},
handler: run,
})
.help()
.strict(true)
.version(false)
.parse();