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,204 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { walkNodes } from './walk.js';
|
|
3
|
+
import { generatedSource } from './duplicates.js';
|
|
4
|
+
import { isVendoredMinified } from '../shared/execution-context.js';
|
|
5
|
+
import { isVendoredOrSamplePath } from './source-exclusions.js';
|
|
6
|
+
const TEST_FILE = /(?:^|\/)(?:tests?|__tests__|specs?|e2e|integration-tests?|cypress)\/|\.(?:test|spec|e2e|e2e-spec|cy)\.[cm]?[jt]sx?$/i;
|
|
7
|
+
// Code generators (GraphQL codegen, Prisma, OpenAPI clients) write casts and directives the team cannot edit.
|
|
8
|
+
const GENERATED_PATH = /(?:^|\/)(?:__generated__|generated[\w-]*|gen)\/|\.(?:generated|gen)\.[cm]?[jt]sx?$/i;
|
|
9
|
+
const TYPESCRIPT_FILE = /\.[cm]?tsx?$/i;
|
|
10
|
+
const FOCUSABLE_RUNNERS = new Set(['describe', 'it', 'test', 'suite']);
|
|
11
|
+
// Jasmine's focused forms, which are plain functions rather than `.only` members.
|
|
12
|
+
const JASMINE_FOCUSED = new Set(['fit', 'fdescribe']);
|
|
13
|
+
// The compiler reads a directive from the last line of a comment, where a block comment's `*` gutter may precede it.
|
|
14
|
+
const SUPPRESSION_DIRECTIVE = /^\s*(?:[/*]\s*)*@ts-(ignore|expect-error|nocheck)\b(.*)$/s;
|
|
15
|
+
const WORD_CHARACTER = /[\p{L}\p{N}]/u;
|
|
16
|
+
const WATCHED_DIRECTIVE = /@ts-(?:ignore|expect-error|nocheck)/;
|
|
17
|
+
// `test.concurrent.only(...)` and `test.describe.serial.only(...)` still focus the runner.
|
|
18
|
+
const RUNNER_MODIFIERS = new Set(['concurrent', 'sequential', 'serial', 'parallel', 'describe']);
|
|
19
|
+
// A runner imported under another name (`import { test as nodeTest } from 'node:test'`) is still a runner.
|
|
20
|
+
function runnerNamesOf(sourceFile) {
|
|
21
|
+
const names = new Set(FOCUSABLE_RUNNERS);
|
|
22
|
+
for (const statement of sourceFile.statements) {
|
|
23
|
+
if (!ts.isImportDeclaration(statement))
|
|
24
|
+
continue;
|
|
25
|
+
const bindings = statement.importClause?.namedBindings;
|
|
26
|
+
if (!bindings || !ts.isNamedImports(bindings))
|
|
27
|
+
continue;
|
|
28
|
+
for (const specifier of bindings.elements) {
|
|
29
|
+
if (specifier.propertyName && FOCUSABLE_RUNNERS.has(specifier.propertyName.text)) {
|
|
30
|
+
names.add(specifier.name.text);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return names;
|
|
35
|
+
}
|
|
36
|
+
function isFocusableRunner(node, runnerNames) {
|
|
37
|
+
if (ts.isIdentifier(node))
|
|
38
|
+
return runnerNames.has(node.text);
|
|
39
|
+
if (ts.isCallExpression(node)) {
|
|
40
|
+
// `it.each(cases).only(...)`
|
|
41
|
+
const callee = node.expression;
|
|
42
|
+
return (ts.isPropertyAccessExpression(callee) &&
|
|
43
|
+
callee.name.text === 'each' &&
|
|
44
|
+
isFocusableRunner(callee.expression, runnerNames));
|
|
45
|
+
}
|
|
46
|
+
return (ts.isPropertyAccessExpression(node) &&
|
|
47
|
+
RUNNER_MODIFIERS.has(node.name.text) &&
|
|
48
|
+
isFocusableRunner(node.expression, runnerNames));
|
|
49
|
+
}
|
|
50
|
+
function focusedMemberName(node) {
|
|
51
|
+
if (ts.isPropertyAccessExpression(node))
|
|
52
|
+
return node.name.text;
|
|
53
|
+
if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
|
|
54
|
+
return node.argumentExpression.text;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function isInvokedMember(node) {
|
|
58
|
+
const { parent } = node;
|
|
59
|
+
if (ts.isCallExpression(parent))
|
|
60
|
+
return parent.expression === node;
|
|
61
|
+
return ts.isTaggedTemplateExpression(parent) && parent.tag === node;
|
|
62
|
+
}
|
|
63
|
+
function isFocusedMember(node, runnerNames) {
|
|
64
|
+
if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node))
|
|
65
|
+
return false;
|
|
66
|
+
if (focusedMemberName(node) !== 'only' || !isFocusableRunner(node.expression, runnerNames))
|
|
67
|
+
return false;
|
|
68
|
+
// `it.only(...)` and `describe.only.each(table)(...)` run focused; a bare `it.only` or `it.only.each` reference does not.
|
|
69
|
+
const { parent } = node;
|
|
70
|
+
if (isInvokedMember(node))
|
|
71
|
+
return true;
|
|
72
|
+
return ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) &&
|
|
73
|
+
parent.expression === node &&
|
|
74
|
+
focusedMemberName(parent) === 'each' &&
|
|
75
|
+
isInvokedMember(parent));
|
|
76
|
+
}
|
|
77
|
+
function isJasmineFocusedCall(node) {
|
|
78
|
+
if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
|
|
79
|
+
return false;
|
|
80
|
+
if (!JASMINE_FOCUSED.has(node.expression.text))
|
|
81
|
+
return false;
|
|
82
|
+
// `fit` is also a common name outside test runners, so a title string must lead the arguments.
|
|
83
|
+
const [title] = node.arguments;
|
|
84
|
+
return title !== undefined && ts.isStringLiteralLike(title);
|
|
85
|
+
}
|
|
86
|
+
function findingAt(sourceFile, file, position, { ruleId, message }) {
|
|
87
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(position);
|
|
88
|
+
return { file, line: line + 1, column: character + 1, ruleId, message };
|
|
89
|
+
}
|
|
90
|
+
function isExcludedSource(file, sourceFile) {
|
|
91
|
+
const normalized = file.replaceAll('\\', '/');
|
|
92
|
+
return (isVendoredOrSamplePath(normalized) ||
|
|
93
|
+
GENERATED_PATH.test(normalized) ||
|
|
94
|
+
/\.d\.[cm]?ts$/i.test(normalized) ||
|
|
95
|
+
isVendoredMinified(file) ||
|
|
96
|
+
Boolean(generatedSource(sourceFile, file)));
|
|
97
|
+
}
|
|
98
|
+
function isTestFile(file) {
|
|
99
|
+
return TEST_FILE.test(file.replaceAll('\\', '/'));
|
|
100
|
+
}
|
|
101
|
+
function checkFocusedTests(sourceFile, file) {
|
|
102
|
+
if (!isTestFile(file) || !/\bonly\b|\bf(?:it|describe)\b/.test(sourceFile.text))
|
|
103
|
+
return [];
|
|
104
|
+
const findings = [];
|
|
105
|
+
const runnerNames = runnerNamesOf(sourceFile);
|
|
106
|
+
walkNodes(sourceFile, (node) => {
|
|
107
|
+
if (!isFocusedMember(node, runnerNames) && !isJasmineFocusedCall(node))
|
|
108
|
+
return;
|
|
109
|
+
findings.push(findingAt(sourceFile, file, node.getStart(sourceFile), {
|
|
110
|
+
ruleId: 'focused-test-committed',
|
|
111
|
+
message: 'A focused test (`.only`, `fit` or `fdescribe`) makes the runner skip every other test, so CI passes while most of the suite never runs. Remove the focus before committing.',
|
|
112
|
+
}));
|
|
113
|
+
});
|
|
114
|
+
return findings;
|
|
115
|
+
}
|
|
116
|
+
function suppressionReason(commentText) {
|
|
117
|
+
const lastNewline = commentText.lastIndexOf('\n');
|
|
118
|
+
const match = SUPPRESSION_DIRECTIVE.exec(commentText.slice(lastNewline + 1));
|
|
119
|
+
if (!match)
|
|
120
|
+
return;
|
|
121
|
+
// Text after the directive counts as a reason only when it holds a word, so `-` or `*/` alone do not.
|
|
122
|
+
const afterDirective = match[2].replace(/\*\/\s*$/, '');
|
|
123
|
+
// Earlier lines of a block comment may already explain the suppression.
|
|
124
|
+
const precedingLines = commentText.slice(0, Math.max(lastNewline, 0));
|
|
125
|
+
return { directive: match[1], hasReason: WORD_CHARACTER.test(afterDirective) || WORD_CHARACTER.test(precedingLines) };
|
|
126
|
+
}
|
|
127
|
+
function commentRangesOf(sourceFile) {
|
|
128
|
+
const seenPositions = new Set();
|
|
129
|
+
const seenComments = new Set();
|
|
130
|
+
const ranges = [];
|
|
131
|
+
walkNodes(sourceFile, (node) => {
|
|
132
|
+
if (seenPositions.has(node.pos))
|
|
133
|
+
return;
|
|
134
|
+
seenPositions.add(node.pos);
|
|
135
|
+
// A directive after code on the same line (`setup(); // @ts-ignore`) is a trailing comment of the previous token.
|
|
136
|
+
const found = [
|
|
137
|
+
...(ts.getLeadingCommentRanges(sourceFile.text, node.pos) ?? []),
|
|
138
|
+
...(ts.getTrailingCommentRanges(sourceFile.text, node.pos) ?? []),
|
|
139
|
+
];
|
|
140
|
+
for (const range of found) {
|
|
141
|
+
if (seenComments.has(range.pos))
|
|
142
|
+
continue;
|
|
143
|
+
seenComments.add(range.pos);
|
|
144
|
+
ranges.push(range);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
return ranges;
|
|
148
|
+
}
|
|
149
|
+
function checkSuppressionReasons(sourceFile, file) {
|
|
150
|
+
if (!WATCHED_DIRECTIVE.test(sourceFile.text))
|
|
151
|
+
return [];
|
|
152
|
+
const findings = [];
|
|
153
|
+
for (const range of commentRangesOf(sourceFile)) {
|
|
154
|
+
const result = suppressionReason(sourceFile.text.slice(range.pos, range.end));
|
|
155
|
+
if (!result || result.hasReason)
|
|
156
|
+
continue;
|
|
157
|
+
findings.push(findingAt(sourceFile, file, range.pos, {
|
|
158
|
+
ruleId: 'ts-suppression-without-reason',
|
|
159
|
+
message: `\`@ts-${result.directive}\` silences the compiler with no explanation, so a later reader cannot tell whether the error is still real. Add the reason after the directive, or fix the type error.`,
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
return findings;
|
|
163
|
+
}
|
|
164
|
+
function unwrapParentheses(node) {
|
|
165
|
+
return ts.isParenthesizedExpression(node) ? unwrapParentheses(node.expression) : node;
|
|
166
|
+
}
|
|
167
|
+
function isTypeAssertion(node) {
|
|
168
|
+
return ts.isAsExpression(node) || ts.isTypeAssertionExpression(node);
|
|
169
|
+
}
|
|
170
|
+
function isDoubleAssertion(node) {
|
|
171
|
+
if (!isTypeAssertion(node))
|
|
172
|
+
return false;
|
|
173
|
+
const inner = unwrapParentheses(node.expression);
|
|
174
|
+
return (isTypeAssertion(inner) &&
|
|
175
|
+
(inner.type.kind === ts.SyntaxKind.UnknownKeyword || inner.type.kind === ts.SyntaxKind.AnyKeyword));
|
|
176
|
+
}
|
|
177
|
+
function checkDoubleTypeAssertions(sourceFile, file) {
|
|
178
|
+
// Tests cast through `unknown` to build partial mocks, which is the accepted way to do it there.
|
|
179
|
+
if (!TYPESCRIPT_FILE.test(file) || isTestFile(file))
|
|
180
|
+
return [];
|
|
181
|
+
// A comment may sit between `as` and the type, so the cheap prefilter only looks for both words.
|
|
182
|
+
if (!/\bas\b|<[^>]*>/.test(sourceFile.text) || !/\b(?:unknown|any)\b/.test(sourceFile.text))
|
|
183
|
+
return [];
|
|
184
|
+
const findings = [];
|
|
185
|
+
walkNodes(sourceFile, (node) => {
|
|
186
|
+
if (!isDoubleAssertion(node))
|
|
187
|
+
return;
|
|
188
|
+
findings.push(findingAt(sourceFile, file, node.getStart(sourceFile), {
|
|
189
|
+
ruleId: 'double-type-assertion',
|
|
190
|
+
message: 'Casting through `unknown` or `any` to a second type turns the type checker off for this value, so a wrong shape fails at runtime instead. Narrow the value with a type guard or validate it, or fix the declared type.',
|
|
191
|
+
}));
|
|
192
|
+
});
|
|
193
|
+
return findings;
|
|
194
|
+
}
|
|
195
|
+
function checkTypeSafetyHygiene(sourceFile, file) {
|
|
196
|
+
if (isExcludedSource(file, sourceFile))
|
|
197
|
+
return [];
|
|
198
|
+
return [
|
|
199
|
+
...checkFocusedTests(sourceFile, file),
|
|
200
|
+
...checkSuppressionReasons(sourceFile, file),
|
|
201
|
+
...checkDoubleTypeAssertions(sourceFile, file),
|
|
202
|
+
];
|
|
203
|
+
}
|
|
204
|
+
export { checkTypeSafetyHygiene };
|
|
@@ -44,6 +44,7 @@ import { checkPromiseAwait } from './awaits.js';
|
|
|
44
44
|
import { checkSortExtreme } from './sort-extreme.js';
|
|
45
45
|
import { checkNodeBlockingCall, flushBlockingCalls } from './node-fs.js';
|
|
46
46
|
import { checkPoolCreation } from './pooling.js';
|
|
47
|
+
import { check as checkLlmMaxTokens } from './llm-max-tokens.js';
|
|
47
48
|
import { checkCollectionCall, checkCollectionAssignment } from './collections.js';
|
|
48
49
|
import { isRepeated } from './repeated.js';
|
|
49
50
|
import { isTestSource, reviewedReason, reviewMarkers, repeatedReviewContext } from './review-context.js';
|
|
@@ -91,6 +92,7 @@ const callRules = [
|
|
|
91
92
|
checkOffsetPagination,
|
|
92
93
|
checkListCounts,
|
|
93
94
|
checkNotificationLoops,
|
|
95
|
+
checkLlmMaxTokens,
|
|
94
96
|
checkSessionStore,
|
|
95
97
|
checkCartesianIncludes,
|
|
96
98
|
checkRetryBackoff,
|
|
@@ -8,8 +8,6 @@ const usage = `Usage:
|
|
|
8
8
|
loadwise perf traces trace.json [--threshold 5] [--json]
|
|
9
9
|
loadwise perf plan explain.json [--json]
|
|
10
10
|
loadwise perf polyglot <file-or-directory> ... [--json]
|
|
11
|
-
loadwise perf editor init
|
|
12
|
-
loadwise perf editor watch [-p tsconfig.json]
|
|
13
11
|
loadwise perf agent init [--mode ask|auto] [--hook [block|warn|off]]
|
|
14
12
|
|
|
15
13
|
With no arguments, check tsconfig.json or jsconfig.json in the current directory.
|
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { loadConfig } from '../shared/config.js';
|
|
4
4
|
import { resolveConfig } from './source-inputs.js';
|
|
5
5
|
import { validateQueryPolicy, loadQueryPolicy } from './query-policy.js';
|
|
6
|
-
import { discoverWorkspaces, projectConfig, selectWorkspaces } from '../shared/workspaces.js';
|
|
6
|
+
import { configlessSources, discoverWorkspaces, projectConfig, selectWorkspaces, uncheckedWorkspaces, } from '../shared/workspaces.js';
|
|
7
7
|
import { errorMessage } from './cli-arguments.js';
|
|
8
8
|
// The folder holding loadwise.config.json: the project, or the working directory for files.
|
|
9
9
|
export function projectDirectory(config, files) {
|
|
@@ -43,8 +43,13 @@ export function sourcePolicy(explicit, settings) {
|
|
|
43
43
|
},
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
|
+
function noteUncheckedWorkspaces(withoutConfig) {
|
|
47
|
+
for (const { name } of uncheckedWorkspaces(withoutConfig)) {
|
|
48
|
+
console.error(`Note: workspace ${name} has no tsconfig.json or jsconfig.json, and a sub-folder's own tsconfig.json or jsconfig.json holds its sources; skipped it. Add a tsconfig.json to the package to check it.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
46
51
|
// A directory without its own config, or an explicit --workspace, means a monorepo: one config per
|
|
47
|
-
// package.
|
|
52
|
+
// package, and the sources of each package without one, checked with the standalone defaults.
|
|
48
53
|
export function workspaceTarget(values, positionals) {
|
|
49
54
|
const directory = path.resolve(values.project ?? '.');
|
|
50
55
|
const isDirectory = fs.statSync(directory, { throwIfNoEntry: false })?.isDirectory();
|
|
@@ -56,18 +61,21 @@ export function workspaceTarget(values, positionals) {
|
|
|
56
61
|
if (!values.workspace.length && projectConfig(directory))
|
|
57
62
|
return undefined;
|
|
58
63
|
const { packages, withoutConfig } = discoverWorkspaces(directory);
|
|
59
|
-
|
|
64
|
+
const configless = withoutConfig.flatMap((workspace) => {
|
|
65
|
+
const sources = configlessSources(workspace.directory);
|
|
66
|
+
return sources ? [{ ...workspace, sources }] : [];
|
|
67
|
+
});
|
|
68
|
+
noteUncheckedWorkspaces(withoutConfig);
|
|
69
|
+
if (!packages.length && !configless.length) {
|
|
60
70
|
if (values.workspace.length)
|
|
61
|
-
throw new Error('--workspace found no workspace package with
|
|
71
|
+
throw new Error('--workspace found no workspace package with JavaScript or TypeScript.');
|
|
62
72
|
return undefined;
|
|
63
73
|
}
|
|
64
|
-
|
|
65
|
-
console.error(`Note: workspace ${name} has no tsconfig.json or jsconfig.json; skipped it.`);
|
|
66
|
-
}
|
|
67
|
-
const chosen = selectWorkspaces(packages, directory, values.workspace);
|
|
74
|
+
const chosen = selectWorkspaces([...packages, ...configless], directory, values.workspace);
|
|
68
75
|
return {
|
|
69
76
|
directory,
|
|
70
|
-
configs: chosen.
|
|
77
|
+
configs: chosen.flatMap((workspace) => ('config' in workspace ? [workspace.config] : [])),
|
|
78
|
+
standaloneFiles: chosen.flatMap((workspace) => ('sources' in workspace ? workspace.sources : [])),
|
|
71
79
|
packages: chosen.map(({ name, directory: packageDirectory }) => ({
|
|
72
80
|
name,
|
|
73
81
|
directory: relativeToCwd(packageDirectory),
|
|
@@ -8,9 +8,9 @@ import { baselineForScan } from '../shared/baseline.js';
|
|
|
8
8
|
import { resolveFormat } from '../shared/formats/index.js';
|
|
9
9
|
import { fixPresentation } from '../shared/fix-presentation.js';
|
|
10
10
|
import { editorAnalyzers, exitCodeWithSkips, noteEmptyIgnoredScan, reportSourceResult } from './scan-outcome.js';
|
|
11
|
-
import { coveringConfig,
|
|
11
|
+
import { coveringConfig, configlessSources, projectConfig } from '../shared/workspaces.js';
|
|
12
12
|
import { enableCompileCache } from 'node:module';
|
|
13
|
-
import { notifyEditor } from '
|
|
13
|
+
import { notifyEditor } from '../shared/notify-editor.js';
|
|
14
14
|
import { sourceHistoryProject } from '../shared/fix-history.js';
|
|
15
15
|
import { applyChosenFixes, applyFixes } from './fix-cli.js';
|
|
16
16
|
import { findProjectRoot, loadSnapshot, useSnapshot } from './schema/context.js';
|
|
@@ -65,7 +65,7 @@ function markupScan({ values, workspace, scope, markupFiles, hasNamedSources })
|
|
|
65
65
|
return { scannedFiles: 0, findings: [] };
|
|
66
66
|
const project = path.resolve(values.project ?? '.');
|
|
67
67
|
const root = fs.statSync(project).isDirectory() ? project : path.dirname(project);
|
|
68
|
-
const roots = workspace && values.workspace.length ? workspace.
|
|
68
|
+
const roots = workspace && values.workspace.length ? workspace.packages.map(({ directory }) => path.resolve(directory)) : [root];
|
|
69
69
|
return scanMarkupFiles({
|
|
70
70
|
roots: markupFiles.length ? [] : roots,
|
|
71
71
|
explicitFiles: markupFiles,
|
|
@@ -187,7 +187,7 @@ export async function checkCode(args, report = printResult, baselineFlags = {},
|
|
|
187
187
|
function resolveScanInputs(values, positionals, workspace, readsMarkupOnly) {
|
|
188
188
|
// A monorepo root keeps its policy and config at the root, beside no project config.
|
|
189
189
|
const input = path.resolve(values.project ?? '.');
|
|
190
|
-
const inferredFiles = !workspace && !positionals.length && !values.watch ?
|
|
190
|
+
const inferredFiles = !workspace && !positionals.length && !values.watch ? configlessSources(input) : undefined;
|
|
191
191
|
// A folder of plain markup has no project config to take its folder from.
|
|
192
192
|
const isMarkupFolder = readsMarkupOnly && !workspace && !positionals.length;
|
|
193
193
|
const directory = workspace?.directory ?? (inferredFiles || isMarkupFolder ? input : projectDirectory(values.project, positionals));
|
|
@@ -220,8 +220,9 @@ async function scanSource({ values, positionals, workspace, inferredFiles, polic
|
|
|
220
220
|
// shows the reliability and security findings too, from the same Program.
|
|
221
221
|
const editor = report !== printResult;
|
|
222
222
|
return await analyzeSourceCode({
|
|
223
|
-
project: workspace?.configs ?? values.project,
|
|
224
|
-
files:
|
|
223
|
+
project: inferredFiles ? [] : (workspace?.configs ?? values.project),
|
|
224
|
+
files: positionals,
|
|
225
|
+
standaloneFiles: inferredFiles ?? workspace?.standaloneFiles,
|
|
225
226
|
policy,
|
|
226
227
|
onlyFiles: scanFilter(values.settings, scope),
|
|
227
228
|
analyzers: editor ? await editorAnalyzers() : analyzers,
|
|
@@ -285,8 +286,9 @@ async function checkWithPillars({ values, positionals, policy, scope, workspace,
|
|
|
285
286
|
files: inferredFiles ?? positionals,
|
|
286
287
|
});
|
|
287
288
|
const result = analyzeSources({
|
|
288
|
-
project: workspace?.configs ?? values.project,
|
|
289
|
-
files:
|
|
289
|
+
project: inferredFiles ? [] : (workspace?.configs ?? values.project),
|
|
290
|
+
files: positionals,
|
|
291
|
+
standaloneFiles: inferredFiles ?? workspace?.standaloneFiles,
|
|
290
292
|
policy,
|
|
291
293
|
onlyFiles: scanFilter(values.settings, scope),
|
|
292
294
|
analyzers: sharedAnalyzers(commands),
|
package/lib/performance/cli.js
CHANGED
|
@@ -2,12 +2,12 @@ import { parseMinImpact } from '../shared/impact-levels.js';
|
|
|
2
2
|
import { loadSettings } from '../shared/config.js';
|
|
3
3
|
import { extractBaselineFlags } from '../shared/baseline.js';
|
|
4
4
|
import { formatImpact } from './impact.js';
|
|
5
|
-
import { notifyEditor } from '
|
|
5
|
+
import { notifyEditor } from '../shared/notify-editor.js';
|
|
6
6
|
import { runAgentCommand } from '../shared/agent-init.js';
|
|
7
7
|
import { parseCommand, readJsonFile, showHelp } from './cli-arguments.js';
|
|
8
|
-
import { printResult, scanFilter
|
|
8
|
+
import { printResult, scanFilter } from './cli-output.js';
|
|
9
9
|
import { projectDirectory, relativeToCwd, sourcePolicy, workspaceTarget } from './cli-policy.js';
|
|
10
|
-
import { checkCode
|
|
10
|
+
import { checkCode } from './cli-scan.js';
|
|
11
11
|
async function checkPlan(args) {
|
|
12
12
|
const { values, positionals } = parseCommand(args, { json: { type: 'boolean' } });
|
|
13
13
|
if (values.help)
|
|
@@ -54,25 +54,6 @@ async function checkTraces(args) {
|
|
|
54
54
|
}
|
|
55
55
|
return findings.length ? 1 : 0;
|
|
56
56
|
}
|
|
57
|
-
async function runEditor(args) {
|
|
58
|
-
if (args[0] === 'init' && args.length === 1) {
|
|
59
|
-
const editorSetup = await import('./editor-setup.js');
|
|
60
|
-
const setup = editorSetup.setupEditor(process.cwd());
|
|
61
|
-
console.log((setup.changed ? 'Configured ' : 'Already configured: ') + setup.filename);
|
|
62
|
-
console.log('Open or reopen the trusted folder in VS Code or Cursor and allow automatic tasks once. Terminal source scans refresh the active watcher.');
|
|
63
|
-
return 0;
|
|
64
|
-
}
|
|
65
|
-
if (args[0] !== 'watch')
|
|
66
|
-
throw new Error('Usage: loadwise perf editor init | editor watch [-p tsconfig.json]');
|
|
67
|
-
const { values, positionals } = parseCommand(args.slice(1), { project: { type: 'string', short: 'p' } });
|
|
68
|
-
if (values.help)
|
|
69
|
-
return showHelp();
|
|
70
|
-
if (positionals.length)
|
|
71
|
-
throw new Error('editor watch accepts only an optional -p project config.');
|
|
72
|
-
await loadSqlParser();
|
|
73
|
-
(await import('./editor-watch.js')).watchEditor(process.cwd(), values.project, (inputs) => checkCode(inputs, selectFindings));
|
|
74
|
-
return 0;
|
|
75
|
-
}
|
|
76
57
|
// `pillar` picks the rule set: `loadwise perf polyglot` or `loadwise rel polyglot`.
|
|
77
58
|
async function runPolyglot(args, pillar = 'performance') {
|
|
78
59
|
const { values, positionals } = parseCommand(args, {
|
|
@@ -98,7 +79,7 @@ async function main(args) {
|
|
|
98
79
|
// Resolve subcommand dependencies only after selecting the command.
|
|
99
80
|
switch (args[0]) {
|
|
100
81
|
case 'editor':
|
|
101
|
-
|
|
82
|
+
throw new Error('`loadwise perf editor` was removed. Use the language server, `loadwise lsp`, in your editor.');
|
|
102
83
|
case 'agent':
|
|
103
84
|
return runAgentCommand(args.slice(1));
|
|
104
85
|
case 'migrations':
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { signalDirectory, isPrivateDirectory, notifyEditor } from '
|
|
4
|
+
import { signalDirectory, isPrivateDirectory, notifyEditor } from '../shared/notify-editor.js';
|
|
5
5
|
function listenForEditorRefresh(root, onRequest) {
|
|
6
6
|
let watcher;
|
|
7
7
|
let directory;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { diffLines, labelledLines } from '../shared/fix-terminal.js';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { exampleFor } from '
|
|
4
|
-
import { exampleFor as securityExample } from '
|
|
5
|
-
import { exampleFor as accessibilityExample } from '
|
|
3
|
+
import { exampleFor } from '../editor/reliability-examples.js';
|
|
4
|
+
import { exampleFor as securityExample } from '../editor/security-examples.js';
|
|
5
|
+
import { exampleFor as accessibilityExample } from '../editor/accessibility-examples.js';
|
|
6
6
|
import { formatImpact } from './impact.js';
|
|
7
7
|
import { hotPathLabel } from '../shared/hot-path.js';
|
|
8
8
|
import { findingReason, groupByReason } from '../shared/reason-groups.js';
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { askChoice, labelledLines } from '../shared/fix-terminal.js';
|
|
5
|
-
import { applyFix } from '
|
|
5
|
+
import { applyFix } from '../editor/apply-fix.js';
|
|
6
6
|
import { diffLines, findingLabel } from './finding-text.js';
|
|
7
7
|
import { applyFixSafely } from '../shared/fix-safety.js';
|
|
8
8
|
import { createWriteTracker, withoutWhyComment } from '../shared/fix-presentation.js';
|
|
@@ -8,10 +8,12 @@
|
|
|
8
8
|
// - angular-default-change-detection
|
|
9
9
|
// - vue-watch-missing-cleanup
|
|
10
10
|
// - vue-v-for-missing-key
|
|
11
|
+
// frontend-render-perf.ts adds react-component-defined-in-component and angular-ngfor-missing-trackby.
|
|
11
12
|
// Every rule rests on where a name comes from (its import), never on the name alone.
|
|
12
13
|
import { ts } from './compiler.js';
|
|
13
14
|
import { isTestSource } from './review-context.js';
|
|
14
15
|
import { declaredInPackage, initializerOf, packageOf, propertyName } from './schema/ts-helpers.js';
|
|
16
|
+
import { checkComponentInComponent, checkNgForTrackBy, isFunctionNode } from './frontend-render-perf.js';
|
|
15
17
|
import { checkAddEventListener, checkHeavyBarrelImport, checkLayoutThrashing, isLoop } from './frontend-dom-perf.js';
|
|
16
18
|
import { ANGULAR_MODULES, REACT_MODULES, VUE_MODULES, calleeName, containsReturnValue, effectCallback, importedName, isBrowserGlobal, isGlobalEventTarget, isVueImport, walkAll, walkSkippingFunctions, } from './frontend-helpers.js';
|
|
17
19
|
const RXJS_OPERATOR_MODULES = ['rxjs', 'rxjs/operators', '@angular/core/rxjs-interop'];
|
|
@@ -346,6 +348,9 @@ function checkAngularClass(classNode, context) {
|
|
|
346
348
|
if (!ts.canHaveDecorators(classNode) || !ts.getDecorators(classNode)?.length)
|
|
347
349
|
return;
|
|
348
350
|
checkAngularChangeDetection(classNode, context);
|
|
351
|
+
const component = componentMetadata(classNode, context.checker);
|
|
352
|
+
if (component)
|
|
353
|
+
checkNgForTrackBy(component.metadata, context);
|
|
349
354
|
if (!isAngularComponentOrDirective(classNode, context.checker))
|
|
350
355
|
return;
|
|
351
356
|
if (destroyHookReleases(classNode))
|
|
@@ -460,6 +465,8 @@ function checkFrontendNode(node, context) {
|
|
|
460
465
|
checkInlineObjectProps(node, context);
|
|
461
466
|
else if (ts.isClassDeclaration(node))
|
|
462
467
|
checkAngularClass(node, context);
|
|
468
|
+
else if (isFunctionNode(node))
|
|
469
|
+
checkComponentInComponent(node, context);
|
|
463
470
|
else if (isLoop(node))
|
|
464
471
|
checkLayoutThrashing(node, context);
|
|
465
472
|
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// Frontend render-cost rules that read the shape of a component rather than one call:
|
|
2
|
+
// - react-component-defined-in-component
|
|
3
|
+
// - angular-ngfor-missing-trackby
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { ts } from './compiler.js';
|
|
6
|
+
import { propertyName } from './schema/ts-helpers.js';
|
|
7
|
+
import { walkAll, walkSkippingFunctions } from './frontend-helpers.js';
|
|
8
|
+
const COMPONENT_NAME = /^[A-Z]/;
|
|
9
|
+
// `*ngFor="let item of items; trackBy: byId"`, in either quote style; the expression never contains its own quote.
|
|
10
|
+
const NG_FOR_ATTRIBUTE = /\*ngFor\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
|
11
|
+
// Only an array of string and number literals keeps its identities; objects, calls and spreads do not.
|
|
12
|
+
const LITERAL_ITEM = String.raw `(?:'[^']*'|"[^"]*"|-?\d+(?:\.\d+)?)`;
|
|
13
|
+
const STATIC_ARRAY_SOURCE = new RegExp(String.raw `\bof\s+\[\s*(?:${LITERAL_ITEM}\s*(?:,\s*${LITERAL_ITEM}\s*)*)?\](?:\s+as\s+[\w$]+)?\s*(?:;|$)`);
|
|
14
|
+
// A `trackBy` binding in the microsyntax (`trackBy: fn` or `trackBy fn`), not a property or variable of that name.
|
|
15
|
+
const TRACK_BY = /(?<![.\w$])trackBy(?:\s*:|\s+[\w$])/;
|
|
16
|
+
// A terminated comment, or an unterminated `<!--` and everything after it, so no `<!--` survives.
|
|
17
|
+
const HTML_COMMENT = /<!--[\s\S]*?(?:-->|$)/g;
|
|
18
|
+
const CONTROL_CHARACTERS = /\p{Cc}/gu;
|
|
19
|
+
const REACT_COMPONENT_WRAPPERS = new Set(['memo', 'forwardRef']);
|
|
20
|
+
const HTML_FILE = /\.html?$/i;
|
|
21
|
+
// --- React: component defined inside a component
|
|
22
|
+
// ------------------------------------------------------------------------------
|
|
23
|
+
function isFunctionNode(node) {
|
|
24
|
+
return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node);
|
|
25
|
+
}
|
|
26
|
+
// The function declaration itself, or the variable it initialises: the node the checker reports as
|
|
27
|
+
// the declaration of the component's name.
|
|
28
|
+
function declarationOf(fn) {
|
|
29
|
+
if (ts.isFunctionDeclaration(fn))
|
|
30
|
+
return fn.name ? fn : undefined;
|
|
31
|
+
const parent = fn.parent;
|
|
32
|
+
if (ts.isVariableDeclaration(parent) && parent.initializer === fn)
|
|
33
|
+
return parent;
|
|
34
|
+
return wrappingVariable(fn);
|
|
35
|
+
}
|
|
36
|
+
function declaredName(fn) {
|
|
37
|
+
if (ts.isFunctionDeclaration(fn))
|
|
38
|
+
return fn.name?.text;
|
|
39
|
+
const parent = fn.parent;
|
|
40
|
+
const variable = ts.isVariableDeclaration(parent) && parent.initializer === fn ? parent : wrappingVariable(fn);
|
|
41
|
+
return variable && ts.isIdentifier(variable.name) ? variable.name.text : undefined;
|
|
42
|
+
}
|
|
43
|
+
// The variable initialised with `memo(fn)` or `forwardRef(fn)`; React documents both as returning a new component.
|
|
44
|
+
function wrappingVariable(fn) {
|
|
45
|
+
const wrapper = fn.parent;
|
|
46
|
+
if (!ts.isCallExpression(wrapper) || wrapper.arguments[0] !== fn)
|
|
47
|
+
return;
|
|
48
|
+
const callee = ts.isPropertyAccessExpression(wrapper.expression) ? wrapper.expression.name : wrapper.expression;
|
|
49
|
+
if (!ts.isIdentifier(callee) || !REACT_COMPONENT_WRAPPERS.has(callee.text))
|
|
50
|
+
return;
|
|
51
|
+
const variable = wrapper.parent;
|
|
52
|
+
return ts.isVariableDeclaration(variable) && variable.initializer === wrapper ? variable : undefined;
|
|
53
|
+
}
|
|
54
|
+
function isJsx(expression) {
|
|
55
|
+
const target = ts.skipOuterExpressions(expression);
|
|
56
|
+
if (ts.isJsxElement(target) || ts.isJsxSelfClosingElement(target) || ts.isJsxFragment(target))
|
|
57
|
+
return true;
|
|
58
|
+
if (ts.isConditionalExpression(target))
|
|
59
|
+
return isJsx(target.whenTrue) || isJsx(target.whenFalse);
|
|
60
|
+
if (ts.isArrayLiteralExpression(target))
|
|
61
|
+
return target.elements.some(isJsx);
|
|
62
|
+
// `items.map(() => <Row />)`: a callback argument that itself returns JSX.
|
|
63
|
+
if (ts.isCallExpression(target)) {
|
|
64
|
+
return target.arguments.some((argument) => isFunctionNode(argument) && returnsJsx(argument));
|
|
65
|
+
}
|
|
66
|
+
if (!ts.isBinaryExpression(target))
|
|
67
|
+
return false;
|
|
68
|
+
const operator = target.operatorToken.kind;
|
|
69
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken)
|
|
70
|
+
return isJsx(target.right);
|
|
71
|
+
return ((operator === ts.SyntaxKind.BarBarToken || operator === ts.SyntaxKind.QuestionQuestionToken) &&
|
|
72
|
+
(isJsx(target.left) || isJsx(target.right)));
|
|
73
|
+
}
|
|
74
|
+
function returnsJsx(fn) {
|
|
75
|
+
if (!fn.body)
|
|
76
|
+
return false;
|
|
77
|
+
if (!ts.isBlock(fn.body))
|
|
78
|
+
return isJsx(fn.body);
|
|
79
|
+
// `const content = <Row />; return content;`. A name declared more than once (a shadowing block
|
|
80
|
+
// local) is ambiguous without scope analysis, so it never counts.
|
|
81
|
+
const declarationCounts = new Map();
|
|
82
|
+
const jsxLocals = new Set();
|
|
83
|
+
walkSkippingFunctions(fn.body, (node) => {
|
|
84
|
+
if (!ts.isVariableDeclaration(node) || !ts.isIdentifier(node.name))
|
|
85
|
+
return;
|
|
86
|
+
declarationCounts.set(node.name.text, (declarationCounts.get(node.name.text) ?? 0) + 1);
|
|
87
|
+
if (node.initializer && isJsx(node.initializer))
|
|
88
|
+
jsxLocals.add(node.name.text);
|
|
89
|
+
});
|
|
90
|
+
let found = false;
|
|
91
|
+
walkSkippingFunctions(fn.body, (node) => {
|
|
92
|
+
if (!ts.isReturnStatement(node) || !node.expression)
|
|
93
|
+
return;
|
|
94
|
+
const returned = ts.skipOuterExpressions(node.expression);
|
|
95
|
+
if (isJsx(returned) ||
|
|
96
|
+
(ts.isIdentifier(returned) && jsxLocals.has(returned.text) && declarationCounts.get(returned.text) === 1))
|
|
97
|
+
found = true;
|
|
98
|
+
});
|
|
99
|
+
return found;
|
|
100
|
+
}
|
|
101
|
+
// `function Row() {}`, `const Row = () => ...`, `const Row = memo(() => ...)` / `forwardRef(...)`.
|
|
102
|
+
function isComponent(fn) {
|
|
103
|
+
const name = declaredName(fn);
|
|
104
|
+
return name !== undefined && COMPONENT_NAME.test(name);
|
|
105
|
+
}
|
|
106
|
+
// Only the nearest function counts: a component declared inside a callback of the outer component
|
|
107
|
+
// is not matched, which keeps render-prop shapes out.
|
|
108
|
+
function enclosingFunction(node) {
|
|
109
|
+
let current = node.parent;
|
|
110
|
+
while (current && !ts.isSourceFile(current)) {
|
|
111
|
+
if (isFunctionNode(current))
|
|
112
|
+
return current;
|
|
113
|
+
if (ts.isClassLike(current))
|
|
114
|
+
return;
|
|
115
|
+
current = current.parent;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Whether the outer component renders `<Inner />` where the tag resolves to this very declaration.
|
|
119
|
+
function rendersAsElement(outer, declaration, name, context) {
|
|
120
|
+
let rendered = false;
|
|
121
|
+
walkAll(outer, (node) => {
|
|
122
|
+
if (rendered || !(ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)))
|
|
123
|
+
return;
|
|
124
|
+
if (!ts.isIdentifier(node.tagName) || node.tagName.text !== name)
|
|
125
|
+
return;
|
|
126
|
+
const declarations = context.checker.getSymbolAtLocation(node.tagName)?.declarations;
|
|
127
|
+
rendered = Boolean(declarations?.includes(declaration));
|
|
128
|
+
});
|
|
129
|
+
return rendered;
|
|
130
|
+
}
|
|
131
|
+
function checkComponentInComponent(fn, context) {
|
|
132
|
+
const name = declaredName(fn);
|
|
133
|
+
const declaration = declarationOf(fn);
|
|
134
|
+
if (!name || !declaration || !COMPONENT_NAME.test(name))
|
|
135
|
+
return;
|
|
136
|
+
const outer = enclosingFunction(fn);
|
|
137
|
+
if (!outer || !isComponent(outer) || !returnsJsx(outer))
|
|
138
|
+
return;
|
|
139
|
+
if (!rendersAsElement(outer, declaration, name, context))
|
|
140
|
+
return;
|
|
141
|
+
context.report(declaration, 'react-component-defined-in-component', `\`${name}\` is a component declared inside another component and rendered as \`<${name} />\`. It is a new component type on every render, so React unmounts and remounts its whole subtree each time, losing state and DOM. Move it to module scope and pass what it needs as props.`);
|
|
142
|
+
}
|
|
143
|
+
// --- Angular: *ngFor without trackBy
|
|
144
|
+
// ------------------------------------------------------------------------------
|
|
145
|
+
// Interpolated parts of a template literal cannot hide an `*ngFor` attribute, so they are dropped.
|
|
146
|
+
function stringValueOf(initializer) {
|
|
147
|
+
const target = ts.skipOuterExpressions(initializer);
|
|
148
|
+
if (ts.isStringLiteralLike(target))
|
|
149
|
+
return target.text;
|
|
150
|
+
if (ts.isTemplateExpression(target)) {
|
|
151
|
+
return [target.head.text, ...target.templateSpans.map((span) => span.literal.text)].join(' ');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// The `*ngFor` expressions that name no trackBy. A loop over a literal array never reorders, so it
|
|
155
|
+
// costs nothing.
|
|
156
|
+
function untrackedLoops(template) {
|
|
157
|
+
const loops = [];
|
|
158
|
+
// Angular drops HTML comments, so a commented-out loop renders nothing.
|
|
159
|
+
for (const match of template.replaceAll(HTML_COMMENT, '').matchAll(NG_FOR_ATTRIBUTE)) {
|
|
160
|
+
const expression = match[1] ?? match[2];
|
|
161
|
+
if (!TRACK_BY.test(expression) && !STATIC_ARRAY_SOURCE.test(expression))
|
|
162
|
+
loops.push(expression.trim());
|
|
163
|
+
}
|
|
164
|
+
return loops;
|
|
165
|
+
}
|
|
166
|
+
function metadataProperty(metadata, name) {
|
|
167
|
+
return metadata.properties.find((property) => ts.isPropertyAssignment(property) && propertyName(property) === name);
|
|
168
|
+
}
|
|
169
|
+
// A `templateUrl` is relative to its component; an absolute or UNC path would make the scan read an
|
|
170
|
+
// arbitrary location, including a network share.
|
|
171
|
+
function externalTemplate(property, sourceFileName) {
|
|
172
|
+
const url = stringValueOf(property.initializer);
|
|
173
|
+
if (!url || !HTML_FILE.test(url) || path.isAbsolute(url) || path.win32.isAbsolute(url))
|
|
174
|
+
return;
|
|
175
|
+
const text = ts.sys.readFile(path.resolve(path.dirname(sourceFileName), url));
|
|
176
|
+
return text === undefined ? undefined : { url, text };
|
|
177
|
+
}
|
|
178
|
+
function reportUntracked(property, loops, context, templateUrl) {
|
|
179
|
+
const more = loops.length > 1 ? ` (and ${loops.length - 1} more in this template)` : '';
|
|
180
|
+
const location = templateUrl ? ` in \`${templateUrl}\`` : '';
|
|
181
|
+
const loop = loops[0].replaceAll(CONTROL_CHARACTERS, ' ');
|
|
182
|
+
context.report(property, 'angular-ngfor-missing-trackby', `\`*ngFor="${loop}"\`${location}${more} has no \`trackBy\`, so when the list is replaced with new objects Angular destroys and recreates the DOM for every item instead of moving the ones that stayed. Add \`trackBy: trackById\` with a function returning a stable identifier, or migrate to \`@for (... ; track item.id)\`.`);
|
|
183
|
+
}
|
|
184
|
+
function checkNgForTrackBy(metadata, context) {
|
|
185
|
+
const inline = metadataProperty(metadata, 'template');
|
|
186
|
+
const inlineText = inline && stringValueOf(inline.initializer);
|
|
187
|
+
if (inline && inlineText) {
|
|
188
|
+
const loops = untrackedLoops(inlineText);
|
|
189
|
+
if (loops.length)
|
|
190
|
+
reportUntracked(inline, loops, context);
|
|
191
|
+
}
|
|
192
|
+
const external = metadataProperty(metadata, 'templateUrl');
|
|
193
|
+
const template = external && externalTemplate(external, metadata.getSourceFile().fileName);
|
|
194
|
+
if (!external || !template)
|
|
195
|
+
return;
|
|
196
|
+
const loops = untrackedLoops(template.text);
|
|
197
|
+
if (loops.length)
|
|
198
|
+
reportUntracked(external, loops, context, template.url);
|
|
199
|
+
}
|
|
200
|
+
export { checkComponentInComponent, checkNgForTrackBy, isFunctionNode };
|