-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
/
Copy pathHookApiBuilder.ts
595 lines (536 loc) · 18.5 KB
/
HookApiBuilder.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import { readFileSync, writeFileSync } from 'fs';
import path from 'path';
import * as ts from 'typescript';
import * as astTypes from 'ast-types';
import * as _ from 'lodash';
import * as babel from '@babel/core';
import traverse from '@babel/traverse';
import { defaultHandlers, parse as docgenParse, ReactDocgenApi } from 'react-docgen';
import kebabCase from 'lodash/kebabCase';
import upperFirst from 'lodash/upperFirst';
import { renderMarkdown } from '@mui/internal-markdown';
import { ProjectSettings } from '../ProjectSettings';
import { computeApiDescription } from './ComponentApiBuilder';
import {
getSymbolDescription,
getSymbolJSDocTags,
HookInfo,
stringifySymbol,
toGitHubPath,
writePrettifiedFile,
} from '../buildApiUtils';
import { TypeScriptProject } from '../utils/createTypeScriptProject';
import generateApiTranslations from '../utils/generateApiTranslation';
interface ParsedProperty {
name: string;
description: string;
tags: { [tagName: string]: ts.JSDocTagInfo };
required: boolean;
typeStr: string;
}
const parseProperty = async (
propertySymbol: ts.Symbol,
project: TypeScriptProject,
): Promise<ParsedProperty> => ({
name: propertySymbol.name,
description: getSymbolDescription(propertySymbol, project),
tags: getSymbolJSDocTags(propertySymbol),
required: !propertySymbol.declarations?.find(ts.isPropertySignature)?.questionToken,
typeStr: await stringifySymbol(propertySymbol, project),
});
export interface ReactApi extends ReactDocgenApi {
demos: ReturnType<HookInfo['getDemos']>;
EOL: string;
filename: string;
apiPathname: string;
parameters?: ParsedProperty[];
returnValue?: ParsedProperty[];
/**
* hook name
* @example 'useButton'
*/
name: string;
description: string;
/**
* Different ways to import components
*/
imports: string[];
/**
* result of path.readFileSync from the `filename` in utf-8
*/
src: string;
parametersTable: _.Dictionary<{
default: string | undefined;
required: boolean | undefined;
type: { name: string | undefined; description: string | undefined };
deprecated: true | undefined;
deprecationInfo: string | undefined;
}>;
returnValueTable: _.Dictionary<{
default: string | undefined;
required: boolean | undefined;
type: { name: string | undefined; description: string | undefined };
deprecated: true | undefined;
deprecationInfo: string | undefined;
}>;
translations: {
hookDescription: string;
parametersDescriptions: {
[key: string]: {
description: string;
deprecated?: string;
};
};
returnValueDescriptions: {
[key: string]: {
description: string;
deprecated?: string;
};
};
};
/**
* The folder used to store the API translation.
*/
apiDocsTranslationFolder?: string;
}
/**
* Add demos & API comment block to type definitions, e.g.:
* /**
* * Demos:
* *
* * - [Button](https://mui.com/base-ui/react-button/)
* *
* * API:
* *
* * - [useButton API](https://mui.com/base-ui/api/use-button/)
*/
async function annotateHookDefinition(api: ReactApi) {
const HOST = 'https://mui.com';
const typesFilename = api.filename.replace(/\.js$/, '.d.ts');
const fileName = path.parse(api.filename).name;
const typesSource = readFileSync(typesFilename, { encoding: 'utf8' });
const typesAST = await babel.parseAsync(typesSource, {
configFile: false,
filename: typesFilename,
presets: [require.resolve('@babel/preset-typescript')],
});
if (typesAST === null) {
throw new Error('No AST returned from babel.');
}
let start = 0;
let end = null;
traverse(typesAST, {
ExportDefaultDeclaration(babelPath) {
if (api.filename.includes('mui-base')) {
// Base UI does not use default exports.
return;
}
/**
* export default function Menu() {}
*/
let node: babel.Node = babelPath.node;
if (node.declaration.type === 'Identifier') {
// declare const Menu: {};
// export default Menu;
if (babel.types.isIdentifier(babelPath.node.declaration)) {
const bindingId = babelPath.node.declaration.name;
const binding = babelPath.scope.bindings[bindingId];
// The JSDoc MUST be located at the declaration
if (babel.types.isFunctionDeclaration(binding.path.node)) {
// For function declarations the binding is equal to the declaration
// /**
// */
// function Component() {}
node = binding.path.node;
} else {
// For variable declarations the binding points to the declarator.
// /**
// */
// const Component = () => {}
node = binding.path.parentPath!.node;
}
}
}
const { leadingComments } = node;
const leadingCommentBlocks =
leadingComments != null
? leadingComments.filter(({ type }) => type === 'CommentBlock')
: null;
const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null;
if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) {
throw new Error(
`Should only have a single leading jsdoc block but got ${
leadingCommentBlocks.length
}:\n${leadingCommentBlocks
.map(({ type, value }, index) => `#${index} (${type}): ${value}`)
.join('\n')}`,
);
}
if (jsdocBlock?.start != null && jsdocBlock?.end != null) {
start = jsdocBlock.start;
end = jsdocBlock.end;
} else if (node.start != null) {
start = node.start - 1;
end = start;
}
},
ExportNamedDeclaration(babelPath) {
if (!api.filename.includes('mui-base')) {
return;
}
let node: babel.Node = babelPath.node;
if (babel.types.isTSDeclareFunction(node.declaration)) {
// export function useHook() in .d.ts
if (node.declaration.id?.name !== fileName) {
return;
}
} else if (node.declaration == null) {
// export { useHook };
node.specifiers.forEach((specifier) => {
if (specifier.type === 'ExportSpecifier' && specifier.local.name === fileName) {
const binding = babelPath.scope.bindings[specifier.local.name];
if (babel.types.isFunctionDeclaration(binding.path.node)) {
// For function declarations the binding is equal to the declaration
// /**
// */
// function useHook() {}
node = binding.path.node;
} else {
// For variable declarations the binding points to the declarator.
// /**
// */
// const useHook = () => {}
node = binding.path.parentPath!.node;
}
}
});
} else if (babel.types.isFunctionDeclaration(node.declaration)) {
// export function useHook() in .ts
if (node.declaration.id?.name !== fileName) {
return;
}
} else {
return;
}
const { leadingComments } = node;
const leadingCommentBlocks =
leadingComments != null
? leadingComments.filter(({ type }) => type === 'CommentBlock')
: null;
const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null;
if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) {
throw new Error(
`Should only have a single leading jsdoc block but got ${
leadingCommentBlocks.length
}:\n${leadingCommentBlocks
.map(({ type, value }, index) => `#${index} (${type}): ${value}`)
.join('\n')}`,
);
}
if (jsdocBlock?.start != null && jsdocBlock?.end != null) {
start = jsdocBlock.start;
end = jsdocBlock.end;
} else if (node.start != null) {
start = node.start - 1;
end = start;
}
},
});
if (end === null || start === 0) {
throw new TypeError(
`${api.filename}: Don't know where to insert the jsdoc block. Probably no default export found`,
);
}
const markdownLines = (await computeApiDescription(api, { host: HOST })).split('\n');
// Ensure a newline between manual and generated description.
if (markdownLines[markdownLines.length - 1] !== '') {
markdownLines.push('');
}
if (api.demos && api.demos.length > 0) {
markdownLines.push(
'Demos:',
'',
...api.demos.map((item) => {
return `- [${item.demoPageTitle}](${
item.demoPathname.startsWith('http') ? item.demoPathname : `${HOST}${item.demoPathname}`
})`;
}),
'',
);
}
markdownLines.push(
'API:',
'',
`- [${api.name} API](${
api.apiPathname.startsWith('http') ? api.apiPathname : `${HOST}${api.apiPathname}`
})`,
);
const jsdoc = `/**\n${markdownLines
.map((line) => (line.length > 0 ? ` * ${line}` : ` *`))
.join('\n')}\n */`;
const typesSourceNew = typesSource.slice(0, start) + jsdoc + typesSource.slice(end);
writeFileSync(typesFilename, typesSourceNew, { encoding: 'utf8' });
}
const attachTable = (
reactApi: ReactApi,
params: ParsedProperty[],
tableName: 'parametersTable' | 'returnValueTable',
) => {
const propErrors: Array<[propName: string, error: Error]> = [];
const parameters: ReactApi[typeof tableName] = params
.map((p) => {
const { name: propName, ...propDescriptor } = p;
let prop: Omit<ParsedProperty, 'name'> | null;
try {
prop = propDescriptor;
} catch (error) {
propErrors.push([propName, error as Error]);
prop = null;
}
if (prop === null) {
// have to delete `componentProps.undefined` later
return [] as any;
}
const defaultTag = propDescriptor.tags?.default;
const defaultValue: string | undefined = defaultTag?.text?.[0]?.text;
const requiredProp = prop.required;
const deprecation = (propDescriptor.description || '').match(/@deprecated(\s+(?<info>.*))?/);
const typeDescription = (propDescriptor.typeStr ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
return {
[propName]: {
type: {
// The docgen generates this structure for the components. For consistency in the structure
// we are adding the same value in both the name and the description
name: typeDescription,
description: typeDescription,
},
default: defaultValue,
// undefined values are not serialized => saving some bytes
required: requiredProp || undefined,
deprecated: !!deprecation || undefined,
deprecationInfo: renderMarkdown(deprecation?.groups?.info || '').trim() || undefined,
},
};
})
.reduce((acc, curr) => ({ ...acc, ...curr }), {}) as unknown as ReactApi['parametersTable'];
if (propErrors.length > 0) {
throw new Error(
`There were errors creating prop descriptions:\n${propErrors
.map(([propName, error]) => {
return ` - ${propName}: ${error}`;
})
.join('\n')}`,
);
}
// created by returning the `[]` entry
delete parameters.undefined;
reactApi[tableName] = parameters;
};
const generateTranslationDescription = (description: string) => {
return renderMarkdown(description.replace(/\n@default.*$/, ''));
};
const attachTranslations = (reactApi: ReactApi) => {
const translations: ReactApi['translations'] = {
hookDescription: reactApi.description,
parametersDescriptions: {},
returnValueDescriptions: {},
};
(reactApi.parameters ?? []).forEach(({ name: propName, description }) => {
if (description) {
translations.parametersDescriptions[propName] = {
description: generateTranslationDescription(description),
};
const deprecation = (description || '').match(/@deprecated(\s+(?<info>.*))?/);
if (deprecation !== null) {
translations.parametersDescriptions[propName].deprecated =
renderMarkdown(deprecation?.groups?.info || '').trim() || undefined;
}
}
});
(reactApi.returnValue ?? []).forEach(({ name: propName, description }) => {
if (description) {
translations.returnValueDescriptions[propName] = {
description: generateTranslationDescription(description),
};
const deprecation = (description || '').match(/@deprecated(\s+(?<info>.*))?/);
if (deprecation !== null) {
translations.parametersDescriptions[propName].deprecated =
renderMarkdown(deprecation?.groups?.info || '').trim() || undefined;
}
}
});
reactApi.translations = translations;
};
const generateApiJson = async (outputDirectory: string, reactApi: ReactApi) => {
/**
* Gather the metadata needed for the component's API page.
*/
const pageContent = {
// Sorted by required DESC, name ASC
parameters: _.fromPairs(
Object.entries(reactApi.parametersTable).sort(([aName, aData], [bName, bData]) => {
if ((aData.required && bData.required) || (!aData.required && !bData.required)) {
return aName.localeCompare(bName);
}
if (aData.required) {
return -1;
}
return 1;
}),
),
returnValue: _.fromPairs(
Object.entries(reactApi.returnValueTable).sort(([aName, aData], [bName, bData]) => {
if ((aData.required && bData.required) || (!aData.required && !bData.required)) {
return aName.localeCompare(bName);
}
if (aData.required) {
return -1;
}
return 1;
}),
),
name: reactApi.name,
filename: toGitHubPath(reactApi.filename),
imports: reactApi.imports,
demos: `<ul>${reactApi.demos
.map((item) => `<li><a href="${item.demoPathname}">${item.demoPageTitle}</a></li>`)
.join('\n')}</ul>`,
};
await writePrettifiedFile(
path.resolve(outputDirectory, `${kebabCase(reactApi.name)}.json`),
JSON.stringify(pageContent),
);
};
const extractInfoFromType = async (
typeName: string,
project: TypeScriptProject,
): Promise<ParsedProperty[]> => {
// Generate the params
let result: ParsedProperty[] = [];
try {
const exportedSymbol = project.exports[typeName];
const type = project.checker.getDeclaredTypeOfSymbol(exportedSymbol);
// @ts-ignore
const typeDeclaration = type?.symbol?.declarations?.[0];
if (!typeDeclaration) {
return [];
}
const properties: Record<string, ParsedProperty> = {};
// @ts-ignore
const propertiesOnProject = type.getProperties();
// @ts-ignore
await Promise.all(
propertiesOnProject.map(async (propertySymbol) => {
properties[propertySymbol.name] = await parseProperty(propertySymbol, project);
}),
);
result = Object.values(properties)
.filter((property) => !property.tags.ignore)
.sort((a, b) => a.name.localeCompare(b.name));
} catch (e) {
console.error(`No declaration for ${typeName}`);
}
return result;
};
/**
* Helper to get the import options
* @param name The name of the hook
* @param filename The filename where its defined (to infer the package)
* @returns an array of import command
*/
const getHookImports = (name: string, filename: string) => {
const githubPath = toGitHubPath(filename);
const rootImportPath = githubPath.replace(
/\/packages\/mui(?:-(.+?))?\/src\/.*/,
(match, pkg) => `@mui/${pkg}`,
);
const subdirectoryImportPath = githubPath.replace(
/\/packages\/mui(?:-(.+?))?\/src\/([^\\/]+)\/.*/,
(match, pkg, directory) => `@mui/${pkg}/${directory}`,
);
let namedImportName = name;
const defaultImportName = name;
if (/unstable_/.test(githubPath)) {
namedImportName = `unstable_${name} as ${name}`;
}
const useNamedImports = rootImportPath === '@mui/base';
const subpathImport = useNamedImports
? `import { ${namedImportName} } from '${subdirectoryImportPath}';`
: `import ${defaultImportName} from '${subdirectoryImportPath}';`;
const rootImport = `import { ${namedImportName} } from '${rootImportPath}';`;
return [subpathImport, rootImport];
};
export default async function generateHookApi(
hooksInfo: HookInfo,
project: TypeScriptProject,
projectSettings: ProjectSettings,
) {
const { filename, name, apiPathname, apiPagesDirectory, getDemos, readFile, skipApiGeneration } =
hooksInfo;
const { shouldSkip, EOL, src } = readFile();
if (shouldSkip) {
return null;
}
const reactApi: ReactApi = docgenParse(
src,
(ast) => {
let node;
astTypes.visit(ast, {
visitFunctionDeclaration: (functionPath) => {
if (functionPath.node?.id?.name === name) {
node = functionPath;
}
return false;
},
});
return node;
},
defaultHandlers,
{ filename },
);
const parameters = await extractInfoFromType(`${upperFirst(name)}Parameters`, project);
const returnValue = await extractInfoFromType(`${upperFirst(name)}ReturnValue`, project);
// Ignore what we might have generated in `annotateHookDefinition`
const annotatedDescriptionMatch = reactApi.description.match(/(Demos|API):\r?\n\r?\n/);
if (annotatedDescriptionMatch !== null) {
reactApi.description = reactApi.description.slice(0, annotatedDescriptionMatch.index).trim();
}
reactApi.filename = filename;
reactApi.name = name;
reactApi.imports = getHookImports(name, filename);
reactApi.apiPathname = apiPathname;
reactApi.EOL = EOL;
reactApi.demos = getDemos();
if (reactApi.demos.length === 0) {
// TODO: Enable this error once all public hooks are documented
// throw new Error(
// 'Unable to find demos. \n' +
// `Be sure to include \`hooks: ${reactApi.name}\` in the markdown pages where the \`${reactApi.name}\` hook is relevant. ` +
// 'Every public hook should have a demo. ',
// );
}
attachTable(reactApi, parameters, 'parametersTable');
reactApi.parameters = parameters;
attachTable(reactApi, returnValue, 'returnValueTable');
reactApi.returnValue = returnValue;
attachTranslations(reactApi);
// eslint-disable-next-line no-console
console.log('Built API docs for', reactApi.name);
if (!skipApiGeneration) {
// Generate pages, json and translations
await generateApiTranslations(
path.join(process.cwd(), 'docs/translations/api-docs'),
reactApi,
projectSettings.translationLanguages,
);
await generateApiJson(apiPagesDirectory, reactApi);
// Add comment about demo & api links to the component hook file
await annotateHookDefinition(reactApi);
}
return reactApi;
}