generate-docs.ts 17 KB

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