generate-typescript-docs.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. /* tslint:disable:no-console */
  2. import fs from 'fs-extra';
  3. import klawSync from 'klaw-sync';
  4. import path, { extname } from 'path';
  5. import { deleteGeneratedDocs } from './docgen-utils';
  6. import { TypeMap } from './typescript-docgen-types';
  7. import { TypescriptDocsParser } from './typescript-docs-parser';
  8. import { TypescriptDocsRenderer } from './typescript-docs-renderer';
  9. interface DocsSectionConfig {
  10. sourceDirs: string[];
  11. exclude?: RegExp[];
  12. outputPath: string;
  13. }
  14. const sections: DocsSectionConfig[] = [
  15. {
  16. sourceDirs: [
  17. 'packages/core/src/',
  18. 'packages/common/src/',
  19. 'packages/admin-ui-plugin/src/',
  20. 'packages/asset-server-plugin/src/',
  21. 'packages/email-plugin/src/',
  22. 'packages/elasticsearch-plugin/src/',
  23. 'packages/job-queue-plugin/src/',
  24. 'packages/testing/src/',
  25. ],
  26. exclude: [/generated-shop-types/],
  27. outputPath: 'typescript-api',
  28. },
  29. {
  30. sourceDirs: ['packages/admin-ui/src/lib/', 'packages/ui-devkit/src/'],
  31. exclude: [/generated-types/],
  32. outputPath: 'admin-ui-api',
  33. },
  34. ];
  35. generateTypescriptDocs(sections);
  36. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  37. if (watchMode) {
  38. console.log(`Watching for changes to source files...`);
  39. sections.forEach(section => {
  40. section.sourceDirs.forEach(dir => {
  41. fs.watch(dir, { recursive: true }, (eventType, file) => {
  42. if (extname(file) === '.ts') {
  43. console.log(`Changes detected in ${dir}`);
  44. generateTypescriptDocs([section], true);
  45. }
  46. });
  47. });
  48. });
  49. }
  50. /**
  51. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  52. * into markdown files
  53. */
  54. function generateTypescriptDocs(config: DocsSectionConfig[], isWatchMode: boolean = false) {
  55. const timeStart = +new Date();
  56. // This map is used to cache types and their corresponding Hugo path. It is used to enable
  57. // hyperlinking from a member's "type" to the definition of that type.
  58. const globalTypeMap: TypeMap = new Map();
  59. if (!isWatchMode) {
  60. for (const { outputPath, sourceDirs } of config) {
  61. deleteGeneratedDocs(absOutputPath(outputPath));
  62. }
  63. }
  64. for (const { outputPath, sourceDirs, exclude } of config) {
  65. const sourceFilePaths = getSourceFilePaths(sourceDirs, exclude);
  66. const docsPages = new TypescriptDocsParser().parse(sourceFilePaths);
  67. for (const page of docsPages) {
  68. const { category, fileName, declarations } = page;
  69. for (const declaration of declarations) {
  70. const pathToTypeDoc = `${outputPath}/${category ? category + '/' : ''}${
  71. fileName === '_index' ? '' : fileName
  72. }#${toHash(declaration.title)}`;
  73. globalTypeMap.set(declaration.title, pathToTypeDoc);
  74. }
  75. }
  76. const docsUrl = `/docs`;
  77. const generatedCount = new TypescriptDocsRenderer().render(
  78. docsPages,
  79. docsUrl,
  80. absOutputPath(outputPath),
  81. globalTypeMap,
  82. );
  83. if (generatedCount) {
  84. console.log(
  85. `Generated ${generatedCount} typescript api docs for "${outputPath}" in ${
  86. +new Date() - timeStart
  87. }ms`,
  88. );
  89. }
  90. }
  91. }
  92. function toHash(title: string): string {
  93. return title.replace(/\s/g, '').toLowerCase();
  94. }
  95. function absOutputPath(outputPath: string): string {
  96. return path.join(__dirname, '../../docs/content/', outputPath);
  97. }
  98. function getSourceFilePaths(sourceDirs: string[], excludePatterns: RegExp[] = []): string[] {
  99. return sourceDirs
  100. .map(scanPath =>
  101. klawSync(path.join(__dirname, '../../', scanPath), {
  102. nodir: true,
  103. filter: item => {
  104. if (path.extname(item.path) === '.ts') {
  105. for (const pattern of excludePatterns) {
  106. if (pattern.test(item.path)) {
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. return false;
  113. },
  114. traverseAll: true,
  115. }),
  116. )
  117. .reduce((allFiles, files) => [...allFiles, ...files], [])
  118. .map(item => item.path);
  119. }