loadwise 0.6.2 → 0.8.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.
- package/README.md +175 -115
- package/dist/bin/loadwise.js +132 -67
- package/dist/lib/accessibility/analyze.js +5 -3
- package/dist/lib/accessibility/angular-inline.js +9 -11
- package/dist/lib/accessibility/angular-literal.js +39 -0
- package/dist/lib/accessibility/form-context.js +36 -0
- package/dist/lib/accessibility/frame-head.js +92 -0
- package/dist/lib/accessibility/frame-viewport.js +149 -0
- package/dist/lib/accessibility/frontend-detect.js +6 -5
- package/dist/lib/accessibility/jsx-elements.js +13 -3
- package/dist/lib/accessibility/markup-files.js +7 -2
- package/dist/lib/accessibility/rule-ids.js +3 -0
- package/dist/lib/accessibility/rules.js +128 -41
- package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
- package/dist/lib/accessibility/template-attributes.js +5 -3
- package/dist/lib/accessibility/template-elements.js +25 -6
- package/dist/lib/accessibility/template-file.js +40 -25
- package/dist/lib/accessibility/usage.js +10 -2
- package/dist/lib/editor/accessibility-examples.js +6 -1
- package/dist/lib/editor/actions.js +46 -7
- package/dist/lib/editor/apply-fix.js +69 -4
- package/dist/lib/editor/configured-setup.js +63 -0
- package/dist/lib/editor/diagnostics.js +206 -17
- package/dist/lib/editor/dismissals.js +85 -26
- package/dist/lib/editor/editor-document.js +5 -2
- package/dist/lib/editor/editor-launcher.js +170 -0
- package/dist/lib/editor/fix-edits.js +19 -0
- package/dist/lib/editor/jetbrains-setup.js +53 -0
- package/dist/lib/editor/language-server.js +80 -24
- package/dist/lib/editor/managed-config.js +37 -0
- package/dist/lib/editor/native-setup.js +86 -0
- package/dist/lib/editor/perf-watch.js +8 -6
- package/dist/lib/editor/release-vsix.js +61 -0
- package/dist/lib/editor/reliability-examples.js +15 -0
- package/dist/lib/editor/scan-session.js +29 -8
- package/dist/lib/editor/server-commands.js +38 -9
- package/dist/lib/editor/setup-server.js +87 -0
- package/dist/lib/editor/setup-vim.js +63 -0
- package/dist/lib/editor/setup.js +131 -0
- package/dist/lib/editor/stdio-setup.js +6 -0
- package/dist/lib/editor/workspace-files.js +61 -7
- package/dist/lib/editor/workspace-paths.js +41 -1
- package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
- package/dist/lib/maintainability/architecture/architecture.js +4 -4
- package/dist/lib/maintainability/cli/changed-lines.js +20 -2
- package/dist/lib/maintainability/cli/inputs.js +12 -3
- package/dist/lib/maintainability/cli.js +18 -5
- package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
- package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
- package/dist/lib/maintainability/examples.js +4 -0
- package/dist/lib/maintainability/quality/functions.js +9 -6
- package/dist/lib/maintainability/quality/limits.js +19 -0
- package/dist/lib/maintainability/quality/size-limits.js +8 -2
- package/dist/lib/maintainability/quality/stray-console.js +62 -1
- package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
- package/dist/lib/maintainability/rule-ids.js +3 -0
- package/dist/lib/maintainability/scan-changed.js +4 -1
- package/dist/lib/maintainability/scan-worker.js +6 -2
- package/dist/lib/maintainability/scan.js +21 -8
- package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
- package/dist/lib/maintainability/unused/module-usage.js +43 -21
- package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
- package/dist/lib/maintainability/unused/unused-modules.js +5 -10
- package/dist/lib/performance/analysis/source-inputs.js +7 -2
- package/dist/lib/performance/analysis/source-options.js +7 -6
- package/dist/lib/performance/analyze.js +16 -3
- package/dist/lib/performance/cli/changed-lines.js +8 -1
- package/dist/lib/performance/cli/cli-arguments.js +19 -8
- package/dist/lib/performance/cli/cli-output.js +4 -0
- package/dist/lib/performance/cli/cli-scan.js +21 -2
- package/dist/lib/performance/cli.js +16 -7
- package/dist/lib/performance/collections/memory-growth.js +55 -12
- package/dist/lib/performance/contracts/openapi.js +13 -4
- package/dist/lib/performance/datastores/pg-integrity.js +68 -22
- package/dist/lib/performance/datastores/pg-session-release.js +114 -0
- package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
- package/dist/lib/performance/datastores/pooling.js +62 -3
- package/dist/lib/performance/datastores/redis.js +94 -18
- package/dist/lib/performance/datastores/session-store.js +2 -1
- package/dist/lib/performance/db/checks.js +19 -8
- package/dist/lib/performance/db/gateway.js +3 -1
- package/dist/lib/performance/db/plan-estimates.js +4 -4
- package/dist/lib/performance/engine/native-syntax.js +3 -0
- package/dist/lib/performance/engine/native.js +11 -7
- package/dist/lib/performance/evidence/plans.js +7 -5
- package/dist/lib/performance/evidence/traces.js +21 -1
- package/dist/lib/performance/frontend/angular-teardown.js +96 -0
- package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
- package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
- package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
- package/dist/lib/performance/frontend/frontend-perf.js +149 -74
- package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
- package/dist/lib/performance/migrations/extract-code.js +13 -5
- package/dist/lib/performance/migrations/extract-sql.js +82 -38
- package/dist/lib/performance/migrations/operations.js +56 -13
- package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
- package/dist/lib/performance/migrations/postgres-registry.js +127 -26
- package/dist/lib/performance/migrations/postgres-settings.js +78 -0
- package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
- package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
- package/dist/lib/performance/migrations/rules-postgres.js +88 -39
- package/dist/lib/performance/orm/offset-pagination.js +6 -4
- package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
- package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
- package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
- package/dist/lib/performance/polyglot.js +111 -14
- package/dist/lib/performance/projects.js +3 -3
- package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
- package/dist/lib/performance/request/backend-mastery.js +151 -42
- package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
- package/dist/lib/performance/request/fastify-receivers.js +93 -0
- package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
- package/dist/lib/performance/request/mongoose-lean.js +298 -46
- package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
- package/dist/lib/performance/request/phase5-ast.js +6 -7
- package/dist/lib/performance/request/phase5-rules.js +204 -23
- package/dist/lib/performance/request/request-handlers.js +120 -23
- package/dist/lib/performance/request/sql-select-star.js +150 -0
- package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
- package/dist/lib/performance/request/upload-limits.js +5 -1
- package/dist/lib/performance/site-fix.js +4 -4
- package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
- package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
- package/dist/lib/performance/site-fixes/collections.js +1 -2
- package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
- package/dist/lib/performance/site-fixes/helpers.js +3 -4
- package/dist/lib/performance/site-fixes/integrity.js +2 -4
- package/dist/lib/performance/site-fixes/migration-context.js +8 -1
- package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
- package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
- package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
- package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
- package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
- package/dist/lib/performance/sql/mysql-tokens.js +38 -12
- package/dist/lib/reliability/boundary-access.js +114 -57
- package/dist/lib/reliability/react-bugs.js +29 -7
- package/dist/lib/reliability/resource-leak-intervals.js +258 -0
- package/dist/lib/reliability/resource-leaks.js +209 -195
- package/dist/lib/reliability/rule-ids.js +10 -1
- package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
- package/dist/lib/reliability/swallowed-errors.js +107 -21
- package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
- package/dist/lib/reliability/usage.js +16 -5
- package/dist/lib/reliability/walk.js +3 -2
- package/dist/lib/security/auth-crypto/hashing.js +24 -8
- package/dist/lib/security/auth-crypto/jwt.js +21 -6
- package/dist/lib/security/auth-crypto/secrets.js +44 -1
- package/dist/lib/security/auth-crypto/shared.js +3 -1
- package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
- package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
- package/dist/lib/security/cli.js +21 -6
- package/dist/lib/security/cookie-credentials.js +115 -0
- package/dist/lib/security/cookie-csrf.js +241 -0
- package/dist/lib/security/deps/advisory.js +50 -109
- package/dist/lib/security/deps/cli.js +1 -1
- package/dist/lib/security/deps/cvss-score.js +14 -0
- package/dist/lib/security/deps/fixed-version.js +97 -0
- package/dist/lib/security/deps/lockfiles.js +135 -74
- package/dist/lib/security/deps/osv.js +11 -3
- package/dist/lib/security/deps/scan.js +47 -20
- package/dist/lib/security/deps/yarn-lock.js +158 -0
- package/dist/lib/security/examples/injection.cjs +4 -0
- package/dist/lib/security/exposure/cookies.js +17 -2
- package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
- package/dist/lib/security/exposure/frontend-security.js +21 -14
- package/dist/lib/security/exposure/jsx-url.js +18 -33
- package/dist/lib/security/exposure/logging.js +49 -10
- package/dist/lib/security/exposure/prototype-pollution.js +126 -56
- package/dist/lib/security/exposure/react-html.js +26 -0
- package/dist/lib/security/exposure/reflected-xss.js +34 -5
- package/dist/lib/security/files/compose.js +126 -1
- package/dist/lib/security/files/dockerfile.js +62 -4
- package/dist/lib/security/files/index.js +1 -1
- package/dist/lib/security/injection/command.js +46 -18
- package/dist/lib/security/injection/index.js +2 -0
- package/dist/lib/security/injection/ldap.js +86 -0
- package/dist/lib/security/injection/nosql.js +28 -4
- package/dist/lib/security/injection/redos.js +1 -1
- package/dist/lib/security/injection/rule-ids.js +1 -0
- package/dist/lib/security/injection/shared.js +5 -1
- package/dist/lib/security/injection/sql.js +28 -13
- package/dist/lib/security/lexical-declaration.js +113 -0
- package/dist/lib/security/pg-dynamic-query.js +28 -1
- package/dist/lib/security/pg-identifier-guards.js +107 -3
- package/dist/lib/security/phase5-rules.js +26 -135
- package/dist/lib/security/polyglot.js +2 -2
- package/dist/lib/security/redirect-settings.js +98 -0
- package/dist/lib/security/request-forgery/open-redirect.js +18 -5
- package/dist/lib/security/request-forgery/path-traversal.js +84 -6
- package/dist/lib/security/request-forgery/shared.js +1 -7
- package/dist/lib/security/request-forgery/ssrf.js +176 -14
- package/dist/lib/security/rule-descriptions.js +5 -1
- package/dist/lib/security/rule-ids.js +7 -0
- package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
- package/dist/lib/security/site-fixes/exposure.js +21 -3
- package/dist/lib/security/site-fixes/files.js +11 -13
- package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
- package/dist/lib/security/site-fixes/injection.js +17 -4
- package/dist/lib/security/site-fixes/jwt.js +1 -20
- package/dist/lib/security/site-fixes/request-forgery.js +37 -29
- package/dist/lib/security/taint/binding-inputs.js +236 -0
- package/dist/lib/security/taint/filename-guard.js +45 -45
- package/dist/lib/security/taint/guards.js +14 -8
- package/dist/lib/security/taint/index.js +126 -154
- package/dist/lib/security/taint/propagate.js +43 -9
- package/dist/lib/security/taint/record-writes.js +161 -0
- package/dist/lib/security/taint/resolution-cache.js +13 -7
- package/dist/lib/security/taint/sanitizers.js +89 -5
- package/dist/lib/security/taint/trace-nodes.js +61 -0
- package/dist/lib/security/taint/validators.js +89 -9
- package/dist/lib/shared/agent/agent-init.js +28 -5
- package/dist/lib/shared/agent/agent-prompt.js +74 -0
- package/dist/lib/shared/agent/agent-session.js +6 -1
- package/dist/lib/shared/agent/agent-verify.js +58 -11
- package/dist/lib/shared/agent/git-hook.js +17 -6
- package/dist/lib/shared/agent/review-delivery.js +1 -1
- package/dist/lib/shared/agent/review-mcp.js +8 -2
- package/dist/lib/shared/analysis/ast-semantics.js +2 -2
- package/dist/lib/shared/analysis/scan-cache.js +99 -14
- package/dist/lib/shared/check.js +172 -20
- package/dist/lib/shared/cli-dispatch.js +17 -0
- package/dist/lib/shared/config.js +27 -10
- package/dist/lib/shared/explain.js +1 -1
- package/dist/lib/shared/fix/fix-convergence.js +19 -31
- package/dist/lib/shared/fix/fix-handoff.js +16 -11
- package/dist/lib/shared/fix/fix-imports.js +4 -162
- package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
- package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
- package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
- package/dist/lib/shared/fix/fix-presentation.js +9 -6
- package/dist/lib/shared/fix/fix-safety.js +32 -1
- package/dist/lib/shared/fix/fix-scope.js +82 -0
- package/dist/lib/shared/fix/fix-terminal.js +28 -1
- package/dist/lib/shared/fix/fix-typecheck.js +8 -4
- package/dist/lib/shared/fix/import-text-edits.js +148 -0
- package/dist/lib/shared/fix/project-file-access.js +17 -26
- package/dist/lib/shared/fix/read-fix-text.js +20 -0
- package/dist/lib/shared/fix.js +241 -104
- package/dist/lib/shared/formats/finding-location.js +4 -1
- package/dist/lib/shared/formats/github.js +3 -3
- package/dist/lib/shared/formats/sarif.js +9 -3
- package/dist/lib/shared/report-fp.js +97 -0
- package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
- package/dist/lib/shared/reporting/baseline.js +7 -5
- package/dist/lib/shared/reporting/check-text.js +50 -0
- package/dist/lib/shared/reporting/pillars.js +54 -19
- package/dist/lib/shared/reporting/source-report.js +3 -0
- package/dist/lib/shared/system/atomic-write.js +5 -2
- package/dist/lib/shared/system/glob.js +34 -8
- package/dist/lib/shared/system/sentry.js +222 -0
- package/dist/lib/shared/system/shell-argument.js +5 -1
- package/dist/lib/shared/system/terminal-safe.js +3 -2
- package/dist/lib/shared/system/terminal-style.js +131 -0
- package/dist/lib/shared/workspaces.js +15 -3
- package/docs/assets/cli-workflow.gif +0 -0
- package/integrations/sublime/plugin.py +22 -0
- package/integrations/zed/Cargo.lock +845 -0
- package/integrations/zed/Cargo.toml +11 -0
- package/integrations/zed/extension.toml +11 -0
- package/integrations/zed/src/lib.rs +25 -0
- package/package.json +15 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/loadwise.md +11 -6
- package/plugin/hooks/check-edited-file.mjs +27 -5
- package/polyglot/performance/rules/csharp.yml +34 -5
- package/polyglot/performance/rules/java.yml +24 -1
- package/polyglot/performance/rules/python.yml +74 -2
- package/polyglot/performance/sgconfig.yml +1 -0
- package/polyglot/reliability/rules/csharp.yml +12 -6
- package/polyglot/reliability/rules/go.yml +86 -6
- package/polyglot/reliability/rules/java.yml +22 -1
- package/polyglot/reliability/sgconfig.yml +1 -0
- package/polyglot/security/rules/go.yml +100 -22
- package/polyglot/security/rules/python.yml +74 -6
- package/polyglot/security/rules/rust.yml +65 -0
- package/polyglot/security/sgconfig.yml +1 -0
- package/schema/loadwise.config.schema.json +556 -76
- /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
|
@@ -169,6 +169,20 @@ function globPattern(rawGlob) {
|
|
|
169
169
|
}
|
|
170
170
|
else if (character === ',' && insideBraces)
|
|
171
171
|
pattern += '|';
|
|
172
|
+
else if (character === '[') {
|
|
173
|
+
const close = glob.indexOf(']', index + 1);
|
|
174
|
+
// `[!]` has no members, so minimatch treats it as literal text rather than a negated class.
|
|
175
|
+
if (close > index + 1 && glob.slice(index + 1, close) !== '!') {
|
|
176
|
+
const body = glob.slice(index + 1, close);
|
|
177
|
+
// Escape a leading hyphen after the added `/` so it stays a literal, not a range from `/`.
|
|
178
|
+
const negatedBody = body.slice(1).replace(/^-/, String.raw `\-`);
|
|
179
|
+
pattern += `[${body.startsWith('!') ? '^/' + negatedBody : body}]`;
|
|
180
|
+
index = close;
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
pattern += '\\[';
|
|
184
|
+
}
|
|
185
|
+
}
|
|
172
186
|
else
|
|
173
187
|
pattern += character.replaceAll(/[.+^$()|[\]\\]/g, '\\$&');
|
|
174
188
|
}
|
|
@@ -392,11 +406,9 @@ function createEntryPoints(root, inventory, sourceFiles, fileFacts) {
|
|
|
392
406
|
// Mocha and Jest also read their options from package.json instead of a config file.
|
|
393
407
|
for (const script of Object.values(manifest.scripts ?? {}))
|
|
394
408
|
if (typeof script === 'string')
|
|
395
|
-
|
|
396
|
-
addConfigPath(directory, entry, true);
|
|
409
|
+
addConfigPaths(directory, mochaScriptPaths(script), true);
|
|
397
410
|
for (const toolKey of ['mocha', 'jest'])
|
|
398
|
-
|
|
399
|
-
addConfigPath(directory, entry, toolKey === 'mocha');
|
|
411
|
+
addConfigPaths(directory, jsonConfigFilePaths(isRecord(manifest[toolKey]) ? manifest[toolKey] : {}), toolKey === 'mocha');
|
|
400
412
|
for (const entry of stringValues(manifest.exports))
|
|
401
413
|
if (entry.includes('*'))
|
|
402
414
|
addWildcardEntry(directory, entry, known, explicit);
|
|
@@ -416,32 +428,49 @@ function createEntryPoints(root, inventory, sourceFiles, fileFacts) {
|
|
|
416
428
|
}
|
|
417
429
|
// Mocha loads every file in a folder named as a spec; other tools resolve a folder to its index,
|
|
418
430
|
// so only mocha paths expand.
|
|
419
|
-
function addFolderFiles(directory, entry) {
|
|
431
|
+
function addFolderFiles(directory, entry, excluded = []) {
|
|
420
432
|
const folder = path.posix.normalize(path.posix.join(directory, entry.replaceAll('\\', '/'))).replace(/\/$/, '');
|
|
421
433
|
if (folder === '.' || folder.startsWith('..'))
|
|
422
434
|
return;
|
|
423
435
|
for (const file of known)
|
|
424
|
-
if (file.startsWith(folder + '/'))
|
|
436
|
+
if (file.startsWith(folder + '/') && !excluded.some((pattern) => pattern.test(file)))
|
|
425
437
|
explicit.add(file);
|
|
426
438
|
}
|
|
427
|
-
function addConfigPath(directory, entry, loadsFolder = false) {
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
if (loadsFolder && !sourceExtensions.includes(path.posix.extname(entry)))
|
|
431
|
-
addFolderFiles(directory, entry);
|
|
439
|
+
function addConfigPath(directory, entry, loadsFolder = false, excluded = []) {
|
|
440
|
+
const normalized = entry.replaceAll('\\', '/');
|
|
441
|
+
if (normalized.startsWith('!'))
|
|
432
442
|
return;
|
|
443
|
+
// A bracketed name may be a literal file or a glob class, so it gets both.
|
|
444
|
+
const literalFiles = entryFiles(directory, normalized);
|
|
445
|
+
const bracketed = normalized.includes('[');
|
|
446
|
+
if (!/[*?{]/.test(normalized)) {
|
|
447
|
+
for (const file of literalFiles)
|
|
448
|
+
if (!excluded.some((pattern) => pattern.test(file)))
|
|
449
|
+
explicit.add(file);
|
|
450
|
+
if (loadsFolder && !sourceExtensions.includes(path.posix.extname(normalized)))
|
|
451
|
+
addFolderFiles(directory, normalized, excluded);
|
|
452
|
+
// Mocha also expands the brackets as a glob, so a bracketed name keeps its glob matches too.
|
|
453
|
+
if (!bracketed)
|
|
454
|
+
return;
|
|
433
455
|
}
|
|
434
|
-
const pattern = globPattern(path.posix.normalize(path.posix.join(directory,
|
|
456
|
+
const pattern = globPattern(path.posix.normalize(path.posix.join(directory, normalized)));
|
|
435
457
|
for (const file of known)
|
|
436
|
-
if (pattern.test(file))
|
|
458
|
+
if (pattern.test(file) && !excluded.some((excludedPattern) => excludedPattern.test(file)))
|
|
437
459
|
explicit.add(file);
|
|
438
460
|
}
|
|
461
|
+
function addConfigPaths(directory, entries, loadsFolder = false) {
|
|
462
|
+
const excluded = entries
|
|
463
|
+
.map((entry) => entry.replaceAll('\\', '/'))
|
|
464
|
+
.filter((entry) => entry.startsWith('!') && entry.length > 1)
|
|
465
|
+
.map((entry) => globPattern(path.posix.normalize(path.posix.join(directory, entry.slice(1)))));
|
|
466
|
+
for (const entry of entries)
|
|
467
|
+
addConfigPath(directory, entry, loadsFolder, excluded);
|
|
468
|
+
}
|
|
439
469
|
function addConfigFiles(file, directory) {
|
|
440
470
|
const paths = jsonConfigFile.test(file)
|
|
441
471
|
? jsonConfigFilePaths(readConfig(root, file))
|
|
442
472
|
: configFilePaths(parseScript(path.join(root, file)) ?? ts.createSourceFile(file, '', ts.ScriptTarget.Latest));
|
|
443
|
-
|
|
444
|
-
addConfigPath(directory, entry, /\.mocharc\./.test(file));
|
|
473
|
+
addConfigPaths(directory, paths, /\.mocharc\./.test(file));
|
|
445
474
|
}
|
|
446
475
|
function addEntries(directory, entries) {
|
|
447
476
|
for (const entry of entries)
|
|
@@ -11,6 +11,7 @@ const rawTextTags = new Set([
|
|
|
11
11
|
'xmp',
|
|
12
12
|
]);
|
|
13
13
|
const inertTags = new Set(['math', 'svg', 'template']);
|
|
14
|
+
const foreignSelfClosingTags = new Set(['math', 'svg']);
|
|
14
15
|
const scriptTypes = new Set([
|
|
15
16
|
'',
|
|
16
17
|
'module',
|
|
@@ -19,6 +20,8 @@ const scriptTypes = new Set([
|
|
|
19
20
|
'text/ecmascript',
|
|
20
21
|
'application/ecmascript',
|
|
21
22
|
]);
|
|
23
|
+
// A trailing slash closes the tag only after whitespace, a closing quote or the tag name; in `a=b/` it belongs to the unquoted value.
|
|
24
|
+
const selfClosingDelimiter = /(?:^|[\s"'])\/$/;
|
|
22
25
|
const localSource = /^(?!\/)[\w./-]+\.[cm]?[jt]sx?$/i;
|
|
23
26
|
function parseAttributes(text) {
|
|
24
27
|
const attributes = new Map();
|
|
@@ -50,7 +53,8 @@ function htmlScriptEntries(text = '') {
|
|
|
50
53
|
inert.pop();
|
|
51
54
|
continue;
|
|
52
55
|
}
|
|
53
|
-
|
|
56
|
+
const isSelfClosingForeign = foreignSelfClosingTags.has(name) && selfClosingDelimiter.test(attributes.trimEnd());
|
|
57
|
+
if (inertTags.has(name) && !isSelfClosingForeign)
|
|
54
58
|
inert.push(name);
|
|
55
59
|
if (name === 'plaintext')
|
|
56
60
|
break;
|
|
@@ -123,6 +123,10 @@ const examples = {
|
|
|
123
123
|
before: ["import { readFile, writeFile } from 'node:fs/promises';", 'await writeFile(path, text);'],
|
|
124
124
|
after: ["import { writeFile } from 'node:fs/promises';", 'await writeFile(path, text);'],
|
|
125
125
|
},
|
|
126
|
+
'unused-local-function': {
|
|
127
|
+
before: ['function obsolete() { return 0; }', 'export function total() {', ' return 1;', '}'],
|
|
128
|
+
after: ['export function total() {', ' return 1;', '}'],
|
|
129
|
+
},
|
|
126
130
|
'unused-local-variable': {
|
|
127
131
|
before: [
|
|
128
132
|
'function total(items) {',
|
|
@@ -4,8 +4,8 @@ import { nestingAdvice, sectionAdvice, loopGuardComparison } from '../cli/branch
|
|
|
4
4
|
import { traversalLeaf } from '../analysis/traversal-context.js';
|
|
5
5
|
import { checklistContext } from '../analysis/checklist-context.js';
|
|
6
6
|
import { textChoiceContext, loopGuard, patchMappingContext } from '../analysis/advisory-context.js';
|
|
7
|
-
const
|
|
8
|
-
const
|
|
7
|
+
const defaultNestingLimit = 4;
|
|
8
|
+
const defaultBranchComplexityLimit = 15;
|
|
9
9
|
// A run of independent `if (...) return;` guards reads straight through, so each counts half toward the
|
|
10
10
|
// limit. Past this many in one function they count in full again, so a function of twenty guards is
|
|
11
11
|
// still reported. The reported number stays the plain count of decisions.
|
|
@@ -55,7 +55,9 @@ function functionAnchor(node, parent) {
|
|
|
55
55
|
return parent.name;
|
|
56
56
|
return node;
|
|
57
57
|
}
|
|
58
|
-
function analyzeFunctions(sourceFile, relativePath) {
|
|
58
|
+
function analyzeFunctions(sourceFile, relativePath, limits) {
|
|
59
|
+
const nestingLimit = limits?.maxDepth === undefined ? defaultNestingLimit : limits.maxDepth + 1;
|
|
60
|
+
const branchComplexityLimit = limits?.maxComplexity === undefined ? defaultBranchComplexityLimit : limits.maxComplexity + 1;
|
|
59
61
|
const findings = [];
|
|
60
62
|
const invokedQueryArrows = new WeakSet();
|
|
61
63
|
// A function-level finding also records the whole function's lines, so a change anywhere inside
|
|
@@ -156,7 +158,8 @@ function analyzeFunctions(sourceFile, relativePath) {
|
|
|
156
158
|
inner.complexity < branchComplexityLimit &&
|
|
157
159
|
'The deepest nested loop branches retain an extreme value or enqueue an unseen item, with optional iteration guards.', nestingAdvice(inner.deepest, sourceFile), loopGuardComparison(inner.deepest, sourceFile), node);
|
|
158
160
|
}
|
|
159
|
-
|
|
161
|
+
const score = weightedComplexity(inner);
|
|
162
|
+
if (limits?.maxComplexity === undefined ? score >= defaultBranchComplexityLimit : score > limits.maxComplexity) {
|
|
160
163
|
report({
|
|
161
164
|
node: functionAnchor(node, parent),
|
|
162
165
|
ruleId: 'high-branch-complexity',
|
|
@@ -220,7 +223,7 @@ function analyzeFunctions(sourceFile, relativePath) {
|
|
|
220
223
|
function visitNestedStatement(node, nestedBody, scope, depth) {
|
|
221
224
|
scope.complexity++;
|
|
222
225
|
const nestedDepth = depth + 1;
|
|
223
|
-
classifyNestedTraversal(nestedDepth, scope, node);
|
|
226
|
+
classifyNestedTraversal(nestedDepth, scope, node, nestingLimit);
|
|
224
227
|
if (nestedDepth > scope.maxDepth) {
|
|
225
228
|
scope.maxDepth = nestedDepth;
|
|
226
229
|
scope.deepest = node;
|
|
@@ -302,7 +305,7 @@ function analyzeFunctions(sourceFile, relativePath) {
|
|
|
302
305
|
visit(sourceFile, undefined, 0);
|
|
303
306
|
return findings;
|
|
304
307
|
}
|
|
305
|
-
function classifyNestedTraversal(nestedDepth, scope, node) {
|
|
308
|
+
function classifyNestedTraversal(nestedDepth, scope, node, nestingLimit) {
|
|
306
309
|
if (nestedDepth >= nestingLimit && scope.traversalOnly) {
|
|
307
310
|
if (nestedDepth > nestingLimit)
|
|
308
311
|
scope.traversalOnly = false;
|
|
@@ -1,3 +1,22 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
1
2
|
// Defaults for the size rules; the "maintainability" config section can override each one under "limits".
|
|
2
3
|
const defaultLimits = { largeModuleLines: 600, largeClassMembers: 30, longParameterCount: 5 };
|
|
4
|
+
export function configuredLimits(settings, root, legacy) {
|
|
5
|
+
const base = settings.filename ? path.dirname(settings.filename) : root;
|
|
6
|
+
return (file) => {
|
|
7
|
+
const relative = path.relative(base, path.resolve(root, file)).split(path.sep).join('/');
|
|
8
|
+
function option(ruleId, key) {
|
|
9
|
+
const value = settings.ruleOptions(ruleId, relative)?.[key];
|
|
10
|
+
return typeof value === 'number' ? value : undefined;
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
largeModuleLines: option('large-module', 'maxLines') ?? legacy.largeModuleLines,
|
|
14
|
+
largeClassMembers: option('large-class', 'maxMethods') ?? legacy.largeClassMembers,
|
|
15
|
+
longParameterCount: option('long-parameter-list', 'maxParams') ?? legacy.longParameterCount,
|
|
16
|
+
maxClassLines: option('large-class', 'maxLines'),
|
|
17
|
+
maxDepth: option('deep-control-flow', 'maxDepth'),
|
|
18
|
+
maxComplexity: option('high-branch-complexity', 'maxComplexity'),
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
}
|
|
3
22
|
export { defaultLimits };
|
|
@@ -6,9 +6,9 @@ import { generatedSource } from './duplicates.js';
|
|
|
6
6
|
import { isVendoredMinified } from '../../shared/analysis/execution-context.js';
|
|
7
7
|
import { defaultLimits } from './limits.js';
|
|
8
8
|
// Lines that hold at least one token, so comments and blank lines are not counted.
|
|
9
|
-
function linesOfCode(sourceFile) {
|
|
9
|
+
function linesOfCode(sourceFile, root = sourceFile) {
|
|
10
10
|
const codeLines = new Set();
|
|
11
|
-
const pending = [
|
|
11
|
+
const pending = [root];
|
|
12
12
|
for (let node = pending.pop(); node; node = pending.pop()) {
|
|
13
13
|
if (ts.isJSDoc(node) || node.kind === ts.SyntaxKind.EndOfFileToken)
|
|
14
14
|
continue;
|
|
@@ -81,6 +81,12 @@ function checkSizeLimits(sourceFile, file, limits = defaultLimits, isGenerated)
|
|
|
81
81
|
if (count > limits.largeClassMembers) {
|
|
82
82
|
report(node.name ?? node, 'large-class', `This class has ${count} methods and accessors (limit ${limits.largeClassMembers}). A class this wide usually owns several responsibilities. Group the methods that share state into their own classes and have this one delegate to them.`);
|
|
83
83
|
}
|
|
84
|
+
else if (limits.maxClassLines !== undefined) {
|
|
85
|
+
const lines = linesOfCode(sourceFile, node);
|
|
86
|
+
if (lines > limits.maxClassLines) {
|
|
87
|
+
report(node.name ?? node, 'large-class', `This class has ${lines} lines of code (limit ${limits.maxClassLines}, comments and blank lines excluded). Split responsibilities into smaller classes.`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
84
90
|
return;
|
|
85
91
|
}
|
|
86
92
|
if (!ts.isFunctionLike(node) || !('body' in node) || !node.body || isInjectionConstructor(node))
|
|
@@ -28,13 +28,74 @@ const FIXABLE_METHODS = {
|
|
|
28
28
|
error: 'error',
|
|
29
29
|
};
|
|
30
30
|
const NEST_METHODS = { log: 'log', info: 'log', debug: 'debug', warn: 'warn', error: 'error' };
|
|
31
|
+
function bindingHasName(name, target) {
|
|
32
|
+
if (ts.isIdentifier(name))
|
|
33
|
+
return name.text === target;
|
|
34
|
+
return name.elements.some((element) => !ts.isOmittedExpression(element) && bindingHasName(element.name, target));
|
|
35
|
+
}
|
|
36
|
+
function statementDeclaresName(statement, target) {
|
|
37
|
+
if (ts.isVariableStatement(statement)) {
|
|
38
|
+
return statement.declarationList.declarations.some((declaration) => bindingHasName(declaration.name, target));
|
|
39
|
+
}
|
|
40
|
+
if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {
|
|
41
|
+
return statement.name.text === target;
|
|
42
|
+
}
|
|
43
|
+
if (ts.isImportDeclaration(statement) && statement.importClause && !statement.importClause.isTypeOnly) {
|
|
44
|
+
return valueBindingNames(statement.importClause).includes(target);
|
|
45
|
+
}
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
// `var` is hoisted to the enclosing function or file, even from a nested block.
|
|
49
|
+
function declaresHoistedVar(scope, target) {
|
|
50
|
+
const visit = (node) => {
|
|
51
|
+
if (ts.isFunctionLike(node) || ts.isClassStaticBlockDeclaration(node))
|
|
52
|
+
return false;
|
|
53
|
+
if (ts.isVariableDeclaration(node) &&
|
|
54
|
+
ts.isVariableDeclarationList(node.parent) &&
|
|
55
|
+
!(node.parent.flags & ts.NodeFlags.BlockScoped) &&
|
|
56
|
+
bindingHasName(node.name, target)) {
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
return ts.forEachChild(node, visit) ?? false;
|
|
60
|
+
};
|
|
61
|
+
return ts.forEachChild(scope, visit) ?? false;
|
|
62
|
+
}
|
|
63
|
+
function hasLocalConsoleBinding(node) {
|
|
64
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
65
|
+
if ((ts.isFunctionLike(current) || ts.isClassStaticBlockDeclaration(current) || ts.isSourceFile(current)) &&
|
|
66
|
+
declaresHoistedVar(current, 'console')) {
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
if ((ts.isBlock(current) || ts.isSourceFile(current)) &&
|
|
70
|
+
current.statements.some((s) => statementDeclaresName(s, 'console'))) {
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
if (ts.isFunctionLike(current) && current.parameters.some((p) => bindingHasName(p.name, 'console'))) {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
if (ts.isCatchClause(current) &&
|
|
77
|
+
current.variableDeclaration &&
|
|
78
|
+
bindingHasName(current.variableDeclaration.name, 'console')) {
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
if ((ts.isForStatement(current) || ts.isForOfStatement(current) || ts.isForInStatement(current)) &&
|
|
82
|
+
current.initializer &&
|
|
83
|
+
ts.isVariableDeclarationList(current.initializer) &&
|
|
84
|
+
current.initializer.declarations.some((d) => bindingHasName(d.name, 'console'))) {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
31
90
|
function consoleMethodOf(node) {
|
|
32
91
|
if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
|
|
33
92
|
return;
|
|
34
93
|
const { expression, name } = node.expression;
|
|
35
94
|
if (!ts.isIdentifier(expression) || expression.text !== 'console')
|
|
36
95
|
return;
|
|
37
|
-
|
|
96
|
+
if (!CONSOLE_METHODS.has(name.text) || hasLocalConsoleBinding(node))
|
|
97
|
+
return undefined;
|
|
98
|
+
return name.text;
|
|
38
99
|
}
|
|
39
100
|
function loggerCandidateName(node) {
|
|
40
101
|
if ((ts.isFunctionDeclaration(node) ||
|
|
@@ -39,11 +39,13 @@ function checkTsconfig(root, file) {
|
|
|
39
39
|
if (!problem)
|
|
40
40
|
return [];
|
|
41
41
|
const { line, character } = sourceFile.getLineAndCharacterOfPosition(problem.getStart(sourceFile));
|
|
42
|
+
const endLine = sourceFile.getLineAndCharacterOfPosition(problem.getEnd()).line;
|
|
42
43
|
return [
|
|
43
44
|
{
|
|
44
45
|
file,
|
|
45
46
|
line: line + 1,
|
|
46
47
|
column: character + 1,
|
|
48
|
+
...(endLine > line ? { rangeEndLine: endLine + 1 } : {}),
|
|
47
49
|
ruleId: 'tsconfig-strict-disabled',
|
|
48
50
|
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.',
|
|
49
51
|
},
|
|
@@ -20,6 +20,7 @@ const knownRules = new Set([
|
|
|
20
20
|
'unreferenced-file',
|
|
21
21
|
'unused-export',
|
|
22
22
|
'unused-import',
|
|
23
|
+
'unused-local-function',
|
|
23
24
|
'unused-local-variable',
|
|
24
25
|
]);
|
|
25
26
|
// Impact levels (see lib/shared/reporting/impact-levels.ts) for every rule id a maintainability finding can
|
|
@@ -49,6 +50,7 @@ const impactByRule = {
|
|
|
49
50
|
'unreferenced-file': 'low',
|
|
50
51
|
'unused-export': 'low',
|
|
51
52
|
'unused-import': 'low',
|
|
53
|
+
'unused-local-function': 'low',
|
|
52
54
|
'unused-local-variable': 'low',
|
|
53
55
|
};
|
|
54
56
|
// One-line summaries of every rule above, used where a rule needs a fixed name (SARIF
|
|
@@ -77,6 +79,7 @@ const descriptionByRule = {
|
|
|
77
79
|
'unreferenced-file': 'A source file that nothing imports and that is not an entry point.',
|
|
78
80
|
'unused-export': 'An export that no scanned file imports.',
|
|
79
81
|
'unused-import': 'An imported name is never used in the file.',
|
|
82
|
+
'unused-local-function': 'A private function declaration has no references.',
|
|
80
83
|
'unused-local-variable': 'A local variable is assigned but never read.',
|
|
81
84
|
};
|
|
82
85
|
export { knownRules, impactByRule, descriptionByRule };
|
|
@@ -29,7 +29,10 @@ async function scanChangedFiles(root, policy, changedFiles, { parallelFrom = PAR
|
|
|
29
29
|
const generated = new Set();
|
|
30
30
|
const skippedFiles = [];
|
|
31
31
|
targets.forEach((file, index) => {
|
|
32
|
-
const analysis = analyzeSource(root, file, texts[index], resolve,
|
|
32
|
+
const analysis = analyzeSource(root, file, texts[index], resolve, {
|
|
33
|
+
...policy,
|
|
34
|
+
limits: policy.limitsFor?.(file) ?? policy.limits,
|
|
35
|
+
});
|
|
33
36
|
if (analysis.parseErrors !== undefined)
|
|
34
37
|
return reportUnparsable(root, skippedFiles, file, analysis.parseErrors);
|
|
35
38
|
if (analysis.generated)
|
|
@@ -14,12 +14,16 @@ function describeFailure(error) {
|
|
|
14
14
|
}
|
|
15
15
|
// A rejection in an async listener would crash the worker without a reply, so any failure outside
|
|
16
16
|
// the per-file analysis is reported for every file of the batch instead.
|
|
17
|
-
port.on('message', async ({ batch, files }) => {
|
|
17
|
+
port.on('message', async ({ batch, files, limits }) => {
|
|
18
18
|
try {
|
|
19
19
|
const entries = await readSourceFiles(root, files);
|
|
20
20
|
const results = files.map((file, index) => {
|
|
21
21
|
try {
|
|
22
|
-
return analyzeSource(root, file, entries[index].text, resolve, {
|
|
22
|
+
return analyzeSource(root, file, entries[index].text, resolve, {
|
|
23
|
+
...analysisOptions,
|
|
24
|
+
limits: limits?.[index] ?? analysisOptions.limits,
|
|
25
|
+
disk: entries[index],
|
|
26
|
+
});
|
|
23
27
|
}
|
|
24
28
|
catch (error) {
|
|
25
29
|
return { failure: describeFailure(error) };
|
|
@@ -19,9 +19,9 @@ import { noteFlowSkips, recordUnparsedFile } from '../shared/reporting/flow-skip
|
|
|
19
19
|
const PARALLEL_FROM_FILES = 600;
|
|
20
20
|
const MAXIMUM_WORKERS = 8;
|
|
21
21
|
const BATCH_SIZE = 16;
|
|
22
|
-
//
|
|
23
|
-
// first.
|
|
22
|
+
// Resolve per-file settings on the main thread; only numeric limits cross the worker boundary.
|
|
24
23
|
async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
|
|
24
|
+
const { limitsFor, ...workerOptions } = analysisOptions;
|
|
25
25
|
const results = Array.from({ length: jsFiles.length });
|
|
26
26
|
let next = 0;
|
|
27
27
|
const workers = [];
|
|
@@ -31,9 +31,16 @@ async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
|
|
|
31
31
|
if (next >= jsFiles.length)
|
|
32
32
|
return resolve();
|
|
33
33
|
const first = next;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
const end = Math.min(jsFiles.length, first + BATCH_SIZE);
|
|
35
|
+
try {
|
|
36
|
+
const files = jsFiles.slice(first, end);
|
|
37
|
+
const request = { batch: first, files, limits: limitsFor && files.map(limitsFor) };
|
|
38
|
+
worker.postMessage(request);
|
|
39
|
+
next = end;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
reject(error);
|
|
43
|
+
}
|
|
37
44
|
}
|
|
38
45
|
worker.on('message', ({ batch, results: batchResults }) => {
|
|
39
46
|
batchResults.forEach((result, offset) => (results[batch + offset] = result));
|
|
@@ -46,8 +53,9 @@ async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
|
|
|
46
53
|
}
|
|
47
54
|
try {
|
|
48
55
|
for (let index = 0; index < workerCount; index += 1) {
|
|
49
|
-
const workerData = { root, jsFiles, analysisOptions };
|
|
50
|
-
|
|
56
|
+
const workerData = { root, jsFiles, analysisOptions: workerOptions };
|
|
57
|
+
// The CLI's unbundled scanner and the editor's checker bundle are both one directory below lib/.
|
|
58
|
+
workers.push(new Worker(new URL('../maintainability/scan-worker.js', import.meta.url), { workerData }));
|
|
51
59
|
}
|
|
52
60
|
await Promise.all(workers.map(drive));
|
|
53
61
|
}
|
|
@@ -61,7 +69,11 @@ async function analyzeInParallel(root, jsFiles, workerCount, analysisOptions) {
|
|
|
61
69
|
async function analyzeSequentially(root, jsFiles, analysisOptions) {
|
|
62
70
|
const resolve = createResolver(root, new Set(jsFiles));
|
|
63
71
|
const entries = await readSourceFiles(root, jsFiles);
|
|
64
|
-
return jsFiles.map((file, index) => analyzeSource(root, file, entries[index].text, resolve, {
|
|
72
|
+
return jsFiles.map((file, index) => analyzeSource(root, file, entries[index].text, resolve, {
|
|
73
|
+
...analysisOptions,
|
|
74
|
+
limits: analysisOptions.limitsFor?.(file) ?? analysisOptions.limits,
|
|
75
|
+
disk: entries[index],
|
|
76
|
+
}));
|
|
65
77
|
}
|
|
66
78
|
function analyzeFiles(root, jsFiles, parallelFrom, analysisOptions) {
|
|
67
79
|
const workerCount = Math.min(MAXIMUM_WORKERS, os.availableParallelism() - 1);
|
|
@@ -176,6 +188,7 @@ async function scan(root, policy, { parallelFrom = PARALLEL_FROM_FILES, inScope,
|
|
|
176
188
|
const { analyses, polyglot } = await analyzeWithPolyglot(root, jsFiles, otherSources, parallelFrom, {
|
|
177
189
|
dataAccess: policy.dataAccess,
|
|
178
190
|
limits: policy.limits,
|
|
191
|
+
limitsFor: policy.limitsFor,
|
|
179
192
|
indexIdentifiers: identifierIndex !== undefined,
|
|
180
193
|
});
|
|
181
194
|
for (const [index, file] of jsFiles.entries()) {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
2
|
import { hasCommentBetween } from '../../performance/site-fixes/helpers.js';
|
|
3
|
-
import { unusedImportBindings } from '../unused/unused-bindings.js';
|
|
3
|
+
import { importBindingsOf, unusedImportBindings } from '../unused/unused-bindings.js';
|
|
4
|
+
import { walkNodes } from '../analysis/walk.js';
|
|
5
|
+
import { hasModifier } from '../quality/modifiers.js';
|
|
4
6
|
// A statement alone on its line goes together with one line break, so no blank line is left behind.
|
|
5
7
|
// The fix hunks are whole lines, so the break before it is dropped; on the first line the
|
|
6
8
|
// following line's indentation is. Anything else sharing the line (a trailing comment, another
|
|
@@ -90,7 +92,7 @@ function removeUnusedImport({ node, sourceFile }) {
|
|
|
90
92
|
const unused = new Set(unusedAnchorsOf(sourceFile));
|
|
91
93
|
unused.add(target);
|
|
92
94
|
if (keptClauseParts(clause, unused).length === 0) {
|
|
93
|
-
const removal =
|
|
95
|
+
const removal = unusedDeclarationRemoval(sourceFile, declaration);
|
|
94
96
|
if (!removal)
|
|
95
97
|
return { edits: [], note: sharedLineNote };
|
|
96
98
|
// Dropping a whole import also drops whatever running the module did, unless it only held types.
|
|
@@ -110,6 +112,19 @@ function removeUnusedImport({ node, sourceFile }) {
|
|
|
110
112
|
if (hasCommentBetween(sourceFile.text, edit.start, edit.end)) {
|
|
111
113
|
return { edits: [], note: 'Not applied: the import clause contains comments that rewriting it would remove.' };
|
|
112
114
|
}
|
|
115
|
+
const named = clause.namedBindings;
|
|
116
|
+
if (!clause.isTypeOnly &&
|
|
117
|
+
named &&
|
|
118
|
+
ts.isNamedImports(named) &&
|
|
119
|
+
(!clause.name || unused.has(clause.name)) &&
|
|
120
|
+
named.elements.every((element) => unused.has(element) || element.isTypeOnly) &&
|
|
121
|
+
(clause.name || named.elements.some((element) => !element.isTypeOnly))) {
|
|
122
|
+
return {
|
|
123
|
+
edits: [edit],
|
|
124
|
+
requiresReview: true,
|
|
125
|
+
note: 'Removes the last value binding. Depending on the transpiler, the module may stop running for its side effects.',
|
|
126
|
+
};
|
|
127
|
+
}
|
|
113
128
|
return { edits: [edit], note: 'Removes only the unused name from the import.' };
|
|
114
129
|
}
|
|
115
130
|
// Evaluating these can neither throw nor change anything, so deleting the declaration is safe.
|
|
@@ -158,7 +173,7 @@ function removeUnusedLocal({ node, sourceFile }) {
|
|
|
158
173
|
const statement = declaration && onlyStatementOf(declaration);
|
|
159
174
|
if (!declaration || !statement || !pureInitializer(declaration.initializer))
|
|
160
175
|
return;
|
|
161
|
-
const removal =
|
|
176
|
+
const removal = unusedDeclarationRemoval(sourceFile, statement);
|
|
162
177
|
if (!removal)
|
|
163
178
|
return { edits: [], note: sharedLineNote };
|
|
164
179
|
if (mayAssertType(declaration)) {
|
|
@@ -173,8 +188,128 @@ function removeUnusedLocal({ node, sourceFile }) {
|
|
|
173
188
|
note: 'Removes a variable that is never read; its initializer has no side effects.',
|
|
174
189
|
};
|
|
175
190
|
}
|
|
191
|
+
const typescriptSource = /\.[cm]?tsx?$/i;
|
|
192
|
+
function mayEraseStatement(statement) {
|
|
193
|
+
return (!!statement &&
|
|
194
|
+
(ts.isInterfaceDeclaration(statement) ||
|
|
195
|
+
ts.isTypeAliasDeclaration(statement) ||
|
|
196
|
+
ts.isImportEqualsDeclaration(statement) ||
|
|
197
|
+
ts.isExportDeclaration(statement) ||
|
|
198
|
+
ts.isModuleDeclaration(statement) ||
|
|
199
|
+
ts.isEnumDeclaration(statement) ||
|
|
200
|
+
(ts.isFunctionDeclaration(statement) && !statement.body) ||
|
|
201
|
+
hasModifier(statement, ts.SyntaxKind.DeclareKeyword)));
|
|
202
|
+
}
|
|
203
|
+
const retainedBoundaries = new WeakMap();
|
|
204
|
+
function boundariesIn(scope) {
|
|
205
|
+
const cached = retainedBoundaries.get(scope);
|
|
206
|
+
if (cached)
|
|
207
|
+
return cached;
|
|
208
|
+
const boundaries = new Set();
|
|
209
|
+
const typed = typescriptSource.test(scope.getSourceFile().fileName);
|
|
210
|
+
let needsBoundary = false;
|
|
211
|
+
// Look past whole runs of declarations, which can be erased by TypeScript or removed together by Loadwise.
|
|
212
|
+
for (let index = scope.statements.length - 1; index >= 0; index--) {
|
|
213
|
+
const statement = scope.statements[index];
|
|
214
|
+
if (ts.isVariableStatement(statement) ||
|
|
215
|
+
ts.isFunctionDeclaration(statement) ||
|
|
216
|
+
(ts.isImportDeclaration(statement) && !!statement.importClause) ||
|
|
217
|
+
(typed && mayEraseStatement(statement))) {
|
|
218
|
+
if (needsBoundary)
|
|
219
|
+
boundaries.add(statement);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
// Strings might enter the directive prologue. Some other expressions can join the preceding line via ASI.
|
|
223
|
+
needsBoundary =
|
|
224
|
+
ts.isExpressionStatement(statement) &&
|
|
225
|
+
(ts.isStringLiteral(statement.expression) || /^(?:[([`/+\-<]|(?:as|satisfies)\b)/.test(statement.getText()));
|
|
226
|
+
}
|
|
227
|
+
retainedBoundaries.set(scope, boundaries);
|
|
228
|
+
return boundaries;
|
|
229
|
+
}
|
|
230
|
+
function unusedDeclarationRemoval(sourceFile, declaration) {
|
|
231
|
+
const removal = statementRemoval(sourceFile, declaration);
|
|
232
|
+
if (!removal)
|
|
233
|
+
return;
|
|
234
|
+
const scope = declaration.parent;
|
|
235
|
+
const ownsStatements = ts.isBlock(scope) || ts.isSourceFile(scope) || ts.isCaseClause(scope);
|
|
236
|
+
return ownsStatements && boundariesIn(scope).has(declaration)
|
|
237
|
+
? { start: declaration.getStart(sourceFile), end: declaration.end, text: ';' }
|
|
238
|
+
: removal;
|
|
239
|
+
}
|
|
240
|
+
const durableModuleMarkers = new WeakMap();
|
|
241
|
+
function hasDurableModuleMarker(sourceFile) {
|
|
242
|
+
const cached = durableModuleMarkers.get(sourceFile);
|
|
243
|
+
if (cached !== undefined)
|
|
244
|
+
return cached;
|
|
245
|
+
// Use only markers that do not expose bindings another unused-code fix could remove.
|
|
246
|
+
const marked = sourceFile.statements.some((statement) => (ts.isImportDeclaration(statement) && !statement.importClause) ||
|
|
247
|
+
(ts.isExportDeclaration(statement) &&
|
|
248
|
+
!statement.isTypeOnly &&
|
|
249
|
+
!statement.moduleSpecifier &&
|
|
250
|
+
!!statement.exportClause &&
|
|
251
|
+
ts.isNamedExports(statement.exportClause) &&
|
|
252
|
+
statement.exportClause.elements.length === 0));
|
|
253
|
+
durableModuleMarkers.set(sourceFile, marked);
|
|
254
|
+
return marked;
|
|
255
|
+
}
|
|
256
|
+
function functionRemovalRisks(declaration, sourceFile) {
|
|
257
|
+
const typescript = typescriptSource.test(sourceFile.fileName);
|
|
258
|
+
const names = new Set();
|
|
259
|
+
for (const statement of sourceFile.statements) {
|
|
260
|
+
if (ts.isImportEqualsDeclaration(statement) && !statement.isTypeOnly)
|
|
261
|
+
names.add(statement.name.text);
|
|
262
|
+
if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
|
|
263
|
+
continue;
|
|
264
|
+
for (const { anchor, name } of importBindingsOf(statement)) {
|
|
265
|
+
if (!ts.isImportSpecifier(anchor) || !anchor.isTypeOnly)
|
|
266
|
+
names.add(name);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
let mayElideImport = false;
|
|
270
|
+
let containsImportMeta = false;
|
|
271
|
+
walkNodes(declaration, (node) => {
|
|
272
|
+
// JSX can reference a configured classic factory or introduce an automatic runtime import.
|
|
273
|
+
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
|
|
274
|
+
mayElideImport = true;
|
|
275
|
+
if (typescript && ts.isIdentifier(node) && names.has(node.text))
|
|
276
|
+
mayElideImport = true;
|
|
277
|
+
if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword)
|
|
278
|
+
containsImportMeta = true;
|
|
279
|
+
});
|
|
280
|
+
return { mayElideImport, mayTurnModuleIntoScript: containsImportMeta && !hasDurableModuleMarker(sourceFile) };
|
|
281
|
+
}
|
|
282
|
+
function removeUnusedFunction({ node, sourceFile }) {
|
|
283
|
+
if (!node || !sourceFile)
|
|
284
|
+
return;
|
|
285
|
+
const declaration = ts.findAncestor(node, ts.isFunctionDeclaration);
|
|
286
|
+
if (!declaration || declaration.name !== node || !declaration.body)
|
|
287
|
+
return;
|
|
288
|
+
const start = declaration.getStart(sourceFile);
|
|
289
|
+
if (hasCommentBetween(sourceFile.text, declaration.getFullStart(), start)) {
|
|
290
|
+
return { edits: [], note: 'Not applied: check the comment attached to this declaration before removing it.' };
|
|
291
|
+
}
|
|
292
|
+
const edit = unusedDeclarationRemoval(sourceFile, declaration);
|
|
293
|
+
if (!edit)
|
|
294
|
+
return { edits: [], note: sharedLineNote };
|
|
295
|
+
const { mayElideImport, mayTurnModuleIntoScript } = functionRemovalRisks(declaration, sourceFile);
|
|
296
|
+
// A batch of edits could remove every import.meta use. Without a durable marker, keep these declarations.
|
|
297
|
+
if (mayTurnModuleIntoScript) {
|
|
298
|
+
return { edits: [], note: 'Not applied: removing this import.meta could turn the module into a script.' };
|
|
299
|
+
}
|
|
300
|
+
if (mayElideImport) {
|
|
301
|
+
return {
|
|
302
|
+
edits: [edit],
|
|
303
|
+
omitWhyComment: true,
|
|
304
|
+
requiresReview: true,
|
|
305
|
+
note: 'Removing this function may elide an import or JSX runtime dependency and skip the imported module’s side effects.',
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
return { edits: [edit], omitWhyComment: true, note: 'Removes a private function with no references.' };
|
|
309
|
+
}
|
|
176
310
|
const builders = {
|
|
177
311
|
'unused-import': removeUnusedImport,
|
|
312
|
+
'unused-local-function': removeUnusedFunction,
|
|
178
313
|
'unused-local-variable': removeUnusedLocal,
|
|
179
314
|
};
|
|
180
315
|
export default builders;
|