generate-typescript-docs.ts 4.5 KB

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