typescript-docs-parser.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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, DocsPage,
  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. private readonly atTokenPlaceholder = '__EscapedAtToken__';
  22. /**
  23. * Parses the TypeScript files given by the filePaths array and returns the
  24. * parsed data structures ready for rendering.
  25. */
  26. parse(filePaths: string[]): DocsPage[] {
  27. const sourceFiles = filePaths.map(filePath => {
  28. return ts.createSourceFile(
  29. filePath,
  30. this.replaceEscapedAtTokens(fs.readFileSync(filePath).toString()),
  31. ts.ScriptTarget.ES2015,
  32. true,
  33. );
  34. });
  35. const statements = this.getStatementsWithSourceLocation(sourceFiles);
  36. const pageMap = statements
  37. .map(statement => {
  38. const info = this.parseDeclaration(
  39. statement.statement,
  40. statement.sourceFile,
  41. statement.sourceLine,
  42. );
  43. return info;
  44. })
  45. .filter(notNullOrUndefined)
  46. .reduce((pages, declaration) => {
  47. const pageTitle = declaration.page || declaration.title;
  48. const existingPage = pages.get(pageTitle);
  49. if (existingPage) {
  50. existingPage.declarations.push(declaration);
  51. } else {
  52. const normalizedTitle = this.kebabCase(pageTitle);
  53. const fileName = normalizedTitle === declaration.category ? '_index' : normalizedTitle;
  54. pages.set(pageTitle, {
  55. title: pageTitle,
  56. category: declaration.category,
  57. declarations: [declaration],
  58. fileName,
  59. });
  60. }
  61. return pages;
  62. }, new Map<string, DocsPage>());
  63. return Array.from(pageMap.values());
  64. };
  65. /**
  66. * Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
  67. * came from.
  68. */
  69. private getStatementsWithSourceLocation(
  70. sourceFiles: ts.SourceFile[],
  71. ): Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }> {
  72. return sourceFiles.reduce(
  73. (st, sf) => {
  74. const statementsWithSources = sf.statements.map(statement => {
  75. const sourceFile = path
  76. .relative(path.join(__dirname, '..'), sf.fileName)
  77. .replace(/\\/g, '/');
  78. const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
  79. return { statement, sourceFile, sourceLine };
  80. });
  81. return [...st, ...statementsWithSources];
  82. },
  83. [] as Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }>,
  84. );
  85. }
  86. /**
  87. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  88. */
  89. private parseDeclaration(
  90. statement: ts.Statement,
  91. sourceFile: string,
  92. sourceLine: number,
  93. ): ParsedDeclaration | undefined {
  94. if (!this.isValidDeclaration(statement)) {
  95. return;
  96. }
  97. const category = this.getDocsCategory(statement);
  98. if (category === undefined) {
  99. return;
  100. }
  101. let title: string;
  102. if (ts.isVariableStatement(statement)) {
  103. title = statement.declarationList.declarations[0].name.getText();
  104. } else {
  105. title = statement.name ? statement.name.getText() : 'anonymous';
  106. }
  107. const fullText = this.getDeclarationFullText(statement);
  108. const weight = this.getDeclarationWeight(statement);
  109. const description = this.getDeclarationDescription(statement);
  110. const docsPage = this.getDocsPage(statement);
  111. const packageName = this.getPackageName(sourceFile);
  112. const info = {
  113. packageName,
  114. sourceFile,
  115. sourceLine,
  116. fullText,
  117. title,
  118. weight,
  119. category,
  120. description,
  121. page: docsPage,
  122. };
  123. if (ts.isInterfaceDeclaration(statement)) {
  124. return {
  125. ...info,
  126. kind: 'interface',
  127. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  128. members: this.parseMembers(statement.members),
  129. };
  130. } else if (ts.isTypeAliasDeclaration(statement)) {
  131. return {
  132. ...info,
  133. type: statement.type,
  134. kind: 'typeAlias',
  135. members: ts.isTypeLiteralNode(statement.type)
  136. ? this.parseMembers(statement.type.members)
  137. : undefined,
  138. };
  139. } else if (ts.isClassDeclaration(statement)) {
  140. return {
  141. ...info,
  142. kind: 'class',
  143. members: this.parseMembers(statement.members),
  144. extends: this.getHeritageClauseText(statement, ts.SyntaxKind.ExtendsKeyword),
  145. implements: this.getHeritageClauseText(statement, ts.SyntaxKind.ImplementsKeyword),
  146. };
  147. } else if (ts.isEnumDeclaration(statement)) {
  148. return {
  149. ...info,
  150. kind: 'enum' as 'enum',
  151. members: this.parseMembers(statement.members) as PropertyInfo[],
  152. };
  153. } else if (ts.isFunctionDeclaration(statement)) {
  154. const parameters = statement.parameters.map(p => ({
  155. name: p.name.getText(),
  156. type: p.type ? p.type.getText() : '',
  157. optional: !!p.questionToken,
  158. initializer: p.initializer && p.initializer.getText(),
  159. }));
  160. return {
  161. ...info,
  162. kind: 'function',
  163. parameters,
  164. type: statement.type,
  165. };
  166. } else if (ts.isVariableStatement(statement)) {
  167. return {
  168. ...info,
  169. kind: 'variable',
  170. };
  171. }
  172. }
  173. /**
  174. * Returns the text of any "extends" or "implements" clause of a class or interface.
  175. */
  176. private getHeritageClauseText(
  177. statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
  178. kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
  179. ): string | undefined {
  180. const { heritageClauses } = statement;
  181. if (!heritageClauses) {
  182. return;
  183. }
  184. const clause = heritageClauses.find(cl => cl.token === kind);
  185. if (!clause) {
  186. return;
  187. }
  188. return clause.getText();
  189. }
  190. /**
  191. * Returns the declaration name plus any type parameters.
  192. */
  193. private getDeclarationFullText(declaration: ValidDeclaration): string {
  194. let name: string;
  195. if (ts.isVariableStatement(declaration)) {
  196. name = declaration.declarationList.declarations[0].name.getText();
  197. } else {
  198. name = declaration.name ? declaration.name.getText() : 'anonymous';
  199. }
  200. let typeParams = '';
  201. if (!ts.isEnumDeclaration(declaration) && !ts.isVariableStatement(declaration) && declaration.typeParameters) {
  202. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  203. }
  204. return name + typeParams;
  205. }
  206. private getPackageName(sourceFile: string): string {
  207. const matches = sourceFile.match(/\/packages\/([^/]+)\//);
  208. if (matches) {
  209. return `@vendure/${matches[1]}`;
  210. } else {
  211. return '';
  212. }
  213. }
  214. /**
  215. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  216. */
  217. private parseMembers(
  218. members: ts.NodeArray<ts.TypeElement | ts.ClassElement | ts.EnumMember>,
  219. ): Array<PropertyInfo | MethodInfo> {
  220. const result: Array<PropertyInfo | MethodInfo> = [];
  221. for (const member of members) {
  222. const modifiers = member.modifiers ? member.modifiers.map(m => m.getText()) : [];
  223. const isPrivate = modifiers.includes('private');
  224. if (
  225. !isPrivate &&
  226. (ts.isPropertySignature(member) ||
  227. ts.isMethodSignature(member) ||
  228. ts.isPropertyDeclaration(member) ||
  229. ts.isMethodDeclaration(member) ||
  230. ts.isConstructorDeclaration(member) ||
  231. ts.isEnumMember(member) ||
  232. ts.isGetAccessorDeclaration(member) ||
  233. ts.isIndexSignatureDeclaration(member))
  234. ) {
  235. const name = member.name ? member.name.getText() : ts.isIndexSignatureDeclaration(member) ? '[index]' : 'constructor';
  236. let description = '';
  237. let type = '';
  238. let defaultValue = '';
  239. let parameters: MethodParameterInfo[] = [];
  240. let fullText = '';
  241. let isInternal = false;
  242. if (ts.isConstructorDeclaration(member)) {
  243. fullText = 'constructor';
  244. } else if (ts.isMethodDeclaration(member)) {
  245. fullText = member.name.getText();
  246. } else if (ts.isGetAccessorDeclaration(member)) {
  247. fullText = `${member.name.getText()}: ${member.type ? member.type.getText() : 'void'}`;
  248. } else {
  249. fullText = member.getText();
  250. }
  251. this.parseTags(member, {
  252. description: tag => (description += tag.comment || ''),
  253. example: tag => (description += this.formatExampleCode(tag.comment)),
  254. default: tag => (defaultValue = tag.comment || ''),
  255. internal: tag => (isInternal = true),
  256. });
  257. if (isInternal) {
  258. continue;
  259. }
  260. if (!ts.isEnumMember(member) && member.type) {
  261. type = member.type.getText();
  262. }
  263. const memberInfo: MemberInfo = {
  264. fullText,
  265. name,
  266. description: this.restoreAtTokens(description),
  267. type,
  268. modifiers,
  269. };
  270. if (
  271. ts.isMethodSignature(member) ||
  272. ts.isMethodDeclaration(member) ||
  273. ts.isConstructorDeclaration(member)
  274. ) {
  275. parameters = member.parameters.map(p => ({
  276. name: p.name.getText(),
  277. type: p.type ? p.type.getText() : '',
  278. optional: !!p.questionToken,
  279. initializer: p.initializer && p.initializer.getText(),
  280. }));
  281. result.push({
  282. ...memberInfo,
  283. kind: 'method',
  284. parameters,
  285. });
  286. } else {
  287. result.push({
  288. ...memberInfo,
  289. kind: 'property',
  290. defaultValue,
  291. });
  292. }
  293. }
  294. }
  295. return result;
  296. }
  297. /**
  298. * Reads the @docsWeight JSDoc tag from the interface.
  299. */
  300. private getDeclarationWeight(statement: ValidDeclaration): number {
  301. let weight = 10;
  302. this.parseTags(statement, {
  303. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  304. });
  305. return weight;
  306. }
  307. private getDocsPage(statement: ValidDeclaration): string | undefined {
  308. let docsPage: string | undefined;
  309. this.parseTags(statement, {
  310. docsPage: tag => docsPage = tag.comment,
  311. });
  312. return docsPage;
  313. }
  314. /**
  315. * Reads the @description JSDoc tag from the interface.
  316. */
  317. private getDeclarationDescription(statement: ValidDeclaration): string {
  318. let description = '';
  319. this.parseTags(statement, {
  320. description: tag => (description += tag.comment),
  321. example: tag => (description += this.formatExampleCode(tag.comment)),
  322. });
  323. return this.restoreAtTokens(description);
  324. }
  325. /**
  326. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  327. */
  328. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  329. let category: string | undefined;
  330. this.parseTags(statement, {
  331. docsCategory: tag => (category = tag.comment || ''),
  332. });
  333. return this.kebabCase(category);
  334. }
  335. /**
  336. * Type guard for the types of statement which can ge processed by the doc generator.
  337. */
  338. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  339. return (
  340. ts.isInterfaceDeclaration(statement) ||
  341. ts.isTypeAliasDeclaration(statement) ||
  342. ts.isClassDeclaration(statement) ||
  343. ts.isEnumDeclaration(statement) ||
  344. ts.isFunctionDeclaration(statement) ||
  345. ts.isVariableStatement(statement)
  346. );
  347. }
  348. /**
  349. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  350. */
  351. private parseTags<T extends ts.Node>(
  352. node: T,
  353. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  354. ): void {
  355. const jsDocTags = ts.getJSDocTags(node);
  356. for (const tag of jsDocTags) {
  357. const tagName = tag.tagName.text;
  358. if (tagMatcher[tagName]) {
  359. tagMatcher[tagName](tag);
  360. }
  361. }
  362. }
  363. /**
  364. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  365. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  366. */
  367. private formatExampleCode(example: string = ''): string {
  368. return '\n\n*Example*\n\n' + example.replace(/\n\s+\*\s/g, '\n');
  369. }
  370. private kebabCase<T extends string | undefined>(input: T): T {
  371. if (input == null) {
  372. return input;
  373. }
  374. return input
  375. .replace(/([a-z])([A-Z])/g, '$1-$2')
  376. .replace(/\s+/g, '-')
  377. .toLowerCase() as T;
  378. }
  379. /**
  380. * TypeScript from v3.5.1 interprets all '@' tokens in a tag comment as a new tag. This is a problem e.g.
  381. * when a plugin includes in it's description some text like "install the @vendure/some-plugin package". Here,
  382. * TypeScript will interpret "@vendure" as a JSDoc tag and remove it and all remaining text from the comment.
  383. *
  384. * The solution is to replace all escaped @ tokens ("\@") with a replacer string so that TypeScript treats them
  385. * as regular comment text, and then once it has parsed the statement, we replace them with the "@" character.
  386. */
  387. private replaceEscapedAtTokens(content: string): string {
  388. return content.replace(/\\@/g, this.atTokenPlaceholder);
  389. }
  390. /**
  391. * Restores "@" tokens which were replaced by the replaceEscapedAtTokens() method.
  392. */
  393. private restoreAtTokens(content: string): string {
  394. return content.replace(new RegExp(this.atTokenPlaceholder, 'g'), '@');
  395. }
  396. }