@yearofthedan/warp 0.2.0 → 0.4.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 (54) hide show
  1. package/README.md +24 -25
  2. package/dist/analysis/imports.d.ts +3 -1
  3. package/dist/analysis/imports.js +5 -1
  4. package/dist/analysis/typescript.js +2 -1
  5. package/dist/app/check.d.ts +3 -1
  6. package/dist/app/check.js +5 -3
  7. package/dist/app/checkModel.js +1 -1
  8. package/dist/app/configLines.d.ts +5 -0
  9. package/dist/app/configLines.js +24 -0
  10. package/dist/app/load.d.ts +2 -2
  11. package/dist/app/load.js +31 -43
  12. package/dist/builtins/advice.d.ts +8 -0
  13. package/dist/builtins/advice.js +42 -0
  14. package/dist/builtins/dependency-direction/dependencyDirection.js +33 -16
  15. package/dist/builtins/index.js +2 -0
  16. package/dist/builtins/module-externals/moduleExternals.js +11 -9
  17. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +16 -5
  18. package/dist/builtins/place.js +5 -3
  19. package/dist/builtins/unresolved-import/unresolvedImport.d.ts +2 -0
  20. package/dist/builtins/unresolved-import/unresolvedImport.js +15 -0
  21. package/dist/builtins/unused-declaration/declarations.js +1 -1
  22. package/dist/builtins/unused-declaration/empty.js +19 -11
  23. package/dist/builtins/unused-declaration/grants.js +22 -15
  24. package/dist/builtins/unused-declaration/surfaces.js +24 -22
  25. package/dist/cli.js +14 -11
  26. package/dist/config/loadConfig.d.ts +7 -1
  27. package/dist/config/loadConfig.js +83 -12
  28. package/dist/index.d.ts +0 -1
  29. package/dist/index.js +0 -1
  30. package/dist/model/archetype/data.d.ts +25 -29
  31. package/dist/model/archetype/data.js +1 -1
  32. package/dist/model/archetype/fixes.d.ts +35 -0
  33. package/dist/model/archetype/fixes.js +265 -0
  34. package/dist/model/archetype/language.d.ts +16 -0
  35. package/dist/model/archetype/language.js +419 -0
  36. package/dist/model/archetype/reach.d.ts +8 -3
  37. package/dist/model/archetype/reach.js +142 -122
  38. package/dist/model/archetype/references.d.ts +11 -5
  39. package/dist/model/archetype/references.js +58 -132
  40. package/dist/model/archetype/requirements.d.ts +3 -3
  41. package/dist/model/archetype/requirements.js +65 -61
  42. package/dist/model/archetype/resolve.d.ts +3 -3
  43. package/dist/model/archetype/resolve.js +64 -77
  44. package/dist/model/archetype/rulesets.d.ts +2 -1
  45. package/dist/model/archetype/rulesets.js +72 -49
  46. package/dist/model/archetype/settings.js +4 -19
  47. package/dist/model/facts.d.ts +6 -0
  48. package/dist/reporters/model.js +9 -9
  49. package/dist/rules/registry.js +1 -1
  50. package/package.json +3 -2
  51. package/dist/model/archetype/builder.d.ts +0 -183
  52. package/dist/model/archetype/builder.js +0 -85
  53. package/dist/model/archetype/draft.d.ts +0 -37
  54. package/dist/model/archetype/draft.js +0 -275
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # warp
2
2
 
3
- warp checks a TypeScript codebase against a declared model of its modules. A `warp.config.ts` names the modules and
4
- what each may use, and warp reports the code that steps outside it:
3
+ warp checks a TypeScript codebase against a declared model of its modules. A `warp.yaml` names the modules and what
4
+ each may use, and warp reports the code that steps outside it:
5
5
 
6
6
  - imports outside a module's reach, including packages it doesn't list.
7
7
  - imports and re-exports that go around a module's surface.
@@ -9,8 +9,8 @@ what each may use, and warp reports the code that steps outside it:
9
9
  - files and functions that are too large or too tangled to follow.
10
10
  - parts of the config that the code no longer uses.
11
11
 
12
- `warp diff` reports only what a change made new or worse, so it can run on a pull request or after every edit of a
13
- coding agent.
12
+ `warp check` judges the whole codebase, for CI. `warp diff` reports only what a change made new or worse, so it can
13
+ run after every edit of a coding agent.
14
14
 
15
15
  ## Quick start
16
16
 
@@ -20,37 +20,36 @@ warp needs Node 26 or later. Add it to the project as a dev dependency:
20
20
  pnpm add -D @yearofthedan/warp
