Files
clean-architecture-frontend…/scripts/check-architecture.ts
T
DongHyeonka 5aac37e676 fix(architecture): 구조 규칙의 넓은 예외를 좁히고 kernel 규칙에 fixture를 둔다
문제: 꼭 지킬 것 2의 kernel 규칙을 고정하는 fixture가 없어, pathNot을
넓히거나 규칙을 지워도 아무것도 실패하지 않는다(02-01). routing 예외가
금지 대상 일곱을 다 풀고, contribution 파일 예외가 adapter 값까지 푼다.
그래서 presentation이 HTTP adapter에 닿는 길이 규칙 밖에 있다(02-02).
generic-presentation 예외 목록에 registry를 더는 읽지 않는 home-page가
남았다(02-03). 기능의 계층 밖 폴더가 자기 adapters/를 거쳐 src/adapters에
닿는 두 단계 길이 열려 있다(0929/12-03). application TelemetryPort가
플랫폼 TelemetryPort와 이름이 같고, 폐기 표시된 src/application/result.ts를
ports 셋이 상대 경로로 계속 읽는다(1101/16-05).

고른 방법(R9-D3 좁히기):
- 그래프가 type-only import를 가르고, 규칙 to에 dependencyTypesNot
  ["type-only"]를 쓸 수 있다(산출물 모양은 그대로).
- platform 규칙을 둘로 나눈다. routing도 features·adapters·bootstrap·
  presentation·application은 못 읽고, apps·contexts만 routing이 읽는다.
- feature-adapter-contribution-reads-adapter-types-only: contribution
  파일은 src/adapters를 타입으로만 읽는다.
- feature-support-folders-do-not-reach-feature-adapters: 다섯 계층이 아닌
  폴더는 자기 기능의 adapters/를 import하지 않는다.
- home-page를 예외 목록에서 뺀다. 이름으로 적은 파일 예외가 더 쓰이지
  않으면 check:architecture가 실패한다.
- kernel·routing·type-only·두 단계 길 fixture와 assertion을 더한다.
- ApplicationTelemetryPort로 이름을 나누고 옛 이름은 한 릴리스 동안
  @deprecated 별칭으로 둔다. ports 셋이 Result를 src/contracts/result.ts에서
  읽게 하고 src/application/result.ts를 지운다.
버린 대안: page-templates.tsx가 LinkButton을 design-system index에서
가져오기 — index가 page-templates를 다시 내보내 순환이 된다. 예외
이유에 그것을 적었다. 기능 경계 둘을 하나로 합치기 — 안쪽은 라우트 내용,
바깥은 라우트 틀(RouteLifecycle, 입력 해석)을 맡아 역할이 다르다. 두
자리에 역할을 적었다.

위험·한계: 이름 예외 검사는 pathNot 문자열에 파일 base name이 있는
경우만 이름 예외로 본다. 폴더·이름 패턴 예외는 보지 않는다.

검증: desktop 결과는 PR 본문.

Refs: 1112/02-01, 1112/02-02, 1112/02-03, 0929/12-03, 1101/16-05
2026-11-13 20:18:07 +09:00

1462 lines
48 KiB
TypeScript

