@yearofthedan/warp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +9 -8
  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.js +2 -1
  6. package/dist/app/checkModel.js +1 -1
  7. package/dist/app/load.js +12 -12
  8. package/dist/builtins/advice.d.ts +8 -0
  9. package/dist/builtins/advice.js +42 -0
  10. package/dist/builtins/dependency-direction/dependencyDirection.js +32 -15
  11. package/dist/builtins/index.js +2 -0
  12. package/dist/builtins/module-externals/moduleExternals.js +10 -9
  13. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.js +16 -5
  14. package/dist/builtins/place.js +5 -3
  15. package/dist/builtins/unresolved-import/unresolvedImport.d.ts +2 -0
  16. package/dist/builtins/unresolved-import/unresolvedImport.js +15 -0
  17. package/dist/builtins/unused-declaration/declarations.js +1 -1
  18. package/dist/builtins/unused-declaration/empty.js +16 -9
  19. package/dist/builtins/unused-declaration/grants.js +8 -11
  20. package/dist/builtins/unused-declaration/surfaces.js +11 -19
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/model/archetype/builder.d.ts +11 -11
  24. package/dist/model/archetype/builder.js +14 -21
  25. package/dist/model/archetype/data.d.ts +19 -13
  26. package/dist/model/archetype/draft.d.ts +2 -9
  27. package/dist/model/archetype/draft.js +48 -59
  28. package/dist/model/archetype/fixes.d.ts +37 -0
  29. package/dist/model/archetype/fixes.js +234 -0
  30. package/dist/model/archetype/reach.js +34 -80
  31. package/dist/model/archetype/references.d.ts +1 -1
  32. package/dist/model/archetype/references.js +13 -28
  33. package/dist/model/archetype/requirements.js +3 -6
  34. package/dist/model/archetype/resolve.d.ts +2 -3
  35. package/dist/model/archetype/resolve.js +85 -67
  36. package/dist/model/archetype/rulesets.js +0 -7
  37. package/dist/model/archetype/settings.js +4 -19
  38. package/dist/model/facts.d.ts +6 -0
  39. package/dist/reporters/model.js +8 -9
  40. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { ConfigError } from '../configError.js';
2
2
  export const declarationOf = (config, module) => module.parent && config.archetypes[module.parent.archetype].modules.find((data) => data.name === module.name);
3
+ export const rootId = '(root)';
3
4
  const placeholders = /\{(\w+)\}/g;
4
5
  const join = (dir, name) => (dir === '' ? name : `${dir}/${name}`);
5
6
  const parentDir = (path) => path.slice(0, Math.max(path.lastIndexOf('/'), 0));
@@ -14,17 +15,13 @@ export const fillPattern = (pattern, captures) => {
14
15
  return 'filled' in filled ? filled.filled : undefined;
15
16
  };
16
17
  export const resolveModel = (config, folders, files) => {
17
- const resolution = { config, folders, byDir: new Map(), errors: new Set() };
18
+ const resolution = { config, folders, byDir: new Map(), mirrors: new Map(), errors: new Set() };
18
19
  const root = build(resolution, { dir: '', archetype: config.archetypes[config.root], captures: {} });
20
+ for (const module of walk(root))
21
+ mirrorsOf(resolution, module);
19
22
  const moduleOf = new Map();
20
- const tests = new Set();
21
- const isTest = testMatcher(config.tests);
22
- for (const file of [...files].sort()) {
23
- const { module, test } = assign(resolution, file, isTest(file));
24
- if (test)
25
- tests.add(file);
26
- moduleOf.set(file, module);
27
- }
23
+ for (const file of [...files].sort())
24
+ moduleOf.set(file, assign(resolution, file));
28
25
  if (resolution.errors.size > 0)
29
26
  throw new ConfigError([...resolution.errors].join('\n'));
30
27
  order(config, root);
@@ -32,31 +29,42 @@ export const resolveModel = (config, folders, files) => {
32
29
  root,
33
30
  modules: [...walk(root)],
34
31
  moduleOf: (file) => moduleOf.get(file),
35
- isTest: (file) => tests.has(file),
32
+ isTest: (file) => moduleOf.get(file)?.kind === 'test',
36
33
  };
37
34
  };
