loadwise 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -8,164 +8,33 @@
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
+ // frontend-render-perf.ts adds react-component-defined-in-component and angular-ngfor-missing-trackby,
12
+ // angular-template-calls.ts angular-template-method-call, and jsx-element-perf.ts
13
+ // frontend-render-blocking-script and react-unthrottled-input-fetch.
12
14
  // Every rule rests on where a name comes from (its import), never on the name alone.
13
15
  import { ts } from '../engine/compiler.js';
14
16
  import { effectCleanup, effectDisposes, releases } from './effect-cleanup.js';
15
- import { angularTeardown, subscriptionField, thisField } from './angular-teardown.js';
17
+ import { angularTeardown, subscriptionField } from './angular-teardown.js';
16
18
  import { inZonelessAngularApp } from './angular-bootstrap.js';
17
19
  import { isTestSource } from '../analysis/review-context.js';
18
- import { declaredInPackage, initializerOf, packageOf, propertyName } from '../schema/ts-helpers.js';
19
- import { checkComponentInComponent, checkNgForTrackBy, isFunctionNode } from './frontend-render-perf.js';
20
- import { checkAddEventListener, checkHeavyBarrelImport, checkLayoutThrashing, isLoop } from './frontend-dom-perf.js';
20
+ import { initializerOf, propertyName } from '../schema/ts-helpers.js';
21
+ import { isUnshadowedGlobal } from '../../shared/analysis/ast-semantics.js';
22
+ import { checkComponentInComponent, checkNgForTrackBy, componentExternalTemplate, isFunctionNode, } from './frontend-render-perf.js';
23
+ import { checkTemplateMethodCalls } from './angular-template-calls.js';
24
+ import { checkJsxElement } from './jsx-element-perf.js';
25
+ import { effectiveOptions, optionsHookBody, teardownBodies, teardownMayRelease } from './vue-options-hooks.js';
26
+ import { checkNavigationWithoutLink } from './seo/navigation-without-link.js';
27
+ import { returnedExpressions, unmanagedSubscription } from './rxjs-subscriptions.js';
28
+ import { checkAddEventListener, checkForEachLayoutThrashing, checkHeavyBarrelImport, checkLayoutThrashing, isLoop, } from './frontend-dom-perf.js';
21
29
  import { ANGULAR_MODULES, REACT_MODULES, VUE_MODULES, calleeName, effectCallback, importedName, isBrowserGlobal, isGlobalEventTarget, isVueImport, walkAll, walkSkippingFunctions, } from './frontend-helpers.js';
22
- const RXJS_OPERATOR_MODULES = ['rxjs', 'rxjs/operators', '@angular/core/rxjs-interop'];
23
30
  const DEFINITE_LEAK_CONSTRUCTORS = new Set(['WebSocket', 'EventSource']);
24
31
  const OBSERVER_CONSTRUCTORS = new Set(['ResizeObserver', 'IntersectionObserver', 'MutationObserver']);
25
- const ENDLESS_RXJS_CREATORS = new Set(['interval', 'fromEvent', 'fromEventPattern']);
26
- const COMPLETING_OPERATORS = new Set([
27
- 'takeUntil',
28
- 'takeUntilDestroyed',
29
- 'take',
30
- 'takeWhile',
31
- 'first',
32
- 'single',
33
- 'elementAt',
34
- ]);
35
- const FLATTENING_OPERATORS = new Set([
36
- 'concatAll',
37
- 'concatMap',
38
- 'concatMapTo',
39
- 'exhaust',
40
- 'exhaustAll',
41
- 'exhaustMap',
42
- 'mergeAll',
43
- 'mergeMap',
44
- 'mergeMapTo',
45
- 'switchAll',
46
- 'switchMap',
47
- 'switchMapTo',
48
- ]);
49
- const ENDLESS_PACKAGES = ['@ngrx/store', '@angular/forms'];
50
- const COMPLETING_PACKAGES = ['@angular/common'];
51
32
  const SUBSCRIBE_MAY_COMPLETE_REASON = 'The source may complete on its own (route params, single-emission or finite observables); dismiss if it does.';
52
33
  const FETCH_STATIC_DEPS_REASON = 'With an empty dependency array the request runs once per mount, so only an unmount before the response matters.';
53
34
  const INDEX_KEY_REASON = 'Index keys are fine for lists that never reorder, insert, or delete items.';
