loadwise 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -1,4 +1,5 @@
1
1
  import { ts } from '../performance/engine/compiler.js';
2
+ import { isUnshadowedGlobal } from '../shared/analysis/ast-semantics.js';
2
3
  import { walkNodes } from './walk.js';
3
4
  import { isAccess, isIgnoredSource, withoutParentheses } from './source-helpers.js';
4
5
  // How far below the untyped value the first read that can throw sits: `req.body.user` is fine,
@@ -268,24 +269,61 @@ function matchesSubject(node, subject, sourceFile) {
268
269
  return true;
269
270
  return (ts.isCallExpression(node) && subject.lookup !== undefined && isLookupGuardCall(node, subject.lookup, sourceFile));
270
271
  }
271
- function mentions(root, subject, sourceFile) {
272
- let found = false;
273
- walkNodes(root, (node) => {
274
- if (!found)
275
- found = matchesSubject(node, subject, sourceFile);
276
- });
277
- return found;
272
+ const nullish = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
273
+ function excludedNullish(expression, truthy, subject, sourceFile) {
274
+ const value = withoutParentheses(expression);
275
+ if (matchesSubject(value, subject, sourceFile))
276
+ return truthy ? nullish : 0;
277
+ if (truthy && isAccess(value) && value.questionDotToken)
278
+ return excludedNullish(value.expression, true, subject, sourceFile);
279
+ if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.ExclamationToken)
280
+ return excludedNullish(value.operand, !truthy, subject, sourceFile);
281
+ if (!ts.isBinaryExpression(value))
282
+ return 0;
283
+ const kind = value.operatorToken.kind;
284
+ if (kind === ts.SyntaxKind.AmpersandAmpersandToken || kind === ts.SyntaxKind.BarBarToken) {
285
+ const left = excludedNullish(value.left, truthy, subject, sourceFile);
286
+ const right = excludedNullish(value.right, truthy, subject, sourceFile);
287
+ // With a truthy AND or a falsy OR, both tests hold. Otherwise only exclusions shared by both paths hold.
288
+ return truthy === (kind === ts.SyntaxKind.AmpersandAmpersandToken) ? left | right : left & right;
289
+ }
290
+ return comparisonExclusions(value, truthy, subject, sourceFile);
291
+ }
292
+ function comparisonExclusions(value, truthy, subject, sourceFile) {
293
+ const kind = value.operatorToken.kind;
294
+ const loose = kind === (truthy ? ts.SyntaxKind.ExclamationEqualsToken : ts.SyntaxKind.EqualsEqualsToken);
295
+ if (!loose && kind !== (truthy ? ts.SyntaxKind.ExclamationEqualsEqualsToken : ts.SyntaxKind.EqualsEqualsEqualsToken))
296
+ return 0;
297
+ const left = withoutParentheses(value.left);
298
+ const right = withoutParentheses(value.right);
299
+ const compared = matchesSubject(left, subject, sourceFile)
300
+ ? right
301
+ : matchesSubject(right, subject, sourceFile)
302
+ ? left
303
+ : undefined;
304
+ if (!compared)
305
+ return 0;
306
+ if (compared.kind === ts.SyntaxKind.NullKeyword)
307
+ return loose ? nullish : ts.TypeFlags.Null;
308
+ if (isUnshadowedGlobal(compared, 'undefined', subject.checker))
309
+ return loose ? nullish : ts.TypeFlags.Undefined;
310
+ return 0;
311
+ }
312
+ function provesPresence(expression, truthy, subject, sourceFile) {
313
+ return excludedNullish(expression, truthy, subject, sourceFile) === nullish;
278
314
  }