import { parseAsync } from "@babel/core";
import { mkdir, readFile, readdir } from "node:fs/promises";
import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createRequire } from "node:module";
import { ESLint } from "eslint";
import { architectureDependencyReportArtifactSchema } from "./contracts/release-artifacts.ts";
import { checkArchitectureLintFixtures } from "./lib/architecture-lint-fixtures.ts";
import { formatArchitectureViolation } from "./lib/architecture-violation-message.ts";
import { selectRepositoryEntries } from "./lib/repository-layout.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type PathRule = Readonly<{
path?: string;
pathNot?: string;
/**
* 1112/02-02. `["type-only"]` on `to`: an edge whose every import of the
* target is type-only (`import type`, `export type`, an `import()` type)
* does not match, as dependency-cruiser's option of the same name.
*/
dependencyTypesNot?: readonly "type-only"[];
}>;
type ArchitectureRule = Readonly<{
name: string;
comment?: string;
severity?: string;
from?: PathRule;
to?: PathRule & Readonly<{ circular?: boolean }>;
}>;
type ArchitectureConfig = Readonly<{
forbidden: readonly ArchitectureRule[];
allowed: readonly unknown[];
required: readonly unknown[];
}>;
type DependencyEdge = Readonly<{
source: string;
target: string;
specifier: string;
kind: "local" | "external";
}>;
type UnresolvedDependency = Readonly<{
source: string;
specifier: string;
reason: string;
}>;
type ParseFailure = Readonly<{ source: string; reason: string }>;
type ArchitectureViolation = Readonly<{
rule: string;
severity: string;
source: string;
target: string;
cycle?: readonly string[];
}>;
type SourceGraph = Readonly<{
modules: string[];
dependencies: DependencyEdge[];
unresolved: UnresolvedDependency[];
parseFailures: ParseFailure[];
cycles: string[][];
violations: ArchitectureViolation[];
}>;
type GraphFixtureResult = Readonly<{
passed: boolean;
checks: string[];
failures: string[];
}>;
type DependencyResolution = Readonly<{ path?: string; reason: string }>;
type TypeScriptOnlyPolicy = Readonly<{
checkedRoots: readonly string[];
exceptionsAllowed: false;
violations: readonly string[];
passed: boolean;
}>;
type BabelOptions = NonNullable<Parameters<typeof parseAsync>[1]>;
type BabelParserOptions = NonNullable<BabelOptions["parserOpts"]>;
type BabelParserPlugin = NonNullable<BabelParserOptions["plugins"]>[number];
const projectRoot = process.cwd();
const sourceRoot = resolve(projectRoot, "src");
const qualityArtifact = resolve(
projectRoot,
"artifacts/quality/dependency-report.json",
);
const require = createRequire(import.meta.url);
const architectureConfig = parseArchitectureConfig(
require(resolve(projectRoot, ".dependency-cruiser.json")),
);
const architectureRules = architectureConfig.forbidden;
const sourceExtensionPattern = /\.(?:ts|tsx|mts|cts)$/u;
const declarationExtensionPattern = /\.d\.(?:ts|mts|cts)$/u;
const forbiddenJavaScriptExtensionPattern = /\.(?:js|jsx|mjs|cjs)$/u;
const forbiddenLocalJavaScriptSpecifierPattern =
/\.(?:js|jsx|mjs|cjs)(?:[?#]|$)/u;
const forbiddenLocalJavaScriptSpecifierReason =
"local JavaScript-family specifiers are forbidden; use the actual TypeScript extension";
const relativeSpecifierPattern = /^\.{1,2}(?:\/|$)/u;
await mkdir(dirname(qualityArtifact), { recursive: true });
if (
(architectureConfig.allowed?.length ?? 0) > 0 ||
(architectureConfig.required?.length ?? 0) > 0
) {
throw new Error(
"Static architecture graph must be extended before allowed/required rules are configured",
);
}
validateArchitectureRules(architectureRules);
// 12-05 (D-11): this graph is the only architecture checker. dependency-cruiser
// 18 cannot parse TypeScript 7, so it cruised zero modules and still passed.
// .dependency-cruiser.json keeps its name and is read here as the rule file.
const sourceGraph = await analyzeSourceGraph(sourceRoot, "src");
const typeScriptOnlyPolicy = await inspectTypeScriptOnlyPolicy();
const graphFixtureResult = await runGraphFixtureChecks();
const graphErrors = blockingViolations(sourceGraph);
const staticImportGraph = {
analyzer: "babel-parser-node-resolver",
modules: sourceGraph.modules,
dependencies: sourceGraph.dependencies,
unresolved: sourceGraph.unresolved,
parseFailures: sourceGraph.parseFailures,
cycles: sourceGraph.cycles,
violations: sourceGraph.violations,
summary: {
modules: sourceGraph.modules.length,
typescriptModules: sourceGraph.modules.filter((module) =>
sourceExtensionPattern.test(module),
).length,
dependencies: sourceGraph.dependencies.length,
localDependencies: sourceGraph.dependencies.filter(
({ kind }) => kind === "local",
).length,
unresolved: sourceGraph.unresolved.length,
parseFailures: sourceGraph.parseFailures.length,
cycles: sourceGraph.cycles.length,
errors: graphErrors.length,
typeScriptOnlyPolicyPassed: typeScriptOnlyPolicy.passed,
nonTypeScriptExecutableSources: typeScriptOnlyPolicy.violations.length,
},
fixtureChecks: graphFixtureResult,
typeScriptOnlySourcePolicy: typeScriptOnlyPolicy,
};
await writeValidatedJsonArtifact({
path: qualityArtifact,
schema: architectureDependencyReportArtifactSchema,
value: { staticImportGraph },
});
let architectureFailed = false;
for (const failure of sourceGraph.parseFailures) {
architectureFailed = true;
process.stderr.write(
`Architecture graph parse failure: ${failure.source}: ${failure.reason}\n`,
);
}
for (const dependency of sourceGraph.unresolved) {
architectureFailed = true;
process.stderr.write(
`Unresolved architecture dependency: ${dependency.source} -> ${dependency.specifier} (${dependency.reason})\n`,
);
}
for (const violation of graphErrors) {
architectureFailed = true;
process.stderr.write(
formatArchitectureViolation(
violation,
violation.cycle
? []
: sourceGraph.dependencies
.filter(({ source, target }) => source === violation.source && target === violation.target)
.map(({ specifier }) => specifier),
architectureRules.find(({ name }) => name === violation.rule)?.comment,
),
);
}
// 1112/02-03. An exemption a rule gives a file by name outlives its use
// unnoticed: the file stops making the edge and the hole stays open.
for (const problem of unusedFileExceptions(sourceGraph, architectureRules)) {
architectureFailed = true;
process.stderr.write(`Architecture exception unused: ${problem}\n`);
}
for (const file of typeScriptOnlyPolicy.violations) {
architectureFailed = true;
process.stderr.write(`Non-TypeScript executable source: ${file}\n`);
}
if (!graphFixtureResult.passed) {
architectureFailed = true;
for (const failure of graphFixtureResult.failures) {
process.stderr.write(`Architecture graph fixture failed: ${failure}\n`);
}
}
if (architectureFailed) {
process.exit(1);
}
process.stdout.write(
`Static import graph: ${sourceGraph.modules.length} modules, ${sourceGraph.dependencies.length} dependencies, all imports resolved\n`,
);
process.stdout.write(
`Architecture graph fixtures: ${graphFixtureResult.checks.length} regression checks PASS\n`,
);
process.stdout.write(
`TypeScript-only source policy: PASS (${typeScriptOnlyPolicy.checkedRoots.join(", ")}; no fixture exceptions)\n`,
);
// 1103/12-04. Each fixture is linted under the production configuration of
// the path it stands for, and a forbidden one must be reported by the rule it
// names (scripts/lib/architecture-lint-fixtures.ts).
const lintFixtures = await checkArchitectureLintFixtures({
root: projectRoot,
linter: new ESLint({ cwd: projectRoot }),
});
if (lintFixtures.failures.length > 0) {
for (const failure of lintFixtures.failures) {
process.stderr.write(`Architecture lint fixture: ${failure}\n`);
}
process.exit(1);
}
process.stdout.write(
`Architecture fixtures: ${lintFixtures.allowed} allowed PASS, ${lintFixtures.forbidden} forbidden rejected by the production rule for their layer\n`,
);
async function analyzeSourceGraph(
rootDirectory: string,
reportPrefix: string,
): Promise<SourceGraph> {
const allFiles = await listFiles(rootDirectory);
const allFileSet = new Set(allFiles);
const sourceFiles = allFiles.filter((file) => sourceExtensionPattern.test(file));
const modules = sourceFiles
.map((file) => reportPath(file, rootDirectory, reportPrefix))
.sort();
const moduleNames = new Set(modules);
const dependencies: DependencyEdge[] = [];
// 1112/02-02. Edges at least one import of which carries a value; every
// other local edge is type-only. Kept by edge, not by specifier: two
// spellings of one target (one `import type`, one value) are one value edge.
// Beside the graph artifact rather than in it: only `dependencyTypesNot`
// rules read it.
const valueEdges = new Set<string>();
const unresolved: UnresolvedDependency[] = [];
const parseFailures: ParseFailure[] = [];
for (const sourceFile of sourceFiles) {
const source = reportPath(sourceFile, rootDirectory, reportPrefix);
let specifiers: string[];
let valueSpecifiers: ReadonlySet<string>;
try {
({ specifiers, valueSpecifiers } = await importSpecifiers(sourceFile));
} catch (error) {
parseFailures.push({
source,
reason: error instanceof Error ? error.message : String(error),
});
continue;
}
for (const specifier of specifiers) {
if (isExplicitLocalJavaScriptSpecifier(specifier)) {
unresolved.push({
source,
specifier,
reason: forbiddenLocalJavaScriptSpecifierReason,
});
continue;
}
if (relativeSpecifierPattern.test(specifier)) {
const resolution = resolveRelativeDependency(
sourceFile,
specifier,
rootDirectory,
allFileSet,
);
if (!resolution.path) {
unresolved.push({ source, specifier, reason: resolution.reason });
continue;
}
const target = reportPath(resolution.path, rootDirectory, reportPrefix);
dependencies.push({ source, target, specifier, kind: "local" });
if (valueSpecifiers.has(specifier)) valueEdges.add(edgeKey(source, target));
continue;
}
try {
const resolvedSpecifier = import.meta.resolve(
specifier,
pathToFileURL(sourceFile).href,
);
if (resolvedSpecifier.startsWith("file:")) {
const resolvedFile = fileURLToPath(resolvedSpecifier);
const resolvedSource = resolutionCandidates(resolvedFile).find(
(candidate) => allFileSet.has(candidate),
);
if (resolvedSource) {
const target = reportPath(resolvedSource, rootDirectory, reportPrefix);
dependencies.push({ source, target, specifier, kind: "local" });
if (valueSpecifiers.has(specifier)) valueEdges.add(edgeKey(source, target));
continue;
}
if (specifier.startsWith("/") || specifier.startsWith("file:")) {
throw new Error(
"absolute file imports must resolve within the analyzed source root",
);
}
}
dependencies.push({
source,
target: specifier,
specifier,
kind: "external",
});
} catch (error) {
unresolved.push({
source,
specifier,
reason: error instanceof Error ? error.message : String(error),
});
}
}
}
dependencies.sort(compareDependencies);
unresolved.sort(compareSourceAndSpecifier);
parseFailures.sort((left, right) => left.source.localeCompare(right.source));
const cycles = findCycles(modules, dependencies, moduleNames);
return {
modules,
dependencies,
unresolved,
parseFailures,
cycles,
violations: findArchitectureViolations(
dependencies,
cycles,
new Set(
dependencies
.map(({ source, target }) => edgeKey(source, target))
.filter((key) => !valueEdges.has(key)),
),
),
};
}
/**
* 1112/02-03. Each file a rule's `from.pathNot` names (its base name is in the
* pattern, so a folder or a name pattern is not one) must still import what
* the rule's `to` forbids everyone else; otherwise the exemption is wider
* than its use and goes. A file the rule protects as the single entry (it
* matches `to` itself, such as `src/contracts/zod.ts`) is not an exemption.
*/
function unusedFileExceptions(
graph: SourceGraph,
rules: readonly ArchitectureRule[],
): string[] {
const problems: string[] = [];
for (const rule of rules) {
const pathNot = rule.from?.pathNot;
if (!pathNot || rule.to?.circular) continue;
const exempted = new RegExp(pathNot, "u");
for (const module of graph.modules) {
if (rule.from?.path && !new RegExp(rule.from.path, "u").test(module)) continue;
if (!exempted.test(module)) continue;
const name = basename(module).replace(/\.[^.]+$/u, "");
// Named: the base name stands as a whole alternative followed by its
// escaped extension, as in `pages/not-found-page\.tsx` or
// `(route-contract|app-router)\.(ts|tsx)`, not inside a folder name.
const named = new RegExp(`[/(|]${escapeRegExp(name)}(?:\\\\\\.|[|)])`, "u").test(pathNot);
if (!named || matchesPath(module, rule.to)) continue;
const sourceGroups = rule.from?.path
? (new RegExp(rule.from.path, "u").exec(module)?.slice(1) ?? [])
: [];
const used = graph.dependencies.some(
(dependency) =>
dependency.source === module &&
matchesPath(dependency.target, rule.to, sourceGroups),
);
if (!used) {
problems.push(
`${rule.name}: from.pathNot names ${module}, which no longer imports what the rule forbids (${rule.to?.path ?? "any"}); take it out of the list in .dependency-cruiser.json`,
);
}
}
}
return problems;
}
function edgeKey(source: string, target: string): string {
return `${source}\u0000${target}`;
}
async function importSpecifiers(sourceFile: string): Promise<
Readonly<{ specifiers: string[]; valueSpecifiers: ReadonlySet<string> }>
> {
const sourceText = await readFile(sourceFile, "utf8");
const isTypeScript = sourceExtensionPattern.test(sourceFile);
const isJsx = /\.tsx$/u.test(sourceFile);
const plugins: BabelParserPlugin[] = [];
if (isTypeScript) {
plugins.push([
"typescript",
{
dts: declarationExtensionPattern.test(sourceFile),
},
]);
}
if (isJsx) {
plugins.push("jsx");
}
const syntaxTree = await parseAsync(sourceText, {
filename: sourceFile,
babelrc: false,
configFile: false,
sourceType: "unambiguous",
parserOpts: { plugins },
});
if (!syntaxTree) {
throw new Error("Babel returned no syntax tree");
}
const specifiers = new Set<string>();
const valueSpecifiers = new Set<string>();
const nonLiteralModuleLoads = new Set<string>();
visitSyntaxNode(syntaxTree, specifiers, nonLiteralModuleLoads, valueSpecifiers);
if (nonLiteralModuleLoads.size > 0) {
throw new Error(
`module loading must name one module with a string literal: ${[...nonLiteralModuleLoads].join(", ")}`,
);
}
for (const comment of syntaxTree.comments ?? []) {
const importTypePattern =
/\bimport\s*\(\s*["']([^"'\\\r\n]+)["']\s*\)/gu;
let match = importTypePattern.exec(comment.value);
while (match) {
const specifier = match[1];
if (specifier) specifiers.add(specifier);
match = importTypePattern.exec(comment.value);
}
}
return { specifiers: [...specifiers].sort(), valueSpecifiers };
}
/**
* 1112/02-02. Whether an import or re-export declaration carries a value: it
* does unless the declaration itself is `type`, or it names specifiers and
* each one is `type`. A bare side-effect import carries a value.
*/
function declarationCarriesValue(node: Record<string, unknown>): boolean {
const declarationKind = node.importKind ?? node.exportKind;
if (declarationKind === "type") return false;
const named = Array.isArray(node.specifiers) ? node.specifiers : [];
if (named.length === 0) return true;
return named.some((specifier: unknown) => {
const kind =
syntaxNodeProperty(specifier, "importKind") ?? syntaxNodeProperty(specifier, "exportKind");
return kind !== "type";
});
}
function visitSyntaxNode(
value: unknown,
specifiers: Set<string>,
nonLiteralModuleLoads: Set<string>,
valueSpecifiers: Set<string>,
): void {
if (Array.isArray(value)) {
for (const child of value) {
visitSyntaxNode(child, specifiers, nonLiteralModuleLoads, valueSpecifiers);
}
return;
}
if (!value || typeof value !== "object") {
return;
}
const node = value as Record<string, unknown>;
const nodeType = typeof node.type === "string" ? node.type : undefined;
if (
nodeType === "ImportDeclaration" ||
nodeType === "ExportNamedDeclaration" ||
nodeType === "ExportAllDeclaration"
) {
if (addStringLiteral(node.source, specifiers) && declarationCarriesValue(node)) {
addStringLiteral(node.source, valueSpecifiers);
}
} else if (nodeType === "ImportExpression") {
if (!addStringLiteral(node.source, specifiers)) {
nonLiteralModuleLoads.add("import()");
} else {
addStringLiteral(node.source, valueSpecifiers);
}
} else if (
nodeType === "CallExpression" &&
syntaxNodeType(node.callee) === "Import"
) {
const arguments_ = Array.isArray(node.arguments) ? node.arguments : [];
if (!addStringLiteral(arguments_[0], specifiers)) {
nonLiteralModuleLoads.add("import()");
} else {
addStringLiteral(arguments_[0], valueSpecifiers);
}
} else if (
nodeType === "CallExpression" &&
syntaxNodeType(node.callee) === "Identifier" &&
syntaxNodeProperty(node.callee, "name") === "require"
) {
const arguments_ = Array.isArray(node.arguments) ? node.arguments : [];
if (!addStringLiteral(arguments_[0], specifiers)) {
nonLiteralModuleLoads.add("require()");
} else {
addStringLiteral(arguments_[0], valueSpecifiers);
}
} else if (
nodeType === "CallExpression" &&
syntaxNodeType(node.callee) === "MemberExpression" &&
syntaxNodeType(syntaxNodeProperty(node.callee, "object")) === "MetaProperty" &&
/^glob(?:Eager)?$/u.test(
String(syntaxNodeProperty(syntaxNodeProperty(node.callee, "property"), "name")),
)
) {
// 12-06: a glob pulls in every matching module without naming one, so no
// edge rule can see it. Refuse it like a non-literal import().
nonLiteralModuleLoads.add("import.meta.glob()");
} else if (nodeType === "TSExternalModuleReference") {
addStringLiteral(node.expression, specifiers);
addStringLiteral(node.expression, valueSpecifiers);
} else if (nodeType === "TSImportType") {
addStringLiteral(
syntaxNodeType(node.argument) === "TSLiteralType"
? syntaxNodeProperty(node.argument, "literal")
: node.argument,
specifiers,
);
}
for (const [key, child] of Object.entries(node)) {
if (
key === "comments" ||
key === "leadingComments" ||
key === "trailingComments" ||
key === "innerComments" ||
key === "loc"
) {
continue;
}
visitSyntaxNode(child, specifiers, nonLiteralModuleLoads, valueSpecifiers);
}
}
function syntaxNodeType(value: unknown): string | undefined {
const type = syntaxNodeProperty(value, "type");
return typeof type === "string" ? type : undefined;
}
function syntaxNodeProperty(value: unknown, key: string): unknown {
return value && typeof value === "object"
? (value as Record<string, unknown>)[key]
: undefined;
}
function addStringLiteral(value: unknown, specifiers: Set<string>): boolean {
if (!value || typeof value !== "object") {
return false;
}
const literal = value as Record<string, unknown>;
if (
(literal.type === "StringLiteral" || literal.type === "Literal") &&
typeof literal.value === "string"
) {
specifiers.add(literal.value);
return true;
}
return false;
}
function resolveRelativeDependency(
sourceFile: string,
specifier: string,
rootDirectory: string,
allFiles: Set<string>,
): DependencyResolution {
if (isExplicitLocalJavaScriptSpecifier(specifier)) {
return { reason: forbiddenLocalJavaScriptSpecifierReason };
}
const pathPart = specifier.split(/[?#]/u, 1)[0];
const requestedPath = resolve(dirname(sourceFile), pathPart);
const relativeToRoot = relative(rootDirectory, requestedPath);
if (
relativeToRoot === ".." ||
relativeToRoot.startsWith(`..${sep}`) ||
isAbsolute(relativeToRoot)
) {
return { reason: "relative import resolves outside the analyzed source root" };
}
for (const candidate of resolutionCandidates(requestedPath)) {
if (allFiles.has(candidate)) {
return { path: candidate, reason: "" };
}
}
return { reason: "no matching source or asset exists within the analyzed root" };
}
function isExplicitLocalJavaScriptSpecifier(specifier: string): boolean {
return (
(relativeSpecifierPattern.test(specifier) ||
specifier.startsWith("/") ||
specifier.startsWith("file:")) &&
forbiddenLocalJavaScriptSpecifierPattern.test(specifier)
);
}
function resolutionCandidates(requestedPath: string): string[] {
const extension = extname(requestedPath);
const sourceExtensions = [
".ts",
".tsx",
".mts",
".cts",
".d.ts",
".d.mts",
".d.cts",
".json",
];
if (extension) {
return [requestedPath];
}
return [
requestedPath,
...sourceExtensions.map((candidate) => `${requestedPath}${candidate}`),
...sourceExtensions.map((candidate) =>
resolve(requestedPath, `index${candidate}`),
),
];
}
function findCycles(
modules: string[],
dependencies: DependencyEdge[],
moduleNames: Set<string>,
): string[][] {
const adjacency = new Map<string, string[]>(
modules.map((module) => [module, []]),
);
for (const dependency of dependencies) {
if (dependency.kind === "local" && moduleNames.has(dependency.target)) {
adjacency.get(dependency.source)?.push(dependency.target);
}
}
let nextIndex = 0;
const indexes = new Map<string, number>();
const lowLinks = new Map<string, number>();
const stack: string[] = [];
const onStack = new Set<string>();
const cycles: string[][] = [];
function connect(module: string): void {
indexes.set(module, nextIndex);
lowLinks.set(module, nextIndex);
nextIndex += 1;
stack.push(module);
onStack.add(module);
for (const target of adjacency.get(module) ?? []) {
if (!indexes.has(target)) {
connect(target);
lowLinks.set(
module,
Math.min(
requireMapValue(lowLinks, module),
requireMapValue(lowLinks, target),
),
);
} else if (onStack.has(target)) {
lowLinks.set(
module,
Math.min(
requireMapValue(lowLinks, module),
requireMapValue(indexes, target),
),
);
}
}
if (lowLinks.get(module) !== indexes.get(module)) {
return;
}
const component: string[] = [];
let member: string | undefined;
do {
member = stack.pop();
if (!member) break;
onStack.delete(member);
component.push(member);
} while (member !== module);
const firstComponent = component[0];
const selfCycle =
component.length === 1 &&
firstComponent !== undefined &&
adjacency.get(firstComponent)?.includes(firstComponent);
if (component.length > 1 || selfCycle) {
cycles.push(component.sort());
}
}
for (const module of modules) {
if (!indexes.has(module)) connect(module);
}
return cycles.sort((left, right) =>
(left[0] ?? "").localeCompare(right[0] ?? ""),
);
}
function requireMapValue<Key, Value>(map: Map<Key, Value>, key: Key): Value {
const value = map.get(key);
if (value === undefined) {
throw new Error("Architecture graph invariant failed");
}
return value;
}
function findArchitectureViolations(
dependencies: DependencyEdge[],
cycles: string[][],
typeOnlyEdges: ReadonlySet<string> = new Set(),
): ArchitectureViolation[] {
const violations: ArchitectureViolation[] = [];
for (const rule of architectureRules) {
if (rule.to?.circular) {
for (const cycle of cycles) {
violations.push({
rule: rule.name,
severity: rule.severity ?? "warn",
source: cycle[0] ?? "unknown-cycle-source",
target: cycle[1] ?? cycle[0] ?? "unknown-cycle-target",
cycle,
});
}
continue;
}
for (const dependency of dependencies) {
const sourceGroups = rule.from?.path
? (new RegExp(rule.from.path, "u").exec(dependency.source)?.slice(1) ??
[])
: [];
if (
rule.to?.dependencyTypesNot?.includes("type-only") &&
typeOnlyEdges.has(edgeKey(dependency.source, dependency.target))
) {
continue;
}
if (
matchesPath(dependency.source, rule.from) &&
matchesPath(dependency.target, rule.to, sourceGroups)
) {
violations.push({
rule: rule.name,
severity: rule.severity ?? "warn",
source: dependency.source,
target: dependency.target,
});
}
}
}
return violations.sort((left, right) =>
`${left.rule}:${left.source}:${left.target}`.localeCompare(
`${right.rule}:${right.source}:${right.target}`,
),
);
}
function matchesPath(
modulePath: string,
criterion: PathRule | undefined,
sourceGroups: readonly string[] = [],
): boolean {
if (!criterion) return true;
if (
criterion.path &&
!new RegExp(expandSourceGroups(criterion.path, sourceGroups), "u").test(
modulePath,
)
) {
return false;
}
return !(
criterion.pathNot &&
new RegExp(expandSourceGroups(criterion.pathNot, sourceGroups), "u").test(
modulePath,
)
);
}
/**
* Substitutes `$1`..`$9` in a `to` pattern with the capture groups the `from`
* pattern matched on the importing module.
*
* Without it, "an adapter may not import a *different* adapter" cannot be
* written as one rule: the target pattern has to name the importer's own
* directory to exempt it. The alternative is one rule per adapter group, which
* silently stops covering a group the moment somebody adds one — exactly the
* gap that let `diagnostics` import `telemetry` while the documented rule said
* it could not.
*/
function expandSourceGroups(
pattern: string,
sourceGroups: readonly string[],
): string {
return pattern.replaceAll(/\$([1-9])/gu, (whole, index: string) => {
const captured = sourceGroups[Number(index) - 1];
// A `from` pattern that did not capture leaves the token literal rather
// than quietly matching everything.
return captured === undefined ? whole : escapeRegExp(captured);
});
}
function escapeRegExp(value: string): string {
return value.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
}
function validateArchitectureRules(rules: readonly ArchitectureRule[]): void {
if (!rules.some((rule) => rule.to?.circular === true)) {
throw new Error("Architecture configuration must contain a circular rule");
}
for (const rule of rules) {
for (const key of Object.keys(rule.from ?? {})) {
if (key !== "path" && key !== "pathNot") {
throw new Error(`Unsupported architecture matcher from.${key} in ${rule.name}`);
}
}
for (const key of Object.keys(rule.to ?? {})) {
if (
key !== "path" &&
key !== "pathNot" &&
key !== "circular" &&
key !== "dependencyTypesNot"
) {
throw new Error(`Unsupported architecture matcher to.${key} in ${rule.name}`);
}
}
}
}
function blockingViolations(graph: SourceGraph): ArchitectureViolation[] {
return graph.violations.filter(({ severity }) => severity === "error");
}
async function runGraphFixtureChecks(): Promise<GraphFixtureResult> {
const fixtureRoot = resolve(
projectRoot,
"tests/fixtures/architecture/dependency-graph",
);
const allowedRoot = resolve(fixtureRoot, "allowed");
const [
allowedGraph,
unresolvedGraph,
layerGraph,
cycleGraph,
barrelGraph,
crossBoundaryGraph,
importBoundaryGraph,
kernelGraph,
typeOnlyGraph,
mixedImportsGraph,
] = await Promise.all([
analyzeSourceGraph(allowedRoot, "src"),
analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "cross-boundary"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "import-boundaries"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "kernel"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "type-only"), "src"),
analyzeSourceGraph(resolve(fixtureRoot, "mixed-imports"), "src"),
]);
const rejected = (
graph: SourceGraph,
rule: string,
source: string,
target: string,
) =>
blockingViolations(graph).some(
(violation) =>
violation.rule === rule &&
violation.source === source &&
violation.target === target,
);
const allowedFiles = new Set(await listFiles(allowedRoot));
const allowedSourceFile = resolve(
allowedRoot,
"application/read-value.ts",
);
const legacySpecifierRejections = [
"../domain/value.js",
"../domain/value.jsx",
"../domain/value.mjs",
"../domain/value.cjs",
].map((specifier) =>
resolveRelativeDependency(
allowedSourceFile,
specifier,
allowedRoot,
allowedFiles,
),
);
const assertions = [
{
name: "cross-feature concrete imports are rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "features-do-not-import-other-features" &&
source === "src/features/alpha/read-beta.ts" &&
target === "src/features/beta/value.ts",
),
},
{
name: "cross-context concrete imports are rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "contexts-do-not-import-other-contexts" &&
source === "src/contexts/customer/read-admin.ts" &&
target === "src/contexts/admin/value.ts",
),
},
{
name: "feature root re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "feature-and-app-roots-do-not-reach-adapters" &&
source === "src/features/alpha/telemetry.ts" &&
target === "src/adapters/telemetry/index.ts",
),
},
// 0929/12-03. A feature folder that is not a layer (support/) had no rule,
// so presentation reached the http adapter barrel through it with the
// graph and ESLint both passing.
{
name: "feature non-layer folder re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "feature-and-app-roots-do-not-reach-adapters" &&
source === "src/features/alpha/support/telemetry.ts" &&
target === "src/adapters/telemetry/index.ts",
),
},
{
name: "feature adapters folder import of a concrete adapter is accepted",
passed: !blockingViolations(crossBoundaryGraph).some(
({ source }) => source === "src/features/alpha/adapters/telemetry-sink.ts",
),
},
{
name: "context re-export of a concrete adapter is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "feature-and-app-roots-do-not-reach-adapters" &&
source === "src/contexts/customer/telemetry.ts" &&
target === "src/adapters/telemetry/index.ts",
),
},
{
name: "presentation import of a context is rejected",
passed: blockingViolations(crossBoundaryGraph).some(
({ rule, source, target }) =>
rule === "presentation-does-not-import-apps-or-contexts" &&
source === "src/presentation/read-context.ts" &&
target === "src/contexts/customer/telemetry.ts",
),
},
// 1112/02-01. The kernel rule (AGENTS.md rule 2) had no fixture: widening
// its pathNot or deleting it failed nothing.
{
name: "adapter import of another concrete adapter group is rejected",
passed: rejected(
kernelGraph,
"adapters-do-not-know-other-concrete-adapters",
"src/adapters/alpha/read-beta.ts",
"src/adapters/beta/value.ts",
),
},
{
name: "adapter import of browser-file-storage outside result.ts is rejected",
passed: rejected(
kernelGraph,
"adapters-do-not-know-other-concrete-adapters",
"src/adapters/alpha/read-storage-internals.ts",
"src/adapters/browser-file-storage/other.ts",
),
},
{
name: "adapter imports of the kernel set and its own group are accepted",
passed: !blockingViolations(kernelGraph).some(
({ source }) => source === "src/adapters/alpha/read-kernel.ts",
),
},
// 1112/02-02. Two exceptions wider than their use: routing could reach any
// of seven targets, the contribution file any adapter value.
{
name: "routing re-export of a concrete adapter is rejected",
passed: rejected(
crossBoundaryGraph,
"platform-kernel-is-product-neutral",
"src/platform/routing/reexport.ts",
"src/adapters/telemetry/index.ts",
),
},
{
name: "routing importing an app value is rejected",
passed: rejected(
crossBoundaryGraph,
"platform-routing-reads-app-types-only",
"src/platform/routing/import-app-value.ts",
"src/apps/app-value.ts",
),
},
{
name: "routing reading an app descriptor is accepted",
passed: !blockingViolations(crossBoundaryGraph).some(
({ source }) => source === "src/platform/routing/read-app.ts",
),
},
{
name: "platform outside routing reading an app is rejected",
passed: rejected(
crossBoundaryGraph,
"platform-kernel-does-not-know-apps-or-contexts",
"src/platform/read-app.ts",
"src/apps/app.ts",
),
},
{
name: "a value re-export of an adapter from the contribution file is rejected",
passed: rejected(
crossBoundaryGraph,
"feature-adapter-contribution-reads-adapter-types-only",
"src/features/feature-adapter-contribution.ts",
"src/adapters/telemetry/index.ts",
),
},
{
name: "a value import beside a type import of the same adapter file is rejected",
passed: rejected(
mixedImportsGraph,
"feature-adapter-contribution-reads-adapter-types-only",
"src/features/feature-adapter-contribution.ts",
"src/adapters/telemetry/index.ts",
),
},
{
name: "type-only adapter imports in the contribution file are accepted",
passed:
typeOnlyGraph.dependencies.some(
({ source }) => source === "src/features/feature-adapter-contribution.ts",
) &&
!blockingViolations(typeOnlyGraph).some(
({ source }) => source === "src/features/feature-adapter-contribution.ts",
),
},
// 1112/02-03. The unused named-exception check itself.
{
name: "a file named in from.pathNot with no forbidden edge is reported",
passed: (() => {
const rule: ArchitectureRule = {
name: "fixture-rule",
from: { path: "^src/", pathNot: "^src/pages/(named-page|other-page)\\.tsx$" },
to: { path: "^src/registry/" },
};
const graph = (dependencies: DependencyEdge[]): SourceGraph => ({
modules: ["src/pages/named-page.tsx", "src/registry/value.ts"],
dependencies,
unresolved: [],
parseFailures: [],
cycles: [],
violations: [],
});
const used: DependencyEdge = {
source: "src/pages/named-page.tsx",
target: "src/registry/value.ts",
specifier: "../registry/value.ts",
kind: "local",
};
return (
unusedFileExceptions(graph([]), [rule]).length === 1 &&
unusedFileExceptions(graph([used]), [rule]).length === 0
);
})(),
},
// 0929/12-03. The two-step path through a feature's own adapters/.
{
name: "feature non-layer folder import of its own adapters is rejected",
passed: rejected(
crossBoundaryGraph,
"feature-support-folders-do-not-reach-feature-adapters",
"src/features/alpha/support/gateway.ts",
"src/features/alpha/adapters/telemetry-sink.ts",
),
},
// 12-08 / 12-10: these import rules used to be regular expressions in
// check-design-system.ts and realtime-boundaries.ts beside the graph.
{
name: "design-system deep import is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source }) =>
rule === "design-system-is-reached-through-its-index" &&
source === "src/presentation/pages/deep-import.ts",
),
},
{
name: "design-system index and named facades are accepted",
passed: !blockingViolations(importBoundaryGraph).some(({ source }) =>
["src/presentation/pages/public-import.ts", "src/presentation/components/ui/button.ts"].includes(source),
),
},
{
name: "direct icon vendor import is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source, target }) =>
rule === "icon-vendor-is-facade-only" &&
source === "src/presentation/pages/direct-icon.ts" &&
target === "lucide-react",
),
},
// F-7 (13-08): zod must be configured jitless before any schema is built.
{
name: "direct zod import outside src/contracts/zod.ts is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source, target }) =>
rule === "zod-is-reached-through-contracts-zod" &&
source === "src/presentation/pages/direct-zod.ts" &&
target === "zod",
),
},
{
name: "zod subpath import outside src/contracts/zod.ts is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source, target }) =>
rule === "zod-is-reached-through-contracts-zod" &&
source === "src/presentation/pages/subpath-zod.ts" &&
target === "zod/v4",
),
},
{
name: "zod through src/contracts/zod.ts is accepted",
passed: !blockingViolations(importBoundaryGraph).some(({ source }) =>
["src/contracts/zod.ts", "src/presentation/pages/wrapped-zod.ts"].includes(source),
),
},
{
name: "unselected realtime runtime composition is rejected",
passed: blockingViolations(importBoundaryGraph).some(
({ rule, source }) =>
rule === "unselected-realtime-runtime-is-not-composed" &&
source === "src/bootstrap/compose-realtime.ts",
),
},
{
name: "deep adapter import from outside the group is rejected",
passed: blockingViolations(barrelGraph).some(
({ rule, source, target }) =>
rule === "adapter-groups-are-reached-through-their-barrel" &&
source === "src/bootstrap/compose-deep.ts" &&
target === "src/adapters/http/client.ts",
),
},
{
name: "second-level index import from outside the group is rejected",
passed: blockingViolations(barrelGraph).some(
({ rule, source, target }) =>
rule === "adapter-groups-are-reached-through-their-barrel" &&
source === "src/bootstrap/compose-sub-barrel.ts" &&
target === "src/adapters/http/internals/index.ts",
),
},
{
name: "storage runtime sub-barrel import is accepted",
passed: !blockingViolations(barrelGraph).some(
({ source }) => source === "src/bootstrap/compose-storage-sub-barrel.ts",
),
},
{
name: "barrel import from outside the group is accepted",
passed: !blockingViolations(barrelGraph).some(
({ source }) => source === "src/bootstrap/compose-barrel.ts",
),
},
{
name: "explicit TS specifier resolves to a TS module",
passed: allowedGraph.dependencies.some(
({ source, target, specifier }) =>
source === "src/application/read-value.ts" &&
target === "src/domain/value.ts" &&
specifier === "../domain/value.ts",
),
},
{
name: "local JavaScript-family specifiers are rejected",
passed: legacySpecifierRejections.every(
({ path, reason }) =>
path === undefined &&
reason === forbiddenLocalJavaScriptSpecifierReason,
),
},
{
name: "TSX modules are included",
passed: allowedGraph.modules.includes("src/presentation/value-view.tsx"),
},
{
name: "allowed graph has no blocking findings",
passed:
allowedGraph.unresolved.length === 0 &&
allowedGraph.parseFailures.length === 0 &&
blockingViolations(allowedGraph).length === 0,
},
{
name: "unresolved relative imports are rejected",
passed: unresolvedGraph.unresolved.some(
({ specifier }) => specifier === "../domain/missing-value.ts",
),
},
{
name: "unresolved package imports are rejected",
passed: unresolvedGraph.unresolved.some(
({ specifier }) =>
specifier === "architecture-fixture-package-that-does-not-exist",
),
},
{
name: "unresolved absolute imports are rejected",
passed: unresolvedGraph.unresolved.some(
({ specifier }) =>
specifier === "/definitely-missing-architecture-fixture.ts",
),
},
{
name: "unresolved file URL imports are rejected",
passed: unresolvedGraph.unresolved.some(
({ specifier }) =>
specifier === "file:///definitely-missing-architecture-fixture.ts",
),
},
{
name: "non-literal dynamic imports are rejected",
passed: unresolvedGraph.parseFailures.some(
({ source, reason }) =>
source === "src/application/load-value.ts" &&
reason.includes("import()"),
),
},
{
name: "import.meta.glob module loads are rejected",
passed: unresolvedGraph.parseFailures.some(
({ source, reason }) =>
source === "src/application/glob-value.ts" &&
reason.includes("import.meta.glob"),
),
},
{
name: "non-literal CommonJS imports are rejected",
passed: unresolvedGraph.parseFailures.some(
({ source, reason }) =>
source === "src/application/require-value.ts" &&
reason.includes("require()"),
),
},
{
name: "TypeScript layer violations are rejected",
passed: blockingViolations(layerGraph).some(
({ rule }) => rule === "application-does-not-know-concrete-runtime",
),
},
{
name: "TypeScript cycles are rejected",
passed: blockingViolations(cycleGraph).some(
({ rule }) => rule === "no-circular-dependencies",
),
},
];
return {
passed: assertions.every(({ passed }) => passed),
checks: assertions.map(({ name }) => name),
failures: assertions.filter(({ passed }) => !passed).map(({ name }) => name),
};
}
async function inspectTypeScriptOnlyPolicy(): Promise<TypeScriptOnlyPolicy> {
// The typescript-only set of config/repository-layout.json (R2). An optional
// root (recipes/) may be gone after a removal drill.
const selected = selectRepositoryEntries("typescript-only");
const requiredRoots = selected.filter(({ optional }) => !optional).map(({ path }) => path);
const optionalRoots = selected.filter(({ optional }) => optional).map(({ path }) => path);
const checkedRoots = [...requiredRoots, ...optionalRoots];
const files = (
await Promise.all(
[
...requiredRoots.map((root) =>
listFiles(resolve(projectRoot, root)),
),
...optionalRoots.map((root) =>
listOptionalFiles(resolve(projectRoot, root)),
),
],
)
).flat();
const rootEntries = await readdir(projectRoot, { withFileTypes: true });
const rootConfigFiles = rootEntries
.filter(
(entry) =>
entry.isFile() &&
/\.config\.(?:js|jsx|mjs|cjs)$/u.test(entry.name),
)
.map((entry) => resolve(projectRoot, entry.name));
const candidates = [...files, ...rootConfigFiles]
.filter((file) => forbiddenJavaScriptExtensionPattern.test(file))
.map((file) => reportPath(file, projectRoot, ""))
.sort();
const violations = candidates;
return {
checkedRoots,
exceptionsAllowed: false,
violations,
passed: violations.length === 0,
};
}
async function listOptionalFiles(directory: string): Promise<string[]> {
try {
return await listFiles(directory);
} catch (error) {
if (hasErrorCode(error, "ENOENT")) {
return [];
}
throw error;
}
}
function hasErrorCode(error: unknown, code: string): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
error.code === code
);
}
async function listFiles(directory: string): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true });
const files = await Promise.all(
entries.map((entry) => {
const target = resolve(directory, entry.name);
return entry.isDirectory() ? listFiles(target) : [target];
}),
);
return files.flat().sort();
}
function reportPath(
file: string,
rootDirectory: string,
prefix: string,
): string {
const childPath = relative(rootDirectory, file).split(sep).join("/");
return prefix ? `${prefix}/${childPath}` : childPath;
}
function compareDependencies(
left: DependencyEdge,
right: DependencyEdge,
): number {
return `${left.source}:${left.target}:${left.specifier}`.localeCompare(
`${right.source}:${right.target}:${right.specifier}`,
);
}
function compareSourceAndSpecifier(
left: Pick<UnresolvedDependency, "source" | "specifier">,
right: Pick<UnresolvedDependency, "source" | "specifier">,
): number {
return `${left.source}:${left.specifier}`.localeCompare(
`${right.source}:${right.specifier}`,
);
}
function parseArchitectureConfig(value: unknown): ArchitectureConfig {
if (!isRecord(value)) {
throw new TypeError(".dependency-cruiser.json must contain an object");
}
const forbidden = value.forbidden ?? [];
const allowed = value.allowed ?? [];
const required = value.required ?? [];
if (!Array.isArray(forbidden) || !forbidden.every(isArchitectureRule)) {
throw new TypeError(
".dependency-cruiser.json forbidden rules have an invalid shape",
);
}
if (!Array.isArray(allowed) || !Array.isArray(required)) {
throw new TypeError(
".dependency-cruiser.json allowed/required must be arrays",
);
}
return { forbidden, allowed, required };
}
function isArchitectureRule(value: unknown): value is ArchitectureRule {
if (!isRecord(value) || typeof value.name !== "string") return false;
if (value.comment !== undefined && typeof value.comment !== "string") return false;
if (value.severity !== undefined && typeof value.severity !== "string") {
return false;
}
return (
(value.from === undefined || isPathRule(value.from, false)) &&
(value.to === undefined || isPathRule(value.to, true))
);
}
function isPathRule(value: unknown, allowCircular: boolean): value is PathRule {
if (!isRecord(value)) return false;
if (value.path !== undefined && typeof value.path !== "string") return false;
if (value.pathNot !== undefined && typeof value.pathNot !== "string") {
return false;
}
if (
value.dependencyTypesNot !== undefined &&
!(
Array.isArray(value.dependencyTypesNot) &&
value.dependencyTypesNot.every((type: unknown) => type === "type-only")
)
) {
return false;
}
return (
!allowCircular ||
value.circular === undefined ||
typeof value.circular === "boolean"
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}