generate-typescript-docs.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* tslint:disable:no-console */
  2. import fs from 'fs';
  3. import klawSync from 'klaw-sync';
  4. import path from 'path';
  5. import ts from 'typescript';
  6. import { deleteGeneratedDocs } from './docgen-utils';
  7. import { TypeMap } from './typescript-docgen-types';
  8. import { TypescriptDocsParser } from './typescript-docs-parser';
  9. import { TypescriptDocsRenderer } from './typescript-docs-renderer';
  10. // The absolute URL to the generated docs section
  11. const DOCS_URL = '/docs/configuration/';
  12. // The directory in which the markdown files will be saved
  13. const OUTPUT_PATH = path.join(__dirname, '../../docs/content/docs/configuration');
  14. // The directories to scan for TypeScript source files
  15. const TS_SOURCE_DIRS = ['packages/core/src/', 'packages/common/src/'];
  16. const tsFiles = TS_SOURCE_DIRS
  17. .map(scanPath =>
  18. klawSync(path.join(__dirname, '../../', scanPath), {
  19. nodir: true,
  20. filter: item => path.extname(item.path) === '.ts',
  21. traverseAll: true,
  22. }),
  23. )
  24. .reduce((allFiles, files) => [...allFiles, ...files], [])
  25. .map(item => item.path);
  26. deleteGeneratedDocs(OUTPUT_PATH);
  27. generateTypescriptDocs(tsFiles, OUTPUT_PATH, DOCS_URL);
  28. const watchMode = !!process.argv.find(arg => arg === '--watch' || arg === '-w');
  29. if (watchMode) {
  30. console.log(`Watching for changes to source files...`);
  31. tsFiles.forEach(file => {
  32. fs.watchFile(file, { interval: 1000 }, () => {
  33. generateTypescriptDocs([file], OUTPUT_PATH, DOCS_URL);
  34. });
  35. });
  36. }
  37. /**
  38. * Uses the TypeScript compiler API to parse the given files and extract out the documentation
  39. * into markdown files
  40. */
  41. function generateTypescriptDocs(filePaths: string[], hugoOutputPath: string, docsUrl: string) {
  42. const timeStart = +new Date();
  43. // This map is used to cache types and their corresponding Hugo path. It is used to enable
  44. // hyperlinking from a member's "type" to the definition of that type.
  45. const globalTypeMap: TypeMap = new Map();
  46. const parsedDeclarations = new TypescriptDocsParser().parse(filePaths);
  47. for (const info of parsedDeclarations) {
  48. globalTypeMap.set(info.title, info.category + '/' + info.fileName);
  49. }
  50. const generatedCount = new TypescriptDocsRenderer().render(parsedDeclarations, docsUrl, OUTPUT_PATH, globalTypeMap);
  51. if (generatedCount) {
  52. console.log(`Generated ${generatedCount} typescript api docs in ${+new Date() - timeStart}ms`);
  53. }
  54. }