@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,19 @@
|
|
|
1
|
+
import type { LayersAuditResult } from "#audit/domain/types";
|
|
2
|
+
import type { LayersAuditPackage } from "#audit/layers/cli-schema";
|
|
3
|
+
import { AppError } from "#core/errors";
|
|
4
|
+
import type { Filesystem } from "#core/filesystem/filesystem";
|
|
5
|
+
import type { Result } from "#core/result";
|
|
6
|
+
/**
|
|
7
|
+
* Scans every layered package the target reaches for value imports that point up its layers.
|
|
8
|
+
*
|
|
9
|
+
* @remarks The target narrows the scan: the repo root reaches every package, a package directory
|
|
10
|
+
* reaches that package, and a path under a package's root reaches the modules beneath it.
|
|
11
|
+
*
|
|
12
|
+
* @since 0.14.0
|
|
13
|
+
*/
|
|
14
|
+
export declare function runLayersAudit(fs: Filesystem, args: {
|
|
15
|
+
readonly rootDir: string;
|
|
16
|
+
readonly targetPath: string;
|
|
17
|
+
readonly allowlist: ReadonlyArray<string>;
|
|
18
|
+
readonly packages: ReadonlyArray<LayersAuditPackage>;
|
|
19
|
+
}): Result<LayersAuditResult, AppError>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { auditLayeringSource, LayerMap } from "#audit/layers/domain/layering";
|
|
3
|
+
import { AppError, messageFrom } from "#core/errors";
|
|
4
|
+
import { err, ok } from "#core/result";
|
|
5
|
+
import { walkTsxFiles } from "#core/workspace/typescript-walk";
|
|
6
|
+
/**
|
|
7
|
+
* Scans every layered package the target reaches for value imports that point up its layers.
|
|
8
|
+
*
|
|
9
|
+
* @remarks The target narrows the scan: the repo root reaches every package, a package directory
|
|
10
|
+
* reaches that package, and a path under a package's root reaches the modules beneath it.
|
|
11
|
+
*
|
|
12
|
+
* @since 0.14.0
|
|
13
|
+
*/
|
|
14
|
+
export function runLayersAudit(fs, args) {
|
|
15
|
+
try {
|
|
16
|
+
const allowlist = new Set(args.allowlist);
|
|
17
|
+
const files = [];
|
|
18
|
+
let violationCount = 0;
|
|
19
|
+
let allowlistedCount = 0;
|
|
20
|
+
let scannedFileCount = 0;
|
|
21
|
+
let packageCount = 0;
|
|
22
|
+
for (const layeredPackage of args.packages) {
|
|
23
|
+
const targetInsideRoot = isWithin(layeredPackage.rootPath, args.targetPath);
|
|
24
|
+
if (!targetInsideRoot && !isWithin(args.targetPath, layeredPackage.rootPath)) {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
packageCount++;
|
|
28
|
+
const layers = new LayerMap(layeredPackage.layers);
|
|
29
|
+
const scanRoot = targetInsideRoot ? args.targetPath : layeredPackage.rootPath;
|
|
30
|
+
const filesToScan = fs.statSync(scanRoot).isFile() ? [scanRoot] : walkTsxFiles(scanRoot, fs);
|
|
31
|
+
for (const absolutePath of filesToScan) {
|
|
32
|
+
scannedFileCount++;
|
|
33
|
+
const relativePath = toPosixPath(path.relative(args.rootDir, absolutePath));
|
|
34
|
+
const modulePath = toPosixPath(path.relative(layeredPackage.rootPath, absolutePath));
|
|
35
|
+
const content = fs.readFileSync(absolutePath, "utf8");
|
|
36
|
+
const remaining = auditLayeringSource(absolutePath, modulePath, content, layers).filter(({ raw }) => {
|
|
37
|
+
const isAllowed = allowlist.has(raw) || allowlist.has(`${relativePath}:${raw}`);
|
|
38
|
+
if (isAllowed) {
|
|
39
|
+
allowlistedCount++;
|
|
40
|
+
}
|
|
41
|
+
return !isAllowed;
|
|
42
|
+
});
|
|
43
|
+
if (remaining.length === 0) {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
violationCount += remaining.length;
|
|
47
|
+
files.push({ relativePath, violations: remaining });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return ok({ files, violationCount, allowlistedCount, scannedFileCount, packageCount });
|
|
51
|
+
}
|
|
52
|
+
catch (caughtError) {
|
|
53
|
+
return err(new AppError("INFRA_FAILURE", messageFrom(caughtError), caughtError));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function isWithin(parentPath, childPath) {
|
|
57
|
+
const relative = path.relative(parentPath, childPath);
|
|
58
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
59
|
+
}
|
|
60
|
+
function toPosixPath(filePath) {
|
|
61
|
+
return filePath.split(path.sep).join("/");
|
|
62
|
+
}
|
package/dist/audit/prepare.d.ts
CHANGED
|
@@ -28,4 +28,16 @@ export declare function resolveRepoRelativePath(rootDir: string, maybeRelative:
|
|
|
28
28
|
export declare function prepareRepoRootAudit(fs: Filesystem, args: {
|
|
29
29
|
readonly currentWorkingDirectory: string;
|
|
30
30
|
readonly rawTarget: string | undefined;
|
|
31
|
-
}, selectAllowlist: (config: CodefastConfig) => ReadonlyArray<string>): Promise<Result<AuditCommandPrelude, AppError>>;
|
|
31
|
+
}, selectAllowlist: (config: CodefastConfig) => ReadonlyArray<string>): Promise<Result<AuditCommandPrelude, AppError>>;
|
|
32
|
+
/**
|
|
33
|
+
* Loads config and resolves the repo root as the scan target, taking whatever the caller selects from the config.
|
|
34
|
+
*
|
|
35
|
+
* @remarks The selection runs with the root resolved, so it may read the workspace and refuse a
|
|
36
|
+
* config that names what the workspace does not hold, before anything is scanned.
|
|
37
|
+
*
|
|
38
|
+
* @since 0.14.0
|
|
39
|
+
*/
|
|
40
|
+
export declare function prepareRepoRootAuditWith<Selected extends Pick<AuditCommandPrelude, "allowlist">>(fs: Filesystem, args: {
|
|
41
|
+
readonly currentWorkingDirectory: string;
|
|
42
|
+
readonly rawTarget: string | undefined;
|
|
43
|
+
}, select: (config: CodefastConfig, rootDir: string) => Promise<Result<Selected, AppError>>): Promise<Result<Omit<AuditCommandPrelude, "allowlist"> & Selected, AppError>>;
|
package/dist/audit/prepare.js
CHANGED
|
@@ -19,6 +19,17 @@ export function resolveRepoRelativePath(rootDir, maybeRelative) {
|
|
|
19
19
|
* @since 0.11.0
|
|
20
20
|
*/
|
|
21
21
|
export async function prepareRepoRootAudit(fs, args, selectAllowlist) {
|
|
22
|
+
return prepareRepoRootAuditWith(fs, args, (config) => Promise.resolve(ok({ allowlist: selectAllowlist(config) })));
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Loads config and resolves the repo root as the scan target, taking whatever the caller selects from the config.
|
|
26
|
+
*
|
|
27
|
+
* @remarks The selection runs with the root resolved, so it may read the workspace and refuse a
|
|
28
|
+
* config that names what the workspace does not hold, before anything is scanned.
|
|
29
|
+
*
|
|
30
|
+
* @since 0.14.0
|
|
31
|
+
*/
|
|
32
|
+
export async function prepareRepoRootAuditWith(fs, args, select) {
|
|
22
33
|
let rootDir;
|
|
23
34
|
try {
|
|
24
35
|
rootDir = fs.canonicalPathSync(resolveProjectRoot(args.currentWorkingDirectory, fs).rootDir);
|
|
@@ -34,9 +45,13 @@ export async function prepareRepoRootAudit(fs, args, selectAllowlist) {
|
|
|
34
45
|
if (!fs.existsSync(targetPath)) {
|
|
35
46
|
return err(new AppError("NOT_FOUND", `Not found: ${targetPath}`));
|
|
36
47
|
}
|
|
48
|
+
const selected = await select(loadedOutcome.value.config, rootDir);
|
|
49
|
+
if (!selected.ok) {
|
|
50
|
+
return selected;
|
|
51
|
+
}
|
|
37
52
|
return ok({
|
|
38
53
|
rootDir,
|
|
39
54
|
targetPath: fs.canonicalPathSync(targetPath),
|
|
40
|
-
|
|
55
|
+
...selected.value,
|
|
41
56
|
});
|
|
42
57
|
}
|
|
@@ -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;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/** Finds component props types joined with `&`, and judges each from what its parts resolved to. */
|
|
2
|
+
import { parseSync } from "oxc-parser";
|
|
3
|
+
import { isOxcNode, programStatements } from "#core/oxc-node";
|
|
4
|
+
import { firstLineOf, lineOfOffset } from "#core/source-position";
|
|
5
|
+
function unwrapParentheses(node) {
|
|
6
|
+
let current = node;
|
|
7
|
+
while (current.type === "TSParenthesizedType" && isOxcNode(current.typeAnnotation)) {
|
|
8
|
+
current = current.typeAnnotation;
|
|
9
|
+
}
|
|
10
|
+
return current;
|
|
11
|
+
}
|
|
12
|
+
function intersectionParts(sourceText, intersection) {
|
|
13
|
+
const types = Array.isArray(intersection.types) ? intersection.types.filter(isOxcNode) : [];
|
|
14
|
+
return types.map(({ start, end }) => ({ start, end, text: sourceText.slice(start, end) }));
|
|
15
|
+
}
|
|
16
|
+
function typeArgumentsOf(reference) {
|
|
17
|
+
const typeArguments = reference.typeArguments;
|
|
18
|
+
if (!isOxcNode(typeArguments) || !Array.isArray(typeArguments.params)) {
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
return typeArguments.params.filter(isOxcNode).map(unwrapParentheses);
|
|
22
|
+
}
|
|
23
|
+
function intersectionsOfAlias(sourceText, alias) {
|
|
24
|
+
if (!isOxcNode(alias.id) || typeof alias.id.name !== "string" || !alias.id.name.endsWith("Props")) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
if (!isOxcNode(alias.typeAnnotation)) {
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
const base = {
|
|
31
|
+
site: "alias",
|
|
32
|
+
line: lineOfOffset(sourceText, alias.start),
|
|
33
|
+
raw: firstLineOf(sourceText.slice(alias.start, alias.end)),
|
|
34
|
+
};
|
|
35
|
+
const body = unwrapParentheses(alias.typeAnnotation);
|
|
36
|
+
if (body.type === "TSIntersectionType") {
|
|
37
|
+
return [{ ...base, wrapper: undefined, parts: intersectionParts(sourceText, body) }];
|
|
38
|
+
}
|
|
39
|
+
if (body.type !== "TSTypeReference" || !isOxcNode(body.typeName)) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
const wrapper = sourceText.slice(body.typeName.start, body.typeName.end);
|
|
43
|
+
return typeArgumentsOf(body)
|
|
44
|
+
.filter((argument) => argument.type === "TSIntersectionType")
|
|
45
|
+
.map((argument) => ({ ...base, wrapper, parts: intersectionParts(sourceText, argument) }));
|
|
46
|
+
}
|
|
47
|
+
const FUNCTION_DECLARATION_TYPES = new Set(["FunctionDeclaration", "TSDeclareFunction"]);
|
|
48
|
+
/** JSX renders a capitalised name as a component and a lowercase one as a host element. */
|
|
49
|
+
const COMPONENT_NAME = /^[A-Z]/;
|
|
50
|
+
function isComponentName(node) {
|
|
51
|
+
return isOxcNode(node) && typeof node.name === "string" && COMPONENT_NAME.test(node.name);
|
|
52
|
+
}
|
|
53
|
+
/** Returns the functions an initialiser is: itself, or each one passed to the call it is, such as `memo(…)`. */
|
|
54
|
+
function functionsOfExpression(expression) {
|
|
55
|
+
if (expression.type === "ParenthesizedExpression" && isOxcNode(expression.expression)) {
|
|
56
|
+
return functionsOfExpression(expression.expression);
|
|
57
|
+
}
|
|
58
|
+
if (expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression") {
|
|
59
|
+
return [expression];
|
|
60
|
+
}
|
|
61
|
+
if (expression.type === "CallExpression" && Array.isArray(expression.arguments)) {
|
|
62
|
+
return expression.arguments.filter(isOxcNode).flatMap(functionsOfExpression);
|
|
63
|
+
}
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Returns the components a top-level statement declares: a capitalised function, or the functions a
|
|
68
|
+
* capitalised binding holds; a function nested in another is never one.
|
|
69
|
+
*/
|
|
70
|
+
function componentsOfStatement(statement) {
|
|
71
|
+
const declaration = (statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") &&
|
|
72
|
+
isOxcNode(statement.declaration)
|
|
73
|
+
? statement.declaration
|
|
74
|
+
: statement;
|
|
75
|
+
if (FUNCTION_DECLARATION_TYPES.has(declaration.type)) {
|
|
76
|
+
return isComponentName(declaration.id) ? [declaration] : [];
|
|
77
|
+
}
|
|
78
|
+
if (declaration.type === "VariableDeclaration" && Array.isArray(declaration.declarations)) {
|
|
79
|
+
return declaration.declarations
|
|
80
|
+
.filter(isOxcNode)
|
|
81
|
+
.flatMap(({ id, init }) => (isComponentName(id) && isOxcNode(init) ? functionsOfExpression(init) : []));
|
|
82
|
+
}
|
|
83
|
+
// `export default memo(function Row(…))` names the component on the function itself.
|
|
84
|
+
return statement.type === "ExportDefaultDeclaration"
|
|
85
|
+
? functionsOfExpression(declaration).filter((fn) => isComponentName(fn.id))
|
|
86
|
+
: [];
|
|
87
|
+
}
|
|
88
|
+
/** Returns the type annotating a function's first parameter, past a `this` parameter and a default value. */
|
|
89
|
+
function firstParameterAnnotation(fn) {
|
|
90
|
+
const params = Array.isArray(fn.params) ? fn.params.filter(isOxcNode) : [];
|
|
91
|
+
const first = params.find((param) => !(param.type === "Identifier" && param.name === "this"));
|
|
92
|
+
const binding = first?.type === "AssignmentPattern" && isOxcNode(first.left) ? first.left : first;
|
|
93
|
+
const annotation = binding?.typeAnnotation;
|
|
94
|
+
return isOxcNode(annotation) && isOxcNode(annotation.typeAnnotation) ? annotation.typeAnnotation : undefined;
|
|
95
|
+
}
|
|
96
|
+
function intersectionsOfParameter(sourceText, fn) {
|
|
97
|
+
const annotation = firstParameterAnnotation(fn);
|
|
98
|
+
if (annotation === undefined) {
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
const body = unwrapParentheses(annotation);
|
|
102
|
+
if (body.type !== "TSIntersectionType") {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
return [
|
|
106
|
+
{
|
|
107
|
+
site: "parameter",
|
|
108
|
+
line: lineOfOffset(sourceText, annotation.start),
|
|
109
|
+
raw: firstLineOf(sourceText.slice(annotation.start, annotation.end)),
|
|
110
|
+
wrapper: undefined,
|
|
111
|
+
parts: intersectionParts(sourceText, body),
|
|
112
|
+
},
|
|
113
|
+
];
|
|
114
|
+
}
|
|
115
|
+
function collectNodes(node, matches, found) {
|
|
116
|
+
if (matches(node)) {
|
|
117
|
+
found.push(node);
|
|
118
|
+
}
|
|
119
|
+
for (const value of Object.values(node)) {
|
|
120
|
+
if (Array.isArray(value)) {
|
|
121
|
+
for (const item of value) {
|
|
122
|
+
if (isOxcNode(item)) {
|
|
123
|
+
collectNodes(item, matches, found);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
else if (isOxcNode(value)) {
|
|
128
|
+
collectNodes(value, matches, found);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Finds every props type in one TypeScript source that joins types with `&`.
|
|
134
|
+
*
|
|
135
|
+
* @remarks A candidate is a `*Props` alias, or in a `.tsx` file a module-level component's first
|
|
136
|
+
* parameter whose annotation is an intersection at its top level. Syntax alone decides the candidates;
|
|
137
|
+
* whether an interface could express one is for the type checker, through {@link judgePropsIntersection}.
|
|
138
|
+
*
|
|
139
|
+
* @since 0.15.0
|
|
140
|
+
*/
|
|
141
|
+
export function findPropsIntersections(filePath, sourceText) {
|
|
142
|
+
const readsParameters = filePath.endsWith(".tsx");
|
|
143
|
+
// Most files hold no props type with an `&`, so a text probe spares them the parse.
|
|
144
|
+
if (!sourceText.includes("&") || (!readsParameters && !sourceText.includes("Props"))) {
|
|
145
|
+
return [];
|
|
146
|
+
}
|
|
147
|
+
const { program } = parseSync(filePath, sourceText);
|
|
148
|
+
const candidates = readsParameters ? programStatements(program).flatMap(componentsOfStatement) : [];
|
|
149
|
+
if (isOxcNode(program)) {
|
|
150
|
+
collectNodes(program, (node) => node.type === "TSTypeAliasDeclaration", candidates);
|
|
151
|
+
}
|
|
152
|
+
return candidates
|
|
153
|
+
.toSorted((a, b) => a.start - b.start)
|
|
154
|
+
.flatMap((node) => node.type === "TSTypeAliasDeclaration"
|
|
155
|
+
? intersectionsOfAlias(sourceText, node)
|
|
156
|
+
: intersectionsOfParameter(sourceText, node));
|
|
157
|
+
}
|
|
158
|
+
function listParts(parts) {
|
|
159
|
+
return parts.map(({ text }) => `\`${firstLineOf(text)}\``).join(", ");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Judges a props intersection from the kinds its parts resolved to, or returns `undefined` when it must stay.
|
|
163
|
+
*
|
|
164
|
+
* @remarks An intersection stays a `type` when any part is a union, a type parameter or not an
|
|
165
|
+
* object; it is reported when an interface could extend every part, or when a part did not resolve.
|
|
166
|
+
*
|
|
167
|
+
* @since 0.15.0
|
|
168
|
+
*/
|
|
169
|
+
export function judgePropsIntersection(intersection, kinds) {
|
|
170
|
+
const { site, line, raw, wrapper, parts } = intersection;
|
|
171
|
+
const unresolved = parts.filter((_, index) => kinds[index] === "unresolved" || kinds[index] === undefined);
|
|
172
|
+
if (unresolved.length > 0) {
|
|
173
|
+
return {
|
|
174
|
+
line,
|
|
175
|
+
raw,
|
|
176
|
+
reason: `${listParts(unresolved)} did not resolve to a type, so whether an interface can extend it is unknown — fix the type or build what it imports`,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (!kinds.every((kind) => kind === "object")) {
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
const where = site === "parameter" ? " inline" : wrapper === undefined ? "" : ` passed to \`${wrapper}\``;
|
|
183
|
+
const remedy = site === "parameter" ? "name it as an interface" : "declare an interface";
|
|
184
|
+
return {
|
|
185
|
+
line,
|
|
186
|
+
raw,
|
|
187
|
+
reason: `joins object types with \`&\`${where} — ${remedy} that extends them, so a conflicting member fails at the declaration instead of narrowing silently`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { logger } from "#core/logger";
|
|
2
2
|
/**
|
|
3
|
-
* Human-readable
|
|
3
|
+
* Human-readable props-declaration report.
|
|
4
4
|
*
|
|
5
|
-
* @since 0.
|
|
5
|
+
* @since 0.15.0
|
|
6
6
|
*/
|
|
7
|
-
export function
|
|
7
|
+
export function presentPropsAuditResult(result) {
|
|
8
8
|
for (const file of result.files) {
|
|
9
9
|
logger.out(`\n${file.relativePath}`);
|
|
10
10
|
for (const { line, raw, reason } of file.violations) {
|
|
@@ -13,9 +13,9 @@ export function presentConstantAuditResult(result) {
|
|
|
13
13
|
}
|
|
14
14
|
const allowlistSuffix = result.allowlistedCount > 0 ? ` (${result.allowlistedCount} allowlisted)` : "";
|
|
15
15
|
if (result.violationCount > 0) {
|
|
16
|
-
logger.out(`\n✖ ${result.violationCount}
|
|
16
|
+
logger.out(`\n✖ ${result.violationCount} props-declaration violation(s)${allowlistSuffix}`);
|
|
17
17
|
}
|
|
18
18
|
else {
|
|
19
|
-
logger.out(`✓
|
|
19
|
+
logger.out(`✓ No props intersection an interface could express across ${result.scannedFileCount} file(s)${allowlistSuffix}`);
|
|
20
20
|
}
|
|
21
21
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
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 props`, defaulting to the repo root.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.15.0
|
|
9
|
+
*/
|
|
10
|
+
export declare function preparePropsAudit(fs: Filesystem, args: {
|
|
11
|
+
readonly currentWorkingDirectory: string;
|
|
12
|
+
readonly rawTarget: string | undefined;
|
|
13
|
+
}): Promise<Result<AuditCommandPrelude, AppError>>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { prepareRepoRootAudit } from "#audit/prepare";
|
|
2
|
+
/**
|
|
3
|
+
* Loads config and resolves the scan target for `audit props`, defaulting to the repo root.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.15.0
|
|
6
|
+
*/
|
|
7
|
+
export async function preparePropsAudit(fs, args) {
|
|
8
|
+
return prepareRepoRootAudit(fs, args, (config) => config.audit?.props?.allowlist ?? []);
|
|
9
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { PropsAuditResult } from "#audit/domain/types";
|
|
2
|
+
import type { PropsTypeProbe } from "#audit/props/type-probe";
|
|
3
|
+
import { AppError } from "#core/errors";
|
|
4
|
+
import type { Filesystem } from "#core/filesystem/filesystem";
|
|
5
|
+
import type { Result } from "#core/result";
|
|
6
|
+
/**
|
|
7
|
+
* Scans a target path for component props aliases joined with `&` that an interface could express.
|
|
8
|
+
*
|
|
9
|
+
* @remarks The type server starts only once a file holds a candidate, so a tree without one never spawns it.
|
|
10
|
+
*
|
|
11
|
+
* @since 0.15.0
|
|
12
|
+
*/
|
|
13
|
+
export declare function runPropsAudit(fs: Filesystem, args: {
|
|
14
|
+
readonly rootDir: string;
|
|
15
|
+
readonly targetPath: string;
|
|
16
|
+
readonly allowlist: ReadonlyArray<string>;
|
|
17
|
+
}, createProbe?: () => Promise<PropsTypeProbe>): Promise<Result<PropsAuditResult, AppError>>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { findPropsIntersections, judgePropsIntersection } from "#audit/props/domain/props-intersection";
|
|
3
|
+
import { createPropsTypeProbe } from "#audit/props/type-probe";
|
|
4
|
+
import { AppError, messageFrom } from "#core/errors";
|
|
5
|
+
import { err, ok } from "#core/result";
|
|
6
|
+
import { walkTsxFiles } from "#core/workspace/typescript-walk";
|
|
7
|
+
/**
|
|
8
|
+
* Scans a target path for component props aliases joined with `&` that an interface could express.
|
|
9
|
+
*
|
|
10
|
+
* @remarks The type server starts only once a file holds a candidate, so a tree without one never spawns it.
|
|
11
|
+
*
|
|
12
|
+
* @since 0.15.0
|
|
13
|
+
*/
|
|
14
|
+
export async function runPropsAudit(fs, args, createProbe = createPropsTypeProbe) {
|
|
15
|
+
let probe;
|
|
16
|
+
try {
|
|
17
|
+
const allowlist = new Set(args.allowlist);
|
|
18
|
+
const { rootDir, targetPath } = args;
|
|
19
|
+
const filesToScan = fs.statSync(targetPath).isFile() ? [targetPath] : walkTsxFiles(targetPath, fs);
|
|
20
|
+
const files = [];
|
|
21
|
+
let violationCount = 0;
|
|
22
|
+
let allowlistedCount = 0;
|
|
23
|
+
for (const absolutePath of filesToScan) {
|
|
24
|
+
const intersections = findPropsIntersections(absolutePath, fs.readFileSync(absolutePath, "utf8"));
|
|
25
|
+
if (intersections.length === 0) {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
probe ??= await createProbe();
|
|
29
|
+
const classify = probe.forFile(absolutePath);
|
|
30
|
+
const relativePath = path.relative(rootDir, absolutePath).split(path.sep).join("/");
|
|
31
|
+
const remaining = intersections
|
|
32
|
+
.map((intersection) => judgePropsIntersection(intersection, classify(intersection.parts)))
|
|
33
|
+
.filter((violation) => violation !== undefined)
|
|
34
|
+
.filter(({ raw }) => {
|
|
35
|
+
const isAllowed = allowlist.has(raw) || allowlist.has(`${relativePath}:${raw}`);
|
|
36
|
+
if (isAllowed) {
|
|
37
|
+
allowlistedCount++;
|
|
38
|
+
}
|
|
39
|
+
return !isAllowed;
|
|
40
|
+
});
|
|
41
|
+
if (remaining.length === 0) {
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
violationCount += remaining.length;
|
|
45
|
+
files.push({ relativePath, violations: remaining });
|
|
46
|
+
}
|
|
47
|
+
return ok({ files, violationCount, allowlistedCount, scannedFileCount: filesToScan.length });
|
|
48
|
+
}
|
|
49
|
+
catch (caughtError) {
|
|
50
|
+
return err(caughtError instanceof AppError
|
|
51
|
+
? caughtError
|
|
52
|
+
: new AppError("INFRA_FAILURE", messageFrom(caughtError), caughtError));
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
probe?.dispose();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Type probe that resolves what each part of a props intersection is. */
|
|
2
|
+
import type { ConstituentKind, IntersectionPart } from "#audit/props/domain/props-intersection";
|
|
3
|
+
/** Resolves the kind of each intersection part in one file, in the order given. */
|
|
4
|
+
type ConstituentClassifier = (parts: ReadonlyArray<IntersectionPart>) => Array<ConstituentKind>;
|
|
5
|
+
/**
|
|
6
|
+
* A whole-run type probe backing `audit props`, bound to one type server.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.15.0
|
|
9
|
+
*/
|
|
10
|
+
export interface PropsTypeProbe {
|
|
11
|
+
/** Returns the file's classifier, which reports every part unresolved when no project types the file. */
|
|
12
|
+
forFile(filePath: string): ConstituentClassifier;
|
|
13
|
+
dispose(): void;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates a type probe over the native TypeScript type server for `audit props`.
|
|
17
|
+
*
|
|
18
|
+
* @throws AppError when the `typescript` package providing the type server cannot be loaded.
|
|
19
|
+
*
|
|
20
|
+
* @since 0.15.0
|
|
21
|
+
*/
|
|
22
|
+
export declare function createPropsTypeProbe(): Promise<PropsTypeProbe>;
|
|
23
|
+
export {};
|