38
- const assign = (resolution, file, entry) => {
35
+ const assign = (resolution, file) => {
39
36
  const folder = deepest(resolution.byDir, file);
40
- const claim = claimOf(resolution, folder, file);
41
- if (claim) {
42
- const support = claim.kind === 'dir' ? place(resolution, claim, file, 'tests') : claim;
43
- if (support.test)
44
- support.files.push(file);
37
+ const module = mirrorClaim(resolution, file) ?? claimOf(resolution, folder, file) ?? place(resolution, folder, file);
38
+ module.files.push(file);
39
+ return module;
40
+ };
41
+ const mirrorsOf = (resolution, holder) => {
42
+ if (holder.kind !== 'dir')
43
+ return;
44
+ for (const declared of resolution.config.archetypes[holder.archetype].modules) {
45
+ if (declared.kind !== 'test' || declared.locator.kind !== 'mirror')
46
+ continue;
47
+ const { from, to } = declared.locator;
48
+ const where = `${holder.id}: ${holder.archetype}.${declared.name} mirror('${from}', '${to}')`;
49
+ if (holder.dir !== from && !holder.dir.startsWith(`${from}/`)) {
50
+ resolution.errors.add(`${where} needs a folder under ${from}; this module is not in it`);
51
+ continue;
52
+ }
53
+ const target = `${to}${holder.dir.slice(from.length)}`;
54
+ const taken = resolution.mirrors.get(target);
55
+ if (taken)
56
+ resolution.errors.add(`${target}: mirrored by ${taken.holder.id} and ${holder.id}; one folder mirrors one module`);
45
57
  else
46
- claim.tests.push(file);
47
- return { module: support.test ? support : claim, test: true };
58
+ resolution.mirrors.set(target, { holder, name: declared.name });
48
59
  }
49
- if (entry) {
50
- folder.tests.push(file);
51
- return { module: folder, test: true };
52
- }
53
- const module = place(resolution, folder, file, 'all');
54
- module.files.push(file);
55
- return { module, test: module.test === true };
56
60
  };
57
- const testMatcher = (patterns = []) => {
58
- const regexes = patterns.map(globRegex);
59
- return (file) => regexes.some((regex) => regex.test(file));
61
+ const mirrorClaim = (resolution, file) => {
62
+ for (let dir = parentDir(file); dir !== ''; dir = parentDir(dir)) {
63
+ const mirror = resolution.mirrors.get(dir);
64
+ if (mirror)
65
+ return childModule(mirror.holder, mirror.name, 'test');
66
+ }
67
+ return undefined;
60
68
  };
61
69
  const walk = function* (module) {
62
70
  yield module;
@@ -67,29 +75,22 @@ const order = (config, module) => {
67
75
  if (module.archetype === undefined)
68
76
  return;
69
77
  const archetype = config.archetypes[module.archetype];
70
- const declared = [
71
- ...archetype.modules.map((data) => data.name),
72
- ...(archetype.tests?.modules ?? []).map((data) => `tests.${data.name}`),
73
- ];
78
+ const declared = archetype.modules.map((data) => data.name);
74
79
  module.children.sort((a, b) => declared.indexOf(a.name) - declared.indexOf(b.name) || a.dir.localeCompare(b.dir));
75
80
  for (const child of module.children)
76
81
  order(config, child);
77
82
  };
78
- const place = (resolution, folder, file, among) => {
83
+ const place = (resolution, folder, file) => {
79
84
  const archetype = resolution.config.archetypes[folder.archetype];
80
- const candidates = [
81
- ...(among === 'all' ? archetype.modules : []),
82
- ...(archetype.tests?.modules ?? []).map((module) => ({ ...module, name: `tests.${module.name}` })),
83
- ];
84
- if (candidates.length === 0 || (among === 'all' && isEntry(archetype, folder, file)))
85
+ const production = archetype.modules.filter((module) => module.kind !== 'test');
86
+ if (production.length === 0 || isEntry(archetype, folder, file))
85
87
  return folder;
86
- const name = filesModule(resolution, folder, archetype, candidates, file);
88
+ const name = filesModule(resolution, folder, archetype, production, file);
87
89
  if (name === undefined) {
88
- if (among === 'all' && archetype.modules.length > 0)
89
- folder.looseFiles.push(file);
90
+ folder.looseFiles.push(file);
90
91
  return folder;
91
92
  }
92
- return childModule(folder, name);
93
+ return childModule(folder, name, 'files');
93
94
  };
94
95
  const isEntry = (archetype, folder, file) => {
95
96
  const { exposes } = archetype;
@@ -101,22 +102,20 @@ const isEntry = (archetype, folder, file) => {
101
102
  return filled !== undefined && globRegex(filled).test(path);
102
103
  });
103
104
  };
104
- const childModule = (folder, name) => {
105
+ const childModule = (folder, name, kind) => {
105
106
  const id = `${folder.id}:${name}`;
106
107
  let module = folder.children.find((child) => child.id === id);
107
108
  if (!module) {
108
109
  module = {
109
110
  id,
110
111
  name,
111
- kind: 'files',
112
+ kind,
112
113
  dir: folder.dir,
113
114
  captures: folder.captures,
114
115
  parent: folder,
115
116
  children: [],
116
117
  files: [],
117
118
  looseFiles: [],
118
- tests: [],
119
- ...(name.startsWith('tests.') ? { test: true } : {}),
120
119
  };
121
120
  folder.children.push(module);
122
121
  }
@@ -126,35 +125,39 @@ const claimOf = (resolution, folder, file) => {
126
125
  for (let at = folder; at; at = at.parent) {
127
126
  const archetype = resolution.config.archetypes[at.archetype];
128
127
  const level = at;
129
- const claims = [
130
- ...(locates(level, archetype.tests?.locator, file) ? [level] : []),
131
- ...archetype.modules
132
- .filter((declared) => declared.kind === 'files')
133
- .filter((declared) => locates(level, declared.tests?.locator, file))
134
- .map((declared) => childModule(level, declared.name)),
135
- ];
136
- if (claims.length > 1)
137
- resolution.errors.add(`${file}: claimed as tests by ${claims.map((claim) => claim.id).join(' and ')}; narrow one of their locators`);
138
- if (claims.length > 0)
139
- return claims[0];
128
+ const claims = archetype.modules
129
+ .filter((declared) => declared.kind === 'test')
130
+ .flatMap((declared) => {
131
+ const score = locates(level, declared.locator, file);
132
+ return score === undefined ? [] : [{ name: declared.name, score }];
133
+ });
134
+ if (claims.length === 0)
135
+ continue;
136
+ const best = claims.reduce((top, claim) => (claim.score > top.score ? claim : top));
137
+ const tied = claims.filter((claim) => claim !== best && claim.score === best.score);
138
+ if (tied.length > 0)
139
+ resolution.errors.add(`${file}: claimed by ${archetype.name}'s test modules ${[best, ...tied].map((claim) => claim.name).join(' and ')}, which are equally specific; narrow one of their selectors`);
140
+ return childModule(level, best.name, 'test');
140
141
  }
141
142
  return undefined;
142
143
  };
143
144
  const locates = (module, locator, file) => {
144
- if (!locator)
145
- return false;
145
+ if (locator.kind === 'mirror')
146
+ return undefined;
146
147
  const path = module.dir === '' ? file : file.slice(module.dir.length + 1);
147
- return locator.patterns.some((pattern) => {
148
+ const scores = locator.patterns.flatMap((pattern) => {
148
149
  const filled = fillPattern(pattern, module.captures);
149
150
  if (filled === undefined)
150
- return false;
151
- return locator.kind === 'dir' ? path.startsWith(`${filled}/`) : globRegex(filled).test(path);
151
+ return [];
152
+ const glob = locator.kind === 'dir' ? `${filled}/**` : filled;
153
+ return globRegex(glob).test(path) ? [specificity(glob)] : [];
152
154
  });
155
+ return scores.length === 0 ? undefined : Math.max(...scores);
153
156
  };
154
157
  const pathOf = (module) => module.parent?.name === undefined ? module.name : `${pathOf(module.parent)}.${module.name}`;
155
158
  const build = (resolution, { dir, archetype, captures, parent, name }) => {
156
159
  const module = {
157
- id: dir === '' ? '.' : dir,
160
+ id: dir === '' ? rootId : dir,
158
161
  ...(name === undefined ? {} : { name }),
159
162
  kind: 'dir',
160
163
  dir,
@@ -164,7 +167,6 @@ const build = (resolution, { dir, archetype, captures, parent, name }) => {
164
167
  children: [],
165
168
  files: [],
166
169
  looseFiles: [],
167
- tests: [],
168
170
  };
169
171
  resolution.byDir.set(dir, module);
170
172
  for (const [childDir, claims] of [...claimsIn(resolution, module, archetype)].sort(([a], [b]) => a.localeCompare(b))) {
@@ -198,7 +200,7 @@ const claimsIn = (resolution, module, archetype) => {
198
200
  const claimsOf = (resolution, module, declared) => {
199
201
  const child = resolution.config.archetypes[declared.archetype];
200
202
  return declared.paths.flatMap((path) => matchFolders(resolution.folders, module.dir, path).flatMap((match) => {
201
- const captures = identify(resolution, child, match.dir, match.captures, module);
203
+ const captures = identify(resolution, child, match.dir, match.captures, module, { declared, path });
202
204
  return captures ? [{ module: declared, path, archetype: child, ...match, captures }] : [];
203
205
  }));
204
206
  };
@@ -217,7 +219,7 @@ const matchFolders = (folders, base, path) => {
217
219
  }
218
220
  return found;
219
221
  };
220
- const identify = (resolution, archetype, dir, captures, parent) => {
222
+ const identify = (resolution, archetype, dir, captures, parent, claim) => {
221
223
  const how = archetype.identify;
222
224
  if (how === undefined)
223
225
  return captures;
@@ -227,11 +229,27 @@ const identify = (resolution, archetype, dir, captures, parent) => {
227
229
  }
228
230
  const marker = fill(how.marker, captures);
229
231
  if ('missing' in marker) {
230
- resolution.errors.add(`${dir}: ${archetype.name}'s marker '${how.marker}' names {${marker.missing}}, which its dir path doesn't capture`);
232
+ resolution.errors.add(`${dir}: ${archetype.name}'s marker '${how.marker}' names {${marker.missing}}, which its dir path doesn't capture` +
233
+ sharedHint(resolution, parent, claim, marker.missing));
231
234
  return undefined;
232
235
  }
233
236
  return resolution.folders.exists(join(dir, marker.filled)) ? captures : undefined;
234
237
  };
238
+ const sharedHint = (resolution, parent, { declared, path }, missing) => {
239
+ if (path.includes('{'))
240
+ return '';
241
+ const sibling = resolution.config.archetypes[parent.archetype].modules.find((module) => module.kind === 'dir' &&
242
+ module !== declared &&
243
+ module.archetype === declared.archetype &&
244
+ module.paths.some((candidate) => candidate.includes(`{${missing}}`)));
245
+ if (!sibling)
246
+ return '';
247
+ const folder = path.slice(path.lastIndexOf('/') + 1);
248
+ const shown = sibling.paths.map((candidate) => `'${candidate}'`).join(', ');
249
+ return (`. A literal dir() binds no placeholders. If ${sibling.name} use ${declared.name}, it is shared: move ${folder} ` +
250
+ `out of the folders dir(${shown}) matches, for example into shared/${folder}, and declare it as its own module ` +
251
+ `with dir('shared/{${missing}}')`);
252
+ };
235
253
  const chain = (module) => (module.parent ? [...chain(module.parent), module] : [module]);
236
254
  const compareRanks = (a, b) => {
237
255
  const index = a.findIndex((value, at) => value !== b[at]);
@@ -86,13 +86,6 @@ const applyTo = (archetype, module, layer, at, fail) => {
86
86
  archetype.rules = merged(archetype.rules, layer);
87
87
  return;
88
88
  }
89
- if (module === 'tests') {
90
- if (archetype.tests)
91
- archetype.tests = { ...archetype.tests, rules: merged(archetype.tests.rules, layer) };
92
- else
93
- fail(`${at}: ${archetype.name} has no test layer`);
94
- return;
95
- }
96
89
  const index = archetype.modules.findIndex((declared) => declared.name === module);
97
90
  if (index < 0)
98
91
  fail(`${at}: ${archetype.name} has modules ${list(archetype.modules.map((declared) => declared.name), 'none')}`);
@@ -1,32 +1,17 @@
1
1
  import { declarationOf } from './resolve.js';
2
2
  import { isRecord } from './shared.js';
3
- const layerOf = (config, module) => {
4
- if (module.archetype !== undefined)
5
- return config.archetypes[module.archetype].tests;
6
- const declared = declarationOf(config, module);
7
- return declared?.kind === 'files' ? declared.tests : undefined;
8
- };
9
3
  const own = (config, module) => [
10
4
  declarationOf(config, module)?.rules,
11
5
  module.archetype === undefined ? undefined : config.archetypes[module.archetype].rules,
12
6
  ];
13
- const testModuleRules = (config, module) => layerOf(config, module.parent)?.modules.find((data) => `tests.${data.name}` === module.name)?.rules;
14
- const levels = (config, module) => {
15
- if (module.test)
16
- return [testModuleRules(config, module), ...testLevels(config, module.parent)];
17
- return [...own(config, module), ...(module.parent ? levels(config, module.parent) : [config.rules])];
18
- };
19
- const testLevels = (config, owner) => [
20
- layerOf(config, owner)?.rules,
21
- ...own(config, owner),
22
- ...(owner.parent ? testLevels(config, owner.parent) : [config.rules]),
7
+ const levels = (config, module) => [
8
+ ...own(config, module),
9
+ ...(module.parent ? levels(config, module.parent) : [config.rules]),
23
10
  ];
24
11
  export const settings = (config, model) => {
25
12
  const fileLevels = (file) => {
26
13
  const module = model.moduleOf(file);
27
- if (!module)
28
- return [config.rules];
29
- return model.isTest(file) && !module.test ? testLevels(config, module) : levels(config, module);
14
+ return module ? levels(config, module) : [config.rules];
30
15
  };
31
16
  return {
32
17
  atFile: (file, id, defaults) => ruleAt(fileLevels(file), id, defaults),
@@ -6,6 +6,7 @@ export interface FileFacts {
6
6
  lines: number;
7
7
  imports: ImportEdge[];
8
8
  externals: ExternalImport[];
9
+ unresolved: UnresolvedImport[];
9
10
  members: MemberGraph;
10
11
  functions: FunctionFacts[];
11
12
  }
@@ -28,6 +29,11 @@ export interface ExternalImport {
28
29
  reExport?: true;
29
30
  line: number;
30
31
  }
32
+ export interface UnresolvedImport {
33
+ from: string;
34
+ specifier: string;
35
+ line: number;
36
+ }
31
37
  export type MemberKind = 'function' | 'class' | 'state' | 'type' | 'code';
32
38
  export interface Member {
33
39
  name: string;
@@ -14,10 +14,11 @@ export const modelText = (model, rules) => {
14
14
  visit(child, depth + 1);
15
15
  };
16
16
  visit(model.root, 0);
17
- const files = model.modules.reduce((sum, module) => sum + module.files.length, 0);
17
+ const total = (modules) => modules.reduce((sum, module) => sum + module.files.length, 0);
18
+ const files = total(model.modules.filter((module) => module.kind !== 'test'));
19
+ const tests = total(model.modules.filter((module) => module.kind === 'test'));
18
20
  const loose = model.modules.reduce((sum, module) => sum + module.looseFiles.length, 0);
19
- const tests = model.modules.reduce((sum, module) => sum + module.tests.length, 0);
20
- const tested = tests > 0 ? `, ${count(tests, 'test')}` : '';
21
+ const tested = tests > 0 ? `, ${count(tests, 'test file')}` : '';
21
22
  lines.push('', `${model.modules.length} modules, ${files} files${tested}, ${loose} loose.`);
22
23
  return lines.join('\n');
23
24
  };
@@ -34,14 +35,13 @@ const heading = (module) => {
34
35
  const owned = module.files.length - module.looseFiles.length;
35
36
  if (module.kind === 'files')
36
37
  return count(owned);
38
+ if (module.kind === 'test')
39
+ return count(owned, 'test file');
37
40
  const captures = Object.entries(module.captures)
38
41
  .map(([key, value]) => ` {${key}=${value}}`)
39
42
  .join('');
40
- const contents = [
41
- ...(owned > 0 ? [count(owned)] : []),
42
- ...(module.tests.length > 0 ? [count(module.tests.length, 'test')] : []),
43
- ];
44
- return `${module.name ?? 'root'}: ${module.archetype}${captures}${contents.map((part) => `, ${part}`).join('')}`;
43
+ const contents = owned > 0 ? `, ${count(owned)}` : '';
44
+ return `${module.name ?? 'root'}: ${module.archetype}${captures}${contents}`;
45
45
  };
46
46
  export const modelJson = (model, rules) => JSON.stringify({
47
47
  modules: model.modules.map((module) => ({
@@ -54,7 +54,6 @@ export const modelJson = (model, rules) => JSON.stringify({
54
54
  children: module.children.map((child) => child.id),
55
55
  files: module.files,
56
56
  looseFiles: module.looseFiles,
57
- tests: module.tests,
58
57
  ...(rules ? { rules: rules.module(module) } : {}),
59
58
  })),
60
59
  }, null, 2);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yearofthedan/warp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Architectural fitness checks for TypeScript codebases",
5
5
  "license": "MIT",
6
6
  "repository": {