@yearofthedan/warp 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +97 -2
- package/dist/analysis/complexity.d.ts +4 -0
- package/dist/analysis/complexity.js +84 -0
- package/dist/analysis/folders.d.ts +2 -0
- package/dist/analysis/folders.js +15 -0
- package/dist/analysis/imports.d.ts +13 -0
- package/dist/analysis/imports.js +135 -0
- package/dist/analysis/members.d.ts +4 -0
- package/dist/analysis/members.js +190 -0
- package/dist/analysis/source.d.ts +13 -0
- package/dist/analysis/source.js +29 -0
- package/dist/analysis/specifiers.d.ts +2 -0
- package/dist/analysis/specifiers.js +6 -0
- package/dist/analysis/typescript.d.ts +2 -0
- package/dist/analysis/typescript.js +105 -0
- package/dist/app/check.d.ts +23 -0
- package/dist/app/check.js +15 -0
- package/dist/app/checkModel.d.ts +5 -0
- package/dist/app/checkModel.js +30 -0
- package/dist/app/diff.d.ts +25 -0
- package/dist/app/diff.js +53 -0
- package/dist/app/facts.d.ts +7 -0
- package/dist/app/facts.js +55 -0
- package/dist/app/load.d.ts +13 -0
- package/dist/app/load.js +76 -0
- package/dist/app/ports.d.ts +41 -0
- package/dist/app/ports.js +1 -0
- package/dist/app/unclassified.d.ts +5 -0
- package/dist/app/unclassified.js +13 -0
- package/dist/builtins/cognitive-complexity/cognitiveComplexity.d.ts +6 -0
- package/dist/builtins/cognitive-complexity/cognitiveComplexity.js +26 -0
- package/dist/builtins/components.d.ts +2 -0
- package/dist/builtins/components.js +20 -0
- package/dist/builtins/dependency-direction/dependencyDirection.d.ts +2 -0
- package/dist/builtins/dependency-direction/dependencyDirection.js +65 -0
- package/dist/builtins/file-cohesion/fileCohesion.d.ts +6 -0
- package/dist/builtins/file-cohesion/fileCohesion.js +30 -0
- package/dist/builtins/function-cohesion/functionCohesion.d.ts +6 -0
- package/dist/builtins/function-cohesion/functionCohesion.js +30 -0
- package/dist/builtins/index.d.ts +4 -0
- package/dist/builtins/index.js +30 -0
- package/dist/builtins/loops.d.ts +25 -0
- package/dist/builtins/loops.js +64 -0
- package/dist/builtins/module-cycle/moduleCycle.d.ts +3 -0
- package/dist/builtins/module-cycle/moduleCycle.js +61 -0
- package/dist/builtins/module-externals/moduleExternals.d.ts +2 -0
- package/dist/builtins/module-externals/moduleExternals.js +41 -0
- package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.d.ts +2 -0
- package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +47 -0
- package/dist/builtins/no-cycle/noCycle.d.ts +3 -0
- package/dist/builtins/no-cycle/noCycle.js +39 -0
- package/dist/builtins/no-double-export/noDoubleExport.d.ts +2 -0
- package/dist/builtins/no-double-export/noDoubleExport.js +38 -0
- package/dist/builtins/packages.d.ts +2 -0
- package/dist/builtins/packages.js +5 -0
- package/dist/builtins/place.d.ts +2 -0
- package/dist/builtins/place.js +6 -0
- package/dist/builtins/shared.d.ts +10 -0
- package/dist/builtins/shared.js +13 -0
- package/dist/builtins/unused-declaration/declarations.d.ts +32 -0
- package/dist/builtins/unused-declaration/declarations.js +26 -0
- package/dist/builtins/unused-declaration/empty.d.ts +3 -0
- package/dist/builtins/unused-declaration/empty.js +22 -0
- package/dist/builtins/unused-declaration/grants.d.ts +3 -0
- package/dist/builtins/unused-declaration/grants.js +48 -0
- package/dist/builtins/unused-declaration/surfaces.d.ts +3 -0
- package/dist/builtins/unused-declaration/surfaces.js +57 -0
- package/dist/builtins/unused-declaration/unusedDeclaration.d.ts +2 -0
- package/dist/builtins/unused-declaration/unusedDeclaration.js +14 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +168 -0
- package/dist/config/loadConfig.d.ts +7 -0
- package/dist/config/loadConfig.js +53 -0
- package/dist/config/toolDigest.d.ts +1 -0
- package/dist/config/toolDigest.js +16 -0
- package/dist/git/cache.d.ts +3 -0
- package/dist/git/cache.js +41 -0
- package/dist/git/repository.d.ts +3 -0
- package/dist/git/repository.js +81 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/model/archetype/builder.d.ts +183 -0
- package/dist/model/archetype/builder.js +85 -0
- package/dist/model/archetype/data.d.ts +92 -0
- package/dist/model/archetype/data.js +1 -0
- package/dist/model/archetype/draft.d.ts +37 -0
- package/dist/model/archetype/draft.js +275 -0
- package/dist/model/archetype/reach.d.ts +35 -0
- package/dist/model/archetype/reach.js +209 -0
- package/dist/model/archetype/references.d.ts +13 -0
- package/dist/model/archetype/references.js +166 -0
- package/dist/model/archetype/requirements.d.ts +5 -0
- package/dist/model/archetype/requirements.js +69 -0
- package/dist/model/archetype/resolve.d.ts +30 -0
- package/dist/model/archetype/resolve.js +311 -0
- package/dist/model/archetype/rulesets.d.ts +4 -0
- package/dist/model/archetype/rulesets.js +115 -0
- package/dist/model/archetype/settings.d.ts +21 -0
- package/dist/model/archetype/settings.js +64 -0
- package/dist/model/archetype/shared.d.ts +5 -0
- package/dist/model/archetype/shared.js +4 -0
- package/dist/model/configError.d.ts +3 -0
- package/dist/model/configError.js +3 -0
- package/dist/model/facts.d.ts +57 -0
- package/dist/model/facts.js +1 -0
- package/dist/reporters/claudeHook.d.ts +2 -0
- package/dist/reporters/claudeHook.js +10 -0
- package/dist/reporters/index.d.ts +2 -0
- package/dist/reporters/index.js +9 -0
- package/dist/reporters/json.d.ts +2 -0
- package/dist/reporters/json.js +4 -0
- package/dist/reporters/model.d.ts +4 -0
- package/dist/reporters/model.js +60 -0
- package/dist/reporters/omp.d.ts +2 -0
- package/dist/reporters/omp.js +8 -0
- package/dist/reporters/reporter.d.ts +26 -0
- package/dist/reporters/reporter.js +14 -0
- package/dist/reporters/sarif.d.ts +2 -0
- package/dist/reporters/sarif.js +44 -0
- package/dist/reporters/text.d.ts +6 -0
- package/dist/reporters/text.js +35 -0
- package/dist/rules/diff.d.ts +10 -0
- package/dist/rules/diff.js +31 -0
- package/dist/rules/registry.d.ts +5 -0
- package/dist/rules/registry.js +33 -0
- package/dist/rules/rule.d.ts +59 -0
- package/dist/rules/rule.js +18 -0
- package/integrations/omp/warp.ts +40 -0
- package/package.json +44 -4
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import { join, relative, sep } from 'node:path';
|
|
4
|
+
import { API } from 'typescript/sync';
|
|
5
|
+
import { freshFacts } from '../app/facts.js';
|
|
6
|
+
import { fileEdges } from './imports.js';
|
|
7
|
+
import { moduleSpecifiers } from './specifiers.js';
|
|
8
|
+
import { countLines, readSource } from './source.js';
|
|
9
|
+
import { functionFacts, fileMembers } from './members.js';
|
|
10
|
+
export const typescriptAnalyzer = {
|
|
11
|
+
analyze(root, tsconfig, store) {
|
|
12
|
+
const api = new API({ cwd: root });
|
|
13
|
+
try {
|
|
14
|
+
const tsconfigs = tsconfig.map((path) => join(root, path));
|
|
15
|
+
const snapshot = api.createSnapshot({ openProjects: tsconfigs });
|
|
16
|
+
const projects = tsconfigs.map((path) => {
|
|
17
|
+
const project = snapshot.getConfiguredProject(path);
|
|
18
|
+
if (!project)
|
|
19
|
+
throw new Error(`could not load ${path}`);
|
|
20
|
+
return { project, files: projectFiles(root, project) };
|
|
21
|
+
});
|
|
22
|
+
const hashes = new Map(projects.flatMap(({ files }) => [...files.values()].map((file) => [file, hashOf(root, file)])));
|
|
23
|
+
const digest = digestOf(root, projects);
|
|
24
|
+
const fresh = freshFacts(store?.read(), { digest, hashes });
|
|
25
|
+
const cached = new Map();
|
|
26
|
+
for (const { project, files } of projects)
|
|
27
|
+
for (const [file, entry] of analyzeProgram(project, files, fresh, cached))
|
|
28
|
+
cached.set(file, entry);
|
|
29
|
+
const facts = [...cached.values()].flatMap(({ facts }) => (facts ? [facts] : []));
|
|
30
|
+
if (facts.length === 0)
|
|
31
|
+
throw new Error(`${tsconfigs.join(', ')} include no files to check`);
|
|
32
|
+
const files = [...hashes].map(([file, hash]) => [file, { ...cached.get(file), hash }]);
|
|
33
|
+
store?.write({ digest, files: Object.fromEntries(files) });
|
|
34
|
+
return { files: facts };
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
api.close();
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
const projectFiles = (root, { program }) => {
|
|
42
|
+
const files = new Map();
|
|
43
|
+
for (const fileName of program.getSourceFileNames()) {
|
|
44
|
+
const file = toRelative(root, fileName);
|
|
45
|
+
if (file && !file.includes('node_modules/'))
|
|
46
|
+
files.set(fileName, file);
|
|
47
|
+
}
|
|
48
|
+
return files;
|
|
49
|
+
};
|
|
50
|
+
const hashOf = (root, file) => createHash('sha256')
|
|
51
|
+
.update(readFileSync(join(root, file)))
|
|
52
|
+
.digest('hex')
|
|
53
|
+
.slice(0, 16);
|
|
54
|
+
const digestOf = (root, projects) => {
|
|
55
|
+
const digest = createHash('sha256');
|
|
56
|
+
const own = (path) => path.split(root).join('.');
|
|
57
|
+
for (const { project, files } of projects) {
|
|
58
|
+
digest.update(own(JSON.stringify(project.program.getCompilerOptions())));
|
|
59
|
+
for (const fileName of project.program.getSourceFileNames()) {
|
|
60
|
+
if (files.has(fileName))
|
|
61
|
+
continue;
|
|
62
|
+
const { size, mtimeMs } = statSync(fileName);
|
|
63
|
+
digest.update(`${own(fileName)}\0${size}\0${mtimeMs}\0`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return digest.digest('hex').slice(0, 16);
|
|
67
|
+
};
|
|
68
|
+
const analyzeProgram = ({ program, checker }, files, fresh, done) => {
|
|
69
|
+
const byPath = new Map([...files].flatMap(([fileName, file]) => [
|
|
70
|
+
[fileName, file],
|
|
71
|
+
[fileName.toLowerCase(), file],
|
|
72
|
+
]));
|
|
73
|
+
const resolver = {
|
|
74
|
+
program,
|
|
75
|
+
checker,
|
|
76
|
+
relative: (path) => byPath.get(path) ?? byPath.get(path.toLowerCase()),
|
|
77
|
+
};
|
|
78
|
+
const analyzed = new Map();
|
|
79
|
+
for (const [fileName, file] of files) {
|
|
80
|
+
if (done.has(file) || file.endsWith('.d.ts'))
|
|
81
|
+
continue;
|
|
82
|
+
const reused = fresh.get(file);
|
|
83
|
+
if (reused) {
|
|
84
|
+
analyzed.set(file, reused);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const sourceFile = program.getSourceFile(fileName);
|
|
88
|
+
if (!sourceFile)
|
|
89
|
+
continue;
|
|
90
|
+
const source = readSource(checker, sourceFile, file);
|
|
91
|
+
const facts = {
|
|
92
|
+
path: file,
|
|
93
|
+
lines: countLines(sourceFile.text),
|
|
94
|
+
...fileEdges(source, resolver),
|
|
95
|
+
members: fileMembers(source),
|
|
96
|
+
functions: functionFacts(source),
|
|
97
|
+
};
|
|
98
|
+
analyzed.set(file, { specifiers: moduleSpecifiers(sourceFile), facts });
|
|
99
|
+
}
|
|
100
|
+
return analyzed;
|
|
101
|
+
};
|
|
102
|
+
const toRelative = (root, fileName) => {
|
|
103
|
+
const path = relative(root, fileName);
|
|
104
|
+
return path.startsWith('..') ? undefined : path.split(sep).join('/');
|
|
105
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ConfigData } from '../model/archetype/data.ts';
|
|
2
|
+
import { type Model } from '../model/archetype/resolve.ts';
|
|
3
|
+
import type { Project } from '../model/facts.ts';
|
|
4
|
+
import type { Finding, Rule } from '../rules/rule.ts';
|
|
5
|
+
import type { Analyzer, FactsStore, FoldersAt } from './ports.ts';
|
|
6
|
+
export interface ProjectCheck {
|
|
7
|
+
config: unknown;
|
|
8
|
+
requiredFile: string;
|
|
9
|
+
check(root: string): Finding[];
|
|
10
|
+
}
|
|
11
|
+
export interface Adapters {
|
|
12
|
+
analyzer: Analyzer;
|
|
13
|
+
foldersAt: FoldersAt;
|
|
14
|
+
facts?: FactsStore;
|
|
15
|
+
}
|
|
16
|
+
export declare const modelProject: ({ analyzer, foldersAt, facts }: Adapters, root: string, config: ConfigData) => {
|
|
17
|
+
model: Model;
|
|
18
|
+
project: Project;
|
|
19
|
+
};
|
|
20
|
+
export declare const projectCheck: (adapters: Adapters, config: ConfigData, { rules, unclassifiedDocs }?: {
|
|
21
|
+
rules?: readonly Rule[];
|
|
22
|
+
unclassifiedDocs?: string;
|
|
23
|
+
}) => ProjectCheck;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { checkModel } from './checkModel.js';
|
|
2
|
+
import { resolveModel } from '../model/archetype/resolve.js';
|
|
3
|
+
export const modelProject = ({ analyzer, foldersAt, facts }, root, config) => {
|
|
4
|
+
const project = analyzer.analyze(root, config.tsconfig, facts);
|
|
5
|
+
const files = project.files.map((file) => file.path);
|
|
6
|
+
return { model: resolveModel(config, foldersAt(root), files), project };
|
|
7
|
+
};
|
|
8
|
+
export const projectCheck = (adapters, config, { rules = [], unclassifiedDocs } = {}) => ({
|
|
9
|
+
config,
|
|
10
|
+
requiredFile: config.tsconfig[0],
|
|
11
|
+
check: (root) => {
|
|
12
|
+
const { model, project } = modelProject(adapters, root, config);
|
|
13
|
+
return checkModel(config, model, project, rules, unclassifiedDocs);
|
|
14
|
+
},
|
|
15
|
+
});
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Project } from '../model/facts.ts';
|
|
2
|
+
import type { Rule, Finding } from '../rules/rule.ts';
|
|
3
|
+
import type { ConfigData } from '../model/archetype/data.ts';
|
|
4
|
+
import type { Model } from '../model/archetype/resolve.ts';
|
|
5
|
+
export declare const checkModel: (config: ConfigData, model: Model, project: Project, rules?: readonly Rule[], unclassifiedDocs?: string) => Finding[];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { verdicts } from '../model/archetype/reach.js';
|
|
2
|
+
import { settings } from '../model/archetype/settings.js';
|
|
3
|
+
import { unclassifiedFindings } from './unclassified.js';
|
|
4
|
+
export const checkModel = (config, model, project, rules = [], unclassifiedDocs) => {
|
|
5
|
+
const settled = settings(config, model);
|
|
6
|
+
const judged = verdicts(config, model);
|
|
7
|
+
const found = rules.flatMap((rule) => {
|
|
8
|
+
const findings = run(rule, { project, config, model, verdicts: judged }, settled);
|
|
9
|
+
return rule.docs ? findings.map((finding) => ({ ...finding, docs: rule.docs })) : findings;
|
|
10
|
+
});
|
|
11
|
+
return [...unclassifiedFindings(model, settled, unclassifiedDocs), ...found].map((finding) => placed(model, finding));
|
|
12
|
+
};
|
|
13
|
+
const placed = (model, finding) => {
|
|
14
|
+
const module = model.moduleOf(finding.file);
|
|
15
|
+
if (!module)
|
|
16
|
+
return finding;
|
|
17
|
+
return { ...finding, module: model.isTest(finding.file) ? `${module.id}:tests` : module.id };
|
|
18
|
+
};
|
|
19
|
+
const run = (rule, shared, settled) => {
|
|
20
|
+
if (rule.scope === 'project')
|
|
21
|
+
return rule.check({
|
|
22
|
+
...shared,
|
|
23
|
+
atFile: (file) => settled.atFile(file, rule.id, rule.defaults),
|
|
24
|
+
atModule: (module) => settled.atModule(module, rule.id, rule.defaults),
|
|
25
|
+
});
|
|
26
|
+
return shared.project.files.flatMap((file) => {
|
|
27
|
+
const { on, options } = settled.atFile(file.path, rule.id, rule.defaults);
|
|
28
|
+
return on ? rule.check({ file, options }) : [];
|
|
29
|
+
});
|
|
30
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Delta } from '../rules/diff.ts';
|
|
2
|
+
import type { ProjectCheck } from './check.ts';
|
|
3
|
+
import type { FindingsCache, Repository } from './ports.ts';
|
|
4
|
+
export interface Range {
|
|
5
|
+
base: string;
|
|
6
|
+
head?: string;
|
|
7
|
+
fromMergeBase: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare class InvalidRange extends Error {
|
|
10
|
+
}
|
|
11
|
+
export declare const parseRange: (range: string) => Range;
|
|
12
|
+
export interface DiffRequest {
|
|
13
|
+
range: Range;
|
|
14
|
+
root: string;
|
|
15
|
+
project: ProjectCheck;
|
|
16
|
+
configDigest?: string;
|
|
17
|
+
toolDigest: string;
|
|
18
|
+
sinceLastRun?: boolean;
|
|
19
|
+
}
|
|
20
|
+
type Ports = {
|
|
21
|
+
repository: Repository;
|
|
22
|
+
cache: FindingsCache;
|
|
23
|
+
};
|
|
24
|
+
export declare const diffProject: (request: DiffRequest, ports: Ports) => Delta;
|
|
25
|
+
export {};
|
package/dist/app/diff.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { anchorAtChange, diff } from '../rules/diff.js';
|
|
3
|
+
export class InvalidRange extends Error {
|
|
4
|
+
}
|
|
5
|
+
export const parseRange = (range) => {
|
|
6
|
+
const match = /^(.+?)(\.\.\.|\.\.)(.*)$/.exec(range);
|
|
7
|
+
const [base, separator, head] = match ? match.slice(1) : [range, '', ''];
|
|
8
|
+
if (!base || base.includes('..') || head.includes('..'))
|
|
9
|
+
throw new InvalidRange(`${range} is not a range: expected <base>, <base>..<head> or <base>...<head>`);
|
|
10
|
+
return { base, ...(head ? { head } : {}), fromMergeBase: separator === '...' };
|
|
11
|
+
};
|
|
12
|
+
const changedAt = (lines) => ({ file, line }) => lines.some((range) => range.file === file && range.from <= line && line <= range.to);
|
|
13
|
+
const baseOf = ({ base, head, fromMergeBase }, repository) => fromMergeBase ? repository.mergeBase(base, head ?? 'HEAD') : base;
|
|
14
|
+
export const diffProject = (request, ports) => anchorAtChange(compareProject(request, ports), () => changedAt(ports.repository.changedLines(baseOf(request.range, ports.repository), request.range.head)));
|
|
15
|
+
const compareProject = ({ range, root, project, configDigest = '', toolDigest, sinceLastRun = false }, { repository, cache }) => {
|
|
16
|
+
const configHash = createHash('sha256')
|
|
17
|
+
.update(JSON.stringify(project.config))
|
|
18
|
+
.update(configDigest)
|
|
19
|
+
.digest('hex')
|
|
20
|
+
.slice(0, 16);
|
|
21
|
+
const atCommit = (ref) => {
|
|
22
|
+
const commit = repository.commit(ref);
|
|
23
|
+
const key = `${toolDigest}-${configHash}-${commit}-${repository.projectPath().replaceAll('/', '_')}`;
|
|
24
|
+
const cached = cache.get(key);
|
|
25
|
+
if (cached)
|
|
26
|
+
return cached;
|
|
27
|
+
const checkout = repository.checkout(commit, project.requiredFile);
|
|
28
|
+
try {
|
|
29
|
+
const findings = checkout.projectRoot ? project.check(checkout.projectRoot) : [];
|
|
30
|
+
cache.set(key, findings);
|
|
31
|
+
cache.prune((other) => other.startsWith(`${toolDigest}-`));
|
|
32
|
+
return findings;
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
checkout.dispose();
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const { head } = range;
|
|
39
|
+
if (sinceLastRun && head !== undefined)
|
|
40
|
+
throw new InvalidRange('a diff since the last run compares the working tree, so its range takes no <head>');
|
|
41
|
+
const baseFindings = () => atCommit(baseOf(range, repository));
|
|
42
|
+
if (head !== undefined)
|
|
43
|
+
return diff(baseFindings(), atCommit(head));
|
|
44
|
+
const current = project.check(root);
|
|
45
|
+
if (!sinceLastRun)
|
|
46
|
+
return diff(baseFindings(), current);
|
|
47
|
+
const worktree = `${toolDigest}-${configHash}-last-run-${createHash('sha256').update(root).digest('hex').slice(0, 16)}-`;
|
|
48
|
+
const lastRunKey = `${worktree}${repository.commit('HEAD')}`;
|
|
49
|
+
const delta = diff(cache.get(lastRunKey) ?? baseFindings(), current);
|
|
50
|
+
cache.set(lastRunKey, current);
|
|
51
|
+
cache.prune((key) => key === lastRunKey || !key.startsWith(worktree));
|
|
52
|
+
return delta;
|
|
53
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Cache, CachedFacts, CachedFile, FactsStore } from './ports.ts';
|
|
2
|
+
export interface CurrentFiles {
|
|
3
|
+
digest: string;
|
|
4
|
+
hashes: ReadonlyMap<string, string>;
|
|
5
|
+
}
|
|
6
|
+
export declare const factsStore: (cache: Cache<CachedFacts>, toolDigest: string, projectPath: string) => FactsStore;
|
|
7
|
+
export declare const freshFacts: (cached: CachedFacts | undefined, current: CurrentFiles) => Map<string, CachedFile>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export const factsStore = (cache, toolDigest, projectPath) => {
|
|
2
|
+
const key = `${toolDigest}-facts-${projectPath.replaceAll('/', '_')}`;
|
|
3
|
+
return {
|
|
4
|
+
read: () => cache.get(key),
|
|
5
|
+
write(facts) {
|
|
6
|
+
cache.set(key, facts);
|
|
7
|
+
cache.prune((other) => other.startsWith(`${toolDigest}-`));
|
|
8
|
+
},
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
export const freshFacts = (cached, current) => {
|
|
12
|
+
if (!cached || cached.digest !== current.digest)
|
|
13
|
+
return new Map();
|
|
14
|
+
const before = new Map(Object.entries(cached.files));
|
|
15
|
+
const changed = [...before.keys(), ...current.hashes.keys()].filter((file) => before.get(file)?.hash !== current.hashes.get(file));
|
|
16
|
+
if (changed.some(isDeclarationFile))
|
|
17
|
+
return new Map();
|
|
18
|
+
const stale = importersOf(new Set([...changed, ...reresolved(before, current.hashes)]), before);
|
|
19
|
+
const fresh = new Map();
|
|
20
|
+
for (const [file, entry] of before)
|
|
21
|
+
if (entry.facts && !stale.has(file) && current.hashes.has(file))
|
|
22
|
+
fresh.set(file, entry);
|
|
23
|
+
return fresh;
|
|
24
|
+
};
|
|
25
|
+
const isDeclarationFile = (file) => file.endsWith('.d.ts');
|
|
26
|
+
const reresolved = (before, hashes) => {
|
|
27
|
+
const moved = [...before.keys(), ...hashes.keys()].filter((file) => before.has(file) !== hashes.has(file));
|
|
28
|
+
const names = new Set(moved.flatMap(namesOf));
|
|
29
|
+
return [...before].flatMap(([file, { specifiers = [] }]) => specifiers.some((specifier) => names.has(specifierName(specifier))) ? [file] : []);
|
|
30
|
+
};
|
|
31
|
+
const namesOf = (file) => {
|
|
32
|
+
const [name, ...dirs] = file.split('/').reverse();
|
|
33
|
+
const stem = name.replace(/\.[^.]*$/, '');
|
|
34
|
+
return stem === 'index' && dirs[0] ? [stem, dirs[0]] : [stem];
|
|
35
|
+
};
|
|
36
|
+
const specifierName = (specifier) => {
|
|
37
|
+
const name = specifier.split('/').at(-1);
|
|
38
|
+
return name === '' || name === '.' || name === '..' ? 'index' : name.replace(/\.[cm]?[jt]sx?$/, '');
|
|
39
|
+
};
|
|
40
|
+
const importersOf = (seeds, before) => {
|
|
41
|
+
const importers = reverseImports(before);
|
|
42
|
+
const stale = new Set(seeds);
|
|
43
|
+
for (const file of stale)
|
|
44
|
+
for (const importer of importers.get(file) ?? [])
|
|
45
|
+
stale.add(importer);
|
|
46
|
+
return stale;
|
|
47
|
+
};
|
|
48
|
+
const reverseImports = (before) => {
|
|
49
|
+
const importers = new Map();
|
|
50
|
+
const edges = [...before.values()].flatMap(({ facts }) => facts?.imports ?? []);
|
|
51
|
+
for (const { from, to, via = to } of edges)
|
|
52
|
+
for (const target of [to, via])
|
|
53
|
+
importers.set(target, (importers.get(target) ?? new Set()).add(from));
|
|
54
|
+
return importers;
|
|
55
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Rule } from '../rules/rule.ts';
|
|
2
|
+
import type { ConfigData } from '../model/archetype/data.ts';
|
|
3
|
+
export interface LoadedConfigData {
|
|
4
|
+
config: ConfigData;
|
|
5
|
+
rules: Rule[];
|
|
6
|
+
warnings: string[];
|
|
7
|
+
}
|
|
8
|
+
export interface LoadOptions {
|
|
9
|
+
builtins?: readonly Rule[];
|
|
10
|
+
ruleset?: string;
|
|
11
|
+
file?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare const loadConfigData: (raw: unknown, { builtins, ruleset, file }?: LoadOptions) => LoadedConfigData;
|
package/dist/app/load.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { pluginRules, registry } from '../rules/registry.js';
|
|
2
|
+
import { ConfigError } from '../model/configError.js';
|
|
3
|
+
import { noOptions } from '../rules/rule.js';
|
|
4
|
+
import { recordedAs } from '../model/archetype/builder.js';
|
|
5
|
+
import { collect, draft } from '../model/archetype/draft.js';
|
|
6
|
+
import { resolveDraft, toRules } from '../model/archetype/references.js';
|
|
7
|
+
import { checkRequirements, checkUnused } from '../model/archetype/requirements.js';
|
|
8
|
+
import { unclassified } from './unclassified.js';
|
|
9
|
+
import { withRuleset } from '../model/archetype/rulesets.js';
|
|
10
|
+
import { defined, isName, isRecord } from '../model/archetype/shared.js';
|
|
11
|
+
export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.config.ts' } = {}) => {
|
|
12
|
+
const errors = [];
|
|
13
|
+
const fail = (message) => {
|
|
14
|
+
if (!errors.includes(message))
|
|
15
|
+
errors.push(message);
|
|
16
|
+
};
|
|
17
|
+
const failed = () => {
|
|
18
|
+
if (errors.length > 0)
|
|
19
|
+
throw new ConfigError(errors.join('\n'));
|
|
20
|
+
};
|
|
21
|
+
if (!isRecord(raw))
|
|
22
|
+
throw new ConfigError('config: expected an object, defineConfig({ root })');
|
|
23
|
+
const unknownKeys = Object.keys(raw).filter((key) => !['root', 'tsconfig', 'tests', 'plugins', 'rulesets'].includes(key));
|
|
24
|
+
if (unknownKeys.length > 0)
|
|
25
|
+
fail(`config: unknown key ${unknownKeys.join(', ')}`);
|
|
26
|
+
const root = recordedAs(raw.root, 'archetype');
|
|
27
|
+
if (!root)
|
|
28
|
+
throw new ConfigError("config.root: expected an archetype, archetype('name')...");
|
|
29
|
+
const rules = [...registry([...(builtins ?? []), ...pluginRules(plugins(raw.plugins, fail))]).values()];
|
|
30
|
+
const drafts = [...collect(root.definition, fail)].map(([name, state]) => draft(name, state, fail));
|
|
31
|
+
const check = {
|
|
32
|
+
fail,
|
|
33
|
+
ruleIds: builtins && new Set([...rules.map((rule) => rule.id), unclassified]),
|
|
34
|
+
options: Object.fromEntries(rules.map((rule) => [rule.id, rule.parseOptions ?? noOptions])),
|
|
35
|
+
exposesOf: (name) => drafts.find((d) => d.data.name === name)?.exposes,
|
|
36
|
+
};
|
|
37
|
+
for (const d of drafts)
|
|
38
|
+
resolveDraft(check, d);
|
|
39
|
+
const structure = {
|
|
40
|
+
file,
|
|
41
|
+
root: root.definition.name,
|
|
42
|
+
archetypes: Object.fromEntries(drafts.map(({ data }) => [data.name, archetypeData(data)])),
|
|
43
|
+
tsconfig: tsconfigs(raw.tsconfig, fail),
|
|
44
|
+
...testPatterns(raw.tests, fail),
|
|
45
|
+
};
|
|
46
|
+
const config = withRuleset(structure, raw.rulesets, ruleset, (value, at) => toRules(check, value, at), fail);
|
|
47
|
+
checkUnused(drafts, fail);
|
|
48
|
+
failed();
|
|
49
|
+
const warnings = checkRequirements(config.archetypes, config.root, fail);
|
|
50
|
+
failed();
|
|
51
|
+
return { config, rules, warnings };
|
|
52
|
+
};
|
|
53
|
+
const archetypeData = ({ name, inline, description, identify, requires, modules, exposes, provides, tests, }) => defined({ name, inline, description, identify, requires, modules: modules.map(defined), exposes, provides, tests });
|
|
54
|
+
const plugins = (value, fail) => {
|
|
55
|
+
if (value === undefined)
|
|
56
|
+
return {};
|
|
57
|
+
if (isRecord(value))
|
|
58
|
+
return value;
|
|
59
|
+
fail('config.plugins: expected plugins by namespace');
|
|
60
|
+
return {};
|
|
61
|
+
};
|
|
62
|
+
const testPatterns = (value, fail) => {
|
|
63
|
+
if (value === undefined)
|
|
64
|
+
return {};
|
|
65
|
+
const selector = recordedAs(value, 'selector');
|
|
66
|
+
if (selector?.kind === 'files' && selector.patterns.every(isName))
|
|
67
|
+
return { tests: [...selector.patterns] };
|
|
68
|
+
fail("config.tests: expected the test entry files, files('**/*.test.ts', ...)");
|
|
69
|
+
return {};
|
|
70
|
+
};
|
|
71
|
+
const tsconfigs = (value, fail) => {
|
|
72
|
+
const paths = [value ?? 'tsconfig.json'].flat();
|
|
73
|
+
if (paths.length === 0 || !paths.every(isName))
|
|
74
|
+
fail('config.tsconfig: expected a path or a list of paths');
|
|
75
|
+
return paths;
|
|
76
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Folders } from '../model/archetype/resolve.ts';
|
|
2
|
+
import type { FileFacts, Project } from '../model/facts.ts';
|
|
3
|
+
import type { Finding } from '../rules/rule.ts';
|
|
4
|
+
export interface Analyzer {
|
|
5
|
+
analyze(root: string, tsconfig: readonly string[], facts?: FactsStore): Project;
|
|
6
|
+
}
|
|
7
|
+
export type FoldersAt = (root: string) => Folders;
|
|
8
|
+
export interface Repository {
|
|
9
|
+
projectPath(): string;
|
|
10
|
+
commit(ref: string): string;
|
|
11
|
+
mergeBase(a: string, b: string): string;
|
|
12
|
+
changedLines(base: string, head?: string): ChangedLines[];
|
|
13
|
+
checkout(commit: string, requiredFile: string): {
|
|
14
|
+
projectRoot?: string;
|
|
15
|
+
dispose(): void;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export interface ChangedLines {
|
|
19
|
+
file: string;
|
|
20
|
+
from: number;
|
|
21
|
+
to: number;
|
|
22
|
+
}
|
|
23
|
+
export interface Cache<T> {
|
|
24
|
+
get(key: string): T | undefined;
|
|
25
|
+
set(key: string, value: T): void;
|
|
26
|
+
prune(keep: (key: string) => boolean): void;
|
|
27
|
+
}
|
|
28
|
+
export type FindingsCache = Cache<Finding[]>;
|
|
29
|
+
export interface FactsStore {
|
|
30
|
+
read(): CachedFacts | undefined;
|
|
31
|
+
write(facts: CachedFacts): void;
|
|
32
|
+
}
|
|
33
|
+
export interface CachedFacts {
|
|
34
|
+
digest: string;
|
|
35
|
+
files: Record<string, CachedFile>;
|
|
36
|
+
}
|
|
37
|
+
export interface CachedFile {
|
|
38
|
+
hash: string;
|
|
39
|
+
specifiers?: string[];
|
|
40
|
+
facts?: FileFacts;
|
|
41
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Finding } from '../rules/rule.ts';
|
|
2
|
+
import type { Model } from '../model/archetype/resolve.ts';
|
|
3
|
+
import type { Settings } from '../model/archetype/settings.ts';
|
|
4
|
+
export declare const unclassified = "unclassified";
|
|
5
|
+
export declare const unclassifiedFindings: (model: Model, settled: Settings, docs: string | undefined) => Finding[];
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const unclassified = 'unclassified';
|
|
2
|
+
export const unclassifiedFindings = (model, settled, docs) => model.modules.flatMap((module) => (settled.decidedAt(module, unclassified) ?? module.parent === undefined)
|
|
3
|
+
? module.looseFiles.map((file) => ({
|
|
4
|
+
rule: unclassified,
|
|
5
|
+
key: `${unclassified}:${file}`,
|
|
6
|
+
file,
|
|
7
|
+
line: 1,
|
|
8
|
+
value: 1,
|
|
9
|
+
message: `${file} is in no module of ${module.id} (${module.archetype}), so nothing says what it may import. ` +
|
|
10
|
+
`Add a files module to ${module.archetype} that matches it, or move it into a module's folder.`,
|
|
11
|
+
...(docs ? { docs } : {}),
|
|
12
|
+
}))
|
|
13
|
+
: []);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { wholeNumberOptions } from '../../rules/rule.js';
|
|
2
|
+
import { withOrdinals } from '../shared.js';
|
|
3
|
+
const defaults = { max: 15 };
|
|
4
|
+
export const cognitiveComplexity = {
|
|
5
|
+
id: 'cognitive-complexity',
|
|
6
|
+
defaults,
|
|
7
|
+
parseOptions: wholeNumberOptions(defaults),
|
|
8
|
+
check: ({ file, options }) => withOrdinals(file.functions).flatMap(([fn, name]) => {
|
|
9
|
+
if (!fn.complexity || fn.complexity.total <= options.max)
|
|
10
|
+
return [];
|
|
11
|
+
const top = [...fn.complexity.increments].sort((a, b) => b.amount - a.amount || a.line - b.line).slice(0, 3);
|
|
12
|
+
return [
|
|
13
|
+
{
|
|
14
|
+
rule: 'cognitive-complexity',
|
|
15
|
+
key: `cognitive-complexity:${file.path}:${name}`,
|
|
16
|
+
file: file.path,
|
|
17
|
+
line: fn.line,
|
|
18
|
+
value: fn.complexity.total,
|
|
19
|
+
limit: options.max,
|
|
20
|
+
message: `Function ${fn.name} in ${file.path}:${fn.line} has cognitive complexity ${fn.complexity.total} (limit ${options.max}). ` +
|
|
21
|
+
`The largest increments: ${top.map((i) => `${i.reason} at line ${i.line} (+${i.amount})`).join(', ')}.`,
|
|
22
|
+
details: { increments: fn.complexity.increments },
|
|
23
|
+
},
|
|
24
|
+
];
|
|
25
|
+
}),
|
|
26
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const components = (graph, counted) => {
|
|
2
|
+
const parent = graph.members.map((_, index) => index);
|
|
3
|
+
const root = (index) => {
|
|
4
|
+
while (parent[index] !== index) {
|
|
5
|
+
parent[index] = parent[parent[index]];
|
|
6
|
+
index = parent[index];
|
|
7
|
+
}
|
|
8
|
+
return index;
|
|
9
|
+
};
|
|
10
|
+
for (const [a, b] of graph.links)
|
|
11
|
+
parent[root(a)] = root(b);
|
|
12
|
+
const groups = new Map();
|
|
13
|
+
graph.members.forEach((member, index) => {
|
|
14
|
+
const key = root(index);
|
|
15
|
+
groups.set(key, [...(groups.get(key) ?? []), member]);
|
|
16
|
+
});
|
|
17
|
+
return [...groups.values()]
|
|
18
|
+
.filter((group) => group.some((member) => counted.includes(member.kind)))
|
|
19
|
+
.sort((a, b) => a[0].line - b[0].line);
|
|
20
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { exposesText } from '../../model/archetype/references.js';
|
|
2
|
+
import { place } from '../place.js';
|
|
3
|
+
import { noOptions } from '../../rules/rule.js';
|
|
4
|
+
const id = 'dependency-direction';
|
|
5
|
+
export const dependencyDirection = {
|
|
6
|
+
id,
|
|
7
|
+
scope: 'project',
|
|
8
|
+
parseOptions: noOptions,
|
|
9
|
+
check: ({ config, model, verdicts, project, atFile }) => project.files.flatMap((file) => {
|
|
10
|
+
if (!atFile(file.path).on)
|
|
11
|
+
return [];
|
|
12
|
+
const byTarget = Map.groupBy(file.imports, (edge) => edge.via ?? edge.to);
|
|
13
|
+
return [...byTarget].flatMap(([to, edges]) => {
|
|
14
|
+
const verdict = verdicts.verdict(file.path, to);
|
|
15
|
+
if (verdict === undefined || verdict.allowed)
|
|
16
|
+
return [];
|
|
17
|
+
return [refused({ config, model, verdicts }, file.path, to, verdict, edges)];
|
|
18
|
+
});
|
|
19
|
+
}),
|
|
20
|
+
};
|
|
21
|
+
const refused = (context, from, to, refusal, edges) => {
|
|
22
|
+
const { model } = context;
|
|
23
|
+
const source = model.moduleOf(from);
|
|
24
|
+
const target = model.moduleOf(to);
|
|
25
|
+
const names = [...new Set(edges.flatMap((edge) => edge.names))];
|
|
26
|
+
const imports = edges.every((edge) => edge.typeOnly) ? 'imports types from' : 'imports';
|
|
27
|
+
return {
|
|
28
|
+
rule: id,
|
|
29
|
+
key: `${id}:${from}->${to}`,
|
|
30
|
+
file: from,
|
|
31
|
+
line: edges[0].line,
|
|
32
|
+
value: Math.max(1, names.length),
|
|
33
|
+
message: `${from} (${place(model, from, source)}) ${imports} ${to} (${place(model, to, target)}), ${explain(context, from, to, refusal)}`,
|
|
34
|
+
details: {
|
|
35
|
+
from: source.id,
|
|
36
|
+
to: target.id,
|
|
37
|
+
reason: refusal.reason,
|
|
38
|
+
...(refusal.reason === 'private' ? { hiddenBy: refusal.hiddenBy.id } : {}),
|
|
39
|
+
edges,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
const explain = ({ config, model, verdicts }, from, to, refusal) => {
|
|
44
|
+
const source = model.moduleOf(from);
|
|
45
|
+
if (refusal.reason === 'test')
|
|
46
|
+
return 'a test file. Production code never imports tests: move what both need out of the test file into the module it tests.';
|
|
47
|
+
if (refusal.reason === 'private') {
|
|
48
|
+
const { hiddenBy } = refusal;
|
|
49
|
+
return (`which ${hiddenBy.id} keeps private (it exposes ${exposesText(verdicts.exposes(hiddenBy))}). ` +
|
|
50
|
+
`Import what ${hiddenBy.id} exposes, or expose ${to} from ${hiddenBy.archetype ?? hiddenBy.name} if other modules should reach it.`);
|
|
51
|
+
}
|
|
52
|
+
if (refusal.reason === 'above') {
|
|
53
|
+
const folder = source.kind === 'files' ? source.parent : source;
|
|
54
|
+
return (`which is above ${folder.id}. A module reaches up only through what it requires: ` +
|
|
55
|
+
`require it in ${namedArchetype(config, folder.archetype)} and have an ancestor provide it, or move it below.`);
|
|
56
|
+
}
|
|
57
|
+
const owner = source.name ?? source.id;
|
|
58
|
+
const uses = Map.groupBy(verdicts.reach(from).filter((grant) => grant.ref !== undefined), (grant) => grant.owner);
|
|
59
|
+
const reaches = uses.size > 0
|
|
60
|
+
? `: ${[...uses].map(([by, grants]) => `${by} uses ${grants.map((grant) => grant.ref).join(', ')}`).join('; ')}`
|
|
61
|
+
: ', its own files only';
|
|
62
|
+
return (`which is outside ${owner}'s reach${reaches}. ` +
|
|
63
|
+
`Add what holds ${to} to a using if the dependency is intended, or move the code.`);
|
|
64
|
+
};
|
|
65
|
+
const namedArchetype = (config, name) => config.archetypes[name].inline ? namedArchetype(config, name.slice(0, name.lastIndexOf('.'))) : name;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { components } from '../components.js';
|
|
2
|
+
import { wholeNumberOptions } from '../../rules/rule.js';
|
|
3
|
+
import { group } from '../shared.js';
|
|
4
|
+
const defaults = { maxLines: 200 };
|
|
5
|
+
export const fileCohesion = {
|
|
6
|
+
id: 'file-cohesion',
|
|
7
|
+
defaults,
|
|
8
|
+
parseOptions: wholeNumberOptions(defaults),
|
|
9
|
+
check: ({ file, options }) => {
|
|
10
|
+
if (file.lines <= options.maxLines)
|
|
11
|
+
return [];
|
|
12
|
+
const groups = components(file.members, ['function', 'class', 'code']).map(group);
|
|
13
|
+
if (groups.length <= 1)
|
|
14
|
+
return [];
|
|
15
|
+
return [
|
|
16
|
+
{
|
|
17
|
+
rule: 'file-cohesion',
|
|
18
|
+
key: `file-cohesion:${file.path}`,
|
|
19
|
+
file: file.path,
|
|
20
|
+
line: 1,
|
|
21
|
+
value: groups.length,
|
|
22
|
+
limit: 1,
|
|
23
|
+
message: `${file.path} is ${file.lines} lines (tripwire ${options.maxLines}) and its top-level code falls into ${groups.length} groups ` +
|
|
24
|
+
`that share no calls, top-level state or types: ${groups.map(describe).join('; ')}. Each group can move to its own file.`,
|
|
25
|
+
details: { lines: file.lines, tripwire: options.maxLines, groups },
|
|
26
|
+
},
|
|
27
|
+
];
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
const describe = (g) => `[${g.names.join(', ')}] (lines ${g.lines[0]}-${g.lines[1]})`;
|