@codefast/cli 0.14.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +70 -5
  3. package/dist/arrange/simplify/variant-classname-probe.js +2 -11
  4. package/dist/audit/command.js +40 -0
  5. package/dist/audit/comments/domain/comment-dividers.js +8 -1
  6. package/dist/audit/display-names/domain/display-names.js +4 -3
  7. package/dist/audit/domain/types.d.ts +94 -0
  8. package/dist/audit/engines/cli-result.d.ts +13 -0
  9. package/dist/audit/engines/cli-result.js +22 -0
  10. package/dist/audit/engines/cli-schema.d.ts +18 -0
  11. package/dist/audit/engines/cli-schema.js +12 -0
  12. package/dist/audit/engines/domain/node-floor.d.ts +34 -0
  13. package/dist/audit/engines/domain/node-floor.js +40 -0
  14. package/dist/audit/engines/domain/range-gaps.d.ts +21 -0
  15. package/dist/audit/engines/domain/range-gaps.js +136 -0
  16. package/dist/audit/engines/output.d.ts +7 -0
  17. package/dist/audit/engines/output.js +40 -0
  18. package/dist/audit/engines/prepare.d.ts +16 -0
  19. package/dist/audit/engines/prepare.js +12 -0
  20. package/dist/audit/engines/run.d.ts +18 -0
  21. package/dist/audit/engines/run.js +225 -0
  22. package/dist/audit/props/cli-result.d.ts +13 -0
  23. package/dist/audit/props/cli-result.js +22 -0
  24. package/dist/audit/props/cli-schema.d.ts +18 -0
  25. package/dist/audit/props/cli-schema.js +12 -0
  26. package/dist/audit/props/domain/props-intersection.d.ts +56 -0
  27. package/dist/audit/props/domain/props-intersection.js +189 -0
  28. package/dist/audit/props/output.d.ts +7 -0
  29. package/dist/audit/props/output.js +21 -0
  30. package/dist/audit/props/prepare.d.ts +13 -0
  31. package/dist/audit/props/prepare.js +9 -0
  32. package/dist/audit/props/run.d.ts +17 -0
  33. package/dist/audit/props/run.js +57 -0
  34. package/dist/audit/props/type-probe.d.ts +23 -0
  35. package/dist/audit/props/type-probe.js +85 -0
  36. package/dist/core/config/schema.d.ts +1 -0
  37. package/dist/core/config/schema.js +1 -0
  38. package/dist/core/type-server.d.ts +21 -0
  39. package/dist/core/type-server.js +32 -0
  40. package/package.json +6 -5
