policy.mjs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import { promises as fs } from "node:fs";
  2. import path from "node:path";
  3. import ts from "typescript";
  4. import { parse as parseYaml } from "yaml";
  5. const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
  6. export function posix(value) {
  7. return value.split(path.sep).join("/");
  8. }
  9. function isSourceFile(file) {
  10. return SOURCE_EXTENSIONS.some((extension) => file.endsWith(extension));
  11. }
  12. async function walk(root, files) {
  13. let entries;
  14. try {
  15. entries = await fs.readdir(root, { withFileTypes: true });
  16. } catch {
  17. return;
  18. }
  19. for (const entry of entries) {
  20. if (["node_modules", "dist", "out", "coverage", ".git"].includes(entry.name)) continue;
  21. const target = path.join(root, entry.name);
  22. if (entry.isDirectory()) await walk(target, files);
  23. // 契约文档也是必需产物;只枚举源码会把实际存在的 CONTRACT.md 误报为缺失。
  24. else if (entry.isFile() && (isSourceFile(target) || entry.name === "CONTRACT.md"))
  25. files.push(target);
  26. }
  27. }
  28. function validatePolicy(raw, cwd) {
  29. if (!raw || raw.version !== 1 || !Array.isArray(raw.modules)) {
  30. throw new Error("architecture-policy.yaml 必须包含 version: 1 和 modules 数组");
  31. }
  32. const ids = new Set();
  33. const modules = raw.modules.map((module) => {
  34. if (!module?.id || ids.has(module.id))
  35. throw new Error(`模块 id 重复或为空: ${module?.id ?? ""}`);
  36. ids.add(module.id);
  37. if (!Array.isArray(module.roots) || module.roots.length === 0) {
  38. throw new Error(`模块 ${module.id} 必须声明 roots`);
  39. }
  40. return {
  41. id: module.id,
  42. roots: module.roots.map((root) => path.resolve(cwd, root)),
  43. managed: module.managed === true,
  44. requires: [...new Set(module.requires ?? [])],
  45. publicEntrypoints: (module.publicEntrypoints ?? []).map((entry) => posix(entry)),
  46. layers: module.layers ?? {},
  47. layerOrder: module.layerOrder ?? Object.keys(module.layers ?? {}),
  48. owner: module.owner ?? null,
  49. };
  50. });
  51. const moduleIds = new Set(modules.map((module) => module.id));
  52. for (const module of modules) {
  53. for (const dependency of module.requires) {
  54. if (!moduleIds.has(dependency))
  55. throw new Error(`模块 ${module.id} 依赖未知模块 ${dependency}`);
  56. }
  57. }
  58. const global = {
  59. maxFileLines: raw.global?.maxFileLines ?? 400,
  60. maxContractLines: raw.global?.maxContractLines ?? 300,
  61. forbidCycles: raw.global?.forbidCycles !== false,
  62. forbidDeepImports: raw.global?.forbidDeepImports !== false,
  63. managedOnly: raw.global?.managedOnly !== false,
  64. maxPublicMethods: raw.global?.maxPublicMethods ?? 12,
  65. };
  66. const exceptions = (raw.exceptions ?? []).map((exception) => ({
  67. ...exception,
  68. paths: exception.paths ?? [],
  69. }));
  70. return { version: 1, modules, global, exceptions };
  71. }
  72. export function layerForFile(file, module) {
  73. const matches = module.roots
  74. .flatMap((root) =>
  75. Object.entries(module.layers).map(([name, directory]) => ({
  76. name,
  77. directory: path.resolve(root, directory),
  78. })),
  79. )
  80. .filter(({ directory }) => file === directory || file.startsWith(`${directory}${path.sep}`))
  81. .sort((a, b) => b.directory.length - a.directory.length);
  82. return matches[0]?.name ?? null;
  83. }
  84. export function publicEntrypointMatches(target, targetModule, cwd) {
  85. return targetModule.publicEntrypoints.some((entry) => {
  86. const candidates = [
  87. path.resolve(cwd, entry),
  88. ...targetModule.roots.map((root) => path.resolve(root, entry)),
  89. ];
  90. return candidates.includes(target);
  91. });
  92. }
  93. export function manifestRequires(source) {
  94. const match = source.match(/requires\s*:\s*\[([^\]]*)\]/s);
  95. if (!match) return null;
  96. return [...match[1].matchAll(/["']([^"']+)["']/g)].map((item) => item[1]);
  97. }
  98. export function countPublicMethods(source) {
  99. const sourceFile = ts.createSourceFile("contract.ts", source, ts.ScriptTarget.Latest, true);
  100. let count = 0;
  101. function visit(node) {
  102. if (ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) {
  103. for (const member of node.members) {
  104. if (
  105. ts.isMethodSignature(member) ||
  106. ts.isMethodDeclaration(member) ||
  107. ts.isCallSignatureDeclaration(member)
  108. )
  109. count += 1;
  110. }
  111. }
  112. ts.forEachChild(node, visit);
  113. }
  114. visit(sourceFile);
  115. return count;
  116. }
  117. export async function loadPolicy(cwd = process.cwd()) {
  118. const filename = path.join(cwd, "architecture-policy.yaml");
  119. const content = await fs.readFile(filename, "utf8");
  120. return validatePolicy(parseYaml(content), cwd);
  121. }
  122. export function moduleForFile(file, policy) {
  123. const candidates = policy.modules
  124. .filter((module) =>
  125. module.roots.some((root) => file === root || file.startsWith(`${root}${path.sep}`)),
  126. )
  127. .sort(
  128. (a, b) =>
  129. Math.max(...b.roots.map((root) => root.length)) -
  130. Math.max(...a.roots.map((root) => root.length)),
  131. );
  132. return candidates[0] ?? null;
  133. }
  134. export async function discoverFiles(policy) {
  135. const files = [];
  136. for (const module of policy.modules) {
  137. for (const root of module.roots) await walk(root, files);
  138. }
  139. return [...new Set(files)].sort();
  140. }
  141. export function resolveImport(from, specifier, knownFiles) {
  142. if (!specifier.startsWith(".")) return null;
  143. let base = path.resolve(path.dirname(from), specifier);
  144. if (SOURCE_EXTENSIONS.some((extension) => base.endsWith(extension))) {
  145. base = base.slice(0, base.lastIndexOf("."));
  146. }
  147. const candidates = [];
  148. for (const extension of SOURCE_EXTENSIONS) candidates.push(`${base}${extension}`);
  149. for (const extension of SOURCE_EXTENSIONS) candidates.push(path.join(base, `index${extension}`));
  150. return candidates.find((candidate) => knownFiles.has(candidate)) ?? null;
  151. }
  152. export function importsOf(file, source) {
  153. const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
  154. const imports = [];
  155. function visit(node) {
  156. if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier) {
  157. imports.push(node.moduleSpecifier.text);
  158. }
  159. if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
  160. if (ts.isStringLiteral(node.moduleReference.expression))
  161. imports.push(node.moduleReference.expression.text);
  162. }
  163. ts.forEachChild(node, visit);
  164. }
  165. visit(sourceFile);
  166. return imports;
  167. }
  168. export function isException(policy, rule, file, cwd) {
  169. const relative = posix(path.relative(cwd, file));
  170. return policy.exceptions.some(
  171. (exception) =>
  172. exception.rule === rule &&
  173. exception.paths.some(
  174. (pattern) => relative === pattern || relative.startsWith(pattern.replace(/\*\*$/, "")),
  175. ),
  176. );
  177. }