loadwise 0.9.0 → 0.10.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 (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -5,6 +5,7 @@ import ts from 'typescript';
5
5
  import { isVendoredOrSamplePath } from '../analysis/source-exclusions.js';
6
6
  import { isPathInside } from '../../shared/system/path-inside.js';
7
7
  import { normalizeSlashes } from '../../shared/system/posix-path.js';
8
+ import { isRecord } from '../../shared/system/is-record.js';
8
9
  const TSCONFIG_FILE = /(?:^|\/)tsconfig(?:\.[\w-]+)*\.json$/i;
9
10
  // Configs that exist to compile tests, tooling or sample projects are allowed to be looser.
10
11
  const NON_PRODUCTION_CONFIG = /(?:^|[./_-])(?:test|tests|spec|e2e|jest|vitest|cypress|playwright|storybook)(?:[./_-]|$)/i;
@@ -37,22 +38,307 @@ function compilerOptionsOf(sourceFile, requireUnique = false) {
37
38
  const initializer = properties[0]?.initializer;
38
39
  return initializer && ts.isObjectLiteralExpression(initializer) ? initializer : undefined;
39
40
  }
40
- function strictnessProblem(options) {
41
- const strict = objectProperty(options, 'strict');
41
+ const BOTH_MAIN_CHECKS_OFF_EFFECT = 'null and undefined values and implicit `any` types pass the compiler and fail at runtime';
42
+ const MAIN_CHECK_EFFECTS = {
43
+ strictNullChecks: 'null and undefined values pass the compiler and fail at runtime',
44
+ noImplicitAny: 'implicit `any` types pass the compiler unchecked',
45
+ };
46
+ const STEPWISE_ADVICE = 'or turn it on in steps by fixing the errors per flag.';
47
+ // Strict-family flags that `strict: true` turns on and a config can turn back off. `strictPropertyInitialization`
48
+ // is left out because decorator-based frameworks (TypeORM, class-validator, DI containers) disable it by design;
49
+ // `alwaysStrict` only controls emitted "use strict" prologues, not type checking.
50
+ const STRICT_FAMILY_EFFECTS = {
51
+ strictFunctionTypes: 'callbacks with incompatible parameter types pass the compiler',
52
+ strictBindCallApply: '`bind`, `call` and `apply` accept arguments of the wrong type',
53
+ noImplicitThis: 'a `this` with an implicit `any` type passes unchecked',
54
+ useUnknownInCatchVariables: 'catch clause variables are typed `any` instead of `unknown`',
55
+ strictBuiltinIteratorReturn: 'results of built-in iterators are typed `any` instead of `undefined`',
56
+ };
57
+ // TypeScript 6.0 turned `strict` on by default.
58
+ const STRICT_BY_DEFAULT_MAJOR = 6;
59
+ const MAX_EXTENDS_DEPTH = 16;
60
+ // One plain comparator such as `5.4.2`, `^5.4.0` or `~4.9`; `>=5`, `*`, `latest` and unions are unknown.
61
+ const SINGLE_VERSION_RANGE = /^(?:npm:typescript@)?[\^~=v]?\s*(\d+)(?:\.(?:\d+|[x*]))*(?:-[\w.]+)?$/;
62
+ function readConfig(context, absolute) {
63
+ const key = path.resolve(absolute);
64
+ if (context.configs.has(key))
65
+ return context.configs.get(key);
66
+ let config;
67
+ if (fs.statSync(key, { throwIfNoEntry: false })?.isFile()) {
68
+ const sourceFile = ts.parseJsonText(key, fs.readFileSync(key, 'utf8'));
69
+ const rootObject = sourceFile.statements[0]?.expression;
70
+ if (rootObject && ts.isObjectLiteralExpression(rootObject))
71
+ config = { sourceFile, root: rootObject, options: compilerOptionsOf(sourceFile) };
72
+ }
73
+ context.configs.set(key, config);
74
+ return config;
75
+ }
76
+ function literalBoolean(property) {
77
+ if (property?.initializer.kind === ts.SyntaxKind.TrueKeyword)
78
+ return true;
79
+ if (property?.initializer.kind === ts.SyntaxKind.FalseKeyword)
80
+ return false;
81
+ return undefined;
82
+ }
83
+ // Same lookup as TypeScript: the path as written, then with `.json` appended. Package names stay unresolved.
84
+ function extendedConfigPath(context, configFile, parent) {
85
+ const normalized = normalizeSlashes(parent);
86
+ if (!normalized.startsWith('.') && !path.isAbsolute(normalized))
87
+ return;
88
+ const target = path.resolve(path.dirname(configFile), normalized);
89
+ if (!isPathInside(context.repositoryRoot, target))
90
+ return;
91
+ if (fs.statSync(target, { throwIfNoEntry: false })?.isFile())
92
+ return target;
93
+ return normalized.endsWith('.json') ? undefined : target + '.json';
94
+ }
95
+ function parentsOf(config) {
96
+ const property = objectProperty(config.root, 'extends');
97
+ if (!property)
98
+ return [];
99
+ const value = property.initializer;
100
+ if (ts.isStringLiteral(value))
101
+ return [value.text];
102
+ if (ts.isArrayLiteralExpression(value))
103
+ return value.elements.map((element) => (ts.isStringLiteral(element) ? element.text : undefined));
104
+ return [undefined];
105
+ }
106
+ function resolvedOption(context, configFile, name, depth = 0) {
107
+ const config = readConfig(context, configFile);
108
+ if (!config || depth > MAX_EXTENDS_DEPTH)
109
+ return 'unknown';
110
+ const own = config.options && literalBoolean(objectProperty(config.options, name));
111
+ if (own !== undefined)
112
+ return own;
113
+ // A later `extends` entry overrides an earlier one.
114
+ for (const parent of parentsOf(config).reverse()) {
115
+ const target = typeof parent === 'string' ? extendedConfigPath(context, configFile, parent) : undefined;
116
+ const value = target ? resolvedOption(context, target, name, depth + 1) : 'unknown';
117
+ if (value !== 'absent')
118
+ return value;
119
+ }
120
+ return 'absent';
121
+ }
122
+ function versionMajor(version) {
123
+ if (typeof version !== 'string')
124
+ return;
125
+ const match = SINGLE_VERSION_RANGE.exec(version.trim());
126
+ return match ? Number(match[1]) : undefined;
127
+ }
128
+ function readJson(file) {
129
+ if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile())
130
+ return;
131
+ try {
132
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
133
+ return isRecord(value) ? value : undefined;
134
+ }
135
+ catch {
136
+ return;
137
+ }
138
+ }
139
+ function declaredTypescript(manifest) {
140
+ for (const field of ['devDependencies', 'dependencies', 'peerDependencies']) {
141
+ const dependencies = manifest?.[field];
142
+ if (isRecord(dependencies) && 'typescript' in dependencies)
143
+ return dependencies.typescript;
144
+ }
145
+ return undefined;
146
+ }
147
+ // The repository root ends the climb; a workspace package scanned alone takes its TypeScript from there.
148
+ function isClimbEnd(directory) {
149
+ return path.dirname(directory) === directory || fs.existsSync(path.join(directory, '.git'));
150
+ }
151
+ function repositoryRootOf(directory) {
152
+ let current = path.resolve(directory);
153
+ while (!isClimbEnd(current))
154
+ current = path.dirname(current);
155
+ return current;
156
+ }
157
+ function nearest(directory, read) {
158
+ for (let current = path.resolve(directory);; current = path.dirname(current)) {
159
+ const value = read(current);
160
+ if (value !== undefined || isClimbEnd(current))
161
+ return value;
162
+ }
163
+ }
164
+ // The compiler that runs decides what a missing `strict` means: the nearest installed TypeScript, even a
165
+ // hoisted one above a package that declares another range, and only without one the nearest declaration.
166
+ function typescriptMajor(context, directory) {
167
+ const key = path.resolve(directory);
168
+ if (context.typescriptMajors.has(key))
169
+ return context.typescriptMajors.get(key);
170
+ const installed = nearest(key, (folder) => readJson(path.join(folder, 'node_modules', 'typescript', 'package.json')));
171
+ const major = installed
172
+ ? versionMajor(installed.version)
173
+ : versionMajor(nearest(key, (folder) => declaredTypescript(readJson(path.join(folder, 'package.json')))));
174
+ context.typescriptMajors.set(key, major);
175
+ return major;
176
+ }
177
+ function strictIsOn(context, configFile) {
178
+ const strict = resolvedOption(context, configFile, 'strict');
179
+ if (strict === 'absent')
180
+ return (typescriptMajor(context, path.dirname(configFile)) ?? 0) >= STRICT_BY_DEFAULT_MAJOR;
181
+ return strict === true;
182
+ }
183
+ // A check `strict` covers is on when the config sets it, or when it follows `strict` and strict mode is on.
184
+ function checkIsOn(context, configFile, name) {
185
+ const value = resolvedOption(context, configFile, name);
186
+ return typeof value === 'boolean' ? value : strictIsOn(context, configFile);
187
+ }
188
+ // What the checks that stay off let through, so the message names only those; undefined when none are off.
189
+ function offChecksEffect(context, configFile) {
190
+ const mainOff = LOOSENED_CHECKS.filter((name) => !checkIsOn(context, configFile, name));
191
+ if (mainOff.length === LOOSENED_CHECKS.length)
192
+ return BOTH_MAIN_CHECKS_OFF_EFFECT;
193
+ if (mainOff.length)
194
+ return MAIN_CHECK_EFFECTS[mainOff[0]];
195
+ const familyOff = Object.keys(STRICT_FAMILY_EFFECTS).filter((name) => !checkIsOn(context, configFile, name));
196
+ return familyOff.length ? familyOff.map((name) => STRICT_FAMILY_EFFECTS[name]).join('; ') : undefined;
197
+ }
198
+ function isScannedProductionTsconfig(context, configFile) {
199
+ return (isPathInside(path.resolve(context.root), configFile) &&
200
+ isProductionTsconfig(context.root, path.relative(context.root, configFile)));
201
+ }
202
+ // Only configs this rule checks count: a test config or `jsconfig.json` extending a base would not report its gap.
203
+ function extendedConfigs(context) {
204
+ if (context.extendedConfigs)
205
+ return context.extendedConfigs;
206
+ const targets = new Set();
207
+ const configs = ts.sys.readDirectory(context.root, ['.json'], ['**/.git', '**/node_modules'], ['**/tsconfig*.json']);
208
+ for (const configFile of configs) {
209
+ if (!isScannedProductionTsconfig(context, path.resolve(configFile)))
210
+ continue;
211
+ const config = readConfig(context, configFile);
212
+ if (!config)
213
+ continue;
214
+ for (const parent of parentsOf(config)) {
215
+ const target = typeof parent === 'string' && extendedConfigPath(context, configFile, parent);
216
+ if (target)
217
+ targets.add(caseKey(target));
218
+ }
219
+ }
220
+ context.extendedConfigs = targets;
221
+ return targets;
222
+ }
223
+ function caseKey(file) {
224
+ const resolved = path.resolve(file);
225
+ return ts.sys.useCaseSensitiveFileNames ? resolved : resolved.toLowerCase();
226
+ }
227
+ function isEmptyArray(property) {
228
+ const value = property?.initializer;
229
+ return Boolean(value && ts.isArrayLiteralExpression(value) && value.elements.length === 0);
230
+ }
231
+ // A config that compiles nothing itself (a solution config) or that another config extends without
232
+ // selecting files of its own (a shared base) leaves strictness to the configs that use it. A config named
233
+ // `tsconfig.json` without `include` or `files` is not a shared base: tsc and editors compile its folder with it.
234
+ function leavesStrictnessToOthers(context, configFile, config) {
235
+ const files = objectProperty(config.root, 'files');
236
+ const include = objectProperty(config.root, 'include');
237
+ if ((files || include) && (!files || isEmptyArray(files)) && (!include || isEmptyArray(include)))
238
+ return true;
239
+ if (files || include || path.basename(configFile).toLowerCase() === 'tsconfig.json')
240
+ return false;
241
+ return extendedConfigs(context).has(caseKey(configFile));
242
+ }
243
+ // Whether this config compiles files without `strict` on a TypeScript that leaves it off by default.
244
+ function hasMissingStrictGap(context, configFile, config) {
245
+ if (resolvedOption(context, configFile, 'strict') !== 'absent')
246
+ return false;
247
+ const major = typescriptMajor(context, path.dirname(configFile));
248
+ if (major === undefined || major >= STRICT_BY_DEFAULT_MAJOR)
249
+ return false;
250
+ // Turning on the two checks that matter most one by one is a deliberate setup, not a forgotten flag.
251
+ if (LOOSENED_CHECKS.every((name) => resolvedOption(context, configFile, name) === true))
252
+ return false;
253
+ return !leavesStrictnessToOthers(context, configFile, config);
254
+ }
255
+ // A `tsconfig.build.json` extending a `tsconfig.json` that has the same gap inherits it, and the finding on
256
+ // that parent (or on its own parent) already covers it.
257
+ function inheritsReportedGap(context, configFile, config) {
258
+ return parentsOf(config).some((parent) => {
259
+ const target = typeof parent === 'string' ? extendedConfigPath(context, configFile, parent) : undefined;
260
+ const parentConfig = target && readConfig(context, target);
261
+ return Boolean(target &&
262
+ parentConfig &&
263
+ isScannedProductionTsconfig(context, target) &&
264
+ hasMissingStrictGap(context, target, parentConfig));
265
+ });
266
+ }
267
+ function missingStrictProblem(context, configFile, config) {
268
+ if (!hasMissingStrictGap(context, configFile, config) || inheritsReportedGap(context, configFile, config))
269
+ return;
270
+ const effect = offChecksEffect(context, configFile);
271
+ if (!effect)
272
+ return;
273
+ const anchor = objectProperty(config.root, 'compilerOptions') ?? objectProperty(config.root, 'extends');
274
+ return {
275
+ node: anchor ?? config.root,
276
+ message: `This tsconfig never sets \`strict\`, and TypeScript before 6.0 leaves it off by default, so ${effect}. Add \`"strict": true\`, ${STEPWISE_ADVICE}`,
277
+ };
278
+ }
279
+ // A scanned parent with strict mode on and the same flag off reports the opt-out itself.
280
+ function parentReportsOptOut(context, configFile, config, name) {
281
+ return parentsOf(config).some((parent) => {
282
+ const target = typeof parent === 'string' ? extendedConfigPath(context, configFile, parent) : undefined;
283
+ return Boolean(target &&
284
+ isScannedProductionTsconfig(context, target) &&
285
+ strictIsOn(context, target) &&
286
+ resolvedOption(context, target, name) === false);
287
+ });
288
+ }
289
+ function strictFamilyProblem(context, configFile, config) {
290
+ if (!strictIsOn(context, configFile))
291
+ return;
292
+ for (const name of Object.keys(STRICT_FAMILY_EFFECTS)) {
293
+ if (resolvedOption(context, configFile, name) !== false)
294
+ continue;
295
+ const own = config.options && objectProperty(config.options, name);
296
+ if (isFalse(own))
297
+ return {
298
+ node: own,
299
+ message: `This tsconfig enables strict mode but turns \`${name}\` back off, so ${STRICT_FAMILY_EFFECTS[name]}. Remove the override, or fix the errors it hides.`,
300
+ };
301
+ if (parentReportsOptOut(context, configFile, config, name))
302
+ continue;
303
+ return {
304
+ node: objectProperty(config.root, 'extends') ?? config.root,
305
+ message: `This tsconfig enables strict mode but inherits \`"${name}": false\` through \`extends\`, so ${STRICT_FAMILY_EFFECTS[name]}. Set \`"${name}": true\`, or fix the errors it hides.`,
306
+ };
307
+ }
308
+ return undefined;
309
+ }
310
+ function disabledProblem(context, configFile, node) {
311
+ const effect = offChecksEffect(context, configFile);
312
+ if (!effect)
313
+ return;
314
+ return {
315
+ node,
316
+ message: `This tsconfig turns off strict type checking, so ${effect}. Enable \`"strict": true\`, ${STEPWISE_ADVICE}`,
317
+ };
318
+ }
319
+ function strictnessProblem(context, configFile) {
320
+ const config = readConfig(context, configFile);
321
+ if (!config)
322
+ return;
323
+ const { options } = config;
324
+ const strict = options && objectProperty(options, 'strict');
42
325
  if (isFalse(strict))
43
- return strict;
326
+ return disabledProblem(context, configFile, strict);
44
327
  // An explicit opt-out of the two checks that matter most is the same decision, with or without `strict: true`.
45
- return LOOSENED_CHECKS.map((name) => objectProperty(options, name)).find(isFalse);
46
- }
47
- function checkTsconfig(root, file) {
48
- const text = fs.readFileSync(path.join(root, file), 'utf8');
49
- const sourceFile = ts.parseJsonText(file, text);
50
- const options = compilerOptionsOf(sourceFile);
51
- const problem = options && strictnessProblem(options);
52
- if (!problem)
328
+ const loosened = options && LOOSENED_CHECKS.map((name) => objectProperty(options, name)).find(isFalse);
329
+ if (loosened)
330
+ return disabledProblem(context, configFile, loosened);
331
+ return strictFamilyProblem(context, configFile, config) || missingStrictProblem(context, configFile, config);
332
+ }
333
+ function checkTsconfig(context, file) {
334
+ const configFile = path.resolve(context.root, file);
335
+ const problem = strictnessProblem(context, configFile);
336
+ const config = readConfig(context, configFile);
337
+ if (!problem || !config)
53
338
  return [];
54
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(problem.getStart(sourceFile));
55
- const endLine = sourceFile.getLineAndCharacterOfPosition(problem.getEnd()).line;
339
+ const { sourceFile } = config;
340
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(problem.node.getStart(sourceFile));
341
+ const endLine = sourceFile.getLineAndCharacterOfPosition(problem.node.getEnd()).line;
56
342
  return [
57
343
  {
58
344
  file,
@@ -60,7 +346,7 @@ function checkTsconfig(root, file) {
60
346
  column: character + 1,
61
347
  ...(endLine > line ? { rangeEndLine: endLine + 1 } : {}),
62
348
  ruleId: 'tsconfig-strict-disabled',
63
- 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.',
349
+ message: problem.message,
64
350
  },
65
351
  ];
66
352
  }
@@ -74,11 +360,17 @@ function isProductionTsconfig(root, file) {
74
360
  !testPathKindInProject(path.resolve(root, file)));
75
361
  }
76
362
  function checkTsconfigStrictness(root, inventory) {
363
+ const context = {
364
+ root,
365
+ repositoryRoot: repositoryRootOf(root),
366
+ configs: new Map(),
367
+ typescriptMajors: new Map(),
368
+ };
77
369
  return inventory
78
370
  .filter((file) => isProductionTsconfig(root, file))
79
371
  .flatMap((file) => {
80
372
  try {
81
- return checkTsconfig(root, file);
373
+ return checkTsconfig(context, file);
82
374
  }
83
375
  catch {
84
376
  // An unreadable config is not this rule's finding.
@@ -1,5 +1,6 @@
1
1
  // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
2
2
  const knownRules = new Set([
3
+ 'arguments-object',
3
4
  'data-access-boundary',
4
5
  'deep-control-flow',
5
6
  'dependency-cycle',
@@ -14,17 +15,22 @@ const knownRules = new Set([
14
15
  'large-class',
15
16
  'large-module',
16
17
  'long-parameter-list',
18
+ 'node-callback-api',
17
19
  'python-interactive-debugger',
18
20
  'query-mutates-state',
21
+ 'redundant-promise-wrapper',
19
22
  'stray-console',
23
+ 'then-chain-in-async',
20
24
  'ts-suppression-without-reason',
21
25
  'tsconfig-strict-disabled',
22
26
  'unreferenced-file',
23
27
  'unsafe-wide-type',
28
+ 'unused-dependency',
24
29
  'unused-export',
25
30
  'unused-import',
26
31
  'unused-local-function',
27
32
  'unused-local-variable',
33
+ 'var-declaration',
28
34
  ]);
29
35
  // Impact levels (see lib/shared/reporting/impact-levels.ts) for every rule id a maintainability finding can
30
36
  // carry. README
@@ -32,6 +38,7 @@ const knownRules = new Set([
32
38
  // debt, low readability.
33
39
  // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
34
40
  const impactByRule = {
41
+ 'arguments-object': 'low',
35
42
  'data-access-boundary': 'medium',
36
43
  'deep-control-flow': 'low',
37
44
  'dependency-cycle': 'high',
@@ -46,24 +53,30 @@ const impactByRule = {
46
53
  'large-class': 'low',
47
54
  'large-module': 'low',
48
55
  'long-parameter-list': 'low',
56
+ 'node-callback-api': 'low',
49
57
  'python-interactive-debugger': 'medium',
50
58
  'query-mutates-state': 'medium',
59
+ 'redundant-promise-wrapper': 'low',
51
60
  'stray-console': 'low',
52
61
  'syntax-error': 'medium',
62
+ 'then-chain-in-async': 'low',
53
63
  'ts-suppression-without-reason': 'low',
54
64
  'tsconfig-strict-disabled': 'medium',
55
65
  'unreferenced-file': 'low',
56
66
  'unsafe-wide-type': 'low',
67
+ 'unused-dependency': 'low',
57
68
  'unused-export': 'low',
58
69
  'unused-import': 'low',
59
70
  'unused-local-function': 'low',
60
71
  'unused-local-variable': 'low',
72
+ 'var-declaration': 'low',
61
73
  };
62
74
  // One-line summaries of every rule above, used where a rule needs a fixed name (SARIF
63
75
  // shortDescription) rather than the per-site finding message. The README row for each rule has the
64
76
  // full evidence.
65
77
  // Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
66
78
  const descriptionByRule = {
79
+ 'arguments-object': 'A function reads the arguments object instead of declaring a rest parameter.',
67
80
  'data-access-boundary': 'A file outside the approved paths imports a configured database driver or ORM.',
68
81
  'deep-control-flow': 'Control structures are nested four levels deep.',
69
82
  'dependency-cycle': 'An eager chain of internal imports leads back to the module it started from.',
@@ -78,17 +91,22 @@ const descriptionByRule = {
78
91
  'large-class': 'A class has more than 30 methods, accessors, constructors or function-valued fields.',
79
92
  'large-module': 'A file has more than 600 lines of code.',
80
93
  'long-parameter-list': 'A function takes more than 5 positional parameters.',
94
+ 'node-callback-api': 'A Node.js fs, dns, crypto or zlib API is called with a callback instead of its promise form.',
81
95
  'python-interactive-debugger': 'A Python call enters an interactive debugger in production source.',
82
96
  'query-mutates-state': 'A method marked @maintainabilityQuery writes through this.',
97
+ 'redundant-promise-wrapper': 'A new Promise only forwards another promise to resolve and reject.',
83
98
  'stray-console': 'A console call in production code bypasses the logger, so its output has no level or structure.',
84
99
  'syntax-error': 'A native parser could not read the file, so it is skipped and listed and the scan exits 2.',
100
+ 'then-chain-in-async': 'An async function awaits or returns a .then() chain instead of using await.',
85
101
  'ts-suppression-without-reason': 'A @ts-ignore, @ts-expect-error or @ts-nocheck directive has no explanation.',
86
102
  'tsconfig-strict-disabled': 'A tsconfig turns off strict type checking.',
87
103
  'unreferenced-file': 'A source file that nothing imports and that is not an entry point.',
88
104
  'unsafe-wide-type': 'A Function, Object or {} type accepts almost any value, so the compiler checks little.',
105
+ 'unused-dependency': 'An installed runtime dependency has no references in a private project.',
89
106
  'unused-export': 'An export that no scanned file imports.',
90
107
  'unused-import': 'An imported name is never used in the file.',
91
108
  'unused-local-function': 'A private function declaration has no references.',
92
109
  'unused-local-variable': 'A local variable is assigned but never read.',
110
+ 'var-declaration': 'A var declaration in a module or TypeScript file, where let or const would be block-scoped.',
93
111
  };
94
112
  export { knownRules, impactByRule, descriptionByRule };
@@ -11,11 +11,27 @@ import { checkTsconfigStrictness } from './quality/tsconfig-strict.js';
11
11
  import { analyzePolyglot } from './polyglot.js';
12
12
  import { readSources, analyzeSource } from './analysis/analyze-source.js';
13
13
  import { noteFlowSkips } from '../shared/reporting/flow-skips.js';
14
+ import { noteOnce } from '../shared/reporting/coverage-notes.js';
14
15
  import { scan, isAnalyzableSource, isOtherSource, reportUnparsable, reportUnparsablePolyglot, sourceCoverage, PARALLEL_FROM_FILES, } from './scan.js';
15
- async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PARALLEL_FROM_FILES, inScope } = {}) {
16
+ // Each needs every file's imports, exports or bodies, which this mode does not read.
17
+ const crossFileRules = ['duplicate-implementation', 'unreferenced-file', 'unused-dependency', 'unused-export'];
18
+ // Cycles through the changed files are still found; only those through unchanged files are missed.
19
+ const partiallyCheckedRules = ['dependency-cycle'];
20
+ // Rules the user turned off are left out, so the note and the report fields name only lost coverage.
21
+ function noteSkippedCrossFileRules(skippedRules, partialRules) {
22
+ const missed = [
23
+ skippedRules.length && `rules that need every file (${skippedRules.join(', ')})`,
24
+ partialRules.length && 'dependency cycles that pass through unchanged files',
25
+ ].filter(Boolean);
26
+ if (!missed.length)
27
+ return;
28
+ noteOnce('maintainability-changed-cross-file-rules', `Note: the changed-lines maintainability scan skipped ${missed.join(' and ')}. Run a full scan to include them.`);
29
+ }
30
+ async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PARALLEL_FROM_FILES, inScope, mayEnableRule = () => true } = {}) {
16
31
  if (changedFiles.length >= parallelFrom)
17
32
  return scan(root, policy, { inScope });
18
- const inventory = listFiles(root, policy.exclude, policy.isIgnored);
33
+ const coverage = { skippedLink: false };
34
+ const inventory = listFiles(root, policy.exclude, policy.isIgnored, undefined, coverage);
19
35
  const sourceFiles = inventory.filter(isAnalyzableSource);
20
36
  const known = new Set(sourceFiles);
21
37
  const targets = changedFiles.filter((file) => known.has(file)).sort();
@@ -55,6 +71,19 @@ async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PAR
55
71
  findings.push(finding);
56
72
  reportUnparsablePolyglot(root, skippedFiles, polyglot);
57
73
  noteFlowSkips(skippedFiles);
74
+ // The full scan checks dependencies only over the whole unfiltered, fully parsed project without skipped links, so
75
+ // only then is that coverage lost. Unparsable unchanged files are not read here, so they can still over-report.
76
+ const dependenciesChecked = !coverage.skippedLink &&
77
+ !inScope &&
78
+ !policy.isIgnored &&
79
+ !policy.exclude.length &&
80
+ sourceFiles.length > 0 &&
81
+ !skippedFiles.length;
82
+ const skippedRules = crossFileRules.filter((ruleId) => mayEnableRule(ruleId) && (ruleId !== 'unused-dependency' || dependenciesChecked));
83
+ // When every source file changed and parsed, the import graph is whole and cycles are fully checked.
84
+ const wholeGraph = constEnums.size === sourceFiles.length;
85
+ const partialRules = wholeGraph ? [] : partiallyCheckedRules.filter(mayEnableRule);
86
+ noteSkippedCrossFileRules(skippedRules, partialRules);
58
87
  for (const finding of checkGraph({ files: sourceFiles, edges, boundaries: policy.boundaries, constEnums }))
59
88
  findings.push(finding);
60
89
  const snapshots = archivedCopies(inventory);
@@ -75,6 +104,8 @@ async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PAR
75
104
  }),
76
105
  findings,
77
106
  ...(skippedFiles.length && { skippedFiles }),
107
+ ...(skippedRules.length && { skippedRules }),
108
+ ...(partialRules.length && { partialRules }),
78
109
  };
79
110
  }
80
111
  export { scanChangedFiles };
@@ -8,6 +8,7 @@ import { archivedCopies, sourceContext } from './analysis/snapshot-context.js';
8
8
  import { checkGraph } from './architecture/architecture.js';
9
9
  import { createEntryPoints } from './entry-points/entry-points.js';
10
10
  import { checkUnusedModules } from './unused/unused-modules.js';
11
+ import { checkUnusedDependencies } from './unused/unused-dependencies.js';
11
12
  import { collectModuleUsage } from './unused/module-usage.js';
12
13
  import { checkPlacement } from './architecture/layout.js';
13
14
  import { nonJsLanguages, analyzePolyglot } from './polyglot.js';
@@ -184,7 +185,8 @@ function detectIgnoredAllSources(root, policy, jsFiles, otherSources) {
184
185
  throw new Error('No supported source files or placement rules in this directory. Use --graph for a dependency graph from another language.');
185
186
  }
186
187
  async function scan(root, policy, { parallelFrom = PARALLEL_FROM_FILES, inScope, indexIdentifiers } = {}) {
187
- const inventory = listFiles(root, policy.exclude, policy.isIgnored);
188
+ const coverage = { skippedLink: false };
189
+ const inventory = listFiles(root, policy.exclude, policy.isIgnored, undefined, coverage);
188
190
  const jsFiles = inventory.filter(isAnalyzableSource);
189
191
  const otherSources = inventory.filter(isOtherSource);
190
192
  const ignoredAllSources = detectIgnoredAllSources(root, policy, jsFiles, otherSources);
@@ -239,6 +241,13 @@ async function scan(root, policy, { parallelFrom = PARALLEL_FROM_FILES, inScope,
239
241
  findings.push(finding);
240
242
  const { isEntryPoint, isToolingFile, workspacePackages, isPrivateApplication, operatorScripts, siblingUsages } = createEntryPoints(root, inventory, jsFiles, fileFacts);
241
243
  const declarations = await declarationUsages(root, inventory, jsFiles, identifierIndex);
244
+ if (!coverage.skippedLink &&
245
+ !inScope &&
246
+ !policy.isIgnored &&
247
+ !policy.exclude.length &&
248
+ jsFiles.length &&
249
+ !skippedFiles.length)
250
+ findings.push(...checkUnusedDependencies(root, { inventory, usages, declarations }));
242
251
  for (const finding of checkUnusedModules({
243
252
  files: jsFiles,
244
253
  usages,
@@ -40,12 +40,21 @@ function importBindingAt(node) {
40
40
  }
41
41
  // The unused-import findings of one file are judged against the same set, so one parse serves them all.
42
42
  const unusedAnchorsBySourceFile = new WeakMap();
43
- // Siblings are judged without the project's compiler options, which can only keep more of them.
44
- function unusedAnchorsOf(sourceFile) {
43
+ // Siblings are judged without the project's compiler options, so a configured `jsxFactory` that only
44
+ // JSX reads looks unused. In a fix run, only siblings the scan also reported under those options go.
45
+ function unusedAnchorsOf(sourceFile, file, reported) {
45
46
  const cached = unusedAnchorsBySourceFile.get(sourceFile);
46
47
  if (cached)
47
48
  return cached;
48
- const anchors = new Set(unusedImportBindings(sourceFile, {}).map((binding) => binding.anchor));
49
+ const confirmed = (anchor) => {
50
+ if (!reported)
51
+ return true;
52
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(anchor.getStart(sourceFile));
53
+ return reported.has(`${file}:${line + 1}:${character + 1}`);
54
+ };
55
+ const anchors = new Set(unusedImportBindings(sourceFile, {})
56
+ .map((binding) => binding.anchor)
57
+ .filter(confirmed));
49
58
  unusedAnchorsBySourceFile.set(sourceFile, anchors);
50
59
  return anchors;
51
60
  }
@@ -81,15 +90,15 @@ function clauseRewrite(clause, unused, sourceFile) {
81
90
  text: keptClauseParts(clause, unused).join(', '),
82
91
  };
83
92
  }
84
- function removeUnusedImport({ node, sourceFile }) {
85
- if (!node || !sourceFile)
93
+ function removeUnusedImport({ finding, node, sourceFile, load }) {
94
+ if (!node || !sourceFile || typeof finding.file !== 'string')
86
95
  return;
87
96
  const target = importBindingAt(node);
88
97
  const declaration = target && ts.findAncestor(target, ts.isImportDeclaration);
89
98
  const clause = declaration?.importClause;
90
99
  if (!target || !declaration || !clause)
91
100
  return;
92
- const unused = new Set(unusedAnchorsOf(sourceFile));
101
+ const unused = new Set(unusedAnchorsOf(sourceFile, finding.file, load.reportedUnusedImports));
93
102
  unused.add(target);
94
103
  if (keptClauseParts(clause, unused).length === 0) {
95
104
  const removal = unusedDeclarationRemoval(sourceFile, declaration);