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
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
2
2
|
const examples = {
|
|
3
|
+
'a11y-aria-hidden-focus': {
|
|
4
|
+
jsx: { before: '<button aria-hidden="true">Close</button>', code: '<button>Close</button>' },
|
|
5
|
+
html: { before: '<button aria-hidden="true">Close</button>', code: '<button>Close</button>' },
|
|
6
|
+
note: 'Expose the control if it is interactive. If the entire region is inactive, consider making it inert.',
|
|
7
|
+
},
|
|
3
8
|
'a11y-button-missing-type': {
|
|
4
9
|
jsx: {
|
|
5
10
|
before: '<button onClick={save}>Save</button>',
|
|
@@ -43,7 +48,7 @@ const examples = {
|
|
|
43
48
|
'a11y-img-missing-alt': {
|
|
44
49
|
jsx: { before: '<img src={logo} />', code: '<img src={logo} alt="Company logo" />' },
|
|
45
50
|
html: { before: '<img src="logo.png">', code: '<img src="logo.png" alt="Company logo">' },
|
|
46
|
-
note: '
|
|
51
|
+
note: 'For an image submit button, describe its action, for example alt="Search". Reserve empty alt text for decorative images.',
|
|
47
52
|
},
|
|
48
53
|
'a11y-input-missing-autocomplete': {
|
|
49
54
|
jsx: { before: '<input type="email" />', code: '<input type="email" autoComplete="email" />' },
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// Code actions and code lenses for the published findings of one file.
|
|
2
2
|
import { CodeActionKind } from 'vscode-languageserver';
|
|
3
|
+
import { locateChange } from './apply-fix.js';
|
|
4
|
+
import { samePosition } from './editor-document.js';
|
|
3
5
|
import { bulkFixesFor, fixAllEdit, fixEdit, missingFolders } from './fix-edits.js';
|
|
4
6
|
const commands = {
|
|
5
7
|
scan: 'loadwise.scan',
|
|
@@ -18,8 +20,7 @@ function kindRequested(only, kind) {
|
|
|
18
20
|
return only.some((requested) => kind === requested || kind.startsWith(requested + '.'));
|
|
19
21
|
}
|
|
20
22
|
// The lightbulb appears with the cursor anywhere on a flagged line, not only on the reported token.
|
|
21
|
-
function onLines(
|
|
22
|
-
const flagged = entry.diagnostic.range;
|
|
23
|
+
function onLines(flagged, range) {
|
|
23
24
|
return flagged.start.line <= range.end.line && flagged.end.line >= range.start.line;
|
|
24
25
|
}
|
|
25
26
|
function command(title, name, argument) {
|
|
@@ -33,6 +34,22 @@ function applyFixAction(entry, fix, workspace) {
|
|
|
33
34
|
diagnostics: [entry.diagnostic],
|
|
34
35
|
isPreferred: !fix.requiresReview,
|
|
35
36
|
};
|
|
37
|
+
const shiftedLine = entry.diagnostic.range.start.line;
|
|
38
|
+
if (shiftedLine !== entry.anchor.line - 1) {
|
|
39
|
+
const [change] = fix.changes;
|
|
40
|
+
const document = workspace.documentFor(entry.filename);
|
|
41
|
+
const relativeLine = change ? entry.anchor.line - change.line : -1;
|
|
42
|
+
const lines = document?.getText().split(/\r?\n/);
|
|
43
|
+
if (fix.changes.length !== 1 ||
|
|
44
|
+
change.create ||
|
|
45
|
+
workspace.keyOf(change.filename) !== workspace.keyOf(entry.filename) ||
|
|
46
|
+
relativeLine < 0 ||
|
|
47
|
+
relativeLine >= change.before.split(/\r?\n/).length ||
|
|
48
|
+
!lines ||
|
|
49
|
+
locateChange(lines, change) !== shiftedLine - relativeLine) {
|
|
50
|
+
return { ...action, disabled: { reason: 'Save and rescan to verify the edit target for this moved finding.' } };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
36
53
|
const result = fixEdit(fix, workspace);
|
|
37
54
|
if (result.edit === undefined)
|
|
38
55
|
action.disabled = { reason: result.error };
|
|
@@ -51,10 +68,10 @@ function dismissAction(entry, title, dismissal) {
|
|
|
51
68
|
command: command(title, commands.dismiss, dismissal),
|
|
52
69
|
};
|
|
53
70
|
}
|
|
54
|
-
function quickFixes(entries,
|
|
71
|
+
function quickFixes(entries, selected, uri, workspace) {
|
|
55
72
|
const actions = [];
|
|
56
73
|
const fileWide = new Set();
|
|
57
|
-
for (const entry of
|
|
74
|
+
for (const entry of selected) {
|
|
58
75
|
const { fix, dismissal, ruleId } = entry.anchor;
|
|
59
76
|
if (fix)
|
|
60
77
|
actions.push(applyFixAction(entry, fix, workspace));
|
|
@@ -64,7 +81,7 @@ function quickFixes(entries, range, uri, workspace) {
|
|
|
64
81
|
fileWide.add(ruleId);
|
|
65
82
|
actions.push(dismissAction(entry, 'Dismiss ' + ruleId + ' in this file', { file: dismissal.file, ruleId: dismissal.ruleId }));
|
|
66
83
|
}
|
|
67
|
-
if (actions.length && bulkFixesFor(entries).eligible.length > 1) {
|
|
84
|
+
if (actions.length && !actions.some((action) => action.disabled) && bulkFixesFor(entries).eligible.length > 1) {
|
|
68
85
|
actions.push({
|
|
69
86
|
title: applyAllTitle,
|
|
70
87
|
kind: CodeActionKind.QuickFix,
|
|
@@ -86,10 +103,32 @@ function fixAllActions(entries, uri, workspace) {
|
|
|
86
103
|
}
|
|
87
104
|
return [{ title: applyAllTitle, kind: fixAllKind, edit }];
|
|
88
105
|
}
|
|
89
|
-
function
|
|
106
|
+
function findingsForAction(entries, range, diagnostics) {
|
|
107
|
+
if (!diagnostics.length)
|
|
108
|
+
return entries.filter((entry) => onLines(entry.diagnostic.range, range));
|
|
109
|
+
const selected = new Map();
|
|
110
|
+
for (const diagnostic of diagnostics) {
|
|
111
|
+
if (!onLines(diagnostic.range, range))
|
|
112
|
+
continue;
|
|
113
|
+
const matches = entries.filter(({ diagnostic: saved }) => saved.source === diagnostic.source &&
|
|
114
|
+
saved.code === diagnostic.code &&
|
|
115
|
+
(diagnostic.data !== undefined ? diagnostic.data === saved.data : diagnostic.message === saved.message));
|
|
116
|
+
// Without an echoed identity, identical diagnostics cannot safely identify a moved occurrence.
|
|
117
|
+
if (matches.length !== 1)
|
|
118
|
+
continue;
|
|
119
|
+
const [entry] = matches;
|
|
120
|
+
const published = entry.diagnostic.range;
|
|
121
|
+
if (diagnostic.data === undefined &&
|
|
122
|
+
(!samePosition(published.start, diagnostic.range.start) || !samePosition(published.end, diagnostic.range.end)))
|
|
123
|
+
continue;
|
|
124
|
+
selected.set(entry, { ...entry, diagnostic: { ...entry.diagnostic, range: diagnostic.range } });
|
|
125
|
+
}
|
|
126
|
+
return [...selected.values()];
|
|
127
|
+
}
|
|
128
|
+
function codeActions(entries, { range, context: { only, diagnostics }, textDocument: { uri } }, workspace) {
|
|
90
129
|
const actions = [];
|
|
91
130
|
if (kindRequested(only, CodeActionKind.QuickFix))
|
|
92
|
-
actions.push(...quickFixes(entries, range, uri, workspace));
|
|
131
|
+
actions.push(...quickFixes(entries, findingsForAction(entries, range, diagnostics), uri, workspace));
|
|
93
132
|
// Building the fix-all edit reads files, so it runs only when the editor asks for that kind.
|
|
94
133
|
if (only && kindRequested(only, fixAllKind))
|
|
95
134
|
actions.push(...fixAllActions(entries, uri, workspace));
|
|
@@ -8,6 +8,19 @@ const alreadyApplied = 'already applied';
|
|
|
8
8
|
function splitLines(text) {
|
|
9
9
|
return text.split(/\r?\n/);
|
|
10
10
|
}
|
|
11
|
+
function splitLinesWithEndings(text) {
|
|
12
|
+
const result = [];
|
|
13
|
+
let start = 0;
|
|
14
|
+
for (let index = 0; index < text.length; index++) {
|
|
15
|
+
if (text[index] !== '\n')
|
|
16
|
+
continue;
|
|
17
|
+
const end = index > start && text[index - 1] === '\r' ? index - 1 : index;
|
|
18
|
+
result.push({ content: text.slice(start, end), eol: text.slice(end, index + 1) });
|
|
19
|
+
start = index + 1;
|
|
20
|
+
}
|
|
21
|
+
result.push({ content: text.slice(start), eol: '' });
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
11
24
|
// Prefer the reported row. After a shift, only a unique nearby match identifies the intended edit.
|
|
12
25
|
function locateChange(lines, change) {
|
|
13
26
|
const expected = splitLines(change.before);
|
|
@@ -71,15 +84,64 @@ function mergeNamedImport(lines, change) {
|
|
|
71
84
|
const added = wanted.names.filter((name) => !current.names.includes(name));
|
|
72
85
|
if (!added.length)
|
|
73
86
|
return { applied: true };
|
|
87
|
+
if (!current.names.length)
|
|
88
|
+
return { row, line: current.head + wanted.namesText + current.tail };
|
|
74
89
|
const trailingSpace = /\s*$/.exec(current.namesText)?.[0] ?? '';
|
|
75
90
|
const keptNames = current.namesText.trimEnd().replace(/,$/, '');
|
|
76
91
|
return { row, line: `${current.head}${keptNames}, ${added.join(', ')}${trailingSpace}${current.tail}` };
|
|
77
92
|
}
|
|
78
93
|
}
|
|
94
|
+
// The lines that replace `removed` lines at `row`, keeping each line's own terminator where it can.
|
|
95
|
+
function buildReplacement(lineEntries, row, removed, added, fallbackEol) {
|
|
96
|
+
const removedEntries = lineEntries.slice(row, row + removed);
|
|
97
|
+
const defaultEol = removedEntries.find((entry) => entry.eol)?.eol ||
|
|
98
|
+
lineEntries[row - 1]?.eol ||
|
|
99
|
+
lineEntries[row + removed]?.eol ||
|
|
100
|
+
fallbackEol;
|
|
101
|
+
// Unchanged lines keep their own ending wherever they land; only the rest take it by position.
|
|
102
|
+
const matchedRemoved = new Map();
|
|
103
|
+
let nextRemoved = 0;
|
|
104
|
+
for (const [index, content] of added.entries()) {
|
|
105
|
+
const found = removedEntries.findIndex((entry, at) => at >= nextRemoved && entry.content === content);
|
|
106
|
+
if (found === -1)
|
|
107
|
+
continue;
|
|
108
|
+
matchedRemoved.set(index, found);
|
|
109
|
+
nextRemoved = found + 1;
|
|
110
|
+
}
|
|
111
|
+
const matchedRows = new Set(matchedRemoved.values());
|
|
112
|
+
const replacement = added.map((content, index) => {
|
|
113
|
+
if (!removed)
|
|
114
|
+
return { content, eol: defaultEol };
|
|
115
|
+
const matchedRow = matchedRemoved.get(index);
|
|
116
|
+
if (matchedRow !== undefined)
|
|
117
|
+
return { content, eol: removedEntries[matchedRow].eol };
|
|
118
|
+
if (index === added.length - 1)
|
|
119
|
+
return { content, eol: removedEntries[removed - 1].eol };
|
|
120
|
+
if (index < removed - 1 && !matchedRows.has(index))
|
|
121
|
+
return { content, eol: removedEntries[index].eol };
|
|
122
|
+
return { content, eol: undefined };
|
|
123
|
+
});
|
|
124
|
+
// An inserted line takes the terminator of its neighbour in the replacement, not a distant one.
|
|
125
|
+
for (const [index, entry] of replacement.entries()) {
|
|
126
|
+
if (entry.eol !== undefined)
|
|
127
|
+
continue;
|
|
128
|
+
entry.eol =
|
|
129
|
+
replacement[index - 1]?.eol || replacement.slice(index + 1).find((later) => later.eol)?.eol || defaultEol;
|
|
130
|
+
}
|
|
131
|
+
// Only the file's last line may lack a terminator; one kept mid-replacement would join its neighbour.
|
|
132
|
+
for (const entry of replacement.slice(0, -1))
|
|
133
|
+
entry.eol ||= defaultEol;
|
|
134
|
+
// A block that ends at an unterminated EOF keeps its last line unterminated, even if that line was retained from earlier.
|
|
135
|
+
if (removed && !removedEntries[removed - 1].eol && row + removed === lineEntries.length && replacement.length) {
|
|
136
|
+
replacement[replacement.length - 1].eol = '';
|
|
137
|
+
}
|
|
138
|
+
return replacement.map(({ content, eol }) => ({ content, eol: eol ?? defaultEol }));
|
|
139
|
+
}
|
|
79
140
|
// Returns the new text, or { error } when the code no longer matches the scan.
|
|
80
141
|
function applyChangesToText(text, changes, { exactLocation = false, capture } = {}) {
|
|
81
|
-
const
|
|
82
|
-
const
|
|
142
|
+
const fallbackEol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
143
|
+
const lineEntries = splitLinesWithEndings(text);
|
|
144
|
+
const lines = lineEntries.map((entry) => entry.content);
|
|
83
145
|
const located = [];
|
|
84
146
|
for (const change of changes) {
|
|
85
147
|
const row = locateChange(lines, change);
|
|
@@ -110,10 +172,13 @@ function applyChangesToText(text, changes, { exactLocation = false, capture } =
|
|
|
110
172
|
return { error: 'overlapping changes' };
|
|
111
173
|
}
|
|
112
174
|
for (const { row, removed, added } of located) {
|
|
113
|
-
const
|
|
175
|
+
const removedEntries = lineEntries.slice(row, row + removed);
|
|
176
|
+
const replacement = buildReplacement(lineEntries, row, removed, added, fallbackEol);
|
|
177
|
+
lineEntries.splice(row, removed, ...replacement);
|
|
178
|
+
const original = removedEntries.map((entry) => entry.content);
|
|
114
179
|
capture?.({ file: changes[0].file, line: row + 1, before: original.join('\n'), after: added.join('\n') });
|
|
115
180
|
}
|
|
116
|
-
return { text:
|
|
181
|
+
return { text: lineEntries.map((entry) => entry.content + entry.eol).join('') };
|
|
117
182
|
}
|
|
118
183
|
// A change with `create: true` holds a whole new file. It refuses to overwrite a different existing
|
|
119
184
|
// file, and an identical one means the fix was already applied.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { packagePath } from '../shared/package-root.js';
|
|
5
|
+
import { writeResolvedFileAtomic } from '../shared/system/atomic-write.js';
|
|
6
|
+
import { absoluteSetting, editorDataDirectory, ensureEditorServer } from './setup-server.js';
|
|
7
|
+
function copyTemplate(relative, destination) {
|
|
8
|
+
const content = fs.readFileSync(packagePath('integrations', relative), 'utf8');
|
|
9
|
+
writeResolvedFileAtomic(destination, content);
|
|
10
|
+
}
|
|
11
|
+
function prepareZed(directory, server) {
|
|
12
|
+
fs.mkdirSync(path.join(directory, 'src'), { recursive: true });
|
|
13
|
+
for (const file of ['extension.toml', 'Cargo.toml', 'Cargo.lock', 'src/lib.rs']) {
|
|
14
|
+
copyTemplate('zed/' + file, path.join(directory, file));
|
|
15
|
+
}
|
|
16
|
+
writeResolvedFileAtomic(path.join(directory, 'server.json'), JSON.stringify([server.command, server.args[0]]));
|
|
17
|
+
return [
|
|
18
|
+
'In Zed run “zed: install dev extension” and select:',
|
|
19
|
+
directory,
|
|
20
|
+
'Zed compiles the extension using Rust installed via rustup. Open a supported file in a project folder.',
|
|
21
|
+
].join('\n');
|
|
22
|
+
}
|
|
23
|
+
function sublimePackages() {
|
|
24
|
+
const home = os.homedir();
|
|
25
|
+
if (process.platform === 'win32')
|
|
26
|
+
return path.join(absoluteSetting(process.env.APPDATA) || path.join(home, 'AppData', 'Roaming'), 'Sublime Text', 'Packages');
|
|
27
|
+
if (process.platform === 'darwin')
|
|
28
|
+
return path.join(home, 'Library', 'Application Support', 'Sublime Text', 'Packages');
|
|
29
|
+
return path.join(absoluteSetting(process.env.XDG_CONFIG_HOME) || path.join(home, '.config'), 'sublime-text', 'Packages');
|
|
30
|
+
}
|
|
31
|
+
const sublimePackage = 'LSP-loadwise';
|
|
32
|
+
function prepareSublime(directory, server, packages) {
|
|
33
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
34
|
+
const settings = {
|
|
35
|
+
command: ['${loadwise_node}', '${loadwise_cli}', 'lsp', '--stdio'],
|
|
36
|
+
selector: 'source.js, source.jsx, source.ts, source.tsx, text.html, source.vue, source.svelte, source.python, source.go, source.java, source.cs, source.rust',
|
|
37
|
+
schemes: ['file'],
|
|
38
|
+
};
|
|
39
|
+
writeResolvedFileAtomic(path.join(directory, sublimePackage + '.sublime-settings'), JSON.stringify(settings, null, 2));
|
|
40
|
+
writeResolvedFileAtomic(path.join(directory, 'runtime.json'), JSON.stringify({ loadwise_node: server.command, loadwise_cli: server.args[0] }));
|
|
41
|
+
// Sublime isolates Python hosts. LSP and its helper must load in the same host.
|
|
42
|
+
writeResolvedFileAtomic(path.join(directory, '.python-version'), '3.8\n');
|
|
43
|
+
copyTemplate('sublime/plugin.py', path.join(directory, 'plugin.py'));
|
|
44
|
+
const prerequisite = 'Install LSP with Package Control, then open a project folder and a supported source file.';
|
|
45
|
+
if (!fs.statSync(packages, { throwIfNoEntry: false })?.isDirectory())
|
|
46
|
+
return `In Sublime Text open Preferences > Browse Packages and copy this folder there:\n${directory}\n${prerequisite}`;
|
|
47
|
+
const target = path.join(packages, sublimePackage);
|
|
48
|
+
const existing = fs.lstatSync(target, { throwIfNoEntry: false });
|
|
49
|
+
if (!existing)
|
|
50
|
+
fs.symlinkSync(directory, target, process.platform === 'win32' ? 'junction' : 'dir');
|
|
51
|
+
else if (existing.isSymbolicLink() && !fs.statSync(target, { throwIfNoEntry: false }))
|
|
52
|
+
throw new Error(`The Sublime package link at ${target} has a missing target. Remove the stale link and rerun setup. The generated Loadwise package is at ${directory}.`);
|
|
53
|
+
else if (!existing.isSymbolicLink() || fs.realpathSync(target) !== fs.realpathSync(directory))
|
|
54
|
+
throw new Error(`Another Sublime package already exists at ${target}. The generated Loadwise package is at ${directory}.`);
|
|
55
|
+
return `Registered ${sublimePackage} in ${packages}.\n${prerequisite}`;
|
|
56
|
+
}
|
|
57
|
+
export async function setupConfiguredEditor(editor) {
|
|
58
|
+
const server = await ensureEditorServer();
|
|
59
|
+
const root = editorDataDirectory();
|
|
60
|
+
return editor === 'zed'
|
|
61
|
+
? prepareZed(path.join(root, 'zed'), server)
|
|
62
|
+
: prepareSublime(path.join(root, 'sublime', sublimePackage), server, sublimePackages());
|
|
63
|
+
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// Turns checker reports into language server diagnostics and hovers. Each published diagnostic keeps
|
|
2
2
|
// an anchor with what the code actions, code lenses and hovers need: the reported site, the
|
|
3
3
|
// scanner's fix and the dismissal entry.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
4
5
|
import fs from 'node:fs';
|
|
5
6
|
import path from 'node:path';
|
|
7
|
+
import * as ts from 'typescript';
|
|
6
8
|
import { pathToFileURL } from 'node:url';
|
|
7
9
|
import { DiagnosticSeverity } from 'vscode-languageserver';
|
|
8
10
|
import { exampleFor as reliabilityExample } from './reliability-examples.js';
|
|
@@ -169,14 +171,64 @@ function insideRoot(rootPath, file) {
|
|
|
169
171
|
function defaultUri(filename) {
|
|
170
172
|
return pathToFileURL(filename).href;
|
|
171
173
|
}
|
|
172
|
-
|
|
174
|
+
const dirtyLineMaps = new WeakMap();
|
|
175
|
+
// A report may stay published over several saves. Keep the original snapshot per reported site,
|
|
176
|
+
// retaining text only for findings of open buffers and only while their report is alive.
|
|
177
|
+
const reportedSources = new WeakMap();
|
|
178
|
+
const publishedSources = new WeakMap();
|
|
179
|
+
function liveLine(document, line, original, root) {
|
|
180
|
+
if (!document || (!document.isDirty && (!original || original.document === document)))
|
|
181
|
+
return line;
|
|
182
|
+
if (!original || (original.root !== root && !isRealPathInside(root, document.filename)))
|
|
183
|
+
return;
|
|
184
|
+
const saved = original.document;
|
|
185
|
+
let map = dirtyLineMaps.get(document);
|
|
186
|
+
if (map?.source !== saved) {
|
|
187
|
+
let prefix = 0;
|
|
188
|
+
let savedEnd = saved.lineCount;
|
|
189
|
+
let liveEnd = document.lineCount;
|
|
190
|
+
while (prefix < savedEnd && prefix < liveEnd && saved.lineAt(prefix).text === document.lineAt(prefix).text)
|
|
191
|
+
prefix++;
|
|
192
|
+
while (savedEnd > 0 && liveEnd > 0 && saved.lineAt(savedEnd - 1).text === document.lineAt(liveEnd - 1).text) {
|
|
193
|
+
savedEnd--;
|
|
194
|
+
liveEnd--;
|
|
195
|
+
}
|
|
196
|
+
// Equal lines at an insertion or deletion can belong to either side.
|
|
197
|
+
// Only positions common to both alignments have an unambiguous counterpart.
|
|
198
|
+
const overlap = saved.lineCount === document.lineCount ? 0 : Math.max(0, prefix - Math.min(savedEnd, liveEnd));
|
|
199
|
+
map = { source: saved, prefix: prefix - overlap, savedEnd: savedEnd + overlap, liveEnd: liveEnd + overlap };
|
|
200
|
+
dirtyLineMaps.set(document, map);
|
|
201
|
+
}
|
|
202
|
+
if (line <= map.prefix)
|
|
203
|
+
return line;
|
|
204
|
+
if (line > saved.lineCount)
|
|
205
|
+
return;
|
|
206
|
+
if (line > map.savedEnd)
|
|
207
|
+
return line + map.liveEnd - map.savedEnd;
|
|
208
|
+
if (map.savedEnd === map.prefix + 1 && map.liveEnd === map.prefix + 1)
|
|
209
|
+
return line;
|
|
210
|
+
}
|
|
211
|
+
function location(rootPath, site, options, reported) {
|
|
173
212
|
if (!isLocatedSite(site))
|
|
174
213
|
return;
|
|
175
214
|
const filename = insideRoot(rootPath, site.file);
|
|
176
215
|
if (filename === undefined)
|
|
177
216
|
return;
|
|
178
217
|
const uri = (options.uriFor ?? defaultUri)(filename);
|
|
179
|
-
|
|
218
|
+
const document = options.documentFor(filename);
|
|
219
|
+
const identity = reported ?? site;
|
|
220
|
+
let original = reportedSources.get(identity);
|
|
221
|
+
if (!original && document && document.version !== null && isRealPathInside(rootPath, filename)) {
|
|
222
|
+
const saved = document.isDirty ? options.savedDocumentFor?.(filename) : document;
|
|
223
|
+
if (saved) {
|
|
224
|
+
original = { root: rootPath, document: saved };
|
|
225
|
+
reportedSources.set(identity, original);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const line = liveLine(document, site.line, original, rootPath);
|
|
229
|
+
if (line === undefined)
|
|
230
|
+
return;
|
|
231
|
+
return { filename, uri, range: sourceRange({ line, column: site.column }, document), original };
|
|
180
232
|
}
|
|
181
233
|
// Resolves each change of a site fix inside the workspace folder; a path outside it, also through a
|
|
182
234
|
// symbolic link, drops the whole fix.
|
|
@@ -212,6 +264,8 @@ function severityFor(finding, setting) {
|
|
|
212
264
|
}
|
|
213
265
|
function readSavedLines(filename) {
|
|
214
266
|
try {
|
|
267
|
+
if (!fs.statSync(filename).isFile())
|
|
268
|
+
return [];
|
|
215
269
|
return fs.readFileSync(filename, 'utf8').split(/\r?\n/);
|
|
216
270
|
}
|
|
217
271
|
catch {
|
|
@@ -222,6 +276,8 @@ function readSavedLines(filename) {
|
|
|
222
276
|
// The trimmed text of the reported line identifies a dismissed finding. An edited buffer no longer
|
|
223
277
|
// matches the scan, so its line is read from the saved file.
|
|
224
278
|
function flaggedLineText(filename, line, options, savedLines) {
|
|
279
|
+
if (line < 1)
|
|
280
|
+
return '';
|
|
225
281
|
const document = options.documentFor(filename);
|
|
226
282
|
if (document && !document.isDirty)
|
|
227
283
|
return line <= document.lineCount ? document.lineAt(line - 1).text.trim() : '';
|
|
@@ -251,9 +307,13 @@ function buildDiagnostic(site, finding, anchor, options) {
|
|
|
251
307
|
const diagnostic = {
|
|
252
308
|
range: site.range,
|
|
253
309
|
message: preview ? preview + '\n' + anchor.message : anchor.message,
|
|
254
|
-
severity: severityFor(finding, options.severity),
|
|
310
|
+
severity: severityFor(finding, options.severityFor ? options.severityFor(site.filename) : options.severity),
|
|
255
311
|
source: anchor.source,
|
|
256
312
|
code: finding.ruleId,
|
|
313
|
+
// LSP clients can preserve this identity while their tracked ranges move in an unsaved buffer.
|
|
314
|
+
data: createHash('sha256')
|
|
315
|
+
.update(JSON.stringify([anchor.line, anchor.column, anchor.dismissal.lineText, anchor.message]))
|
|
316
|
+
.digest('hex'),
|
|
257
317
|
};
|
|
258
318
|
const documentation = ruleDocUrl(finding.ruleId);
|
|
259
319
|
if (documentation)
|
|
@@ -264,17 +324,16 @@ function publishedFinding(rootPath, source, reported, options, savedLines) {
|
|
|
264
324
|
const finding = databaseFinding(reported);
|
|
265
325
|
if (!isLocatedSite(finding) || typeof finding.message !== 'string' || typeof finding.ruleId !== 'string')
|
|
266
326
|
return;
|
|
267
|
-
const site = location(rootPath, finding, options);
|
|
327
|
+
const site = location(rootPath, finding, options, reported);
|
|
268
328
|
if (!site)
|
|
269
329
|
return;
|
|
270
330
|
const lineText = finding === reported
|
|
271
|
-
?
|
|
331
|
+
? (site.original?.document.lineAt(finding.line - 1).text.trim() ??
|
|
332
|
+
flaggedLineText(site.filename, finding.line, options, savedLines))
|
|
272
333
|
: typeof finding.target === 'string'
|
|
273
334
|
? finding.target
|
|
274
335
|
: undefined;
|
|
275
336
|
const dismissal = { file: site.filename, ruleId: finding.ruleId, lineText };
|
|
276
|
-
if (options.isDismissed?.(dismissal))
|
|
277
|
-
return;
|
|
278
337
|
const anchor = {
|
|
279
338
|
source,
|
|
280
339
|
ruleId: finding.ruleId,
|
|
@@ -290,12 +349,122 @@ function publishedFinding(rootPath, source, reported, options, savedLines) {
|
|
|
290
349
|
const related = relatedInformation(rootPath, finding, options);
|
|
291
350
|
if (related)
|
|
292
351
|
diagnostic.relatedInformation = related;
|
|
293
|
-
|
|
352
|
+
const entry = { filename: site.filename, uri: site.uri, diagnostic, anchor };
|
|
353
|
+
if (site.original)
|
|
354
|
+
publishedSources.set(entry, site.original);
|
|
355
|
+
return entry;
|
|
356
|
+
}
|
|
357
|
+
// Python reports use source lines rather than TypeScript nodes. Keep the enclosing declaration
|
|
358
|
+
// headers in the fingerprint so replacing the first function also invalidates its dismissal.
|
|
359
|
+
function indexPythonScopes(text) {
|
|
360
|
+
const declarations = [];
|
|
361
|
+
const scopes = text.split(/\r?\n/).map((line) => {
|
|
362
|
+
const code = line.trimStart();
|
|
363
|
+
const indent = line.length - code.length;
|
|
364
|
+
// A closing delimiter on a continuation line can align with its enclosing declaration.
|
|
365
|
+
if (code && !/^[#)\]}]/.test(code)) {
|
|
366
|
+
while (declarations.length && declarations[declarations.length - 1].indent >= indent)
|
|
367
|
+
declarations.pop();
|
|
368
|
+
}
|
|
369
|
+
const header = /^(?:(?:async\s+)?def|class)\s+([^\s(:[]+)/u.exec(code);
|
|
370
|
+
if (header) {
|
|
371
|
+
const names = [...(declarations.at(-1)?.names ?? []), header[1]];
|
|
372
|
+
declarations.push({ indent, names });
|
|
373
|
+
}
|
|
374
|
+
return declarations.at(-1)?.names ?? [];
|
|
375
|
+
});
|
|
376
|
+
return (line) => scopes[line - 1] ?? [];
|
|
377
|
+
}
|
|
378
|
+
// Walk a repeated-finding file once. Every named scope records its entry and exit offsets in
|
|
379
|
+
// source order, so lookups never rescan all sibling declarations for each diagnostic.
|
|
380
|
+
function indexScopes(file, text) {
|
|
381
|
+
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
|
|
382
|
+
const boundaries = [];
|
|
383
|
+
function visit(node, parents) {
|
|
384
|
+
const named = ts.isFunctionLike(node) ||
|
|
385
|
+
ts.isClassLike(node) ||
|
|
386
|
+
ts.isModuleDeclaration(node) ||
|
|
387
|
+
ts.isVariableDeclaration(node) ||
|
|
388
|
+
ts.isPropertyAssignment(node);
|
|
389
|
+
const names = named && node.name ? [...parents, node.name.getText(source)] : parents;
|
|
390
|
+
if (names !== parents)
|
|
391
|
+
boundaries.push({ offset: node.getStart(source), names });
|
|
392
|
+
ts.forEachChild(node, (child) => visit(child, names));
|
|
393
|
+
if (names !== parents)
|
|
394
|
+
boundaries.push({ offset: node.end, names: parents });
|
|
395
|
+
}
|
|
396
|
+
visit(source, []);
|
|
397
|
+
const starts = source.getLineStarts();
|
|
398
|
+
return (line, column) => {
|
|
399
|
+
const start = starts[line - 1];
|
|
400
|
+
if (start === undefined)
|
|
401
|
+
return [];
|
|
402
|
+
const offset = start + column - 1;
|
|
403
|
+
let lower = 0;
|
|
404
|
+
let upper = boundaries.length;
|
|
405
|
+
while (lower < upper) {
|
|
406
|
+
const middle = Math.floor((lower + upper) / 2);
|
|
407
|
+
if (boundaries[middle].offset <= offset)
|
|
408
|
+
lower = middle + 1;
|
|
409
|
+
else
|
|
410
|
+
upper = middle;
|
|
411
|
+
}
|
|
412
|
+
return boundaries[lower - 1]?.names ?? [];
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function identifyOccurrences(matches, options, savedLines, scopesByFile) {
|
|
416
|
+
if (matches.length === 1) {
|
|
417
|
+
matches[0].dismissal.occurrence = '1/1';
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
matches.sort((left, right) => left.line - right.line || left.column - right.column);
|
|
421
|
+
const file = matches[0].dismissal.file;
|
|
422
|
+
if (!scopesByFile.has(file) && /\.(?:[cm]?[jt]sx?|py)$/i.test(file)) {
|
|
423
|
+
const document = options.documentFor(file);
|
|
424
|
+
const text = document && !document.isDirty ? document.getText() : (savedLines.get(file) ?? []).join('\n');
|
|
425
|
+
scopesByFile.set(file, /\.py$/i.test(file) ? indexPythonScopes(text) : indexScopes(file, text));
|
|
426
|
+
}
|
|
427
|
+
const scopesAt = scopesByFile.get(file);
|
|
428
|
+
const contexts = matches.map(({ line, column }) => JSON.stringify([
|
|
429
|
+
scopesAt?.(line, column),
|
|
430
|
+
flaggedLineText(file, line - 1, options, savedLines),
|
|
431
|
+
column,
|
|
432
|
+
flaggedLineText(file, line + 1, options, savedLines),
|
|
433
|
+
]));
|
|
434
|
+
const groupHash = createHash('sha256').update(JSON.stringify(contexts));
|
|
435
|
+
if (new Set(contexts).size < matches.length) {
|
|
436
|
+
// The intervening source distinguishes otherwise identical sites in separate scopes, without
|
|
437
|
+
// binding the dismissal to unrelated lines above or below the matching group.
|
|
438
|
+
const document = options.documentFor(file);
|
|
439
|
+
const lineCount = document && !document.isDirty ? document.lineCount : (savedLines.get(file)?.length ?? 0);
|
|
440
|
+
const lastLine = Math.min(matches[matches.length - 1].line, lineCount);
|
|
441
|
+
for (let line = matches[0].line; line <= lastLine; line++) {
|
|
442
|
+
groupHash.update('\n').update(flaggedLineText(file, line, options, savedLines));
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
const group = groupHash.digest('hex');
|
|
446
|
+
for (const [index, anchor] of matches.entries()) {
|
|
447
|
+
anchor.dismissal.occurrence = index + 1 + '/' + matches.length + '#' + group;
|
|
448
|
+
}
|
|
294
449
|
}
|
|
295
450
|
/** The diagnostics of one checker report, skipping findings outside the folder or dismissed. */
|
|
296
451
|
function buildDiagnostics(rootPath, source, findings, options) {
|
|
297
452
|
const savedLines = new Map();
|
|
298
|
-
|
|
453
|
+
const entries = findings.flatMap((finding) => publishedFinding(rootPath, source, finding, options, savedLines) ?? []);
|
|
454
|
+
const matchingLines = new Map();
|
|
455
|
+
for (const { anchor } of entries) {
|
|
456
|
+
const { file, ruleId, lineText } = anchor.dismissal;
|
|
457
|
+
const key = JSON.stringify([file, ruleId, lineText]);
|
|
458
|
+
const matches = matchingLines.get(key);
|
|
459
|
+
if (matches)
|
|
460
|
+
matches.push(anchor);
|
|
461
|
+
else
|
|
462
|
+
matchingLines.set(key, [anchor]);
|
|
463
|
+
}
|
|
464
|
+
const scopesByFile = new Map();
|
|
465
|
+
for (const matches of matchingLines.values())
|
|
466
|
+
identifyOccurrences(matches, options, savedLines, scopesByFile);
|
|
467
|
+
return entries.filter(({ anchor }) => !options.isDismissed?.(anchor.dismissal));
|
|
299
468
|
}
|
|
300
469
|
// The editor renders hovers as markdown; finding text is shown literally.
|
|
301
470
|
function escapeMarkdown(text) {
|
|
@@ -320,13 +489,12 @@ function comparisonMarkdown(comparison, example, document, ruleId) {
|
|
|
320
489
|
}
|
|
321
490
|
return parts;
|
|
322
491
|
}
|
|
323
|
-
function hoverMarkdown(document,
|
|
324
|
-
const {
|
|
325
|
-
|
|
326
|
-
if (!comparison && !example)
|
|
492
|
+
function hoverMarkdown(document, { anchor, diagnostic }, range) {
|
|
493
|
+
const { example, comparison } = examplesFor(document, range, anchor);
|
|
494
|
+
if (!comparison && !example && !anchor.message)
|
|
327
495
|
return;
|
|
328
496
|
const parts = [];
|
|
329
|
-
const firstLine = recommendation(document,
|
|
497
|
+
const firstLine = recommendation(document, range, anchor);
|
|
330
498
|
if (firstLine)
|
|
331
499
|
parts.push('**' + escapeMarkdown(firstLine) + '**');
|
|
332
500
|
parts.push(paragraphs(anchor.message));
|
|
@@ -338,20 +506,41 @@ function hoverMarkdown(document, entry) {
|
|
|
338
506
|
const note = comparison ? comparison.note : example?.note;
|
|
339
507
|
if (note)
|
|
340
508
|
parts.push(paragraphs(note));
|
|
509
|
+
const docsHref = diagnostic.codeDescription?.href;
|
|
510
|
+
if (!comparison && !example && docsHref)
|
|
511
|
+
parts.push(`[${escapeMarkdown(anchor.ruleId)}](${docsHref})`);
|
|
341
512
|
return parts.join('\n\n');
|
|
342
513
|
}
|
|
514
|
+
function indentation(text) {
|
|
515
|
+
return text.length - text.trimStart().length;
|
|
516
|
+
}
|
|
343
517
|
/** The hover for a position: one section per rule flagged there, or undefined. */
|
|
344
|
-
function hoverFor(document, entries, position) {
|
|
518
|
+
function hoverFor(document, entries, position, root) {
|
|
345
519
|
const sections = [];
|
|
346
520
|
const shown = new Set();
|
|
347
521
|
let hoverRange;
|
|
348
522
|
const word = wordRangeAt(document, position);
|
|
523
|
+
const currentLine = document.lineAt(position.line).text.trim();
|
|
349
524
|
for (const entry of entries) {
|
|
350
|
-
|
|
525
|
+
let issueRange = entry.diagnostic.range;
|
|
526
|
+
const original = publishedSources.get(entry);
|
|
527
|
+
if (document.isDirty || (original && original.document !== document)) {
|
|
528
|
+
const originalText = original?.document.lineAt(entry.anchor.line - 1).text;
|
|
529
|
+
if (originalText?.trim() !== currentLine)
|
|
530
|
+
continue;
|
|
531
|
+
const line = liveLine(document, entry.anchor.line, original, root);
|
|
532
|
+
if (line !== position.line + 1)
|
|
533
|
+
continue;
|
|
534
|
+
// Indentation edits move the flagged token, so shift the saved column by the indent change.
|
|
535
|
+
const column = entry.anchor.column + indentation(document.lineAt(position.line).text) - indentation(originalText);
|
|
536
|
+
if (column < 1)
|
|
537
|
+
continue;
|
|
538
|
+
issueRange = sourceRange({ line, column }, document);
|
|
539
|
+
}
|
|
351
540
|
const range = word && samePosition(word.start, issueRange.start) ? word : issueRange;
|
|
352
541
|
if (!rangeContains(range, position) || shown.has(entry.anchor.ruleId))
|
|
353
542
|
continue;
|
|
354
|
-
const markdown = hoverMarkdown(document, entry);
|
|
543
|
+
const markdown = hoverMarkdown(document, entry, issueRange);
|
|
355
544
|
if (!markdown)
|
|
356
545
|
continue;
|
|
357
546
|
sections.push(markdown);
|