2
0

patch.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // @ts-ignore
  2. import path from 'path';
  3. // @ts-ignore
  4. import fs from 'fs/promises'; // 使用 fs/promises 简化异步操作
  5. async function patchLinks(outputDir: string) {
  6. /**
  7. * 修复 Markdown 文件中的链接。
  8. * 1. [foo](bar) -> [foo](./bar)
  9. * 2. [foo](./bar) -> [foo](./bar) (保持不变)
  10. */
  11. const normalizeLinksInFile = async (filePath: string) => {
  12. try {
  13. const content = await fs.readFile(filePath, 'utf-8');
  14. const newContent = content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, p1, p2) => {
  15. // 如果链接以 '/' 或 './' 开头,则保持不变
  16. if (['/', '.'].includes(p2[0])) {
  17. return `[${p1}](${p2})`;
  18. }
  19. // 否则添加 './'
  20. return `[${p1}](./${p2})`;
  21. });
  22. if (newContent !== content) {
  23. await fs.writeFile(filePath, newContent);
  24. // console.log(`Updated links in file: ${filePath}`);
  25. }
  26. } catch (error) {
  27. console.error(`Error processing file ${filePath}:`, error);
  28. }
  29. };
  30. const traverse = async (dir: string) => {
  31. try {
  32. const entries = await fs.readdir(dir, { withFileTypes: true });
  33. await Promise.all(
  34. entries.map(async (entry) => {
  35. const fullPath = path.join(dir, entry.name);
  36. if (entry.isDirectory()) {
  37. await traverse(fullPath);
  38. } else if (entry.isFile() && /\.mdx?$/.test(entry.name)) {
  39. await normalizeLinksInFile(fullPath);
  40. }
  41. })
  42. );
  43. } catch (error) {
  44. console.error(`Error traversing directory ${dir}:`, error);
  45. }
  46. };
  47. await traverse(outputDir);
  48. }
  49. export async function patchGeneratedApiDocs(absoluteApiDir: string) {
  50. console.log(`Patching links in API docs at: ${absoluteApiDir}`);
  51. await patchLinks(absoluteApiDir);
  52. }