loadwise 0.5.0 → 0.6.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 +543 -628
- package/bin/loadwise.js +5 -1
- package/lib/accessibility/frontend-detect.js +2 -1
- package/lib/accessibility/rule-ids.js +12 -9
- package/lib/accessibility/template-attributes.js +4 -2
- package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
- package/lib/editor/actions.js +117 -0
- package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
- package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
- package/lib/editor/diagnostics.js +365 -0
- package/lib/editor/dismissals.js +111 -0
- package/lib/editor/editor-document.js +99 -0
- package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
- package/lib/editor/fix-edits.js +200 -0
- package/lib/editor/language-server.js +437 -0
- package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
- package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
- package/lib/editor/perf-watch.js +78 -0
- package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
- package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
- package/lib/editor/scan-session.js +334 -0
- package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
- package/lib/editor/server-commands.js +232 -0
- package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
- package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
- package/lib/editor/types/dismissal.js +1 -0
- package/lib/editor/types/fix-example.js +1 -0
- package/lib/editor/types/source-document.js +1 -0
- package/lib/editor/workspace-files.js +78 -0
- package/lib/editor/workspace-paths.js +22 -0
- package/lib/maintainability/analyze-source.js +2 -0
- package/lib/maintainability/apply-fix.js +1 -1
- package/lib/maintainability/cli.js +1 -1
- package/lib/maintainability/examples.js +58 -41
- package/lib/maintainability/rule-ids.js +29 -14
- package/lib/maintainability/scan-changed.js +3 -0
- package/lib/maintainability/scan.js +13 -9
- package/lib/maintainability/tsconfig-strict.js +69 -0
- package/lib/maintainability/type-safety-hygiene.js +204 -0
- package/lib/performance/analyze.js +2 -0
- package/lib/performance/cli-arguments.js +0 -2
- package/lib/performance/cli-policy.js +17 -9
- package/lib/performance/cli-scan.js +10 -8
- package/lib/performance/cli.js +4 -23
- package/lib/performance/editor-signal.js +1 -1
- package/lib/performance/finding-text.js +3 -3
- package/lib/performance/fix-cli.js +1 -1
- package/lib/performance/frontend-perf.js +7 -0
- package/lib/performance/frontend-render-perf.js +200 -0
- package/lib/performance/llm-max-tokens.js +56 -0
- package/lib/performance/native.js +46 -26
- package/lib/performance/polyglot.js +22 -1
- package/lib/performance/pooling.js +38 -23
- package/lib/performance/projects.js +42 -21
- package/lib/performance/rule-ids.js +236 -222
- package/lib/performance/site-fixes/database.js +3 -1
- package/lib/performance/site-fixes/integrity.js +15 -1
- package/lib/performance/source-inputs.js +18 -6
- package/lib/performance/unscanned-javascript.js +66 -19
- package/lib/reliability/analyze.js +12 -0
- package/lib/reliability/child-process.js +106 -0
- package/lib/reliability/error-values.js +177 -0
- package/lib/reliability/pool-timeout.js +79 -0
- package/lib/reliability/react-bugs.js +602 -0
- package/lib/reliability/resource-leaks.js +3 -6
- package/lib/reliability/rule-ids.js +169 -127
- package/lib/reliability/switch-exhaustive.js +284 -0
- package/lib/reliability/uncaught-exception.js +223 -0
- package/lib/security/auth-crypto/rule-ids.js +3 -2
- package/lib/security/cli.js +6 -5
- package/lib/security/deps/rule-ids.js +1 -0
- package/lib/security/examples/auth-crypto.cjs +5 -4
- package/lib/security/examples/deps.cjs +1 -0
- package/lib/security/examples/exposure.cjs +55 -42
- package/lib/security/examples/files.cjs +1 -0
- package/lib/security/examples/injection.cjs +1 -0
- package/lib/security/examples/moved.cjs +5 -4
- package/lib/security/examples/request-forgery.cjs +1 -0
- package/lib/security/exposure/client-env.js +113 -0
- package/lib/security/exposure/frontend-security.js +12 -10
- package/lib/security/exposure/index.js +14 -3
- package/lib/security/exposure/jsx-url.js +267 -0
- package/lib/security/exposure/next-image-config.js +34 -0
- package/lib/security/exposure/package-manifest.js +45 -0
- package/lib/security/exposure/react-version.js +45 -0
- package/lib/security/exposure/rule-ids.js +16 -12
- package/lib/security/files/index.js +1 -1
- package/lib/security/files/rule-ids.js +1 -0
- package/lib/security/injection/code.js +24 -10
- package/lib/security/injection/command.js +81 -28
- package/lib/security/injection/nosql.js +109 -22
- package/lib/security/injection/redos.js +152 -308
- package/lib/security/injection/regex-pattern.js +290 -0
- package/lib/security/injection/regex.js +30 -11
- package/lib/security/injection/rule-ids.js +2 -1
- package/lib/security/injection/shared.js +19 -1
- package/lib/security/injection/sql.js +83 -2
- package/lib/security/request-forgery/rule-ids.js +1 -0
- package/lib/security/rule-descriptions.js +36 -32
- package/lib/security/rule-ids.js +74 -67
- package/lib/security/taint/filename-guard.js +3 -1
- package/lib/security/taint/guards.js +84 -10
- package/lib/security/taint/index.js +124 -13
- package/lib/security/taint/propagate.js +10 -7
- package/lib/security/taint/sanitizers.js +7 -3
- package/lib/security/taint/sources.js +6 -3
- package/lib/security/taint/summaries.js +13 -1
- package/lib/security/taint/url-parts.js +14 -5
- package/lib/shared/agent-session.js +2 -2
- package/lib/shared/check.js +16 -6
- package/lib/shared/explain.js +5 -5
- package/lib/shared/fix-convergence.js +1 -1
- package/lib/shared/formats/finding-location.js +6 -2
- package/lib/shared/formats/sarif.js +3 -3
- package/lib/shared/heap-limit.js +20 -3
- package/lib/shared/pillars.js +7 -7
- package/lib/shared/rule-docs.js +12 -0
- package/lib/shared/scan-cache.js +0 -1
- package/lib/shared/workspaces.js +31 -9
- package/package.json +12 -19
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/schema/loadwise.config.schema.json +44 -0
- package/editor/README.md +0 -47
- package/examples/redis-keys.otlp.json +0 -22
- package/lib/maintainability/notify-editor.js +0 -1
- package/lib/performance/editor-report.js +0 -191
- package/lib/performance/editor-setup.js +0 -189
- package/lib/performance/editor-watch-supervisor.js +0 -104
- package/lib/performance/editor-watch.js +0 -193
- package/lib/performance/notify-editor.js +0 -1
- package/lib/performance/recursive-watch.js +0 -181
- /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
// Turns checker reports into language server diagnostics and hovers. Each published diagnostic keeps
|
|
2
|
+
// an anchor with what the code actions, code lenses and hovers need: the reported site, the
|
|
3
|
+
// scanner's fix and the dismissal entry.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { DiagnosticSeverity } from 'vscode-languageserver';
|
|
8
|
+
import { exampleFor as reliabilityExample } from './reliability-examples.js';
|
|
9
|
+
import { exampleFor as maintainabilityExample } from './maintainability-examples.js';
|
|
10
|
+
import { exampleFor as securityExample } from './security-examples.js';
|
|
11
|
+
import { exampleFor as accessibilityExample } from './accessibility-examples.js';
|
|
12
|
+
import { getFindingComparison, inlineComparison } from './finding-comparison.js';
|
|
13
|
+
import { rangeContains, samePosition, validateRange, wordRangeAt } from './editor-document.js';
|
|
14
|
+
import { isRealPathInside } from './workspace-paths.js';
|
|
15
|
+
import { ruleDocUrl } from '../shared/rule-docs.js';
|
|
16
|
+
const maintainabilitySource = 'loadwise maint';
|
|
17
|
+
const severityNames = {
|
|
18
|
+
error: DiagnosticSeverity.Error,
|
|
19
|
+
warning: DiagnosticSeverity.Warning,
|
|
20
|
+
information: DiagnosticSeverity.Information,
|
|
21
|
+
hint: DiagnosticSeverity.Hint,
|
|
22
|
+
};
|
|
23
|
+
const polyglotLanguages = new Set(['python', 'go', 'java', 'csharp', 'rust', 'php', 'ruby', 'kotlin', 'c', 'cpp']);
|
|
24
|
+
const contracts = new Set([
|
|
25
|
+
'pg-transaction-on-pool',
|
|
26
|
+
'folder-boundary',
|
|
27
|
+
'file-placement',
|
|
28
|
+
'query-mutates-state',
|
|
29
|
+
'data-access-boundary',
|
|
30
|
+
]);
|
|
31
|
+
const advice = new Map([
|
|
32
|
+
[
|
|
33
|
+
'dependency-cycle',
|
|
34
|
+
'Follow the imports in the reported cycle. Move a shared dependency into a module that both sides can import, or pass it to the caller explicitly.',
|
|
35
|
+
],
|
|
36
|
+
[
|
|
37
|
+
'folder-boundary',
|
|
38
|
+
'Use an API the importing layer is allowed to call, or move the code that needs this dependency into the layer that owns it.',
|
|
39
|
+
],
|
|
40
|
+
['file-placement', 'Move the file to one of the configured folders and update its imports.'],
|
|
41
|
+
]);
|
|
42
|
+
function sourceExample(ruleId, languageId, message) {
|
|
43
|
+
// Reliability examples fall back to the performance ones, so one lookup covers the shared source pass.
|
|
44
|
+
return (reliabilityExample(ruleId, languageId, message) ??
|
|
45
|
+
securityExample(ruleId, languageId) ??
|
|
46
|
+
accessibilityExample(ruleId, languageId));
|
|
47
|
+
}
|
|
48
|
+
// ast-grep counts Unicode code points; editor positions and TypeScript use UTF-16.
|
|
49
|
+
function utf16Column(document, line, codePoints) {
|
|
50
|
+
let remaining = codePoints;
|
|
51
|
+
let column = 0;
|
|
52
|
+
for (const character of document.lineAt(line).text) {
|
|
53
|
+
if (remaining === 0)
|
|
54
|
+
break;
|
|
55
|
+
column += character.length;
|
|
56
|
+
remaining--;
|
|
57
|
+
}
|
|
58
|
+
return column;
|
|
59
|
+
}
|
|
60
|
+
function sourceRange(site, document) {
|
|
61
|
+
const line = site.line - 1;
|
|
62
|
+
let column = site.column - 1;
|
|
63
|
+
if (document && polyglotLanguages.has(document.languageId) && line < document.lineCount && column > 0) {
|
|
64
|
+
column = utf16Column(document, line, column);
|
|
65
|
+
}
|
|
66
|
+
const anchor = { start: { line, character: column }, end: { line, character: column + 1 } };
|
|
67
|
+
if (!document)
|
|
68
|
+
return anchor;
|
|
69
|
+
const range = validateRange(document, anchor);
|
|
70
|
+
const word = wordRangeAt(document, range.start);
|
|
71
|
+
return word && samePosition(word.start, range.start) ? word : range;
|
|
72
|
+
}
|
|
73
|
+
const sentenceEnds = '.!?';
|
|
74
|
+
// Findings are written as short paragraphs; one sentence per line is easier to read in a tooltip.
|
|
75
|
+
// Code spans are kept whole, and a break needs a capital, backtick or parenthesis after the space,
|
|
76
|
+
// so "e.g. x" stays together.
|
|
77
|
+
function sentenceLines(text) {
|
|
78
|
+
const lines = [];
|
|
79
|
+
let start = 0;
|
|
80
|
+
let inCode = false;
|
|
81
|
+
for (let index = 0; index < text.length; index++) {
|
|
82
|
+
const character = text[index];
|
|
83
|
+
if (character === '`')
|
|
84
|
+
inCode = !inCode;
|
|
85
|
+
else if (!inCode &&
|
|
86
|
+
sentenceEnds.includes(character) &&
|
|
87
|
+
text[index + 1] === ' ' &&
|
|
88
|
+
/[A-Z`(]/.test(text[index + 2] ?? '')) {
|
|
89
|
+
lines.push(text.slice(start, index + 1));
|
|
90
|
+
start = index + 2;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
lines.push(text.slice(start));
|
|
94
|
+
return lines.map((line) => line.trim()).filter(Boolean);
|
|
95
|
+
}
|
|
96
|
+
function readable(text) {
|
|
97
|
+
return text.split('\n').flatMap(sentenceLines).join('\n');
|
|
98
|
+
}
|
|
99
|
+
function dedent(text) {
|
|
100
|
+
const lines = text.split('\n');
|
|
101
|
+
const width = Math.min(...lines.filter((line) => line.trim()).map((line) => /^[ \t]*/.exec(line)?.[0].length ?? 0));
|
|
102
|
+
return lines.map((line) => line.slice(width)).join('\n');
|
|
103
|
+
}
|
|
104
|
+
// The scanner's rewrite of this exact code; the generic rule example is only a fallback.
|
|
105
|
+
function fixComparison(fix) {
|
|
106
|
+
const shown = fix.changes.find((change) => !change.create) ?? fix.changes[0];
|
|
107
|
+
const others = fix.changes.filter((change) => change !== shown);
|
|
108
|
+
const created = others.filter((change) => change.create).map((change) => change.file);
|
|
109
|
+
const edited = others.length - created.length;
|
|
110
|
+
const more = (edited ? ' Also changes ' + edited + ' more place(s).' : '') +
|
|
111
|
+
(created.length ? ' Also creates ' + created.join(', ') + '.' : '');
|
|
112
|
+
return {
|
|
113
|
+
kind: 'source',
|
|
114
|
+
before: shown.create ? '(new file ' + shown.file + ')' : dedent(shown.before),
|
|
115
|
+
after: shown.create ? shown.after.trimEnd() : dedent(shown.after),
|
|
116
|
+
note: ((fix.note ?? '') +
|
|
117
|
+
more +
|
|
118
|
+
(fix.requiresReview ? ' Review this change and apply it individually.' : '') +
|
|
119
|
+
' Use the Apply fix code action or the code lens above the line.').trim(),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function examplesFor(document, range, anchor) {
|
|
123
|
+
// Every source checker but maintainability shares the source examples, which fall back to the
|
|
124
|
+
// security ones.
|
|
125
|
+
const lookup = anchor.source === maintainabilitySource ? maintainabilityExample : sourceExample;
|
|
126
|
+
const example = lookup(anchor.ruleId, document.languageId, anchor.message);
|
|
127
|
+
if (anchor.fix)
|
|
128
|
+
return { example, comparison: fixComparison(anchor.fix) };
|
|
129
|
+
const comparison = getFindingComparison(document, {
|
|
130
|
+
source: anchor.source,
|
|
131
|
+
code: anchor.ruleId,
|
|
132
|
+
message: anchor.message,
|
|
133
|
+
suggestion: anchor.suggestion,
|
|
134
|
+
comparison: anchor.comparison,
|
|
135
|
+
range,
|
|
136
|
+
}, example);
|
|
137
|
+
return { example, comparison };
|
|
138
|
+
}
|
|
139
|
+
/** The one-line recommendation shown before the finding, or undefined without a comparison. */
|
|
140
|
+
function recommendation(document, range, anchor) {
|
|
141
|
+
const { comparison } = examplesFor(document, range, anchor);
|
|
142
|
+
const preview = comparison && inlineComparison(comparison);
|
|
143
|
+
if (!comparison || !preview)
|
|
144
|
+
return;
|
|
145
|
+
return (comparison.kind === 'source' ? 'Code: ' : '') + preview;
|
|
146
|
+
}
|
|
147
|
+
function isLocatedSite(site) {
|
|
148
|
+
if (typeof site !== 'object' || site === null)
|
|
149
|
+
return false;
|
|
150
|
+
if (!('file' in site) || !('line' in site) || !('column' in site))
|
|
151
|
+
return false;
|
|
152
|
+
return (typeof site.file === 'string' &&
|
|
153
|
+
site.file !== '' &&
|
|
154
|
+
!site.file.includes('\0') &&
|
|
155
|
+
typeof site.line === 'number' &&
|
|
156
|
+
Number.isSafeInteger(site.line) &&
|
|
157
|
+
site.line >= 1 &&
|
|
158
|
+
typeof site.column === 'number' &&
|
|
159
|
+
Number.isSafeInteger(site.column) &&
|
|
160
|
+
site.column >= 1);
|
|
161
|
+
}
|
|
162
|
+
function insideRoot(rootPath, file) {
|
|
163
|
+
const filename = path.resolve(rootPath, file);
|
|
164
|
+
const relative = path.relative(rootPath, filename);
|
|
165
|
+
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
|
|
166
|
+
return;
|
|
167
|
+
return filename;
|
|
168
|
+
}
|
|
169
|
+
function defaultUri(filename) {
|
|
170
|
+
return pathToFileURL(filename).href;
|
|
171
|
+
}
|
|
172
|
+
function location(rootPath, site, options) {
|
|
173
|
+
if (!isLocatedSite(site))
|
|
174
|
+
return;
|
|
175
|
+
const filename = insideRoot(rootPath, site.file);
|
|
176
|
+
if (filename === undefined)
|
|
177
|
+
return;
|
|
178
|
+
const uri = (options.uriFor ?? defaultUri)(filename);
|
|
179
|
+
return { filename, uri, range: sourceRange(site, options.documentFor(filename)) };
|
|
180
|
+
}
|
|
181
|
+
// Resolves each change of a site fix inside the workspace folder; a path outside it, also through a
|
|
182
|
+
// symbolic link, drops the whole fix.
|
|
183
|
+
function workspaceFix(rootPath, fix) {
|
|
184
|
+
if (!fix || !Array.isArray(fix.changes) || !fix.changes.length)
|
|
185
|
+
return;
|
|
186
|
+
const changes = [];
|
|
187
|
+
for (const change of fix.changes) {
|
|
188
|
+
if (typeof change?.file !== 'string' ||
|
|
189
|
+
change.file.includes('\0') ||
|
|
190
|
+
typeof change.before !== 'string' ||
|
|
191
|
+
typeof change.after !== 'string')
|
|
192
|
+
return;
|
|
193
|
+
if (!Number.isSafeInteger(change.line) || change.line < 1)
|
|
194
|
+
return;
|
|
195
|
+
const filename = insideRoot(rootPath, change.file);
|
|
196
|
+
if (filename === undefined || !isRealPathInside(rootPath, filename))
|
|
197
|
+
return;
|
|
198
|
+
changes.push({ ...change, filename });
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
changes,
|
|
202
|
+
note: typeof fix.note === 'string' ? fix.note : undefined,
|
|
203
|
+
requiresReview: fix.requiresReview === true,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
// Every finding is an optional suggestion: a warning by default, an error for a declared contract,
|
|
207
|
+
// unless the loadwise.severity setting picks one level for all of them.
|
|
208
|
+
function severityFor(finding, setting) {
|
|
209
|
+
const isError = finding.level === 'error' || (finding.level !== 'warn' && contracts.has(finding.ruleId));
|
|
210
|
+
const chosen = setting === undefined ? undefined : severityNames[setting];
|
|
211
|
+
return chosen ?? (isError ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning);
|
|
212
|
+
}
|
|
213
|
+
function readSavedLines(filename) {
|
|
214
|
+
try {
|
|
215
|
+
return fs.readFileSync(filename, 'utf8').split(/\r?\n/);
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
// A file deleted since the scan has no line text; its findings disappear on the next scan.
|
|
219
|
+
return [];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// The trimmed text of the reported line identifies a dismissed finding. An edited buffer no longer
|
|
223
|
+
// matches the scan, so its line is read from the saved file.
|
|
224
|
+
function flaggedLineText(filename, line, options, savedLines) {
|
|
225
|
+
const document = options.documentFor(filename);
|
|
226
|
+
if (document && !document.isDirty)
|
|
227
|
+
return line <= document.lineCount ? document.lineAt(line - 1).text.trim() : '';
|
|
228
|
+
if (!savedLines.has(filename))
|
|
229
|
+
savedLines.set(filename, readSavedLines(filename));
|
|
230
|
+
return ((savedLines.get(filename) ?? [])[line - 1] ?? '').trim();
|
|
231
|
+
}
|
|
232
|
+
// A live-database finding names a table, not a file. It is shown on the first line of the project's
|
|
233
|
+
// package.json, prefixed by the table, and dismissed by table name.
|
|
234
|
+
function databaseFinding(finding) {
|
|
235
|
+
if (finding.file !== undefined || typeof finding.target !== 'string' || typeof finding.message !== 'string')
|
|
236
|
+
return finding;
|
|
237
|
+
return { ...finding, file: 'package.json', line: 1, column: 1, message: finding.target + ': ' + finding.message };
|
|
238
|
+
}
|
|
239
|
+
function relatedInformation(rootPath, finding, options) {
|
|
240
|
+
if (!Array.isArray(finding.related))
|
|
241
|
+
return;
|
|
242
|
+
const label = finding.ruleId === 'dependency-cycle' ? 'Import in this cycle' : 'Matching implementation';
|
|
243
|
+
return finding.related.flatMap((item) => {
|
|
244
|
+
const link = location(rootPath, item, options);
|
|
245
|
+
return link ? [{ location: { uri: link.uri, range: link.range }, message: label }] : [];
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function buildDiagnostic(site, finding, anchor, options) {
|
|
249
|
+
const document = options.documentFor(site.filename);
|
|
250
|
+
const preview = document && recommendation(document, site.range, anchor);
|
|
251
|
+
const diagnostic = {
|
|
252
|
+
range: site.range,
|
|
253
|
+
message: preview ? preview + '\n' + anchor.message : anchor.message,
|
|
254
|
+
severity: severityFor(finding, options.severity),
|
|
255
|
+
source: anchor.source,
|
|
256
|
+
code: finding.ruleId,
|
|
257
|
+
};
|
|
258
|
+
const documentation = ruleDocUrl(finding.ruleId);
|
|
259
|
+
if (documentation)
|
|
260
|
+
diagnostic.codeDescription = { href: documentation };
|
|
261
|
+
return diagnostic;
|
|
262
|
+
}
|
|
263
|
+
function publishedFinding(rootPath, source, reported, options, savedLines) {
|
|
264
|
+
const finding = databaseFinding(reported);
|
|
265
|
+
if (!isLocatedSite(finding) || typeof finding.message !== 'string' || typeof finding.ruleId !== 'string')
|
|
266
|
+
return;
|
|
267
|
+
const site = location(rootPath, finding, options);
|
|
268
|
+
if (!site)
|
|
269
|
+
return;
|
|
270
|
+
const lineText = finding === reported
|
|
271
|
+
? flaggedLineText(site.filename, finding.line, options, savedLines)
|
|
272
|
+
: typeof finding.target === 'string'
|
|
273
|
+
? finding.target
|
|
274
|
+
: undefined;
|
|
275
|
+
const dismissal = { file: site.filename, ruleId: finding.ruleId, lineText };
|
|
276
|
+
if (options.isDismissed?.(dismissal))
|
|
277
|
+
return;
|
|
278
|
+
const anchor = {
|
|
279
|
+
source,
|
|
280
|
+
ruleId: finding.ruleId,
|
|
281
|
+
line: finding.line,
|
|
282
|
+
column: finding.column,
|
|
283
|
+
message: readable([finding.message, advice.get(finding.ruleId), finding.contextualReason].filter(Boolean).join('\n')),
|
|
284
|
+
suggestion: finding.suggestion,
|
|
285
|
+
comparison: finding.comparison,
|
|
286
|
+
fix: workspaceFix(rootPath, finding.fix),
|
|
287
|
+
dismissal,
|
|
288
|
+
};
|
|
289
|
+
const diagnostic = buildDiagnostic(site, finding, anchor, options);
|
|
290
|
+
const related = relatedInformation(rootPath, finding, options);
|
|
291
|
+
if (related)
|
|
292
|
+
diagnostic.relatedInformation = related;
|
|
293
|
+
return { filename: site.filename, uri: site.uri, diagnostic, anchor };
|
|
294
|
+
}
|
|
295
|
+
/** The diagnostics of one checker report, skipping findings outside the folder or dismissed. */
|
|
296
|
+
function buildDiagnostics(rootPath, source, findings, options) {
|
|
297
|
+
const savedLines = new Map();
|
|
298
|
+
return findings.flatMap((finding) => publishedFinding(rootPath, source, finding, options, savedLines) ?? []);
|
|
299
|
+
}
|
|
300
|
+
// The editor renders hovers as markdown; finding text is shown literally.
|
|
301
|
+
function escapeMarkdown(text) {
|
|
302
|
+
return text.replaceAll(/[\\`*_{}[\]()#+\-.!|<>~]/g, '\\$&');
|
|
303
|
+
}
|
|
304
|
+
function paragraphs(text) {
|
|
305
|
+
return readable(text).split('\n').map(escapeMarkdown).join('\n\n');
|
|
306
|
+
}
|
|
307
|
+
function codeBlock(code, language) {
|
|
308
|
+
const longestFence = Math.max(2, ...[...code.matchAll(/`+/g)].map((match) => match[0].length));
|
|
309
|
+
const fence = '`'.repeat(longestFence + 1);
|
|
310
|
+
return fence + language + '\n' + code + '\n' + fence;
|
|
311
|
+
}
|
|
312
|
+
function comparisonMarkdown(comparison, example, document, ruleId) {
|
|
313
|
+
const label = (comparison.kind === 'source' ? 'Current code' : 'Flagged line') + ' (' + ruleId + ')';
|
|
314
|
+
const parts = [escapeMarkdown(label), codeBlock(comparison.before, document.languageId)];
|
|
315
|
+
if (comparison.kind === 'review')
|
|
316
|
+
parts.push(escapeMarkdown('Review: ' + comparison.inline));
|
|
317
|
+
else {
|
|
318
|
+
parts.push(comparison.kind === 'source' ? 'Suggested rewrite' : 'Illustrative alternative');
|
|
319
|
+
parts.push(codeBlock(comparison.after, comparison.language ?? example?.language ?? document.languageId));
|
|
320
|
+
}
|
|
321
|
+
return parts;
|
|
322
|
+
}
|
|
323
|
+
function hoverMarkdown(document, entry) {
|
|
324
|
+
const { anchor, diagnostic } = entry;
|
|
325
|
+
const { example, comparison } = examplesFor(document, diagnostic.range, anchor);
|
|
326
|
+
if (!comparison && !example)
|
|
327
|
+
return;
|
|
328
|
+
const parts = [];
|
|
329
|
+
const firstLine = recommendation(document, diagnostic.range, anchor);
|
|
330
|
+
if (firstLine)
|
|
331
|
+
parts.push('**' + escapeMarkdown(firstLine) + '**');
|
|
332
|
+
parts.push(paragraphs(anchor.message));
|
|
333
|
+
if (comparison)
|
|
334
|
+
parts.push(...comparisonMarkdown(comparison, example, document, anchor.ruleId));
|
|
335
|
+
else if (example) {
|
|
336
|
+
parts.push(escapeMarkdown('Illustrative alternative (' + anchor.ruleId + ')'), codeBlock(example.code, example.language));
|
|
337
|
+
}
|
|
338
|
+
const note = comparison ? comparison.note : example?.note;
|
|
339
|
+
if (note)
|
|
340
|
+
parts.push(paragraphs(note));
|
|
341
|
+
return parts.join('\n\n');
|
|
342
|
+
}
|
|
343
|
+
/** The hover for a position: one section per rule flagged there, or undefined. */
|
|
344
|
+
function hoverFor(document, entries, position) {
|
|
345
|
+
const sections = [];
|
|
346
|
+
const shown = new Set();
|
|
347
|
+
let hoverRange;
|
|
348
|
+
const word = wordRangeAt(document, position);
|
|
349
|
+
for (const entry of entries) {
|
|
350
|
+
const issueRange = entry.diagnostic.range;
|
|
351
|
+
const range = word && samePosition(word.start, issueRange.start) ? word : issueRange;
|
|
352
|
+
if (!rangeContains(range, position) || shown.has(entry.anchor.ruleId))
|
|
353
|
+
continue;
|
|
354
|
+
const markdown = hoverMarkdown(document, entry);
|
|
355
|
+
if (!markdown)
|
|
356
|
+
continue;
|
|
357
|
+
sections.push(markdown);
|
|
358
|
+
shown.add(entry.anchor.ruleId);
|
|
359
|
+
hoverRange ??= range;
|
|
360
|
+
}
|
|
361
|
+
if (!sections.length || !hoverRange)
|
|
362
|
+
return;
|
|
363
|
+
return { markdown: sections.join('\n\n---\n\n'), range: hoverRange };
|
|
364
|
+
}
|
|
365
|
+
export { buildDiagnostics, hoverFor };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Dismissed findings live in .loadwise/dismissed.json at the workspace folder root, never in the
|
|
2
|
+
// user's code. A finding is matched by file, rule and the trimmed text of its flagged line, so it
|
|
3
|
+
// stays hidden across rescans and line shifts and returns once that line changes. An entry without
|
|
4
|
+
// line text hides the rule for the whole file. Paths are stored relative to the folder, so the file
|
|
5
|
+
// can be shared through version control.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { writeFileAtomic } from '../shared/atomic-write.js';
|
|
9
|
+
import { errorMessage } from '../shared/error-code.js';
|
|
10
|
+
import { isRecord } from '../shared/is-record.js';
|
|
11
|
+
import { isRealPathInside } from './workspace-paths.js';
|
|
12
|
+
const dismissalsPath = path.join('.loadwise', 'dismissed.json');
|
|
13
|
+
// The file is read synchronously on every change to it; a file this large is not a list of
|
|
14
|
+
// dismissals anyone curates, and parsing it would stall the server.
|
|
15
|
+
const maxDismissalBytes = 4 * 1024 * 1024;
|
|
16
|
+
function keyOf({ file, ruleId, lineText }) {
|
|
17
|
+
return JSON.stringify([file, ruleId, lineText ?? null]);
|
|
18
|
+
}
|
|
19
|
+
function storedEntry(root, stored) {
|
|
20
|
+
if (!isRecord(stored) || typeof stored.file !== 'string' || typeof stored.ruleId !== 'string')
|
|
21
|
+
return;
|
|
22
|
+
if (stored.file.includes('\0'))
|
|
23
|
+
return;
|
|
24
|
+
const entry = { file: path.resolve(root, stored.file), ruleId: stored.ruleId };
|
|
25
|
+
if (typeof stored.lineText === 'string')
|
|
26
|
+
entry.lineText = stored.lineText;
|
|
27
|
+
return entry;
|
|
28
|
+
}
|
|
29
|
+
function readEntries(filename, root) {
|
|
30
|
+
let stored;
|
|
31
|
+
try {
|
|
32
|
+
const size = fs.statSync(filename, { throwIfNoEntry: false })?.size;
|
|
33
|
+
if (size === undefined)
|
|
34
|
+
return { entries: [] };
|
|
35
|
+
if (size > maxDismissalBytes)
|
|
36
|
+
return { problem: 'is larger than ' + maxDismissalBytes / 1024 / 1024 + ' MB' };
|
|
37
|
+
stored = JSON.parse(fs.readFileSync(filename, 'utf8'));
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
return { problem: 'cannot be read: ' + errorMessage(error) };
|
|
41
|
+
}
|
|
42
|
+
if (!Array.isArray(stored))
|
|
43
|
+
return { problem: 'does not hold a list of dismissals' };
|
|
44
|
+
return { entries: stored.flatMap((item) => storedEntry(root, item) ?? []) };
|
|
45
|
+
}
|
|
46
|
+
function serialize(root, entries) {
|
|
47
|
+
const stored = entries.map(({ file, ruleId, lineText }) => ({
|
|
48
|
+
file: path.relative(root, file).split(path.sep).join('/'),
|
|
49
|
+
ruleId,
|
|
50
|
+
...(typeof lineText === 'string' ? { lineText } : {}),
|
|
51
|
+
}));
|
|
52
|
+
return JSON.stringify(stored, null, 2) + '\n';
|
|
53
|
+
}
|
|
54
|
+
function createDismissals(root, { onProblem }) {
|
|
55
|
+
const filename = path.join(root, dismissalsPath);
|
|
56
|
+
const describe = (problem) => dismissalsPath.split(path.sep).join('/') + ' in ' + root + ' ' + problem + '.';
|
|
57
|
+
let current = [];
|
|
58
|
+
let keys = new Set();
|
|
59
|
+
let pendingWrite = Promise.resolve();
|
|
60
|
+
function replace(next) {
|
|
61
|
+
current = next;
|
|
62
|
+
keys = new Set(current.map(keyOf));
|
|
63
|
+
}
|
|
64
|
+
// A file that does not parse keeps the dismissals already shown: it may be mid-rewrite by a
|
|
65
|
+
// checkout, and an edit the user is still making should not flood the editor with findings.
|
|
66
|
+
function load() {
|
|
67
|
+
const stored = readEntries(filename, root);
|
|
68
|
+
if (stored.entries)
|
|
69
|
+
replace(stored.entries);
|
|
70
|
+
else
|
|
71
|
+
onProblem(describe(stored.problem));
|
|
72
|
+
}
|
|
73
|
+
// Writes run one after another, each on the latest saved entries, so quick dismissals never lose
|
|
74
|
+
// one. The shown state changes only once the file holds it.
|
|
75
|
+
function update(transform) {
|
|
76
|
+
const next = pendingWrite
|
|
77
|
+
.catch(() => { })
|
|
78
|
+
.then(() => {
|
|
79
|
+
const stored = readEntries(filename, root);
|
|
80
|
+
if (stored.entries === undefined) {
|
|
81
|
+
throw new Error(describe(stored.problem) + ' Fix or remove it, then try again; it was left unchanged.');
|
|
82
|
+
}
|
|
83
|
+
if (!isRealPathInside(root, filename)) {
|
|
84
|
+
throw new Error(describe('resolves outside the workspace folder') + ' Nothing was written.');
|
|
85
|
+
}
|
|
86
|
+
const entries = transform(stored.entries);
|
|
87
|
+
fs.mkdirSync(path.dirname(filename), { recursive: true });
|
|
88
|
+
writeFileAtomic(filename, serialize(root, entries));
|
|
89
|
+
replace(entries);
|
|
90
|
+
});
|
|
91
|
+
pendingWrite = next;
|
|
92
|
+
return next;
|
|
93
|
+
}
|
|
94
|
+
load();
|
|
95
|
+
return {
|
|
96
|
+
entries: () => [...current],
|
|
97
|
+
has(site) {
|
|
98
|
+
return keys.has(keyOf(site)) || keys.has(keyOf({ file: site.file, ruleId: site.ruleId }));
|
|
99
|
+
},
|
|
100
|
+
add(entry) {
|
|
101
|
+
const key = keyOf(entry);
|
|
102
|
+
return update((entries) => [...entries.filter((existing) => keyOf(existing) !== key), entry]);
|
|
103
|
+
},
|
|
104
|
+
remove(removed) {
|
|
105
|
+
const gone = new Set(removed.map(keyOf));
|
|
106
|
+
return update((entries) => entries.filter((entry) => !gone.has(keyOf(entry))));
|
|
107
|
+
},
|
|
108
|
+
reload: load,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
export { createDismissals, dismissalsPath };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// The text of a source file as the language server sees it: the editor's open buffer when there is
|
|
2
|
+
// one, otherwise the file on disk. Diagnostics, hovers and fixes all read files through this shape.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
const languageBySuffix = {
|
|
6
|
+
ts: 'typescript',
|
|
7
|
+
mts: 'typescript',
|
|
8
|
+
cts: 'typescript',
|
|
9
|
+
tsx: 'typescriptreact',
|
|
10
|
+
js: 'javascript',
|
|
11
|
+
mjs: 'javascript',
|
|
12
|
+
cjs: 'javascript',
|
|
13
|
+
jsx: 'javascriptreact',
|
|
14
|
+
py: 'python',
|
|
15
|
+
go: 'go',
|
|
16
|
+
java: 'java',
|
|
17
|
+
cs: 'csharp',
|
|
18
|
+
rs: 'rust',
|
|
19
|
+
rb: 'ruby',
|
|
20
|
+
php: 'php',
|
|
21
|
+
kt: 'kotlin',
|
|
22
|
+
kts: 'kotlin',
|
|
23
|
+
c: 'c',
|
|
24
|
+
h: 'c',
|
|
25
|
+
cc: 'cpp',
|
|
26
|
+
cpp: 'cpp',
|
|
27
|
+
cxx: 'cpp',
|
|
28
|
+
hpp: 'cpp',
|
|
29
|
+
hh: 'cpp',
|
|
30
|
+
hxx: 'cpp',
|
|
31
|
+
sql: 'sql',
|
|
32
|
+
json: 'json',
|
|
33
|
+
prisma: 'prisma',
|
|
34
|
+
html: 'html',
|
|
35
|
+
vue: 'vue',
|
|
36
|
+
svelte: 'svelte',
|
|
37
|
+
};
|
|
38
|
+
// VS Code's default word definition, so a diagnostic covers the same token in every editor.
|
|
39
|
+
const wordPattern = /(-?\d*\.\d\w*)|([^`~!@#$%^&*()\-=+[{\]}\\|;:'",.<>/?\s]+)/g;
|
|
40
|
+
function languageIdOf(filename) {
|
|
41
|
+
return languageBySuffix[path.extname(filename).slice(1).toLowerCase()] ?? 'plaintext';
|
|
42
|
+
}
|
|
43
|
+
function createEditorDocument(filename, text, { languageId = languageIdOf(filename), version = null, isDirty = false } = {}) {
|
|
44
|
+
const lines = text.split(/\r?\n/);
|
|
45
|
+
return {
|
|
46
|
+
filename,
|
|
47
|
+
languageId,
|
|
48
|
+
version,
|
|
49
|
+
isDirty,
|
|
50
|
+
eol: text.includes('\r\n') ? '\r\n' : '\n',
|
|
51
|
+
lineCount: lines.length,
|
|
52
|
+
lineAt: (line) => ({ text: lines[line] ?? '' }),
|
|
53
|
+
getText: () => text,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function readDiskDocument(filename) {
|
|
57
|
+
try {
|
|
58
|
+
return createEditorDocument(filename, fs.readFileSync(filename, 'utf8'));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// A file deleted since the scan has no text; its findings disappear on the next scan.
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function clampPosition(document, position) {
|
|
66
|
+
if (position.line < 0)
|
|
67
|
+
return { line: 0, character: 0 };
|
|
68
|
+
if (position.line >= document.lineCount) {
|
|
69
|
+
const lastLine = document.lineCount - 1;
|
|
70
|
+
return { line: lastLine, character: document.lineAt(lastLine).text.length };
|
|
71
|
+
}
|
|
72
|
+
const length = document.lineAt(position.line).text.length;
|
|
73
|
+
return { line: position.line, character: Math.max(0, Math.min(position.character, length)) };
|
|
74
|
+
}
|
|
75
|
+
function validateRange(document, range) {
|
|
76
|
+
return { start: clampPosition(document, range.start), end: clampPosition(document, range.end) };
|
|
77
|
+
}
|
|
78
|
+
function wordRangeAt(document, position) {
|
|
79
|
+
if (position.line < 0 || position.line >= document.lineCount)
|
|
80
|
+
return;
|
|
81
|
+
const text = document.lineAt(position.line).text;
|
|
82
|
+
for (const match of text.matchAll(wordPattern)) {
|
|
83
|
+
const start = match.index;
|
|
84
|
+
const end = start + match[0].length;
|
|
85
|
+
if (start <= position.character && position.character <= end) {
|
|
86
|
+
return { start: { line: position.line, character: start }, end: { line: position.line, character: end } };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function samePosition(left, right) {
|
|
91
|
+
return left.line === right.line && left.character === right.character;
|
|
92
|
+
}
|
|
93
|
+
function comparePositions(left, right) {
|
|
94
|
+
return left.line - right.line || left.character - right.character;
|
|
95
|
+
}
|
|
96
|
+
function rangeContains(range, position) {
|
|
97
|
+
return comparePositions(range.start, position) <= 0 && comparePositions(position, range.end) <= 0;
|
|
98
|
+
}
|
|
99
|
+
export { createEditorDocument, rangeContains, readDiskDocument, samePosition, validateRange, wordRangeAt };
|
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
exports.getFindingComparison = getFindingComparison;
|
|
4
|
-
exports.inlineComparison = inlineComparison;
|
|
5
|
-
const control_flow_comparison_cjs_1 = require("./control-flow-comparison.cjs");
|
|
6
|
-
const source_example_cjs_1 = require("./source-example.cjs");
|
|
1
|
+
import { controlFlowComparison } from './control-flow-comparison.js';
|
|
2
|
+
import { sourceExampleFor } from './source-example.js';
|
|
7
3
|
const maxExcerptLength = 220;
|
|
8
4
|
const maxInlineLength = 150;
|
|
9
5
|
const controls = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
|
|
@@ -29,7 +25,7 @@ function getFindingComparison(document, diagnostic, example) {
|
|
|
29
25
|
const text = document.lineAt(position.line).text;
|
|
30
26
|
if (position.character < 0 || position.character > text.length || !text.trim())
|
|
31
27
|
return;
|
|
32
|
-
const rewrite =
|
|
28
|
+
const rewrite = controlFlowComparison(document, diagnostic) ?? sourceExampleFor(document, diagnostic);
|
|
33
29
|
if (rewrite) {
|
|
34
30
|
return {
|
|
35
31
|
kind: 'source',
|
|
@@ -75,3 +71,4 @@ function inlineComparison(comparison) {
|
|
|
75
71
|
const action = comparison.message?.match(/(?:^|[.!?] )((?:Use|Consider|Compile|Reuse|Build|Move|Batch|Fetch|Bind|Pass|Replace|Prefer|Push|Keep|Check|Review)\b[^\n]*?)(?:\.(?:\s|$)|$)/i)?.[1];
|
|
76
72
|
return shorten('Review: ' + cleanLine(action || comparison.note || comparison.message || comparison.after.split('\n')[0]));
|
|
77
73
|
}
|
|
74
|
+
export { getFindingComparison, inlineComparison };
|