patch.ts 1.9 KB

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