typescript-docs-renderer.ts 15 KB

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