loadwise 0.5.1 → 0.6.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 (132) hide show
  1. package/PERFORMANCE.md +31 -6
  2. package/README.md +580 -1024
  3. package/bin/loadwise.js +4 -0
  4. package/lib/accessibility/frontend-detect.js +2 -1
  5. package/lib/accessibility/rule-ids.js +12 -9
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +9 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +6 -0
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +25 -17
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ // Which files of a workspace folder feed the checkers, and so which changes trigger a rescan.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { dismissalsPath } from './dismissals.js';
5
+ import { isNamedConfigFile } from '../security/files/index.js';
6
+ const sourceSuffixes = new Set('js jsx ts tsx mjs mts cjs cts py go java cs rs rb php kt kts c h cc cpp cxx hpp hh hxx'.split(' '));
7
+ const polyglotSuffixes = new Set(['py', 'go', 'java', 'cs', 'rs']);
8
+ // Templates outside the TypeScript program, which the accessibility checker reads on its own.
9
+ const markupSuffixes = new Set(['html', 'htm', 'vue', 'svelte']);
10
+ const ignoredFolders = new Set('.git node_modules dist build coverage .next .nuxt .venv venv __pycache__ target vendor'.split(' '));
11
+ // Inputs besides source files that change findings. A change restarts the incremental watcher as
12
+ // well.
13
+ const configPatterns = [
14
+ /^schema\.prisma$/,
15
+ /^package\.json$/,
16
+ /^tsconfig.*\.json$/,
17
+ /^jsconfig.*\.json$/,
18
+ /^loadwise\.config\.json$/,
19
+ /\.sql$/,
20
+ ];
21
+ /** The globs the server asks the editor to watch. */
22
+ const watchedGlobs = [
23
+ '**/*.{' + [...sourceSuffixes, ...markupSuffixes].join(',') + '}',
24
+ '**/schema.prisma',
25
+ '**/*.sql',
26
+ '**/migrations/**',
27
+ '**/package.json',
28
+ '**/tsconfig*.json',
29
+ '**/jsconfig*.json',
30
+ '**/loadwise.config.json',
31
+ // The files the security checker reads without a source config: env files, Dockerfiles and Compose files.
32
+ '**/.env*',
33
+ '**/*{Dockerfile,dockerfile}*',
34
+ '**/*compose*.{yml,yaml}',
35
+ '**/' + dismissalsPath.split(path.sep).join('/'),
36
+ ];
37
+ function suffixOf(filename) {
38
+ return path.extname(filename).slice(1).toLowerCase();
39
+ }
40
+ // `project` is the folder's loadwise.project setting, which can name a config of any file name.
41
+ function classifyChange(root, filename, project = '') {
42
+ const relative = path.relative(root, filename);
43
+ if (relative === dismissalsPath)
44
+ return 'dismissals';
45
+ if (project.trim() && path.relative(path.resolve(root, project.trim()), filename) === '')
46
+ return 'config';
47
+ const segments = relative.split(path.sep);
48
+ if (segments.some((segment) => ignoredFolders.has(segment)))
49
+ return 'ignored';
50
+ const name = path.basename(filename);
51
+ if (configPatterns.some((pattern) => pattern.test(name)) || segments.slice(0, -1).includes('migrations'))
52
+ return 'config';
53
+ const suffix = suffixOf(filename);
54
+ if (sourceSuffixes.has(suffix) || markupSuffixes.has(suffix))
55
+ return 'source';
56
+ return isNamedConfigFile(filename) ? 'source' : 'ignored';
57
+ }
58
+ // Breadth first, so a match near the root ends the walk early.
59
+ async function hasFileWithSuffix(root, suffixes) {
60
+ const pending = [root];
61
+ for (let index = 0; index < pending.length; index++) {
62
+ let entries;
63
+ try {
64
+ entries = await fs.readdir(pending[index], { withFileTypes: true });
65
+ }
66
+ catch {
67
+ continue;
68
+ }
69
+ for (const entry of entries) {
70
+ if (entry.isFile() && suffixes.has(suffixOf(entry.name)))
71
+ return true;
72
+ if (entry.isDirectory() && !ignoredFolders.has(entry.name))
73
+ pending.push(path.join(pending[index], entry.name));
74
+ }
75
+ }
76
+ return false;
77
+ }
78
+ export { classifyChange, hasFileWithSuffix, markupSuffixes, polyglotSuffixes, sourceSuffixes, watchedGlobs };
@@ -0,0 +1,22 @@
1
+ // Whether a path stays inside a workspace folder. Reads only need the lexical check; anything the
2
+ // server writes, or asks the editor to write, also resolves symbolic links, so a link inside the
3
+ // folder cannot send the write elsewhere.
4
+ import path from 'node:path';
5
+ import { realTarget } from '../shared/real-target.js';
6
+ function isInside(root, filename) {
7
+ const relative = path.relative(root, filename);
8
+ return relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative));
9
+ }
10
+ /** Whether `filename`, with every link on its path resolved, is inside the real folder `root`. */
11
+ function isRealPathInside(root, filename) {
12
+ if (!isInside(root, filename))
13
+ return false;
14
+ try {
15
+ return isInside(realTarget(root), realTarget(filename));
16
+ }
17
+ catch {
18
+ // A link loop or an unreadable folder: the target cannot be shown to stay inside.
19
+ return false;
20
+ }
21
+ }
22
+ export { isInside, isRealPathInside };
@@ -11,6 +11,7 @@ import { sourceFacts } from './source-facts.js';
11
11
  import { checkUnusedBindings } from './unused-bindings.js';
