generate-config-docs.ts 18 KB

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