54
35
  const INLINE_OBJECT_REASON = 'Matters only when the memoised child re-renders often enough for the extra renders to show.';
55
36
  const OBSERVER_REASON = 'An observer attached to an element the component owns is collected with that element; it leaks when attached to document-level targets.';
56
37
  const ON_PUSH_REASON = 'OnPush skips checks for @Input objects that are mutated in place, so confirm the inputs are immutable or signal-driven first; zoneless apps do not need it.';
57
- // --- RxJS subscriptions
58
- // -------------------------------------------------------------------------------------
59
- // Keep the lifetime effects in pipeline order, including across separate pipe() calls.
60
- function unwrapPipes(expression, checker, teardown) {
61
- const effects = [];
62
- let source = ts.skipOuterExpressions(expression);
63
- while (ts.isCallExpression(source) && ts.isPropertyAccessExpression(source.expression)) {
64
- const method = source.expression.name.text;
65
- if (method === 'pipe')
66
- effects.unshift(...operatorEffects(source.arguments, checker, teardown));
67
- else if (method !== 'asObservable')
68
- break;
69
- source = ts.skipOuterExpressions(source.expression.expression);
70
- }
71
- return { source, effects };
72
- }
73
- function operatorEffects(pipeArguments, checker, teardown) {
74
- const effects = [];
75
- for (const argument of pipeArguments) {
76
- const operator = ts.skipOuterExpressions(argument);
77
- if (!ts.isCallExpression(operator))
78
- continue;
79
- const name = importedName(operator.expression, checker, RXJS_OPERATOR_MODULES);
80
- if (!name)
81
- continue;
82
- if (name === 'takeUntil' && teardown) {
83
- const notifier = thisField(operator.arguments[0]);
84
- if (notifier && teardown.ownedNotifiers.has(notifier) && !teardown.notifiers.has(notifier))
85
- continue;
86
- }
87
- // RxJS implements a nonpositive takeLast count as an immediately completing stream.
88
- if (COMPLETING_OPERATORS.has(name) || (name === 'takeLast' && isNonpositiveCount(operator.arguments[0]))) {
89
- effects.push('complete');
90
- }
91
- else if (FLATTENING_OPERATORS.has(name) && !hasFiniteInnerStream(name, operator, checker)) {
92
- effects.push('flatten');
93
- }
94
- }
95
- return effects;
96
- }
97
- function hasFiniteInnerStream(name, operator, checker) {
98
- const argument = operator.arguments[0] && ts.skipOuterExpressions(operator.arguments[0]);
99
- if (!argument)
100
- return false;
101
- if (name.endsWith('MapTo'))
102
- return isFiniteRxjsSource(argument, checker);
103
- if (!name.endsWith('Map') || (!ts.isArrowFunction(argument) && !ts.isFunctionExpression(argument))) {
104
- return false;
105
- }
106
- const returned = returnedExpressions(argument);
107
- return returned.length > 0 && returned.every((value) => isFiniteRxjsSource(value, checker));
108
- }
109
- function isFiniteRxjsSource(value, checker) {
110
- if (ts.isCallExpression(value))
111
- return importedName(value.expression, checker, ['rxjs']) === 'of';
112
- return importedName(value, checker, ['rxjs']) === 'EMPTY';
113
- }
114
- function isNonpositiveCount(argument) {
115
- if (!argument)
116
- return false;
117
- const count = ts.skipOuterExpressions(argument);
118
- if (ts.isNumericLiteral(count))
119
- return Number(count.text) === 0;
120
- return (ts.isPrefixUnaryExpression(count) &&
121
- count.operator === ts.SyntaxKind.MinusToken &&
122
- ts.isNumericLiteral(count.operand));
123
- }
124
- function isRxjsSubject(source, checker) {
125
- const symbol = checker.getTypeAtLocation(source).getSymbol();
126
- if (!symbol || !symbol.name.endsWith('Subject'))
127
- return false;
128
- return (symbol.declarations ?? []).every((declaration) => packageOf(declaration) === 'rxjs');
129
- }
130
- function isEndlessCreator(callee, checker) {
131
- const name = importedName(callee, checker, ['rxjs']);
132
- return name !== undefined && ENDLESS_RXJS_CREATORS.has(name);
133
- }
134
- // 'completing' sources finish after one response (HttpClient); 'endless' ones keep emitting until
135
- // unsubscribed.
136
- function classifySource(source, checker) {
137
- if (ts.isCallExpression(source)) {
138
- if (isEndlessCreator(source.expression, checker))
139
- return 'endless';
140
- if (declaredInPackage(source.expression, checker, COMPLETING_PACKAGES))
141
- return 'completing';
142
- if (declaredInPackage(source.expression, checker, ENDLESS_PACKAGES))
143
- return 'endless';
144
- return 'unknown';
145
- }
146
- if (isRxjsSubject(source, checker) || declaredInPackage(source, checker, ENDLESS_PACKAGES))
147
- return 'endless';
148
- return 'unknown';
149
- }
150
- // undefined: not an RxJS subscription, or one that ends on its own. Otherwise 'endless' or
151
- // 'unknown'.
152
- function unmanagedSubscription(call, checker, teardown) {
153
- const callee = ts.skipOuterExpressions(call.expression);
154
- if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'subscribe')
155
- return;
156
- if (!declaredInPackage(callee, checker, ['rxjs']))
157
- return;
158
- const { source, effects } = unwrapPipes(callee.expression, checker, teardown);
159
- let kind = classifySource(source, checker);
160
- for (const effect of effects) {
161
- if (effect === 'complete')
162
- kind = 'completing';
163
- // Completing the outer stream can leave an active inner subscription.
164
- else if (kind === 'completing')
165
- kind = 'unknown';
166
- }
167
- return kind === 'completing' ? undefined : kind;
168
- }
169
38
  // --- React