@@ -0,0 +1,136 @@
1
+ /** Finds the Node releases at or above a floor that an `engines.node` range leaves out. */
2
+ import { compare, Range, SemVer, validRange } from "semver";
3
+ import { formatNodeVersion } from "#audit/engines/domain/node-floor";
4
+ /**
5
+ * Lists the odd majors between the floor's and the newest tested one, which reach end-of-life without becoming LTS.
6
+ *
7
+ * @remarks The floor's own line and every line from the newest tested major up stay judged, since a package still
8
+ * claims those; with no newest release known, every line does.
9
+ *
10
+ * @since 0.15.0
11
+ */
12
+ export function shortLivedMajors(floor, newest) {
13
+ const majors = [];
14
+ for (let major = floor[0] + 1; newest !== null && major < newest[0]; major++) {
15
+ if (major % 2 === 1) {
16
+ majors.push(major);
17
+ }
18
+ }
19
+ return majors;
20
+ }
21
+ /**
22
+ * Lists the sub-ranges of `>=floor` that `range` does not admit, each written as a semver range, or returns `null` when
23
+ * no semver parser reads `range`.
24
+ *
25
+ * @remarks Releases on the `unjudged` majors never count as left out. Node publishes no prereleases on a release line,
26
+ * so a prerelease bound such as the `<23.0.0-0` a caret expands to is read as the release it precedes.
27
+ *
28
+ * @since 0.15.0
29
+ */
30
+ export function uncoveredNodeRanges(floor, range, unjudged = []) {
31
+ if (validRange(range) === null) {
32
+ return null;
33
+ }
34
+ const covered = mergeIntervals([
35
+ ...new Range(range).set.flatMap((comparators) => intervalOf(comparators) ?? []),
36
+ ...unjudged.map((major) => ({
37
+ lower: { version: new SemVer(`${major}.0.0`), inclusive: true },
38
+ upper: { version: new SemVer(`${major + 1}.0.0`), inclusive: false },
39
+ })),
40
+ ]);
41
+ const gaps = [];
42
+ let cursor = { version: new SemVer(formatNodeVersion(floor)), inclusive: true };
43
+ for (const interval of covered) {
44
+ if (cursor === null) {
45
+ break;
46
+ }
47
+ if (interval.upper !== null && compareUpperToLower(interval.upper, cursor) < 0) {
48
+ continue;
49
+ }
50
+ if (interval.lower !== null && compareLowers(interval.lower, cursor) > 0) {
51
+ gaps.push(formatInterval({ lower: cursor, upper: flip(interval.lower) }));
52
+ }
53
+ cursor = interval.upper === null ? null : flip(interval.upper);
54
+ }
55
+ if (cursor !== null) {
56
+ gaps.push(formatInterval({ lower: cursor, upper: null }));
57
+ }
58
+ return gaps;
59
+ }
60
+ // The one interval a comparator set admits, or `null` when its bounds cross.
61
+ function intervalOf(comparators) {
62
+ let lower = null;
63
+ let upper = null;
64
+ for (const comparator of comparators) {
65
+ if (comparator.value === "") {
66
+ continue;
67
+ }
68
+ const prerelease = comparator.semver.prerelease.length > 0;
69
+ const version = new SemVer(`${comparator.semver.major}.${comparator.semver.minor}.${comparator.semver.patch}`);
70
+ const { operator } = comparator;
71
+ if (operator === "" || operator === "=" || operator === ">=" || operator === ">") {
72
+ const bound = { version, inclusive: prerelease || operator !== ">" };
73
+ lower = lower === null || compareLowers(bound, lower) > 0 ? bound : lower;
74
+ }
75
+ if (operator === "" || operator === "=" || operator === "<=" || operator === "<") {
76
+ const bound = { version, inclusive: !prerelease && operator !== "<" };
77
+ upper = upper === null || compareUppers(bound, upper) < 0 ? bound : upper;
78
+ }
79
+ }
80
+ if (lower !== null && upper !== null && compareUpperToLower(upper, lower) < 0) {
81
+ return null;
82
+ }
83
+ return { lower, upper };
84
+ }
85
+ // The union of the intervals, sorted and with every overlapping or touching pair joined.
86
+ function mergeIntervals(intervals) {
87
+ const sorted = intervals.toSorted((left, right) => {
88
+ if (left.lower === null || right.lower === null) {
89
+ return left.lower === right.lower ? 0 : left.lower === null ? -1 : 1;
90
+ }
91
+ return compareLowers(left.lower, right.lower);
92
+ });
93
+ const merged = [];
94
+ for (const interval of sorted) {
95
+ const last = merged.at(-1);
96
+ if (last === undefined || (last.upper !== null && compareUpperToLower(last.upper, interval.lower) < 0)) {
97
+ merged.push(interval);
98
+ continue;
99
+ }
100
+ const upper = last.upper === null || interval.upper === null
101
+ ? null
102
+ : compareUppers(interval.upper, last.upper) > 0
103
+ ? interval.upper
104
+ : last.upper;
105
+ merged[merged.length - 1] = { lower: last.lower, upper };
106
+ }
107
+ return merged;
108
+ }
109
+ function compareLowers(left, right) {
110
+ return compare(left.version, right.version) || Number(right.inclusive) - Number(left.inclusive);
111
+ }
112
+ function compareUppers(left, right) {
113
+ return compare(left.version, right.version) || Number(left.inclusive) - Number(right.inclusive);
114
+ }
115
+ // Negative when a version sits strictly between the upper bound and the lower bound, so nothing joins them.
116
+ function compareUpperToLower(upper, lower) {
117
+ if (lower === null) {
118
+ return 1;
119
+ }
120
+ const order = compare(upper.version, lower.version);
121
+ return order !== 0 ? order : upper.inclusive || lower.inclusive ? 0 : -1;
122
+ }
123
+ // The bound that starts where this one ends, on the other side of it.
124
+ function flip(bound) {
125
+ return { version: bound.version, inclusive: !bound.inclusive };
126
+ }
127
+ function formatInterval({ lower, upper }) {
128
+ const parts = [];
129
+ if (lower !== null) {
130
+ parts.push(`${lower.inclusive ? ">=" : ">"}${lower.version.version}`);
131
+ }
132
+ if (upper !== null) {
133
+ parts.push(`${upper.inclusive ? "<=" : "<"}${upper.version.version}`);
134
+ }
135
+ return parts.join(" ");
136
+ }
@@ -0,0 +1,7 @@
1
+ import type { EnginesAuditResult } from "#audit/domain/types";
2
+ /**
3
+ * Human-readable engines audit report.
4
+ *
5
+ * @since 0.15.0
6
+ */
7
+ export declare function presentEnginesAuditResult(result: EnginesAuditResult): void;
@@ -0,0 +1,40 @@
1
+ import { logger } from "#core/logger";
2
+ /**
3
+ * Human-readable engines audit report.
4
+ *
5
+ * @since 0.15.0
6
+ */
7
+ export function presentEnginesAuditResult(result) {
8
+ for (const violation of result.violations) {
9
+ logger.out(`\n${violation.packageName}: ${describeViolation(violation)}`);
10
+ }
11
+ if (result.violations.length > 0) {
12
+ logger.out(`\n✖ ${result.violations.length} Node floor violation(s) across ${result.packageCount} package(s)`);
13
+ return;
14
+ }
15
+ const counts = new Map();
16
+ for (const { floor } of result.floors) {
17
+ counts.set(floor, (counts.get(floor) ?? 0) + 1);
18
+ }
19
+ const summary = [...counts].map(([floor, count]) => `${floor} (${count})`).join(", ") || "none declared";
20
+ logger.out(`✓ Every Node floor holds across ${result.packageCount} package(s): ${summary}`);
21
+ }
22
+ function describeViolation(violation) {
23
+ switch (violation.kind) {
24
+ case "missing-floor": {
25
+ return `declares no engines.node → a published package states the Node floor it supports`;
26
+ }
27
+ case "unparsable-floor": {
28
+ return `engines.node "${violation.range}" → write the floor as ">=X.Y.Z"`;
29
+ }
30
+ case "outside-dependency-engines": {
31
+ return `floor ${violation.floor} claims Node "${violation.uncovered}", which ${violation.dependency}'s engines.node "${violation.range}" (${violation.field}) leaves out → raise the floor or drop the dependency`;
32
+ }
33
+ case "root-outside-dependency-engines": {
34
+ return `workspace root floor ${violation.floor} claims Node "${violation.uncovered}", which ${violation.dependency}'s engines.node "${violation.range}" (installed for ${violation.dependents.join(", ")}) leaves out → raise the root floor or drop the dependency`;
35
+ }
36
+ case "types-off-floor": {
37
+ return `@types/node resolves to ${violation.typesVersion}, off floor ${violation.floor}'s line → pin it to the floor's major at a minor no newer`;
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,16 @@
1
+ import type { AuditCommandPrelude } from "#audit/prepare";
2
+ import type { AppError } from "#core/errors";
3
+ import type { Filesystem } from "#core/filesystem/filesystem";
4
+ import type { Result } from "#core/result";
5
+ /**
6
+ * Loads config and resolves the scan target for `audit engines`.
7
+ *
8
+ * @remarks Defaults to the repo root. A narrower target checks only the packages it reaches, still against the floors
9
+ * of every workspace package they depend on. It takes no allowlist.
10
+ *
11
+ * @since 0.15.0
12
+ */
13
+ export declare function prepareEnginesAudit(fs: Filesystem, args: {
14
+ readonly currentWorkingDirectory: string;
15
+ readonly rawTarget: string | undefined;
16
+ }): Promise<Result<AuditCommandPrelude, AppError>>;
@@ -0,0 +1,12 @@
1
+ import { prepareRepoRootAudit } from "#audit/prepare";
2
+ /**
3
+ * Loads config and resolves the scan target for `audit engines`.
4
+ *
5
+ * @remarks Defaults to the repo root. A narrower target checks only the packages it reaches, still against the floors
6
+ * of every workspace package they depend on. It takes no allowlist.
7
+ *
8
+ * @since 0.15.0
9
+ */
10
+ export async function prepareEnginesAudit(fs, args) {
11
+ return prepareRepoRootAudit(fs, args, () => []);
12
+ }
@@ -0,0 +1,18 @@
1
+ import type { EnginesAuditResult } from "#audit/domain/types";
2
+ import { AppError } from "#core/errors";
3
+ import type { Filesystem } from "#core/filesystem/filesystem";
4
+ import type { Result } from "#core/result";
5
+ /**
6
+ * Reports every Node floor that breaks a rule a consumer or CI depends on.
7
+ *
8
+ * @remarks A published package declares a floor as `>=X.Y.Z`. The `engines.node` of every runtime dependency must
9
+ * admit every release from the floor up, short-lived odd lines aside; that of every dev dependency, the floor and the
10
+ * newest release CI tests on. The `@types/node` the lockfile resolves must declare nothing the floor lacks. The
11
+ * workspace root's floor, never listed among `floors`, must be admitted by every dependency any package installs.
12
+ *
13
+ * @since 0.15.0
14
+ */
15
+ export declare function runEnginesAudit(fs: Filesystem, args: {
16
+ readonly rootDir: string;
17
+ readonly targetPath: string;
18
+ }): Promise<Result<EnginesAuditResult, AppError>>;
@@ -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 { PropsAuditResult } from "#audit/domain/types";
2
+ /**
3
+ * Exit `1` when any non-allowlisted props-declaration violation remains.
4
+ *
5
+ * @since 0.15.0
6
+ */
7
+ export declare function exitCodeForPropsAuditResult(result: PropsAuditResult): number;
8
+ /**
9
+ * Machine-readable props-declaration summary for `--json`.
10
+ *
11
+ * @since 0.15.0
12
+ */
13
+ export declare function formatPropsAuditJsonOutput(result: PropsAuditResult, rootDir: string): string;
@@ -0,0 +1,22 @@
1
+ import { CLI_EXIT_GENERAL_ERROR, CLI_EXIT_SUCCESS } from "#core/exit-codes";
2
+ /**
3
+ * Exit `1` when any non-allowlisted props-declaration violation remains.
4
+ *
5
+ * @since 0.15.0
6
+ */
7
+ export function exitCodeForPropsAuditResult(result) {
8
+ return result.violationCount > 0 ? CLI_EXIT_GENERAL_ERROR : CLI_EXIT_SUCCESS;
9
+ }
10
+ /**
11
+ * Machine-readable props-declaration summary for `--json`.
12
+ *
13
+ * @since 0.15.0
14
+ */
15
+ export function formatPropsAuditJsonOutput(result, rootDir) {
16
+ return JSON.stringify({
17
+ schemaVersion: 1,
18
+ ok: result.violationCount === 0,
19
+ cwd: rootDir,
20
+ result,
21
+ });
22
+ }
@@ -0,0 +1,18 @@
1
+ import * as z from "zod";
2
+ /**
3
+ * Resolved request for a single props-declaration audit run.
4
+ *
5
+ * @since 0.15.0
6
+ */
7
+ export type PropsAuditRunRequest = {
8
+ readonly rootDir: string;
9
+ readonly targetPath: string;
10
+ readonly allowlist?: ReadonlyArray<string> | undefined;
11
+ readonly json: boolean;
12
+ };
13
+ /**
14
+ * Zod schema for {@link PropsAuditRunRequest}.
15
+ *
16
+ * @since 0.15.0
17
+ */
18
+ export declare const propsAuditRunRequestSchema: z.ZodType<PropsAuditRunRequest>;
@@ -0,0 +1,12 @@
1
+ import * as z from "zod";
2
+ /**
3
+ * Zod schema for {@link PropsAuditRunRequest}.
4
+ *
5
+ * @since 0.15.0
6
+ */
7
+ export const propsAuditRunRequestSchema = 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
+ });
@@ -0,0 +1,56 @@
1
+ /** Finds component props types joined with `&`, and judges each from what its parts resolved to. */
2
+ import type { PropsViolation } from "#audit/domain/types";
3
+ /**
4
+ * What the type checker resolved one part of an intersection to.
5
+ *
6
+ * @remarks Only an `object` part can be extended by an interface. A `union` part needs the `&` to
7
+ * distribute over its members and a `type-parameter` part needs it to defer; an `other` part (a
8
+ * primitive, a conditional) has no interface form; an `unresolved` part leaves the question open.
9
+ *
10
+ * @since 0.15.0
11
+ */
12
+ export type ConstituentKind = "object" | "union" | "type-parameter" | "other" | "unresolved";
13
+ /**
14
+ * One part of a props intersection: its UTF-16 source span and its text as written.
15
+ *
16
+ * @since 0.15.0
17
+ */
18
+ export interface IntersectionPart {
19
+ readonly start: number;
20
+ readonly end: number;
21
+ readonly text: string;
22
+ }
23
+ /**
24
+ * A props type joined with `&`: a `*Props` alias, or the inline annotation of a component's props parameter.
25
+ *
26
+ * @since 0.15.0
27
+ */
28
+ export interface PropsIntersection {
29
+ /** Whether a `*Props` alias declares the intersection or a parameter annotation spells it inline. */
30
+ readonly site: "alias" | "parameter";
31
+ readonly line: number;
32
+ /** The alias, or the parameter's annotation, as written up to its first line break. */
33
+ readonly raw: string;
34
+ /** The type the intersection is passed to, when it is not the alias's whole body. */
35
+ readonly wrapper: string | undefined;
36
+ readonly parts: ReadonlyArray<IntersectionPart>;
37
+ }
38
+ /**
39
+ * Finds every props type in one TypeScript source that joins types with `&`.
40
+ *
41
+ * @remarks A candidate is a `*Props` alias, or in a `.tsx` file a module-level component's first
42
+ * parameter whose annotation is an intersection at its top level. Syntax alone decides the candidates;
43
+ * whether an interface could express one is for the type checker, through {@link judgePropsIntersection}.
44
+ *
45
+ * @since 0.15.0
46
+ */
47
+ export declare function findPropsIntersections(filePath: string, sourceText: string): Array<PropsIntersection>;
48
+ /**
49
+ * Judges a props intersection from the kinds its parts resolved to, or returns `undefined` when it must stay.
50
+ *
51
+ * @remarks An intersection stays a `type` when any part is a union, a type parameter or not an
52
+ * object; it is reported when an interface could extend every part, or when a part did not resolve.
53
+ *
54
+ * @since 0.15.0
55
+ */
56
+ export declare function judgePropsIntersection(intersection: PropsIntersection, kinds: ReadonlyArray<ConstituentKind>): PropsViolation | undefined;