typescript-docs-parser.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. ): ParsedDeclaration | 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 packageName = this.getPackageName(sourceFile);
  83. const info = {
  84. packageName,
  85. sourceFile,
  86. sourceLine,
  87. fullText,
  88. title,
  89. weight,
  90. category,
  91. description,
  92. fileName,
  93. };
  94. if (ts.isInterfaceDeclaration(statement)) {
  95. return {
  96. ...info,
  97. kind: 'interface',
  98. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  99. members: this.parseMembers(statement.members),
  100. };
  101. } else if (ts.isTypeAliasDeclaration(statement)) {
  102. return {
  103. ...info,
  104. type: statement.type,
  105. kind: 'typeAlias',
  106. members: ts.isTypeLiteralNode(statement.type) ? this.parseMembers(statement.type.members) : undefined,
  107. };
  108. } else if (ts.isClassDeclaration(statement)) {
  109. return {
  110. ...info,
  111. kind: 'class',
  112. members: this.parseMembers(statement.members),
  113. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  114. implements: this.getHeritageClauseText(statement, ts.SyntaxKind.ImplementsKeyword),
  115. };
  116. } else if (ts.isEnumDeclaration(statement)) {
  117. return {
  118. ...info,
  119. kind: 'enum' as 'enum',
  120. members: this.parseMembers(statement.members) as PropertyInfo[],
  121. };
  122. } else if (ts.isFunctionDeclaration(statement)) {
  123. const parameters = statement.parameters.map(p => ({
  124. name: p.name.getText(),
  125. type: p.type ? p.type.getText() : '',
  126. optional: !!p.questionToken,
  127. initializer: p.initializer && p.initializer.getText(),
  128. }));
  129. return {
  130. ...info,
  131. kind: 'function',
  132. parameters,
  133. type: statement.type,
  134. };
  135. }
  136. }
  137. /**
  138. * Returns the text of any "extends" or "implements" clause of a class or interface.
  139. */
  140. private getHeritageClauseText(
  141. statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
  142. kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
  143. ): string | undefined {
  144. const {heritageClauses} = statement;
  145. if (!heritageClauses) {
  146. return;
  147. }
  148. const clause = heritageClauses.find(cl => cl.token === kind);
  149. if (!clause) {
  150. return;
  151. }
  152. return clause.getText();
  153. }
  154. /**
  155. * Returns the declaration name plus any type parameters.
  156. */
  157. private getDeclarationFullText(declaration: ValidDeclaration): string {
  158. const name = declaration.name ? declaration.name.getText() : 'anonymous';
  159. let typeParams = '';
  160. if (!ts.isEnumDeclaration(declaration) && declaration.typeParameters) {
  161. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  162. }
  163. return name + typeParams;
  164. }
  165. private getPackageName(sourceFile: string): string {
  166. const matches = sourceFile.match(/\/packages\/([^/]+)\//);
  167. if (matches) {
  168. return `@vendure/${matches[1]}`;
  169. } else {
  170. return '';
  171. }
  172. }
  173. /**
  174. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  175. */
  176. private parseMembers(
  177. members: ts.NodeArray<ts.TypeElement | ts.ClassElement | ts.EnumMember>,
  178. ): Array<PropertyInfo | MethodInfo> {
  179. const result: Array<PropertyInfo | MethodInfo> = [];
  180. for (const member of members) {
  181. const modifiers = member.modifiers ? member.modifiers.map(m => m.getText()) : [];
  182. const isPrivate = modifiers.includes('private');
  183. if (
  184. !isPrivate &&
  185. (ts.isPropertySignature(member) ||
  186. ts.isMethodSignature(member) ||
  187. ts.isPropertyDeclaration(member) ||
  188. ts.isMethodDeclaration(member) ||
  189. ts.isConstructorDeclaration(member) ||
  190. ts.isEnumMember(member)
  191. )
  192. ) {
  193. const name = member.name ? member.name.getText() : 'constructor';
  194. let description = '';
  195. let type = '';
  196. let defaultValue = '';
  197. let parameters: MethodParameterInfo[] = [];
  198. let fullText = '';
  199. let isInternal = false;
  200. if (ts.isConstructorDeclaration(member)) {
  201. fullText = 'constructor';
  202. } else if (ts.isMethodDeclaration(member)) {
  203. fullText = member.name.getText();
  204. } else {
  205. fullText = member.getText();
  206. }
  207. this.parseTags(member, {
  208. description: tag => (description += tag.comment || ''),
  209. example: tag => (description += this.formatExampleCode(tag.comment)),
  210. default: tag => (defaultValue = tag.comment || ''),
  211. internal: tag => isInternal = true,
  212. });
  213. if (isInternal) {
  214. continue;
  215. }
  216. if (!ts.isEnumMember(member) && member.type) {
  217. type = member.type.getText();
  218. }
  219. const memberInfo: MemberInfo = {
  220. fullText,
  221. name,
  222. description,
  223. type,
  224. modifiers,
  225. };
  226. if (
  227. ts.isMethodSignature(member) ||
  228. ts.isMethodDeclaration(member) ||
  229. ts.isConstructorDeclaration(member)
  230. ) {
  231. parameters = member.parameters.map(p => ({
  232. name: p.name.getText(),
  233. type: p.type ? p.type.getText() : '',
  234. optional: !!p.questionToken,
  235. initializer: p.initializer && p.initializer.getText(),
  236. }));
  237. result.push({
  238. ...memberInfo,
  239. kind: 'method',
  240. parameters,
  241. });
  242. } else {
  243. result.push({
  244. ...memberInfo,
  245. kind: 'property',
  246. defaultValue,
  247. });
  248. }
  249. }
  250. }
  251. return result;
  252. }
  253. /**
  254. * Reads the @docsWeight JSDoc tag from the interface.
  255. */
  256. private getDeclarationWeight(statement: ValidDeclaration): number {
  257. let weight = 10;
  258. this.parseTags(statement, {
  259. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  260. });
  261. return weight;
  262. }
  263. /**
  264. * Reads the @description JSDoc tag from the interface.
  265. */
  266. private getDeclarationDescription(statement: ValidDeclaration): string {
  267. let description = '';
  268. this.parseTags(statement, {
  269. description: tag => (description += tag.comment),
  270. example: tag => (description += this.formatExampleCode(tag.comment)),
  271. });
  272. return description;
  273. }
  274. /**
  275. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  276. */
  277. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  278. let category: string | undefined;
  279. this.parseTags(statement, {
  280. docsCategory: tag => (category = tag.comment || ''),
  281. });
  282. return this.kebabCase(category);
  283. }
  284. /**
  285. * Type guard for the types of statement which can ge processed by the doc generator.
  286. */
  287. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  288. return (
  289. ts.isInterfaceDeclaration(statement) ||
  290. ts.isTypeAliasDeclaration(statement) ||
  291. ts.isClassDeclaration(statement) ||
  292. ts.isEnumDeclaration(statement) ||
  293. ts.isFunctionDeclaration(statement)
  294. );
  295. }
  296. /**
  297. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  298. */
  299. private parseTags<T extends ts.Node>(
  300. node: T,
  301. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  302. ): void {
  303. const jsDocTags = ts.getJSDocTags(node);
  304. for (const tag of jsDocTags) {
  305. const tagName = tag.tagName.text;
  306. if (tagMatcher[tagName]) {
  307. tagMatcher[tagName](tag);
  308. }
  309. }
  310. }
  311. /**
  312. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  313. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  314. */
  315. private formatExampleCode(example: string = ''): string {
  316. return '\n\n*Example*\n\n' + example.replace(/\n\s+\*\s/g, '\n');
  317. }
  318. private kebabCase<T extends string | undefined>(input: T): T {
  319. if (input == null) {
  320. return input;
  321. }
  322. return input.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\s+/g, '-').toLowerCase() as T;
  323. }
  324. }