dependency-graph.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. #!/usr/bin/env node
  2. import fs from "node:fs";
  3. import path from "node:path";
  4. import process from "node:process";
  5. import ts from "typescript";
  6. const ROOT = process.cwd();
  7. const DEFAULT_OUTPUT = "dependency-graph.mmd";
  8. const CODE_EXTENSIONS = [
  9. ".ts",
  10. ".tsx",
  11. ".mts",
  12. ".cts",
  13. ".js",
  14. ".jsx",
  15. ".mjs",
  16. ".cjs",
  17. ".d.ts",
  18. ".d.mts",
  19. ".d.cts",
  20. ];
  21. const IGNORE_DIRS = new Set(["node_modules", "dist", "out", "coverage", "docs", "build"]);
  22. function parseArgs(argv) {
  23. const options = {
  24. paths: [],
  25. output: DEFAULT_OUTPUT,
  26. format: "mermaid",
  27. direction: "LR",
  28. includeIsolated: false,
  29. };
  30. for (let index = 0; index < argv.length; index += 1) {
  31. const arg = argv[index];
  32. // pnpm run 在透传参数时会保留一个裸 --,这里需要显式跳过,避免把它误当成待分析路径。
  33. if (arg === "--") {
  34. continue;
  35. }
  36. if (arg === "-o" || arg === "--output") {
  37. options.output = argv[index + 1] ?? DEFAULT_OUTPUT;
  38. index += 1;
  39. continue;
  40. }
  41. if (arg === "--format") {
  42. options.format = argv[index + 1] ?? "mermaid";
  43. index += 1;
  44. continue;
  45. }
  46. if (arg === "--direction") {
  47. options.direction = argv[index + 1] ?? "LR";
  48. index += 1;
  49. continue;
  50. }
  51. if (arg === "--include-isolated") {
  52. options.includeIsolated = true;
  53. continue;
  54. }
  55. if (arg === "-h" || arg === "--help") {
  56. printHelp();
  57. process.exit(0);
  58. }
  59. options.paths.push(arg);
  60. }
  61. if (!["mermaid", "dot", "json"].includes(options.format)) {
  62. throw new Error(`不支持的输出格式: ${options.format}`);
  63. }
  64. if (!["LR", "RL", "TB", "TD", "BT"].includes(options.direction)) {
  65. throw new Error(`不支持的 Mermaid 方向: ${options.direction}`);
  66. }
  67. return options;
  68. }
  69. function printHelp() {
  70. console.log(`根据 packages 里的源码 import/export 关系生成文件级依赖图。
  71. 用法:
  72. pnpm dep:graph
  73. pnpm dep:graph -- packages/ui/src
  74. pnpm dep:graph -- --format json -o -
  75. 选项:
  76. -o, --output <path> 输出文件路径,传 - 表示输出到 stdout
  77. --format <mermaid|dot|json> 输出格式,默认 mermaid
  78. --direction <LR|RL|TB|TD|BT> Mermaid 图方向,默认 LR
  79. --include-isolated 把没有任何入边或出边的文件也输出出来
  80. -h, --help 查看帮助
  81. `);
  82. }
  83. function isCodeFile(filePath) {
  84. return CODE_EXTENSIONS.some((extension) => filePath.endsWith(extension));
  85. }
  86. function shouldIgnorePath(filePath) {
  87. const relativePath = path.relative(ROOT, filePath);
  88. if (relativePath.startsWith("..")) {
  89. return true;
  90. }
  91. const segments = relativePath.split(path.sep);
  92. return segments.some((segment) => IGNORE_DIRS.has(segment));
  93. }
  94. function walkCodeFiles(entryPath, bucket) {
  95. const stats = fs.statSync(entryPath);
  96. if (stats.isDirectory()) {
  97. for (const name of fs.readdirSync(entryPath)) {
  98. const childPath = path.join(entryPath, name);
  99. if (!shouldIgnorePath(childPath)) {
  100. walkCodeFiles(childPath, bucket);
  101. }
  102. }
  103. return;
  104. }
  105. if (!isCodeFile(entryPath) || shouldIgnorePath(entryPath)) {
  106. return;
  107. }
  108. bucket.push(path.resolve(entryPath));
  109. }
  110. function readJson(jsonPath) {
  111. return JSON.parse(fs.readFileSync(jsonPath, "utf8"));
  112. }
  113. function listWorkspacePackages() {
  114. const packagesDir = path.join(ROOT, "packages");
  115. const packages = [];
  116. for (const name of fs.readdirSync(packagesDir)) {
  117. const packageRoot = path.join(packagesDir, name);
  118. const packageJsonPath = path.join(packageRoot, "package.json");
  119. if (!fs.existsSync(packageJsonPath)) {
  120. continue;
  121. }
  122. const packageJson = readJson(packageJsonPath);
  123. packages.push({
  124. name: packageJson.name,
  125. root: packageRoot,
  126. srcRoot: path.join(packageRoot, "src"),
  127. exports: packageJson.exports ?? {},
  128. });
  129. }
  130. return packages;
  131. }
  132. function getDefaultRoots(workspacePackages) {
  133. return workspacePackages.map((pkg) => pkg.srcRoot).filter((srcRoot) => fs.existsSync(srcRoot));
  134. }
  135. function toPosix(relativePath) {
  136. return relativePath.split(path.sep).join("/");
  137. }
  138. function ensureInsideRoot(targetPath) {
  139. const resolvedPath = path.resolve(targetPath);
  140. if (path.relative(ROOT, resolvedPath).startsWith("..")) {
  141. return null;
  142. }
  143. return resolvedPath;
  144. }
  145. function fileCandidates(basePath) {
  146. const normalizedBase = basePath.replace(/\\/g, "/");
  147. const ext = CODE_EXTENSIONS.find((candidate) => normalizedBase.endsWith(candidate));
  148. if (ext) {
  149. const stem = normalizedBase.slice(0, -ext.length);
  150. if ([".js", ".jsx", ".mjs", ".cjs"].includes(ext)) {
  151. return [
  152. normalizedBase,
  153. `${stem}.ts`,
  154. `${stem}.tsx`,
  155. `${stem}.mts`,
  156. `${stem}.cts`,
  157. `${stem}.d.ts`,
  158. ];
  159. }
  160. return [normalizedBase];
  161. }
  162. return [
  163. `${normalizedBase}.ts`,
  164. `${normalizedBase}.tsx`,
  165. `${normalizedBase}.mts`,
  166. `${normalizedBase}.cts`,
  167. `${normalizedBase}.js`,
  168. `${normalizedBase}.jsx`,
  169. `${normalizedBase}.mjs`,
  170. `${normalizedBase}.cjs`,
  171. `${normalizedBase}.d.ts`,
  172. `${normalizedBase}/index.ts`,
  173. `${normalizedBase}/index.tsx`,
  174. `${normalizedBase}/index.mts`,
  175. `${normalizedBase}/index.cts`,
  176. `${normalizedBase}/index.js`,
  177. `${normalizedBase}/index.jsx`,
  178. `${normalizedBase}/index.mjs`,
  179. `${normalizedBase}/index.cjs`,
  180. `${normalizedBase}/index.d.ts`,
  181. ];
  182. }
  183. function findExistingFile(basePath, knownFiles) {
  184. for (const candidate of fileCandidates(basePath)) {
  185. const normalizedCandidate = path.normalize(candidate);
  186. if (knownFiles.has(normalizedCandidate)) {
  187. return normalizedCandidate;
  188. }
  189. }
  190. return null;
  191. }
  192. function findOwningPackage(filePath, workspacePackages) {
  193. return (
  194. workspacePackages.find(
  195. (pkg) => filePath === pkg.root || filePath.startsWith(`${pkg.root}${path.sep}`),
  196. ) ?? null
  197. );
  198. }
  199. function extractStringExportTarget(value) {
  200. if (typeof value === "string") {
  201. return value;
  202. }
  203. if (!value || typeof value !== "object") {
  204. return null;
  205. }
  206. for (const nestedValue of Object.values(value)) {
  207. const target = extractStringExportTarget(nestedValue);
  208. if (target) {
  209. return target;
  210. }
  211. }
  212. return null;
  213. }
  214. function resolveWorkspaceSpecifier(specifier, sourceFile, workspacePackages, knownFiles) {
  215. if (specifier.startsWith("node:")) {
  216. return null;
  217. }
  218. const sourcePackage = findOwningPackage(sourceFile, workspacePackages);
  219. if (!sourcePackage) {
  220. return null;
  221. }
  222. if (specifier.startsWith("./") || specifier.startsWith("../")) {
  223. return findExistingFile(path.resolve(path.dirname(sourceFile), specifier), knownFiles);
  224. }
  225. if (specifier.startsWith("@/")) {
  226. return findExistingFile(path.join(sourcePackage.srcRoot, specifier.slice(2)), knownFiles);
  227. }
  228. if (!specifier.startsWith("@zcode/")) {
  229. return null;
  230. }
  231. const segments = specifier.split("/");
  232. const packageName = segments.slice(0, 2).join("/");
  233. const subPath = segments.slice(2).join("/");
  234. const targetPackage = workspacePackages.find((pkg) => pkg.name === packageName);
  235. if (!targetPackage) {
  236. return null;
  237. }
  238. if (subPath) {
  239. const exportKey = `./${subPath}`;
  240. const exportedTarget = extractStringExportTarget(targetPackage.exports?.[exportKey]);
  241. if (exportedTarget) {
  242. const resolvedExport = ensureInsideRoot(path.join(targetPackage.root, exportedTarget));
  243. if (resolvedExport) {
  244. const existingExport = findExistingFile(resolvedExport, knownFiles);
  245. if (existingExport) {
  246. return existingExport;
  247. }
  248. }
  249. }
  250. return findExistingFile(path.join(targetPackage.srcRoot, subPath), knownFiles);
  251. }
  252. const rootExport = extractStringExportTarget(targetPackage.exports?.["."]);
  253. if (rootExport) {
  254. const resolvedExport = ensureInsideRoot(path.join(targetPackage.root, rootExport));
  255. if (resolvedExport) {
  256. const existingExport = findExistingFile(resolvedExport, knownFiles);
  257. if (existingExport) {
  258. return existingExport;
  259. }
  260. }
  261. }
  262. return findExistingFile(path.join(targetPackage.srcRoot, "index"), knownFiles);
  263. }
  264. function collectSpecifiers(filePath) {
  265. const text = fs.readFileSync(filePath, "utf8");
  266. const info = ts.preProcessFile(text, true, true);
  267. return Array.from(new Set(info.importedFiles.map((item) => item.fileName).filter(Boolean)));
  268. }
  269. function formatMermaid(nodes, edges, direction) {
  270. const ids = new Map(nodes.map((node, index) => [node, `N${index}`]));
  271. const lines = [`flowchart ${direction}`];
  272. for (const node of nodes) {
  273. lines.push(` ${ids.get(node)}["${node.replaceAll('"', '\\"')}"]`);
  274. }
  275. for (const [from, to] of edges) {
  276. lines.push(` ${ids.get(from)} --> ${ids.get(to)}`);
  277. }
  278. return `${lines.join("\n")}\n`;
  279. }
  280. function formatDot(nodes, edges) {
  281. const lines = ["digraph dependencies {", ' rankdir="LR";', ' node [shape="box"];'];
  282. for (const node of nodes) {
  283. lines.push(` "${node.replaceAll('"', '\\"')}";`);
  284. }
  285. for (const [from, to] of edges) {
  286. lines.push(` "${from.replaceAll('"', '\\"')}" -> "${to.replaceAll('"', '\\"')}";`);
  287. }
  288. lines.push("}");
  289. return `${lines.join("\n")}\n`;
  290. }
  291. function formatJson(nodes, edges) {
  292. return `${JSON.stringify(
  293. {
  294. nodes,
  295. edges: edges.map(([from, to]) => ({ from, to })),
  296. },
  297. null,
  298. 2,
  299. )}\n`;
  300. }
  301. function writeOutput(outputPath, content) {
  302. if (outputPath === "-") {
  303. process.stdout.write(content);
  304. return;
  305. }
  306. const absoluteOutput = path.resolve(ROOT, outputPath);
  307. fs.mkdirSync(path.dirname(absoluteOutput), { recursive: true });
  308. fs.writeFileSync(absoluteOutput, content, "utf8");
  309. }
  310. function main() {
  311. const options = parseArgs(process.argv.slice(2));
  312. const workspacePackages = listWorkspacePackages();
  313. const defaultRoots = getDefaultRoots(workspacePackages);
  314. const roots =
  315. options.paths.length > 0
  316. ? options.paths.map((entry) => path.resolve(ROOT, entry))
  317. : defaultRoots;
  318. for (const rootPath of roots) {
  319. if (!fs.existsSync(rootPath)) {
  320. throw new Error(`路径不存在: ${path.relative(ROOT, rootPath) || rootPath}`);
  321. }
  322. }
  323. const universeFiles = [];
  324. for (const rootPath of Array.from(new Set([...defaultRoots, ...roots]))) {
  325. if (!fs.existsSync(rootPath)) {
  326. continue;
  327. }
  328. walkCodeFiles(rootPath, universeFiles);
  329. }
  330. const discoveredFiles = [];
  331. for (const rootPath of roots) {
  332. walkCodeFiles(rootPath, discoveredFiles);
  333. }
  334. const uniqueFiles = Array.from(new Set(discoveredFiles)).sort();
  335. const knownFiles = new Set(Array.from(new Set(universeFiles)).sort());
  336. const edges = new Set();
  337. const nodes = new Set();
  338. for (const filePath of uniqueFiles) {
  339. const sourceLabel = toPosix(path.relative(ROOT, filePath));
  340. for (const specifier of collectSpecifiers(filePath)) {
  341. const resolvedFile = resolveWorkspaceSpecifier(
  342. specifier,
  343. filePath,
  344. workspacePackages,
  345. knownFiles,
  346. );
  347. if (!resolvedFile) {
  348. continue;
  349. }
  350. const targetLabel = toPosix(path.relative(ROOT, resolvedFile));
  351. nodes.add(sourceLabel);
  352. nodes.add(targetLabel);
  353. if (sourceLabel !== targetLabel) {
  354. edges.add(`${sourceLabel}\u0000${targetLabel}`);
  355. }
  356. }
  357. }
  358. if (options.includeIsolated) {
  359. for (const filePath of uniqueFiles) {
  360. nodes.add(toPosix(path.relative(ROOT, filePath)));
  361. }
  362. }
  363. const orderedNodes = Array.from(nodes).sort();
  364. const orderedEdges = Array.from(edges)
  365. .map((entry) => entry.split("\u0000"))
  366. .sort((left, right) => left[0].localeCompare(right[0]) || left[1].localeCompare(right[1]));
  367. const content =
  368. options.format === "json"
  369. ? formatJson(orderedNodes, orderedEdges)
  370. : options.format === "dot"
  371. ? formatDot(orderedNodes, orderedEdges)
  372. : formatMermaid(orderedNodes, orderedEdges, options.direction);
  373. writeOutput(options.output, content);
  374. const destination = options.output === "-" ? "stdout" : options.output;
  375. console.error(
  376. `已生成依赖图: ${destination} (nodes=${orderedNodes.length}, edges=${orderedEdges.length})`,
  377. );
  378. }
  379. try {
  380. main();
  381. } catch (error) {
  382. console.error(error instanceof Error ? error.message : String(error));
  383. process.exit(1);
  384. }