@yearofthedan/warp 0.4.0 → 0.5.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 (152) hide show
  1. package/README.md +5 -7
  2. package/dist/{analysis → adapters/analysis}/complexity.d.ts +1 -1
  3. package/dist/adapters/analysis/folders.d.ts +2 -0
  4. package/dist/{app/facts.d.ts → adapters/analysis/freshFacts.d.ts} +1 -2
  5. package/dist/{app/facts.js → adapters/analysis/freshFacts.js} +0 -10
  6. package/dist/{analysis → adapters/analysis}/imports.d.ts +2 -1
  7. package/dist/{analysis → adapters/analysis}/imports.js +52 -18
  8. package/dist/{analysis → adapters/analysis}/members.d.ts +1 -1
  9. package/dist/adapters/analysis/specifiers.d.ts +10 -0
  10. package/dist/adapters/analysis/specifiers.js +39 -0
  11. package/dist/adapters/analysis/typescript.d.ts +2 -0
  12. package/dist/{analysis → adapters/analysis}/typescript.js +10 -4
  13. package/dist/adapters/config/loadConfig.d.ts +8 -0
  14. package/dist/{config → adapters/config}/loadConfig.js +44 -21
  15. package/dist/{git → adapters/git}/cache.d.ts +1 -1
  16. package/dist/{git → adapters/git}/cache.js +5 -1
  17. package/dist/adapters/git/factsStore.d.ts +2 -0
  18. package/dist/adapters/git/factsStore.js +10 -0
  19. package/dist/{git → adapters/git}/repository.d.ts +1 -1
  20. package/dist/{config → adapters/git}/toolDigest.js +1 -1
  21. package/dist/{reporters → adapters/reporters}/model.d.ts +2 -2
  22. package/dist/{reporters → adapters/reporters}/reporter.d.ts +2 -2
  23. package/dist/{reporters → adapters/reporters}/text.d.ts +2 -2
  24. package/dist/app/check.d.ts +5 -6
  25. package/dist/app/check.js +3 -3
  26. package/dist/app/checkModel.d.ts +5 -5
  27. package/dist/app/checkModel.js +4 -5
  28. package/dist/app/configLines.d.ts +1 -1
  29. package/dist/app/diff.d.ts +1 -1
  30. package/dist/app/diff.js +1 -1
  31. package/dist/app/failures.d.ts +6 -0
  32. package/dist/app/failures.js +15 -0
  33. package/dist/app/load.d.ts +11 -5
  34. package/dist/app/load.js +22 -59
  35. package/dist/app/ports.d.ts +13 -3
  36. package/dist/builtins/advice.d.ts +4 -4
  37. package/dist/builtins/advice.js +2 -2
  38. package/dist/builtins/cognitive-complexity/{cognitiveComplexity.d.ts → rule.d.ts} +1 -1
  39. package/dist/builtins/cognitive-complexity/{cognitiveComplexity.js → rule.js} +1 -1
  40. package/dist/builtins/components.d.ts +1 -1
  41. package/dist/builtins/dependency-direction/rule.d.ts +2 -0
  42. package/dist/builtins/dependency-direction/{dependencyDirection.js → rule.js} +9 -4
  43. package/dist/builtins/file-cohesion/{fileCohesion.d.ts → rule.d.ts} +1 -1
  44. package/dist/builtins/file-cohesion/{fileCohesion.js → rule.js} +1 -1
  45. package/dist/builtins/function-cohesion/{functionCohesion.d.ts → rule.d.ts} +1 -1
  46. package/dist/builtins/function-cohesion/{functionCohesion.js → rule.js} +1 -1
  47. package/dist/builtins/index.d.ts +2 -2
  48. package/dist/builtins/index.js +18 -13
  49. package/dist/builtins/loops.d.ts +1 -1
  50. package/dist/builtins/loops.js +1 -1
  51. package/dist/builtins/module-cycle/{moduleCycle.d.ts → rule.d.ts} +1 -1
  52. package/dist/builtins/module-externals/rule.d.ts +2 -0
  53. package/dist/builtins/module-externals/{moduleExternals.js → rule.js} +3 -3
  54. package/dist/builtins/no-cross-module-reexport/rule.d.ts +2 -0
  55. package/dist/builtins/no-cross-module-reexport/{noCrossModuleReexport.js → rule.js} +1 -1
  56. package/dist/builtins/no-cycle/{noCycle.d.ts → rule.d.ts} +1 -1
  57. package/dist/builtins/no-double-export/rule.d.ts +2 -0
  58. package/dist/builtins/no-double-export/{noDoubleExport.js → rule.js} +1 -1
  59. package/dist/builtins/packages.d.ts +1 -1
  60. package/dist/builtins/place.d.ts +1 -1
  61. package/dist/builtins/shared.d.ts +1 -1
  62. package/dist/builtins/unclassified/rule.d.ts +2 -0
  63. package/dist/builtins/unclassified/rule.js +15 -0
  64. package/dist/builtins/unresolved-import/rule.d.ts +2 -0
  65. package/dist/builtins/unresolved-import/{unresolvedImport.js → rule.js} +1 -1
  66. package/dist/builtins/unused-declaration/declarations.d.ts +3 -3
  67. package/dist/builtins/unused-declaration/empty.d.ts +1 -1
  68. package/dist/builtins/unused-declaration/empty.js +1 -1
  69. package/dist/builtins/unused-declaration/grants.d.ts +1 -1
  70. package/dist/builtins/unused-declaration/grants.js +64 -14
  71. package/dist/builtins/unused-declaration/rule.d.ts +2 -0
  72. package/dist/builtins/unused-declaration/{unusedDeclaration.js → rule.js} +1 -1
  73. package/dist/builtins/unused-declaration/surfaces.d.ts +1 -1
  74. package/dist/builtins/unused-declaration/surfaces.js +1 -1
  75. package/dist/cli.js +51 -54
  76. package/dist/{model/archetype → domain/fixes}/fixes.d.ts +2 -2
  77. package/dist/{model/archetype → domain/fixes}/fixes.js +36 -29
  78. package/dist/domain/language/compile.d.ts +11 -0
  79. package/dist/domain/language/compile.js +58 -0
  80. package/dist/{model/archetype → domain/language}/references.d.ts +3 -6
  81. package/dist/{model/archetype → domain/language}/references.js +16 -21
  82. package/dist/{model/archetype → domain/language}/requirements.d.ts +3 -3
  83. package/dist/{model/archetype → domain/language}/requirements.js +13 -2
  84. package/dist/domain/language/rulesets.d.ts +10 -0
  85. package/dist/domain/language/rulesets.js +60 -0
  86. package/dist/{model/archetype/language.d.ts → domain/language/structure.d.ts} +4 -3
  87. package/dist/{model/archetype/language.js → domain/language/structure.js} +50 -17
  88. package/dist/{model/archetype → domain/model}/data.d.ts +10 -6
  89. package/dist/{model/archetype → domain/model}/reach.d.ts +1 -0
  90. package/dist/{model/archetype → domain/model}/reach.js +3 -7
  91. package/dist/{model/archetype → domain/model}/resolve.d.ts +2 -0
  92. package/dist/{model/archetype → domain/model}/resolve.js +9 -3
  93. package/dist/{model/archetype → domain/model}/settings.d.ts +1 -1
  94. package/dist/domain/model/settings.js +82 -0
  95. package/dist/domain/model/text.d.ts +4 -0
  96. package/dist/domain/model/text.js +13 -0
  97. package/dist/{rules → domain/rules}/registry.d.ts +1 -0
  98. package/dist/{rules → domain/rules}/registry.js +11 -1
  99. package/dist/{rules → domain/rules}/rule.d.ts +10 -4
  100. package/dist/index.d.ts +6 -6
  101. package/dist/index.js +2 -2
  102. package/package.json +2 -1
  103. package/dist/analysis/folders.d.ts +0 -2
  104. package/dist/analysis/specifiers.d.ts +0 -2
  105. package/dist/analysis/specifiers.js +0 -6
  106. package/dist/analysis/typescript.d.ts +0 -2
  107. package/dist/app/unclassified.d.ts +0 -5
  108. package/dist/app/unclassified.js +0 -13
  109. package/dist/builtins/dependency-direction/dependencyDirection.d.ts +0 -2
  110. package/dist/builtins/module-externals/moduleExternals.d.ts +0 -2
  111. package/dist/builtins/no-cross-module-reexport/noCrossModuleReexport.d.ts +0 -2
  112. package/dist/builtins/no-double-export/noDoubleExport.d.ts +0 -2
  113. package/dist/builtins/unresolved-import/unresolvedImport.d.ts +0 -2
  114. package/dist/builtins/unused-declaration/unusedDeclaration.d.ts +0 -2
  115. package/dist/config/loadConfig.d.ts +0 -13
  116. package/dist/model/archetype/rulesets.d.ts +0 -5
  117. package/dist/model/archetype/rulesets.js +0 -138
  118. package/dist/model/archetype/settings.js +0 -49
  119. /package/dist/{analysis → adapters/analysis}/complexity.js +0 -0
  120. /package/dist/{analysis → adapters/analysis}/folders.js +0 -0
  121. /package/dist/{analysis → adapters/analysis}/members.js +0 -0
  122. /package/dist/{analysis → adapters/analysis}/source.d.ts +0 -0
  123. /package/dist/{analysis → adapters/analysis}/source.js +0 -0
  124. /package/dist/{git → adapters/git}/repository.js +0 -0
  125. /package/dist/{config → adapters/git}/toolDigest.d.ts +0 -0
  126. /package/dist/{reporters → adapters/reporters}/agent.d.ts +0 -0
  127. /package/dist/{reporters → adapters/reporters}/agent.js +0 -0
  128. /package/dist/{reporters → adapters/reporters}/claudeHook.d.ts +0 -0
  129. /package/dist/{reporters → adapters/reporters}/claudeHook.js +0 -0
  130. /package/dist/{reporters → adapters/reporters}/index.d.ts +0 -0
  131. /package/dist/{reporters → adapters/reporters}/index.js +0 -0
  132. /package/dist/{reporters → adapters/reporters}/json.d.ts +0 -0
  133. /package/dist/{reporters → adapters/reporters}/json.js +0 -0
  134. /package/dist/{reporters → adapters/reporters}/model.js +0 -0
  135. /package/dist/{reporters → adapters/reporters}/omp.d.ts +0 -0
  136. /package/dist/{reporters → adapters/reporters}/omp.js +0 -0
  137. /package/dist/{reporters → adapters/reporters}/reporter.js +0 -0
  138. /package/dist/{reporters → adapters/reporters}/sarif.d.ts +0 -0
  139. /package/dist/{reporters → adapters/reporters}/sarif.js +0 -0
  140. /package/dist/{reporters → adapters/reporters}/text.js +0 -0
  141. /package/dist/builtins/module-cycle/{moduleCycle.js → rule.js} +0 -0
  142. /package/dist/builtins/no-cycle/{noCycle.js → rule.js} +0 -0
  143. /package/dist/{model → domain/facts}/facts.d.ts +0 -0
  144. /package/dist/{model → domain/facts}/facts.js +0 -0
  145. /package/dist/{model → domain/model}/configError.d.ts +0 -0
  146. /package/dist/{model → domain/model}/configError.js +0 -0
  147. /package/dist/{model/archetype → domain/model}/data.js +0 -0
  148. /package/dist/{model/archetype → domain/model}/shared.d.ts +0 -0
  149. /package/dist/{model/archetype → domain/model}/shared.js +0 -0
  150. /package/dist/{rules → domain/rules}/diff.d.ts +0 -0
  151. /package/dist/{rules → domain/rules}/diff.js +0 -0
  152. /package/dist/{rules → domain/rules}/rule.js +0 -0
