typescript-docs-renderer.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /* eslint-disable no-console */
  2. import fs from 'fs-extra';
  3. import path from 'path';
  4. import { HeritageClause } from 'typescript';
  5. import { assertNever } from '../../packages/common/src/shared-utils';
  6. import { generateFrontMatter, titleCase } from './docgen-utils';
  7. import {
  8. ClassInfo,
  9. DeclarationInfo,
  10. DocsPage,
  11. EnumInfo,
  12. FunctionInfo,
  13. InterfaceInfo,
  14. MethodParameterInfo,
  15. TypeAliasInfo,
  16. TypeMap,
  17. VariableInfo,
  18. } from './typescript-docgen-types';
  19. const INDENT = ' ';
  20. export class TypescriptDocsRenderer {
  21. render(pages: DocsPage[], docsUrl: string, outputPath: string, typeMap: TypeMap): number {
  22. let generatedCount = 0;
  23. if (!fs.existsSync(outputPath)) {
  24. fs.ensureDirSync(outputPath);
  25. }
  26. // Extract the section base path (e.g., 'typescript-api' from '.../reference/typescript-api')
  27. const referenceIndex = outputPath.indexOf('/reference/');
  28. const sectionBasePath = referenceIndex !== -1
  29. ? outputPath.slice(referenceIndex + '/reference/'.length)
  30. : '';
  31. // Build a map of parent category paths to their direct child categories
  32. const categoryChildren = new Map<string, Set<string>>();
  33. // Also track direct children of the section root (for sections like 'admin-ui-api', 'dashboard')
  34. const sectionRootChildren = new Set<string>();
  35. for (const page of pages) {
  36. // Track the first category as a child of the section root
  37. if (page.category.length > 0) {
  38. sectionRootChildren.add(page.category[0]);
  39. }
  40. // Track nested category relationships
  41. for (let i = 0; i < page.category.length - 1; i++) {
  42. const parentPath = page.category.slice(0, i + 1).join('/');
  43. const childCategory = page.category[i + 1];
  44. if (!categoryChildren.has(parentPath)) {
  45. categoryChildren.set(parentPath, new Set());
  46. }
  47. categoryChildren.get(parentPath)!.add(childCategory);
  48. }
  49. }
  50. for (const page of pages) {
  51. let markdown = '';
  52. markdown += generateFrontMatter(page.title);
  53. const declarationsByWeight = page.declarations.sort((a, b) => a.weight - b.weight);
  54. for (const info of declarationsByWeight) {
  55. switch (info.kind) {
  56. case 'interface':
  57. markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
  58. break;
  59. case 'typeAlias':
  60. markdown += this.renderTypeAlias(info, typeMap, docsUrl);
  61. break;
  62. case 'class':
  63. markdown += this.renderInterfaceOrClass(info, typeMap, docsUrl);
  64. break;
  65. case 'enum':
  66. markdown += this.renderEnum(info, typeMap, docsUrl);
  67. break;
  68. case 'function':
  69. markdown += this.renderFunction(info, typeMap, docsUrl);
  70. break;
  71. case 'variable':
  72. markdown += this.renderVariable(info, typeMap, docsUrl);
  73. break;
  74. default:
  75. assertNever(info);
  76. }
  77. }
  78. const categoryDir = path.join(outputPath, ...page.category);
  79. if (!fs.existsSync(categoryDir)) {
  80. fs.mkdirsSync(categoryDir);
  81. }
  82. const pathParts: string[] = [];
  83. for (const subCategory of page.category) {
  84. pathParts.push(subCategory);
  85. const indexFile = path.join(outputPath, ...pathParts, 'index.mdx');
  86. const exists = fs.existsSync(indexFile);
  87. const existingContent = exists ? fs.readFileSync(indexFile).toString() : '';
  88. const isGenerated = existingContent.includes('generated: true');
  89. const hasCustomContent = existingContent.includes('isDefaultIndex: false');
  90. // Skip files with custom content
  91. if (hasCustomContent) {
  92. continue;
  93. }
  94. const categoryPath = pathParts.join('/');
  95. const children = categoryChildren.get(categoryPath);
  96. // Collect existing LinkCards from the file if it exists
  97. const existingLinkCards = new Set<string>();
  98. if (exists && isGenerated) {
  99. const linkCardRegex = /<LinkCard href="([^"]+)"/g;
  100. let match;
  101. while ((match = linkCardRegex.exec(existingContent)) !== null) {
  102. existingLinkCards.add(match[1]);
  103. }
  104. }
  105. // Build set of new LinkCards
  106. const newLinkCards = new Set<string>();
  107. if (children && children.size > 0) {
  108. for (const child of children) {
  109. const basePath = sectionBasePath ? `${sectionBasePath}/` : '';
  110. const absolutePath = `/reference/${basePath}${categoryPath}/${child}`;
  111. newLinkCards.add(absolutePath);
  112. }
  113. }
  114. // Merge and check if we need to write
  115. const allLinkCards = new Set([...existingLinkCards, ...newLinkCards]);
  116. const hasNewCards = newLinkCards.size > 0 &&
  117. [...newLinkCards].some(card => !existingLinkCards.has(card));
  118. if (!exists || hasNewCards) {
  119. let indexFileContent = generateFrontMatter(subCategory, true);
  120. if (allLinkCards.size > 0) {
  121. indexFileContent += '\n';
  122. const sortedCards = Array.from(allLinkCards).sort();
  123. for (const href of sortedCards) {
  124. // Extract child name from href for title
  125. const childName = href.split('/').pop() || '';
  126. const title = titleCase(childName.replace(/-/g, ' '));
  127. indexFileContent += `<LinkCard href="${href}" title="${title}" />\n`;
  128. }
  129. }
  130. fs.writeFileSync(indexFile, indexFileContent);
  131. if (!exists) {
  132. generatedCount++;
  133. }
  134. }
  135. }
  136. fs.writeFileSync(path.join(categoryDir, page.fileName + '.mdx'), markdown);
  137. generatedCount++;
  138. }
  139. // Generate index file for the section root (e.g., admin-ui-api/index.mdx, dashboard/index.mdx)
  140. if (sectionBasePath && sectionRootChildren.size > 0) {
  141. const sectionIndexFile = path.join(outputPath, 'index.mdx');
  142. const exists = fs.existsSync(sectionIndexFile);
  143. const existingContent = exists ? fs.readFileSync(sectionIndexFile).toString() : '';
  144. const isGenerated = existingContent.includes('generated: true');
  145. const hasCustomContent = existingContent.includes('isDefaultIndex: false');
  146. if (!hasCustomContent) {
  147. // Collect existing LinkCards
  148. const existingLinkCards = new Set<string>();
  149. if (exists && isGenerated) {
  150. const linkCardRegex = /<LinkCard href="([^"]+)"/g;
  151. let match;
  152. while ((match = linkCardRegex.exec(existingContent)) !== null) {
  153. existingLinkCards.add(match[1]);
  154. }
  155. }
  156. // Build new LinkCards
  157. const newLinkCards = new Set<string>();
  158. for (const child of sectionRootChildren) {
  159. const absolutePath = `/reference/${sectionBasePath}/${child}`;
  160. newLinkCards.add(absolutePath);
  161. }
  162. // Merge and check if update needed
  163. const allLinkCards = new Set([...existingLinkCards, ...newLinkCards]);
  164. const hasNewCards = [...newLinkCards].some(card => !existingLinkCards.has(card));
  165. if (!exists || hasNewCards) {
  166. const sectionTitle = titleCase(sectionBasePath.replace(/-/g, ' '));
  167. let indexFileContent = generateFrontMatter(sectionTitle, true);
  168. indexFileContent += '\n';
  169. const sortedCards = Array.from(allLinkCards).sort();
  170. for (const href of sortedCards) {
  171. const childName = href.split('/').pop() || '';
  172. const title = titleCase(childName.replace(/-/g, ' '));
  173. indexFileContent += `<LinkCard href="${href}" title="${title}" />\n`;
  174. }
  175. fs.writeFileSync(sectionIndexFile, indexFileContent);
  176. if (!exists) {
  177. generatedCount++;
  178. }
  179. }
  180. }
  181. }
  182. return generatedCount;
  183. }
  184. /**
  185. * Render the interface to a markdown string.
  186. */
  187. private renderInterfaceOrClass(
  188. info: InterfaceInfo | ClassInfo,
  189. knownTypeMap: TypeMap,
  190. docsUrl: string,
  191. ): string {
  192. const { title, weight, category, description, members } = info;
  193. let output = '';
  194. output += this.renderGenerationInfoShortcode(info);
  195. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  196. output +=
  197. info.kind === 'interface' ? this.renderInterfaceSignature(info) : this.renderClassSignature(info);
  198. if (info.extendsClause) {
  199. output += '* Extends: ';
  200. output += `${this.renderHeritageClause(info.extendsClause, knownTypeMap, docsUrl)}\n`;
  201. }
  202. if (info.kind === 'class' && info.implementsClause) {
  203. output += '* Implements: ';
  204. output += `${this.renderHeritageClause(info.implementsClause, knownTypeMap, docsUrl)}\n`;
  205. }
  206. if (info.members && info.members.length) {
  207. output += '\n<div className="members-wrapper">\n';
  208. output += `${this.renderMembers(info, knownTypeMap, docsUrl)}\n`;
  209. output += '\n\n</div>\n';
  210. }
  211. return output;
  212. }
  213. /**
  214. * Render the type alias to a markdown string.
  215. */
  216. private renderTypeAlias(typeAliasInfo: TypeAliasInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  217. const { title, weight, description, type, fullText } = typeAliasInfo;
  218. let output = '';
  219. output += this.renderGenerationInfoShortcode(typeAliasInfo);
  220. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  221. output += this.renderTypeAliasSignature(typeAliasInfo);
  222. if (typeAliasInfo.members && typeAliasInfo.members.length) {
  223. output += '\n<div className="members-wrapper">\n';
  224. output += `${this.renderMembers(typeAliasInfo, knownTypeMap, docsUrl)}\n`;
  225. output += '\n\n</div>\n';
  226. }
  227. return output;
  228. }
  229. private renderEnum(enumInfo: EnumInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  230. const { title, weight, description, fullText } = enumInfo;
  231. let output = '';
  232. output += this.renderGenerationInfoShortcode(enumInfo);
  233. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  234. output += this.renderEnumSignature(enumInfo);
  235. return output;
  236. }
  237. private renderFunction(functionInfo: FunctionInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  238. const { title, weight, description, fullText, parameters } = functionInfo;
  239. let output = '';
  240. output += this.renderGenerationInfoShortcode(functionInfo);
  241. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  242. output += this.renderFunctionSignature(functionInfo, knownTypeMap);
  243. if (parameters.length) {
  244. output += 'Parameters\n\n';
  245. output += this.renderFunctionParams(parameters, knownTypeMap, docsUrl);
  246. }
  247. return output;
  248. }
  249. private renderVariable(variableInfo: VariableInfo, knownTypeMap: TypeMap, docsUrl: string): string {
  250. const { title, weight, description, fullText } = variableInfo;
  251. let output = '';
  252. output += this.renderGenerationInfoShortcode(variableInfo);
  253. output += `${this.renderDescription(description, knownTypeMap, docsUrl)}\n\n`;
  254. return output;
  255. }
  256. /**
  257. * Generates a markdown code block string for the interface signature.
  258. */
  259. private renderInterfaceSignature(interfaceInfo: InterfaceInfo): string {
  260. const { fullText, members } = interfaceInfo;
  261. let output = '';
  262. output += '```ts title="Signature"\n';
  263. output += `interface ${fullText} `;
  264. if (interfaceInfo.extendsClause) {
  265. output += interfaceInfo.extendsClause.getText() + ' ';
  266. }
  267. output += '{\n';
  268. output += members.map(member => `${INDENT}${member.fullText}`).join('\n');
  269. output += '\n}\n';
  270. output += '```\n';
  271. return output;
  272. }
  273. private renderClassSignature(classInfo: ClassInfo): string {
  274. const { fullText, members } = classInfo;
  275. let output = '';
  276. output += '```ts title="Signature"\n';
  277. output += `class ${fullText} `;
  278. if (classInfo.extendsClause) {
  279. output += classInfo.extendsClause.getText() + ' ';
  280. }
  281. if (classInfo.implementsClause) {
  282. output += classInfo.implementsClause.getText() + ' ';
  283. }
  284. output += '{\n';
  285. const renderModifiers = (modifiers: string[]) => (modifiers.length ? modifiers.join(' ') + ' ' : '');
  286. output += members
  287. .map(member => {
  288. if (member.kind === 'method') {
  289. const args = member.parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  290. if (member.fullText === 'constructor') {
  291. return `${INDENT}constructor(${args})`;
  292. } else {
  293. return `${INDENT}${member.fullText}(${args}) => ${member.type};`;
  294. }
  295. } else {
  296. return `${INDENT}${member.fullText}`;
  297. }
  298. })
  299. .join('\n');
  300. output += '\n}\n';
  301. output += '```\n';
  302. return output;
  303. }
  304. private renderTypeAliasSignature(typeAliasInfo: TypeAliasInfo): string {
  305. const { fullText, members, type } = typeAliasInfo;
  306. let output = '';
  307. output += '```ts title="Signature"\n';
  308. output += `type ${fullText} = `;
  309. if (members) {
  310. output += '{\n';
  311. output += members.map(member => `${INDENT}${member.fullText}`).join('\n');
  312. output += '\n}\n';
  313. } else {
  314. output += type.getText() + '\n';
  315. }
  316. output += '```\n';
  317. return output;
  318. }
  319. private renderEnumSignature(enumInfo: EnumInfo): string {
  320. const { fullText, members } = enumInfo;
  321. let output = '';
  322. output += '```ts title="Signature"\n';
  323. output += `enum ${fullText} `;
  324. if (members) {
  325. output += '{\n';
  326. output += members
  327. .map(member => {
  328. let line = member.description ? `${INDENT}// ${member.description}\n` : '';
  329. line += `${INDENT}${member.fullText}`;
  330. return line;
  331. })
  332. .join('\n');
  333. output += '\n}\n';
  334. }
  335. output += '```\n';
  336. return output;
  337. }
  338. private renderFunctionSignature(functionInfo: FunctionInfo, knownTypeMap: TypeMap): string {
  339. const { fullText, parameters, type } = functionInfo;
  340. const args = parameters.map(p => this.renderParameter(p, p.type)).join(', ');
  341. let output = '';
  342. output += '```ts title="Signature"\n';
  343. output += `function ${fullText}(${args}): ${type ? type.getText() : 'void'}\n`;
  344. output += '```\n';
  345. return output;
  346. }
  347. private renderFunctionParams(
  348. params: MethodParameterInfo[],
  349. knownTypeMap: TypeMap,
  350. docsUrl: string,
  351. ): string {
  352. let output = '';
  353. for (const param of params) {
  354. const type = this.renderType(param.type, knownTypeMap, docsUrl);
  355. output += `### ${param.name}\n\n`;
  356. output += `<MemberInfo kind="parameter" type={\`${type}\`} />\n\n`;
  357. }
  358. return output;
  359. }
  360. private renderMembers(
  361. info: InterfaceInfo | ClassInfo | TypeAliasInfo | EnumInfo,
  362. knownTypeMap: TypeMap,
  363. docsUrl: string,
  364. ): string {
  365. const { members, title } = info;
  366. let output = '';
  367. for (const member of members || []) {
  368. let defaultParam = '';
  369. let sinceParam = '';
  370. let experimentalParam = '';
  371. let type = '';
  372. if (member.kind === 'property') {
  373. type = this.renderType(member.type, knownTypeMap, docsUrl);
  374. defaultParam = member.defaultValue
  375. ? `default={\`${this.renderType(member.defaultValue, knownTypeMap, docsUrl)}\`} `
  376. : '';
  377. } else {
  378. const args = member.parameters
  379. .map(p => this.renderParameter(p, this.renderType(p.type, knownTypeMap, docsUrl)))
  380. .join(', ');
  381. if (member.fullText === 'constructor') {
  382. type = `(${args}) => ${title}`;
  383. } else {
  384. type = `(${args}) => ${this.renderType(member.type, knownTypeMap, docsUrl)}`;
  385. }
  386. }
  387. if (member.since) {
  388. sinceParam = `since="${member.since}" `;
  389. }
  390. if (member.experimental) {
  391. experimentalParam = 'experimental="true"';
  392. }
  393. output += `\n### ${member.name}\n\n`;
  394. output += `<MemberInfo kind="${[member.kind].join(
  395. ' ',
  396. )}" type={\`${type}\`} ${defaultParam} ${sinceParam}${experimentalParam} />\n\n`;
  397. output += this.renderDescription(member.description, knownTypeMap, docsUrl);
  398. }
  399. return output;
  400. }
  401. private renderHeritageClause(clause: HeritageClause, knownTypeMap: TypeMap, docsUrl: string) {
  402. return (
  403. clause.types
  404. .map(t => this.renderHeritageType(t.getText(), knownTypeMap, docsUrl))
  405. .join(', ') + '\n\n'
  406. );
  407. }
  408. private renderParameter(p: MethodParameterInfo, typeString: string): string {
  409. return `${p.name}${p.optional ? '?' : ''}: ${typeString}${
  410. p.initializer ? ` = ${p.initializer}` : ''
  411. }`;
  412. }
  413. private renderGenerationInfoShortcode(info: DeclarationInfo): string {
  414. const sourceFile = info.sourceFile.replace(/^\.\.\//, '');
  415. let sinceData = '';
  416. if (info.since) {
  417. sinceData = ` since="${info.since}"`;
  418. }
  419. let experimental = '';
  420. if (info.experimental) {
  421. experimental = ' experimental="true"';
  422. }
  423. return `<GenerationInfo sourceFile="${sourceFile}" sourceLine="${info.sourceLine}" packageName="${info.packageName}"${sinceData}${experimental} />\n\n`;
  424. }
  425. /**
  426. * This function takes a string representing a type (e.g. "Array<ShippingMethod>") and turns
  427. * and known types (e.g. "ShippingMethod") into hyperlinks.
  428. */
  429. private renderType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  430. let typeText = type
  431. .trim()
  432. // encode HTML entities
  433. .replace(/[\u00A0-\u9999\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  434. // remove newlines
  435. .replace(/\n/g, ' ');
  436. for (const [key, val] of knownTypeMap) {
  437. const re = new RegExp(`(?!<a[^>]*>)\\b${key}\\b(?![^<]*<\/a>)`, 'g');
  438. const strippedIndex = val.replace(/\/_index$/, '');
  439. typeText = typeText.replace(re, `<a href='${docsUrl}/${strippedIndex}'>${key}</a>`);
  440. }
  441. return typeText;
  442. }
  443. /**
  444. * Renders a heritage clause type (extends/implements) with DocsLink and backticks.
  445. */
  446. private renderHeritageType(type: string, knownTypeMap: TypeMap, docsUrl: string): string {
  447. let typeText = type
  448. .trim()
  449. // encode HTML entities
  450. .replace(/[\u00A0-\u9999\&]/gim, i => '&#' + i.charCodeAt(0) + ';')
  451. // remove newlines
  452. .replace(/\n/g, ' ');
  453. for (const [key, val] of knownTypeMap) {
  454. const re = new RegExp(`(?!<DocsLink[^>]*>)\\b${key}\\b(?![^<]*<\\/DocsLink>)`, 'g');
  455. const strippedIndex = val.replace(/\/_index$/, '');
  456. typeText = typeText.replace(re, `<DocsLink href="${docsUrl}/${strippedIndex}">\`${key}\`</DocsLink>`);
  457. }
  458. // Wrap generic type wrappers (like Partial<, Array<) in backticks when they precede <DocsLink
  459. // to prevent MDX from interpreting consecutive < characters as nested JSX
  460. typeText = typeText.replace(/(\w+<)(<DocsLink)/g, '`$1`$2');
  461. // Wrap any trailing generic type closing brackets in backticks to prevent MDX issues
  462. typeText = typeText.replace(/(<\/DocsLink>)(>+)/g, '$1`$2`');
  463. // If no DocsLink was added (type not in knownTypeMap) but the type contains
  464. // angle brackets, wrap the entire type in backticks
  465. if (!typeText.includes('<DocsLink') && typeText.includes('<')) {
  466. typeText = '`' + typeText + '`';
  467. }
  468. return typeText;
  469. }
  470. /**
  471. * Replaces any `{@link Foo}` references in the description with hyperlinks.
  472. */
  473. private renderDescription(description: string, knownTypeMap: TypeMap, docsUrl: string): string {
  474. for (const [key, val] of knownTypeMap) {
  475. const re = new RegExp(`{@link\\s*${key}}`, 'g');
  476. description = description.replace(re, `<DocsLink href="${docsUrl}/${val}">${key}</DocsLink>`);
  477. }
  478. return description;
  479. }
  480. }