generate-typescript-docs.ts 5.0 KB

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