루트 항목 하나를 옮기려면 코드 7곳의 루트 경로 목록을 같이 고쳐야 했다(복사 대상, 비밀값 검사 범위, 공급망 시험의 필수 입력, 이력 문서 검사, 규모 입력, vite 입력, TS 전용 규칙). 서로 다른 부분집합이고 한 곳에서 선언하지 않았다. 목록이 갈라져 공급망 생성이 깨진 적도 있다 (removal-fixture.ts 주석). 루트에는 JSON Schema 5개만 담은 `schemas/`가 `config/` 옆에 따로 있었다. `artifacts/`(출력 폴더)에는 사람이 쓴 수동 a11y 기록이, `config/hosting/`(호스트 계약)에는 시험 fixture가 섞였다. 고른 방법(design-docs repo-structure/04-frontend-layout.md 9.2절 3단계, 11절 R1·R2, 소유자 승인 2026-11-07): - `config/repository-layout.json`이 루트 항목마다 종류·역할·읽는 곳과 들어가는 목록(`sets`, 항목 안 경로는 `setPaths`)을 적는다. `scripts/lib/repository-layout.ts`가 읽고 검증한다. 6곳은 이름 붙은 집합을 고른다. JSON인 비밀값 검사 정책은 집합의 사본을 두고 시험이 같은지 본다(정책 파일은 릴리스 후보에 실려 형식을 바꾸지 않았다). 공급망 시험의 필수 입력 목록은 그 시험으로 대신한다. - `tests/unit/repository-layout.test.ts`: 등록부에 없는 루트 항목이 추적되면 실패(R1). 7곳이 등록부 모듈을 쓰고 루트 이름 둘 이상의 문자열 배열을 갖지 않는지(R2). - `schemas/artifacts/` → `config/schemas/artifacts/`, recipe 카탈로그 스키마 → `config/schemas/recipes/`. 정책 입력 순서(ASCII)에 맞춰 `config/schemas/`가 `config/security/` 앞에 온다. - 수동 a11y 기록 3개 → `docs/accessibility/route-reviews/`. `artifacts/`는 `.gitkeep`만 추적한다. 기록은 단위 시험이 읽어서 drill 사본에도 복사한다(`fixture-copy` 집합의 `docs/accessibility/route-reviews`). - `config/hosting/response-headers.fixture.json` → `tests/fixtures/hosting/response-headers.json`. 버린 것: 비밀값 검사 정책이 집합 이름을 참조하게 바꾸는 방법. 정책 파일은 릴리스 후보와 로컬 증거 평가가 읽는 형식이라 바꾸면 릴리스 증거 계약이 바뀐다. 루트 항목이 지워졌는데 등록부에 남는 경우는 시험하지 않았다. drill 사본은 일부만 복사해 그 방향을 볼 수 없다. 그런 항목은 그 집합을 쓰는 곳(복사, 비밀값 검사)에서 실패한다. 위험: 하네스 작업(fe-c)이 더할 `AGENTS.md`·`.claude/`를 미리 등록했다 (optional). 등록부가 이력 문서(`SPEC.md`)와 `CLAUDE.md` 이름을 적어서 이력 문서 검사에서 등록부 파일은 뺐다. 다운스트림은 자기 루트 항목을 등록부에 더해야 한다(CHANGELOG). CI 계약 기준선을 다시 받았다(a11y 기록 산출물 id·경로). 검증(desktop): 아래 4단계 커밋까지 쌓은 트리에서 test:unit, check:types, check:ci, lint, verify:documentation을 돌렸다(그 커밋에 적음). 이 커밋 단독으로 test:unit·check:ci·check:types를 돌렸다. Refs: design-docs repo-structure/04-frontend-layout.md 2.4·9.2·11절, README.md 3.4절
1193 lines
38 KiB
TypeScript
1193 lines
38 KiB
TypeScript
import { parseAsync } from "@babel/core";
|
|
import { mkdir, readFile, readdir } from "node:fs/promises";
|
|
import { 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 }>;
|
|
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,
|
|
),
|
|
);
|
|
}
|
|
|
|
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[] = [];
|
|
const unresolved: UnresolvedDependency[] = [];
|
|
const parseFailures: ParseFailure[] = [];
|
|
|
|
for (const sourceFile of sourceFiles) {
|
|
const source = reportPath(sourceFile, rootDirectory, reportPrefix);
|
|
let specifiers: string[];
|
|
try {
|
|
specifiers = 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;
|
|
}
|
|
dependencies.push({
|
|
source,
|
|
target: reportPath(resolution.path, rootDirectory, reportPrefix),
|
|
specifier,
|
|
kind: "local",
|
|
});
|
|
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) {
|
|
dependencies.push({
|
|
source,
|
|
target: reportPath(resolvedSource, rootDirectory, reportPrefix),
|
|
specifier,
|
|
kind: "local",
|
|
});
|
|
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),
|
|
};
|
|
}
|
|
|
|
async function importSpecifiers(sourceFile: string): Promise<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 nonLiteralModuleLoads = new Set<string>();
|
|
visitSyntaxNode(syntaxTree, specifiers, nonLiteralModuleLoads);
|
|
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].sort();
|
|
}
|
|
|
|
function visitSyntaxNode(
|
|
value: unknown,
|
|
specifiers: Set<string>,
|
|
nonLiteralModuleLoads: Set<string>,
|
|
): void {
|
|
if (Array.isArray(value)) {
|
|
for (const child of value) {
|
|
visitSyntaxNode(child, specifiers, nonLiteralModuleLoads);
|
|
}
|
|
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"
|
|
) {
|
|
addStringLiteral(node.source, specifiers);
|
|
} else if (nodeType === "ImportExpression") {
|
|
if (!addStringLiteral(node.source, specifiers)) {
|
|
nonLiteralModuleLoads.add("import()");
|
|
}
|
|
} 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 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 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);
|
|
} 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);
|
|
}
|
|
}
|
|
|
|
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[][],
|
|
): 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 (
|
|
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") {
|
|
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,
|
|
] = 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"),
|
|
]);
|
|
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",
|
|
),
|
|
},
|
|
// 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;
|
|
}
|
|
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));
|
|
}
|