generate-docs.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import fs from 'fs';
  2. import klawSync from 'klaw-sync';
  3. import path from 'path';
  4. import ts from 'typescript';
  5. import { notNullOrUndefined } from '../shared/shared-utils';
  6. // tslint:disable:no-console
  7. interface MethodParameterInfo {
  8. name: string;
  9. type: string;
  10. }
  11. interface MemberInfo {
  12. name: string;
  13. description: string;
  14. type: string;
  15. }
  16. interface PropertyInfo extends MemberInfo {
  17. kind: 'property';
  18. defaultValue: string;
  19. }
  20. interface MethodInfo extends MemberInfo {
  21. kind: 'method';
  22. parameters: MethodParameterInfo[];
  23. }
  24. interface DeclarationInfo {
  25. sourceFile: string;
  26. title: string;
  27. weight: number;
  28. category: string;
  29. description: string;
  30. fileName: string;
  31. }
  32. interface InterfaceInfo extends DeclarationInfo {
  33. kind: 'interface';
  34. members: Array<PropertyInfo | MethodInfo>;
  35. }
  36. interface TypeAliasInfo extends DeclarationInfo {
  37. kind: 'typeAlias';
  38. type: string;
  39. }
  40. type ValidDeclaration = ts.InterfaceDeclaration | ts.TypeAliasDeclaration;
  41. type TypeMap = Map<string, string>;
  42. const docsPath = '/docs/api/';
  43. const outputPath = path.join(__dirname, '../docs/content/docs/api');
  44. /**
  45. * This map is used to cache types and their corresponding Hugo path. It is used to enable
  46. * hyperlinking from a member's "type" to the definition of that type.
  47. */
  48. const globalTypeMap: TypeMap = new Map();
  49. const tsFiles = klawSync(path.join(__dirname, '../server/src/'), {
  50. nodir: true,
  51. filter: item => path.extname(item.path) === '.ts',
  52. traverseAll: true,
  53. }).map(item => item.path);
  54. deleteGeneratedDocs();
  55. generateDocs(tsFiles, outputPath, globalTypeMap);
  56. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  57. if (watchMode) {
  58. console.log(`Watching for changes to source files...`);
  59. tsFiles.forEach(file => {
  60. fs.watchFile(file, { interval: 1000 }, () => {
  61. generateDocs([file], outputPath, globalTypeMap);
  62. });
  63. });
  64. }
  65. /**
  66. * Delete all generated docs found in the outputPath.
  67. */
  68. function deleteGeneratedDocs() {
  69. let deleteCount = 0;
  70. const files = klawSync(outputPath, { nodir: true });
  71. for (const file of files) {
  72. const content = fs.readFileSync(file.path, 'utf-8');
  73. if (isGenerated(content)) {
  74. fs.unlinkSync(file.path);
  75. deleteCount++;
  76. }
  77. }
  78. console.log(`Deleted ${deleteCount} generated docs`);
  79. }
  80. /**
  81. * Returns true if the content matches that of a generated document.
  82. */
  83. function isGenerated(content: string) {
  84. return /generated\: true\n---\n/.test(content);
  85. }
  86. /**
  87. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  88. * into markdown files
  89. * @param filePaths
  90. * @param typeMap
  91. */
  92. function generateDocs(filePaths: string[], hugoApiDocsPath: string, typeMap: TypeMap) {
  93. const timeStart = +new Date();
  94. const sourceFiles = filePaths.map(filePath => {
  95. return ts.createSourceFile(
  96. filePath,
  97. fs.readFileSync(filePath).toString(),
  98. ts.ScriptTarget.ES2015,
  99. true,
  100. );
  101. });
  102. const statements = getStatementsWithSourceFile(sourceFiles);
  103. const declarationInfos = statements
  104. .map(statement => {
  105. const info = parseDeclaration(statement.statement, statement.sourceFile);
  106. if (info) {
  107. typeMap.set(info.title, info.category + '/' + info.fileName);
  108. }
  109. return info;
  110. })
  111. .filter(notNullOrUndefined);
  112. for (const info of declarationInfos) {
  113. let markdown = '';
  114. switch (info.kind) {
  115. case 'interface':
  116. markdown = renderInterface(info, typeMap);
  117. break;
  118. case 'typeAlias':
  119. markdown = renderTypeAlias(info, typeMap);
  120. break;
  121. }
  122. const categoryDir = path.join(hugoApiDocsPath, info.category);
  123. const indexFile = path.join(categoryDir, '_index.md');
  124. if (!fs.existsSync(categoryDir)) {
  125. fs.mkdirSync(categoryDir);
  126. }
  127. if (!fs.existsSync(indexFile)) {
  128. const indexFileContent = generateFrontMatter(info.category, 10, false) + `\n\n# ${info.category}`;
  129. fs.writeFileSync(indexFile, indexFileContent);
  130. }
  131. fs.writeFileSync(path.join(categoryDir, info.fileName + '.md'), markdown);
  132. }
  133. if (declarationInfos.length) {
  134. console.log(`Generated ${declarationInfos.length} docs in ${+new Date() - timeStart}ms`);
  135. }
  136. }
  137. /**
  138. * Maps an array of parsed SourceFiles into statements, including a reference to the original file each statement
  139. * came from.
  140. */
  141. function getStatementsWithSourceFile(sourceFiles: ts.SourceFile[]): Array<{ statement: ts.Statement; sourceFile: string }> {
  142. return sourceFiles.reduce(
  143. (st, sf) => {
  144. const statementsWithSources = sf.statements.map(statement => {
  145. const serverSourceRoot = '/server/src';
  146. const sourceFile = sf.fileName.substring(sf.fileName.indexOf(serverSourceRoot));
  147. return {statement, sourceFile };
  148. });
  149. return [...st, ...statementsWithSources];
  150. },
  151. [] as Array<{ statement: ts.Statement; sourceFile: string }>,
  152. );
  153. }
  154. /**
  155. * Parses an InterfaceDeclaration into a simple object which can be rendered into markdown.
  156. */
  157. function parseDeclaration(statement: ts.Statement, sourceFile: string): InterfaceInfo | TypeAliasInfo | undefined {
  158. if (!isValidDeclaration(statement)) {
  159. return;
  160. }
  161. const category = getDocsCategory(statement);
  162. if (category === undefined) {
  163. return;
  164. }
  165. const title = statement.name.text;
  166. const weight = getDeclarationWeight(statement);
  167. const description = getDeclarationDescription(statement);
  168. const fileName = title
  169. .split(/(?=[A-Z])/)
  170. .join('-')
  171. .toLowerCase();
  172. const info = {
  173. sourceFile,
  174. title,
  175. weight,
  176. category,
  177. description,
  178. fileName,
  179. };
  180. if (ts.isInterfaceDeclaration(statement)) {
  181. return {
  182. ...info,
  183. kind: 'interface',
  184. members: parseMembers(statement.members),
  185. };
  186. } else if (ts.isTypeAliasDeclaration(statement)) {
  187. return {
  188. ...info,
  189. type: statement.type.getFullText().trim(),
  190. kind: 'typeAlias',
  191. };
  192. }
  193. }
  194. /**
  195. * Parses an array of inteface members into a simple object which can be rendered into markdown.
  196. */
  197. function parseMembers(members: ts.NodeArray<ts.TypeElement>): Array<PropertyInfo | MethodInfo> {
  198. const result: Array<PropertyInfo | MethodInfo> = [];
  199. for (const member of members) {
  200. if (ts.isPropertySignature(member) || ts.isMethodSignature(member)) {
  201. const name = member.name.getText();
  202. let description = '';
  203. let type = '';
  204. let defaultValue = '';
  205. let parameters: MethodParameterInfo[] = [];
  206. parseTags(member, {
  207. description: tag => (description += tag.comment || ''),
  208. example: tag => (description += formatExampleCode(tag.comment)),
  209. default: tag => (defaultValue = tag.comment || ''),
  210. });
  211. if (member.type) {
  212. type = member.type.getFullText().trim();
  213. }
  214. if (ts.isMethodSignature(member)) {
  215. parameters = member.parameters.map(p => ({
  216. name: p.name.getText(),
  217. type: p.type ? p.type.getFullText() : '',
  218. }));
  219. result.push({
  220. kind: 'method',
  221. name,
  222. description,
  223. type,
  224. parameters,
  225. });
  226. } else {
  227. result.push({
  228. kind: 'property',
  229. name,
  230. description,
  231. type,
  232. defaultValue,
  233. });
  234. }
  235. }
  236. }
  237. return result;
  238. }
  239. /**
  240. * Render the interface to a markdown string.
  241. */
  242. function renderInterface(interfaceInfo: InterfaceInfo, knownTypeMap: Map<string, string>): string {
  243. const { title, weight, category, description, sourceFile, members } = interfaceInfo;
  244. let output = '';
  245. output += generateFrontMatter(title, weight);
  246. output += `\n\n# ${title}\n\n`;
  247. output += `{{< generation-info source="${sourceFile}">}}\n\n`;
  248. output += `${description}\n\n`;
  249. output += `## Signature\n\n`;
  250. output += renderInterfaceSignature(interfaceInfo);
  251. output += `## Members\n\n`;
  252. for (const member of members) {
  253. let defaultParam = '';
  254. let type = '';
  255. if (member.kind === 'property') {
  256. type = renderType(member.type, knownTypeMap);
  257. defaultParam = member.defaultValue ? `default="${member.defaultValue}" ` : '';
  258. } else {
  259. const args = member.parameters
  260. .map(p => {
  261. return `${p.name}: ${renderType(p.type, knownTypeMap)}`;
  262. })
  263. .join(', ');
  264. type = `(${args}) => ${renderType(member.type, knownTypeMap)}`;
  265. }
  266. output += `### ${member.name}\n\n`;
  267. output += `{{< member-info kind="${member.kind}" type="${type}" ${defaultParam}>}}\n\n`;
  268. output += `${member.description}\n\n`;
  269. }
  270. return output;
  271. }
  272. /**
  273. * Generates a markdown code block string for the interface signature.
  274. */
  275. function renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  276. const { title, members } = interfaceInfo;
  277. let output = '';
  278. output += `\`\`\`ts\n`;
  279. output += `interface ${title} {\n`;
  280. output += members.map(member => {
  281. if (member.kind === 'property') {
  282. return ` ${member.name}: ${member.type};`;
  283. } else {
  284. const args = member.parameters
  285. .map(p => `${p.name}: ${p.type}`)
  286. .join(', ');
  287. return ` ${member.name}: (${args}) => ${member.type}`;
  288. }
  289. }).join(`\n`) ;
  290. output += `\n}\n`;
  291. output += `\`\`\`\n`;
  292. return output;
  293. }
  294. /**
  295. * Render the type alias to a markdown string.
  296. */
  297. function renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: Map<string, string>): string {
  298. const { title, weight, category, description, sourceFile, type } = typeAliasInfo;
  299. let output = '';
  300. output += generateFrontMatter(title, weight);
  301. output += `\n\n# ${title}\n\n`;
  302. output += `{{< generation-info source="${sourceFile}">}}\n\n`;
  303. output += `${description}\n\n`;
  304. output += `## Signature\n\n`;
  305. output += `\`\`\`ts\ntype ${title} = ${type};\n\`\`\``;
  306. return output;
  307. }
  308. /**
  309. * Extracts the "@docsCategory" value from the JSDoc comments if present.
  310. */
  311. function getDocsCategory(statement: ValidDeclaration): string | undefined {
  312. let category: string | undefined;
  313. parseTags(statement, {
  314. docsCategory: tag => (category = tag.comment || ''),
  315. });
  316. return category;
  317. }
  318. /**
  319. * Parses the Node's JSDoc tags and invokes the supplied functions against any matching tag names.
  320. */
  321. function parseTags<T extends ts.Node>(
  322. node: T,
  323. tagMatcher: { [tagName: string]: (tag: ts.JSDocTag) => void },
  324. ): void {
  325. const jsDocTags = ts.getJSDocTags(node);
  326. for (const tag of jsDocTags) {
  327. const tagName = tag.tagName.text;
  328. if (tagMatcher[tagName]) {
  329. tagMatcher[tagName](tag);
  330. }
  331. }
  332. }
  333. /**
  334. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  335. * and known types (e.g. "ShippingMethod") into hyperlinks.
  336. */
  337. function renderType(type: string, knownTypeMap: Map<string, string>): string {
  338. let typeText = type
  339. .trim()
  340. // encode HTML entities
  341. .replace(/[\u00A0-\u9999<>\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  342. // remove newlines
  343. .replace(/\n/g, ' ');
  344. for (const [key, val] of knownTypeMap) {
  345. typeText = typeText.replace(key, `<a href='${docsPath}/${val}/'>${key}</a>`);
  346. }
  347. return typeText;
  348. }
  349. /**
  350. * Generates the Hugo front matter with the title of the document
  351. */
  352. function generateFrontMatter(title: string, weight: number, showToc: boolean = true): string {
  353. return `---
  354. title: "${title}"
  355. weight: ${weight}
  356. date: ${new Date().toISOString()}
  357. showtoc: ${showToc}
  358. generated: true
  359. ---
  360. <!-- This file was generated from the Vendure TypeScript source. Do not modify. Instead, re-run "generate-docs" -->
  361. `;
  362. }
  363. /**
  364. * Reads the @docsWeight JSDoc tag from the interface.
  365. */
  366. function getDeclarationWeight(statement: ValidDeclaration): number {
  367. let weight = 10;
  368. parseTags(statement, {
  369. docsWeight: tag => (weight = Number.parseInt(tag.comment || '10', 10)),
  370. });
  371. return weight;
  372. }
  373. /**
  374. * Reads the @description JSDoc tag from the interface.
  375. */
  376. function getDeclarationDescription(statement: ValidDeclaration): string {
  377. let description = '';
  378. parseTags(statement, {
  379. description: tag => (description += tag.comment),
  380. });
  381. return description;
  382. }
  383. /**
  384. * Cleans up a JSDoc "@example" block by removing leading whitespace and asterisk (TypeScript has an open issue
  385. * wherein the asterisks are not stripped as they should be, see https://github.com/Microsoft/TypeScript/issues/23517)
  386. */
  387. function formatExampleCode(example: string = ''): string {
  388. return '\n\n' + example.replace(/\n\s+\*\s/g, '');
  389. }
  390. /**
  391. * Type guard for the types of statement which can ge processed by the doc generator.
  392. */
  393. function isValidDeclaration(statement: ts.Statement): statement is ValidDeclaration {
  394. return ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement);
  395. }