@yearofthedan/warp 0.3.0 → 0.4.1

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 (45) hide show
  1. package/README.md +20 -22
  2. package/dist/app/check.d.ts +3 -1
  3. package/dist/app/check.js +3 -2
  4. package/dist/app/configLines.d.ts +5 -0
  5. package/dist/app/configLines.js +24 -0
  6. package/dist/app/load.d.ts +2 -2
  7. package/dist/app/load.js +32 -44
  8. package/dist/app/unclassified.js +1 -1
  9. package/dist/builtins/advice.js +9 -9
  10. package/dist/builtins/dependency-direction/dependencyDirection.js +7 -2
  11. package/dist/builtins/module-externals/moduleExternals.js +3 -2
  12. package/dist/builtins/unused-declaration/empty.js +11 -10
  13. package/dist/builtins/unused-declaration/grants.js +39 -11
  14. package/dist/builtins/unused-declaration/surfaces.js +16 -6
  15. package/dist/cli.js +37 -17
  16. package/dist/config/loadConfig.d.ts +8 -2
  17. package/dist/config/loadConfig.js +107 -14
  18. package/dist/git/cache.js +5 -1
  19. package/dist/index.d.ts +0 -1
  20. package/dist/index.js +0 -1
  21. package/dist/model/archetype/data.d.ts +14 -23
  22. package/dist/model/archetype/data.js +1 -1
  23. package/dist/model/archetype/fixes.d.ts +5 -7
  24. package/dist/model/archetype/fixes.js +132 -90
  25. package/dist/model/archetype/language.d.ts +16 -0
  26. package/dist/model/archetype/language.js +432 -0
  27. package/dist/model/archetype/reach.d.ts +8 -3
  28. package/dist/model/archetype/reach.js +122 -56
  29. package/dist/model/archetype/references.d.ts +11 -5
  30. package/dist/model/archetype/references.js +59 -118
  31. package/dist/model/archetype/requirements.d.ts +3 -3
  32. package/dist/model/archetype/requirements.js +75 -58
  33. package/dist/model/archetype/resolve.d.ts +1 -0
  34. package/dist/model/archetype/resolve.js +26 -56
  35. package/dist/model/archetype/rulesets.d.ts +2 -1
  36. package/dist/model/archetype/rulesets.js +74 -43
  37. package/dist/model/archetype/settings.d.ts +1 -0
  38. package/dist/model/archetype/settings.js +5 -0
  39. package/dist/reporters/model.js +4 -3
  40. package/dist/rules/registry.js +2 -2
  41. package/package.json +4 -2
  42. package/dist/model/archetype/builder.d.ts +0 -183
  43. package/dist/model/archetype/builder.js +0 -78
  44. package/dist/model/archetype/draft.d.ts +0 -30
  45. package/dist/model/archetype/draft.js +0 -264
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.
@@ -20,27 +20,25 @@ 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
- .testModule('tests', files('src/**/*.test.ts')),
37
- )
38
- .entry(files('src/index.ts'))
39
- .testUsing([pkg('vitest')]);
40
-
41
- const base = ruleset().on(app.modules.tests, { 'function-cohesion': false });
42
-
43
- export default defineConfig({ root: app, 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 }
44
42
  ```
45
43
 
46
44
  Then check it, and after an edit, see what the edit broke:
@@ -51,7 +49,7 @@ pnpm exec warp diff HEAD # what changed since the last commit made new or worse
51
49
  ```
52
50
 
53
51
  ```text
54
- 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. Declare db above utils in app and add m.db to the using of app.utils, 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.
55
53
  ```
56
54
 
57
55
  ## Read next
@@ -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,4 +1,5 @@
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
5
  const analyzed = analyzer.analyze(root, config.tsconfig, facts);
@@ -6,11 +7,11 @@ export const modelProject = ({ analyzer, foldersAt, facts }, root, config) => {
6
7
  const files = project.files.map((file) => file.path);
7
8
  return { model: resolveModel(config, foldersAt(root), files), project };
8
9
  };
9
- export const projectCheck = (adapters, config, { rules = [], unclassifiedDocs } = {}) => ({
10
+ export const projectCheck = (adapters, config, { rules = [], unclassifiedDocs, lines = new Map(), } = {}) => ({
10
11
  config,
11
12
  requiredFile: config.tsconfig[0],
12
13
  check: (root) => {
13
14
  const { model, project } = modelProject(adapters, root, config);
14
- return checkModel(config, model, project, rules, unclassifiedDocs);
15
+ return placeFindings(lines, config.file, checkModel(config, model, project, rules, unclassifiedDocs));
15
16
  },
16
17
  });
@@ -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', '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));
22
+ throw new ConfigError(`${file}: expected a mapping, root: { modules: ... }`);
23
+ const unknownKeys = Object.keys(raw).filter((key) => !keys.includes(key));
24
+ for (const key of unknownKeys)
25
+ fail(`${key}: unknown key; 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
43
  };
45
- const config = withRuleset(structure, raw.rulesets, ruleset, (value, at) => toRules(check, value, at), fail);
46
- checkUnused(drafts, fail);
47
- failed();
48
- const warnings = checkRequirements(config.archetypes, config.root, fail);
44
+ const config = withRuleset(data, raw.rulesets, ruleset, (value, at) => toRules(check, value, at), fail);
49
45
  failed();
50
- return { config, rules, warnings };
46
+ return { config, rules };
51
47
  };
52
- const archetypeData = ({ name, inline, description, identify, requires, modules, exposes, provides, testUsing, }) => defined({
53
- name,
54
- inline,
55
- description,
56
- identify,
57
- requires,
58
- modules: modules.map(defined),
59
- exposes,
60
- provides,
61
- testUsing,
62
- });
63
- const plugins = (value, fail) => {
64
- if (value === undefined)
65
- return {};
66
- if (isRecord(value))
67
- return value;
68
- fail('config.plugins: expected plugins by namespace');
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
  };
@@ -6,7 +6,7 @@ export const unclassifiedFindings = (model, settled, docs) => model.modules.flat
6
6
  file,
7
7
  line: 1,
8
8
  value: 1,
9
- message: `${file} is in no module of ${module.id} (${module.archetype}), so nothing says what it may import. ` +
9
+ message: `${file} is in no module of ${module.parent ? `${module.id} (${module.archetype})` : 'the root'}, so nothing says what it may import. ` +
10
10
  `Add a files module to ${module.archetype} that matches it, or move it into a module's folder.`,
11
11
  ...(docs ? { docs } : {}),
12
12
  }))
