@codefast/cli 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -0
- package/README.md +124 -40
- package/dist/arrange/simplify/variant-classname-probe.js +2 -11
- package/dist/audit/command.js +57 -16
- package/dist/audit/comments/domain/comment-content.d.ts +12 -0
- package/dist/audit/comments/domain/comment-content.js +17 -4
- package/dist/audit/comments/domain/comment-dividers.js +8 -1
- package/dist/audit/display-names/domain/display-names.js +4 -3
- package/dist/audit/domain/types.d.ts +119 -24
- package/dist/audit/engines/cli-result.d.ts +13 -0
- package/dist/audit/engines/cli-result.js +22 -0
- package/dist/audit/engines/cli-schema.d.ts +18 -0
- package/dist/audit/{constants → engines}/cli-schema.js +3 -3
- package/dist/audit/engines/domain/node-floor.d.ts +34 -0
- package/dist/audit/engines/domain/node-floor.js +40 -0
- package/dist/audit/engines/domain/range-gaps.d.ts +21 -0
- package/dist/audit/engines/domain/range-gaps.js +136 -0
- package/dist/audit/engines/output.d.ts +7 -0
- package/dist/audit/engines/output.js +40 -0
- package/dist/audit/engines/prepare.d.ts +16 -0
- package/dist/audit/engines/prepare.js +12 -0
- package/dist/audit/engines/run.d.ts +18 -0
- package/dist/audit/engines/run.js +225 -0
- package/dist/audit/layers/cli-result.d.ts +13 -0
- package/dist/audit/{constants → layers}/cli-result.js +6 -6
- package/dist/audit/layers/cli-schema.d.ts +29 -0
- package/dist/audit/layers/cli-schema.js +17 -0
- package/dist/audit/layers/domain/layering.d.ts +46 -0
- package/dist/audit/layers/domain/layering.js +191 -0
- package/dist/audit/layers/output.d.ts +7 -0
- package/dist/audit/layers/output.js +21 -0
- package/dist/audit/layers/prepare.d.ts +25 -0
- package/dist/audit/layers/prepare.js +66 -0
- package/dist/audit/layers/run.d.ts +19 -0
- package/dist/audit/layers/run.js +62 -0
- package/dist/audit/prepare.d.ts +13 -1
- package/dist/audit/prepare.js +16 -1
- package/dist/audit/props/cli-result.d.ts +13 -0
- package/dist/audit/props/cli-result.js +22 -0
- package/dist/audit/props/cli-schema.d.ts +18 -0
- package/dist/audit/props/cli-schema.js +12 -0
- package/dist/audit/props/domain/props-intersection.d.ts +56 -0
- package/dist/audit/props/domain/props-intersection.js +189 -0
- package/dist/audit/props/output.d.ts +7 -0
- package/dist/audit/{constants → props}/output.js +5 -5
- package/dist/audit/props/prepare.d.ts +13 -0
- package/dist/audit/props/prepare.js +9 -0
- package/dist/audit/props/run.d.ts +17 -0
- package/dist/audit/props/run.js +57 -0
- package/dist/audit/props/type-probe.d.ts +23 -0
- package/dist/audit/props/type-probe.js +85 -0
- package/dist/core/config/schema.d.ts +13 -4
- package/dist/core/config/schema.js +14 -1
- package/dist/core/type-server.d.ts +21 -0
- package/dist/core/type-server.js +32 -0
- package/dist/tag/cli-result.d.ts +3 -0
- package/dist/tag/cli-result.js +8 -2
- package/dist/tag/domain/types.d.ts +15 -0
- package/dist/tag/output.js +13 -6
- package/dist/tag/run.js +2 -0
- package/dist/tag/writer/since-writer.d.ts +5 -0
- package/dist/tag/writer/since-writer.js +41 -9
- package/package.json +6 -5
- package/dist/audit/constants/cli-result.d.ts +0 -13
- package/dist/audit/constants/cli-schema.d.ts +0 -18
- package/dist/audit/constants/domain/constants.d.ts +0 -8
- package/dist/audit/constants/domain/constants.js +0 -66
- package/dist/audit/constants/output.d.ts +0 -7
- package/dist/audit/constants/prepare.d.ts +0 -16
- package/dist/audit/constants/prepare.js +0 -37
- package/dist/audit/constants/run.d.ts +0 -14
- package/dist/audit/constants/run.js +0 -64
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { satisfies } from "semver";
|
|
3
|
+
import { parseAllDocuments } from "yaml";
|
|
4
|
+
import { formatNodeVersion, parseNodeFloor, parseNodeVersion, typesFitFloor } from "#audit/engines/domain/node-floor";
|
|
5
|
+
import { shortLivedMajors, uncoveredNodeRanges } from "#audit/engines/domain/range-gaps";
|
|
6
|
+
import { AppError, messageFrom } from "#core/errors";
|
|
7
|
+
import { err, ok } from "#core/result";
|
|
8
|
+
import { listWorkspacePackageDirectories } from "#core/workspace/resolver";
|
|
9
|
+
import { packageJsonFileName } from "#core/workspace/well-known-files";
|
|
10
|
+
const lockfileName = "pnpm-lock.yaml";
|
|
11
|
+
// The Node release CI develops and runs every package's tests on, besides each package's own floor.
|
|
12
|
+
const nodeVersionFileName = ".node-version";
|
|
13
|
+
const typesPackageName = "@types/node";
|
|
14
|
+
// Runtime fields are what a consumer installs on every release the floor claims; dev dependencies run the package's
|
|
15
|
+
// own tests, which CI runs on the floor and on the newest line.
|
|
16
|
+
const dependencyFields = ["dependencies", "peerDependencies", "optionalDependencies", "devDependencies"];
|
|
17
|
+
const testFields = new Set(["devDependencies"]);
|
|
18
|
+
const lockfileDependencyFields = ["dependencies", "devDependencies", "optionalDependencies"];
|
|
19
|
+
/**
|
|
20
|
+
* Reports every Node floor that breaks a rule a consumer or CI depends on.
|
|
21
|
+
*
|
|
22
|
+
* @remarks A published package declares a floor as `>=X.Y.Z`. The `engines.node` of every runtime dependency must
|
|
23
|
+
* admit every release from the floor up, short-lived odd lines aside; that of every dev dependency, the floor and the
|
|
24
|
+
* newest release CI tests on. The `@types/node` the lockfile resolves must declare nothing the floor lacks. The
|
|
25
|
+
* workspace root's floor, never listed among `floors`, must be admitted by every dependency any package installs.
|
|
26
|
+
*
|
|
27
|
+
* @since 0.15.0
|
|
28
|
+
*/
|
|
29
|
+
export async function runEnginesAudit(fs, args) {
|
|
30
|
+
try {
|
|
31
|
+
const { rootDir, targetPath } = args;
|
|
32
|
+
const layout = await listWorkspacePackageDirectories(rootDir, fs, true);
|
|
33
|
+
const manifests = [];
|
|
34
|
+
for (const packageDir of layout.packageDirectoryPathsAbsolute) {
|
|
35
|
+
const manifest = readManifest(fs, packageDir);
|
|
36
|
+
if (manifest === null) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const directory = toPosixPath(path.relative(rootDir, packageDir)) || ".";
|
|
40
|
+
manifests.push({
|
|
41
|
+
packageName: typeof manifest.name === "string" ? manifest.name : directory,
|
|
42
|
+
packageDir,
|
|
43
|
+
directory,
|
|
44
|
+
manifest,
|
|
45
|
+
checked: isWithin(packageDir, targetPath) || isWithin(targetPath, packageDir),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
manifests.sort((left, right) => left.directory.localeCompare(right.directory));
|
|
49
|
+
const workspaceManifests = new Map(manifests.map((entry) => [entry.packageName, entry.manifest]));
|
|
50
|
+
const typesVersions = readLockfileTypesVersions(fs, rootDir);
|
|
51
|
+
const testedNewest = readNodeVersion(fs, rootDir);
|
|
52
|
+
const floors = [];
|
|
53
|
+
const violations = [];
|
|
54
|
+
const checked = manifests.filter((entry) => entry.checked);
|
|
55
|
+
for (const { packageName, packageDir, directory, manifest } of checked) {
|
|
56
|
+
const range = nodeRangeOf(manifest);
|
|
57
|
+
if (range === undefined) {
|
|
58
|
+
if (manifest.private !== true) {
|
|
59
|
+
violations.push({ kind: "missing-floor", packageName });
|
|
60
|
+
}
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const floor = parseNodeFloor(range);
|
|
64
|
+
if (floor === null) {
|
|
65
|
+
violations.push({ kind: "unparsable-floor", packageName, range });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const formatted = formatNodeVersion(floor);
|
|
69
|
+
floors.push({ packageName, directory, floor: formatted });
|
|
70
|
+
const unjudgedMajors = shortLivedMajors(floor, testedNewest);
|
|
71
|
+
const tested = [formatted, ...(testedNewest === null ? [] : [formatNodeVersion(testedNewest)])];
|
|
72
|
+
for (const { dependency, field } of dependenciesOf(manifest)) {
|
|
73
|
+
const dependencyManifest = workspaceManifests.get(dependency) ?? readInstalledManifest(fs, packageDir, dependency);
|
|
74
|
+
const dependencyRange = dependencyManifest === null ? undefined : nodeRangeOf(dependencyManifest);
|
|
75
|
+
// A range no semver parser reads cannot be judged, so it passes rather than guessing.
|
|
76
|
+
const gaps = dependencyRange === undefined ? null : uncoveredNodeRanges(floor, dependencyRange, unjudgedMajors);
|
|
77
|
+
if (dependencyRange === undefined || gaps === null) {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const uncovered = testFields.has(field)
|
|
81
|
+
? gaps.filter((gap) => tested.some((version) => satisfies(version, gap)))
|
|
82
|
+
: gaps;
|
|
83
|
+
if (uncovered.length > 0) {
|
|
84
|
+
violations.push({
|
|
85
|
+
kind: "outside-dependency-engines",
|
|
86
|
+
packageName,
|
|
87
|
+
floor: formatted,
|
|
88
|
+
dependency,
|
|
89
|
+
field,
|
|
90
|
+
range: dependencyRange,
|
|
91
|
+
uncovered: uncovered.join(" || "),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const typesVersion = typesVersions.get(directory);
|
|
96
|
+
const resolvedTypes = typesVersion === undefined ? null : parseNodeVersion(typesVersion);
|
|
97
|
+
if (typesVersion !== undefined && (resolvedTypes === null || !typesFitFloor(resolvedTypes, floor))) {
|
|
98
|
+
violations.push({ kind: "types-off-floor", packageName, floor: formatted, typesVersion });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (isWithin(targetPath, rootDir)) {
|
|
102
|
+
violations.push(...auditRootFloor(fs, rootDir, manifests, workspaceManifests, testedNewest));
|
|
103
|
+
}
|
|
104
|
+
return ok({ floors, violations, packageCount: checked.length });
|
|
105
|
+
}
|
|
106
|
+
catch (caughtError) {
|
|
107
|
+
return err(new AppError("INFRA_FAILURE", messageFrom(caughtError), caughtError));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Reports each dependency installed anywhere in the workspace whose `engines.node` leaves out a release the root floor
|
|
112
|
+
* claims, since a contributor on that release runs every package's build and tests.
|
|
113
|
+
*/
|
|
114
|
+
function auditRootFloor(fs, rootDir, manifests, workspaceManifests, testedNewest) {
|
|
115
|
+
const rootManifest = readManifest(fs, rootDir);
|
|
116
|
+
const rootRange = rootManifest === null ? undefined : nodeRangeOf(rootManifest);
|
|
117
|
+
const floor = rootRange === undefined ? null : parseNodeFloor(rootRange);
|
|
118
|
+
if (rootManifest === null || floor === null) {
|
|
119
|
+
return [];
|
|
120
|
+
}
|
|
121
|
+
const packageName = typeof rootManifest.name === "string" ? rootManifest.name : ".";
|
|
122
|
+
const formatted = formatNodeVersion(floor);
|
|
123
|
+
const unjudgedMajors = shortLivedMajors(floor, testedNewest);
|
|
124
|
+
const importers = manifests.some((entry) => entry.packageDir === rootDir)
|
|
125
|
+
? manifests
|
|
126
|
+
: [{ packageName, packageDir: rootDir, manifest: rootManifest }, ...manifests];
|
|
127
|
+
const byDependency = new Map();
|
|
128
|
+
for (const importer of importers) {
|
|
129
|
+
for (const { dependency } of dependenciesOf(importer.manifest)) {
|
|
130
|
+
const dependencyManifest = workspaceManifests.get(dependency) ?? readInstalledManifest(fs, importer.packageDir, dependency);
|
|
131
|
+
const dependencyRange = dependencyManifest === null ? undefined : nodeRangeOf(dependencyManifest);
|
|
132
|
+
const gaps = dependencyRange === undefined ? null : uncoveredNodeRanges(floor, dependencyRange, unjudgedMajors);
|
|
133
|
+
if (dependencyRange === undefined || gaps === null || gaps.length === 0) {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const key = `${dependency}@${dependencyRange}`;
|
|
137
|
+
const existing = byDependency.get(key);
|
|
138
|
+
if (existing === undefined) {
|
|
139
|
+
byDependency.set(key, {
|
|
140
|
+
kind: "root-outside-dependency-engines",
|
|
141
|
+
packageName,
|
|
142
|
+
floor: formatted,
|
|
143
|
+
dependency,
|
|
144
|
+
range: dependencyRange,
|
|
145
|
+
dependents: [importer.packageName],
|
|
146
|
+
uncovered: gaps.join(" || "),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
else if (!existing.dependents.includes(importer.packageName)) {
|
|
150
|
+
existing.dependents.push(importer.packageName);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return [...byDependency.values()];
|
|
155
|
+
}
|
|
156
|
+
// Each dependency once, under the first field that lists it.
|
|
157
|
+
function dependenciesOf(manifest) {
|
|
158
|
+
const seen = new Set();
|
|
159
|
+
const dependencies = [];
|
|
160
|
+
for (const field of dependencyFields) {
|
|
161
|
+
for (const dependency of Object.keys(recordOf(manifest[field]))) {
|
|
162
|
+
if (!seen.has(dependency)) {
|
|
163
|
+
seen.add(dependency);
|
|
164
|
+
dependencies.push({ dependency, field });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return dependencies;
|
|
169
|
+
}
|
|
170
|
+
// The release `.node-version` pins, or `null` when the file is absent or names no full version.
|
|
171
|
+
function readNodeVersion(fs, rootDir) {
|
|
172
|
+
const filePath = path.join(rootDir, nodeVersionFileName);
|
|
173
|
+
if (!fs.existsSync(filePath)) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
return parseNodeVersion(fs.readFileSync(filePath, "utf8").trim().replace(/^v/, ""));
|
|
177
|
+
}
|
|
178
|
+
function readManifest(fs, directory) {
|
|
179
|
+
const manifestPath = path.join(directory, packageJsonFileName);
|
|
180
|
+
if (!fs.existsSync(manifestPath)) {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
return recordOf(JSON.parse(fs.readFileSync(manifestPath, "utf8")));
|
|
184
|
+
}
|
|
185
|
+
// The manifest pnpm links into the package's own `node_modules`; a dependency not installed there is not judged.
|
|
186
|
+
function readInstalledManifest(fs, packageDir, dependency) {
|
|
187
|
+
return readManifest(fs, path.join(packageDir, "node_modules", ...dependency.split("/")));
|
|
188
|
+
}
|
|
189
|
+
function nodeRangeOf(manifest) {
|
|
190
|
+
const range = recordOf(manifest.engines).node;
|
|
191
|
+
return typeof range === "string" ? range : undefined;
|
|
192
|
+
}
|
|
193
|
+
// The `@types/node` version the lockfile resolves for each importer, keyed by its repo-relative directory.
|
|
194
|
+
function readLockfileTypesVersions(fs, rootDir) {
|
|
195
|
+
const versions = new Map();
|
|
196
|
+
const lockfilePath = path.join(rootDir, lockfileName);
|
|
197
|
+
if (!fs.existsSync(lockfilePath)) {
|
|
198
|
+
return versions;
|
|
199
|
+
}
|
|
200
|
+
// pnpm prefixes the dependency lockfile with an env document pinning pnpm itself, so the last document is the one.
|
|
201
|
+
const lockfile = parseAllDocuments(fs.readFileSync(lockfilePath, "utf8")).at(-1)?.toJS();
|
|
202
|
+
const importers = recordOf(recordOf(lockfile).importers);
|
|
203
|
+
for (const [directory, importer] of Object.entries(importers)) {
|
|
204
|
+
for (const field of lockfileDependencyFields) {
|
|
205
|
+
const version = recordOf(recordOf(recordOf(importer)[field])[typesPackageName]).version;
|
|
206
|
+
if (typeof version === "string") {
|
|
207
|
+
versions.set(directory, version);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return versions;
|
|
212
|
+
}
|
|
213
|
+
function recordOf(value) {
|
|
214
|
+
return isRecord(value) ? value : {};
|
|
215
|
+
}
|
|
216
|
+
function isRecord(value) {
|
|
217
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
218
|
+
}
|
|
219
|
+
function isWithin(parent, child) {
|
|
220
|
+
const relative = path.relative(parent, child);
|
|
221
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
222
|
+
}
|
|
223
|
+
function toPosixPath(filePath) {
|
|
224
|
+
return filePath.split(path.sep).join("/");
|
|
225
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { LayersAuditResult } from "#audit/domain/types";
|
|
2
|
+
/**
|
|
3
|
+
* Exit `1` when any non-allowlisted layering violation remains.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.14.0
|
|
6
|
+
*/
|
|
7
|
+
export declare function exitCodeForLayersAuditResult(result: LayersAuditResult): number;
|
|
8
|
+
/**
|
|
9
|
+
* Machine-readable layering summary for `--json`.
|
|
10
|
+
*
|
|
11
|
+
* @since 0.14.0
|
|
12
|
+
*/
|
|
13
|
+
export declare function formatLayersAuditJsonOutput(result: LayersAuditResult, rootDir: string): string;
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { CLI_EXIT_GENERAL_ERROR, CLI_EXIT_SUCCESS } from "#core/exit-codes";
|
|
2
2
|
/**
|
|
3
|
-
* Exit `1` when any non-allowlisted
|
|
3
|
+
* Exit `1` when any non-allowlisted layering violation remains.
|
|
4
4
|
*
|
|
5
|
-
* @since 0.
|
|
5
|
+
* @since 0.14.0
|
|
6
6
|
*/
|
|
7
|
-
export function
|
|
7
|
+
export function exitCodeForLayersAuditResult(result) {
|
|
8
8
|
return result.violationCount > 0 ? CLI_EXIT_GENERAL_ERROR : CLI_EXIT_SUCCESS;
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
|
-
* Machine-readable
|
|
11
|
+
* Machine-readable layering summary for `--json`.
|
|
12
12
|
*
|
|
13
|
-
* @since 0.
|
|
13
|
+
* @since 0.14.0
|
|
14
14
|
*/
|
|
15
|
-
export function
|
|
15
|
+
export function formatLayersAuditJsonOutput(result, rootDir) {
|
|
16
16
|
return JSON.stringify({
|
|
17
17
|
schemaVersion: 1,
|
|
18
18
|
ok: result.violationCount === 0,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* One layered package as the run reads it: its name, the absolute root the layers sit under, and the layers.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.14.0
|
|
6
|
+
*/
|
|
7
|
+
export type LayersAuditPackage = {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly rootPath: string;
|
|
10
|
+
readonly layers: ReadonlyArray<ReadonlyArray<string>>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Resolved request for a single layering audit run.
|
|
14
|
+
*
|
|
15
|
+
* @since 0.14.0
|
|
16
|
+
*/
|
|
17
|
+
export type LayersAuditRunRequest = {
|
|
18
|
+
readonly rootDir: string;
|
|
19
|
+
readonly targetPath: string;
|
|
20
|
+
readonly allowlist?: ReadonlyArray<string> | undefined;
|
|
21
|
+
readonly json: boolean;
|
|
22
|
+
readonly packages: ReadonlyArray<LayersAuditPackage>;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Zod schema for {@link LayersAuditRunRequest}.
|
|
26
|
+
*
|
|
27
|
+
* @since 0.14.0
|
|
28
|
+
*/
|
|
29
|
+
export declare const layersAuditRunRequestSchema: z.ZodType<LayersAuditRunRequest>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Zod schema for {@link LayersAuditRunRequest}.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.14.0
|
|
6
|
+
*/
|
|
7
|
+
export const layersAuditRunRequestSchema = z.object({
|
|
8
|
+
rootDir: z.string().min(1),
|
|
9
|
+
targetPath: z.string().min(1),
|
|
10
|
+
allowlist: z.array(z.string()).optional(),
|
|
11
|
+
json: z.boolean(),
|
|
12
|
+
packages: z.array(z.object({
|
|
13
|
+
name: z.string().min(1),
|
|
14
|
+
rootPath: z.string().min(1),
|
|
15
|
+
layers: z.array(z.array(z.string().min(1))),
|
|
16
|
+
})),
|
|
17
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { LayerViolation } from "#audit/domain/types";
|
|
2
|
+
/**
|
|
3
|
+
* The key a layer entry and a module path share: the first path segment, without a module extension.
|
|
4
|
+
*
|
|
5
|
+
* @remarks `errors.ts`, `errors/` and `errors/taxonomy.ts` all key as `errors`, so a layer entry names
|
|
6
|
+
* a family directly under the root — a directory, or a lone module sitting flat.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.14.0
|
|
9
|
+
*/
|
|
10
|
+
export declare function layerKeyOf(modulePath: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* Returns why a layer list breaks its contract, or `undefined` when every entry is a family under the root, placed once.
|
|
13
|
+
*
|
|
14
|
+
* @since 0.14.0
|
|
15
|
+
*/
|
|
16
|
+
export declare function invalidLayerEntry(layers: ReadonlyArray<ReadonlyArray<string>>): string | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Where a module sits: its layer's position from the bottom, and the entry that placed it there.
|
|
19
|
+
*
|
|
20
|
+
* @since 0.14.0
|
|
21
|
+
*/
|
|
22
|
+
export interface LayerPlacement {
|
|
23
|
+
readonly index: number;
|
|
24
|
+
readonly entry: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* A package's layers, bottom to top, answering the placement of any module path under the root.
|
|
28
|
+
*
|
|
29
|
+
* @since 0.14.0
|
|
30
|
+
*/
|
|
31
|
+
export declare class LayerMap {
|
|
32
|
+
#private;
|
|
33
|
+
constructor(layers: ReadonlyArray<ReadonlyArray<string>>);
|
|
34
|
+
/** The placement of a root-relative module path, or `undefined` when no layer names its family. */
|
|
35
|
+
placementOf(modulePath: string): LayerPlacement | undefined;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Scans one module against its package's layers and returns the violations: the module sitting in no
|
|
39
|
+
* layer, or a value import or re-export whose target sits in a higher layer, or in none.
|
|
40
|
+
*
|
|
41
|
+
* @remarks Type-only imports and re-exports erase at build time and couple nothing, so they pass
|
|
42
|
+
* whichever way they point. Dynamic `import()` counts as a value import wherever it sits.
|
|
43
|
+
*
|
|
44
|
+
* @since 0.14.0
|
|
45
|
+
*/
|
|
46
|
+
export declare function auditLayeringSource(filePath: string, modulePath: string, sourceText: string, layers: LayerMap): Array<LayerViolation>;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The layering rule one package's `src/` follows: a value import never points up the configured layers.
|
|
3
|
+
*/
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { parseSync } from "oxc-parser";
|
|
6
|
+
import { isOxcNode, programStatements } from "#core/oxc-node";
|
|
7
|
+
import { firstLineOf, lineOfOffset } from "#core/source-position";
|
|
8
|
+
const MODULE_EXTENSIONS = [".tsx", ".ts", ".js"];
|
|
9
|
+
function withoutModuleExtension(name) {
|
|
10
|
+
for (const extension of MODULE_EXTENSIONS) {
|
|
11
|
+
if (name.endsWith(extension)) {
|
|
12
|
+
return name.slice(0, -extension.length);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return name;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The key a layer entry and a module path share: the first path segment, without a module extension.
|
|
19
|
+
*
|
|
20
|
+
* @remarks `errors.ts`, `errors/` and `errors/taxonomy.ts` all key as `errors`, so a layer entry names
|
|
21
|
+
* a family directly under the root — a directory, or a lone module sitting flat.
|
|
22
|
+
*
|
|
23
|
+
* @since 0.14.0
|
|
24
|
+
*/
|
|
25
|
+
export function layerKeyOf(modulePath) {
|
|
26
|
+
const [first = ""] = modulePath.split("/");
|
|
27
|
+
return withoutModuleExtension(first);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Returns why a layer list breaks its contract, or `undefined` when every entry is a family under the root, placed once.
|
|
31
|
+
*
|
|
32
|
+
* @since 0.14.0
|
|
33
|
+
*/
|
|
34
|
+
export function invalidLayerEntry(layers) {
|
|
35
|
+
const seen = new Map();
|
|
36
|
+
for (const layer of layers) {
|
|
37
|
+
for (const entry of layer) {
|
|
38
|
+
const trimmed = entry.replace(/\/$/, "");
|
|
39
|
+
if (trimmed === "" || trimmed.includes("/")) {
|
|
40
|
+
return `layer entry "${entry}" must name a directory or a module file directly under the root`;
|
|
41
|
+
}
|
|
42
|
+
const key = layerKeyOf(trimmed);
|
|
43
|
+
const earlier = seen.get(key);
|
|
44
|
+
if (earlier !== undefined) {
|
|
45
|
+
return `layer entry "${entry}" is already placed by "${earlier}"`;
|
|
46
|
+
}
|
|
47
|
+
seen.set(key, entry);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A package's layers, bottom to top, answering the placement of any module path under the root.
|
|
54
|
+
*
|
|
55
|
+
* @since 0.14.0
|
|
56
|
+
*/
|
|
57
|
+
export class LayerMap {
|
|
58
|
+
#placementByKey = new Map();
|
|
59
|
+
constructor(layers) {
|
|
60
|
+
layers.forEach((layer, index) => {
|
|
61
|
+
for (const entry of layer) {
|
|
62
|
+
this.#placementByKey.set(layerKeyOf(entry.replace(/\/$/, "")), { index, entry });
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** The placement of a root-relative module path, or `undefined` when no layer names its family. */
|
|
67
|
+
placementOf(modulePath) {
|
|
68
|
+
return this.#placementByKey.get(layerKeyOf(modulePath));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function sourceValueOf(node) {
|
|
72
|
+
const source = node.source;
|
|
73
|
+
return isOxcNode(source) && typeof source.value === "string" ? source.value : undefined;
|
|
74
|
+
}
|
|
75
|
+
function everySpecifierIsTypeOnly(node, kindField) {
|
|
76
|
+
const specifiers = Array.isArray(node.specifiers) ? node.specifiers.filter(isOxcNode) : [];
|
|
77
|
+
return specifiers.length > 0 && specifiers.every((specifier) => specifier[kindField] === "type");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The module a top-level statement imports or re-exports at runtime, or `undefined` when it erases at build time.
|
|
81
|
+
*/
|
|
82
|
+
function valueSpecifierOf(statement) {
|
|
83
|
+
if (statement.type === "ImportDeclaration") {
|
|
84
|
+
if (statement.importKind === "type" || everySpecifierIsTypeOnly(statement, "importKind")) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
return sourceValueOf(statement);
|
|
88
|
+
}
|
|
89
|
+
if (statement.type === "ExportNamedDeclaration") {
|
|
90
|
+
if (statement.exportKind === "type" || everySpecifierIsTypeOnly(statement, "exportKind")) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
return sourceValueOf(statement);
|
|
94
|
+
}
|
|
95
|
+
if (statement.type === "ExportAllDeclaration") {
|
|
96
|
+
return statement.exportKind === "type" ? undefined : sourceValueOf(statement);
|
|
97
|
+
}
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The root-relative module path a specifier names, or `undefined` for one outside the root (a package, a
|
|
102
|
+
* relative path climbing out).
|
|
103
|
+
*
|
|
104
|
+
* @remarks A `#` subpath import maps to the root directly, which is how every package's `#*` imports
|
|
105
|
+
* field is declared; a relative import resolves against the importing module.
|
|
106
|
+
*/
|
|
107
|
+
function moduleTargetOf(specifier, fromModulePath) {
|
|
108
|
+
if (specifier.startsWith("#")) {
|
|
109
|
+
const target = specifier.slice(1);
|
|
110
|
+
return target === "" ? undefined : target;
|
|
111
|
+
}
|
|
112
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
113
|
+
const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(fromModulePath), specifier));
|
|
114
|
+
return resolved.startsWith("../") ? undefined : resolved;
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
function collectDynamicImports(node, visit) {
|
|
119
|
+
if (node.type === "ImportExpression") {
|
|
120
|
+
const specifier = sourceValueOf(node);
|
|
121
|
+
if (specifier !== undefined) {
|
|
122
|
+
visit(node, specifier);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
for (const value of Object.values(node)) {
|
|
126
|
+
if (Array.isArray(value)) {
|
|
127
|
+
for (const item of value) {
|
|
128
|
+
if (isOxcNode(item)) {
|
|
129
|
+
collectDynamicImports(item, visit);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
else if (isOxcNode(value)) {
|
|
134
|
+
collectDynamicImports(value, visit);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Scans one module against its package's layers and returns the violations: the module sitting in no
|
|
140
|
+
* layer, or a value import or re-export whose target sits in a higher layer, or in none.
|
|
141
|
+
*
|
|
142
|
+
* @remarks Type-only imports and re-exports erase at build time and couple nothing, so they pass
|
|
143
|
+
* whichever way they point. Dynamic `import()` counts as a value import wherever it sits.
|
|
144
|
+
*
|
|
145
|
+
* @since 0.14.0
|
|
146
|
+
*/
|
|
147
|
+
export function auditLayeringSource(filePath, modulePath, sourceText, layers) {
|
|
148
|
+
const own = layers.placementOf(modulePath);
|
|
149
|
+
if (own === undefined) {
|
|
150
|
+
return [
|
|
151
|
+
{
|
|
152
|
+
line: 1,
|
|
153
|
+
raw: modulePath,
|
|
154
|
+
reason: `module sits in no configured layer — place "${layerKeyOf(modulePath)}" in one`,
|
|
155
|
+
},
|
|
156
|
+
];
|
|
157
|
+
}
|
|
158
|
+
const violations = [];
|
|
159
|
+
const check = (node, specifier) => {
|
|
160
|
+
const target = moduleTargetOf(specifier, modulePath);
|
|
161
|
+
if (target === undefined) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const placement = layers.placementOf(target);
|
|
165
|
+
if (placement === undefined) {
|
|
166
|
+
violations.push(violationAt(sourceText, node, `imports "${specifier}", which sits in no configured layer`));
|
|
167
|
+
}
|
|
168
|
+
else if (placement.index > own.index) {
|
|
169
|
+
violations.push(violationAt(sourceText, node, `value import of "${specifier}" points up the layers — ${own.entry} (layer ${String(own.index + 1)}) reaches ${placement.entry} (layer ${String(placement.index + 1)})`));
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const { program } = parseSync(filePath, sourceText);
|
|
173
|
+
for (const statement of programStatements(program)) {
|
|
174
|
+
const specifier = valueSpecifierOf(statement);
|
|
175
|
+
if (specifier !== undefined) {
|
|
176
|
+
check(statement, specifier);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (isOxcNode(program)) {
|
|
180
|
+
collectDynamicImports(program, check);
|
|
181
|
+
}
|
|
182
|
+
violations.sort((a, b) => a.line - b.line);
|
|
183
|
+
return violations;
|
|
184
|
+
}
|
|
185
|
+
function violationAt(sourceText, node, reason) {
|
|
186
|
+
return {
|
|
187
|
+
line: lineOfOffset(sourceText, node.start),
|
|
188
|
+
raw: firstLineOf(sourceText.slice(node.start, node.end)),
|
|
189
|
+
reason,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { logger } from "#core/logger";
|
|
2
|
+
/**
|
|
3
|
+
* Human-readable layering report.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.14.0
|
|
6
|
+
*/
|
|
7
|
+
export function presentLayersAuditResult(result) {
|
|
8
|
+
for (const file of result.files) {
|
|
9
|
+
logger.out(`\n${file.relativePath}`);
|
|
10
|
+
for (const { line, raw, reason } of file.violations) {
|
|
11
|
+
logger.out(` ${line}: ${raw} → ${reason}`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const allowlistSuffix = result.allowlistedCount > 0 ? ` (${result.allowlistedCount} allowlisted)` : "";
|
|
15
|
+
if (result.violationCount > 0) {
|
|
16
|
+
logger.out(`\n✖ ${result.violationCount} layering violation(s)${allowlistSuffix}`);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
logger.out(`✓ Every value import points down the layers across ${result.scannedFileCount} file(s) in ${result.packageCount} package(s)${allowlistSuffix}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { LayersAuditPackage } from "#audit/layers/cli-schema";
|
|
2
|
+
import type { AuditCommandPrelude } from "#audit/prepare";
|
|
3
|
+
import { AppError } from "#core/errors";
|
|
4
|
+
import type { Filesystem } from "#core/filesystem/filesystem";
|
|
5
|
+
import type { Result } from "#core/result";
|
|
6
|
+
/**
|
|
7
|
+
* The shared audit prelude plus the layered packages `audit.layers.packages` names, resolved to their roots.
|
|
8
|
+
*
|
|
9
|
+
* @since 0.14.0
|
|
10
|
+
*/
|
|
11
|
+
export type LayersAuditPrelude = AuditCommandPrelude & {
|
|
12
|
+
readonly packages: ReadonlyArray<LayersAuditPackage>;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Loads config and resolves every package `audit.layers.packages` names to the root its layers sit under.
|
|
16
|
+
*
|
|
17
|
+
* @remarks A configured name no workspace package carries, an entry nested below the root or placed
|
|
18
|
+
* twice, and a root that does not exist are each reported here, before anything is scanned.
|
|
19
|
+
*
|
|
20
|
+
* @since 0.14.0
|
|
21
|
+
*/
|
|
22
|
+
export declare function prepareLayersAudit(fs: Filesystem, args: {
|
|
23
|
+
readonly currentWorkingDirectory: string;
|
|
24
|
+
readonly rawTarget: string | undefined;
|
|
25
|
+
}): Promise<Result<LayersAuditPrelude, AppError>>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { invalidLayerEntry } from "#audit/layers/domain/layering";
|
|
3
|
+
import { prepareRepoRootAuditWith } from "#audit/prepare";
|
|
4
|
+
import { AppError, messageFrom } from "#core/errors";
|
|
5
|
+
import { err, ok } from "#core/result";
|
|
6
|
+
import { listWorkspacePackageDirectories } from "#core/workspace/resolver";
|
|
7
|
+
import { packageJsonFileName } from "#core/workspace/well-known-files";
|
|
8
|
+
const DEFAULT_LAYERS_ROOT = "src";
|
|
9
|
+
async function workspacePackageDirectoriesByName(rootDir, fs) {
|
|
10
|
+
const layout = await listWorkspacePackageDirectories(rootDir, fs, true);
|
|
11
|
+
const byName = new Map();
|
|
12
|
+
for (const directory of layout.packageDirectoryPathsAbsolute) {
|
|
13
|
+
const manifestPath = path.join(directory, packageJsonFileName);
|
|
14
|
+
if (!fs.existsSync(manifestPath)) {
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
|
18
|
+
if (typeof manifest === "object" && manifest !== null && "name" in manifest && typeof manifest.name === "string") {
|
|
19
|
+
byName.set(manifest.name, directory);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return byName;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Loads config and resolves every package `audit.layers.packages` names to the root its layers sit under.
|
|
26
|
+
*
|
|
27
|
+
* @remarks A configured name no workspace package carries, an entry nested below the root or placed
|
|
28
|
+
* twice, and a root that does not exist are each reported here, before anything is scanned.
|
|
29
|
+
*
|
|
30
|
+
* @since 0.14.0
|
|
31
|
+
*/
|
|
32
|
+
export async function prepareLayersAudit(fs, args) {
|
|
33
|
+
return prepareRepoRootAuditWith(fs, args, async (config, rootDir) => {
|
|
34
|
+
const layersConfig = config.audit?.layers;
|
|
35
|
+
const allowlist = layersConfig?.allowlist ?? [];
|
|
36
|
+
const configured = Object.entries(layersConfig?.packages ?? {});
|
|
37
|
+
if (configured.length === 0) {
|
|
38
|
+
return ok({ allowlist, packages: [] });
|
|
39
|
+
}
|
|
40
|
+
let directoryByName;
|
|
41
|
+
try {
|
|
42
|
+
directoryByName = await workspacePackageDirectoriesByName(rootDir, fs);
|
|
43
|
+
}
|
|
44
|
+
catch (caughtError) {
|
|
45
|
+
return err(new AppError("INFRA_FAILURE", messageFrom(caughtError), caughtError));
|
|
46
|
+
}
|
|
47
|
+
const packages = [];
|
|
48
|
+
for (const [name, packageConfig] of configured) {
|
|
49
|
+
const directory = directoryByName.get(name);
|
|
50
|
+
if (directory === undefined) {
|
|
51
|
+
return err(new AppError("VALIDATION_ERROR", `audit.layers.packages["${name}"]: no workspace package has that name`));
|
|
52
|
+
}
|
|
53
|
+
const invalid = invalidLayerEntry(packageConfig.layers);
|
|
54
|
+
if (invalid !== undefined) {
|
|
55
|
+
return err(new AppError("VALIDATION_ERROR", `audit.layers.packages["${name}"]: ${invalid}`));
|
|
56
|
+
}
|
|
57
|
+
const rootPath = path.join(directory, packageConfig.root ?? DEFAULT_LAYERS_ROOT);
|
|
58
|
+
if (!fs.existsSync(rootPath)) {
|
|
59
|
+
return err(new AppError("NOT_FOUND", `Not found: ${rootPath}`));
|
|
60
|
+
}
|
|
61
|
+
packages.push({ name, rootPath: fs.canonicalPathSync(rootPath), layers: packageConfig.layers });
|
|
62
|
+
}
|
|
63
|
+
packages.sort((left, right) => left.name.localeCompare(right.name));
|
|
64
|
+
return ok({ allowlist, packages });
|
|
65
|
+
});
|
|
66
|
+
}
|