policy.mjs 6.4 KB

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