241 lines
11 KiB
TypeScript
241 lines
11 KiB
TypeScript
import { describe, expect, test } from "bun:test";
|
|
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
import { dirname, join, relative, resolve } from "node:path";
|
|
import ts from "typescript";
|
|
|
|
const SRC_ROOT = join(import.meta.dir, "..");
|
|
|
|
function collectTsFiles(dir: string, includeTests = false): string[] {
|
|
const results: string[] = [];
|
|
for (const entry of readdirSync(dir)) {
|
|
const full = join(dir, entry);
|
|
const stat = statSync(full);
|
|
if (stat.isDirectory()) {
|
|
results.push(...collectTsFiles(full, includeTests));
|
|
} else if (full.endsWith(".ts") && (includeTests || !full.endsWith(".test.ts"))) {
|
|
results.push(full);
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
function extractImportSpecifiers(source: string): string[] {
|
|
const specifiers: string[] = [];
|
|
const ast = ts.createSourceFile("boundary.ts", source, ts.ScriptTarget.Latest, true);
|
|
const visit = (node: ts.Node) => {
|
|
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text);
|
|
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) specifiers.push(node.arguments[0].text);
|
|
if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) specifiers.push(node.argument.literal.text);
|
|
ts.forEachChild(node, visit);
|
|
};
|
|
visit(ast);
|
|
return specifiers;
|
|
}
|
|
|
|
function resolveImportRelativeToSrc(fromFile: string, specifier: string): string | null {
|
|
const path = specifier.startsWith(".") ? resolve(dirname(fromFile), specifier)
|
|
: specifier.startsWith("@core/") ? join(SRC_ROOT, "core", specifier.slice(6))
|
|
: specifier.startsWith("@domains/") ? join(SRC_ROOT, "domains", specifier.slice(9)) : undefined;
|
|
return path ? relative(SRC_ROOT, path.replace(/\.[jt]s$/, "")).replaceAll("\\", "/") : null;
|
|
}
|
|
|
|
function platformModule(path: string): string | undefined {
|
|
return path.match(/^domains\/platform\/(applications|datalink|workflow)\//)?.[1];
|
|
}
|
|
|
|
function platformDependencyViolation(from: string, to: string): boolean {
|
|
const source = platformModule(from), target = platformModule(to);
|
|
if (!source || !target || source === target) return false;
|
|
return /\/api$/.test(to) || source === "applications" || (source === "datalink" && target === "workflow");
|
|
}
|
|
|
|
function findCycles(graph: Map<string, Set<string>>): string[][] {
|
|
const done = new Set<string>(), active: string[] = [], cycles: string[][] = [];
|
|
const visit = (node: string) => {
|
|
const index = active.indexOf(node);
|
|
if (index >= 0) { cycles.push([...active.slice(index), node]); return; }
|
|
if (done.has(node)) return;
|
|
active.push(node);
|
|
for (const next of graph.get(node) ?? []) visit(next);
|
|
active.pop(); done.add(node);
|
|
};
|
|
for (const node of graph.keys()) visit(node);
|
|
return cycles;
|
|
}
|
|
|
|
describe("Architecture Layering Boundaries", () => {
|
|
test("dependency extraction covers aliases, re-exports and literal dynamic/type imports", () => {
|
|
const imports = extractImportSpecifiers(`
|
|
import { x } from "@core/errors.js";
|
|
export { y } from "@domains/bill/api.js";
|
|
const z = import("../domains/bill/api.js");
|
|
type T = import("@domains/bill/types.js").FormSpecification;
|
|
const text = 'import("not-a-real-import")';
|
|
`);
|
|
expect(imports).toEqual(["@core/errors.js", "@domains/bill/api.js", "../domains/bill/api.js", "@domains/bill/types.js"]);
|
|
expect(resolveImportRelativeToSrc(join(SRC_ROOT, "cli", "example.ts"), imports[1])).toBe("domains/bill/api");
|
|
});
|
|
|
|
test("nested APIs and platform dependency directions cannot bypass boundaries", () => {
|
|
const api = /^domains\/(?:[^/]+\/)+api$/;
|
|
expect(api.test("domains/platform/workflow/api")).toBe(true);
|
|
expect(api.test("domains/platform/workflow/transport/pipeline/api")).toBe(true);
|
|
expect(api.test("domains/platform/workflow/transport/execution/api")).toBe(true);
|
|
expect(api.test("domains/bill/api")).toBe(true);
|
|
expect(api.test("domains/platform/workflow/services")).toBe(false);
|
|
expect(platformDependencyViolation("domains/platform/workflow/services", "domains/platform/applications/services")).toBe(false);
|
|
expect(platformDependencyViolation("domains/platform/workflow/services", "domains/platform/applications/api")).toBe(true);
|
|
expect(platformDependencyViolation("domains/platform/datalink/services", "domains/platform/workflow/transport/catalog/api")).toBe(true);
|
|
expect(platformDependencyViolation("domains/platform/applications/types", "domains/platform/datalink/types")).toBe(true);
|
|
expect(platformDependencyViolation("domains/platform/datalink/services", "domains/platform/workflow/services")).toBe(true);
|
|
expect(findCycles(new Map([["a", new Set(["b"])], ["b", new Set(["a"])]]))).toEqual([["a", "b", "a"]]);
|
|
expect(findCycles(new Map([["a", new Set(["b"])], ["b", new Set<string>()]]))).toEqual([]);
|
|
});
|
|
|
|
test("platform submodules respect ownership and have no cross-module cycles", () => {
|
|
const graph = new Map<string, Set<string>>(), fileGraph = new Map<string, Set<string>>(), violations: string[] = [];
|
|
for (const file of collectTsFiles(join(SRC_ROOT, "domains", "platform"))) {
|
|
const from = relative(SRC_ROOT, file).replaceAll("\\", "/").replace(/\.ts$/, "");
|
|
const source = platformModule(from);
|
|
fileGraph.set(from, new Set());
|
|
for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) {
|
|
const target = resolveImportRelativeToSrc(file, specifier);
|
|
if (!target) continue;
|
|
if (target.startsWith("domains/platform/")) fileGraph.get(from)!.add(target);
|
|
if (platformDependencyViolation(from, target)) violations.push(`${from} -> ${target}`);
|
|
const destination = platformModule(target);
|
|
if (source && destination && source !== destination) {
|
|
if (!graph.has(source)) graph.set(source, new Set());
|
|
graph.get(source)!.add(destination);
|
|
}
|
|
}
|
|
}
|
|
expect(violations).toEqual([]);
|
|
expect(findCycles(graph)).toEqual([]);
|
|
expect(findCycles(fileGraph)).toEqual([]);
|
|
});
|
|
|
|
test("bill Session HTTP calls stay in the transport module", () => {
|
|
const violations: string[] = [];
|
|
for (const file of collectTsFiles(join(SRC_ROOT, "domains", "bill"))) {
|
|
if (file.endsWith("api.ts")) continue;
|
|
const source = readFileSync(file, "utf8");
|
|
const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
|
|
const visit = (node: ts.Node) => {
|
|
if (ts.isCallExpression(node)) {
|
|
const expr = node.expression;
|
|
const receiver = ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr) ? expr.expression.getText(ast) : "";
|
|
const method = ts.isPropertyAccessExpression(expr) ? expr.name.text
|
|
: ts.isElementAccessExpression(expr) && ts.isStringLiteral(expr.argumentExpression) ? expr.argumentExpression.text : "";
|
|
if (/client|^ky$/i.test(receiver) && ["get", "post", "put", "patch", "delete"].includes(method)) {
|
|
violations.push(`${relative(SRC_ROOT, file)}:${ast.getLineAndCharacterOfPosition(node.getStart(ast)).line + 1}`);
|
|
}
|
|
}
|
|
ts.forEachChild(node, visit);
|
|
};
|
|
visit(ast);
|
|
}
|
|
expect(violations).toEqual([]);
|
|
});
|
|
test("platform imports use owned submodules and reject retired private paths", () => {
|
|
const legacy = /^(?:domains\/datalink(?:\/|$)|domains\/platform\/(?:api|services|types|execution-context|analysis|workflow-(?:alert-store|branch|nodes|script|state|watch))$)/;
|
|
const violations: string[] = [];
|
|
for (const file of collectTsFiles(SRC_ROOT, true)) {
|
|
for (const specifier of extractImportSpecifiers(readFileSync(file, "utf8"))) {
|
|
const target = resolveImportRelativeToSrc(file, specifier);
|
|
if (target && legacy.test(target)) violations.push(`${relative(SRC_ROOT, file)} -> ${target}`);
|
|
}
|
|
}
|
|
expect(violations).toEqual([]);
|
|
});
|
|
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/**/api directly", () => {
|
|
const entrypointFiles = [
|
|
...collectTsFiles(join(SRC_ROOT, "cli")),
|
|
...collectTsFiles(join(SRC_ROOT, "http")),
|
|
join(SRC_ROOT, "server.ts"),
|
|
join(SRC_ROOT, "cli.ts"),
|
|
join(SRC_ROOT, "aipro-cli.ts"),
|
|
];
|
|
|
|
const violations: string[] = [];
|
|
for (const file of entrypointFiles) {
|
|
const content = readFileSync(file, "utf8");
|
|
const specifiers = extractImportSpecifiers(content);
|
|
for (const spec of specifiers) {
|
|
const targetRel = resolveImportRelativeToSrc(file, spec);
|
|
if (targetRel && /^domains\/(?:[^/]+\/)+api$/.test(targetRel)) {
|
|
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
expect(violations).toEqual([]);
|
|
});
|
|
|
|
test("src/domains/ must remain pure SDK and never import from cli, http, or server entrypoints", () => {
|
|
const domainFiles = collectTsFiles(join(SRC_ROOT, "domains"));
|
|
const violations: string[] = [];
|
|
|
|
for (const file of domainFiles) {
|
|
const content = readFileSync(file, "utf8");
|
|
const specifiers = extractImportSpecifiers(content);
|
|
for (const spec of specifiers) {
|
|
const targetRel = resolveImportRelativeToSrc(file, spec);
|
|
if (
|
|
targetRel &&
|
|
(targetRel.startsWith("cli/") ||
|
|
targetRel.startsWith("http/") ||
|
|
targetRel === "server" ||
|
|
targetRel === "cli" ||
|
|
targetRel === "aipro-cli")
|
|
) {
|
|
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
expect(violations).toEqual([]);
|
|
});
|
|
|
|
test("src/core/ must never depend upward on domains, cli, http, or server entrypoints", () => {
|
|
const coreFiles = collectTsFiles(join(SRC_ROOT, "core"));
|
|
const violations: string[] = [];
|
|
|
|
for (const file of coreFiles) {
|
|
const content = readFileSync(file, "utf8");
|
|
const specifiers = extractImportSpecifiers(content);
|
|
for (const spec of specifiers) {
|
|
const targetRel = resolveImportRelativeToSrc(file, spec);
|
|
if (
|
|
targetRel &&
|
|
(targetRel.startsWith("domains/") ||
|
|
targetRel.startsWith("cli/") ||
|
|
targetRel.startsWith("http/") ||
|
|
targetRel === "server" ||
|
|
targetRel === "cli" ||
|
|
targetRel === "aipro-cli")
|
|
) {
|
|
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
expect(violations).toEqual([]);
|
|
});
|
|
|
|
test("src/core/ must only contain whitelisted infrastructure modules", () => {
|
|
const allowedTopLevel = new Set([
|
|
"README.core.md",
|
|
"auth",
|
|
"cache",
|
|
"config",
|
|
"db",
|
|
"errors.ts",
|
|
"http",
|
|
]);
|
|
const entries = readdirSync(join(SRC_ROOT, "core"));
|
|
const unexpected = entries.filter((entry) => !allowedTopLevel.has(entry));
|
|
expect(unexpected).toEqual([]);
|
|
});
|
|
});
|