generate-typescript-docs.ts 5.2 KB

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