typescript-docs-renderer.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // tslint:disable:no-console
  2. import fs from 'fs-extra';
  3. import klawSync from 'klaw-sync';
  4. import path from 'path';
  5. import ts from 'typescript';
  6. import { assertNever } from '../../packages/common/src/shared-utils';
  7. import { deleteGeneratedDocs, generateFrontMatter } from './docgen-utils';
  8. import {
  9. ClassInfo,
  10. DeclarationInfo,
  11. EnumInfo,
  12. FunctionInfo,
  13. InterfaceInfo, MethodParameterInfo,
  14. ParsedDeclaration,
  15. TypeAliasInfo,
  16. TypeMap,
  17. } from './typescript-docgen-types';
  18. export class TypescriptDocsRenderer {
  19. render(parsedDeclarations: ParsedDeclaration[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  20. let generatedCount = 0;
  21. if (!fs.existsSync(outputPath)) {
  22. fs.mkdirs(outputPath);
  23. }
  24. for (const info of parsedDeclarations) {
  25. let markdown = '';
  26. switch (info.kind) {
  27. case 'interface':
  28. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  29. break;
  30. case 'typeAlias':
  31. markdown = this.renderTypeAlias(info, typeMap, docsUrl);
  32. break;
  33. case 'class':
  34. markdown = this.renderInterfaceOrClass(info, typeMap, docsUrl);
  35. break;
  36. case 'enum':
  37. markdown = this.renderEnum(info, typeMap, docsUrl);
  38. break;
  39. case 'function':
  40. markdown = this.renderFunction(info, typeMap, docsUrl);
  41. break;
  42. default:
  43. assertNever(info);
  44. }
  45. const categoryDir = path.join(outputPath, info.category);
  46. const indexFile = path.join(categoryDir, '_index.md');
  47. if (!fs.existsSync(categoryDir)) {
  48. fs.mkdirsSync(categoryDir);
  49. }
  50. if (!fs.existsSync(indexFile)) {
  51. const indexFileContent = generateFrontMatter(info.category, 10, false) + `\n\n# ${info.category}`;
  52. fs.writeFileSync(indexFile, indexFileContent);
  53. generatedCount++;
  54. }
  55. fs.writeFileSync(path.join(categoryDir, info.fileName + '.md'), markdown);
  56. generatedCount++;
  57. }
  58. return generatedCount;
  59. }
  60. /**
  61. * Render the interface to a markdown string.
  62. */
  63. private renderInterfaceOrClass(info: InterfaceInfo | ClassInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  64. const { title, weight, category, description, members } = info;
  65. let output = '';
  66. output += generateFrontMatter(title, weight);
  67. output += `\n\n# ${title}\n\n`;
  68. output += this.renderGenerationInfoShortcode(info);
  69. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  70. output += `## Signature\n\n`;
  71. output += info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  72. output += `## Members\n\n`;
  73. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  74. return output;
  75. }
  76. /**
  77. * Render the type alias to a markdown string.
  78. */
  79. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  80. const { title, weight, description, type, fullText } = typeAliasInfo;
  81. let output = '';
  82. output += generateFrontMatter(title, weight);
  83. output += `\n\n# ${title}\n\n`;
  84. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  85. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  86. output += `## Signature\n\n`;
  87. output += this.renderTypeAliasSignature(typeAliasInfo);
  88. if (typeAliasInfo.members) {
  89. output += `## Members\n\n`;
  90. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  91. }
  92. return output;
  93. }
  94. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  95. const { title, weight, description, fullText } = enumInfo;
  96. let output = '';
  97. output += generateFrontMatter(title, weight);
  98. output += `\n\n# ${title}\n\n`;
  99. output += this.renderGenerationInfoShortcode(enumInfo);
  100. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  101. output += `## Signature\n\n`;
  102. output += this.renderEnumSignature(enumInfo);
  103. return output;
  104. }
  105. private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  106. const { title, weight, description, fullText, parameters } = functionInfo;
  107. let output = '';
  108. output += generateFrontMatter(title, weight);
  109. output += `\n\n# ${title}\n\n`;
  110. output += this.renderGenerationInfoShortcode(functionInfo);
  111. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  112. output += `## Signature\n\n`;
  113. output += this.renderFunctionSignature(functionInfo, knownTypeMap);
  114. if (parameters.length) {
  115. output += `## Parameters\n\n`;
  116. output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
  117. }
  118. return output;
  119. }
  120. /**
  121. * Generates a markdown code block string for the interface signature.
  122. */
  123. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  124. const { fullText, members } = interfaceInfo;
  125. let output = '';
  126. output += `\`\`\`TypeScript\n`;
  127. output += `interface ${fullText} `;
  128. if (interfaceInfo.extends) {
  129. output += interfaceInfo.extends + ' ';
  130. }
  131. output += `{\n`;
  132. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  133. output += `\n}\n`;
  134. output += `\`\`\`\n`;
  135. return output;
  136. }
  137. private renderClassSignature(classInfo: ClassInfo): string {
  138. const { fullText, members } = classInfo;
  139. let output = '';
  140. output += `\`\`\`TypeScript\n`;
  141. output += `class ${fullText} `;
  142. if (classInfo.extends) {
  143. output += classInfo.extends + ' ';
  144. }
  145. if (classInfo.implements) {
  146. output += classInfo.implements + ' ';
  147. }
  148. output += `{\n`;
  149. const renderModifiers = (modifiers: string[]) => modifiers.length ? modifiers.join(' ') + ' ' : '';
  150. output += members
  151. .map(member => {
  152. if (member.kind === 'method') {
  153. const args = member.parameters
  154. .map(p => this.renderParameter(p, p.type))
  155. .join(', ');
  156. if (member.fullText === 'constructor') {
  157. return ` constructor(${args})`;
  158. } else {
  159. return ` ${renderModifiers(member.modifiers)}${member.fullText}(${args}) => ${member.type};`;
  160. }
  161. } else {
  162. return ` ${renderModifiers(member.modifiers)}${member.fullText}`;
  163. }
  164. })
  165. .join(`\n`);
  166. output += `\n}\n`;
  167. output += `\`\`\`\n`;
  168. return output;
  169. }
  170. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  171. const { fullText, members, type } = typeAliasInfo;
  172. let output = '';
  173. output += `\`\`\`TypeScript\n`;
  174. output += `type ${fullText} = `;
  175. if (members) {
  176. output += `{\n`;
  177. output += members.map(member => ` ${member.fullText}`).join(`\n`);
  178. output += `\n}\n`;
  179. } else {
  180. output += type.getText() + `\n`;
  181. }
  182. output += `\`\`\`\n`;
  183. return output;
  184. }
  185. private renderEnumSignature(enumInfo: EnumInfo): string {
  186. const { fullText, members } = enumInfo;
  187. let output = '';
  188. output += `\`\`\`TypeScript\n`;
  189. output += `enum ${fullText} `;
  190. if (members) {
  191. output += `{\n`;
  192. output += members.map(member => {
  193. let line = member.description ? ` // ${member.description}\n` : '';
  194. line += ` ${member.fullText}`;
  195. return line;
  196. }).join(`\n`);
  197. output += `\n}\n`;
  198. }
  199. output += `\`\`\`\n`;
  200. return output;
  201. }
  202. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  203. const { fullText, parameters, type } = functionInfo;
  204. const args = parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  205. let output = '';
  206. output += `\`\`\`TypeScript\n`;
  207. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  208. output += `\`\`\`\n`;
  209. return output;
  210. }
  211. private renderFunctionParams(params: MethodParameterInfo[], knownTypeMap: TypeMap, docsUrl: string): string {
  212. let output = '';
  213. for (const param of params) {
  214. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  215. output += `### ${param.name}\n\n`;
  216. output += `{{< member-info kind="parameter" type="${type}" >}}\n\n`;
  217. }
  218. return output;
  219. }
  220. private renderMembers(info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  221. const { members, title } = info;
  222. let output = '';
  223. for (const member of members || []) {
  224. let defaultParam = '';
  225. let type = '';
  226. if (member.kind === 'property') {
  227. type = this.renderType(member.type, knownTypeMap, docsUrl);
  228. defaultParam = member.defaultValue
  229. ? `default="${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}" `
  230. : '';
  231. } else {
  232. const args = member.parameters
  233. .map(p => this.renderParameter(p, this.renderType(p.type, knownTypeMap, docsUrl)))
  234. .join(', ');
  235. if (member.fullText === 'constructor') {
  236. type = `(${args}) => ${title}`;
  237. } else {
  238. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  239. }
  240. }
  241. output += `### ${member.name}\n\n`;
  242. output += `{{< member-info kind="${[...member.modifiers, member.kind].join(' ')}" type="${type}" ${defaultParam}>}}\n\n`;
  243. output += `${this.renderDescription(member.description, knownTypeMap, docsUrl)}\n\n`;
  244. }
  245. return output;
  246. }
  247. private renderParameter(p: MethodParameterInfo, typeString: string): string {
  248. return `${p.name}${p.optional ? '?' : ''}: ${typeString}${p.initializer ? ` = ${p.initializer}` : ''}`;
  249. }
  250. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  251. const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
  252. return `{{< generation-info sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}">}}\n\n`;
  253. }
  254. /**
  255. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  256. * and known types (e.g. "ShippingMethod") into hyperlinks.
  257. */
  258. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  259. let typeText = type
  260. .trim()
  261. // encode HTML entities
  262. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  263. // remove newlines
  264. .replace(/\n/g, ' ');
  265. for (const [key, val] of knownTypeMap) {
  266. const re = new RegExp(`\\b${key}\\b`, 'g');
  267. const strippedIndex = val.replace(/\/_index$/, '');
  268. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}/'>${key}</a>`);
  269. }
  270. return typeText;
  271. }
  272. /**
  273. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  274. */
  275. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  276. for (const [key, val] of knownTypeMap) {
  277. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  278. description = description.replace(re, `<a href='${docsUrl}/${val}/'>${key}</a>`);
  279. }
  280. return description;
  281. }
  282. }