index.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import { promises as fs } from "node:fs";
  2. import path from "node:path";
  3. import {
  4. countPublicMethods,
  5. discoverFiles,
  6. importDeclarationsOf,
  7. isException,
  8. layerForFile,
  9. loadPolicy,
  10. manifestRequires,
  11. moduleForFile,
  12. posix,
  13. publicEntrypointMatches,
  14. resolveImport,
  15. } from "./policy.mjs";
  16. import { loadWorkspace } from "./resolver.mjs";
  17. import { cycleViolations, unmanagedNewFileViolations, violation } from "./violations.mjs";
  18. async function readBaseline(cwd) {
  19. try {
  20. return JSON.parse(await fs.readFile(path.join(cwd, ".architecture-baseline.json"), "utf8"));
  21. } catch {
  22. return { version: 1, violations: [] };
  23. }
  24. }
  25. export async function checkArchitecture({
  26. cwd = process.cwd(),
  27. changedFiles = null,
  28. addedFiles = null,
  29. } = {}) {
  30. const policy = await loadPolicy(cwd);
  31. const workspace = await loadWorkspace(cwd);
  32. const files = await discoverFiles(policy);
  33. const knownFiles = new Set(files);
  34. const modulesByFile = new Map(files.map((file) => [file, moduleForFile(file, policy)]));
  35. const edges = new Map(files.map((file) => [file, []]));
  36. const violations = [];
  37. const manifestRequiresByModule = new Map();
  38. const moduleIds = new Set(policy.modules.map((module) => module.id));
  39. const today = new Date().toISOString().slice(0, 10);
  40. for (const exception of policy.exceptions) {
  41. if (exception.expires && exception.expires < today) {
  42. violations.push(
  43. violation({
  44. cwd,
  45. rule: "expired-exception",
  46. file: path.join(cwd, "architecture-policy.yaml"),
  47. detail: exception.id ?? exception.rule,
  48. message: `例外 ${exception.id ?? exception.rule} 已于 ${exception.expires} 过期`,
  49. global: true,
  50. }),
  51. );
  52. }
  53. }
  54. for (const module of policy.modules.filter((item) => item.managed)) {
  55. const moduleFiles = files.filter((file) => modulesByFile.get(file)?.id === module.id);
  56. const manifest = moduleFiles.find((file) => path.basename(file) === "module.ts");
  57. if (manifest) {
  58. const declared = manifestRequires(await fs.readFile(manifest, "utf8"));
  59. if (declared) {
  60. manifestRequiresByModule.set(module.id, declared);
  61. // manifest-policy-mismatch:文档写"策略与模块声明必须互相校验",首版只是优先读 module.ts。
  62. const unknown = declared.filter((id) => !moduleIds.has(id));
  63. const onlyInManifest = declared.filter((id) => !module.requires.includes(id));
  64. const onlyInPolicy = module.requires.filter((id) => !declared.includes(id));
  65. if (unknown.length || onlyInManifest.length || onlyInPolicy.length) {
  66. const parts = [];
  67. if (unknown.length) parts.push(`未知模块 ${unknown.join(", ")}`);
  68. if (onlyInManifest.length) parts.push(`仅 module.ts 声明 ${onlyInManifest.join(", ")}`);
  69. if (onlyInPolicy.length) parts.push(`仅 policy 声明 ${onlyInPolicy.join(", ")}`);
  70. violations.push(
  71. violation({
  72. cwd,
  73. rule: "manifest-policy-mismatch",
  74. file: manifest,
  75. detail: parts.join("; "),
  76. module,
  77. message: `module.ts 与 architecture-policy.yaml 的 requires 不一致:${parts.join(";")}`,
  78. }),
  79. );
  80. }
  81. }
  82. }
  83. // App 单测已退役;模块边界依靠契约、示例和文档,不再强制测试骨架。
  84. const required = ["module.ts", "contract.ts", "contract.example.ts", "CONTRACT.md"];
  85. for (const artifact of required) {
  86. // 修复原因:discoverFiles 只收集源码扩展名,CONTRACT.md 永远不在 moduleFiles 里,
  87. // 首版对每个 managed 模块都会误报缺少 CONTRACT.md(--changed 下被 scope 过滤掉才没暴露)。
  88. const present = (
  89. await Promise.all(
  90. module.roots.map((root) =>
  91. fs.stat(path.join(root, artifact)).then(
  92. () => true,
  93. () => false,
  94. ),
  95. ),
  96. )
  97. ).some(Boolean);
  98. if (!present) {
  99. violations.push(
  100. violation({
  101. cwd,
  102. rule: "missing-module-artifact",
  103. file: module.roots[0],
  104. detail: artifact,
  105. module,
  106. message: `模块 ${module.id} 缺少 ${artifact}`,
  107. }),
  108. );
  109. }
  110. }
  111. }
  112. for (const file of files) {
  113. // CONTRACT.md 只参与产物存在性检查,文档里的示例不能当成源码依赖或源码行数。
  114. if (path.extname(file) === ".md") continue;
  115. const module = modulesByFile.get(file);
  116. if (!module) continue;
  117. const source = await fs.readFile(file, "utf8");
  118. const declarations = importDeclarationsOf(file, source);
  119. // 边对所有文件建立(含 unmanaged),否则 --changed 的反向闭包与环检测都会缺边;规则只对 managed 生效。
  120. for (const { specifier } of declarations) {
  121. const target = resolveImport(file, specifier, knownFiles, workspace);
  122. if (target) edges.get(file).push(target);
  123. }
  124. if (policy.global.managedOnly && !module.managed) continue;
  125. const lines = source.split(/\r?\n/).length;
  126. if (lines > policy.global.maxFileLines && !isException(policy, "max-file-lines", file, cwd)) {
  127. violations.push(
  128. violation({
  129. cwd,
  130. rule: "max-file-lines",
  131. file,
  132. detail: String(lines),
  133. module,
  134. message: `文件 ${lines} 行,超过上限 ${policy.global.maxFileLines} 行`,
  135. }),
  136. );
  137. }
  138. if (path.basename(file).startsWith("contract.") && lines > policy.global.maxContractLines) {
  139. violations.push(
  140. violation({
  141. cwd,
  142. rule: "max-contract-lines",
  143. file,
  144. detail: String(lines),
  145. module,
  146. message: `契约 ${lines} 行,超过上限 ${policy.global.maxContractLines} 行`,
  147. }),
  148. );
  149. }
  150. const disableCount = source
  151. .split(/\r?\n/)
  152. .filter((line) => /(?:oxlint|eslint)-disable/.test(line)).length;
  153. if (disableCount > 0 && !isException(policy, "disable-count", file, cwd)) {
  154. violations.push(
  155. violation({
  156. cwd,
  157. rule: "disable-count",
  158. file,
  159. detail: String(disableCount),
  160. module,
  161. message: `文件包含 ${disableCount} 条 lint disable`,
  162. }),
  163. );
  164. }
  165. if (
  166. path.basename(file) === "contract.ts" &&
  167. countPublicMethods(source) > policy.global.maxPublicMethods
  168. ) {
  169. violations.push(
  170. violation({
  171. cwd,
  172. rule: "max-public-methods",
  173. file,
  174. detail: String(countPublicMethods(source)),
  175. module,
  176. message: `契约公开方法超过上限 ${policy.global.maxPublicMethods}`,
  177. }),
  178. );
  179. }
  180. const importerLayer = layerForFile(file, module);
  181. const layerOrder = module.layerOrder ?? [];
  182. for (const { specifier, typeOnly } of declarations) {
  183. if (
  184. importerLayer === "domain" &&
  185. !typeOnly &&
  186. /^(node:|fs$|path$|http$|https$|net$|child_process$|timers$|electron$|electron\/)/.test(
  187. specifier,
  188. )
  189. ) {
  190. violations.push(
  191. violation({
  192. cwd,
  193. rule: "domain-io",
  194. file,
  195. detail: specifier,
  196. module,
  197. message: "domain 层不能依赖 IO、进程、网络、定时器或 electron",
  198. }),
  199. );
  200. }
  201. const target = resolveImport(file, specifier, knownFiles, workspace);
  202. if (!target) continue;
  203. const targetModule = modulesByFile.get(target);
  204. if (targetModule?.id === module.id) {
  205. const targetLayer = layerForFile(target, module);
  206. if (
  207. importerLayer &&
  208. targetLayer &&
  209. layerOrder.includes(importerLayer) &&
  210. layerOrder.includes(targetLayer) &&
  211. layerOrder.indexOf(importerLayer) < layerOrder.indexOf(targetLayer)
  212. ) {
  213. violations.push(
  214. violation({
  215. cwd,
  216. rule: "layer-direction",
  217. file,
  218. detail: target,
  219. module,
  220. message: `层 ${importerLayer} 不能依赖更高层 ${targetLayer}`,
  221. }),
  222. );
  223. }
  224. }
  225. // 修复原因:首版以 module.id === "ui" 触发,而 ui 是 unmanaged 模块,规则从未执行;改为按层触发。
  226. if (
  227. (importerLayer === "ui" || module.id === "ui") &&
  228. /(?:^|\/)(repo|repos|repository|runtime|services?)(?:\/|$)/i.test(
  229. posix(path.relative(cwd, target)),
  230. )
  231. ) {
  232. violations.push(
  233. violation({
  234. cwd,
  235. rule: "ui-implementation-import",
  236. file,
  237. detail: target,
  238. module,
  239. message:
  240. "UI 层不能直接依赖 Repo、Runtime 或 Service 实现;通过本模块 contract/port 访问",
  241. }),
  242. );
  243. }
  244. if (!targetModule || targetModule.id === module.id) continue;
  245. const declaredRequires = manifestRequiresByModule.get(module.id) ?? module.requires;
  246. if (!declaredRequires.includes(targetModule.id)) {
  247. violations.push(
  248. violation({
  249. cwd,
  250. rule: "module-dependency",
  251. file,
  252. detail: target,
  253. module,
  254. message: `模块 ${module.id} 未声明依赖 ${targetModule.id}(import "${specifier}")`,
  255. }),
  256. );
  257. }
  258. if (policy.global.forbidDeepImports && targetModule.publicEntrypoints.length > 0) {
  259. if (!publicEntrypointMatches(target, targetModule, cwd)) {
  260. violations.push(
  261. violation({
  262. cwd,
  263. rule: "deep-import",
  264. file,
  265. detail: target,
  266. module,
  267. message: `跨模块只能通过公开入口访问 ${posix(path.relative(cwd, target))}(import "${specifier}")`,
  268. }),
  269. );
  270. }
  271. }
  272. }
  273. if (importerLayer === "domain" && /\b(fetch|setTimeout|setInterval)\s*\(/.test(source)) {
  274. violations.push(
  275. violation({
  276. cwd,
  277. rule: "domain-io",
  278. file,
  279. detail: "runtime-call",
  280. module,
  281. message: "domain 层不能依赖 IO、进程、网络或定时器",
  282. }),
  283. );
  284. }
  285. }
  286. if (policy.global.forbidCycles)
  287. violations.push(...cycleViolations(edges, policy, modulesByFile, cwd));
  288. if (addedFiles) violations.push(...unmanagedNewFileViolations(addedFiles, policy, cwd));
  289. const baseline = await readBaseline(cwd);
  290. const baselineFingerprints = new Set(baseline.violations.map((item) => item.fingerprint));
  291. const changed = changedFiles
  292. ? new Set(changedFiles.map((file) => path.resolve(cwd, file)))
  293. : null;
  294. if (changed) {
  295. const reverse = new Map(files.map((file) => [file, []]));
  296. for (const [from, targets] of edges)
  297. for (const target of targets) reverse.get(target)?.push(from);
  298. const queue = [...changed];
  299. while (queue.length > 0) {
  300. const current = queue.shift();
  301. for (const dependent of reverse.get(current) ?? []) {
  302. if (!changed.has(dependent)) {
  303. changed.add(dependent);
  304. queue.push(dependent);
  305. }
  306. }
  307. }
  308. }
  309. const scoped = changed
  310. ? violations.filter((item) => item.global || changed.has(path.resolve(cwd, item.file)))
  311. : violations;
  312. const baselineViolations = scoped.filter((item) => baselineFingerprints.has(item.fingerprint));
  313. const newViolations = scoped.filter((item) => !baselineFingerprints.has(item.fingerprint));
  314. return {
  315. policy,
  316. violations: scoped,
  317. baselineViolations,
  318. newViolations,
  319. baseline,
  320. changedClosure: changed,
  321. };
  322. }
  323. /**
  324. * scope 为 --changed 的变更闭包。修复原因:首版直接用 scoped 结果覆盖整份 baseline,
  325. * `baseline:update -- --changed` 会把闭包之外的所有条目全部丢掉。
  326. */
  327. export async function updateBaseline({ cwd = process.cwd(), violations, scope = null }) {
  328. const filename = path.join(cwd, ".architecture-baseline.json");
  329. const previous = scope ? (await readBaseline(cwd)).violations : [];
  330. const kept = scope
  331. ? previous.filter((item) => !item.global && !scope.has(path.resolve(cwd, item.file)))
  332. : [];
  333. const merged = new Map();
  334. for (const item of [...kept, ...violations]) merged.set(item.fingerprint, item);
  335. const entries = [...merged.values()].sort((a, b) => a.fingerprint.localeCompare(b.fingerprint));
  336. await fs.writeFile(filename, `${JSON.stringify({ version: 1, violations: entries }, null, 2)}\n`);
  337. return entries;
  338. }
  339. export { loadPolicy };
  340. export { addedFilesFromGit, changedFilesFromGit, resolveDiffBase } from "./git-base.mjs";
  341. export { generateContext } from "./context.mjs";
  342. export { formatMarkdownReport, formatReport } from "./report.mjs";