package/README.md CHANGED
@@ -34,11 +34,8 @@ root:
34
34
  provides: [npm:vitest]
35
35
  modules:
36
36
  tests: { files: 'src/**/*.test.ts' }
37
-
38
- rulesets:
39
- default:
40
- extends: [warp:recommended]
41
- test: { function-cohesion: off }
37
+ ruleset: { rules: { function-cohesion: off } }
38
+ ruleset: [warp:recommended]
42
39
  ```
43
40
 
44
41
  Then check it, and after an edit, see what the edit broke:
@@ -66,7 +63,8 @@ new: src/utils/slug.ts:1 [dependency-direction] src/utils/slug.ts (root.utils sr
66
63
 
67
64
  ## Limits
68
65
 
69
- - warp follows static `import` and `export … from` declarations. Dependencies through `import()`, `require()` and
70
- `import x = require()` go unchecked.
66
+ - warp follows `import`, `export … from`, `import x = require()`, `import()`, `require()` and `import('…')` types
67
+ when the specifier is a string literal, a template literal without `${}` included. A specifier computed at runtime,
68
+ such as `import(name)` or `` import(`./${name}.ts`) ``, goes unchecked.
71
69
  - A namespace import (`import * as x`) points at the module the specifier resolves to, a barrel included.
72
70
  - Each class method is checked as a function of its own, and a class is one member of its file.
@@ -1,4 +1,4 @@
1
1
  import type { Node } from 'typescript/ast';
2
- import type { Complexity } from '../model/facts.ts';
2
+ import type { Complexity } from '../../domain/facts/facts.ts';
3
3
  import { type Source } from './source.ts';
4
4
  export declare const cognitiveComplexity: (fn: Node, self: string | undefined, source: Source) => Complexity;
@@ -0,0 +1,2 @@
1
+ import type { Folders } from '../../domain/model/resolve.ts';
2
+ export declare const diskFolders: (root: string) => Folders;
@@ -1,7 +1,6 @@
1
- import type { Cache, CachedFacts, CachedFile, FactsStore } from './ports.ts';
1
+ import type { CachedFacts, CachedFile } from '../../app/ports.ts';
2
2
  export interface CurrentFiles {
3
3
  digest: string;
4
4
  hashes: ReadonlyMap<string, string>;
5
5
  }
6
- export declare const factsStore: (cache: Cache<CachedFacts>, toolDigest: string, projectPath: string) => FactsStore;
7
6
  export declare const freshFacts: (cached: CachedFacts | undefined, current: CurrentFiles) => Map<string, CachedFile>;
@@ -1,13 +1,3 @@
1
- export const factsStore = (cache, toolDigest, projectPath) => {
2
- const key = `${toolDigest}-facts-${projectPath.replaceAll('/', '_')}`;
3
- return {
4
- read: () => cache.get(key),
5
- write(facts) {
6
- cache.set(key, facts);
7
- cache.prune((other) => other.startsWith(`${toolDigest}-`));
8
- },
9
- };
10
- };
11
1
  export const freshFacts = (cached, current) => {
12
2
  if (!cached || cached.digest !== current.digest)
13
3
  return new Map();
@@ -1,11 +1,12 @@
1
1
  import { type Checker, type Program } from 'typescript/sync';
2
- import type { ExternalImport, ImportEdge, UnresolvedImport } from '../model/facts.ts';
2
+ import type { ExternalImport, ImportEdge, UnresolvedImport } from '../../domain/facts/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
8
  exists: (fileName: string) => boolean;
9
+ requireTarget: (specifier: string, directory: string) => string | undefined;
9
10
  }
10
11
  export interface FileEdges {
11
12
  imports: ImportEdge[];
@@ -1,26 +1,29 @@
1
1
  import { SyntaxKind } from 'typescript/ast';
2
- import { isExportAssignment, isExportDeclaration, isIdentifier, isImportDeclaration, isNamedExports, isNamedImports, isNamespaceImport, isStringLiteralLikeNode, } from 'typescript/ast/is';
2
+ import { isExportAssignment, isExportDeclaration, isIdentifier, isImportDeclaration, isImportEqualsDeclaration, isNamedExports, isNamedImports, isNamespaceImport, isStringLiteralLikeNode, } from 'typescript/ast/is';
3
3
  import { SymbolFlags } from 'typescript/sync';
4
4
  import { isBuiltin } from 'node:module';
5
5
  import { dirname, resolve } from 'node:path';
6
+ import { inlineReferences, statementSpecifier } from './specifiers.js';
6
7
  export const fileEdges = (source, resolver) => {
7
- const exported = locallyExportedNames(source.sourceFile);
8
8
  const edges = { imports: [], externals: [], unresolved: [] };
9
- for (const statement of source.sourceFile.statements) {
10
- const declaration = moduleDeclaration(statement, exported);
11
- if (!declaration)
12
- continue;
13
- const resolved = resolver.program.getResolvedModuleFromModuleSpecifier(declaration.specifier, source.sourceFile.fileName);
14
- const via = resolved?.resolvedFileName ? resolver.relative(resolved.resolvedFileName) : undefined;
9
+ for (const reference of moduleReferences(source.sourceFile)) {
10
+ const { specifier } = reference;
11
+ const resolvedFileName = resolvedTarget(reference, source, resolver);
12
+ const via = resolvedFileName ? resolver.relative(resolvedFileName) : undefined;
15
13
  if (via)
16
- edges.imports.push(...statementEdges(statement, declaration, via, source, resolver));
17
- else if (isBare(declaration.specifier.text))
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) });
14
+ edges.imports.push(...referenceEdges(reference, via, source, resolver));
15
+ else if (isBare(specifier.text))
16
+ edges.externals.push(externalImport(reference, source));
17
+ else if (!resolvedFileName && !namesFileOnDisk(specifier.text, source, resolver))
18
+ edges.unresolved.push({ from: source.file, specifier: specifier.text, line: source.line(reference.node) });
21
19
  }
22
20
  return edges;
23
21
  };
22
+ const resolvedTarget = (reference, source, resolver) => {
23
+ const { fileName } = source.sourceFile;
24
+ const resolved = resolver.program.getResolvedModuleFromModuleSpecifier(reference.specifier, fileName)?.resolvedFileName;
25
+ return (resolved ?? (reference.require ? resolver.requireTarget(reference.specifier.text, dirname(fileName)) : undefined));
26
+ };
24
27
  const namesFileOnDisk = (specifier, source, resolver) => resolver.exists(resolve(dirname(source.sourceFile.fileName), specifier));
25
28
  const isBare = (specifier) => !specifier.startsWith('.') && !specifier.startsWith('/');
26
29
  const packageOf = (specifier) => {
@@ -30,7 +33,7 @@ const packageOf = (specifier) => {
30
33
  const [name] = segments;
31
34
  return !name.includes(':') && isBuiltin(name) ? `node:${name}` : name;
32
35
  };
33
- const externalImport = (statement, declaration, source) => {
36
+ const externalImport = (declaration, source) => {
34
37
  const reExport = declaration.reExport || declaration.bindings.some((binding) => binding.reExport);
35
38
  return {
36
39
  from: source.file,
@@ -40,10 +43,10 @@ const externalImport = (statement, declaration, source) => {
40
43
  typeOnly: declaration.typeOnly ||
41
44
  (declaration.bindings.length > 0 && declaration.bindings.every((binding) => binding.typeOnly)),
42
45
  ...(reExport ? { reExport } : {}),
43
- line: source.line(statement),
46
+ line: source.line(declaration.node),
44
47
  };
45
48
  };
46
- const statementEdges = (statement, declaration, via, source, resolver) => {
49
+ const referenceEdges = (declaration, via, source, resolver) => {
47
50
  const edge = (to, names, typeOnly, reExport) => ({
48
51
  from: source.file,
49
52
  to,
@@ -52,7 +55,7 @@ const statementEdges = (statement, declaration, via, source, resolver) => {
52
55
  names,
53
56
  typeOnly,
54
57
  ...(reExport ? { reExport } : {}),
55
- line: source.line(statement),
58
+ line: source.line(declaration.node),
56
59
  });
57
60
  if (declaration.bindings.length === 0)
58
61
  return [edge(via, [], declaration.typeOnly, declaration.reExport)];
@@ -67,11 +70,29 @@ const statementEdges = (statement, declaration, via, source, resolver) => {
67
70
  }
68
71
  return [...byTarget.values()].map(({ to, names, typeOnly, reExport }) => edge(to, names, typeOnly, reExport));
69
72
  };
73
+ const moduleReferences = (sourceFile) => {
74
+ const exported = locallyExportedNames(sourceFile);
75
+ const statements = sourceFile.statements.flatMap((statement) => {
76
+ const declaration = moduleDeclaration(statement, exported);
77
+ return declaration ? [{ ...declaration, node: statement, require: false }] : [];
78
+ });
79
+ const inline = inlineReferences(sourceFile).map(({ node, specifier, typeOnly, require }) => ({
80
+ node,
81
+ specifier,
82
+ typeOnly,
83
+ require,
84
+ reExport: false,
85
+ bindings: [],
86
+ }));
87
+ return [...statements, ...inline];
88
+ };
70
89
  const moduleDeclaration = (statement, exported) => isImportDeclaration(statement)
71
90
  ? importStatement(statement, exported)
72
91
  : isExportDeclaration(statement)
73
92
  ? reExportStatement(statement)
74
- : undefined;
93
+ : isImportEqualsDeclaration(statement)
94
+ ? importEqualsStatement(statement, exported)
95
+ : undefined;
75
96
  const locallyExportedNames = (sourceFile) => {
76
97
  const names = new Set();
77
98
  for (const statement of sourceFile.statements) {
@@ -115,6 +136,19 @@ const importStatement = (statement, exported) => {
115
136
  bindings,
116
137
  };
117
138
  };
139
+ const importEqualsStatement = (statement, exported) => {
140
+ const specifier = statementSpecifier(statement);
141
+ if (!specifier || !isIdentifier(statement.name))
142
+ return undefined;
143
+ const reExport = exported.has(statement.name.text) ||
144
+ (statement.modifiers?.some((modifier) => modifier.kind === SyntaxKind.ExportKeyword) ?? false);
145
+ return {
146
+ specifier,
147
+ typeOnly: statement.isTypeOnly,
148
+ reExport: false,
149
+ bindings: [{ identifier: statement.name, typeOnly: false, reExport }],
150
+ };
151
+ };
118
152
  const reExportStatement = (statement) => {
119
153
  if (!statement.moduleSpecifier || !isStringLiteralLikeNode(statement.moduleSpecifier))
120
154
  return undefined;
@@ -1,4 +1,4 @@
1
- import type { FunctionFacts, MemberGraph } from '../model/facts.ts';
1
+ import type { FunctionFacts, MemberGraph } from '../../domain/facts/facts.ts';
2
2
  import { type Source } from './source.ts';
3
3
  export declare const fileMembers: (source: Source) => MemberGraph;
4
4
  export declare const functionFacts: (source: Source) => FunctionFacts[];
@@ -0,0 +1,10 @@
1
+ import type { Node, SourceFile, StringLiteralLikeNode } from 'typescript/ast';
2
+ export interface InlineReference {
3
+ node: Node;
4
+ specifier: StringLiteralLikeNode;
5
+ typeOnly: boolean;
6
+ require: boolean;
7
+ }
8
+ export declare const inlineReferences: (sourceFile: SourceFile) => InlineReference[];
9
+ export declare const statementSpecifier: (node: Node) => StringLiteralLikeNode | undefined;
10
+ export declare const moduleSpecifiers: (sourceFile: SourceFile) => string[];
@@ -0,0 +1,39 @@
1
+ import { SyntaxKind } from 'typescript/ast';
2
+ import { isCallExpression, isExportDeclaration, isExternalModuleReference, isIdentifier, isImportDeclaration, isImportEqualsDeclaration, isImportTypeNode, isLiteralTypeNode, isStringLiteralLikeNode, } from 'typescript/ast/is';
3
+ import { walk } from './source.js';
4
+ export const inlineReferences = (sourceFile) => {
5
+ const found = [];
6
+ walk(sourceFile, (node) => {
7
+ const reference = inlineReference(node);
8
+ if (reference)
9
+ found.push(reference);
10
+ });
11
+ return found;
12
+ };
13
+ const inlineReference = (node) => {
14
+ if (isImportTypeNode(node))
15
+ return isLiteralTypeNode(node.argument) && isStringLiteralLikeNode(node.argument.literal)
16
+ ? { node, specifier: node.argument.literal, typeOnly: true, require: false }
17
+ : undefined;
18
+ if (!isCallExpression(node))
19
+ return undefined;
20
+ const [specifier] = node.arguments;
21
+ if (!specifier || !isStringLiteralLikeNode(specifier))
22
+ return undefined;
23
+ if (node.expression.kind === SyntaxKind.ImportKeyword)
24
+ return { node, specifier, typeOnly: false, require: false };
25
+ const isRequire = isIdentifier(node.expression) && node.expression.text === 'require' && node.arguments.length === 1;
26
+ return isRequire ? { node, specifier, typeOnly: false, require: true } : undefined;
27
+ };
28
+ export const statementSpecifier = (node) => {
29
+ const specifier = isImportDeclaration(node) || isExportDeclaration(node)
30
+ ? node.moduleSpecifier
31
+ : isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference)
32
+ ? node.moduleReference.expression
33
+ : undefined;
34
+ return specifier && isStringLiteralLikeNode(specifier) ? specifier : undefined;
35
+ };
36
+ export const moduleSpecifiers = (sourceFile) => [
37
+ ...sourceFile.statements.flatMap((statement) => statementSpecifier(statement)?.text ?? []),
38
+ ...inlineReferences(sourceFile).map((reference) => reference.specifier.text),
39
+ ];
@@ -0,0 +1,2 @@
1
+ import type { Analyzer } from '../../app/ports.ts';
2
+ export declare const typescriptAnalyzer: Analyzer;
@@ -1,8 +1,8 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { existsSync, readFileSync, statSync } from 'node:fs';
3
3
  import { join, relative, sep } from 'node:path';
4
- import { API } from 'typescript/sync';
5
- import { freshFacts } from '../app/facts.js';
4
+ import { API, ModuleKind } from 'typescript/sync';
5
+ import { freshFacts } from './freshFacts.js';
6
6
  import { fileEdges } from './imports.js';
7
7
  import { moduleSpecifiers } from './specifiers.js';
8
8
  import { countLines, readSource } from './source.js';
@@ -24,7 +24,7 @@ export const typescriptAnalyzer = {
24
24
  const fresh = freshFacts(store?.read(), { digest, hashes });
25
25
  const cached = new Map();
26
26
  for (const { project, files } of projects)
27
- for (const [file, entry] of analyzeProgram(project, files, fresh, cached))
27
+ for (const [file, entry] of analyzeProgram(api, project, files, fresh, cached))
28
28
  cached.set(file, entry);
29
29
  const facts = [...cached.values()].flatMap(({ facts }) => (facts ? [facts] : []));
30
30
  if (facts.length === 0)
@@ -65,16 +65,22 @@ const digestOf = (root, projects) => {
65
65
  }
66
66
  return digest.digest('hex').slice(0, 16);
67
67
  };
68
- const analyzeProgram = ({ program, checker }, files, fresh, done) => {
68
+ const analyzeProgram = (api, { program, checker }, files, fresh, done) => {
69
69
  const byPath = new Map([...files].flatMap(([fileName, file]) => [
70
70
  [fileName, file],
71
71
  [fileName.toLowerCase(), file],
72
72
  ]));
73
+ let moduleResolver;
73
74
  const resolver = {
74
75
  program,
75
76
  checker,
76
77
  relative: (path) => byPath.get(path) ?? byPath.get(path.toLowerCase()),
77
78
  exists: existsSync,
79
+ requireTarget: (specifier, directory) => {
80
+ moduleResolver ??= api.createModuleResolver(program.getCompilerOptions());
81
+ return moduleResolver.resolveModuleName(specifier, directory, ModuleKind.CommonJS).resolvedModule
82
+ ?.resolvedFileName;
83
+ },
78
84
  };
79
85
  const analyzed = new Map();
80
86
  for (const [fileName, file] of files) {
@@ -0,0 +1,8 @@
1
+ import type { ConfigSource } from '../../app/ports.ts';
2
+ export declare const configName = "warp.yaml";
3
+ export declare const findConfig: (start: string, exists?: (path: string) => boolean) => string;
4
+ export declare const parseConfig: (text: string, file: string) => {
5
+ raw: unknown;
6
+ lines: Map<string, number>;
7
+ };
8
+ export declare const yamlConfig: (file: string) => ConfigSource;
@@ -18,23 +18,29 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
18
18
  import { createHash } from 'node:crypto';
19
19
  import { existsSync, readFileSync } from 'node:fs';
20
20
  import { createRequire, registerHooks } from 'node:module';
21
- import { dirname, join, resolve } from 'node:path';
21
+ import { basename, dirname, join, resolve } from 'node:path';
22
22
  import { pathToFileURL } from 'node:url';
23
23
  import { isAlias, isMap, isNode, isPair, isScalar, parseDocument, visit } from 'yaml';
24
- import { ConfigError } from '../model/configError.js';
24
+ import { ConfigError } from '../../domain/model/configError.js';
25
25
  export const configName = 'warp.yaml';
26
- export const findConfig = (dir) => {
27
- const found = join(dir, configName);
28
- if (!existsSync(found))
29
- throw new ConfigError(`no config in ${dir}: add a ${configName}`);
30
- return found;
26
+ export const findConfig = (start, exists = existsSync) => {
27
+ for (let dir = start;; dir = dirname(dir)) {
28
+ const found = join(dir, configName);
29
+ if (exists(found))
30
+ return found;
31
+ if (dirname(dir) === dir)
32
+ throw new ConfigError(`no ${configName} in ${start} or any folder above it`);
33
+ }
31
34
  };
32
35
  export const parseConfig = (text, file) => {
33
36
  const doc = parseDocument(text, { version: '1.2', merge: false, uniqueKeys: true });
34
37
  const lineOf = (offset) => text.slice(0, offset).split('\n').length;
38
+ const unquoted = doc.errors.filter((error) => error.code === 'BAD_ALIAS' && text[error.pos[0]] === '*');
35
39
  const problems = [
36
- ...doc.errors.map((error) => `${file}:${lineOf(error.pos[0])}: ${firstLine(error.message)}`),
37
- ...anchors(doc).map((offset) => `${file}:${lineOf(offset)}: anchors and aliases are not part of warp.yaml; write it out`),
40
+ ...doc.errors.map((error) => `${file}:${lineOf(error.pos[0])}: ${yamlProblem(error, text, unquoted)}`),
41
+ ...anchors(doc)
42
+ .filter((offset) => !unquoted.some((error) => error.pos[0] === offset))
43
+ .map((offset) => `${file}:${lineOf(offset)}: anchors and aliases are not part of warp.yaml; write it out`),
38
44
  ];
39
45
  if (problems.length > 0)
40
46
  throw new ConfigError(problems.join('\n'));
@@ -54,6 +60,13 @@ export const parseConfig = (text, file) => {
54
60
  walk(doc.contents, top);
55
61
  return { raw: doc.toJS() ?? {}, lines };
56
62
  };
63
+ const yamlProblem = (error, text, unquoted) => {
64
+ if (unquoted.includes(error))
65
+ return "a value that starts with * is quoted, '*'";
66
+ if (error.code !== 'DUPLICATE_KEY')
67
+ return firstLine(error.message);
68
+ return `${firstLine(error.message)} (${/^['"]?([^'":\n]*)/.exec(text.slice(error.pos[0]))[1]})`;
69
+ };
57
70
  const firstLine = (message) => message.split('\n')[0].replace(/ at line \d+, column \d+:?$/, '');
58
71
  const anchors = (doc) => {
59
72
  const offsets = [];
@@ -69,12 +82,14 @@ const plain = (path) => (key) => ({ path: `${path}.${key}`, inside: plain(`${pat
69
82
  const moduleAt = (path) => ({ path, inside: moduleKey(path) });
70
83
  const moduleKey = (path) => (key) => {
71
84
  if (key === 'modules')
72
- return { inside: (child) => moduleAt(`${path}.${child}`) };
85
+ return { path: `${path}.modules`, inside: (child) => moduleAt(`${path}.${child}`) };
73
86
  if (key === 'test')
74
87
  return { path: `${path}.test`, inside: testKey(path) };
75
88
  return plain(path)(key);
76
89
  };
77
- const testKey = (path) => (key) => key === 'modules' ? { inside: (child) => moduleAt(`${path}.${child}`) } : plain(`${path}.test`)(key);
90
+ const testKey = (path) => (key) => key === 'modules'
91
+ ? { path: `${path}.test.modules`, inside: (child) => moduleAt(`${path}.${child}`) }
92
+ : plain(`${path}.test`)(key);
78
93
  const top = (key) => {
79
94
  if (key === 'root')
80
95
  return moduleAt('root');
@@ -82,12 +97,14 @@ const top = (key) => {
82
97
  return { inside: moduleAt };
83
98
  return { path: key, inside: plain(key) };
84
99
  };
85
- const entry = new URL(import.meta.url.endsWith('.ts') ? '../index.ts' : '../index.js', import.meta.url).href;
86
- const ownFiles = new URL('../../', import.meta.url).href;
87
- export const loadConfig = async (file) => {
100
+ const entry = new URL(import.meta.url.endsWith('.ts') ? '../../index.ts' : '../../index.js', import.meta.url).href;
101
+ const ownFiles = new URL('../../../', import.meta.url).href;
102
+ export const yamlConfig = (file) => ({ file: basename(file), read: () => readConfig(file) });
103
+ const readConfig = async (file) => {
88
104
  const text = readFileSync(file, 'utf8');
89
105
  const digest = createHash('sha256').update(text);
90
- const { raw, lines } = parseConfig(text, file);
106
+ const name = basename(file);
107
+ const { raw, lines } = parseConfig(text, name);
91
108
  const declared = raw.plugins;
92
109
  const specs = declared && typeof declared === 'object' && !Array.isArray(declared) ? Object.entries(declared) : [];
93
110
  const hooks = registerHooks({
@@ -104,10 +121,7 @@ export const loadConfig = async (file) => {
104
121
  for (const [namespace, spec] of specs) {
105
122
  if (typeof spec !== 'string')
106
123
  continue;
107
- const module = await import(__rewriteRelativeImportExtension(pathToFileURL(pluginPath(file, spec)).href));
108
- if (module.default === undefined)
109
- throw new ConfigError(`${file}:${lines.get(`plugins.${namespace}`) ?? 1}: plugins.${namespace}: ${spec} has no default export; export the plugin as default`);
110
- plugins[namespace] = module.default;
124
+ plugins[namespace] = await importPlugin(file, spec, `${name}:${lines.get(`plugins.${namespace}`) ?? 1}: plugins.${namespace}`);
111
125
  }
112
126
  return { raw, plugins, lines, digest: digest.digest('hex') };
113
127
  }
@@ -115,10 +129,19 @@ export const loadConfig = async (file) => {
115
129
  hooks.deregister();
116
130
  }
117
131
  };
118
- const pluginPath = (file, spec) => {
132
+ const importPlugin = async (file, spec, at) => {
133
+ const path = pluginPath(file, spec, at);
134
+ if (!spec.startsWith('npm:') && !existsSync(path))
135
+ throw new ConfigError(`${at}: no file at ${spec}`);
136
+ const module = await import(__rewriteRelativeImportExtension(pathToFileURL(path).href));
137
+ if (module.default === undefined)
138
+ throw new ConfigError(`${at}: ${spec} has no default export; export the plugin as default`);
139
+ return module.default;
140
+ };
141
+ const pluginPath = (file, spec, at) => {
119
142
  if (spec.startsWith('npm:'))
120
143
  return createRequire(file).resolve(spec.slice(4));
121
144
  if (spec.startsWith('./') || spec.startsWith('../'))
122
145
  return resolve(dirname(file), spec);
123
- throw new ConfigError(`${file}: plugin '${spec}': name a path, ./rules/x.ts, or a package, npm:x`);
146
+ throw new ConfigError(`${at}: '${spec}' is a path, ./${spec}, or a package, npm:${spec}`);
124
147
  };
@@ -1,3 +1,3 @@
1
- import type { Cache } from '../app/ports.ts';
1
+ import type { Cache } from '../../app/ports.ts';
2
2
  export declare const maxAgeMs: number;
3
3
  export declare const gitDirCache: <T>(projectRoot: string, now?: () => number) => Cache<T>;
@@ -3,7 +3,11 @@ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, uti
3
3
  import { join, resolve } from 'node:path';
4
4
  export const maxAgeMs = 30 * 24 * 60 * 60 * 1000;
5
5
  export const gitDirCache = (projectRoot, now = Date.now) => {
6
- const gitDir = execFileSync('git', ['rev-parse', '--git-common-dir'], { cwd: projectRoot, encoding: 'utf8' }).trim();
6
+ const gitDir = execFileSync('git', ['rev-parse', '--git-common-dir'], {
7
+ cwd: projectRoot,
8
+ encoding: 'utf8',
9
+ stdio: ['ignore', 'pipe', 'pipe'],
10
+ }).trim();
7
11
  const dir = join(resolve(projectRoot, gitDir), 'warp-cache');
8
12
  const file = (key) => join(dir, `${key}.json`);
9
13
  const touch = (key) => {
@@ -0,0 +1,2 @@
1
+ import type { Cache, CachedFacts, FactsStore } from '../../app/ports.ts';
2
+ export declare const factsStore: (cache: Cache<CachedFacts>, toolDigest: string, projectPath: string) => FactsStore;
@@ -0,0 +1,10 @@
1
+ export const factsStore = (cache, toolDigest, projectPath) => {
2
+ const key = `${toolDigest}-facts-${projectPath.replaceAll('/', '_')}`;
3
+ return {
4
+ read: () => cache.get(key),
5
+ write(facts) {
6
+ cache.set(key, facts);
7
+ cache.prune((other) => other.startsWith(`${toolDigest}-`));
8
+ },
9
+ };
10
+ };
@@ -1,3 +1,3 @@
1
- import type { Repository } from '../app/ports.ts';
1
+ import type { Repository } from '../../app/ports.ts';
2
2
  export declare const gitRepository: (projectRoot: string) => Repository;
3
3
  export declare const projectPathOf: (projectRoot: string) => string;
@@ -3,7 +3,7 @@ import { readdirSync, readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
- const sourceDir = fileURLToPath(new URL('../', import.meta.url));
6
+ const sourceDir = fileURLToPath(new URL('../../', import.meta.url));
7
7
  const code = /(?<!\.test)\.(ts|js)$/;
8
8
  export const toolDigest = () => {
9
9
  const digest = createHash('sha256').update(createRequire(import.meta.url)('typescript/package.json').version);
@@ -1,4 +1,4 @@
1
- import type { Model } from '../model/archetype/resolve.ts';
2
- import type { RulesOf } from '../model/archetype/settings.ts';
1
+ import type { Model } from '../../domain/model/resolve.ts';
2
+ import type { RulesOf } from '../../domain/model/settings.ts';
3
3
  export declare const modelText: (model: Model, rules?: RulesOf) => string;
4
4
  export declare const modelJson: (model: Model, rules?: RulesOf) => string;
@@ -1,5 +1,5 @@
1
- import type { Delta } from '../rules/diff.ts';
2
- import type { Finding } from '../rules/rule.ts';
1
+ import type { Delta } from '../../domain/rules/diff.ts';
2
+ import type { Finding } from '../../domain/rules/rule.ts';
3
3
  export type Report = {
4
4
  mode: 'check';
5
5
  findings: Finding[];
@@ -1,5 +1,5 @@
1
- import type { Delta } from '../rules/diff.ts';
2
- import type { Finding } from '../rules/rule.ts';
1
+ import type { Delta } from '../../domain/rules/diff.ts';
2
+ import type { Finding } from '../../domain/rules/rule.ts';
3
3
  import type { Reporter } from './reporter.ts';
4
4
  export declare const textReporter: Reporter;
5
5
  export declare const diffText: (delta: Delta) => string;
@@ -1,8 +1,8 @@
1
- import type { ConfigData } from '../model/archetype/data.ts';
1
+ import type { ConfigData } from '../domain/model/data.ts';
2
2
  import { type ConfigLines } from './configLines.ts';
3
- import { type Model } from '../model/archetype/resolve.ts';
4
- import type { Project } from '../model/facts.ts';
5
- import type { Finding, Rule } from '../rules/rule.ts';
3
+ import { type Model } from '../domain/model/resolve.ts';
4
+ import type { Project } from '../domain/facts/facts.ts';
5
+ import type { Finding, Rule } from '../domain/rules/rule.ts';
6
6
  import type { Analyzer, FactsStore, FoldersAt } from './ports.ts';
7
7
  export interface ProjectCheck {
8
8
  config: unknown;
@@ -18,8 +18,7 @@ export declare const modelProject: ({ analyzer, foldersAt, facts }: Adapters, ro
18
18
  model: Model;
19
19
  project: Project;
20
20
  };
21
- export declare const projectCheck: (adapters: Adapters, config: ConfigData, { rules, unclassifiedDocs, lines, }?: {
21
+ export declare const projectCheck: (adapters: Adapters, config: ConfigData, { rules, lines }?: {
22
22
  rules?: readonly Rule[];
23
- unclassifiedDocs?: string;
24
23
  lines?: ConfigLines;
25
24
  }) => ProjectCheck;
package/dist/app/check.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import { checkModel } from './checkModel.js';
2
2
  import { placeFindings } from './configLines.js';
3
- import { resolveModel } from '../model/archetype/resolve.js';
3
+ import { resolveModel } from '../domain/model/resolve.js';
4
4
  export const modelProject = ({ analyzer, foldersAt, facts }, root, config) => {
5
5
  const analyzed = analyzer.analyze(root, config.tsconfig, facts);
6
6
  const project = { files: analyzed.files.filter((file) => file.path !== config.file) };
7
7
  const files = project.files.map((file) => file.path);
8
8
  return { model: resolveModel(config, foldersAt(root), files), project };
9
9
  };
10
- export const projectCheck = (adapters, config, { rules = [], unclassifiedDocs, lines = new Map(), } = {}) => ({
10
+ export const projectCheck = (adapters, config, { rules = [], lines = new Map() } = {}) => ({
11
11
  config,
12
12
  requiredFile: config.tsconfig[0],
13
13
  check: (root) => {
14
14
  const { model, project } = modelProject(adapters, root, config);
15
- return placeFindings(lines, config.file, checkModel(config, model, project, rules, unclassifiedDocs));
15
+ return placeFindings(lines, config.file, checkModel(config, model, project, rules));
16
16
  },
17
17
  });
@@ -1,5 +1,5 @@
1
- import type { Project } from '../model/facts.ts';
2
- import type { Rule, Finding } from '../rules/rule.ts';
3
- import type { ConfigData } from '../model/archetype/data.ts';
4
- import type { Model } from '../model/archetype/resolve.ts';
5
- export declare const checkModel: (config: ConfigData, model: Model, project: Project, rules?: readonly Rule[], unclassifiedDocs?: string) => Finding[];
1
+ import type { Project } from '../domain/facts/facts.ts';
2
+ import type { Rule, Finding } from '../domain/rules/rule.ts';
3
+ import type { ConfigData } from '../domain/model/data.ts';
4
+ import type { Model } from '../domain/model/resolve.ts';
5
+ export declare const checkModel: (config: ConfigData, model: Model, project: Project, rules?: readonly Rule[]) => Finding[];
@@ -1,14 +1,13 @@
1
- import { verdicts } from '../model/archetype/reach.js';
2
- import { settings } from '../model/archetype/settings.js';
3
- import { unclassifiedFindings } from './unclassified.js';
4
- export const checkModel = (config, model, project, rules = [], unclassifiedDocs) => {
1
+ import { verdicts } from '../domain/model/reach.js';
2
+ import { settings } from '../domain/model/settings.js';
3
+ export const checkModel = (config, model, project, rules = []) => {
5
4
  const settled = settings(config, model);
6
5
  const judged = verdicts(config, model);
7
6
  const found = rules.flatMap((rule) => {
8
7
  const findings = run(rule, { project, config, model, verdicts: judged }, settled);
9
8
  return rule.docs ? findings.map((finding) => ({ ...finding, docs: rule.docs })) : findings;
10
9
  });
11
- return [...unclassifiedFindings(model, settled, unclassifiedDocs), ...found].map((finding) => placed(model, finding));
10
+ return found.map((finding) => placed(model, finding));
12
11
  };
13
12
  const placed = (model, finding) => {
14
13
  const module = model.moduleOf(finding.file);
@@ -1,4 +1,4 @@
1
- import type { Finding } from '../rules/rule.ts';
1
+ import type { Finding } from '../domain/rules/rule.ts';
2
2
  export type ConfigLines = ReadonlyMap<string, number>;
3
3
  export declare const lineAt: (lines: ConfigLines, text: string) => number | undefined;
4
4
  export declare const placeProblems: (lines: ConfigLines, file: string, message: string) => string;
@@ -1,4 +1,4 @@
1
- import { type Delta } from '../rules/diff.ts';
1
+ import { type Delta } from '../domain/rules/diff.ts';
2
2
  import type { ProjectCheck } from './check.ts';
3
3
  import type { FindingsCache, Repository } from './ports.ts';
4
4
  export interface Range {
package/dist/app/diff.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { anchorAtChange, diff } from '../rules/diff.js';
2
+ import { anchorAtChange, diff } from '../domain/rules/diff.js';
3
3
  export class InvalidRange extends Error {
4
4
  }
5
5
  export const parseRange = (range) => {
@@ -0,0 +1,6 @@
1
+ import type { Cache } from './ports.ts';
2
+ export interface Failures {
3
+ isNew(problem: string): boolean;
4
+ forget(): void;
5
+ }
6
+ export declare const failures: (cache: Cache<string> | undefined, toolDigest: string) => Failures;