21
21
  ```
22
22
 
23
- Describe the codebase as it is, one module per folder under `src/`, in a `warp.config.ts` next to the project's
23
+ Describe the codebase as it is, one module per folder under `src/`, in a `warp.yaml` next to the project's
24
24
  `tsconfig.json`:
25
25
 
26
- ```ts
27
- // warp.config.ts
28
- import { all, archetype, defineConfig, dir, exposes, files, pkg, ruleset, using } from '@yearofthedan/warp';
29
-
30
- const app = archetype('app')
31
- .contains((c) =>
32
- c
33
- .module('utils', dir('src/utils'), exposes(all()))
34
- .module('db', dir('src/db'), exposes(all()))
35
- .module('api', dir('src/api'), exposes(all()).using((m) => [m.db, m.utils, pkg('*')])),
36
- )
37
- .entry(files('src/index.ts'))
38
- .tests(using([pkg('vitest')]));
39
-
40
- const base = ruleset().on(app.modules.tests, { 'function-cohesion': false });
41
-
42
- export default defineConfig({ root: app, tests: files('src/**/*.test.ts'), rulesets: { default: base } });
26
+ ```yaml
27
+ root:
28
+ modules:
29
+ utils: { dir: src/utils, exposes: all }
30
+ db: { dir: src/db, exposes: all }
31
+ api: { dir: src/api, dependencies: [db, utils, 'npm:*'], exposes: all }
32
+ main: { files: src/index.ts, dependencies: [api] }
33
+ test:
34
+ provides: [npm:vitest]
35
+ modules:
36
+ tests: { files: 'src/**/*.test.ts' }
37
+
38
+ rulesets:
39
+ default:
40
+ extends: [warp:recommended]
41
+ test: { function-cohesion: off }
43
42
  ```
44
43
 
45
44
  Then check it, and after an edit, see what the edit broke:
46
45
 
47
46
  ```sh
48
- pnpm exec warp check # every finding in the working tree
49
- pnpm exec warp diff HEAD # what changed since the last commit made new or worse
47
+ pnpm exec warp check # every finding in the working tree, for CI
48
+ pnpm exec warp diff HEAD # what changed since the last commit made new or worse, for an edit hook
50
49
  ```
51
50
 
52
51
  ```text
53
- new: src/utils/slug.ts:1 [dependency-direction] src/utils/slug.ts (app.utils src/utils) imports src/db/client.ts (app.db src/db), which is outside utils's reach: utils may use nothing. Add what holds src/db/client.ts to a using if the dependency is intended, or move the code.
52
+ new: src/utils/slug.ts:1 [dependency-direction] src/utils/slug.ts (root.utils src/utils) imports src/db/client.ts (root.db src/db), which is outside utils's reach. Add db to root.utils.dependencies (warp.yaml:3), or move the code.
54
53
  ```
55
54
 
56
55
  ## Read next
@@ -1,13 +1,15 @@
1
1
  import { type Checker, type Program } from 'typescript/sync';
2
- import type { ExternalImport, ImportEdge } from '../model/facts.ts';
2
+ import type { ExternalImport, ImportEdge, UnresolvedImport } from '../model/facts.ts';
3
3
  import type { Source } from './source.ts';
4
4
  export interface Resolver {
5
5
  checker: Checker;
6
6
  program: Program;
7
7
  relative: (pathOrFileName: string) => string | undefined;
8
+ exists: (fileName: string) => boolean;
8
9
  }
9
10
  export interface FileEdges {
10
11
  imports: ImportEdge[];
11
12
  externals: ExternalImport[];
13
+ unresolved: UnresolvedImport[];
12
14
  }
13
15
  export declare const fileEdges: (source: Source, resolver: Resolver) => FileEdges;
@@ -2,9 +2,10 @@ import { SyntaxKind } from 'typescript/ast';
2
2
  import { isExportAssignment, isExportDeclaration, isIdentifier, isImportDeclaration, isNamedExports, isNamedImports, isNamespaceImport, isStringLiteralLikeNode, } from 'typescript/ast/is';
3
3
  import { SymbolFlags } from 'typescript/sync';
4
4
  import { isBuiltin } from 'node:module';