279
315
  function exitsEarly(statement) {
280
- let found = false;
281
- walkNodes(statement, (node) => {
282
- if (ts.isReturnStatement(node) ||
283
- ts.isThrowStatement(node) ||
284
- ts.isContinueStatement(node) ||
285
- ts.isBreakStatement(node))
286
- found = true;
287
- });
288
- return found;
316
+ if (ts.isBlock(statement))
317
+ return statement.statements.some(exitsEarly);
318
+ if (ts.isTryStatement(statement))
319
+ return ((!!statement.finallyBlock && exitsEarly(statement.finallyBlock)) ||
320
+ (exitsEarly(statement.tryBlock) && (!statement.catchClause || exitsEarly(statement.catchClause.block))));
321
+ if (ts.isIfStatement(statement))
322
+ return !!statement.elseStatement && exitsEarly(statement.thenStatement) && exitsEarly(statement.elseStatement);
323
+ return (ts.isReturnStatement(statement) ||
324
+ ts.isThrowStatement(statement) ||
325
+ ts.isBreakStatement(statement) ||
326
+ ts.isContinueStatement(statement));
289
327
  }
290
328
  // `assert(x)`, `invariant(x)` and `assert.ok(x)` throw when the check fails.
291
329
  function assertionCall(statement) {
@@ -311,23 +349,25 @@ function setsSubject(node, subject, sourceFile) {
311
349
  normalized(key.getText(sourceFile)) === subject.lookup.keys);
312
350
  }
313
351
  function establishes(root, subject, sourceFile) {
314
- let found = false;
315
- walkNodes(root, (node) => {
316
- if (!found)
317
- found = setsSubject(node, subject, sourceFile);
318
- });
319
- return found;
320
- }
321
- function isNegation(expression) {
322
- const value = withoutParentheses(expression);
323
- return ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.ExclamationToken;
352
+ if (ts.isParenthesizedExpression(root))
353
+ return establishes(root.expression, subject, sourceFile);
354
+ if (ts.isBlock(root))
355
+ return root.statements.some((statement) => establishes(statement, subject, sourceFile));
356
+ if (ts.isIfStatement(root))
357
+ return (!!root.elseStatement &&
358
+ (exitsEarly(root.thenStatement) || establishes(root.thenStatement, subject, sourceFile)) &&
359
+ (exitsEarly(root.elseStatement) || establishes(root.elseStatement, subject, sourceFile)));
360
+ if (ts.isExpressionStatement(root))
361
+ return setsSubject(root.expression, subject, sourceFile);
362
+ return setsSubject(root, subject, sourceFile);
324
363
  }
325
364
  // An early exit, or the get-or-create idiom `if (!map.has(key)) map.set(key, value)`.
326
365
  function ifGuards(statement, subject, sourceFile) {
327
- if (!mentions(statement.expression, subject, sourceFile))
328
- return false;
329
- return (exitsEarly(statement.thenStatement) ||
330
- (isNegation(statement.expression) && establishes(statement.thenStatement, subject, sourceFile)));
366
+ return ((provesPresence(statement.expression, false, subject, sourceFile) &&
367
+ (exitsEarly(statement.thenStatement) || establishes(statement.thenStatement, subject, sourceFile))) ||
368
+ (!!statement.elseStatement &&
369
+ provesPresence(statement.expression, true, subject, sourceFile) &&
370
+ (exitsEarly(statement.elseStatement) || establishes(statement.elseStatement, subject, sourceFile))));
331
371
  }
332
372
  // `cache.get(key) || cache.set(key, value)` and `req.body.user ??= {}` leave the subject present.