170
39
  // ---------------------------------------------------------------------------------------------------
171
40
  function leakOfNode(node, checker) {
@@ -307,31 +176,43 @@ function isStaticList(call, checker) {
307
176
  const initializer = ts.isIdentifier(target) ? initializerOf(target, checker) : undefined;
308
177
  return initializer !== undefined && ts.isArrayLiteralExpression(ts.skipOuterExpressions(initializer));
309
178
  }
310
- // The expressions a callback returns, which are the list items it renders.
311
- function returnedExpressions(callback) {
312
- if (!ts.isBlock(callback.body))
313
- return [ts.skipOuterExpressions(callback.body)];
314
- const returned = [];
315
- walkSkippingFunctions(callback.body, (node) => {
316
- if (ts.isReturnStatement(node) && node.expression)
317
- returned.push(ts.skipOuterExpressions(node.expression));
318
- });
319
- return returned;
320
- }
321
179
  function jsxAttributesOf(element) {
322
180
  if (ts.isJsxSelfClosingElement(element))
323
181
  return element.attributes.properties;
324
182
  return ts.isJsxElement(element) ? element.openingElement.attributes.properties : [];
325
183
  }
326
- function indexKeyAttribute(element, indexName) {
184
+ function indexKeyAttribute(element, indexName, checker) {
327
185
  return jsxAttributesOf(element).find((attribute) => {
328
186
  if (!ts.isJsxAttribute(attribute) || !ts.isIdentifier(attribute.name) || attribute.name.text !== 'key')
329
187
  return false;
330
188
  const value = attribute.initializer;
331
189
  const expression = value && ts.isJsxExpression(value) && value.expression && ts.skipOuterExpressions(value.expression);
332
- return Boolean(expression && ts.isIdentifier(expression) && expression.text === indexName);
190
+ return Boolean(expression && isIndexDerived(expression, indexName, checker));
333
191
  });
334
192
  }
193
+ // `i`, `` `row-${i}` ``, `'row-' + i`, `String(i)` or `i.toString()`: a key that changes with the position alone.
194
+ function isIndexDerived(expression, indexName, checker) {
195
+ const target = ts.skipOuterExpressions(expression);
196
+ if (ts.isIdentifier(target))
197
+ return target.text === indexName;
198
+ if (ts.isTemplateExpression(target))
199
+ return target.templateSpans.every((span) => isIndexDerived(span.expression, indexName, checker));
200
+ if (ts.isBinaryExpression(target) && target.operatorToken.kind === ts.SyntaxKind.PlusToken) {
201
+ const parts = [target.left, target.right].map((part) => ts.skipOuterExpressions(part));
202
+ const literal = parts.find(ts.isStringLiteralLike);
203
+ const other = parts.find((part) => part !== literal);
204
+ return literal !== undefined && other !== undefined && isIndexDerived(other, indexName, checker);
205
+ }
206
+ if (!ts.isCallExpression(target))
207
+ return false;
208
+ const callee = ts.skipOuterExpressions(target.expression);
209
+ if (isUnshadowedGlobal(callee, 'String', checker) && target.arguments.length === 1)
210
+ return isIndexDerived(target.arguments[0], indexName, checker);
211
+ return (ts.isPropertyAccessExpression(callee) &&
212
+ callee.name.text === 'toString' &&
213
+ target.arguments.length === 0 &&
214
+ isIndexDerived(callee.expression, indexName, checker));
215
+ }
335
216
  function checkReactIndexKey(call, context) {
336
217
  const callee = ts.skipOuterExpressions(call.expression);
337
218
  if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'map')
@@ -342,7 +223,7 @@ function checkReactIndexKey(call, context) {
342
223
  return;
343
224
  const attributes = [];
344
225
  for (const item of returnedExpressions(callback)) {
345
- const attribute = indexKeyAttribute(item, indexParameter.text);
226
+ const attribute = indexKeyAttribute(item, indexParameter.text, context.checker);
346
227
  if (attribute)
347
228
  attributes.push(attribute);
348
229
  }
@@ -355,27 +236,55 @@ function checkReactIndexKey(call, context) {
355
236
  }
356
237
  }
357
238
  // A fresh object only defeats React.memo when the child is memoised, so the tag must resolve to a
358
- // memo() call.
239
+ // memo() call. A custom comparator may ignore the prop, so memo() with one does not count;
240
+ // `undefined` in its place keeps the default shallow comparison.
359
241
  function isMemoComponent(tagName, checker) {
360
242
  if (!ts.isIdentifier(tagName))
361
243
  return false;
362
244
  const initializer = initializerOf(tagName, checker);
363
- return (initializer !== undefined &&
364
- ts.isCallExpression(initializer) &&
245
+ if (initializer === undefined || !ts.isCallExpression(initializer))
246
+ return false;
247
+ const comparator = initializer.arguments[1] && ts.skipOuterExpressions(initializer.arguments[1]);
248
+ return ((!comparator || isUnshadowedGlobal(comparator, 'undefined', checker)) &&
365
249
  importedName(initializer.expression, checker, REACT_MODULES) === 'memo');
366
250
  }
367
251
  function checkInlineObjectProps(element, context) {
368
252
  const tagName = element.tagName;
253
+ // JSX outside any function, such as a module-scope element, is created once, not on every render.
254
+ if (!ts.findAncestor(element, ts.isFunctionLike))
255
+ return;
369
256
  if (!ts.isIdentifier(tagName) || !isMemoComponent(tagName, context.checker))
370
257
  return;
371
258
  for (const attribute of element.attributes.properties) {
372
259
  const value = ts.isJsxAttribute(attribute) && attribute.initializer;
373
260
  const expression = value && ts.isJsxExpression(value) && value.expression && ts.skipOuterExpressions(value.expression);
374
- if (!expression || !ts.isObjectLiteralExpression(expression))
261
+ const literal = expression && inlineLiteralKind(expression);
262
+ if (!literal)
375
263
  continue;
376
- context.report(attribute, 'react-inline-object-in-jsx-prop', `Passing an inline object literal to \`<${tagName.text} ${attribute.name.getText()}={{ ... }}>\` creates a new reference on every render, defeating the \`memo()\` wrapper of the child. Hoist static objects to module scope or memoise with \`useMemo\`.`, INLINE_OBJECT_REASON);
264
+ context.report(attribute, 'react-inline-object-in-jsx-prop', `Passing an inline ${literal.label} to \`<${tagName.text} ${attribute.name.getText()}={${literal.shape}}>\` creates a new reference on every render, defeating the \`memo()\` wrapper of the child. ${literal.advice}`, INLINE_OBJECT_REASON);
377
265
  }
378
266
  }
267
+ // Object and array literals and inline functions are all new references on every render.
268
+ function inlineLiteralKind(expression) {
269
+ if (ts.isObjectLiteralExpression(expression))
270
+ return {
271
+ label: 'object literal',
272
+ shape: '{ ... }',
273
+ advice: 'Hoist static objects to module scope or memoise with `useMemo`.',
274
+ };
275
+ if (ts.isArrayLiteralExpression(expression))
276
+ return {
277
+ label: 'array literal',
278
+ shape: '[ ... ]',
279
+ advice: 'Hoist static arrays to module scope or memoise with `useMemo`.',
280
+ };
281
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))
282
+ return {
283
+ label: 'function',
284
+ shape: '() => ...',
285
+ advice: 'Wrap the callback in `useCallback` or hoist it out of the component.',
286
+ };
287
+ }
379
288
  // --- Angular
380
289
  // -------------------------------------------------------------------------------------------------
381
290
  function isAngularComponentOrDirective(classNode, checker) {
@@ -413,8 +322,11 @@ function checkAngularClass(classNode, context) {
413
322
  return;
414
323
  checkAngularChangeDetection(classNode, context);
415
324
  const component = componentMetadata(classNode, context.checker);
416
- if (component)
417
- checkNgForTrackBy(component.metadata, context);
325
+ if (component) {
326
+ const template = componentExternalTemplate(component.metadata);
327
+ checkNgForTrackBy(component.metadata, template, context);
328
+ checkTemplateMethodCalls(classNode, component.metadata, template, context);
329
+ }
418
330
  if (!isAngularComponentOrDirective(classNode, context.checker))
419
331
  return;
420
332
  const teardown = angularTeardown(classNode, context.checker);
@@ -459,12 +371,20 @@ function scopeRegistersUnmount(scope, checker) {
459
371
  });
460
372
  return registers;
461
373
  }
462
- function vueLeakInCallback(callback, checker) {
463
- let leak;
374
+ // The resources the hook starts and does not release itself, as `clearInterval(timer)` in the same hook does.
375
+ function vueLeaksInCallback(callback, checker) {
376
+ const acquired = [];
377
+ const calls = [];
464
378
  walkAll(callback, (node) => {
465
- leak ??= leakOfNode(node, checker);
379
+ const leak = leakOfNode(node, checker);
380
+ if (leak)
381
+ acquired.push({ node, leak });
382
+ if (ts.isCallExpression(node))
383
+ calls.push(node);
466
384
  });
467
- return leak;
385
+ return acquired
386
+ .filter(({ node, leak }) => !calls.some((call) => releases(node, leak.release, call, checker)))
387
+ .map(({ leak }) => leak);
468
388
  }
469
389
  function checkVueMounted(call, context) {
470
390
  const callback = call.arguments[0] && ts.skipOuterExpressions(call.arguments[0]);
@@ -474,11 +394,30 @@ function checkVueMounted(call, context) {
474
394
  return;
475
395
  if (scopeRegistersUnmount(enclosingScope(call), context.checker))
476
396
  return;
477
- const leak = vueLeakInCallback(callback, context.checker);
397
+ const [leak] = vueLeaksInCallback(callback, context.checker);
478
398
  if (!leak)
479
399
  return;
480
400
  context.report(call, 'vue-watch-missing-cleanup', `\`onMounted\` registers \`${leak.label}\` without an apparent unmount cleanup, leaking resources when the Vue component unmounts. Release it with \`onUnmounted\` or \`onScopeDispose\`.`, leak.reason);
481
401
  }
402
+ // Options API: `defineComponent({ mounted() { ... } })` with no unmount hook that could release what it started.
403
+ function checkVueOptionsMounted(call, context) {
404
+ if (!isVueImport(call.expression, context.checker, 'defineComponent'))
405
+ return;
406
+ const options = call.arguments[0] && ts.skipOuterExpressions(call.arguments[0]);
407
+ if (!options || !ts.isObjectLiteralExpression(options))
408
+ return;
409
+ const effective = effectiveOptions(options, context.checker);
410
+ const mounted = effective?.get('mounted');
411
+ const body = mounted && optionsHookBody(mounted);
412
+ // Only a `mounted` written in this call is reported, never one a spread brings in.
413
+ if (!effective || !mounted || !body || mounted.parent !== options)
414
+ return;
415
+ const teardowns = teardownBodies(effective, context.checker);
416
+ const leak = vueLeaksInCallback(body, context.checker).find((candidate) => !teardowns.some((teardown) => teardownMayRelease(teardown, candidate.release)));
417
+ if (!leak)
418
+ return;
419
+ context.report(mounted, 'vue-watch-missing-cleanup', `\`mounted\` registers \`${leak.label}\` without a \`beforeUnmount\` or \`unmounted\` hook that releases it, leaking resources when the Vue component unmounts. Release it in \`beforeUnmount\`.`, leak.reason);
420
+ }
482
421
  function hasKeyProperty(propsArgument) {
483
422
  const props = ts.skipOuterExpressions(propsArgument);
484
423
  if (!ts.isObjectLiteralExpression(props))
@@ -527,16 +466,21 @@ function checkCall(call, context) {
527
466
  checkReactEffect(call, context);
528
467
  checkReactIndexKey(call, context);
529
468
  checkVueMounted(call, context);
469
+ checkVueOptionsMounted(call, context);
530
470
  checkVueListKey(call, context);
531
471
  checkAddEventListener(call, context);
472
+ checkForEachLayoutThrashing(call, context);
532
473
  }
533
474
  function checkFrontendNode(node, context) {
534
475
  if (ts.isImportDeclaration(node))
535
476
  checkHeavyBarrelImport(node, context);
536
477
  else if (ts.isCallExpression(node))
537
478
  checkCall(node, context);
538
- else if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node))
479
+ else if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
539
480
  checkInlineObjectProps(node, context);
481
+ checkJsxElement(node, context);
482
+ checkNavigationWithoutLink(node, context);
483
+ }
540
484
  else if (ts.isClassDeclaration(node))
541
485
  checkAngularClass(node, context);
542
486
  else if (isFunctionNode(node))
@@ -356,7 +356,12 @@ function reportUntracked(property, loops, context, templateText, templateUrl) {
356
356
  const candidate = !templateUrl && loops.length === 1 ? angularTrackingCandidate(templateText, loops[0]) : undefined;
357
357
  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)\`.`, undefined, candidate && { angularTracking: { expression: loops[0], ...candidate } });
358
358
  }