5
+ import { dirname, resolve } from 'node:path';
5
6
  export const fileEdges = (source, resolver) => {
6
7
  const exported = locallyExportedNames(source.sourceFile);
7
- const edges = { imports: [], externals: [] };
8
+ const edges = { imports: [], externals: [], unresolved: [] };
8
9
  for (const statement of source.sourceFile.statements) {
9
10
  const declaration = moduleDeclaration(statement, exported);
10
11
  if (!declaration)
@@ -15,9 +16,12 @@ export const fileEdges = (source, resolver) => {
15
16
  edges.imports.push(...statementEdges(statement, declaration, via, source, resolver));
16
17
  else if (isBare(declaration.specifier.text))
17
18
  edges.externals.push(externalImport(statement, declaration, source));
19
+ else if (!resolved?.resolvedFileName && !namesFileOnDisk(declaration.specifier.text, source, resolver))
20
+ edges.unresolved.push({ from: source.file, specifier: declaration.specifier.text, line: source.line(statement) });
18
21
  }
19
22
  return edges;
20
23
  };
24
+ const namesFileOnDisk = (specifier, source, resolver) => resolver.exists(resolve(dirname(source.sourceFile.fileName), specifier));
21
25
  const isBare = (specifier) => !specifier.startsWith('.') && !specifier.startsWith('/');
22
26
  const packageOf = (specifier) => {
23
27
  const segments = specifier.split('/');
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { readFileSync, statSync } from 'node:fs';
2
+ import { existsSync, readFileSync, statSync } from 'node:fs';
3
3
  import { join, relative, sep } from 'node:path';
4
4
  import { API } from 'typescript/sync';
5
5
  import { freshFacts } from '../app/facts.js';
@@ -74,6 +74,7 @@ const analyzeProgram = ({ program, checker }, files, fresh, done) => {
74
74
  program,
75
75
  checker,
76
76
  relative: (path) => byPath.get(path) ?? byPath.get(path.toLowerCase()),
77
+ exists: existsSync,
77
78
  };
78
79
  const analyzed = new Map();
79
80
  for (const [fileName, file] of files) {
@@ -1,4 +1,5 @@
1
1
  import type { ConfigData } from '../model/archetype/data.ts';
2
+ import { type ConfigLines } from './configLines.ts';
2
3
  import { type Model } from '../model/archetype/resolve.ts';
3
4
  import type { Project } from '../model/facts.ts';
4
5
  import type { Finding, Rule } from '../rules/rule.ts';
@@ -17,7 +18,8 @@ export declare const modelProject: ({ analyzer, foldersAt, facts }: Adapters, ro
17
18
  model: Model;
18
19
  project: Project;
19
20
  };
20
- export declare const projectCheck: (adapters: Adapters, config: ConfigData, { rules, unclassifiedDocs }?: {
21
+ export declare const projectCheck: (adapters: Adapters, config: ConfigData, { rules, unclassifiedDocs, lines, }?: {
21
22
  rules?: readonly Rule[];
22
23
  unclassifiedDocs?: string;
24
+ lines?: ConfigLines;
23
25
  }) => ProjectCheck;
package/dist/app/check.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import { checkModel } from './checkModel.js';
2
+ import { placeFindings } from './configLines.js';
2
3
  import { resolveModel } from '../model/archetype/resolve.js';
3
4
  export const modelProject = ({ analyzer, foldersAt, facts }, root, config) => {
4
- const project = analyzer.analyze(root, config.tsconfig, facts);
5
+ const analyzed = analyzer.analyze(root, config.tsconfig, facts);
6
+ const project = { files: analyzed.files.filter((file) => file.path !== config.file) };
5
7
  const files = project.files.map((file) => file.path);
6
8
  return { model: resolveModel(config, foldersAt(root), files), project };
7
9
  };
8
- export const projectCheck = (adapters, config, { rules = [], unclassifiedDocs } = {}) => ({
10
+ export const projectCheck = (adapters, config, { rules = [], unclassifiedDocs, lines = new Map(), } = {}) => ({
9
11
  config,
10
12
  requiredFile: config.tsconfig[0],
11
13
  check: (root) => {
12
14
  const { model, project } = modelProject(adapters, root, config);
13
- return checkModel(config, model, project, rules, unclassifiedDocs);
15
+ return placeFindings(lines, config.file, checkModel(config, model, project, rules, unclassifiedDocs));
14
16
  },
15
17
  });
@@ -14,7 +14,7 @@ const placed = (model, finding) => {
14
14
  const module = model.moduleOf(finding.file);
15
15
  if (!module)
16
16
  return finding;
17
- return { ...finding, module: model.isTest(finding.file) ? `${module.id}:tests` : module.id };
17
+ return { ...finding, module: module.id };
18
18
  };
19
19
  const run = (rule, shared, settled) => {
20
20
  if (rule.scope === 'project')
@@ -0,0 +1,5 @@
1
+ import type { Finding } from '../rules/rule.ts';
2
+ export type ConfigLines = ReadonlyMap<string, number>;
3
+ export declare const lineAt: (lines: ConfigLines, text: string) => number | undefined;
4
+ export declare const placeProblems: (lines: ConfigLines, file: string, message: string) => string;
5
+ export declare const placeFindings: (lines: ConfigLines, file: string, findings: Finding[]) => Finding[];
@@ -0,0 +1,24 @@
1
+ const ends = new Set([':', ' ', '-', '.', undefined]);
2
+ export const lineAt = (lines, text) => {
3
+ const paths = [...lines.keys()].filter((path) => text.startsWith(path) && ends.has(text[path.length]));
4
+ const longest = paths.sort((a, b) => b.length - a.length)[0];
5
+ return longest === undefined ? undefined : lines.get(longest);
6
+ };
7
+ export const placeProblems = (lines, file, message) => message
8
+ .split('\n')
9
+ .map((problem) => {
10
+ const line = problem.startsWith(`${file}`) ? undefined : lineAt(lines, problem);
11
+ return line === undefined ? problem : `${file}:${line}: ${problem}`;
12
+ })
13
+ .join('\n');
14
+ const site = /\b[\w-]+(?:\.[\w-]+)*\.(?:dependencies|exposes|requires|provides)\b/g;
15
+ const pointed = (lines, file, message) => message.replace(site, (path) => {
16
+ const line = lineAt(lines, path);
17
+ return line === undefined ? path : `${path} (${file}:${line})`;
18
+ });
19
+ export const placeFindings = (lines, file, findings) => findings.map((finding) => {
20
+ if (finding.file !== file)
21
+ return { ...finding, message: pointed(lines, file, finding.message) };
22
+ const line = lineAt(lines, finding.message);
23
+ return line === undefined ? finding : { ...finding, line };
24
+ });
@@ -3,11 +3,11 @@ import type { ConfigData } from '../model/archetype/data.ts';
3
3
  export interface LoadedConfigData {
4
4
  config: ConfigData;
5
5
  rules: Rule[];
6
- warnings: string[];
7
6
  }
8
7
  export interface LoadOptions {
9
8
  builtins?: readonly Rule[];
10
9
  ruleset?: string;
11
10
  file?: string;
11
+ plugins?: Record<string, unknown>;
12
12
  }
13
- export declare const loadConfigData: (raw: unknown, { builtins, ruleset, file }?: LoadOptions) => LoadedConfigData;
13
+ export declare const loadConfigData: (raw: unknown, { builtins, ruleset, file, plugins }?: LoadOptions) => LoadedConfigData;
package/dist/app/load.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { pluginRules, registry } from '../rules/registry.js';
2
2
  import { ConfigError } from '../model/configError.js';
3
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';
4
+ import { parseStructure } from '../model/archetype/language.js';
5
+ import { checkReferences, toRules } from '../model/archetype/references.js';
6
+ import { checkInputs, markTests } from '../model/archetype/requirements.js';
8
7
  import { unclassified } from './unclassified.js';
9
8
  import { withRuleset } from '../model/archetype/rulesets.js';
10
9
  import { defined, isName, isRecord } from '../model/archetype/shared.js';
11
- export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.config.ts' } = {}) => {
10
+ const keys = ['root', 'archetypes', 'rulesets', 'plugins', 'tsconfig'];
11
+ export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.yaml', plugins = {} } = {}) => {
12
12
  const errors = [];
13
13
  const fail = (message) => {
14
14
  if (!errors.includes(message))
@@ -19,58 +19,46 @@ export const loadConfigData = (raw, { builtins, ruleset, file = 'warp.config.ts'
19
19
  throw new ConfigError(errors.join('\n'));
20
20
  };
21
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));
22
+ throw new ConfigError(`${file}: expected a mapping, root: { modules: ... }`);
23
+ const unknownKeys = Object.keys(raw).filter((key) => !keys.includes(key));
24
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));
25
+ fail(`${file}: unknown key ${unknownKeys.join(', ')}; a config takes ${keys.join(', ')}`);
26
+ checkPlugins(raw.plugins, plugins, fail);
27
+ const rules = [...registry([...(builtins ?? []), ...pluginRules(plugins)]).values()];
28
+ const structure = parseStructure(raw.root, raw.archetypes, fail);
29
+ failed();
30
+ checkReferences(structure.archetypes, structure.pending, fail);
31
+ markTests(structure.archetypes, fail);
32
+ checkInputs(structure.archetypes, structure.pending, fail);
31
33
  const check = {
32
34
  fail,
33
35
  ruleIds: builtins && new Set([...rules.map((rule) => rule.id), unclassified]),
34
36
  options: Object.fromEntries(rules.map((rule) => [rule.id, rule.parseOptions ?? noOptions])),
35
- exposesOf: (name) => drafts.find((d) => d.data.name === name)?.exposes,
36
37
  };
37
- for (const d of drafts)
38
- resolveDraft(check, d);
39
- const structure = {
38
+ const data = {
40
39
  file,
41
- root: root.definition.name,
42
- archetypes: Object.fromEntries(drafts.map(({ data }) => [data.name, archetypeData(data)])),
40
+ root: structure.root,
41
+ archetypes: Object.fromEntries(Object.entries(structure.archetypes).map(([name, archetype]) => [name, archetypeData(archetype)])),
43
42
  tsconfig: tsconfigs(raw.tsconfig, fail),
44
- ...testPatterns(raw.tests, fail),
45
43
  };
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);
44
+ const config = withRuleset(data, raw.rulesets, ruleset, (value, at) => toRules(check, value, at), fail);
50
45
  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 {};
46
+ return { config, rules };
61
47
  };
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 {};
48
+ const archetypeData = (archetype) => defined({ ...archetype, modules: archetype.modules.map(defined) });
49
+ const checkPlugins = (declared, loaded, fail) => {
50
+ if (declared === undefined)
51
+ return;
52
+ if (!isRecord(declared) || !Object.values(declared).every(isName)) {
53
+ fail('plugins: expected plugin paths by namespace, { wt: ./rules/wt.ts }');
54
+ return;
55
+ }
56
+ for (const namespace of Object.keys(declared).filter((namespace) => !Object.hasOwn(loaded, namespace)))
57
+ fail(`plugins.${namespace}: not loaded; warp loads each plugin from its path before reading the config`);
70
58
  };
71
59
  const tsconfigs = (value, fail) => {
72
60
  const paths = [value ?? 'tsconfig.json'].flat();
73
61
  if (paths.length === 0 || !paths.every(isName))
74
- fail('config.tsconfig: expected a path or a list of paths');
62
+ fail('tsconfig: expected a path or a list of paths');
75
63
  return paths;
76
64
  };
@@ -0,0 +1,8 @@
1
+ import type { RefData } from '../model/archetype/data.ts';
2
+ import type { Fix } from '../model/archetype/fixes.ts';
3
+ import type { Verdicts } from '../model/archetype/reach.ts';
4
+ import type { Model } from '../model/archetype/resolve.ts';
5
+ export declare const refText: (ref: RefData) => string;
6
+ export declare const sentence: (parts: readonly string[]) => string;
7
+ export declare const reachSize: (verdicts: Verdicts, file: string) => number;
8
+ export declare const fixSteps: (model: Model, fixes: readonly Fix[]) => string[];
@@ -0,0 +1,42 @@
1
+ import { show } from '../model/archetype/references.js';
2
+ export const refText = (ref) => show(ref);
3
+ export const sentence = (parts) => parts.length < 2 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`;
4
+ export const reachSize = (verdicts, file) => new Set((verdicts.reach(file) ?? []).flatMap((grant) => (grant.ref === undefined ? [] : [grant.ref]))).size;
5
+ const instances = (model, archetype) => {
6
+ const count = model.modules.filter((module) => module.archetype === archetype).length;
7
+ return count > 1 ? ` (all ${count} ${archetype} modules)` : '';
8
+ };
9
+ const step = (model, fix, refs) => {
10
+ switch (fix.kind) {
11
+ case 'using':
12
+ return `add ${refText(fix.ref)} to ${fix.site}`;
13
+ case 'require':
14
+ return `add ${fix.name} to ${fix.archetype}.requires, bound in the dependencies of ${sentence(fix.sites)}`;
15
+ case 'expose':
16
+ return `add ${sentence(refs.map(refText))} to ${fix.archetype}.exposes${instances(model, fix.archetype)}`;
17
+ case 'test-expose':
18
+ return `add ${sentence(refs.map(refText))} to ${fix.archetype}.test.exposes${instances(model, fix.archetype)}`;
19
+ case 'expose-file':
20
+ return `add '${fix.pattern}' to ${fix.archetype}.exposes files`;
21
+ }
22
+ };
23
+ export const fixSteps = (model, fixes) => {
24
+ const steps = [];
25
+ for (const [at, fix] of fixes.entries()) {
26
+ if (fix.kind !== 'expose' && fix.kind !== 'test-expose') {
27
+ steps.push(step(model, fix, []));
28
+ continue;
29
+ }
30
+ const previous = fixes[at - 1];
31
+ if (previous?.kind === fix.kind && previous.archetype === fix.archetype)
32
+ continue;
33
+ const refs = [];
34
+ for (const next of fixes.slice(at)) {
35
+ if (next.kind !== fix.kind || next.archetype !== fix.archetype)
36
+ break;
37
+ refs.push(next.ref);
38
+ }
39
+ steps.push(step(model, fix, refs));
40
+ }
41
+ return steps;
42
+ };
@@ -1,5 +1,8 @@
1
1
  import { exposesText } from '../../model/archetype/references.js';
2
+ import { fixSteps, reachSize, sentence } from '../advice.js';
2
3
  import { place } from '../place.js';
4
+ import { title } from '../shared.js';
5
+ import { fixesFor } from '../../model/archetype/fixes.js';
3
6
  import { noOptions } from '../../rules/rule.js';
4
7
  const id = 'dependency-direction';
5
8
  export const dependencyDirection = {
@@ -41,28 +44,42 @@ const refused = (context, from, to, refusal, edges) => {
41
44
  };
42
45
  };
43
46
  const explain = ({ config, model, verdicts }, from, to, refusal) => {
44
- const source = model.moduleOf(from);
45
47
  if (isLoose(model, to))
46
- return `which is in no module yet. Add a module that holds ${to}, then add it to a using if the dependency is intended.`;
48
+ return `which is in no module yet. Add a module that holds ${to}, then add it to the importer's dependencies if the dependency is intended.`;
47
49
  if (refusal.reason === 'test')
48
50
  return 'a test file. Production code never imports tests: move what both need out of the test file into the module it tests.';
51
+ const instead = refusal.reason === 'private' ? throughSurface({ config, model, verdicts }, from, to, refusal.hiddenBy) : '';
52
+ return `${why(config, model, verdicts, from, to, refusal)}. ${instead || advise(config, model, verdicts, from, to)}`;
53
+ };
54
+ const why = (config, model, verdicts, from, to, refusal) => {
55
+ const source = model.moduleOf(from);
49
56
  if (refusal.reason === 'private') {
50
57
  const { hiddenBy } = refusal;
51
- return (`which ${hiddenBy.id} keeps private (it exposes ${exposesText(verdicts.exposes(hiddenBy))}). ` +
52
- `Import what ${hiddenBy.id} exposes, or expose ${to} from ${hiddenBy.archetype ?? hiddenBy.name} if other modules should reach it.`);
58
+ return `which ${hiddenBy.id} keeps private (it exposes ${exposesText(verdicts.exposes(hiddenBy))})`;
53
59
  }
54
- if (refusal.reason === 'above') {
55
- const folder = source.kind === 'files' ? source.parent : source;
56
- return (`which is above ${folder.id}. A module reaches up only through what it requires: ` +
57
- `require it in ${namedArchetype(config, folder.archetype)} and have an ancestor provide it, or move it below.`);
60
+ if (refusal.reason === 'above')
61
+ return `which is above ${(source.kind === 'dir' ? source : source.parent).id}`;
62
+ return `which is outside ${source.name ?? source.id}'s reach`;
63
+ };
64
+ const throughSurface = ({ config, model, verdicts }, from, to, hiddenBy) => {
65
+ if (model.isTest(to))
66
+ return '';
67
+ for (const file of verdicts.surface(hiddenBy)) {
68
+ const fixes = fixesFor(config, model, from, file);
69
+ if (!fixes)
70
+ continue;
71
+ const once = fixes.length > 0 ? `, once you ${sentence(fixSteps(model, fixes))}` : '';
72
+ return `Import what ${hiddenBy.id} exposes instead${once}.`;
58
73
  }
59
- const owner = source.name ?? source.id;
60
- const uses = Map.groupBy(verdicts.reach(from).filter((grant) => grant.ref !== undefined), (grant) => grant.owner);
61
- const reaches = uses.size > 0
62
- ? `: ${[...uses].map(([by, grants]) => `${by} uses ${grants.map((grant) => grant.ref).join(', ')}`).join('; ')}`
63
- : `: ${owner} may use nothing`;
64
- return (`which is outside ${owner}'s reach${reaches}. ` +
65
- `Add what holds ${to} to a using if the dependency is intended, or move the code.`);
74
+ return '';
75
+ };
76
+ const advise = (config, model, verdicts, from, to) => {
77
+ const fixes = fixesFor(config, model, from, to);
78
+ if (!fixes)
79
+ return 'No declared path allows this: either the import or the structure is wrong.';
80
+ const steps = fixSteps(model, fixes);
81
+ const size = reachSize(verdicts, from);
82
+ const more = size > 0 && fixes.some((fix) => fix.kind === 'using') ? ` (+${size} more in reach)` : '';
83
+ return `${title(sentence(steps))}, or move the code.${more}`;
66
84
  };
67
85
  const isLoose = (model, file) => model.moduleOf(file).looseFiles.includes(file);
68
- const namedArchetype = (config, name) => config.archetypes[name].inline ? namedArchetype(config, name.slice(0, name.lastIndexOf('.'))) : name;
@@ -8,8 +8,10 @@ import { moduleExternals } from './module-externals/moduleExternals.js';
8
8
  import { noCrossModuleReexport } from './no-cross-module-reexport/noCrossModuleReexport.js';
9
9
  import { noCycle } from './no-cycle/noCycle.js';
10
10
  import { noDoubleExport } from './no-double-export/noDoubleExport.js';
11
+ import { unresolvedImport } from './unresolved-import/unresolvedImport.js';
11
12
  import { unusedDeclaration } from './unused-declaration/unusedDeclaration.js';
12
13
  export const builtinRules = [
14
+ unresolvedImport,
13
15
  dependencyDirection,
14
16
  moduleExternals,
15
17
  noDoubleExport,
@@ -1,12 +1,14 @@
1
1
  import { listsPackage } from '../packages.js';
2
2
  import { place } from '../place.js';
3
+ import { sitesOf } from '../../model/archetype/fixes.js';
4
+ import { packageText } from '../../model/archetype/references.js';
3
5
  import { noOptions } from '../../rules/rule.js';
4
6
  const id = 'module-externals';
5
7
  export const moduleExternals = {
6
8
  id,
7
9
  scope: 'project',
8
10
  parseOptions: noOptions,
9
- check: ({ model, verdicts, project, atFile }) => project.files.flatMap((file) => {
11
+ check: ({ config, model, verdicts, project, atFile }) => project.files.flatMap((file) => {
10
12
  const reach = verdicts.reach(file.path);
11
13
  if (!reach || !atFile(file.path).on)
12
14
  return [];
@@ -14,28 +16,28 @@ export const moduleExternals = {
14
16
  const byPackage = Map.groupBy(file.externals, (external) => external.package);
15
17
  return [...byPackage].flatMap(([name, edges]) => {
16
18
  const outside = edges.filter((edge) => !packages.some((grant) => listsPackage(grant.package, edge)));
17
- return outside.length === 0 ? [] : [refused(model, file.path, name, outside, packages)];
19
+ return outside.length === 0 ? [] : [refused(config, model, file.path, name, outside, packages)];
18
20
  });
19
21
  }),
20
22
  };
21
- const refused = (model, from, name, edges, packages) => {
23
+ const refused = (config, model, from, name, edges, packages) => {
22
24
  const module = model.moduleOf(from);
23
25
  const owner = module.name ?? module.id;
24
26
  const names = [...new Set(edges.flatMap((edge) => edge.names))];
25
27
  const specifiers = [...new Set(edges.map((edge) => edge.specifier))];
26
28
  const imports = edges.every((edge) => edge.typeOnly) ? 'imports types from' : 'imports';
27
- const uses = Map.groupBy(packages, (grant) => grant.owner);
28
- const lists = uses.size > 0
29
- ? `: ${[...uses].map(([by, grants]) => `${by} uses ${grants.map((grant) => grant.ref).join(', ')}`).join('; ')}`
30
- : ': no using in its reach lists a package';
29
+ const site = sitesOf(config, model, from)[0];
30
+ const where = site?.label ?? 'its dependencies';
31
+ const listed = new Set(packages.map((grant) => grant.ref)).size;
32
+ const more = listed > 0 ? ` (+${listed} more in reach)` : '';
31
33
  return {
32
34
  rule: id,
33
35
  key: `${id}:${from}->${name}`,
34
36
  file: from,
35
37
  line: edges[0].line,
36
38
  value: Math.max(1, names.length),
37
- message: `${from} (${place(model, from, module)}) ${imports} ${specifiers.join(', ')}, a package outside ${owner}'s reach${lists}. ` +
38
- `Add pkg('${name}') to a using if the dependency is intended, or move the code.`,
39
+ message: `${from} (${place(model, from, module)}) ${imports} ${specifiers.join(', ')}, a package outside ${owner}'s reach. ` +
40
+ `Add ${packageText(name)} to ${where}, or move the code.${more}`,
39
41
  details: { from: module.id, package: name, edges },
40
42
  };
41
43
  };
@@ -5,7 +5,7 @@ export const noCrossModuleReexport = {
5
5
  id,
6
6
  scope: 'project',
7
7
  parseOptions: noOptions,
8
- check: ({ model, project, atFile }) => project.files.flatMap((file) => {
8
+ check: ({ model, verdicts, project, atFile }) => project.files.flatMap((file) => {
9
9
  const module = model.moduleOf(file.path);
10
10
  if (!module || !atFile(file.path).on)
11
11
  return [];
@@ -14,7 +14,8 @@ export const noCrossModuleReexport = {
14
14
  const target = model.moduleOf(to);
15
15
  if (!target || owns(module, target))
16
16
  return [];
17
- return [passedThrough(model, module, target, to, edges)];
17
+ const blocked = importersOf(project, file.path, to).filter((importer) => !owns(target, model.moduleOf(importer)) && !verdicts.verdict(importer, to)?.allowed);
18
+ return [passedThrough(model, module, target, to, edges, blocked)];
18
19
  });
19
20
  }),
20
21
  };
@@ -24,7 +25,10 @@ const owns = (module, target) => {
24
25
  return true;
25
26
  return false;
26
27
  };
27
- const passedThrough = (model, module, target, to, edges) => {
28
+ const importersOf = (project, file, to) => project.files
29
+ .filter((other) => other.imports.some((edge) => edge.via === file && edge.to === to && !edge.reExport))
30
+ .map((other) => other.path);
31
+ const passedThrough = (model, module, target, to, edges, blocked) => {
28
32
  const from = edges[0].from;
29
33
  const names = [...new Set(edges.flatMap((edge) => edge.names))];
30
34
  const what = names.length > 0 ? names.join(', ') : 'everything';
@@ -35,8 +39,8 @@ const passedThrough = (model, module, target, to, edges) => {
35
39
  line: edges[0].line,
36
40
  value: Math.max(1, names.length),
37
41
  message: `${from} (${place(model, from, module)}) re-exports ${what} from ${to} (${place(model, to, target)}), so its ` +
38
- `importers reach ${target.id} through ${module.id}. Have importers that need it use ${target.id} directly, give ` +
39
- `${module.id} its own type that hides it, or move it into ${module.id} if ${module.id} owns it.`,
42
+ `importers reach ${target.id} through ${module.id}. ${direct(target, blocked)}give ${module.id} its own type that ` +
43
+ `hides it, or move it into ${module.id} if ${module.id} owns it.`,
40
44
  details: {
41
45
  from: module.id,
42
46
  to: target.id,
@@ -45,3 +49,10 @@ const passedThrough = (model, module, target, to, edges) => {
45
49
  },
46
50
  };
47
51
  };
52
+ const direct = (target, blocked) => {
53
+ if (blocked.length === 0)
54
+ return `Have importers that need it use ${target.id} directly, `;
55
+ const count = blocked.length - 1;
56
+ const others = count > 0 ? ` and ${count} other importer${count > 1 ? 's' : ''}` : '';
57
+ return `${blocked[0]}${others} may not use ${target.id} directly, so `;
58
+ };
@@ -1,6 +1,8 @@
1
1
  export const place = (model, file, module = model.moduleOf(file)) => {
2
- if (module.kind === 'files')
3
- return `${module.name} of ${module.parent.archetype} ${module.parent.id}`;
4
- const role = module.looseFiles.includes(file) ? 'loose in ' : model.isTest(file) ? 'a test of ' : '';
2
+ if (module.kind !== 'dir') {
3
+ const role = module.kind === 'test' ? 'test module ' : '';
4
+ return `${role}${module.name} of ${module.parent.archetype} ${module.parent.id}`;
5
+ }
6
+ const role = module.looseFiles.includes(file) ? 'loose in ' : '';
5
7
  return `${role}${module.archetype} ${module.id}`;
6
8
  };
@@ -0,0 +1,2 @@
1
+ import { type FileRule } from '../../rules/rule.ts';
2
+ export declare const unresolvedImport: FileRule;
@@ -0,0 +1,15 @@
1
+ import { noOptions } from '../../rules/rule.js';
2
+ const id = 'unresolved-import';
3
+ export const unresolvedImport = {
4
+ id,
5
+ parseOptions: noOptions,
6
+ check: ({ file }) => file.unresolved.map(({ from, specifier, line }) => ({
7
+ rule: id,
8
+ key: `${id}:${from}->${specifier}`,
9
+ file: from,
10
+ line,
11
+ value: 1,
12
+ message: `${specifier} from ${from} resolves to no file. Fix the path, or add the file it names.`,
13
+ details: { from, specifier },
14
+ })),
15
+ };
@@ -8,7 +8,7 @@ export const holding = ({ model, project }) => {
8
8
  };
9
9
  export const instancesOf = ({ model, held }, archetype) => model.modules.filter((module) => module.archetype === archetype && held.has(module));
10
10
  export const childrenNamed = ({ held }, instances, name) => instances.flatMap((instance) => instance.children.filter((child) => child.name === name && held.has(child)));
11
- export const named = (module) => (module.id === '.' ? 'the root' : module.id);
11
+ export const named = (module) => (module.parent === undefined ? 'the root' : module.id);
12
12
  export const within = (module, holder) => {
13
13
  for (let at = module; at; at = at.parent)
14
14
  if (at === holder)