typescript-docs-parser.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import fs from 'fs';
  2. import path from 'path';
  3. import ts from 'typescript';
  4. import { notNullOrUndefined } from '../../packages/common/src/shared-utils';
  5. import {
  6. ClassInfo,
  7. InterfaceInfo,
  8. MemberInfo,
  9. MethodInfo,
  10. MethodParameterInfo,
  11. ParsedDeclaration,
  12. PropertyInfo,
  13. TypeAliasInfo,
  14. ValidDeclaration,
  15. } from './typescript-docgen-types';
  16. /**
  17. * Parses TypeScript source files into data structures which can then be rendered into
  18. * markdown for documentation.
  19. */
  20. export class TypescriptDocsParser {
  21. /**
  22. * Parses the TypeScript files given by the filePaths array and returns the
  23. * parsed data structures ready for rendering.
  24. */
  25. parse(filePaths: string[]): ParsedDeclaration[] {
  26. const sourceFiles = filePaths.map(filePath => {
  27. return ts.createSourceFile(
  28. filePath,
  29. fs.readFileSync(filePath).toString(),
  30. ts.ScriptTarget.ES2015,
  31. true,
  32. );
  33. });
  34. const statements = this.getStatementsWithSourceLocation(sourceFiles);
  35. return statements
  36. .map(statement => {
  37. const info = this.parseDeclaration(statement.statement, statement.sourceFile, statement.sourceLine);
  38. return info;
  39. })
  40. .filter(notNullOrUndefined);
  41. }
  42. /**
  43. * Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
  44. * came from.
  45. */
  46. private getStatementsWithSourceLocation(
  47. sourceFiles: ts.SourceFile[],
  48. ): Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }> {
  49. return sourceFiles.reduce(
  50. (st, sf) => {
  51. const statementsWithSources = sf.statements.map(statement => {
  52. const sourceFile = path.relative(path.join(__dirname, '..'), sf.fileName).replace(/\\/g, '/');
  53. const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
  54. return {statement, sourceFile, sourceLine};
  55. });
  56. return [...st, ...statementsWithSources];
  57. },
  58. [] as Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }>,
  59. );
  60. }
  61. /**
  62. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  63. */
  64. private parseDeclaration(
  65. statement: ts.Statement,
  66. sourceFile: string,
  67. sourceLine: number,
  68. ): InterfaceInfo | TypeAliasInfo | ClassInfo | undefined {
  69. if (!this.isValidDeclaration(statement)) {
  70. return;
  71. }
  72. const category = this.getDocsCategory(statement);
  73. if (category === undefined) {
  74. return;
  75. }
  76. const title = statement.name ? statement.name.getText() : 'anonymous';
  77. const fullText = this.getDeclarationFullText(statement);
  78. const weight = this.getDeclarationWeight(statement);
  79. const description = this.getDeclarationDescription(statement);
  80. const normalizedTitle = this.kebabCase(title);
  81. const fileName = normalizedTitle === category ? '_index' : normalizedTitle;
  82. const info = {
  83. sourceFile,
  84. sourceLine,
  85. fullText,
  86. title,
  87. weight,
  88. category,
  89. description,
  90. fileName,
  91. };
  92. if (ts.isInterfaceDeclaration(statement)) {
  93. return {
  94. ...info,
  95. kind: 'interface',
  96. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  97. members: this.parseMembers(statement.members),
  98. };
  99. } else if (ts.isTypeAliasDeclaration(statement)) {
  100. return {
  101. ...info,
  102. type: statement.type,
  103. kind: 'typeAlias',
  104. members: ts.isTypeLiteralNode(statement.type) ? this.parseMembers(statement.type.members) : undefined,
  105. };
  106. } else if (ts.isClassDeclaration(statement)) {
  107. return {
  108. ...info,
  109. kind: 'class',
  110. members: this.parseMembers(statement.members),
  111. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  112. implements: this.getHeritageClauseText(statement, ts.SyntaxKind.ImplementsKeyword),
  113. };
  114. }
  115. }
  116. /**
  117. * Returns the text of any "extends" or "implements" clause of a class or interface.
  118. */
  119. private getHeritageClauseText(
  120. statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
  121. kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
  122. ): string | undefined {
  123. const {heritageClauses} = statement;
  124. if (!heritageClauses) {
  125. return;
  126. }
  127. const clause = heritageClauses.find(cl => cl.token === kind);
  128. if (!clause) {
  129. return;
  130. }
  131. return clause.getText();
  132. }
  133. /**
  134. * Returns the declaration name plus any type parameters.
  135. */
  136. private getDeclarationFullText(declaration: ValidDeclaration): string {
  137. const name = declaration.name ? declaration.name.getText() : 'anonymous';
  138. let typeParams = '';
  139. if (declaration.typeParameters) {
  140. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  141. }
  142. return name + typeParams;
  143. }
  144. /**
  145. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  146. */
  147. private parseMembers(
  148. members: ts.NodeArray<ts.TypeElement | ts.ClassElement>,
  149. ): Array<PropertyInfo | MethodInfo> {
  150. const result: Array<PropertyInfo | MethodInfo> = [];
  151. for (const member of members) {
  152. const modifiers = member.modifiers ? member.modifiers.map(m => m.getText()) : [];
  153. const isPrivate = modifiers.includes('private');
  154. if (
  155. !isPrivate &&
  156. (ts.isPropertySignature(member) ||
  157. ts.isMethodSignature(member) ||
  158. ts.isPropertyDeclaration(member) ||
  159. ts.isMethodDeclaration(member) ||
  160. ts.isConstructorDeclaration(member))
  161. ) {
  162. const name = member.name ? member.name.getText() : 'constructor';
  163. let description = '';
  164. let type = '';
  165. let defaultValue = '';
  166. let parameters: MethodParameterInfo[] = [];
  167. let fullText = '';
  168. if (ts.isConstructorDeclaration(member)) {
  169. fullText = 'constructor';
  170. } else if (ts.isMethodDeclaration(member)) {
  171. fullText = member.name.getText();
  172. } else {
  173. fullText = member.getText();
  174. }
  175. this.parseTags(member, {
  176. description: tag => (description += tag.comment || ''),
  177. example: tag => (description += this.formatExampleCode(tag.comment)),
  178. default: tag => (defaultValue = tag.comment || ''),
  179. });
  180. if (member.type) {
  181. type = member.type.getText();
  182. }
  183. const memberInfo: MemberInfo = {
  184. fullText,
  185. name,
  186. description,
  187. type,
  188. };
  189. if (
  190. ts.isMethodSignature(member) ||
  191. ts.isMethodDeclaration(member) ||
  192. ts.isConstructorDeclaration(member)
  193. ) {
  194. parameters = member.parameters.map(p => ({
  195. name: p.name.getText(),
  196. type: p.type ? p.type.getText() : '',
  197. }));
  198. result.push({
  199. ...memberInfo,
  200. kind: 'method',
  201. parameters,
  202. });
  203. } else {
  204. result.push({
  205. ...memberInfo,
  206. kind: 'property',
  207. defaultValue,
  208. });
  209. }
  210. }
  211. }
  212. return result;
  213. }
  214. /**
  215. * Reads the @docsWeight JSDoc tag from the interface.
  216. */
  217. private getDeclarationWeight(statement: ValidDeclaration): number {
  218. let weight = 10;
  219. this.parseTags(statement, {
  220. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  221. });
  222. return weight;
  223. }
  224. /**
  225. * Reads the @description JSDoc tag from the interface.
  226. */
  227. private getDeclarationDescription(statement: ValidDeclaration): string {
  228. let description = '';
  229. this.parseTags(statement, {
  230. description: tag => (description += tag.comment),
  231. example: tag => (description += this.formatExampleCode(tag.comment)),
  232. });
  233. return description;
  234. }
  235. /**
  236. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  237. */
  238. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  239. let category: string | undefined;
  240. this.parseTags(statement, {
  241. docsCategory: tag => (category = tag.comment || ''),
  242. });
  243. return this.kebabCase(category);
  244. };
  245. /**
  246. * Type guard for the types of statement which can ge processed by the doc generator.
  247. */
  248. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  249. return (
  250. ts.isInterfaceDeclaration(statement) ||
  251. ts.isTypeAliasDeclaration(statement) ||
  252. ts.isClassDeclaration(statement)
  253. );
  254. }
  255. /**
  256. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  257. */
  258. private parseTags<T extends ts.Node>(
  259. node: T,
  260. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  261. ): void {
  262. const jsDocTags = ts.getJSDocTags(node);
  263. for (const tag of jsDocTags) {
  264. const tagName = tag.tagName.text;
  265. if (tagMatcher[tagName]) {
  266. tagMatcher[tagName](tag);
  267. }
  268. }
  269. }
  270. /**
  271. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  272. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  273. */
  274. private formatExampleCode(example: string = ''): string {
  275. return '\n\n*Example*\n\n' + example.replace(/\n\s+\*\s/g, '\n');
  276. }
  277. private kebabCase<T extends string | undefined>(input: T): T {
  278. if (input == null) {
  279. return input;
  280. }
  281. return input.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-').toLowerCase() as T;
  282. }
  283. }