@@ -1,5 +1,5 @@
1
1
  import { show } from '../model/archetype/references.js';
2
- export const refText = (ref) => (ref.kind === 'module' ? `m.${show(ref)}` : show(ref));
2
+ export const refText = (ref) => show(ref);
3
3
  export const sentence = (parts) => parts.length < 2 ? (parts[0] ?? '') : `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}`;
4
4
  export const reachSize = (verdicts, file) => new Set((verdicts.reach(file) ?? []).flatMap((grant) => (grant.ref === undefined ? [] : [grant.ref]))).size;
5
5
  const instances = (model, archetype) => {
@@ -10,29 +10,29 @@ const step = (model, fix, refs) => {
10
10
  switch (fix.kind) {
11
11
  case 'using':
12
12
  return `add ${refText(fix.ref)} to ${fix.site}`;
13
- case 'declare':
14
- return `declare ${fix.module} above ${fix.above} in ${fix.archetype}`;
15
13
  case 'require':
16
- return `require ${fix.name} in ${fix.archetype}, have ${fix.provider} provide m.${fix.module} as ${fix.name}`;
14
+ return `add ${fix.name} to ${fix.archetype}.requires, bound in the dependencies of ${sentence(fix.sites)}`;
17
15
  case 'expose':
18
- return `expose ${sentence(refs.map(refText))} from ${fix.archetype}${instances(model, fix.archetype)}`;
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
19
  case 'expose-file':
20
- return `add '${fix.pattern}' to what ${fix.archetype} exposes`;
20
+ return `add '${fix.pattern}' to the files of ${fix.archetype}.exposes`;
21
21
  }
22
22
  };
23
23
  export const fixSteps = (model, fixes) => {
24
24
  const steps = [];
25
25
  for (const [at, fix] of fixes.entries()) {
26
- if (fix.kind !== 'expose') {
26
+ if (fix.kind !== 'expose' && fix.kind !== 'test-expose') {
27
27
  steps.push(step(model, fix, []));
28
28
  continue;
29
29
  }
30
30
  const previous = fixes[at - 1];
31
- if (previous?.kind === 'expose' && previous.archetype === fix.archetype)
31
+ if (previous?.kind === fix.kind && previous.archetype === fix.archetype)
32
32
  continue;
33
33
  const refs = [];
34
34
  for (const next of fixes.slice(at)) {
35
- if (next.kind !== 'expose' || next.archetype !== fix.archetype)
35
+ if (next.kind !== fix.kind || next.archetype !== fix.archetype)
36
36
  break;
37
37
  refs.push(next.ref);
38
38
  }
@@ -45,16 +45,21 @@ const refused = (context, from, to, refusal, edges) => {
45
45
  };
46
46
  const explain = ({ config, model, verdicts }, from, to, refusal) => {
47
47
  if (isLoose(model, to))
48
- 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.`;
49
49
  if (refusal.reason === 'test')
50
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
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)}`;
52
+ const opened = (instead && fixesFor(config, model, from, to)) || [];
53
+ const exposing = opened.filter((fix) => fix.kind === 'expose' || fix.kind === 'expose-file');
54
+ const open = exposing.length > 0 ? ` Or, if ${to} should be public, ${sentence(fixSteps(model, exposing))}.` : '';
55
+ return `${why(config, model, verdicts, from, to, refusal)}. ${instead ? `${instead}${open}` : advise(config, model, verdicts, from, to)}`;
53
56
  };
54
57
  const why = (config, model, verdicts, from, to, refusal) => {
55
58
  const source = model.moduleOf(from);
56
59
  if (refusal.reason === 'private') {
57
60
  const { hiddenBy } = refusal;
61
+ if (model.isTest(to))
62
+ return `which ${hiddenBy.id} keeps for its own tests`;
58
63
  return `which ${hiddenBy.id} keeps private (it exposes ${exposesText(verdicts.exposes(hiddenBy))})`;
59
64
  }
60
65
  if (refusal.reason === 'above')
@@ -1,6 +1,7 @@
1
1
  import { listsPackage } from '../packages.js';
2
2
  import { place } from '../place.js';
3
3
  import { sitesOf } from '../../model/archetype/fixes.js';
4
+ import { packageText } from '../../model/archetype/references.js';
4
5
  import { noOptions } from '../../rules/rule.js';
5
6
  const id = 'module-externals';
6
7
  export const moduleExternals = {
@@ -26,7 +27,7 @@ const refused = (config, model, from, name, edges, packages) => {
26
27
  const specifiers = [...new Set(edges.map((edge) => edge.specifier))];
27
28
  const imports = edges.every((edge) => edge.typeOnly) ? 'imports types from' : 'imports';
28
29
  const site = sitesOf(config, model, from)[0];
29
- const where = site?.label ?? 'a using';
30
+ const where = site?.label ?? 'its dependencies';
30
31
  const listed = new Set(packages.map((grant) => grant.ref)).size;
31
32
  const more = listed > 0 ? ` (+${listed} more in reach)` : '';
32
33
  return {
@@ -36,7 +37,7 @@ const refused = (config, model, from, name, edges, packages) => {
36
37
  line: edges[0].line,
37
38
  value: Math.max(1, names.length),
38
39
  message: `${from} (${place(model, from, module)}) ${imports} ${specifiers.join(', ')}, a package outside ${owner}'s reach. ` +
39
- `Add pkg('${name}') to ${where}, or move the code.${more}`,
40
+ `Add ${packageText(name)} to ${where}, or move the code.${more}`,
40
41
  details: { from: module.id, package: name, edges },
41
42
  };
42
43
  };
@@ -1,3 +1,4 @@
1
+ import { isTestData } from '../../model/archetype/data.js';
1
2
  import { childrenNamed, instancesOf, named, unused } from './declarations.js';
2
3
  export const emptyModules = (context) => Object.values(context.config.archetypes).flatMap((archetype) => {
3
4
  const instances = instancesOf(context, archetype.name);
@@ -5,7 +6,7 @@ export const emptyModules = (context) => Object.values(context.config.archetypes
5
6
  const declared = archetype.modules.map((module) => ({
6
7
  module,
7
8
  name: module.name,
8
- layer: module.kind === 'test' ? 'test' : 'production',
9
+ layer: isTestData(module) ? 'test' : 'production',
9
10
  }));
10
11
  return declared
11
12
  .filter(({ name }) => on && childrenNamed(context, instances, name).length === 0)
@@ -14,16 +15,16 @@ export const emptyModules = (context) => Object.values(context.config.archetypes
14
15
  const empty = (context, declaredIn, module, layer, instances) => {
15
16
  const selector = selectorText(module);
16
17
  const where = instances.map(named).join(', ');
17
- return unused(context.config, declaredIn, `${declaredIn} matches no files: ${selector} finds nothing in ${where}. Fix the selector, or remove the module.`, { kind: 'empty', declaredIn, layer, selector });
18
+ return unused(context.config, declaredIn, `${declaredIn} matches no files: ${selector} finds nothing in ${where}. Fix the pattern, or remove the module.`, { kind: 'empty', declaredIn, layer, selector });
19
+ };
20
+ const shown = (patterns) => {
21
+ const items = patterns
22
+ .map((pattern) => pattern.replaceAll('{name}', '*'))
23
+ .map((pattern) => (/^[\w./-]+$/.test(pattern) ? pattern : `'${pattern}'`));
24
+ return items.length === 1 ? items[0] : `[${items.join(', ')}]`;
18
25
  };
19
- const quoted = (patterns) => patterns.map((pattern) => `'${pattern}'`).join(', ');
20
26
  const selectorText = (module) => {
21
27
  if (module.kind === 'dir')
22
- return `dir(${quoted(module.paths)})`;
23
- if (module.kind === 'files')
24
- return `files(${quoted(module.patterns)})`;
25
- const { locator } = module;
26
- if (locator.kind === 'mirror')
27
- return `mirror('${locator.from}', '${locator.to}')`;
28
- return `${locator.kind}(${quoted(locator.patterns)})`;
28
+ return `dir: ${shown(module.paths)}`;
29
+ return `files: ${shown(module.patterns)}`;
29
30
  };
@@ -1,42 +1,70 @@
1
+ import { isTestData, } from '../../model/archetype/data.js';
1
2
  import { show } from '../../model/archetype/references.js';
2
3
  import { listsPackage } from '../packages.js';
3
4
  import { childrenNamed, instancesOf, named, unused } from './declarations.js';
4
5
  export const unusedGrants = (context) => {
5
6
  const used = usedRefs(context);
6
- return declared(context)
7
+ return declared(context, used)
7
8
  .filter(({ ref, holders }) => !used.has(ref) && holders.some((holder) => context.atModule(holder).on))
8
- .map(({ ref, declaredIn, layer, holders, kit }) => {
9
+ .map(({ ref, declaredIn, layer, holders, ending, kit }) => {
9
10
  const using = show(ref);
10
11
  const modules = holders.map((holder) => holder.id);
11
12
  const names = holders.map(named).join(', ');
12
13
  const files = kit ? `the tests of ${names}` : names;
13
- return unused(context.config, `${declaredIn}->${using}`, `${declaredIn} uses ${using}, but nothing in ${files} imports through it. Remove it from the using.`, { kind: 'grant', declaredIn, layer, using, modules });
14
+ return unused(context.config, `${declaredIn}->${using}`, `${declaredIn} names ${using}, but nothing in ${files} imports through it. ${ending}`, { kind: 'grant', declaredIn, layer, using, modules });
14
15
  });
15
16
  };
16
- const declared = (context) => Object.values(context.config.archetypes).flatMap((archetype) => {
17
+ const declared = (context, used) => Object.values(context.config.archetypes).flatMap((archetype) => {
17
18
  const instances = instancesOf(context, archetype.name);
19
+ const unusedInputs = new Set(archetype.requires.filter((name) => !bindingsOf(context.config, archetype, name).some((ref) => used.has(ref))));
20
+ const requires = [...unusedInputs].map((name) => ({
21
+ ref: { kind: 'required', name },
22
+ declaredIn: `${archetype.name}.requires`,
23
+ layer: 'production',
24
+ holders: instances,
25
+ ending: 'Remove it, with its binding at each use.',
26
+ }));
18
27
  const modules = archetype.modules.flatMap((module) => {
19
28
  const holders = childrenNamed(context, instances, module.name);
20
- const layer = module.kind === 'test' ? 'test' : 'production';
21
- return module.using.map((ref) => ({ ref, declaredIn: `${archetype.name}.${module.name}`, layer, holders }));
29
+ const layer = isTestData(module) ? 'test' : 'production';
30
+ return module.using
31
+ .filter((ref) => !fills(context.config, module, ref))
32
+ .filter((ref) => ref.kind !== 'required' || !unusedInputs.has(ref.name))
33
+ .map((ref) => ({
34
+ ref,
35
+ declaredIn: `${archetype.name}.${module.name}.dependencies`,
36
+ layer,
37
+ holders,
38
+ ending: 'Remove it.',
39
+ }));
22
40
  });
23
41
  const kit = (archetype.testUsing ?? []).map((ref) => ({
24
42
  ref,
25
- declaredIn: `${archetype.name}.testUsing`,
43
+ declaredIn: `${archetype.name}.test.provides`,
26
44
  layer: 'test',
27
45
  holders: instances,
46
+ ending: 'Remove it.',
28
47
  kit: true,
29
48
  }));
30
- return [...modules, ...kit];
49
+ return [...requires, ...modules, ...kit];
31
50
  });
51
+ const fills = (config, module, ref) => module.kind === 'dir' &&
52
+ Object.entries(module.inputs ?? {}).some(([name, bound]) => bound === ref && config.archetypes[module.archetype].requires.includes(name));
53
+ const bindingsOf = (config, archetype, name) => Object.values(config.archetypes).flatMap((holder) => holder.modules.flatMap((module) => module.kind === 'dir' && module.archetype === archetype.name && module.inputs?.[name]
54
+ ? [module.inputs[name]]
55
+ : []));
32
56
  const usedRefs = ({ project, verdicts }) => {
33
57
  const used = new Set();
34
58
  for (const file of project.files) {
35
59
  const reach = verdicts.reach(file.path) ?? [];
36
60
  const targets = file.imports.map((edge) => edge.via ?? edge.to);
37
- for (const grant of reach)
38
- if (grant.declared && permits(grant, targets, file.externals))
39
- used.add(grant.declared);
61
+ for (const grant of reach) {
62
+ if (!grant.declared || !permits(grant, targets, file.externals))
63
+ continue;
64
+ used.add(grant.declared);
65
+ for (const bound of grant.via ?? [])
66
+ used.add(bound);
67
+ }
40
68
  }
41
69
  return used;
42
70
  };
@@ -1,3 +1,4 @@
1
+ import { isTestData } from '../../model/archetype/data.js';
1
2
  import { childrenNamed, instancesOf, named, unused, within } from './declarations.js';
2
3
  export const unusedSurfaces = (context) => {
3
4
  const edges = context.project.files.flatMap((file) => file.imports.map((edge) => ({ from: file.path, to: edge.via ?? edge.to })));
@@ -16,15 +17,24 @@ const declared = (context) => Object.values(context.config.archetypes).flatMap((
16
17
  const judged = isEntry(archetype.exposes)
17
18
  ? instances.filter((instance) => !isTopLevel(context, instance))
18
19
  : instances;
19
- const own = archetype.exposes ? surfaces(context, archetype.name, archetype.exposes, judged, 'production') : [];
20
+ const own = archetype.exposes
21
+ ? surfaces(context, archetype.name, archetype.exposes, judged, archetype.test ? 'test' : 'production')
22
+ : [];
23
+ const tests = Object.entries(archetype.testExposes ?? {}).map(([name, refs]) => ({
24
+ declaredIn: archetype.name,
25
+ layer: 'test',
26
+ exposes: `test.exposes ${name}`,
27
+ holders: instances,
28
+ files: (holder) => new Set(refs.flatMap((ref) => [...context.verdicts.files(holder, ref, 'test')])),
29
+ }));
20
30
  const modules = archetype.modules.flatMap((module) => {
21
31
  const holders = childrenNamed(context, instances, module.name);
22
- const layer = module.kind === 'test' ? 'test' : 'production';
32
+ const layer = isTestData(module) ? 'test' : 'production';
23
33
  return module.kind !== 'dir' && module.exposes
24
34
  ? surfaces(context, `${archetype.name}.${module.name}`, module.exposes, holders, layer)
25
35
  : [];
26
36
  });
27
- return [...own, ...modules];
37
+ return [...own, ...tests, ...modules];
28
38
  });
29
39
  const isEntry = (exposes) => exposes?.kind === 'files' && exposes.entry === true;
30
40
  const isTopLevel = (context, module) => module.parent === context.model.root;
@@ -43,7 +53,7 @@ const surfaces = (context, declaredIn, exposes, holders, layer) => {
43
53
  };
44
54
  const whole = (exposes) => {
45
55
  if (exposes.kind === 'all')
46
- return 'exposes(all())';
47
- const selector = `files(${exposes.patterns.map((pattern) => `'${pattern}'`).join(', ')})`;
48
- return exposes.entry ? `.entry(${selector})` : `exposes(${selector})`;
56
+ return 'exposes: all';
57
+ const patterns = exposes.patterns.join(', ');
58
+ return exposes.entry ? `entry: ${patterns}` : `exposes: { files: [${patterns}] }`;
49
59
  };
package/dist/cli.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, realpathSync } from 'node:fs';
3
- import { basename, dirname, resolve } from 'node:path';
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
5
  import { diskFolders } from './analysis/folders.js';
6
6
  import { typescriptAnalyzer } from './analysis/typescript.js';
7
7
  import { modelProject, projectCheck } from './app/check.js';
8
+ import { placeProblems } from './app/configLines.js';
8
9
  import { factsStore } from './app/facts.js';
9
10
  import { diffProject, parseRange } from './app/diff.js';
10
11
  import { builtinRegistry, unclassifiedDocs } from './builtins/index.js';
@@ -12,7 +13,8 @@ import { findConfig, loadConfig } from './config/loadConfig.js';
12
13
  import { toolDigest } from './config/toolDigest.js';
13
14
  import { gitDirCache } from './git/cache.js';
14
15
  import { gitRepository, projectPathOf } from './git/repository.js';
15
- import { rulesOf } from './model/archetype/settings.js';
16
+ import { anyRuleOn, rulesOf } from './model/archetype/settings.js';
17
+ import { recommended } from './model/archetype/rulesets.js';
16
18
  import { loadConfigData } from './app/load.js';
17
19
  import { ConfigError } from './model/configError.js';
18
20
  import { reporters } from './reporters/index.js';
@@ -29,7 +31,7 @@ diff reports findings that are new or worse at <head> than at <base>. Without
29
31
  With --since-last-run, compares the working tree with the last such run, or with <base> if there is none.
30
32
  model prints the modules the config finds, and which module each file is in.
31
33
 
32
- --config path to the config file (default: the first of warp.config.ts, .mts, .js, .mjs)
34
+ --config path to the config file (default: warp.yaml)
33
35
  --ruleset one of the config's rulesets (default: the one named default, if any)
34
36
  --reporter ${[...reporters.keys()].join(', ')} (default: text)
35
37
  --since-last-run with diff, compare with the last diff run that had this flag
@@ -81,25 +83,31 @@ const help = (code) => {
81
83
  const resolveConfig = async (options) => {
82
84
  const configFile = realpathSync(options.config ? resolve(options.config) : findConfig(process.cwd()));
83
85
  const root = dirname(configFile);
84
- const { raw, digest } = await loadConfig(configFile);
86
+ const { raw, plugins, lines, digest } = await loadConfig(configFile);
85
87
  const builtins = [...builtinRegistry.values()];
86
- const { config, rules, warnings } = loadConfigData(raw, {
87
- builtins,
88
- ruleset: options.ruleset,
89
- file: basename(configFile),
90
- });
91
- for (const warning of warnings)
92
- console.error(`warp config: ${warning}`);
93
- return { root, config, rules, digest };
88
+ const file = basename(configFile);
89
+ try {
90
+ const { config, rules } = loadConfigData(raw, { builtins, plugins, ruleset: options.ruleset, file });
91
+ for (const tsconfig of config.tsconfig.filter((path) => !existsSync(join(root, path))))
92
+ throw new ConfigError(`tsconfig: no ${tsconfig} beside ${file}; add it, or list the project's tsconfig files under tsconfig`);
93
+ return { root, config, rules, lines, digest };
94
+ }
95
+ catch (error) {
96
+ if (error instanceof ConfigError)
97
+ throw new ConfigError(placeProblems(lines, file, error.message));
98
+ throw error;
99
+ }
94
100
  };
95
- const checkOf = ({ root, config, rules }) => projectCheck(adaptersAt(root), config, { rules, unclassifiedDocs });
101
+ const checkOf = ({ root, config, rules, lines }) => projectCheck(adaptersAt(root), config, { rules, unclassifiedDocs, lines });
96
102
  const run = async (options, produce) => {
97
103
  const reporter = reporters.get(options.reporter);
98
104
  if (!reporter)
99
105
  throw new Error(`no reporter called ${options.reporter}: use one of ${[...reporters.keys()].join(', ')}`);
100
106
  try {
101
107
  const resolved = await resolveConfig(options);
102
- const report = produce(resolved.root, checkOf(resolved), resolved.digest);
108
+ if (!anyRuleOn(resolved.config))
109
+ console.error(nothingOn(resolved.config.file));
110
+ const report = placed(resolved, () => produce(resolved.root, checkOf(resolved), resolved.digest));
103
111
  const output = reporter.render(report, { toolVersion: version(), projectPath: projectPathOf(resolved.root) });
104
112
  if (output)
105
113
  console.log(output);
@@ -116,6 +124,17 @@ const run = async (options, produce) => {
116
124
  return 0;
117
125
  }
118
126
  };
127
+ const placed = ({ lines, config }, run) => {
128
+ try {
129
+ return run();
130
+ }
131
+ catch (error) {
132
+ if (error instanceof ConfigError)
133
+ throw new ConfigError(placeProblems(lines, config.file, error.message));
134
+ throw error;
135
+ }
136
+ };
137
+ const nothingOn = (file) => `No rules are on, so nothing was checked. Turn some on in ${file}: rulesets: { default: { extends: [${recommended}] } }`;
119
138
  const failureKey = () => `${toolDigest()}-failure`;
120
139
  const failureCache = () => {
121
140
  try {
@@ -139,8 +158,9 @@ const forgetFailure = () => {
139
158
  };
140
159
  const printModel = async (options) => {
141
160
  try {
142
- const { root, config, rules } = await resolveConfig(options);
143
- const { model } = modelProject(adaptersAt(root), root, config);
161
+ const resolved = await resolveConfig(options);
162
+ const { root, config, rules } = resolved;
163
+ const { model } = placed(resolved, () => modelProject(adaptersAt(root), root, config));
144
164
  const settings = rulesOf(config, model, rules);
145
165
  console.log(options.json ? modelJson(model, settings) : modelText(model, options.rules ? settings : undefined));
146
166
  return 0;