loadwise 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/README.md +175 -115
  2. package/dist/bin/loadwise.js +132 -67
  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/frontend-detect.js +6 -5
  10. package/dist/lib/accessibility/jsx-elements.js +13 -3
  11. package/dist/lib/accessibility/markup-files.js +7 -2
  12. package/dist/lib/accessibility/rule-ids.js +3 -0
  13. package/dist/lib/accessibility/rules.js +128 -41
  14. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  15. package/dist/lib/accessibility/template-attributes.js +5 -3
  16. package/dist/lib/accessibility/template-elements.js +25 -6
  17. package/dist/lib/accessibility/template-file.js +40 -25
  18. package/dist/lib/accessibility/usage.js +10 -2
  19. package/dist/lib/editor/accessibility-examples.js +6 -1
  20. package/dist/lib/editor/actions.js +46 -7
  21. package/dist/lib/editor/apply-fix.js +69 -4
  22. package/dist/lib/editor/configured-setup.js +63 -0
  23. package/dist/lib/editor/diagnostics.js +206 -17
  24. package/dist/lib/editor/dismissals.js +85 -26
  25. package/dist/lib/editor/editor-document.js +5 -2
  26. package/dist/lib/editor/editor-launcher.js +170 -0
  27. package/dist/lib/editor/fix-edits.js +19 -0
  28. package/dist/lib/editor/jetbrains-setup.js +53 -0
  29. package/dist/lib/editor/language-server.js +80 -24
  30. package/dist/lib/editor/managed-config.js +37 -0
  31. package/dist/lib/editor/native-setup.js +86 -0
  32. package/dist/lib/editor/perf-watch.js +8 -6
  33. package/dist/lib/editor/release-vsix.js +61 -0
  34. package/dist/lib/editor/reliability-examples.js +15 -0
  35. package/dist/lib/editor/scan-session.js +29 -8
  36. package/dist/lib/editor/server-commands.js +38 -9
  37. package/dist/lib/editor/setup-server.js +87 -0
  38. package/dist/lib/editor/setup-vim.js +63 -0
  39. package/dist/lib/editor/setup.js +131 -0
  40. package/dist/lib/editor/stdio-setup.js +6 -0
  41. package/dist/lib/editor/workspace-files.js +61 -7
  42. package/dist/lib/editor/workspace-paths.js +41 -1
  43. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  44. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  45. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  46. package/dist/lib/maintainability/cli/inputs.js +12 -3
  47. package/dist/lib/maintainability/cli.js +18 -5
  48. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  49. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  50. package/dist/lib/maintainability/examples.js +4 -0
  51. package/dist/lib/maintainability/quality/functions.js +9 -6
  52. package/dist/lib/maintainability/quality/limits.js +19 -0
  53. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  54. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  55. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  56. package/dist/lib/maintainability/rule-ids.js +3 -0
  57. package/dist/lib/maintainability/scan-changed.js +4 -1
  58. package/dist/lib/maintainability/scan-worker.js +6 -2
  59. package/dist/lib/maintainability/scan.js +21 -8
  60. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  61. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  62. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  63. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  64. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  65. package/dist/lib/performance/analysis/source-options.js +7 -6
  66. package/dist/lib/performance/analyze.js +16 -3
  67. package/dist/lib/performance/cli/changed-lines.js +8 -1
  68. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  69. package/dist/lib/performance/cli/cli-output.js +4 -0
  70. package/dist/lib/performance/cli/cli-scan.js +21 -2
  71. package/dist/lib/performance/cli.js +16 -7
  72. package/dist/lib/performance/collections/memory-growth.js +55 -12
  73. package/dist/lib/performance/contracts/openapi.js +13 -4
  74. package/dist/lib/performance/datastores/pg-integrity.js +68 -22
  75. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  76. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  77. package/dist/lib/performance/datastores/pooling.js +62 -3
  78. package/dist/lib/performance/datastores/redis.js +94 -18
  79. package/dist/lib/performance/datastores/session-store.js +2 -1
  80. package/dist/lib/performance/db/checks.js +19 -8
  81. package/dist/lib/performance/db/gateway.js +3 -1
  82. package/dist/lib/performance/db/plan-estimates.js +4 -4
  83. package/dist/lib/performance/engine/native-syntax.js +3 -0
  84. package/dist/lib/performance/engine/native.js +11 -7
  85. package/dist/lib/performance/evidence/plans.js +7 -5
  86. package/dist/lib/performance/evidence/traces.js +21 -1
  87. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  88. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  89. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  90. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  91. package/dist/lib/performance/frontend/frontend-perf.js +149 -74
  92. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  93. package/dist/lib/performance/migrations/extract-code.js +13 -5
  94. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  95. package/dist/lib/performance/migrations/operations.js +56 -13
  96. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  97. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  98. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  99. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  100. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  101. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  102. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  103. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  104. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  105. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  106. package/dist/lib/performance/polyglot.js +111 -14
  107. package/dist/lib/performance/projects.js +3 -3
  108. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  109. package/dist/lib/performance/request/backend-mastery.js +151 -42
  110. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  111. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  112. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  113. package/dist/lib/performance/request/mongoose-lean.js +298 -46
  114. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  115. package/dist/lib/performance/request/phase5-ast.js +6 -7
  116. package/dist/lib/performance/request/phase5-rules.js +204 -23
  117. package/dist/lib/performance/request/request-handlers.js +120 -23
  118. package/dist/lib/performance/request/sql-select-star.js +150 -0
  119. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  120. package/dist/lib/performance/request/upload-limits.js +5 -1
  121. package/dist/lib/performance/site-fix.js +4 -4
  122. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  123. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  124. package/dist/lib/performance/site-fixes/collections.js +1 -2
  125. package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
  126. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  127. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  128. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  129. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  130. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  131. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  132. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  133. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  134. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  135. package/dist/lib/reliability/boundary-access.js +114 -57
  136. package/dist/lib/reliability/react-bugs.js +29 -7
  137. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  138. package/dist/lib/reliability/resource-leaks.js +209 -195
  139. package/dist/lib/reliability/rule-ids.js +10 -1
  140. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  141. package/dist/lib/reliability/swallowed-errors.js +107 -21
  142. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  143. package/dist/lib/reliability/usage.js +16 -5
  144. package/dist/lib/reliability/walk.js +3 -2
  145. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  146. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  147. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  148. package/dist/lib/security/auth-crypto/shared.js +3 -1
  149. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  150. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  151. package/dist/lib/security/cli.js +21 -6
  152. package/dist/lib/security/cookie-credentials.js +115 -0
  153. package/dist/lib/security/cookie-csrf.js +241 -0
  154. package/dist/lib/security/deps/advisory.js +50 -109
  155. package/dist/lib/security/deps/cli.js +1 -1
  156. package/dist/lib/security/deps/cvss-score.js +14 -0
  157. package/dist/lib/security/deps/fixed-version.js +97 -0
  158. package/dist/lib/security/deps/lockfiles.js +135 -74
  159. package/dist/lib/security/deps/osv.js +11 -3
  160. package/dist/lib/security/deps/scan.js +47 -20
  161. package/dist/lib/security/deps/yarn-lock.js +158 -0
  162. package/dist/lib/security/examples/injection.cjs +4 -0
  163. package/dist/lib/security/exposure/cookies.js +17 -2
  164. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  165. package/dist/lib/security/exposure/frontend-security.js +21 -14
  166. package/dist/lib/security/exposure/jsx-url.js +18 -33
  167. package/dist/lib/security/exposure/logging.js +49 -10
  168. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  169. package/dist/lib/security/exposure/react-html.js +26 -0
  170. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  171. package/dist/lib/security/files/compose.js +126 -1
  172. package/dist/lib/security/files/dockerfile.js +62 -4
  173. package/dist/lib/security/files/index.js +1 -1
  174. package/dist/lib/security/injection/command.js +46 -18
  175. package/dist/lib/security/injection/index.js +2 -0
  176. package/dist/lib/security/injection/ldap.js +86 -0
  177. package/dist/lib/security/injection/nosql.js +28 -4
  178. package/dist/lib/security/injection/redos.js +1 -1
  179. package/dist/lib/security/injection/rule-ids.js +1 -0
  180. package/dist/lib/security/injection/shared.js +5 -1
  181. package/dist/lib/security/injection/sql.js +28 -13
  182. package/dist/lib/security/lexical-declaration.js +113 -0
  183. package/dist/lib/security/pg-dynamic-query.js +28 -1
  184. package/dist/lib/security/pg-identifier-guards.js +107 -3
  185. package/dist/lib/security/phase5-rules.js +26 -135
  186. package/dist/lib/security/polyglot.js +2 -2
  187. package/dist/lib/security/redirect-settings.js +98 -0
  188. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  189. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  190. package/dist/lib/security/request-forgery/shared.js +1 -7
  191. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  192. package/dist/lib/security/rule-descriptions.js +5 -1
  193. package/dist/lib/security/rule-ids.js +7 -0
  194. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  195. package/dist/lib/security/site-fixes/exposure.js +21 -3
  196. package/dist/lib/security/site-fixes/files.js +11 -13
  197. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  198. package/dist/lib/security/site-fixes/injection.js +17 -4
  199. package/dist/lib/security/site-fixes/jwt.js +1 -20
  200. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  201. package/dist/lib/security/taint/binding-inputs.js +236 -0
  202. package/dist/lib/security/taint/filename-guard.js +45 -45
  203. package/dist/lib/security/taint/guards.js +14 -8
  204. package/dist/lib/security/taint/index.js +126 -154
  205. package/dist/lib/security/taint/propagate.js +43 -9
  206. package/dist/lib/security/taint/record-writes.js +161 -0
  207. package/dist/lib/security/taint/resolution-cache.js +13 -7
  208. package/dist/lib/security/taint/sanitizers.js +89 -5
  209. package/dist/lib/security/taint/trace-nodes.js +61 -0
  210. package/dist/lib/security/taint/validators.js +89 -9
  211. package/dist/lib/shared/agent/agent-init.js +28 -5
  212. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  213. package/dist/lib/shared/agent/agent-session.js +6 -1
  214. package/dist/lib/shared/agent/agent-verify.js +58 -11
  215. package/dist/lib/shared/agent/git-hook.js +17 -6
  216. package/dist/lib/shared/agent/review-delivery.js +1 -1
  217. package/dist/lib/shared/agent/review-mcp.js +8 -2
  218. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  219. package/dist/lib/shared/analysis/scan-cache.js +99 -14
  220. package/dist/lib/shared/check.js +172 -20
  221. package/dist/lib/shared/cli-dispatch.js +17 -0
  222. package/dist/lib/shared/config.js +27 -10
  223. package/dist/lib/shared/explain.js +1 -1
  224. package/dist/lib/shared/fix/fix-convergence.js +19 -31
  225. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  226. package/dist/lib/shared/fix/fix-imports.js +4 -162
  227. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  228. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  229. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  230. package/dist/lib/shared/fix/fix-presentation.js +9 -6
  231. package/dist/lib/shared/fix/fix-safety.js +32 -1
  232. package/dist/lib/shared/fix/fix-scope.js +82 -0
  233. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  234. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  235. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  236. package/dist/lib/shared/fix/project-file-access.js +17 -26
  237. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  238. package/dist/lib/shared/fix.js +241 -104
  239. package/dist/lib/shared/formats/finding-location.js +4 -1
  240. package/dist/lib/shared/formats/github.js +3 -3
  241. package/dist/lib/shared/formats/sarif.js +9 -3
  242. package/dist/lib/shared/report-fp.js +97 -0
  243. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  244. package/dist/lib/shared/reporting/baseline.js +7 -5
  245. package/dist/lib/shared/reporting/check-text.js +50 -0
  246. package/dist/lib/shared/reporting/pillars.js +54 -19
  247. package/dist/lib/shared/reporting/source-report.js +3 -0
  248. package/dist/lib/shared/system/atomic-write.js +5 -2
  249. package/dist/lib/shared/system/glob.js +34 -8
  250. package/dist/lib/shared/system/sentry.js +222 -0
  251. package/dist/lib/shared/system/shell-argument.js +5 -1
  252. package/dist/lib/shared/system/terminal-safe.js +3 -2
  253. package/dist/lib/shared/system/terminal-style.js +131 -0
  254. package/dist/lib/shared/workspaces.js +15 -3
  255. package/docs/assets/cli-workflow.gif +0 -0
  256. package/integrations/sublime/plugin.py +22 -0
  257. package/integrations/zed/Cargo.lock +845 -0
  258. package/integrations/zed/Cargo.toml +11 -0
  259. package/integrations/zed/extension.toml +11 -0
  260. package/integrations/zed/src/lib.rs +25 -0
  261. package/package.json +15 -3
  262. package/plugin/.claude-plugin/plugin.json +1 -1
  263. package/plugin/commands/loadwise.md +11 -6
  264. package/plugin/hooks/check-edited-file.mjs +27 -5
  265. package/polyglot/performance/rules/csharp.yml +34 -5
  266. package/polyglot/performance/rules/java.yml +24 -1
  267. package/polyglot/performance/rules/python.yml +74 -2
  268. package/polyglot/performance/sgconfig.yml +1 -0
  269. package/polyglot/reliability/rules/csharp.yml +12 -6
  270. package/polyglot/reliability/rules/go.yml +86 -6
  271. package/polyglot/reliability/rules/java.yml +22 -1
  272. package/polyglot/reliability/sgconfig.yml +1 -0
  273. package/polyglot/security/rules/go.yml +100 -22
  274. package/polyglot/security/rules/python.yml +74 -6
  275. package/polyglot/security/rules/rust.yml +65 -0
  276. package/polyglot/security/sgconfig.yml +1 -0
  277. package/schema/loadwise.config.schema.json +556 -76
  278. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -73,6 +73,22 @@ function isContractReference(identifier) {
73
73
  return false;
74
74
  return Boolean(ts.findAncestor(identifier, ts.isHeritageClause));
75
75
  }