12
12
  import { checkStrayConsole } from './stray-console.js';
13
13
  import { checkDeprecatedApis } from './deprecated-apis.js';
14
+ import { checkTypeSafetyHygiene } from './type-safety-hygiene.js';
14
15
  const READ_CONCURRENCY = 64;
15
16
  // Synchronous opens are slow on Windows; overlapping them hides most of that latency.
16
17
  async function readSourceFiles(root, files) {
@@ -83,6 +84,7 @@ function analyzeSource(root, file, text, resolve, options = {}) {
83
84
  ...checkUnusedBindings(source, file, compilerOptions ?? {}),
84
85
  ...checkStrayConsole(source, file, compilerOptions ?? {}),
85
86
  ...checkDeprecatedApis(source, file),
87
+ ...checkTypeSafetyHygiene(source, file),
86
88
  ],
87
89
  edges: collectEdges(source, file, resolve, compilerOptions),
88
90
  constEnums: exportedConstEnums(source),
@@ -1,7 +1,7 @@
1
1
  // Applies a site fix to file text. A fix stores the exact original lines, so it is applied only
2
2
  // where those lines still exist; an edit made since the scan moves or removes them and the fix then
3
3
  // refuses instead of guessing.
4
- import { isChangeApplied, locateChange } from '../../editor/apply-fix.cjs';
4
+ import { isChangeApplied, locateChange } from '../editor/apply-fix.js';
5
5
  function splitLines(text) {
6
6
  return text.split(/\r?\n/);
7
7
  }
@@ -15,7 +15,7 @@ import { readChangedRanges, filterToChangedLines } from './changed-lines.js';
15
15
  import { enableCompileCache } from 'node:module';
16
16
  import { assignFindingIds } from './finding-ids.js';
17
17
  import { findingReason, groupByReason } from '../shared/reason-groups.js';
18
- import { notifyEditor } from './notify-editor.js';
18
+ import { notifyEditor } from '../shared/notify-editor.js';
19
19
  const help = `Usage:
20
20
  loadwise maint [directory] [--config policy.json] [--loadwise-config loadwise.config.json] [--workspace name|path ...] [--ignore rule-id] [--json | --format text|json|sarif|github] [--include-contextual] [--fail-on contract|all] [--min-impact low|medium|high|critical] [--baseline [file] | --write-baseline [file]]
21
21
  loadwise maint [directory] [--config policy.json] [--include-contextual] --fix [--yes | --only id,...] [--no-comments] [--no-format]
@@ -1,35 +1,39 @@
1
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
1
2
  const examples = {
2
- 'unused-import': {
3
- before: ["import { readFile, writeFile } from 'node:fs/promises';", 'await writeFile(path, text);'],
4
- after: ["import { writeFile } from 'node:fs/promises';", 'await writeFile(path, text);'],
3
+ 'data-access-boundary': {
4
+ before: ['// src/http/handler.ts', 'import { Pool } from "pg";', 'const rows = await new Pool().query(sql);'],
5
+ after: ['// src/http/handler.ts', 'import { loadUsers } from "../data/users";', 'const rows = await loadUsers();'],
5
6
  },
6
- 'unused-local-variable': {
7
- before: [
8
- 'function total(items) {',
9
- " const label = 'sum';",
10
- ' return items.reduce((sum, item) => sum + item, 0);',
11
- '}',
12
- ],
13
- after: ['function total(items) {', ' return items.reduce((sum, item) => sum + item, 0);', '}'],
7
+ 'deep-control-flow': {
8
+ before: ['for (const item of items) {', ' if (item.ready) {', ' if (item.valid) save(item);', ' }', '}'],
9
+ after: ['for (const item of items) {', ' if (!item.ready || !item.valid) continue;', ' save(item);', '}'],
14
10
  },
15
- 'stray-console': {
16
- before: ['export function placeOrder(order: Order) {', " console.log('placing', order.id);", '}'],
11
+ 'dependency-cycle': {
12
+ before: ['// a.ts: import { total } from "./b";', '// b.ts: import { total } from "./a";'],
17
13
  after: [
18
- 'export function placeOrder(order: Order) {',
19
- " logger.info({ orderId: order.id }, 'placing order');",
20
- '}',
14
+ '// shared.ts: export const total = (xs) => xs.length;',
15
+ '// a.ts and b.ts: import { total } from "./shared";',
21
16
  ],
22
17
  },
23
18
  'deprecated-node-api': {
24
19
  before: ['const zeroed = new Buffer(16);', "const copy = new Buffer('hi', 'utf8');"],
25
20
  after: ['const zeroed = Buffer.alloc(16);', "const copy = Buffer.from('hi', 'utf8');"],
26
21
  },
27
- 'dependency-cycle': {
28
- before: ['// a.ts: import { total } from "./b";', '// b.ts: import { total } from "./a";'],
29
- after: [
30
- '// shared.ts: export const total = (xs) => xs.length;',
31
- '// a.ts and b.ts: import { total } from "./shared";',
32
- ],
22
+ 'double-type-assertion': {
23
+ before: ['const response = await fetchUser();', 'const user = response as unknown as User;'],
24
+ after: ['const response = await fetchUser();', 'const user = parseUser(response);'],
25
+ },
26
+ 'duplicate-implementation': {
27
+ before: ['const okA = (n) => n >= 1 && n <= 9;', 'const okB = (n) => n >= 1 && n <= 9;'],
28
+ after: ['export const inRange = (n) => n >= 1 && n <= 9;', '// call inRange(n) from both sites'],
29
+ },
30
+ 'file-placement': {
31
+ before: ['// outside the declared folder', 'src/user.controller.ts'],
32
+ after: ['// moved, imports updated', 'src/http/user.controller.ts'],
33
+ },
34
+ 'focused-test-committed': {
35
+ before: ["describe.only('checkout', () => {", " it('adds an item', () => {});", '});'],
36
+ after: ["describe('checkout', () => {", " it('adds an item', () => {});", '});'],
33
37
  },
34
38
  'folder-boundary': {
35
39
  before: [
@@ -44,14 +48,6 @@ const examples = {
44
48
  'run(await loadCount());',
45
49
  ],
46
50
  },
47
- 'data-access-boundary': {
48
- before: ['// src/http/handler.ts', 'import { Pool } from "pg";', 'const rows = await new Pool().query(sql);'],
49
- after: ['// src/http/handler.ts', 'import { loadUsers } from "../data/users";', 'const rows = await loadUsers();'],
50
- },
51
- 'duplicate-implementation': {
52
- before: ['const okA = (n) => n >= 1 && n <= 9;', 'const okB = (n) => n >= 1 && n <= 9;'],
53
- after: ['export const inRange = (n) => n >= 1 && n <= 9;', '// call inRange(n) from both sites'],
54
- },
55
51
  'high-branch-complexity': {
56
52
  before: [
57
53
  'if (kind === "a") return doA(x);',
@@ -65,14 +61,6 @@ const examples = {
65
61
  'return handle(x);',
66
62
  ],
67
63
  },
68
- 'deep-control-flow': {
69
- before: ['for (const item of items) {', ' if (item.ready) {', ' if (item.valid) save(item);', ' }', '}'],
70
- after: ['for (const item of items) {', ' if (!item.ready || !item.valid) continue;', ' save(item);', '}'],
71
- },
72
- 'query-mutates-state': {
73
- before: ['/** @maintainabilityQuery */', 'current() { this.count += 1; return this.count; }'],
74
- after: ['/** @maintainabilityQuery */', 'current() { return this.count; }', 'increment() { this.count += 1; }'],
75
- },
76
64
  'large-class': {
77
65
  before: [
78
66
  'class OrderService {',
@@ -103,6 +91,26 @@ const examples = {
103
91
  'send({ to: a, from: b, subject: c, body: d });',
104
92
  ],
105
93
  },
94
+ 'query-mutates-state': {
95
+ before: ['/** @maintainabilityQuery */', 'current() { this.count += 1; return this.count; }'],
96
+ after: ['/** @maintainabilityQuery */', 'current() { return this.count; }', 'increment() { this.count += 1; }'],
97
+ },
98
+ 'stray-console': {
99
+ before: ['export function placeOrder(order: Order) {', " console.log('placing', order.id);", '}'],
100
+ after: [
101
+ 'export function placeOrder(order: Order) {',
102
+ " logger.info({ orderId: order.id }, 'placing order');",
103
+ '}',
104
+ ],
105
+ },
106
+ 'ts-suppression-without-reason': {
107
+ before: ['// @ts-ignore', 'legacyClient.connect(options);'],
108
+ after: ['// @ts-expect-error legacyClient types omit the options argument', 'legacyClient.connect(options);'],
109
+ },
110
+ 'tsconfig-strict-disabled': {
111
+ before: ['// tsconfig.json', '{ "compilerOptions": { "strict": false } }'],
112
+ after: ['// tsconfig.json', '{ "compilerOptions": { "strict": true } }'],
113
+ },
106
114
  'unreferenced-file': {
107
115
  before: ['// src/legacy-export.ts', '// imported by nothing, not an entry point', 'export const run = () => {};'],
108
116
  after: ['// delete src/legacy-export.ts, or import it', '// from the file that really uses it'],
@@ -111,9 +119,18 @@ const examples = {
111
119
  before: ['// helpers.ts', 'export const used = () => 1;', 'export const neverImported = () => 2;'],
112
120
  after: ['// helpers.ts', 'export const used = () => 1;', 'const neverImported = () => 2; // or delete it'],
113
121
  },
114
- 'file-placement': {
115
- before: ['// outside the declared folder', 'src/user.controller.ts'],
116
- after: ['// moved, imports updated', 'src/http/user.controller.ts'],
122
+ 'unused-import': {
123
+ before: ["import { readFile, writeFile } from 'node:fs/promises';", 'await writeFile(path, text);'],
124
+ after: ["import { writeFile } from 'node:fs/promises';", 'await writeFile(path, text);'],
125
+ },
126
+ 'unused-local-variable': {
127
+ before: [
128
+ 'function total(items) {',
129
+ " const label = 'sum';",
130
+ ' return items.reduce((sum, item) => sum + item, 0);',
131
+ '}',
132
+ ],
133
+ after: ['function total(items) {', ' return items.reduce((sum, item) => sum + item, 0);', '}'],
117
134
  },
118
135
  };
119
136
  function exampleFor(ruleId) {
@@ -1,67 +1,82 @@
1
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
1
2
  const knownRules = new Set([
2
3
  'data-access-boundary',
3
4
  'deep-control-flow',
4
5
  'dependency-cycle',
6
+ 'deprecated-node-api',
7
+ 'double-type-assertion',
5
8
  'duplicate-implementation',
6
9
  'file-placement',
10
+ 'focused-test-committed',
7
11
  'folder-boundary',
8
12
  'high-branch-complexity',
9
13
  'large-class',
10
14
  'large-module',
11
15
  'long-parameter-list',
12
16
  'query-mutates-state',
17
+ 'stray-console',
18
+ 'ts-suppression-without-reason',
19
+ 'tsconfig-strict-disabled',
13
20
  'unreferenced-file',
14
21
  'unused-export',
15
22
  'unused-import',
16
23
  'unused-local-variable',
17
- 'stray-console',
18
- 'deprecated-node-api',
19
24
  ]);
20
25
  // Impact levels (see lib/shared/impact-levels.cjs) for every rule id a maintainability finding can
21
26
  // carry. README
22
27
  // criteria: high is a cycle that changes load-time behaviour, medium significant maintainability
23
28
  // debt, low readability.
29
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
24
30
  const impactByRule = {
31
+ 'data-access-boundary': 'medium',
32
+ 'deep-control-flow': 'low',
25
33
  'dependency-cycle': 'high',
34
+ 'deprecated-node-api': 'medium',
35
+ 'double-type-assertion': 'low',
26
36
  'duplicate-implementation': 'medium',
27
- 'high-branch-complexity': 'medium',
37
+ 'file-placement': 'low',
38
+ 'focused-test-committed': 'medium',
28
39
  'folder-boundary': 'medium',
29
- 'data-access-boundary': 'medium',
30
- 'query-mutates-state': 'medium',
31
- 'syntax-error': 'medium',
32
- 'large-module': 'low',
40
+ 'high-branch-complexity': 'medium',
33
41
  'large-class': 'low',
34
- 'deep-control-flow': 'low',
35
- 'file-placement': 'low',
42
+ 'large-module': 'low',
36
43
  'long-parameter-list': 'low',
37
- 'unused-export': 'low',
44
+ 'query-mutates-state': 'medium',
45
+ 'stray-console': 'low',
46
+ 'syntax-error': 'medium',
47
+ 'ts-suppression-without-reason': 'low',
48
+ 'tsconfig-strict-disabled': 'medium',
38
49
  'unreferenced-file': 'low',
50
+ 'unused-export': 'low',
39
51
  'unused-import': 'low',
40
52
  'unused-local-variable': 'low',
41
- 'stray-console': 'low',
42
- 'deprecated-node-api': 'medium',
43
53
  };
44
54
  // One-line summaries of every rule above, used where a rule needs a fixed name (SARIF
45
55
  // shortDescription) rather than the per-site finding message. The README row for each rule has the
46
56
  // full evidence.
57
+ // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
47
58
  const descriptionByRule = {
48
59
  'data-access-boundary': 'A file outside the approved paths imports a configured database driver or ORM.',
49
60
  'deep-control-flow': 'Control structures are nested four levels deep.',
50
61
  'dependency-cycle': 'An eager chain of internal imports leads back to the module it started from.',
62
+ 'deprecated-node-api': 'A deprecated Node.js API is used: new Buffer(), url.parse() or fs.exists().',
63
+ 'double-type-assertion': 'A value is cast through unknown or any to a second type, bypassing the type checker.',
51
64
  'duplicate-implementation': 'Substantial functions share the same implementation.',
52
65
  'file-placement': 'A file with a configured suffix sits outside its allowed folders.',
66
+ 'focused-test-committed': 'A committed .only, fit or fdescribe makes the test runner skip every other test.',
53
67
  'folder-boundary': 'An import crosses a folder boundary the team declared.',
54
68
  'high-branch-complexity': 'A function reaches a branch complexity score of 15.',
55
69
  'large-class': 'A class has more than 30 methods, accessors, constructors or function-valued fields.',
56
70
  'large-module': 'A file has more than 600 lines of code.',
57
71
  'long-parameter-list': 'A function takes more than 5 positional parameters.',
58
72
  'query-mutates-state': 'A method marked @maintainabilityQuery writes through this.',
73
+ 'stray-console': 'A console call in production code bypasses the logger, so its output has no level or structure.',
59
74
  'syntax-error': 'A native parser could not read the file, so it is skipped and listed and the scan exits 2.',
75
+ 'ts-suppression-without-reason': 'A @ts-ignore, @ts-expect-error or @ts-nocheck directive has no explanation.',
76
+ 'tsconfig-strict-disabled': 'A tsconfig turns off strict type checking.',
60
77
  'unreferenced-file': 'A source file that nothing imports and that is not an entry point.',
61
78
  'unused-export': 'An export that no scanned file imports.',
62
79
  'unused-import': 'An imported name is never used in the file.',
63
80
  'unused-local-variable': 'A local variable is assigned but never read.',
64
- 'stray-console': 'A console call in production code bypasses the logger, so its output has no level or structure.',
65
- 'deprecated-node-api': 'A deprecated Node.js API is used: new Buffer(), url.parse() or fs.exists().',
66
81
  };
67
82
  export { knownRules, impactByRule, descriptionByRule };
@@ -7,6 +7,7 @@ import { listFiles, createResolver } from './inputs.js';
7
7
  import { archivedCopies, sourceContext } from './snapshot-context.js';
8
8
  import { checkGraph } from './architecture.js';
9
9
  import { checkPlacement } from './layout.js';
10
+ import { checkTsconfigStrictness } from './tsconfig-strict.js';
10
11
  import { analyzePolyglot } from './polyglot.js';
11
12
  import { readSources, analyzeSource } from './analyze-source.js';
12
13
  import { scan, isAnalyzableSource, isOtherSource, reportUnparsable, reportUnparsablePolyglot, sourceCoverage, PARALLEL_FROM_FILES, } from './scan.js';
@@ -41,6 +42,8 @@ async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PAR
41
42
  const polyglot = await analyzePolyglot({ root, files: polyglotTargets, includeDuplicates: false });
42
43
  for (const finding of polyglot.findings)
43
44
  findings.push(finding);
45
+ for (const finding of checkTsconfigStrictness(root, inventory.filter((file) => changed.has(file))))
46
+ findings.push(finding);
44
47
  reportUnparsablePolyglot(skippedFiles, polyglot);
45
48
  for (const finding of checkGraph({ files: sourceFiles, edges, boundaries: policy.boundaries, constEnums }))
46
49
  findings.push(finding);
@@ -12,6 +12,7 @@ import { collectModuleUsage } from './module-usage.js';
12
12
  import { checkPlacement } from './layout.js';
13
13
  import { nonJsLanguages, analyzePolyglot } from './polyglot.js';
14
14
  import { readSourceFiles, analyzeSource } from './analyze-source.js';
15
+ import { checkTsconfigStrictness } from './tsconfig-strict.js';
15
16
  import { identifierIndexOf, isPrivateManifest } from './source-facts.js';
16
17
  import { recordSkippedFile } from '../performance/scan-outcome.js';
17
18
  // Starting a thread and loading TypeScript in it costs more than analysing a small project.
@@ -146,19 +147,20 @@ async function analyzeWithPolyglot(root, jsFiles, otherSources, parallelFrom, op
146
147
  throw error;
147
148
  }
148
149
  }
150
+ function detectIgnoredAllSources(root, policy, jsFiles, otherSources) {
151
+ if (jsFiles.length || otherSources.length || policy.placement.length)
152
+ return false;
153
+ const ignoredAllSources = Boolean(policy.isIgnored) &&
154
+ listFiles(root, policy.exclude).some((file) => isAnalyzableSource(file) || isOtherSource(file));
155
+ if (ignoredAllSources)
156
+ return true;
157
+ throw new Error('No supported source files or placement rules in this directory. Use --graph for a dependency graph from another language.');
158
+ }
149
159
  async function scan(root, policy, { parallelFrom = PARALLEL_FROM_FILES, inScope, indexIdentifiers } = {}) {
150
160
  const inventory = listFiles(root, policy.exclude, policy.isIgnored);
151
161
  const jsFiles = inventory.filter(isAnalyzableSource);
152
162
  const otherSources = inventory.filter(isOtherSource);
153
- let ignoredAllSources = false;
154
- if (!jsFiles.length && !otherSources.length && !policy.placement.length) {
155
- ignoredAllSources =
156
- Boolean(policy.isIgnored) &&
157
- listFiles(root, policy.exclude).some((file) => isAnalyzableSource(file) || isOtherSource(file));
158
- if (!ignoredAllSources) {
159
- throw new Error('No supported source files or placement rules in this directory. Use --graph for a dependency graph from another language.');
160
- }
161
- }
163
+ const ignoredAllSources = detectIgnoredAllSources(root, policy, jsFiles, otherSources);
162
164
  const duplicates = createDuplicateIndex();
163
165
  const edges = [];
164
166
  const constEnums = new Map();
@@ -198,6 +200,8 @@ async function scan(root, policy, { parallelFrom = PARALLEL_FROM_FILES, inScope,
198
200
  }
199
201
  for (const finding of polyglot.findings)
200
202
  findings.push(finding);
203
+ for (const finding of checkTsconfigStrictness(root, inventory))
204
+ findings.push(finding);
201
205
  reportUnparsablePolyglot(skippedFiles, polyglot);
202
206
  for (const finding of duplicates.findings())
203
207
  findings.push(finding);
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+ import { isVendoredOrSamplePath } from './source-exclusions.js';
5
+ const TSCONFIG_FILE = /(?:^|\/)tsconfig(?:\.[\w-]+)*\.json$/i;
6
+ // Configs that exist to compile tests, tooling or sample projects are allowed to be looser.
7
+ const NON_PRODUCTION_CONFIG = /(?:^|[./_-])(?:test|tests|spec|e2e|jest|vitest|cypress|playwright|storybook)(?:[./_-]|$)/i;
8
+ const NON_PRODUCTION_FOLDER = /(?:^|\/)(?:tests?|__tests__|specs?|e2e|templates?|boilerplates?|starters?)\//i;
9
+ const LOOSENED_CHECKS = ['strictNullChecks', 'noImplicitAny'];
10
+ function objectProperty(object, name) {
11
+ return object.properties
12
+ .filter(ts.isPropertyAssignment)
13
+ .find((property) => (ts.isStringLiteral(property.name) || ts.isIdentifier(property.name)) && property.name.text === name);
14
+ }
15
+ function isFalse(property) {
16
+ return property?.initializer.kind === ts.SyntaxKind.FalseKeyword;
17
+ }
18
+ function compilerOptionsOf(sourceFile) {
19
+ const [statement] = sourceFile.statements;
20
+ const root = statement?.expression;
21
+ if (!root || !ts.isObjectLiteralExpression(root))
22
+ return;
23
+ const initializer = objectProperty(root, 'compilerOptions')?.initializer;
24
+ return initializer && ts.isObjectLiteralExpression(initializer) ? initializer : undefined;
25
+ }
26
+ function strictnessProblem(options) {
27
+ const strict = objectProperty(options, 'strict');
28
+ if (isFalse(strict))
29
+ return strict;
30
+ // An explicit opt-out of the two checks that matter most is the same decision, with or without `strict: true`.
31
+ return LOOSENED_CHECKS.map((name) => objectProperty(options, name)).find(isFalse);
32
+ }
33
+ function checkTsconfig(root, file) {
34
+ const text = fs.readFileSync(path.join(root, file), 'utf8');
35
+ const sourceFile = ts.parseJsonText(file, text);
36
+ const options = compilerOptionsOf(sourceFile);
37
+ const problem = options && strictnessProblem(options);
38
+ if (!problem)
39
+ return [];
40
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(problem.getStart(sourceFile));
41
+ return [
42
+ {
43
+ file,
44
+ line: line + 1,
45
+ column: character + 1,
46
+ ruleId: 'tsconfig-strict-disabled',
47
+ message: 'This tsconfig turns off strict type checking, so null and undefined values and implicit `any` types pass the compiler and fail at runtime. Enable `"strict": true`, or turn it on in steps by fixing the errors per flag.',
48
+ },
49
+ ];
50
+ }
51
+ function isProductionTsconfig(file) {
52
+ const normalized = file.replaceAll('\\', '/');
53
+ return (TSCONFIG_FILE.test(normalized) &&
54
+ !isVendoredOrSamplePath(normalized) &&
55
+ !NON_PRODUCTION_FOLDER.test(normalized) &&
56
+ !NON_PRODUCTION_CONFIG.test(path.posix.basename(normalized)));
57
+ }
58
+ function checkTsconfigStrictness(root, inventory) {
59
+ return inventory.filter(isProductionTsconfig).flatMap((file) => {
60
+ try {
61
+ return checkTsconfig(root, file);
62
+ }
63
+ catch {
64
+ // An unreadable config is not this rule's finding.
65
+ return [];
66
+ }
67
+ });
68
+ }
69
+ export { checkTsconfigStrictness };