index.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { gitFileNames } from "./git-file-names.mjs";
  2. import { promises as fs } from "node:fs";
  3. import path from "node:path";
  4. import { createHash } from "node:crypto";
  5. import {
  6. countPublicMethods,
  7. discoverFiles,
  8. importsOf,
  9. isException,
  10. layerForFile,
  11. loadPolicy,
  12. manifestRequires,
  13. moduleForFile,
  14. posix,
  15. publicEntrypointMatches,
  16. resolveImport,
  17. } from "./policy.mjs";
  18. function fingerprint(rule, file, detail = "") {
  19. return createHash("sha256").update(`${rule}\0${file}\0${detail}`).digest("hex").slice(0, 16);
  20. }
  21. function violation({ rule, file, detail, message, module, global = false }) {
  22. return {
  23. rule,
  24. file: posix(file),
  25. module: module?.id ?? null,
  26. detail,
  27. message,
  28. fingerprint: fingerprint(rule, posix(file), detail),
  29. global,
  30. };
  31. }
  32. function cycleViolations(edges, policy, modulesByFile) {
  33. const state = new Map();
  34. const stack = [];
  35. const cycles = [];
  36. function visit(node) {
  37. state.set(node, 1);
  38. stack.push(node);
  39. for (const next of edges.get(node) ?? []) {
  40. if (!modulesByFile.get(next)?.managed && policy.global.managedOnly) continue;
  41. if (state.get(next) === 1) {
  42. const index = stack.indexOf(next);
  43. cycles.push(stack.slice(index).concat(next));
  44. } else if (!state.get(next)) visit(next);
  45. }
  46. stack.pop();
  47. state.set(node, 2);
  48. }
  49. for (const node of edges.keys()) if (!state.get(node)) visit(node);
  50. const unique = new Map();
  51. for (const cycle of cycles) {
  52. const detail = [...new Set(cycle)].sort().join(" -> ");
  53. const file = cycle[0];
  54. unique.set(
  55. detail,
  56. violation({
  57. rule: "cycle",
  58. file,
  59. detail,
  60. module: modulesByFile.get(file),
  61. message: `检测到循环依赖:${cycle.map((item) => posix(item)).join(" -> ")}`,
  62. global: true,
  63. }),
  64. );
  65. }
  66. return [...unique.values()];
  67. }
  68. async function readBaseline(cwd) {
  69. try {
  70. return JSON.parse(await fs.readFile(path.join(cwd, ".architecture-baseline.json"), "utf8"));
  71. } catch {
  72. return { version: 1, violations: [] };
  73. }
  74. }
  75. export async function checkArchitecture({ cwd = process.cwd(), changedFiles = null } = {}) {
  76. const policy = await loadPolicy(cwd);
  77. const files = await discoverFiles(policy);
  78. const knownFiles = new Set(files);
  79. const modulesByFile = new Map(files.map((file) => [file, moduleForFile(file, policy)]));
  80. const edges = new Map(files.map((file) => [file, []]));
  81. const violations = [];
  82. const manifestRequiresByModule = new Map();
  83. const today = new Date().toISOString().slice(0, 10);
  84. for (const exception of policy.exceptions) {
  85. if (exception.expires && exception.expires < today) {
  86. violations.push(
  87. violation({
  88. rule: "expired-exception",
  89. file: path.join(cwd, "architecture-policy.yaml"),
  90. detail: exception.id ?? exception.rule,
  91. message: `例外 ${exception.id ?? exception.rule} 已于 ${exception.expires} 过期`,
  92. global: true,
  93. }),
  94. );
  95. }
  96. }
  97. for (const module of policy.modules.filter((item) => item.managed)) {
  98. const moduleFiles = files.filter((file) => modulesByFile.get(file)?.id === module.id);
  99. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  100. if (manifest)
  101. manifestRequiresByModule.set(
  102. module.id,
  103. manifestRequires(await fs.readFile(manifest, "utf8")) ?? module.requires,
  104. );
  105. const required = [
  106. "module.ts",
  107. "contract.ts",
  108. "contract.example.ts",
  109. "contract.test.ts",
  110. "CONTRACT.md",
  111. ];
  112. for (const artifact of required) {
  113. if (!moduleFiles.some((file) => path.basename(file) === artifact)) {
  114. const file = module.roots[0];
  115. violations.push(
  116. violation({
  117. rule: "missing-module-artifact",
  118. file,
  119. detail: artifact,
  120. module,
  121. message: `模块 ${module.id} 缺少 ${artifact}`,
  122. }),
  123. );
  124. }
  125. }
  126. }
  127. for (const file of files) {
  128. // CONTRACT.md 只参与产物存在性检查,文档里的示例不能当成源码依赖或源码行数。
  129. if (path.extname(file) === ".md") continue;
  130. const module = modulesByFile.get(file);
  131. if (!module || (policy.global.managedOnly && !module.managed)) continue;
  132. const source = await fs.readFile(file, "utf8");
  133. const lines = source.split(/\r?\n/).length;
  134. if (lines > policy.global.maxFileLines && !isException(policy, "max-file-lines", file, cwd)) {
  135. violations.push(
  136. violation({
  137. rule: "max-file-lines",
  138. file,
  139. detail: String(lines),
  140. module,
  141. message: `文件 ${lines} 行,超过上限 ${policy.global.maxFileLines} 行`,
  142. }),
  143. );
  144. }
  145. if (path.basename(file).startsWith("contract.") && lines > policy.global.maxContractLines) {
  146. violations.push(
  147. violation({
  148. rule: "max-contract-lines",
  149. file,
  150. detail: String(lines),
  151. module,
  152. message: `契约 ${lines} 行,超过上限 ${policy.global.maxContractLines} 行`,
  153. }),
  154. );
  155. }
  156. const disableCount = source
  157. .split(/\r?\n/)
  158. .filter((line) => /(?:oxlint|eslint)-disable/.test(line)).length;
  159. if (disableCount > 0 && !isException(policy, "disable-count", file, cwd)) {
  160. violations.push(
  161. violation({
  162. rule: "disable-count",
  163. file,
  164. detail: String(disableCount),
  165. module,
  166. message: `文件包含 ${disableCount} 条 lint disable`,
  167. }),
  168. );
  169. }
  170. if (
  171. path.basename(file) === "contract.ts" &&
  172. countPublicMethods(source) > policy.global.maxPublicMethods
  173. ) {
  174. violations.push(
  175. violation({
  176. rule: "max-public-methods",
  177. file,
  178. detail: String(countPublicMethods(source)),
  179. module,
  180. message: `契约公开方法超过上限 ${policy.global.maxPublicMethods}`,
  181. }),
  182. );
  183. }
  184. const importerLayer = layerForFile(file, module);
  185. const layerOrder = module.layerOrder ?? [];
  186. for (const specifier of importsOf(file, source)) {
  187. if (
  188. importerLayer === "domain" &&
  189. /^(node:|fs$|path$|http$|https$|net$|child_process$|timers$)/.test(specifier)
  190. ) {
  191. violations.push(
  192. violation({
  193. rule: "domain-io",
  194. file,
  195. detail: specifier,
  196. module,
  197. message: "domain 层不能依赖 IO、进程、网络或定时器",
  198. }),
  199. );
  200. }
  201. const target = resolveImport(file, specifier, knownFiles);
  202. if (!target) continue;
  203. edges.get(file).push(target);
  204. const targetModule = modulesByFile.get(target);
  205. if (targetModule?.id === module.id) {
  206. const targetLayer = layerForFile(target, module);
  207. if (
  208. importerLayer &&
  209. targetLayer &&
  210. layerOrder.includes(importerLayer) &&
  211. layerOrder.includes(targetLayer) &&
  212. layerOrder.indexOf(importerLayer) < layerOrder.indexOf(targetLayer)
  213. ) {
  214. violations.push(
  215. violation({
  216. rule: "layer-direction",
  217. file,
  218. detail: target,
  219. module,
  220. message: `层 ${importerLayer} 不能依赖更高层 ${targetLayer}`,
  221. }),
  222. );
  223. }
  224. }
  225. if (module.id === "ui" && /(?:^|\/)(repo|runtime|services?)(?:\/|$)/i.test(posix(target))) {
  226. violations.push(
  227. violation({
  228. rule: "ui-implementation-import",
  229. file,
  230. detail: target,
  231. module,
  232. message: "UI 层不能直接依赖 Repo、Runtime 或 Service 实现",
  233. }),
  234. );
  235. }
  236. if (!targetModule || targetModule.id === module.id) {
  237. continue;
  238. }
  239. const declaredRequires = manifestRequiresByModule.get(module.id) ?? module.requires;
  240. if (!declaredRequires.includes(targetModule.id)) {
  241. violations.push(
  242. violation({
  243. rule: "module-dependency",
  244. file,
  245. detail: target,
  246. module,
  247. message: `模块 ${module.id} 未声明依赖 ${targetModule.id}`,
  248. }),
  249. );
  250. }
  251. if (policy.global.forbidDeepImports && targetModule.publicEntrypoints.length > 0) {
  252. const targetRelative = posix(path.relative(cwd, target));
  253. const allowed = publicEntrypointMatches(target, targetModule, cwd);
  254. if (!allowed) {
  255. violations.push(
  256. violation({
  257. rule: "deep-import",
  258. file,
  259. detail: target,
  260. module,
  261. message: `跨模块只能通过公开入口访问 ${targetRelative}`,
  262. }),
  263. );
  264. }
  265. }
  266. }
  267. if (importerLayer === "domain" && /\b(fetch|setTimeout|setInterval)\s*\(/.test(source)) {
  268. violations.push(
  269. violation({
  270. rule: "domain-io",
  271. file,
  272. detail: "runtime-call",
  273. module,
  274. message: "domain 层不能依赖 IO、进程、网络或定时器",
  275. }),
  276. );
  277. }
  278. }
  279. if (policy.global.forbidCycles) violations.push(...cycleViolations(edges, policy, modulesByFile));
  280. const baseline = await readBaseline(cwd);
  281. const baselineFingerprints = new Set(baseline.violations.map((item) => item.fingerprint));
  282. const changed = changedFiles
  283. ? new Set(changedFiles.map((file) => path.resolve(cwd, file)))
  284. : null;
  285. if (changed) {
  286. const reverse = new Map(files.map((file) => [file, []]));
  287. for (const [from, targets] of edges)
  288. for (const target of targets) reverse.get(target)?.push(from);
  289. const queue = [...changed];
  290. while (queue.length > 0) {
  291. const current = queue.shift();
  292. for (const dependent of reverse.get(current) ?? []) {
  293. if (!changed.has(dependent)) {
  294. changed.add(dependent);
  295. queue.push(dependent);
  296. }
  297. }
  298. }
  299. }
  300. const scoped = changed
  301. ? violations.filter((item) => item.global || changed.has(path.resolve(cwd, item.file)))
  302. : violations;
  303. const baselineViolations = scoped.filter((item) => baselineFingerprints.has(item.fingerprint));
  304. const newViolations = scoped.filter((item) => !baselineFingerprints.has(item.fingerprint));
  305. return { policy, violations: scoped, baselineViolations, newViolations, baseline };
  306. }
  307. export async function updateBaseline({ cwd = process.cwd(), violations }) {
  308. const entries = [...violations].sort((a, b) => a.fingerprint.localeCompare(b.fingerprint));
  309. const filename = path.join(cwd, ".architecture-baseline.json");
  310. await fs.writeFile(filename, `${JSON.stringify({ version: 1, violations: entries }, null, 2)}\n`);
  311. return entries;
  312. }
  313. export async function changedFilesFromGit(cwd = process.cwd()) {
  314. const [diff, untracked] = await Promise.all([
  315. gitFileNames(cwd, ["diff", "--name-only", "-z", "HEAD"]),
  316. gitFileNames(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
  317. ]);
  318. return [...new Set([...diff, ...untracked])];
  319. }
  320. export async function generateContext({ cwd = process.cwd(), moduleId }) {
  321. const policy = await loadPolicy(cwd);
  322. const module = policy.modules.find((item) => item.id === moduleId);
  323. if (!module) throw new Error(`未知模块: ${moduleId}`);
  324. const files = await discoverFiles(policy);
  325. const moduleFiles = files.filter((file) => moduleForFile(file, policy)?.id === moduleId);
  326. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  327. const contracts = moduleFiles.filter((file) => path.basename(file).startsWith("contract."));
  328. const dependencyContracts = module.requires.flatMap((dependencyId) => {
  329. const dependencyFiles = files.filter(
  330. (file) => moduleForFile(file, policy)?.id === dependencyId,
  331. );
  332. return dependencyFiles
  333. .filter((file) => path.basename(file) === "contract.ts")
  334. .map((file) => `- ${posix(path.relative(cwd, file))}`);
  335. });
  336. return [
  337. `# Architecture context: ${module.id}`,
  338. `owner: ${module.owner ?? "unassigned"}`,
  339. `managed: ${module.managed}`,
  340. `requires: ${module.requires.join(", ") || "none"}`,
  341. "",
  342. "## Files",
  343. ...(manifest ? [`- ${posix(path.relative(cwd, manifest))}`] : ["- module.ts: missing"]),
  344. ...contracts.map((file) => `- ${posix(path.relative(cwd, file))}`),
  345. ...module.publicEntrypoints.map((entry) => `- public: ${entry}`),
  346. "",
  347. "## Direct dependency contracts",
  348. ...(dependencyContracts.length > 0 ? dependencyContracts : ["- none discovered"]),
  349. "",
  350. "## Boundaries",
  351. "- Cross-module imports must use declared requirements and public entrypoints.",
  352. "- Add a contract example and contract test before exposing a new capability.",
  353. ].join("\n");
  354. }
  355. export function formatReport(result) {
  356. const lines = [
  357. `architecture: ${result.newViolations.length === 0 ? "OK" : "FAILED"}`,
  358. `violations: ${result.violations.length}`,
  359. `baseline: ${result.baselineViolations.length}`,
  360. `new: ${result.newViolations.length}`,
  361. ];
  362. for (const item of result.newViolations)
  363. lines.push(`- ${item.rule} ${item.file}: ${item.message}`);
  364. return lines.join("\n");
  365. }
  366. export function formatMarkdownReport(result) {
  367. const lines = [
  368. `# Architecture report`,
  369. "",
  370. `- Status: **${result.newViolations.length === 0 ? "OK" : "FAILED"}**`,
  371. `- Violations: ${result.violations.length}`,
  372. `- Baseline: ${result.baselineViolations.length}`,
  373. `- New: ${result.newViolations.length}`,
  374. ];
  375. if (result.newViolations.length > 0) {
  376. lines.push("", "## New violations", "", "| Rule | File | Message |", "| --- | --- | --- |");
  377. for (const item of result.newViolations)
  378. lines.push(`| ${item.rule} | ${item.file} | ${item.message.replaceAll("|", "\\|")} |`);
  379. }
  380. return lines.join("\n");
  381. }
  382. export { loadPolicy };