typescript-docs-parser.ts 18 KB

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