359
- function checkNgForTrackBy(metadata, context) {
359
+ // The component's `templateUrl` file, read once per component so every template rule shares the text.
360
+ function componentExternalTemplate(metadata) {
361
+ const external = metadataProperty(metadata, 'templateUrl');
362
+ return external && externalTemplate(external, metadata.getSourceFile().fileName);
363
+ }
364
+ function checkNgForTrackBy(metadata, template, context) {
360
365
  const inline = metadataProperty(metadata, 'template');
361
366
  const inlineText = inline && stringValueOf(inline.initializer);
362
367
  if (inline && inlineText) {
@@ -365,11 +370,10 @@ function checkNgForTrackBy(metadata, context) {
365
370
  reportUntracked(inline, loops, context, inlineText);
366
371
  }
367
372
  const external = metadataProperty(metadata, 'templateUrl');
368
- const template = external && externalTemplate(external, metadata.getSourceFile().fileName);
369
373
  if (!external || !template)
370
374
  return;
371
375
  const loops = untrackedLoops(template.text);
372
376
  if (loops.length)
373
377
  reportUntracked(external, loops, context, template.text, template.url);
374
378
  }
375
- export { checkComponentInComponent, checkNgForTrackBy, isFunctionNode };
379
+ export { HTML_COMMENT, QUOTED_TEXT, checkComponentInComponent, checkNgForTrackBy, componentExternalTemplate, isFunctionNode, metadataProperty, stringValueOf, };
@@ -0,0 +1,171 @@
1
+ // Frontend rules that read one JSX element and its attributes:
2
+ // - frontend-render-blocking-script
3
+ // - react-unthrottled-input-fetch
4
+ import { ts } from '../engine/compiler.js';
5
+ import { isUnshadowedGlobal, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
6
+ import { initializerOf } from '../schema/ts-helpers.js';
7
+ import { REACT_MODULES, importedName, walkSkippingFunctions } from './frontend-helpers.js';
8
+ // `type` values that still run as a classic script; anything else (module, JSON, templates) never blocks parsing.
9
+ const CLASSIC_SCRIPT_TYPES = new Set(['', 'text/javascript', 'application/javascript']);
10
+ // `next/head` exports its component as the default; `next/document` exports `Head`.
11
+ const NEXT_HEAD_EXPORTS = new Map([
12
+ ['next/head', 'default'],
13
+ ['next/document', 'Head'],
14
+ ]);
15
+ // Input types the user types into, one change event per keystroke. Checkboxes, radios, files and
16
+ // pickers change once per deliberate action.
17
+ const TYPED_INPUT_TYPES = new Set(['text', 'search', 'email', 'url', 'tel', 'number', 'password']);
18
+ const TYPED_CHANGE_EVENTS = new Set(['onChange', 'onInput']);
19
+ function attributeNamed(element, name) {
20
+ return element.attributes.properties.find((attribute) => ts.isJsxAttribute(attribute) && ts.isIdentifier(attribute.name) && attribute.name.text === name);
21
+ }
22
+ function hasSpread(element) {
23
+ return element.attributes.properties.some(ts.isJsxSpreadAttribute);
24
+ }
25
+ // `async`, `async=""` or any expression but a literal `false`: a computed `async={isProd}` may be set.
26
+ function mayBeSetFlag(attribute) {
27
+ if (!attribute)
28
+ return false;
29
+ const value = attribute.initializer;
30
+ if (!value || ts.isStringLiteral(value))
31
+ return true;
32
+ return ts.isJsxExpression(value) && unwrapExpression(value.expression)?.kind !== ts.SyntaxKind.FalseKeyword;
33
+ }
34
+ // undefined when the attribute is absent, the literal text when it is a string, null when computed.
35
+ function literalAttribute(attribute) {
36
+ if (!attribute)
37
+ return undefined;
38
+ const value = attribute.initializer;
39
+ if (!value)
40
+ return '';
41
+ if (ts.isStringLiteral(value))
42
+ return value.text;
43
+ const expression = ts.isJsxExpression(value) && value.expression && unwrapExpression(value.expression);
44
+ return expression && ts.isStringLiteralLike(expression) ? expression.text : null;
45
+ }
46
+ // React omits `src={null}`, `src={undefined}` and an empty `src`, so no URL is fetched.
47
+ function hasScriptUrl(attribute) {
48
+ const value = attribute?.initializer;
49
+ if (!value)
50
+ return false;
51
+ if (ts.isStringLiteral(value))
52
+ return value.text.trim() !== '';
53
+ const expression = ts.isJsxExpression(value) && value.expression && unwrapExpression(value.expression);
54
+ if (!expression)
55
+ return false;
56
+ if (ts.isStringLiteralLike(expression))
57
+ return expression.text.trim() !== '';
58
+ if (expression.kind === ts.SyntaxKind.NullKeyword)
59
+ return false;
60
+ return !(ts.isIdentifier(expression) && expression.text === 'undefined');
61
+ }
62
+ // The element the script is rendered inside, skipping fragments, conditionals and other expressions.
63
+ function enclosingElementTag(element) {
64
+ const own = ts.isJsxOpeningElement(element) ? element.parent : element;
65
+ for (let node = own.parent; node && !ts.isFunctionLike(node) && !ts.isSourceFile(node); node = node.parent) {
66
+ if (ts.isJsxElement(node))
67
+ return node.openingElement.tagName;
68
+ }
69
+ }
70
+ function isDocumentHead(tag, checker) {
71
+ if (!tag || !(ts.isIdentifier(tag) || ts.isPropertyAccessExpression(tag)))
72
+ return false;
73
+ if (ts.isIdentifier(tag) && tag.text === 'head')
74
+ return true;
75
+ for (const [module, exported] of NEXT_HEAD_EXPORTS) {
76
+ if (importedName(tag, checker, [module]) === exported)
77
+ return true;
78
+ }
79
+ return false;
80
+ }
81
+ function checkRenderBlockingScript(element, context) {
82
+ if (!ts.isIdentifier(element.tagName) || element.tagName.text !== 'script' || hasSpread(element))
83
+ return;
84
+ if (!hasScriptUrl(attributeNamed(element, 'src')))
85
+ return;
86
+ // Browsers that run modules skip a `noModule` script entirely, so it blocks only legacy browsers.
87
+ const nonBlockingFlags = ['async', 'defer', 'noModule'];
88
+ if (nonBlockingFlags.some((flag) => mayBeSetFlag(attributeNamed(element, flag))))
89
+ return;
90
+ const type = literalAttribute(attributeNamed(element, 'type'));
91
+ if (type === null || (type !== undefined && !CLASSIC_SCRIPT_TYPES.has(type.trim().toLowerCase())))
92
+ return;
93
+ if (!isDocumentHead(enclosingElementTag(element), context.checker))
94
+ return;
95
+ context.report(element, 'frontend-render-blocking-script', 'This `<script src>` in the document head has no `async` or `defer`, so the browser stops parsing the page and paints nothing until the script has downloaded and run, on every page load. Add `defer` (keeps execution order) or `async`, or load it with `next/script` and a non-blocking `strategy`.');
96
+ }
97
+ // The function a handler attribute runs: inline, a local function, or a local `useCallback(fn)`.
98
+ function handlerFunction(expression, checker) {
99
+ const target = unwrapExpression(expression);
100
+ if (ts.isArrowFunction(target) || ts.isFunctionExpression(target))
101
+ return target;
102
+ if (!ts.isIdentifier(target))
103
+ return;
104
+ const declaration = checker.getSymbolAtLocation(target)?.declarations?.[0];
105
+ if (declaration && ts.isFunctionDeclaration(declaration) && declaration.body)
106
+ return declaration;
107
+ const initializer = initializerOf(target, checker);
108
+ if (!initializer || ts.isClassDeclaration(initializer))
109
+ return;
110
+ const value = unwrapExpression(initializer);
111
+ if (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
112
+ return value;
113
+ if (!ts.isCallExpression(value) || importedName(value.expression, checker, REACT_MODULES) !== 'useCallback')
114
+ return;
115
+ const callback = value.arguments[0] && unwrapExpression(value.arguments[0]);
116
+ return callback && (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback)) ? callback : undefined;
117
+ }
118
+ // A `fetch()` the handler itself makes; one inside a timer or another callback is deferred, not per keystroke.
119
+ function callsFetchDirectly(handler, checker) {
120
+ let calls = false;
121
+ walkSkippingFunctions(handler, (node) => {
122
+ if (ts.isCallExpression(node) && isUnshadowedGlobal(unwrapExpression(node.expression), 'fetch', checker))
123
+ calls = true;
124
+ });
125
+ return calls;
126
+ }
127
+ // `Date.now()`, `performance.now()` or `event.timeStamp`: the handler compares times, which is how a hand-written
128
+ // rate limit (`if (now - last.current < 300) return;`) looks, so it may not fetch on every keystroke.
129
+ function readsClock(handler) {
130
+ let reads = false;
131
+ walkSkippingFunctions(handler, (node) => {
132
+ if (!ts.isPropertyAccessExpression(node))
133
+ return;
134
+ const owner = ts.isIdentifier(node.expression) ? node.expression.text : undefined;
135
+ const isNow = node.name.text === 'now' && (owner === 'Date' || owner === 'performance');
136
+ if (isNow || node.name.text === 'timeStamp')
137
+ reads = true;
138
+ });
139
+ return reads;
140
+ }
141
+ function isTypedField(element) {
142
+ if (!ts.isIdentifier(element.tagName) || hasSpread(element))
143
+ return false;
144
+ if (element.tagName.text === 'textarea')
145
+ return true;
146
+ if (element.tagName.text !== 'input')
147
+ return false;
148
+ const type = literalAttribute(attributeNamed(element, 'type'));
149
+ return type === undefined || (type !== null && TYPED_INPUT_TYPES.has(type.trim().toLowerCase()));
150
+ }
151
+ function checkInputFetch(element, context) {
152
+ if (!isTypedField(element))
153
+ return;
154
+ for (const attribute of element.attributes.properties) {
155
+ if (!ts.isJsxAttribute(attribute) || !ts.isIdentifier(attribute.name))
156
+ continue;
157
+ if (!TYPED_CHANGE_EVENTS.has(attribute.name.text))
158
+ continue;
159
+ const value = attribute.initializer;
160
+ const expression = value && ts.isJsxExpression(value) ? value.expression : undefined;
161
+ const handler = expression && handlerFunction(expression, context.checker);
162
+ if (!handler || readsClock(handler) || !callsFetchDirectly(handler, context.checker))
163
+ continue;
164
+ context.report(attribute, 'react-unthrottled-input-fetch', `This \`${attribute.name.text}\` handler calls \`fetch()\` on every keystroke, so typing a word sends one request per character and responses can arrive out of order. Debounce the request (about 300 ms) or keep the text in state and fetch from an effect that aborts the previous request.`);
165
+ }
166
+ }
167
+ function checkJsxElement(element, context) {
168
+ checkRenderBlockingScript(element, context);
169
+ checkInputFetch(element, context);
170
+ }
171
+ export { checkJsxElement };