76
+ function declarationSignatures(statement) {
77
+ if (ts.isVariableStatement(statement) &&
78
+ hasModifier(statement, ts.SyntaxKind.ExportKeyword) &&
79
+ !hasModifier(statement, ts.SyntaxKind.DefaultKeyword)) {
80
+ return statement.declarationList.declarations.flatMap((declaration) => {
81
+ const initializer = declaration.initializer && ts.skipOuterExpressions(declaration.initializer);
82
+ const functionParts = initializer && ts.isFunctionLike(initializer) ? functionSignature(initializer) : [];
83
+ const parts = [...(declaration.type ? [declaration.type] : []), ...functionParts];
84
+ if (parts.length === 0)
85
+ return [];
86
+ return bindingNames(declaration.name).map((name) => ({ owner: name.text, parts }));
87
+ });
88
+ }
89
+ const [outer] = declaredExports(statement);
90
+ return outer ? [{ owner: outer.name, parts: signatureParts(statement) }] : [];
91
+ }
76
92
  // For each exported declaration, the other exports whose signature names it.
77
93
  function signatureExposure(statements) {
78
94
  const exportNameByLocal = new Map();
@@ -83,20 +99,19 @@ function signatureExposure(statements) {
83
99
  }
84
100
  const exposedBy = new Map();
85
101
  for (const statement of statements) {
86
- const [outer] = declaredExports(statement);
87
- if (!outer)
88
- continue;
89
- for (const part of signatureParts(statement)) {
90
- walkNodes(part, (node) => {
91
- if (!ts.isIdentifier(node))
92
- return;
93
- const inner = exportNameByLocal.get(node.text);
94
- if (!inner || inner === outer.name || !isContractReference(node))
95
- return;
96
- const owners = exposedBy.get(inner) ?? new Set();
97
- owners.add(outer.name);
98
- exposedBy.set(inner, owners);
99
- });
102
+ for (const { owner, parts } of declarationSignatures(statement)) {
103
+ for (const part of parts) {
104
+ walkNodes(part, (node) => {
105
+ if (!ts.isIdentifier(node))
106
+ return;
107
+ const inner = exportNameByLocal.get(node.text);
108
+ if (!inner || inner === owner || !isContractReference(node))
109
+ return;
110
+ const owners = exposedBy.get(inner) ?? new Set();
111
+ owners.add(owner);
112
+ exposedBy.set(inner, owners);
113
+ });
114
+ }
100
115
  }
101
116
  }
102
117
  return exposedBy;
@@ -205,21 +220,28 @@ function typeReexportRemoval(sourceFile, statement) {
205
220
  return;
206
221
  const lines = sourceFile.text.split(/\r?\n/);
207
222
  const rowOf = (offset) => sourceFile.getLineAndCharacterOfPosition(offset).line;
208
- const first = rowOf(declaration.getStart(sourceFile));
223
+ let first = rowOf(declaration.getStart(sourceFile));
209
224
  const exportRow = rowOf(statement.getStart(sourceFile));
225
+ const exportEndRow = rowOf(statement.end);
210
226
  const removed = new Set();
211
227
  for (let row = first; row <= rowOf(declaration.end); row++)
212
228
  removed.add(row);
213
- removed.add(exportRow);
229
+ for (let row = exportRow; row <= exportEndRow; row++)
230
+ removed.add(row);
214
231
  // Keep one blank line where the re-export sat between two.
215
- if (!lines[exportRow - 1]?.trim() && !lines[exportRow + 1]?.trim() && exportRow + 1 < lines.length)
216
- removed.add(exportRow + 1);
232
+ if (!lines[exportRow - 1]?.trim() && !lines[exportEndRow + 1]?.trim() && exportEndRow + 1 < lines.length)
233
+ removed.add(exportEndRow + 1);
217
234
  let last = Math.max(...removed);
218
- // A line change needs at least one remaining line, so include the next one unchanged.
235
+ // A line change needs at least one remaining line, so include an adjacent line unchanged.
219
236
  if (last + 1 < lines.length)
220
237
  last++;
221
- const span = lines.slice(first, last + 1);
222
- const kept = span.filter((_line, index) => !removed.has(first + index));
238
+ let span = lines.slice(first, last + 1);
239
+ let kept = span.filter((_line, index) => !removed.has(first + index));
240
+ if (!kept.length && first > 0) {
241
+ first--;
242
+ span = lines.slice(first, last + 1);
243
+ kept = span.filter((_line, index) => !removed.has(first + index));
244
+ }
223
245
  if (!kept.length)
224
246
  return;
225
247
  return { name, change: { line: first + 1, before: span.join('\n'), after: kept.join('\n') } };
@@ -14,6 +14,7 @@ function gatherFacts(sourceFile) {
14
14
  const facts = {
15
15
  identifierCounts: new Map(),
16
16
  variableDeclarations: [],
17
+ functionDeclarations: [],
17
18
  hasJsx: false,
18
19
  hasDynamicScope: false,
19
20
  jsDocText: jsDocBlocksOf(sourceFile.text),
@@ -27,6 +28,8 @@ function gatherFacts(sourceFile) {
27
28
  }
28
29
  else if (ts.isVariableDeclaration(node))
29
30
  facts.variableDeclarations.push(node);
31
+ else if (ts.isFunctionDeclaration(node))
32
+ facts.functionDeclarations.push(node);
30
33
  else if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
31
34
  facts.hasJsx = true;
32
35
  else if (ts.isWithStatement(node))
@@ -62,14 +65,14 @@ function jsxFactoryNames(sourceFile, options) {
62
65
  if (root)
63
66
  names.add(root);
64
67
  }
65
- for (const pragma of sourceFile.text.matchAll(/@jsx(?:Frag)?\s+([\w$]+)/g))
68
+ for (const pragma of sourceFile.text.matchAll(/@jsx(?:Frag)?\s+([\w$]+)/gi))
66
69
  names.add(pragma[1]);
67
70
  return names;
68
71
  }
69
72
  function usesClassicJsx(sourceFile, options, facts) {
70
73
  if (!facts.hasJsx)
71
74
  return false;
72
- return !automaticJsxRuntimes.includes(options.jsx) || /@jsxRuntime\s+classic/.test(sourceFile.text);
75
+ return !automaticJsxRuntimes.includes(options.jsx) || /@jsxRuntime\s+classic/i.test(sourceFile.text);
73
76
  }
74
77
  function importBindingsOf(declaration) {
75
78
  const clause = declaration.importClause;
@@ -161,6 +164,37 @@ function unusedLocalFindings(sourceFile, file, facts) {
161
164
  }
162
165
  return findings;
163
166
  }
167
+ function isPrivateFunction(declaration, sourceFile) {
168
+ if (!declaration.body || isAmbient(declaration) || hasModifier(declaration, ts.SyntaxKind.ExportKeyword))
169
+ return false;
170
+ const scope = declaration.parent;
171
+ if (scope === sourceFile)
172
+ return ts.isExternalModule(sourceFile);
173
+ // Block-level function declarations have special hoisting behavior in sloppy scripts.
174
+ return ts.isBlock(scope) && ts.isFunctionLike(scope.parent);
175
+ }
176
+ function unusedFunctionFindings(sourceFile, file, options) {
177
+ const facts = factsOf(sourceFile);
178
+ if (facts.hasDynamicScope || !facts.functionDeclarations.length)
179
+ return [];
180
+ const jsxFactories = usesClassicJsx(sourceFile, options, facts) ? jsxFactoryNames(sourceFile, options) : undefined;
181
+ const findings = [];
182
+ for (const declaration of facts.functionDeclarations) {
183
+ const name = declaration.name;
184
+ if (!name || name.text.startsWith('_') || facts.identifierCounts.get(name.text) !== 1)
185
+ continue;
186
+ if (jsxFactories?.has(name.text) ||
187
+ mentionedInJsDoc(facts, name.text) ||
188
+ !isPrivateFunction(declaration, sourceFile))
189
+ continue;
190
+ findings.push({
191
+ ...locationOf(sourceFile, file, name),
192
+ ruleId: 'unused-local-function',
193
+ message: `'${name.text}' is a local function with no references. Remove the declaration if it is not needed.`,
194
+ });
195
+ }
196
+ return findings;
197
+ }
164
198
  function unusedImportFindings(sourceFile, file, options) {
165
199
  return unusedImportBindings(sourceFile, options).map((binding) => ({
166
200
  ...locationOf(sourceFile, file, binding.anchor),
@@ -168,7 +202,7 @@ function unusedImportFindings(sourceFile, file, options) {
168
202
  message: `'${binding.name}' is imported but never used. Remove it so readers and bundlers do not have to wonder why it is there.`,
169
203
  }));
170
204
  }
171
- // TypeScript reports both rules itself under `noUnusedLocals`, so reporting them here would
205
+ // TypeScript reports unused bindings itself under `noUnusedLocals`, so reporting them here would
172
206
  // duplicate its diagnostics.
173
207
  function checkUnusedBindings(sourceFile, file, options) {
174
208
  if (options.noUnusedLocals === true || sourceFile.isDeclarationFile || skippedSource(sourceFile, file))
@@ -177,6 +211,7 @@ function checkUnusedBindings(sourceFile, file, options) {
177
211
  return [
178
212
  ...unusedImportFindings(sourceFile, file, options),
179
213
  ...unusedLocalFindings(sourceFile, file, factsOf(sourceFile)),
214
+ ...unusedFunctionFindings(sourceFile, file, options),
180
215
  ].filter((finding) => finding.line === undefined || !isDisabled(finding.line));
181
216
  }
182
- export { checkUnusedBindings, unusedImportBindings };
217
+ export { checkUnusedBindings, importBindingsOf, unusedImportBindings };
@@ -51,20 +51,15 @@ function queueReexportDependencies(wanted, reexport, pending) {
51
51
  else if (reexport.star && wanted !== 'default')
52
52
  pending.push([reexport.to, wanted]);
53
53
  }
54
- const sourceSuffixes = [
55
- '',
54
+ const sourceFileExtensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
55
+ // Directory indexes keep the long-standing .ts, .tsx, .js precedence ahead of the later-added extensions.
56
+ const indexExtensions = [
56
57
  '.ts',
57
58
  '.tsx',
58
- '.mts',
59
- '.cts',
60
59
  '.js',
61
- '.jsx',
62
- '.mjs',
63
- '.cjs',
64
- '/index.ts',
65
- '/index.tsx',
66
- '/index.js',
60
+ ...sourceFileExtensions.filter((extension) => !['.ts', '.tsx', '.js'].includes(extension)),
67
61
  ];
62
+ const sourceSuffixes = ['', ...sourceFileExtensions, ...indexExtensions.map((extension) => `/index${extension}`)];
68
63
  // Finds the project file a workspace package name points at when TypeScript could not (dependencies
69
64
  // not installed). Packages that are named but not found are collected, because usage inside them is
70
65
  // then incomplete.
@@ -1,8 +1,13 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { coveringConfig, isWithin } from '../../shared/workspaces.js';
4
+ const declarationFile = /\.d\.[cm]?ts$/i;
4
5
  function isSourceInput(filename) {
5
- return /\.[cm]?[jt]sx?$/i.test(filename) && !/\.d\.[cm]?ts$/i.test(filename);
6
+ return /\.[cm]?[jt]sx?$/i.test(filename) && !declarationFile.test(filename);
7
+ }
8
+ // Unimported declarations can contribute globals and module augmentations to selected sources.
9
+ function scopedProjectRoots(roots, onlyFiles) {
10
+ return onlyFiles ? roots.filter((file) => declarationFile.test(file) || onlyFiles(file)) : roots;
6
11
  }
7
12
  function compareFindings(left, right) {
8
13
  return ((left.file ?? '').localeCompare(right.file ?? '') ||
@@ -80,4 +85,4 @@ function isInScope(scope, filename) {
80
85
  function relativeToWorkingDirectory(filename) {
81
86
  return path.relative(process.cwd(), filename).split(path.sep).join('/');
82
87
  }
83
- export { compareFindings, isInScope, isSourceInput, mergeFinding, relativeToWorkingDirectory, resolveConfig, scanEntries, };
88
+ export { compareFindings, isInScope, isSourceInput, scopedProjectRoots, mergeFinding, relativeToWorkingDirectory, resolveConfig, scanEntries, };
@@ -1,3 +1,4 @@
1
+ import { CliUsageError } from '../../shared/system/sentry.js';
1
2
  import { parseMinImpact } from '../../shared/reporting/impact-levels.js';
2
3
  import { resolveFormat } from '../../shared/formats/index.js';
3
4
  import { registeredRuleIds } from '../../shared/reporting/pillar-rules.js';
@@ -30,14 +31,14 @@ const sourceCheckOptions = {
30
31
  };
31
32
  function sourceEngine(values, positionals) {
32
33
  if (values.native && (values.engine ?? 'native') !== 'native')
33
- throw new Error('--native is an alias for --engine native.');
34
+ throw new CliUsageError('--native is an alias for --engine native.');
34
35
  const engine = values.native ? 'native' : (values.engine ?? 'auto');
35
36
  if (!['auto', 'native', 'js'].includes(engine))
36
- throw new Error('--engine must be auto, native or js.');
37
+ throw new CliUsageError('--engine must be auto, native or js.');
37
38
  if (values.watch && engine === 'native')
38
- throw new Error('--native supports one-shot checks. Use --watch with the incremental JS compiler.');
39
+ throw new CliUsageError('--native supports one-shot checks. Use --watch with the incremental JS compiler.');
39
40
  if (values.watch && positionals.length)
40
- throw new Error('--watch requires a project config.');
41
+ throw new CliUsageError('--watch requires a project config.');
41
42
  return engine;
42
43
  }
43
44
  function selectedFixIds(values, baselineOptions) {
@@ -46,9 +47,9 @@ function selectedFixIds(values, baselineOptions) {
46
47
  .map((id) => id.trim())
47
48
  .filter(Boolean);
48
49
  if (values.only.length && !values.fix)
49
- throw new Error('--only is only valid with --fix.');
50
+ throw new CliUsageError('--only is only valid with --fix.');
50
51
  if (values.only.length && !onlyIds.length)
51
- throw new Error('--only needs at least one finding id.');
52
+ throw new CliUsageError('--only needs at least one finding id.');
52
53
  if (values.fix && values.watch)
53
54
  throw new Error('--fix cannot be combined with --watch.');
54
55
  if ((baselineOptions.baseline || baselineOptions.writeBaseline) && (values.fix || values.watch)) {
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { ts } from './engine/compiler.js';
2
3
  import { withPrismaPackageInventory } from './schema/prisma-owners.js';
3
4
  import { check as checkServiceLoops } from './query-loops/service-loops.js';
@@ -135,15 +136,19 @@ function scanFile(program, sourceFile, policy, forEachSourceCandidate) {
135
136
  const pendingBlockingCalls = checker.getSymbolsAtLocations ? [] : undefined;
136
137
  const checkTransactionLoop = createTransactionLoopCheck(sourceFile, checker);
137
138
  const snapshot = currentSnapshot();
138
- const compilerOptions = policy ? program.getCompilerOptions() : undefined;
139
+ const compilerOptions = program.getCompilerOptions();
139
140
  const repeatedCache = new WeakMap();
140
141
  let hasReviewComments;
142
+ const relativeFile = policy?.projectDirectory
143
+ ? path.relative(policy.projectDirectory, sourceFile.fileName).replaceAll('\\', '/')
144
+ : sourceFile.fileName.replaceAll('\\', '/');
141
145
  const context = {
142
146
  checker,
143
147
  program,
144
- strictNullChecks: compilerOptions ? Boolean(compilerOptions.strictNullChecks ?? compilerOptions.strict) : false,
145
- verbatimModuleSyntax: compilerOptions ? Boolean(compilerOptions.verbatimModuleSyntax) : false,
148
+ strictNullChecks: Boolean(compilerOptions?.strictNullChecks ?? compilerOptions?.strict),
149
+ verbatimModuleSyntax: Boolean(compilerOptions?.verbatimModuleSyntax),
146
150
  fireAndForgetNames: new Set(policy?.fireAndForget),
151
+ ruleOptions: (ruleId) => policy?.ruleOptions?.(ruleId, relativeFile),
147
152
  isRepeated(node) {
148
153
  let repeated = repeatedCache.get(node);
149
154
  if (repeated === undefined) {
@@ -153,6 +158,14 @@ function scanFile(program, sourceFile, policy, forEachSourceCandidate) {
153
158
  return repeated;
154
159
  },
155
160
  isPackageType: createPackageTypeChecker(checker),
161
+ ruleOption(ruleId, option) {
162
+ if (!policy?.ruleOptions)
163
+ return undefined;
164
+ const rel = policy.projectDirectory
165
+ ? path.relative(policy.projectDirectory, sourceFile.fileName).split(path.sep).join('/')
166
+ : sourceFile.fileName;
167
+ return policy.ruleOptions(ruleId, rel)?.[option];
168
+ },
156
169
  // details carries optional suggestion and related links, which index rules attach.
157
170
  report(node, ruleId, message, contextualReason, details) {
158
171
  const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
@@ -31,7 +31,12 @@ function parseChangedLines(diffText, directory) {
31
31
  const rangesByFile = new Map();
32
32
  let ranges;
33
33
  for (const line of diffText.split(/\r?\n/)) {
34
- const header = addedFileHeader.exec(line);
34
+ if (line.startsWith('diff --git ')) {
35
+ ranges = undefined;
36
+ continue;
37
+ }
38
+ // Once the file header is known, added source lines cannot introduce another file.
39
+ const header = ranges === undefined ? addedFileHeader.exec(line) : undefined;
35
40
  const newPath = header && unquoteGitPath(header[1] ?? '');
36
41
  if (newPath?.startsWith('b/')) {
37
42
  const key = fileKey(path.join(directory, newPath.slice('b/'.length)));
@@ -56,6 +61,8 @@ function diffArguments(request) {
56
61
  'diff',
57
62
  '-U0',
58
63
  '--no-color',
64
+ '--no-ext-diff',
65
+ '--no-textconv',
59
66
  '--src-prefix=a/',
60
67
  '--dst-prefix=b/',
61
68
  '--diff-filter=ACMR',
@@ -1,14 +1,25 @@
1
1
  import fs from 'node:fs';
2
2
  import { parseArgs } from 'node:util';
3
3
  const usage = `Usage:
4
- loadwise perf [-p tsconfig.json | -p monorepo-root [--workspace name|path ...] | file.ts file.js ...] [--engine auto|native|js] [--policy policy.json] [--loadwise-config loadwise.config.json] [--schema snapshot.json] [--json | --format text|json|sarif|github] [--include-contextual] [--ignore rule-id] [--min-impact low|medium|high|critical] [--fail-on all|contract] [--baseline [file] | --write-baseline [file]] [--fix [--yes | --only id,...] [--no-comments] [--no-format]]
5
- loadwise perf [-p tsconfig.json] (--staged | --changed-since git-ref) [--json] [--include-contextual] [--ignore rule-id]
6
- loadwise perf --watch [-p tsconfig.json] [--policy policy.json] [--schema snapshot.json] [--include-contextual] [--ignore rule-id]
7
- loadwise perf db [--url-env DATABASE_URL] [--env-file .env] [--engine postgres|mysql|mongo] [--schema-snapshot out.json] [--top 20] [--queries file.sql] [--analyze] [--measure --i-understand-this-locks-tables] [--runs 5] [--json] [--ignore rule-id]
8
- loadwise perf traces trace.json [--threshold 5] [--json]
9
- loadwise perf plan explain.json [--json]
10
- loadwise perf polyglot <file-or-directory> ... [--json]
11
- loadwise perf agent init [--mode ask|auto] [--hook [block|warn|off]]
4
+ loadwise perf [-p <project> | <files...>] [options]
5
+ loadwise perf --watch [-p <project>]
6
+
7
+ Specialist commands
8
+ loadwise perf db [options] Inspect a live database
9
+ loadwise perf traces <trace.json> Find repeated queries in an OTLP trace
10
+ loadwise perf plan <explain.json> Inspect a query plan
11
+ loadwise perf polyglot <paths...> Check non-JavaScript source files
12
+ loadwise perf agent init [options] Set up a coding agent
13
+ Run loadwise perf <command> --help for specialist command options.
14
+
15
+ Source scan options
16
+ -p <project> --workspace <name|path> --engine <auto|native|js>
17
+ --loadwise-config <file> --policy <file> --schema snapshot.json
18
+ --staged | --changed-since <git-ref> --ignore <rule-id>
19
+ --json | --format <text|json|sarif|github> --include-contextual
20
+ --min-impact <low|medium|high|critical> --fail-on <all|contract>
21
+ --baseline [file] | --write-baseline [file]
22
+ --fix [--yes | --only <ids>] [--no-comments] [--no-format]
12
23
 
13
24
  With no arguments, check tsconfig.json or jsconfig.json in the current directory.
14
25
  In a monorepo root without one, every workspace package (package.json "workspaces", pnpm-workspace.yaml or lerna.json) with its own tsconfig.json or jsconfig.json is checked in one report; --workspace limits it to the named packages or folders.
@@ -7,6 +7,7 @@ import { jsonKeyByCommand } from '../analysis/source-pillars.js';
7
7
  import { exitCodeWithSkips } from './scan-outcome.js';
8
8
  import { findProjectRoot } from '../schema/context.js';
9
9
  import { terminalPrinter } from '../../shared/system/terminal-safe.js';
10
+ import { reportAutomaticFixes } from '../../shared/reporting/automatic-fix-signal.js';
10
11
  import { assignFindingIds as assignFindingIdsFindingIds } from './finding-ids.js';
11
12
  import { keepChangedFindings, collectProjectChangedLines, fileKey } from './changed-lines.js';
12
13
  import { attachExample } from './finding-text.js';
@@ -71,6 +72,7 @@ export async function printResult(result, values, print = console.log) {
71
72
  options: values.baselineOptions ?? {},
72
73
  pillar: values.sourcePillar ?? 'performance',
73
74
  findings: result.findings,
75
+ skippedFiles: result.skippedFiles,
74
76
  projectRoot: values.projectDirectory ?? process.cwd(),
75
77
  absoluteFileOf: (finding) => path.resolve(finding.file ?? ''),
76
78
  idRoot,
@@ -118,6 +120,8 @@ function printSourceOutput(result, values, baseline, print) {
118
120
  const warningNote = values.settings.warningNote(result.findings);
119
121
  if (warningNote && format === 'text' && !values.changedLines)
120
122
  print(warningNote);
123
+ if (format === 'text')
124
+ reportAutomaticFixes(result.findings);
121
125
  }
122
126
  // Finding paths are relative to the working directory.
123
127
  function printStructured(format, result, values, print) {
@@ -115,7 +115,20 @@ export async function checkCode(args, report = printResult, baselineFlags = {},
115
115
  projectDirectory: directory,
116
116
  sourcePillar: pillar.jsonKey,
117
117
  };
118
- const policySource = sourcePolicy(values.policy, values.settings);
118
+ const basePolicySource = sourcePolicy(values.policy, values.settings);
119
+ // Override globs are relative to the config file's folder, which can differ from the scan folder.
120
+ const withRuleOptions = (base, settings) => settings.ruleOptions
121
+ ? {
122
+ ...base,
123
+ ruleOptions: settings.ruleOptions,
124
+ projectDirectory: settings.filename ? path.dirname(settings.filename) : directory,
125
+ }
126
+ : base;
127
+ const policySource = {
128
+ filename: basePolicySource.filename,
129
+ // Watch refreshes reread the config so edited rule options apply without a restart.
130
+ read: () => withRuleOptions(basePolicySource.read(), values.watch ? loadSettings({ directory, explicit: values['loadwise-config'] }) : values.settings),
131
+ };
119
132
  const policy = policySource.read();
120
133
  if (withCommands.length)
121
134
  return checkWithPillars({
@@ -204,7 +217,13 @@ async function watchSource(values, policySource) {
204
217
  const { watchProject } = await import('./watch.js');
205
218
  const logError = (error) => {
206
219
  const message = typeof error === 'object' && error !== null && 'message' in error ? error.message : error;
207
- console.error(typeof message === 'string' ? terminalSafe(message) : message);
220
+ // The editor must distinguish an unusable refresh from ordinary stderr coverage notes.
221
+ if (process.env.LOADWISE_EDITOR_WATCH_EVENTS === '1' && values.json) {
222
+ console.log(JSON.stringify({ watchError: terminalSafe(String(message)) }));
223
+ }
224
+ else {
225
+ console.error(typeof message === 'string' ? terminalSafe(message) : message);
226
+ }
208
227
  };
209
228
  const watcher = watchProject(values.project ?? '.', {
210
229
  policySource,
@@ -8,10 +8,11 @@ import { parseCommand, readJsonFile, showHelp } from './cli/cli-arguments.js';
8
8
  import { printResult, scanFilter } from './cli/cli-output.js';
9
9
  import { projectDirectory, relativeToCwd, sourcePolicy, workspaceTarget } from './cli/cli-policy.js';
10
10
  import { checkCode } from './cli/cli-scan.js';
11
+ import { terminalSafe } from '../shared/system/terminal-safe.js';
11
12
  async function checkPlan(args) {
12
13
  const { values, positionals } = parseCommand(args, { json: { type: 'boolean' } });
13
14
  if (values.help)
14
- return showHelp();
15
+ return showHelp('Usage: loadwise perf plan <explain.json> [--json]\nInspect an executed query plan.');
15
16
  if (positionals.length !== 1)
16
17
  throw new Error('Pass exactly one executed query plan to plan.');
17
18
  const result = (await import('./evidence/plans.js')).inspectPlan(readJsonFile(positionals[0], 'Plan'));
@@ -31,7 +32,8 @@ async function checkTraces(args) {
31
32
  threshold: { type: 'string', default: '5' },
32
33
  });
33
34
  if (values.help)
34
- return showHelp();
35
+ return showHelp('Usage: loadwise perf traces <trace.json> [--threshold <count>] [--json]\n' +
36
+ 'Find repeated sibling database calls in an OTLP JSON trace. The default threshold is 5.');
35
37
  if (positionals.length !== 1)
36
38
  throw new Error('Pass exactly one OTLP JSON file to traces.');
37
39
  const threshold = Number(values.threshold);
@@ -61,16 +63,23 @@ async function runPolyglot(args, pillar = 'performance') {
61
63
  'min-impact': { type: 'string' },
62
64
  'loadwise-config': { type: 'string' },
63
65
  });
64
- if (values.help)
65
- return showHelp();
66
+ if (values.help) {
67
+ const checker = pillar === 'reliability' ? 'rel' : 'perf';
68
+ return showHelp(`Usage: loadwise ${checker} polyglot <paths...> [--json] [--min-impact <level>] [--loadwise-config <file>]\n` +
69
+ 'Check non-JavaScript files or directories. Requires the optional ast-grep binary.');
70
+ }
66
71
  parseMinImpact(values['min-impact']);
67
72
  if (!positionals.length)
68
73
  throw new Error('Pass at least one file or directory to polyglot.');
69
- const result = await (await import('./polyglot.js')).checkPolyglot(positionals, pillar);
70
74
  const settings = loadSettings({ directory: process.cwd(), explicit: values['loadwise-config'] });
71
- // The polyglot scan reports skippedFiles as a count, which printing never reads but the JSON
72
- // output keeps.
75
+ const result = await (await import('./polyglot.js')).checkPolyglot(positionals, pillar, settings.isIgnored);
76
+ // The renderer checks skipped-file arrays for exit status. Successful polyglot JSON retains its numeric zero.
73
77
  const printable = result;
78
+ if (!values.json) {
79
+ for (const { file, reason } of result.skippedFiles || []) {
80
+ console.error(terminalSafe(`Note: ${file} was skipped (${reason}).`));
81
+ }
82
+ }
74
83
  const code = await printResult(printable, { ...values, ignore: [], settings, sourcePillar: pillar });
75
84
  notifyEditor(positionals.length === 1 ? positionals[0] : process.cwd());
76
85
  return code;
@@ -3,6 +3,7 @@
3
3
  import { ts } from '../engine/compiler.js';
4
4
  import { unwrapExpression as unwrap } from '../../shared/analysis/ast-semantics.js';
5
5
  import { enclosingRequestHandler, parameterName } from '../request/request-handlers.js';
6
+ import { valueSymbol } from '../request/phase5-ast.js';
6
7
  import { hasFunctionBody } from '../analysis/function-kinds.js';
7
8
  import { classifyExecutionContext } from '../../shared/analysis/execution-context.js';
8
9
  const CACHE_RULE_ID = 'unbounded-module-cache';
@@ -10,15 +11,25 @@ const PAYLOAD_RULE_ID = 'whole-payload-in-memory';
10
11
  const CACHE_NAME = /(?:cache|memo|lookup)s?$/i;
11
12
  // Name parts that mark a key as coming from a request, a tenant or a user, so its space grows with
12
13
  // traffic.
13
- const REQUEST_KEY_PARTS = new Set('id ids uuid tenant user userid workspace workspaceid session email slug token req request args input params query body'.split(' '));
14
+ const REQUEST_KEY_PARTS = new Set('id ids uuid tenant user userid workspace workspaceid session email slug token req request args input params query body locale lang language'.split(' '));
14
15
  const CONTEXTUAL_KEY_REASON = 'The key looks like it comes from configuration or code rather than from requests, so the key space may be small.';
15
16
  const STARTUP_FUNCTION = /^(?:constructor|onModule[A-Za-z]+|onApplication[A-Za-z]+|register[A-Za-z]*|init[A-Za-z]*|bootstrap[A-Za-z]*|setup[A-Za-z]*)$/;
16
17
  const LIST_CACHE_NAME = /cache|memo|history/i;
17
18
  const WRITE_METHODS = new Set(['set', 'add', 'push']);
18
19
  const READ_METHODS = new Set(['get', 'has']);
19
- // Any use of these shows the collection is trimmed, measured or reset, so it may be bounded
20
- // elsewhere.
21
- const BOUNDING_MEMBERS = new Set(['delete', 'clear', 'size', 'length', 'shift', 'pop', 'splice', 'unshift']);
20
+ // Any use of these shows the collection is trimmed or reset, so it may be bounded elsewhere.
21
+ const EVICTION_MEMBERS = new Set(['delete', 'clear', 'shift', 'pop', 'splice', 'unshift']);
22
+ const SIZE_MEMBERS = new Set(['size', 'length']);
23
+ const COMPARISON_TOKENS = new Set([
24
+ ts.SyntaxKind.LessThanToken,
25
+ ts.SyntaxKind.LessThanEqualsToken,
26
+ ts.SyntaxKind.GreaterThanToken,
27
+ ts.SyntaxKind.GreaterThanEqualsToken,
28
+ ts.SyntaxKind.EqualsEqualsToken,
29
+ ts.SyntaxKind.EqualsEqualsEqualsToken,
30
+ ts.SyntaxKind.ExclamationEqualsToken,
31
+ ts.SyntaxKind.ExclamationEqualsEqualsToken,
32
+ ]);
22
33
  const SCOPE_OPTOUT_ARGUMENTS = /REQUEST|TRANSIENT/;
23
34
  const REQUEST_SCOPED_NAMES = /^(?:res|response|reply|next|h)$/;
24
35
  const FS_MODULE = /^(?:node:)?fs(?:\/promises)?$/;
@@ -30,17 +41,34 @@ function isEmptyCollection(initializer) {
30
41
  const value = unwrap(initializer);
31
42
  if (!value)
32
43
  return;
33
- if (ts.isObjectLiteralExpression(value) && value.properties.length === 0)
44
+ if (ts.isObjectLiteralExpression(value))
34
45
  return 'object';
35
- if (ts.isArrayLiteralExpression(value) && value.elements.length === 0)
46
+ if (ts.isArrayLiteralExpression(value))
36
47
  return 'array';
37
- if (ts.isNewExpression(value) && ts.isIdentifier(value.expression) && !value.arguments?.length) {
48
+ if (ts.isNewExpression(value) && ts.isIdentifier(value.expression) && (value.arguments?.length ?? 0) <= 1) {
38
49
  if (value.expression.text === 'Map')
39
50
  return 'map';
40
51
  if (value.expression.text === 'Set')
41
52
  return 'set';
42
53
  }
43
54
  }
55
+ function isSizeCapCheck(access) {
56
+ let current = access;
57
+ while (current.parent &&
58
+ (ts.isParenthesizedExpression(current.parent) ||
59
+ (ts.isBinaryExpression(current.parent) && !COMPARISON_TOKENS.has(current.parent.operatorToken.kind)))) {
60
+ current = current.parent;
61
+ }
62
+ const parent = current.parent;
63
+ if (!parent)
64
+ return false;
65
+ if (ts.isBinaryExpression(parent) && COMPARISON_TOKENS.has(parent.operatorToken.kind))
66
+ return true;
67
+ if (ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken)
68
+ return true;
69
+ return ((ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) &&
70
+ parent.expression === current);
71
+ }
44
72
  function isLiteralKey(key) {
45
73
  const value = unwrap(key);
46
74
  return !value || ts.isStringLiteralLike(value) || ts.isNumericLiteral(value);
@@ -58,8 +86,12 @@ function classifyUse(reference) {
58
86
  const parent = reference.parent;
59
87
  if (ts.isPropertyAccessExpression(parent) && parent.expression === reference) {
60
88
  const member = parent.name.text;
61
- if (BOUNDING_MEMBERS.has(member))
89
+ if (EVICTION_MEMBERS.has(member))
62
90
  return { kind: 'bounded' };
91
+ if (member === 'length' && isAssignmentTarget(parent))
92
+ return { kind: 'bounded' };
93
+ if (SIZE_MEMBERS.has(member))
94
+ return { kind: isSizeCapCheck(parent) ? 'bounded' : 'read' };
63
95
  const call = parent.parent;
64
96
  const isCall = ts.isCallExpression(call) && call.expression === parent;
65
97
  if (isCall && WRITE_METHODS.has(member)) {
@@ -164,8 +196,13 @@ function nameParts(text) {
164
196
  .split(/[^a-z0-9]+/);
165
197
  }
166
198
  function derivesFromRequest(key, checker) {
199
+ if (ts.isCallExpression(unwrap(key) ?? key))
200
+ return false;
167
201
  const declaration = ts.isIdentifier(key) ? checker.getSymbolAtLocation(key)?.valueDeclaration : undefined;
168
- const initializer = declaration && ts.isVariableDeclaration(declaration) ? declaration.initializer : undefined;
202
+ const declared = declaration && ts.isVariableDeclaration(declaration) ? declaration.initializer : undefined;
203
+ // A call may map a request value onto a small set (`normalizeLocale(locale)`), so only the key's own
204
+ // name counts as evidence; a firm finding needs the raw value in the key.
205
+ const initializer = declared && !ts.isCallExpression(unwrap(declared) ?? declared) ? declared : undefined;
169
206
  const text = key.getText() + (initializer ? ' ' + initializer.getText() : '');
170
207
  return nameParts(text).some((part) => REQUEST_KEY_PARTS.has(part));
171
208
  }
@@ -259,7 +296,7 @@ function reportGrowth(context, write, label, contextual) {
259
296
  : undefined;
260
297
  context.report(write.anchor, CACHE_RULE_ID, `${label} \`${target.getText()}\` only grows: nothing in this file deletes, clears or size-checks it, so a long-lived process keeps every entry it was given until memory runs out. Bound it with an LRU or TTL (\`lru-cache\`, or evict when \`size\` passes a cap). Ignore if the key space is small and fixed.`, reason);
261
298
  }
262
- function moduleLevelCaches(sourceFile) {
299
+ function moduleLevelCaches(sourceFile, checker) {
263
300
  const caches = [];
264
301
  for (const statement of sourceFile.statements) {
265
302
  if (!ts.isVariableStatement(statement) || isExported(statement))
@@ -272,7 +309,13 @@ function moduleLevelCaches(sourceFile) {
272
309
  caches.push({
273
310
  name: declaration.name.text,
274
311
  shape,
275
- references: identifierReferences(sourceFile, declaration.name.text, declaration.name),
312
+ references: identifierReferences(sourceFile, declaration.name.text, declaration.name).filter((reference) => {
313
+ const symbol = valueSymbol(reference, checker);
314
+ if (!symbol)
315
+ return false;
316
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
317
+ return target?.valueDeclaration === declaration;
318
+ }),
276
319
  });
277
320
  }
278
321
  }
@@ -301,7 +344,7 @@ function candidatesOf(sourceFile, checker) {
301
344
  const known = cacheCandidates.get(sourceFile);
302
345
  if (known)
303
346
  return known;
304
- const found = [...moduleLevelCaches(sourceFile), ...serviceFieldCaches(sourceFile)].flatMap((candidate) => {
347
+ const found = [...moduleLevelCaches(sourceFile, checker), ...serviceFieldCaches(sourceFile)].flatMap((candidate) => {
305
348
  const growth = growingWrite(candidate.references, candidate.shape, candidate.name, checker);
306
349
  return growth ? [{ write: growth.write, contextual: growth.contextual, shape: candidate.shape }] : [];
307
350
  });