typescript-docs-parser.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import fs from 'fs';
  2. import path from 'path';
  3. import ts, { HeritageClause, JSDocTag, SyntaxKind } from 'typescript';
  4. import { notNullOrUndefined } from '../../packages/common/src/shared-utils';
  5. import {
  6. DocsPage,
  7. MemberInfo,
  8. MethodInfo,
  9. MethodParameterInfo,
  10. ParsedDeclaration,
  11. PropertyInfo,
  12. ValidDeclaration,
  13. } from './typescript-docgen-types';
  14. /**
  15. * Parses TypeScript source files into data structures which can then be rendered into
  16. * markdown for documentation.
  17. */
  18. export class TypescriptDocsParser {
  19. private readonly atTokenPlaceholder = '__EscapedAtToken__';
  20. private readonly commentBlockEndTokenPlaceholder = '__EscapedCommentBlockEndToken__';
  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[]): DocsPage[] {
  26. const sourceFiles = filePaths.map(filePath => {
  27. return ts.createSourceFile(
  28. filePath,
  29. this.replaceEscapedTokens(fs.readFileSync(filePath).toString()),
  30. ts.ScriptTarget.ES2015,
  31. true,
  32. );
  33. });
  34. const statements = this.getStatementsWithSourceLocation(sourceFiles);
  35. const pageMap = statements
  36. .map(statement => {
  37. const info = this.parseDeclaration(
  38. statement.statement,
  39. statement.sourceFile,
  40. statement.sourceLine,
  41. );
  42. return info;
  43. })
  44. .filter(notNullOrUndefined)
  45. .reduce((pages, declaration) => {
  46. const pageTitle = declaration.page || declaration.title;
  47. const existingPage = pages.get(pageTitle);
  48. if (existingPage) {
  49. existingPage.declarations.push(declaration);
  50. } else {
  51. const normalizedTitle = this.kebabCase(pageTitle);
  52. const categoryLastPart = declaration.category.split('/').pop();
  53. const fileName = normalizedTitle === categoryLastPart ? '_index' : normalizedTitle;
  54. pages.set(pageTitle, {
  55. title: pageTitle,
  56. category: declaration.category.split('/'),
  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((st, sf) => {
  73. const statementsWithSources = sf.statements.map(statement => {
  74. const sourceFile = path.relative(path.join(__dirname, '..'), sf.fileName).replace(/\\/g, '/');
  75. const sourceLine = sf.getLineAndCharacterOfPosition(statement.getStart()).line + 1;
  76. return { statement, sourceFile, sourceLine };
  77. });
  78. return [...st, ...statementsWithSources];
  79. }, [] as Array<{ statement: ts.Statement; sourceFile: string; sourceLine: number }>);
  80. }
  81. /**
  82. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  83. */
  84. private parseDeclaration(
  85. statement: ts.Statement,
  86. sourceFile: string,
  87. sourceLine: number,
  88. ): ParsedDeclaration | undefined {
  89. if (!this.isValidDeclaration(statement)) {
  90. return;
  91. }
  92. const category = this.getDocsCategory(statement);
  93. if (category === undefined) {
  94. return;
  95. }
  96. let title: string;
  97. if (ts.isVariableStatement(statement)) {
  98. title = statement.declarationList.declarations[0].name.getText();
  99. } else {
  100. title = statement.name ? statement.name.getText() : 'anonymous';
  101. }
  102. const fullText = this.getDeclarationFullText(statement);
  103. const weight = this.getDeclarationWeight(statement);
  104. const description = this.getDeclarationDescription(statement);
  105. const docsPage = this.getDocsPage(statement);
  106. const since = this.getSince(statement);
  107. const experimental = this.getExperimental(statement);
  108. const packageName = this.getPackageName(sourceFile);
  109. const info = {
  110. packageName,
  111. sourceFile,
  112. sourceLine,
  113. fullText,
  114. title,
  115. weight,
  116. category,
  117. description,
  118. page: docsPage,
  119. since,
  120. experimental,
  121. };
  122. if (ts.isInterfaceDeclaration(statement)) {
  123. return {
  124. ...info,
  125. kind: 'interface',
  126. extendsClause: this.getHeritageClause(statement, ts.SyntaxKind.ExtendsKeyword),
  127. members: this.parseMembers(statement.members),
  128. };
  129. } else if (ts.isTypeAliasDeclaration(statement)) {
  130. return {
  131. ...info,
  132. type: statement.type,
  133. kind: 'typeAlias',
  134. members: ts.isTypeLiteralNode(statement.type)
  135. ? this.parseMembers(statement.type.members)
  136. : undefined,
  137. };
  138. } else if (ts.isClassDeclaration(statement)) {
  139. return {
  140. ...info,
  141. kind: 'class',
  142. members: this.parseMembers(statement.members),
  143. extendsClause: this.getHeritageClause(statement, ts.SyntaxKind.ExtendsKeyword),
  144. implementsClause: this.getHeritageClause(statement, ts.SyntaxKind.ImplementsKeyword),
  145. };
  146. } else if (ts.isEnumDeclaration(statement)) {
  147. return {
  148. ...info,
  149. kind: 'enum' as const,
  150. members: this.parseMembers(statement.members) as PropertyInfo[],
  151. };
  152. } else if (ts.isFunctionDeclaration(statement)) {
  153. const parameters = statement.parameters.map(p => ({
  154. name: p.name.getText(),
  155. type: p.type ? p.type.getText() : '',
  156. optional: !!p.questionToken,
  157. initializer: p.initializer && p.initializer.getText(),
  158. }));
  159. return {
  160. ...info,
  161. kind: 'function',
  162. parameters,
  163. type: statement.type,
  164. };
  165. } else if (ts.isVariableStatement(statement)) {
  166. return {
  167. ...info,
  168. kind: 'variable',
  169. };
  170. }
  171. }
  172. /**
  173. * Returns the text of any "extends" or "implements" clause of a class or interface.
  174. */
  175. private getHeritageClause(
  176. statement: ts.ClassDeclaration | ts.InterfaceDeclaration,
  177. kind: ts.SyntaxKind.ExtendsKeyword | ts.SyntaxKind.ImplementsKeyword,
  178. ): HeritageClause | undefined {
  179. const { heritageClauses } = statement;
  180. if (!heritageClauses) {
  181. return;
  182. }
  183. const clause = heritageClauses.find(cl => cl.token === kind);
  184. if (!clause) {
  185. return;
  186. }
  187. return clause;
  188. }
  189. /**
  190. * Returns the declaration name plus any type parameters.
  191. */
  192. private getDeclarationFullText(declaration: ValidDeclaration): string {
  193. let name: string;
  194. if (ts.isVariableStatement(declaration)) {
  195. name = declaration.declarationList.declarations[0].name.getText();
  196. } else {
  197. name = declaration.name ? declaration.name.getText() : 'anonymous';
  198. }
  199. let typeParams = '';
  200. if (
  201. !ts.isEnumDeclaration(declaration) &&
  202. !ts.isVariableStatement(declaration) &&
  203. declaration.typeParameters
  204. ) {
  205. typeParams = '<' + declaration.typeParameters.map(tp => tp.getText()).join(', ') + '>';
  206. }
  207. return name + typeParams;
  208. }
  209. private getPackageName(sourceFile: string): string {
  210. const matches = sourceFile.match(/\/packages\/([^/]+)\//);
  211. if (matches) {
  212. return `@vendure/${matches[1]}`;
  213. } else {
  214. return '';
  215. }
  216. }
  217. /**
  218. * Parses an array of interface members into a simple object which can be rendered into markdown.
  219. */
  220. private parseMembers(
  221. members: ts.NodeArray<ts.TypeElement | ts.ClassElement | ts.EnumMember>,
  222. ): Array<PropertyInfo | MethodInfo> {
  223. const result: Array<PropertyInfo | MethodInfo> = [];
  224. for (const member of members) {
  225. const modifiers = member.modifiers ? member.modifiers.map(m => m.getText()) : [];
  226. const isPrivate = modifiers.includes('private');
  227. if (
  228. !isPrivate &&
  229. (ts.isPropertySignature(member) ||
  230. ts.isMethodSignature(member) ||
  231. ts.isPropertyDeclaration(member) ||
  232. ts.isMethodDeclaration(member) ||
  233. ts.isConstructorDeclaration(member) ||
  234. ts.isEnumMember(member) ||
  235. ts.isGetAccessorDeclaration(member) ||
  236. ts.isIndexSignatureDeclaration(member))
  237. ) {
  238. const name = member.name
  239. ? member.name.getText()
  240. : ts.isIndexSignatureDeclaration(member)
  241. ? '[index]'
  242. : 'constructor';
  243. let description = '';
  244. let type = '';
  245. let defaultValue = '';
  246. let parameters: MethodParameterInfo[] = [];
  247. let fullText = '';
  248. let isInternal = false;
  249. let since: string | undefined;
  250. let experimental = false;
  251. if (ts.isConstructorDeclaration(member)) {
  252. fullText = 'constructor';
  253. } else if (ts.isMethodDeclaration(member)) {
  254. fullText = member.name.getText();
  255. } else if (ts.isGetAccessorDeclaration(member)) {
  256. fullText = `${member.name.getText()}: ${member.type ? member.type.getText() : 'void'}`;
  257. } else {
  258. fullText = member.getText();
  259. }
  260. this.parseTags(member, {
  261. description: comment => (description += comment || ''),
  262. example: comment => (description += this.formatExampleCode(comment)),
  263. default: comment => (defaultValue = comment || ''),
  264. internal: comment => (isInternal = true),
  265. since: comment => (since = comment || undefined),
  266. experimental: comment => (experimental = comment != null),
  267. });
  268. if (isInternal) {
  269. continue;
  270. }
  271. if (!ts.isEnumMember(member) && member.type) {
  272. type = member.type.getText();
  273. }
  274. const memberInfo: MemberInfo = {
  275. fullText,
  276. name,
  277. description: this.restoreTokens(description),
  278. type,
  279. modifiers,
  280. since,
  281. experimental,
  282. };
  283. if (
  284. ts.isMethodSignature(member) ||
  285. ts.isMethodDeclaration(member) ||
  286. ts.isConstructorDeclaration(member)
  287. ) {
  288. parameters = member.parameters.map(p => ({
  289. name: p.name.getText(),
  290. type: p.type ? p.type.getText() : '',
  291. optional: !!p.questionToken,
  292. initializer: p.initializer && p.initializer.getText(),
  293. }));
  294. result.push({
  295. ...memberInfo,
  296. kind: 'method',
  297. parameters,
  298. });
  299. } else {
  300. result.push({
  301. ...memberInfo,
  302. kind: 'property',
  303. defaultValue,
  304. });
  305. }
  306. }
  307. }
  308. return result;
  309. }
  310. private tagCommentText(tag: JSDocTag): string {
  311. if (!tag.comment) {
  312. return '';
  313. }
  314. if (typeof tag.comment === 'string') {
  315. return tag.comment;
  316. }
  317. return tag.comment.map(t => (t.kind === SyntaxKind.JSDocText ? t.text : t.getText())).join('');
  318. }
  319. /**
  320. * Reads the @docsWeight JSDoc tag from the interface.
  321. */
  322. private getDeclarationWeight(statement: ValidDeclaration): number {
  323. let weight = 10;
  324. this.parseTags(statement, {
  325. docsWeight: comment => (weight = Number.parseInt(comment || '10', 10)),
  326. });
  327. return weight;
  328. }
  329. private getDocsPage(statement: ValidDeclaration): string | undefined {
  330. let docsPage: string | undefined;
  331. this.parseTags(statement, {
  332. docsPage: comment => (docsPage = comment),
  333. });
  334. return docsPage;
  335. }
  336. /**
  337. * Reads the @since JSDoc tag
  338. */
  339. private getSince(statement: ValidDeclaration): string | undefined {
  340. let since: string | undefined;
  341. this.parseTags(statement, {
  342. since: comment => (since = comment),
  343. });
  344. return since;
  345. }
  346. /**
  347. * Reads the @experimental JSDoc tag
  348. */
  349. private getExperimental(statement: ValidDeclaration): boolean {
  350. let experimental = false;
  351. this.parseTags(statement, {
  352. experimental: comment => (experimental = comment != null),
  353. });
  354. return experimental;
  355. }
  356. /**
  357. * Reads the @description JSDoc tag from the interface.
  358. */
  359. private getDeclarationDescription(statement: ValidDeclaration): string {
  360. let description = '';
  361. this.parseTags(statement, {
  362. description: comment => (description += comment),
  363. example: comment => (description += this.formatExampleCode(comment)),
  364. });
  365. return this.restoreTokens(description);
  366. }
  367. /**
  368. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  369. */
  370. private getDocsCategory(statement: ValidDeclaration): string | undefined {
  371. let category: string | undefined;
  372. this.parseTags(statement, {
  373. docsCategory: comment => (category = comment || ''),
  374. });
  375. return this.kebabCase(category);
  376. }
  377. /**
  378. * Type guard for the types of statement which can ge processed by the doc generator.
  379. */
  380. private isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  381. return (
  382. ts.isInterfaceDeclaration(statement) ||
  383. ts.isTypeAliasDeclaration(statement) ||
  384. ts.isClassDeclaration(statement) ||
  385. ts.isEnumDeclaration(statement) ||
  386. ts.isFunctionDeclaration(statement) ||
  387. ts.isVariableStatement(statement)
  388. );
  389. }
  390. /**
  391. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  392. */
  393. private parseTags<T extends ts.Node>(
  394. node: T,
  395. tagMatcher: { [tagName: string]: (tagComment: string) => void },
  396. ): void {
  397. const jsDocTags = ts.getJSDocTags(node);
  398. for (const tag of jsDocTags) {
  399. const tagName = tag.tagName.text;
  400. if (tagMatcher[tagName]) {
  401. tagMatcher[tagName](this.tagCommentText(tag));
  402. }
  403. }
  404. }
  405. /**
  406. * Ensure all the code examples use the unix-style line separators.
  407. */
  408. private formatExampleCode(example: string = ''): string {
  409. return '\n\n*Example*\n\n' + example.replace(/\r/g, '');
  410. }
  411. private kebabCase<T extends string | undefined>(input: T): T {
  412. if (input == null) {
  413. return input;
  414. }
  415. return input
  416. .replace(/([a-z])([A-Z])/g, '$1-$2')
  417. .replace(/\s+/g, '-')
  418. .toLowerCase() as T;
  419. }
  420. /**
  421. * TypeScript from v3.5.1 interprets all '@' tokens in a tag comment as a new tag. This is a problem e.g.
  422. * when a plugin includes in its description some text like "install the @vendure/some-plugin package". Here,
  423. * TypeScript will interpret "@vendure" as a JSDoc tag and remove it and all remaining text from the comment.
  424. *
  425. * The solution is to replace all escaped @ tokens ("\@") with a replacer string so that TypeScript treats them
  426. * as regular comment text, and then once it has parsed the statement, we replace them with the "@" character.
  427. *
  428. * Similarly, '/*' is interpreted as end of a comment block. However, it can be useful to specify a globstar
  429. * pattern in descriptions and therefore it is supported as long as the leading '/' is escaped ("\/").
  430. */
  431. private replaceEscapedTokens(content: string): string {
  432. return content
  433. .replace(/\\@/g, this.atTokenPlaceholder)
  434. .replace(/\\\/\*/g, this.commentBlockEndTokenPlaceholder);
  435. }
  436. /**
  437. * Restores "@" and "/*" tokens which were replaced by the replaceEscapedTokens() method.
  438. */
  439. private restoreTokens(content: string): string {
  440. return content
  441. .replace(new RegExp(this.atTokenPlaceholder, 'g'), '@')
  442. .replace(new RegExp(this.commentBlockEndTokenPlaceholder, 'g'), '/*');
  443. }
  444. }