333
373
  function fallbackEstablishes(expression, subject, sourceFile) {
@@ -338,7 +378,9 @@ function fallbackEstablishes(expression, subject, sourceFile) {
338
378
  if (kind === ts.SyntaxKind.QuestionQuestionEqualsToken || kind === ts.SyntaxKind.BarBarEqualsToken)
339
379
  return matchesSubject(withoutParentheses(value.left), subject, sourceFile);
340
380
  const isFallback = kind === ts.SyntaxKind.BarBarToken || kind === ts.SyntaxKind.QuestionQuestionToken;
341
- return isFallback && mentions(value.left, subject, sourceFile) && establishes(value.right, subject, sourceFile);
381
+ return (isFallback &&
382
+ matchesSubject(withoutParentheses(value.left), subject, sourceFile) &&
383
+ establishes(value.right, subject, sourceFile));
342
384
  }
343
385
  function guardsLater(statement, subject, sourceFile) {
344
386
  if (ts.isIfStatement(statement))
@@ -346,7 +388,7 @@ function guardsLater(statement, subject, sourceFile) {
346
388
  if (ts.isExpressionStatement(statement) && fallbackEstablishes(statement.expression, subject, sourceFile))
347
389
  return true;
348
390
  const assertion = assertionCall(statement);
349
- return assertion !== undefined && mentions(assertion, subject, sourceFile);
391
+ return assertion?.arguments[0] !== undefined && provesPresence(assertion.arguments[0], true, subject, sourceFile);
350
392
  }
351
393
  function precedingStatementGuards(parent, child, subject, sourceFile) {
352
394
  if (!ts.isBlock(parent) && !ts.isSourceFile(parent) && !ts.isCaseClause(parent) && !ts.isDefaultClause(parent))
@@ -360,26 +402,25 @@ function precedingStatementGuards(parent, child, subject, sourceFile) {
360
402
  // the subject.
361
403
  function conditionGuards(parent, child, subject, sourceFile) {
362
404
  if (ts.isIfStatement(parent) && child !== parent.expression)
363
- return mentions(parent.expression, subject, sourceFile);
405
+ return provesPresence(parent.expression, child === parent.thenStatement, subject, sourceFile);
364
406
  if (ts.isConditionalExpression(parent) && child !== parent.condition)
365
- return mentions(parent.condition, subject, sourceFile);
407
+ return provesPresence(parent.condition, child === parent.whenTrue, subject, sourceFile);
366
408
  if (ts.isWhileStatement(parent) && child === parent.statement)
367
- return mentions(parent.expression, subject, sourceFile);
409
+ return provesPresence(parent.expression, true, subject, sourceFile);
368
410
  if (!ts.isBinaryExpression(parent) || child !== parent.right)
369
411
  return false;
370
412
  const kind = parent.operatorToken.kind;
371
- const isShortCircuit = kind === ts.SyntaxKind.AmpersandAmpersandToken ||
372
- kind === ts.SyntaxKind.BarBarToken ||
373
- kind === ts.SyntaxKind.QuestionQuestionToken;
374
- return isShortCircuit && mentions(parent.left, subject, sourceFile);
413
+ if (kind === ts.SyntaxKind.AmpersandAmpersandToken || kind === ts.SyntaxKind.BarBarToken)
414
+ return provesPresence(parent.left, kind === ts.SyntaxKind.AmpersandAmpersandToken, subject, sourceFile);
415
+ return false;
375
416
  }
376
417
  function isCaughtBy(parent, child) {
377
418
  return ts.isTryStatement(parent) && parent.tryBlock === child && parent.catchClause !== undefined;
378
419
  }
379
420
  // An enclosing try/catch (inside the same function), an enclosing condition that checks the subject, or an
380
421
  // earlier `if (!subject) return` keeps absent data from reaching the read.
381
- function isGuarded(access, subject, sourceFile) {
382
- const guardSubject = guardSubjectOf(subject, sourceFile);
422
+ function isGuarded(access, subject, sourceFile, checker) {
423
+ const guardSubject = { ...guardSubjectOf(subject, sourceFile), checker };
383
424
  let insideSameFunction = true;
384
425
  for (let child = access, parent = access.parent; parent; child = parent, parent = parent.parent) {
385
426
  if (insideSameFunction && isCaughtBy(parent, child))
@@ -434,25 +475,41 @@ function aliasCandidateNames(sourceFile) {
434
475
  if (cached)
435
476
  return cached;
436
477
  const names = new Set();
437
- const constants = [];
478
+ const queue = [];
479
+ const dependents = new Map();
480
+ const seed = (name) => {
481
+ if (names.has(name))
482
+ return;
483
+ names.add(name);
484
+ queue.push(name);
485
+ };
438
486
  walkNodes(sourceFile, (node) => {
439
487
  if (ts.isParameter(node) && ts.isIdentifier(node.name) && hasRequestDecorator(node))
440
- names.add(node.name.text);
488
+ seed(node.name.text);
441
489
  const initializer = constInitializerOf(node);
442
- if (initializer && ts.isVariableDeclaration(node) && ts.isIdentifier(node.name))
443
- constants.push({ name: node.name.text, initializer });
444
- });
445
- const isAliasName = (name) => names.has(name);
446
- for (let grew = true; grew;) {
447
- grew = false;
448
- for (const { name, initializer } of constants) {
449
- if (names.has(name))
450
- continue;
451
- if (!isLookupCallSyntax(initializer) && !mayReadUntypedInput(initializer, Infinity, isAliasName))
452
- continue;
453
- names.add(name);
454
- grew = true;
490
+ if (!initializer || !ts.isVariableDeclaration(node) || !ts.isIdentifier(node.name))
491
+ return;
492
+ const name = node.name.text;
493
+ let rootIdentifier;
494
+ const capturesRoot = mayReadUntypedInput(initializer, Infinity, (root) => {
495
+ rootIdentifier = root;
496
+ return false;
497
+ });
498
+ if (isLookupCallSyntax(initializer) || capturesRoot) {
499
+ seed(name);
500
+ return;
455
501
  }
502
+ if (rootIdentifier !== undefined) {
503
+ const list = dependents.get(rootIdentifier);
504
+ if (list)
505
+ list.push(name);
506
+ else
507
+ dependents.set(rootIdentifier, [name]);
508
+ }
509
+ });
510
+ for (let index = 0; index < queue.length; index++) {
511
+ for (const dependent of dependents.get(queue[index]) ?? [])
512
+ seed(dependent);
456
513
  }
457
514
  aliasNamesByFile.set(sourceFile, names);
458
515
  return names;
@@ -500,7 +557,7 @@ function checkBoundaryAccess(sourceFile, file, checker) {
500
557
  if (!isAccess(node))
501
558
  return;
502
559
  const risky = riskyAccess(node, checker, sourceFile);
503
- if (!risky || isGuarded(node, risky.subject, sourceFile))
560
+ if (!risky || isGuarded(node, risky.subject, sourceFile, checker))
504
561
  return;
505
562
  const scope = ts.findAncestor(node, ts.isFunctionLike) ?? sourceFile;
506
563
  const key = `${scope.pos}:${scope.end}:${normalized(risky.subject.getText(sourceFile))}`;
@@ -88,15 +88,27 @@ function isZeroLiteral(expression) {
88
88
  const value = withoutParentheses(expression);
89
89
  return ts.isNumericLiteral(value) && Number(value.text) === 0;
90
90
  }
91
- // `prev => prev`, `prev || true` and `prev + 0` settle on a value React bails out on; `prev + 1` and `[...prev, x]` never do.
92
- function changesValue(result) {
91
+ function isEmptyStringLiteral(expression) {
92
+ const value = withoutParentheses(expression);
93
+ return ts.isStringLiteralLike(value) && value.text === '';
94
+ }
95
+ // `prev => prev`, `prev || true`, `prev + 0`, and `prev + ''` settle on a value React bails out on; `prev + 1`, `!prev`, and `[...prev, x]` never do.
96
+ function changesValue(result, previousName) {
93
97
  if (ts.isArrayLiteralExpression(result) || ts.isObjectLiteralExpression(result))
94
98
  return true;
99
+ if (ts.isPrefixUnaryExpression(result) && result.operator === ts.SyntaxKind.ExclamationToken) {
100
+ // Only `!previous` flips the value; `!!previous` and `!true` settle on a value React bails out on.
101
+ const operand = withoutParentheses(result.operand);
102
+ return previousName !== undefined && ts.isIdentifier(operand) && operand.text === previousName;
103
+ }
95
104
  if (!ts.isBinaryExpression(result))
96
105
  return false;
97
106
  const kind = result.operatorToken.kind;
98
107
  const isArithmetic = kind === ts.SyntaxKind.PlusToken || kind === ts.SyntaxKind.MinusToken;
99
- return isArithmetic && !isZeroLiteral(result.left) && !isZeroLiteral(result.right);
108
+ return (isArithmetic &&
109
+ !isZeroLiteral(result.left) &&
110
+ !isZeroLiteral(result.right) &&
111
+ (kind !== ts.SyntaxKind.PlusToken || (!isEmptyStringLiteral(result.left) && !isEmptyStringLiteral(result.right))));
100
112
  }
101
113
  function returnsOrThrows(statement) {
102
114
  let exits = false;
@@ -123,7 +135,9 @@ function isFreshValue(argument, checker) {
123
135
  if (!updater || updater.parameters.length === 0)
124
136
  return false;
125
137
  const results = updaterResults(updater);
126
- return results.length > 0 && results.every((result) => result !== undefined && changesValue(result));
138
+ const previousParameter = updater.parameters[0].name;
139
+ const previousName = ts.isIdentifier(previousParameter) ? previousParameter.text : undefined;
140
+ return results.length > 0 && results.every((result) => result !== undefined && changesValue(result, previousName));
127
141
  }
128
142
  function freshSetterCall(expression, checker) {
129
143
  const call = withoutParentheses(expression);
@@ -0,0 +1,258 @@
1
+ // The interval rule of the resource-leak checker: a `setInterval` whose handle is dropped or never cleared.
2
+ import { ts } from '../performance/engine/compiler.js';
3
+ import { calleeName } from '../performance/analysis/call-syntax.js';
4
+ import { walkNodes } from './walk.js';
5
+ import { declaringStatement, findingAt, importedReference, importsModule, noMethods, outermostWrapper, referenceKind, referencesTo, sameMembers, } from './resource-leaks.js';
6
+ const frontendFramework = /^(?:react|preact|vue|@vue\/.+|svelte|solid-js|@angular\/core)$/;
7
+ const frontendLifecycleCallbacks = new Set([
8
+ 'useEffect',
9
+ 'useLayoutEffect',
10
+ 'useInsertionEffect',
11
+ 'onMounted',
12
+ 'onBeforeMount',
13
+ 'onUpdated',
14
+ 'onActivated',
15
+ 'watch',
16
+ 'watchEffect',
17
+ 'watchPostEffect',
18
+ ]);
19
+ const frontendLifecycleMethods = new Set([
20
+ 'setup',
21
+ 'mounted',
22
+ 'created',
23
+ 'beforeMount',
24
+ 'componentDidMount',
25
+ 'componentDidUpdate',
26
+ 'ngOnInit',
27
+ 'ngOnChanges',
28
+ 'ngAfterViewInit',
29
+ 'ngAfterContentInit',
30
+ ]);
31
+ const startupFunctionNames = new Set(['main', 'bootstrap']);
32
+ // A background timer started here is the singleton timer of the service, not one per call.
33
+ const singletonInitializerNames = new Set([
34
+ 'onModuleInit',
35
+ 'onApplicationBootstrap',
36
+ 'init',
37
+ 'initialize',
38
+ 'start',
39
+ 'setup',
40
+ 'register',
41
+ 'listen',
42
+ ]);
43
+ // A callback of these runs once when the program starts, like top-level code.
44
+ const startupCallbackOwners = new Set(['listen', 'once', 'then', 'whenReady', 'ready']);
45
+ const reactHookName = /^use[A-Z]/;
46
+ function functionNameOf(functionNode) {
47
+ if ((ts.isMethodDeclaration(functionNode) ||
48
+ ts.isFunctionDeclaration(functionNode) ||
49
+ ts.isFunctionExpression(functionNode)) &&
50
+ functionNode.name &&
51
+ ts.isIdentifier(functionNode.name))
52
+ return functionNode.name.text;
53
+ if (!ts.isArrowFunction(functionNode) && !ts.isFunctionExpression(functionNode))
54
+ return;
55
+ const owner = functionNode.parent;
56
+ if ((ts.isPropertyAssignment(owner) || ts.isVariableDeclaration(owner)) && ts.isIdentifier(owner.name))
57
+ return owner.name.text;
58
+ }
59
+ // A callback handed directly to a call, as opposed to one stored under a name.
60
+ function callbackOwner(functionNode) {
61
+ const call = functionNode.parent;
62
+ return ts.isCallExpression(call) && call.arguments.some((argument) => argument === functionNode) ? call : undefined;
63
+ }
64
+ // React, Vue and Angular lifecycles are covered by the frontend cleanup rules.
65
+ function insideFrontendLifecycle(node) {
66
+ for (let current = node.parent; current; current = current.parent) {
67
+ if (!ts.isFunctionLike(current))
68
+ continue;
69
+ const name = functionNameOf(current);
70
+ if (name !== undefined && (frontendLifecycleMethods.has(name) || reactHookName.test(name)))
71
+ return true;
72
+ const owner = callbackOwner(current);
73
+ const ownerName = owner && calleeName(owner);
74
+ if (ownerName !== undefined && frontendLifecycleCallbacks.has(ownerName))
75
+ return true;
76
+ }
77
+ return false;
78
+ }
79
+ // `main()`, an immediately invoked function or a `listen(...)` callback runs once at startup, where a
80
+ // timer that lives as long as the process is intended.
81
+ function isStartupFunction(functionNode) {
82
+ const name = functionNameOf(functionNode);
83
+ if (name !== undefined && startupFunctionNames.has(name))
84
+ return true;
85
+ const call = ts.isFunctionExpression(functionNode) || ts.isArrowFunction(functionNode)
86
+ ? outermostWrapper(functionNode).parent
87
+ : undefined;
88
+ if (call && ts.isCallExpression(call) && ts.skipOuterExpressions(call.expression) === functionNode)
89
+ return true;
90
+ const owner = callbackOwner(functionNode);
91
+ const ownerName = owner && calleeName(owner);
92
+ return ownerName !== undefined && startupCallbackOwners.has(ownerName);
93
+ }
94
+ // A constructor or lifecycle hook runs once per instance of a singleton service, so a timer it
95
+ // starts without keeping the handle is the service's background timer.
96
+ function isSingletonInitializer(functionNode) {
97
+ if (ts.isConstructorDeclaration(functionNode))
98
+ return true;
99
+ const name = functionNameOf(functionNode);
100
+ return name !== undefined && singletonInitializerNames.has(name);
101
+ }
102
+ function enclosingFunction(node) {
103
+ for (let current = node.parent; current; current = current.parent)
104
+ if (ts.isFunctionLike(current))
105
+ return current;
106
+ }
107
+ // `this` belongs to the nearest non-arrow function, so an arrow function inside an object literal keeps
108
+ // the enclosing class as the owner while an ordinary object method makes the object the owner.
109
+ function isStaticMember(node) {
110
+ if (ts.isClassStaticBlockDeclaration(node))
111
+ return true;
112
+ return ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === ts.SyntaxKind.StaticKeyword);
113
+ }
114
+ function thisOwner(handle) {
115
+ let bindsThis = false;
116
+ let isStatic = false;
117
+ for (let current = handle.parent; current; current = current.parent) {
118
+ if (ts.isClassLike(current))
119
+ return { owner: current, isStatic };
120
+ if (ts.isObjectLiteralExpression(current) && bindsThis)
121
+ return { owner: current, isStatic: false };
122
+ if (ts.isFunctionLike(current) && !ts.isArrowFunction(current))
123
+ bindsThis = true;
124
+ if (isStaticMember(current))
125
+ isStatic = true;
126
+ }
127
+ return { owner: undefined, isStatic: false };
128
+ }
129
+ // `this` in a method of `const poller = { ... }` is the same object as the named receiver `poller.member`.
130
+ function namedObjectDeclaration(literal) {
131
+ let wrapper = literal;
132
+ while (ts.isParenthesizedExpression(wrapper.parent) ||
133
+ ts.isAsExpression(wrapper.parent) ||
134
+ ts.isSatisfiesExpression(wrapper.parent)) {
135
+ wrapper = wrapper.parent;
136
+ }
137
+ const parent = wrapper.parent;
138
+ return ts.isVariableDeclaration(parent) && parent.initializer === wrapper && ts.isIdentifier(parent.name)
139
+ ? parent
140
+ : undefined;
141
+ }
142
+ // An inherited member resolves to its declaring class, so a derived assignment matches a base cleanup;
143
+ // a static `this` matches the explicit `Class.member` form.
144
+ function thisHandleKey(handle, checker) {
145
+ const { owner, isStatic } = thisOwner(handle);
146
+ if (isStatic && owner)
147
+ return `prop:${owner.pos}:${handle.name.text}`;
148
+ const namedObject = owner && ts.isObjectLiteralExpression(owner) ? namedObjectDeclaration(owner) : undefined;
149
+ if (namedObject)
150
+ return `prop:${namedObject.pos}:${handle.name.text}`;
151
+ const declaration = checker.getSymbolAtLocation(handle)?.valueDeclaration;
152
+ const declaringClass = declaration && ts.isClassLike(declaration.parent) ? declaration.parent : owner;
153
+ return `this:${declaringClass ? declaringClass.pos : 'file'}:${handle.name.text}`;
154
+ }
155
+ function handleKey(expression, checker) {
156
+ const handle = ts.skipOuterExpressions(expression);
157
+ if (ts.isIdentifier(handle)) {
158
+ const symbol = checker.getSymbolAtLocation(handle);
159
+ const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
160
+ return declaration ? `id:${declaration.pos}:${handle.text}` : `id:unbound:${handle.text}`;
161
+ }
162
+ if (!ts.isPropertyAccessExpression(handle))
163
+ return undefined;
164
+ const receiver = ts.skipOuterExpressions(handle.expression);
165
+ if (receiver.kind === ts.SyntaxKind.ThisKeyword || receiver.kind === ts.SyntaxKind.SuperKeyword) {
166
+ return thisHandleKey(handle, checker);
167
+ }
168
+ if (ts.isIdentifier(receiver)) {
169
+ const symbol = checker.getSymbolAtLocation(receiver);
170
+ const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
171
+ return `prop:${declaration ? declaration.pos : receiver.text}:${handle.name.text}`;
172
+ }
173
+ const symbol = checker.getSymbolAtLocation(handle);
174
+ const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
175
+ return `prop:${declaration ? declaration.pos : handle.expression.getText()}:${handle.name.text}`;
176
+ }
177
+ function collectHandledNames(sourceFile, checker) {
178
+ const handled = { cleared: new Set(), unreferenced: new Set() };
179
+ walkNodes(sourceFile, (node) => {
180
+ if (!ts.isCallExpression(node))
181
+ return;
182
+ const callee = ts.skipOuterExpressions(node.expression);
183
+ const calledName = calleeName(node);
184
+ if (calledName === 'clearInterval' || calledName === 'clearTimeout') {
185
+ const key = node.arguments[0] && handleKey(node.arguments[0], checker);
186
+ if (key !== undefined)
187
+ handled.cleared.add(key);
188
+ }
189
+ else if (calledName === 'unref' && ts.isPropertyAccessExpression(callee)) {
190
+ const key = handleKey(callee.expression, checker);
191
+ if (key !== undefined)
192
+ handled.unreferenced.add(key);
193
+ }
194
+ });
195
+ return handled;
196
+ }
197
+ function isIntervalCall(call, checker) {
198
+ const callee = ts.skipOuterExpressions(call.expression);
199
+ if (ts.isPropertyAccessExpression(callee)) {
200
+ const receiver = ts.skipOuterExpressions(callee.expression);
201
+ return (callee.name.text === 'setInterval' &&
202
+ ts.isIdentifier(receiver) &&
203
+ ['window', 'globalThis'].includes(receiver.text));
204
+ }
205
+ if (!ts.isIdentifier(callee) || callee.text !== 'setInterval')
206
+ return false;
207
+ const origin = importedReference(callee, checker);
208
+ if (origin)
209
+ return origin.moduleName === 'timers' && sameMembers(origin.members, ['setInterval']);
210
+ // A local function that happens to be named setInterval is not the timer.
211
+ const declarations = checker.getSymbolAtLocation(callee)?.declarations ?? [];
212
+ return declarations.every((declaration) => declaration.getSourceFile().isDeclarationFile);
213
+ }
214
+ function isDiscarded(node) {
215
+ const parent = node.parent;
216
+ if (ts.isExpressionStatement(parent))
217
+ return true;
218
+ return ts.isVoidExpression(parent) && ts.isExpressionStatement(parent.parent);
219
+ }
220
+ function intervalLeaks(call, checker, handled) {
221
+ const node = outermostWrapper(call);
222
+ const parent = node.parent;
223
+ if (isDiscarded(node))
224
+ return true;
225
+ if (ts.isVariableDeclaration(parent) && parent.initializer === node && ts.isIdentifier(parent.name)) {
226
+ const statement = declaringStatement(parent);
227
+ if (!statement)
228
+ return false;
229
+ // Anything beyond reading a property of the handle, clearing or returning it, ends the search.
230
+ return referencesTo(parent, statement.parent, checker).every((reference) => referenceKind(reference, statement.parent, noMethods, new Set(['unref'])) === 'use');
231
+ }
232
+ if (!ts.isBinaryExpression(parent) ||
233
+ parent.right !== node ||
234
+ parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
235
+ return false;
236
+ const key = handleKey(parent.left, checker);
237
+ return key !== undefined && !handled.cleared.has(key) && !handled.unreferenced.has(key);
238
+ }
239
+ function checkIntervals(sourceFile, file, checker, findings) {
240
+ if (!sourceFile.text.includes('setInterval'))
241
+ return;
242
+ if (importsModule(sourceFile, (moduleName) => frontendFramework.test(moduleName)))
243
+ return;
244
+ const handled = collectHandledNames(sourceFile, checker);
245
+ walkNodes(sourceFile, (node) => {
246
+ if (!ts.isCallExpression(node) || !isIntervalCall(node, checker))
247
+ return;
248
+ const owner = enclosingFunction(node);
249
+ if (!owner || isStartupFunction(owner) || insideFrontendLifecycle(node))
250
+ return;
251
+ if (isDiscarded(outermostWrapper(node)) && isSingletonInitializer(owner))
252
+ return;
253
+ if (!intervalLeaks(node, checker, handled))
254
+ return;
255
+ findings.push(findingAt(sourceFile, file, node, 'interval-not-cleared', 'This setInterval handle is discarded or never passed to clearInterval, so the timer keeps running after its owner is gone and each call adds another. Keep the handle and clear it when the owner stops.'));
256
+ });
257
+ }
258
+ export { checkIntervals, enclosingFunction, isIntervalCall };