loadwise 0.6.2 → 0.7.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 (86) hide show
  1. package/README.md +152 -100
  2. package/dist/bin/loadwise.js +126 -49
  3. package/dist/lib/accessibility/frontend-detect.js +6 -5
  4. package/dist/lib/accessibility/usage.js +10 -2
  5. package/dist/lib/editor/configured-setup.js +61 -0
  6. package/dist/lib/editor/editor-launcher.js +165 -0
  7. package/dist/lib/editor/fix-edits.js +19 -0
  8. package/dist/lib/editor/jetbrains-setup.js +53 -0
  9. package/dist/lib/editor/language-server.js +31 -14
  10. package/dist/lib/editor/managed-config.js +37 -0
  11. package/dist/lib/editor/native-setup.js +85 -0
  12. package/dist/lib/editor/release-vsix.js +61 -0
  13. package/dist/lib/editor/server-commands.js +2 -0
  14. package/dist/lib/editor/setup-server.js +87 -0
  15. package/dist/lib/editor/setup-vim.js +61 -0
  16. package/dist/lib/editor/setup.js +131 -0
  17. package/dist/lib/editor/stdio-setup.js +6 -0
  18. package/dist/lib/maintainability/cli/inputs.js +3 -2
  19. package/dist/lib/maintainability/cli.js +14 -5
  20. package/dist/lib/maintainability/examples.js +4 -0
  21. package/dist/lib/maintainability/rule-ids.js +3 -0
  22. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  23. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  24. package/dist/lib/performance/cli/changed-lines.js +8 -1
  25. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  26. package/dist/lib/performance/cli/cli-output.js +3 -0
  27. package/dist/lib/performance/cli.js +8 -4
  28. package/dist/lib/performance/datastores/pg-integrity.js +7 -0
  29. package/dist/lib/performance/datastores/pooling.js +6 -1
  30. package/dist/lib/performance/engine/native-syntax.js +3 -0
  31. package/dist/lib/performance/frontend/frontend-perf.js +80 -20
  32. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  33. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  34. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  35. package/dist/lib/performance/request/mongoose-lean.js +140 -53
  36. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  37. package/dist/lib/performance/request/phase5-ast.js +6 -7
  38. package/dist/lib/performance/request/phase5-rules.js +133 -13
  39. package/dist/lib/performance/request/request-handlers.js +120 -23
  40. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  41. package/dist/lib/performance/site-fixes/collections.js +1 -2
  42. package/dist/lib/performance/site-fixes/frontend-fixes.js +10 -6
  43. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  44. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  45. package/dist/lib/reliability/react-bugs.js +11 -3
  46. package/dist/lib/reliability/usage.js +16 -5
  47. package/dist/lib/security/cli.js +15 -4
  48. package/dist/lib/shared/agent/agent-init.js +26 -4
  49. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  50. package/dist/lib/shared/agent/agent-session.js +6 -1
  51. package/dist/lib/shared/agent/agent-verify.js +54 -10
  52. package/dist/lib/shared/agent/review-delivery.js +1 -1
  53. package/dist/lib/shared/analysis/scan-cache.js +3 -2
  54. package/dist/lib/shared/check.js +172 -20
  55. package/dist/lib/shared/fix/fix-convergence.js +15 -29
  56. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  57. package/dist/lib/shared/fix/fix-imports.js +47 -38
  58. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  59. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  60. package/dist/lib/shared/fix/fix-presentation.js +4 -3
  61. package/dist/lib/shared/fix/fix-safety.js +26 -1
  62. package/dist/lib/shared/fix/fix-scope.js +82 -0
  63. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  64. package/dist/lib/shared/fix/project-file-access.js +17 -26
  65. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  66. package/dist/lib/shared/fix.js +215 -102
  67. package/dist/lib/shared/report-fp.js +93 -0
  68. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  69. package/dist/lib/shared/reporting/check-text.js +50 -0
  70. package/dist/lib/shared/reporting/pillars.js +45 -16
  71. package/dist/lib/shared/reporting/source-report.js +2 -0
  72. package/dist/lib/shared/system/atomic-write.js +5 -2
  73. package/dist/lib/shared/system/sentry.js +203 -0
  74. package/dist/lib/shared/system/shell-argument.js +5 -1
  75. package/dist/lib/shared/system/terminal-safe.js +3 -2
  76. package/dist/lib/shared/system/terminal-style.js +131 -0
  77. package/docs/assets/cli-workflow.gif +0 -0
  78. package/integrations/sublime/plugin.py +22 -0
  79. package/integrations/zed/Cargo.lock +845 -0
  80. package/integrations/zed/Cargo.toml +11 -0
  81. package/integrations/zed/extension.toml +11 -0
  82. package/integrations/zed/src/lib.rs +25 -0
  83. package/package.json +11 -3
  84. package/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugin/commands/loadwise.md +11 -6
  86. package/schema/loadwise.config.schema.json +2 -0
@@ -20,6 +20,7 @@ const knownRules = new Set([
20
20
  'unreferenced-file',
21
21
  'unused-export',
22
22
  'unused-import',
23
+ 'unused-local-function',
23
24
  'unused-local-variable',
24
25
  ]);
25
26
  // Impact levels (see lib/shared/reporting/impact-levels.ts) for every rule id a maintainability finding can
@@ -49,6 +50,7 @@ const impactByRule = {
49
50
  'unreferenced-file': 'low',
50
51
  'unused-export': 'low',
51
52
  'unused-import': 'low',
53
+ 'unused-local-function': 'low',
52
54
  'unused-local-variable': 'low',
53
55
  };
54
56
  // One-line summaries of every rule above, used where a rule needs a fixed name (SARIF
@@ -77,6 +79,7 @@ const descriptionByRule = {
77
79
  'unreferenced-file': 'A source file that nothing imports and that is not an entry point.',
78
80
  'unused-export': 'An export that no scanned file imports.',
79
81
  'unused-import': 'An imported name is never used in the file.',
82
+ 'unused-local-function': 'A private function declaration has no references.',
80
83
  'unused-local-variable': 'A local variable is assigned but never read.',
81
84
  };
82
85
  export { knownRules, impactByRule, descriptionByRule };
@@ -1,6 +1,8 @@
1
1
  import ts from 'typescript';
2
2
  import { hasCommentBetween } from '../../performance/site-fixes/helpers.js';
3
- import { unusedImportBindings } from '../unused/unused-bindings.js';
3
+ import { importBindingsOf, unusedImportBindings } from '../unused/unused-bindings.js';
4
+ import { walkNodes } from '../analysis/walk.js';
5
+ import { hasModifier } from '../quality/modifiers.js';
4
6
  // A statement alone on its line goes together with one line break, so no blank line is left behind.
5
7
  // The fix hunks are whole lines, so the break before it is dropped; on the first line the
6
8
  // following line's indentation is. Anything else sharing the line (a trailing comment, another
@@ -90,7 +92,7 @@ function removeUnusedImport({ node, sourceFile }) {
90
92
  const unused = new Set(unusedAnchorsOf(sourceFile));
91
93
  unused.add(target);
92
94
  if (keptClauseParts(clause, unused).length === 0) {
93
- const removal = statementRemoval(sourceFile, declaration);
95
+ const removal = unusedDeclarationRemoval(sourceFile, declaration);
94
96
  if (!removal)
95
97
  return { edits: [], note: sharedLineNote };
96
98
  // Dropping a whole import also drops whatever running the module did, unless it only held types.
@@ -110,6 +112,19 @@ function removeUnusedImport({ node, sourceFile }) {
110
112
  if (hasCommentBetween(sourceFile.text, edit.start, edit.end)) {
111
113
  return { edits: [], note: 'Not applied: the import clause contains comments that rewriting it would remove.' };
112
114
  }
115
+ const named = clause.namedBindings;
116
+ if (!clause.isTypeOnly &&
117
+ named &&
118
+ ts.isNamedImports(named) &&
119
+ (!clause.name || unused.has(clause.name)) &&
120
+ named.elements.every((element) => unused.has(element) || element.isTypeOnly) &&
121
+ (clause.name || named.elements.some((element) => !element.isTypeOnly))) {
122
+ return {
123
+ edits: [edit],
124
+ requiresReview: true,
125
+ note: 'Removes the last value binding. Depending on the transpiler, the module may stop running for its side effects.',
126
+ };
127
+ }
113
128
  return { edits: [edit], note: 'Removes only the unused name from the import.' };
114
129
  }
115
130
  // Evaluating these can neither throw nor change anything, so deleting the declaration is safe.
@@ -158,7 +173,7 @@ function removeUnusedLocal({ node, sourceFile }) {
158
173
  const statement = declaration && onlyStatementOf(declaration);
159
174
  if (!declaration || !statement || !pureInitializer(declaration.initializer))
160
175
  return;
161
- const removal = statementRemoval(sourceFile, statement);
176
+ const removal = unusedDeclarationRemoval(sourceFile, statement);
162
177
  if (!removal)
163
178
  return { edits: [], note: sharedLineNote };
164
179
  if (mayAssertType(declaration)) {
@@ -173,8 +188,128 @@ function removeUnusedLocal({ node, sourceFile }) {
173
188
  note: 'Removes a variable that is never read; its initializer has no side effects.',
174
189
  };
175
190
  }
191
+ const typescriptSource = /\.[cm]?tsx?$/i;
192
+ function mayEraseStatement(statement) {
193
+ return (!!statement &&
194
+ (ts.isInterfaceDeclaration(statement) ||
195
+ ts.isTypeAliasDeclaration(statement) ||
196
+ ts.isImportEqualsDeclaration(statement) ||
197
+ ts.isExportDeclaration(statement) ||
198
+ ts.isModuleDeclaration(statement) ||
199
+ ts.isEnumDeclaration(statement) ||
200
+ (ts.isFunctionDeclaration(statement) && !statement.body) ||
201
+ hasModifier(statement, ts.SyntaxKind.DeclareKeyword)));
202
+ }
203
+ const retainedBoundaries = new WeakMap();
204
+ function boundariesIn(scope) {
205
+ const cached = retainedBoundaries.get(scope);
206
+ if (cached)
207
+ return cached;
208
+ const boundaries = new Set();
209
+ const typed = typescriptSource.test(scope.getSourceFile().fileName);
210
+ let needsBoundary = false;
211
+ // Look past whole runs of declarations, which can be erased by TypeScript or removed together by Loadwise.
212
+ for (let index = scope.statements.length - 1; index >= 0; index--) {
213
+ const statement = scope.statements[index];
214
+ if (ts.isVariableStatement(statement) ||
215
+ ts.isFunctionDeclaration(statement) ||
216
+ (ts.isImportDeclaration(statement) && !!statement.importClause) ||
217
+ (typed && mayEraseStatement(statement))) {
218
+ if (needsBoundary)
219
+ boundaries.add(statement);
220
+ continue;
221
+ }
222
+ // Strings might enter the directive prologue. Some other expressions can join the preceding line via ASI.
223
+ needsBoundary =
224
+ ts.isExpressionStatement(statement) &&
225
+ (ts.isStringLiteral(statement.expression) || /^(?:[([`/+\-<]|(?:as|satisfies)\b)/.test(statement.getText()));
226
+ }
227
+ retainedBoundaries.set(scope, boundaries);
228
+ return boundaries;
229
+ }
230
+ function unusedDeclarationRemoval(sourceFile, declaration) {
231
+ const removal = statementRemoval(sourceFile, declaration);
232
+ if (!removal)
233
+ return;
234
+ const scope = declaration.parent;
235
+ const ownsStatements = ts.isBlock(scope) || ts.isSourceFile(scope) || ts.isCaseClause(scope);
236
+ return ownsStatements && boundariesIn(scope).has(declaration)
237
+ ? { start: declaration.getStart(sourceFile), end: declaration.end, text: ';' }
238
+ : removal;
239
+ }
240
+ const durableModuleMarkers = new WeakMap();
241
+ function hasDurableModuleMarker(sourceFile) {
242
+ const cached = durableModuleMarkers.get(sourceFile);
243
+ if (cached !== undefined)
244
+ return cached;
245
+ // Use only markers that do not expose bindings another unused-code fix could remove.
246
+ const marked = sourceFile.statements.some((statement) => (ts.isImportDeclaration(statement) && !statement.importClause) ||
247
+ (ts.isExportDeclaration(statement) &&
248
+ !statement.isTypeOnly &&
249
+ !statement.moduleSpecifier &&
250
+ !!statement.exportClause &&
251
+ ts.isNamedExports(statement.exportClause) &&
252
+ statement.exportClause.elements.length === 0));
253
+ durableModuleMarkers.set(sourceFile, marked);
254
+ return marked;
255
+ }
256
+ function functionRemovalRisks(declaration, sourceFile) {
257
+ const typescript = typescriptSource.test(sourceFile.fileName);
258
+ const names = new Set();
259
+ for (const statement of sourceFile.statements) {
260
+ if (ts.isImportEqualsDeclaration(statement) && !statement.isTypeOnly)
261
+ names.add(statement.name.text);
262
+ if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly)
263
+ continue;
264
+ for (const { anchor, name } of importBindingsOf(statement)) {
265
+ if (!ts.isImportSpecifier(anchor) || !anchor.isTypeOnly)
266
+ names.add(name);
267
+ }
268
+ }
269
+ let mayElideImport = false;
270
+ let containsImportMeta = false;
271
+ walkNodes(declaration, (node) => {
272
+ // JSX can reference a configured classic factory or introduce an automatic runtime import.
273
+ if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node))
274
+ mayElideImport = true;
275
+ if (typescript && ts.isIdentifier(node) && names.has(node.text))
276
+ mayElideImport = true;
277
+ if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword)
278
+ containsImportMeta = true;
279
+ });
280
+ return { mayElideImport, mayTurnModuleIntoScript: containsImportMeta && !hasDurableModuleMarker(sourceFile) };
281
+ }
282
+ function removeUnusedFunction({ node, sourceFile }) {
283
+ if (!node || !sourceFile)
284
+ return;
285
+ const declaration = ts.findAncestor(node, ts.isFunctionDeclaration);
286
+ if (!declaration || declaration.name !== node || !declaration.body)
287
+ return;
288
+ const start = declaration.getStart(sourceFile);
289
+ if (hasCommentBetween(sourceFile.text, declaration.getFullStart(), start)) {
290
+ return { edits: [], note: 'Not applied: check the comment attached to this declaration before removing it.' };
291
+ }
292
+ const edit = unusedDeclarationRemoval(sourceFile, declaration);
293
+ if (!edit)
294
+ return { edits: [], note: sharedLineNote };
295
+ const { mayElideImport, mayTurnModuleIntoScript } = functionRemovalRisks(declaration, sourceFile);
296
+ // A batch of edits could remove every import.meta use. Without a durable marker, keep these declarations.
297
+ if (mayTurnModuleIntoScript) {
298
+ return { edits: [], note: 'Not applied: removing this import.meta could turn the module into a script.' };
299
+ }
300
+ if (mayElideImport) {
301
+ return {
302
+ edits: [edit],
303
+ omitWhyComment: true,
304
+ requiresReview: true,
305
+ note: 'Removing this function may elide an import or JSX runtime dependency and skip the imported module’s side effects.',
306
+ };
307
+ }
308
+ return { edits: [edit], omitWhyComment: true, note: 'Removes a private function with no references.' };
309
+ }
176
310
  const builders = {
177
311
  'unused-import': removeUnusedImport,
312
+ 'unused-local-function': removeUnusedFunction,
178
313
  'unused-local-variable': removeUnusedLocal,
179
314
  };
180
315
  export default builders;
@@ -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 };
@@ -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';
@@ -118,6 +119,8 @@ function printSourceOutput(result, values, baseline, print) {
118
119
  const warningNote = values.settings.warningNote(result.findings);
119
120
  if (warningNote && format === 'text' && !values.changedLines)
120
121
  print(warningNote);
122
+ if (format === 'text')
123
+ reportAutomaticFixes(result.findings);
121
124
  }
122
125
  // Finding paths are relative to the working directory.
123
126
  function printStructured(format, result, values, print) {
@@ -11,7 +11,7 @@ import { checkCode } from './cli/cli-scan.js';
11
11
  async function checkPlan(args) {
12
12
  const { values, positionals } = parseCommand(args, { json: { type: 'boolean' } });
13
13
  if (values.help)
14
- return showHelp();
14
+ return showHelp('Usage: loadwise perf plan <explain.json> [--json]\nInspect an executed query plan.');
15
15
  if (positionals.length !== 1)
16
16
  throw new Error('Pass exactly one executed query plan to plan.');
17
17
  const result = (await import('./evidence/plans.js')).inspectPlan(readJsonFile(positionals[0], 'Plan'));
@@ -31,7 +31,8 @@ async function checkTraces(args) {
31
31
  threshold: { type: 'string', default: '5' },
32
32
  });
33
33
  if (values.help)
34
- return showHelp();
34
+ return showHelp('Usage: loadwise perf traces <trace.json> [--threshold <count>] [--json]\n' +
35
+ 'Find repeated sibling database calls in an OTLP JSON trace. The default threshold is 5.');
35
36
  if (positionals.length !== 1)
36
37
  throw new Error('Pass exactly one OTLP JSON file to traces.');
37
38
  const threshold = Number(values.threshold);
@@ -61,8 +62,11 @@ async function runPolyglot(args, pillar = 'performance') {
61
62
  'min-impact': { type: 'string' },
62
63
  'loadwise-config': { type: 'string' },
63
64
  });
64
- if (values.help)
65
- return showHelp();
65
+ if (values.help) {
66
+ const checker = pillar === 'reliability' ? 'rel' : 'perf';
67
+ return showHelp(`Usage: loadwise ${checker} polyglot <paths...> [--json] [--min-impact <level>] [--loadwise-config <file>]\n` +
68
+ 'Check non-JavaScript files or directories. Requires the optional ast-grep binary.');
69
+ }
66
70
  parseMinImpact(values['min-impact']);
67
71
  if (!positionals.length)
68
72
  throw new Error('Pass at least one file or directory to polyglot.');
@@ -9,6 +9,13 @@ const transactionStart = new RegExp(`^(?:begin(?: work| transaction)?|start tran
9
9
  const setTransaction = new RegExp(`^set transaction ${modes}$`, 'i');
10
10
  const transactionEnd = /^(?:end|abort|commit|rollback)(?: work| transaction)?(?: and (?:no )?chain)?$/i;
11
11
  const savepoint = /^(?:savepoint|release(?: savepoint)?|rollback(?: work| transaction)? to(?: savepoint)?) [a-z_][a-z0-9_$]*$/i;
12
+ // Even a SELECT can change session state through a function. Only rewrite a
13
+ // fixed scalar projection with no table, function, or additional statement.
14
+ const independentSelect = /^select\s+(?:[0-9]+|\$[1-9][0-9]*|null|true|false)\s*;?$/i;
15
+ export function isSessionIndependentCheckoutQuery(call) {
16
+ const argument = call.arguments[0];
17
+ return !!argument && ts.isStringLiteralLike(argument) && independentSelect.test(argument.text.trim());
18
+ }
12
19
  function transactionControl(text) {
13
20
  // Restrict recognition to one command. A complete transaction submitted in
14
21
  // one query uses one connection, and COMMIT PREPARED can use another session.
@@ -1,5 +1,6 @@
1
1
  import { ts } from '../engine/compiler.js';
2
2
  import { findRepeatOwner, outerExpression } from '../collections/repeated.js';
3
+ import { isSessionIndependentCheckoutQuery } from './pg-integrity.js';
3
4
  import { resolveImportedBinding, staticMemberName, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
4
5
  const pgDriver = { member: 'Pool', declarations: ['pg', '@types/pg', 'pg-pool', '@types/pg-pool'] };
5
6
  const drivers = new Map([
@@ -166,7 +167,11 @@ function checkLostCheckout(query, callee, context) {
166
167
  if (!context.isPackageType(connect.expression.expression, pg, ['Pool']) ||
167
168
  !context.isPackageType(client, pg, ['PoolClient']))
168
169
  return;
169
- context.report(connect, 'pg-unreleased-checkout', 'This checkout discards the client after one query(), so it can never be released and leaks a pooled connection. Call `pool.query()` for a single statement, or keep `client` and call `client.release()` in finally.');
170
+ const advice = isSessionIndependentCheckoutQuery(query)
171
+ ? 'Call `pool.query()` so the pool manages the checkout.'
172
+ : 'Keep the checked-out client for the operation and any session cleanup. Release it in finally after cleanup, or discard it if cleanup fails.';
173
+ context.report(connect, 'pg-unreleased-checkout', 'This checkout discards the client after query(), so it cannot be released and leaks a pooled connection. ' +
174
+ advice);
170
175
  }
171
176
  function checkPoolCreation(node, context) {
172
177
  const target = node.expression;
@@ -109,6 +109,9 @@ const nativeSyntax = {
109
109
  SymbolFlags,
110
110
  TypeFlags,
111
111
  getCombinedModifierFlags,
112
+ // A skipped array binding slot is a nameless BindingElement in the native tree.
113
+ isOmittedExpression: (node) => guards.isOmittedExpression(node) || (guards.isBindingElement(node) && !node.name),
114
+ isBindingElement: (node) => guards.isBindingElement(node) && Boolean(node.name),
112
115
  isFunctionLike: guards.isFunctionLikeDeclaration,
113
116
  isClassLike: guards.isClassLikeDeclaration,
114
117
  isParameter: guards.isParameterDeclaration,
@@ -25,12 +25,24 @@ const COMPLETING_OPERATORS = new Set([
25
25
  'takeUntilDestroyed',
26
26
  'take',
27
27
  'takeWhile',
28
- 'takeLast',
29
28
  'first',
30
- 'last',
31
29
  'single',
32
30
  'elementAt',
33
31
  ]);
32
+ const FLATTENING_OPERATORS = new Set([
33
+ 'concatAll',
34
+ 'concatMap',
35
+ 'concatMapTo',
36
+ 'exhaust',
37
+ 'exhaustAll',
38
+ 'exhaustMap',
39
+ 'mergeAll',
40
+ 'mergeMap',
41
+ 'mergeMapTo',
42
+ 'switchAll',
43
+ 'switchMap',
44
+ 'switchMapTo',
45
+ ]);
34
46
  const ENDLESS_PACKAGES = ['@ngrx/store', '@angular/forms'];
35
47
  const COMPLETING_PACKAGES = ['@angular/common'];
36
48
  const SUBSCRIBE_MAY_COMPLETE_REASON = 'The source may complete on its own (route params, single-emission or finite observables); dismiss if it does.';
@@ -41,30 +53,65 @@ const OBSERVER_REASON = 'An observer attached to an element the component owns i
41
53
  const ON_PUSH_REASON = 'OnPush skips checks for @Input objects that are mutated in place, so confirm the inputs are immutable or signal-driven first; zoneless apps do not need it.';
42
54
  // --- RxJS subscriptions
43
55
  // -------------------------------------------------------------------------------------
44
- // `source.pipe(a(), b()).asObservable()` -> the source expression plus the imported operator names
45
- // applied to it.
56
+ // Keep the lifetime effects in pipeline order, including across separate pipe() calls.
46
57
  function unwrapPipes(expression, checker) {
47
- const operatorNames = [];
58
+ const effects = [];
48
59
  let source = ts.skipOuterExpressions(expression);
49
60
  while (ts.isCallExpression(source) && ts.isPropertyAccessExpression(source.expression)) {
50
61
  const method = source.expression.name.text;
51
62
  if (method === 'pipe')
52
- operatorNames.push(...importedOperatorNames(source.arguments, checker));
63
+ effects.unshift(...operatorEffects(source.arguments, checker));
53
64
  else if (method !== 'asObservable')
54
65
  break;
55
66
  source = ts.skipOuterExpressions(source.expression.expression);
56
67
  }
57
- return { source, operatorNames };
68
+ return { source, effects };
58
69
  }
59
- function importedOperatorNames(pipeArguments, checker) {
60
- const names = [];
70
+ function operatorEffects(pipeArguments, checker) {
71
+ const effects = [];
61
72
  for (const argument of pipeArguments) {
62
73
  const operator = ts.skipOuterExpressions(argument);
63
- const name = ts.isCallExpression(operator) && importedName(operator.expression, checker, RXJS_OPERATOR_MODULES);
64
- if (name)
65
- names.push(name);
74
+ if (!ts.isCallExpression(operator))
75
+ continue;
76
+ const name = importedName(operator.expression, checker, RXJS_OPERATOR_MODULES);
77
+ if (!name)
78
+ continue;
79
+ // RxJS implements a nonpositive takeLast count as an immediately completing stream.
80
+ if (COMPLETING_OPERATORS.has(name) || (name === 'takeLast' && isNonpositiveCount(operator.arguments[0]))) {
81
+ effects.push('complete');
82
+ }
83
+ else if (FLATTENING_OPERATORS.has(name) && !hasFiniteInnerStream(name, operator, checker)) {
84
+ effects.push('flatten');
85
+ }
86
+ }
87
+ return effects;
88
+ }
89
+ function hasFiniteInnerStream(name, operator, checker) {
90
+ const argument = operator.arguments[0] && ts.skipOuterExpressions(operator.arguments[0]);
91
+ if (!argument)
92
+ return false;
93
+ if (name.endsWith('MapTo'))
94
+ return isFiniteRxjsSource(argument, checker);
95
+ if (!name.endsWith('Map') || (!ts.isArrowFunction(argument) && !ts.isFunctionExpression(argument))) {
96
+ return false;
66
97
  }
67
- return names;
98
+ const returned = returnedExpressions(argument);
99
+ return returned.length > 0 && returned.every((value) => isFiniteRxjsSource(value, checker));
100
+ }
101
+ function isFiniteRxjsSource(value, checker) {
102
+ if (ts.isCallExpression(value))
103
+ return importedName(value.expression, checker, ['rxjs']) === 'of';
104
+ return importedName(value, checker, ['rxjs']) === 'EMPTY';
105
+ }
106
+ function isNonpositiveCount(argument) {
107
+ if (!argument)
108
+ return false;
109
+ const count = ts.skipOuterExpressions(argument);
110
+ if (ts.isNumericLiteral(count))
111
+ return Number(count.text) === 0;
112
+ return (ts.isPrefixUnaryExpression(count) &&
113
+ count.operator === ts.SyntaxKind.MinusToken &&
114
+ ts.isNumericLiteral(count.operand));
68
115
  }
69
116
  function isRxjsSubject(source, checker) {
70
117
  const symbol = checker.getTypeAtLocation(source).getSymbol();
@@ -100,10 +147,15 @@ function unmanagedSubscription(call, checker) {
100
147
  return;
101
148
  if (!declaredInPackage(callee, checker, ['rxjs']))
102
149
  return;
103
- const { source, operatorNames } = unwrapPipes(callee.expression, checker);
104
- if (operatorNames.some((name) => COMPLETING_OPERATORS.has(name)))
105
- return;
106
- const kind = classifySource(source, checker);
150
+ const { source, effects } = unwrapPipes(callee.expression, checker);
151
+ let kind = classifySource(source, checker);
152
+ for (const effect of effects) {
153
+ if (effect === 'complete')
154
+ kind = 'completing';
155
+ // Completing the outer stream can leave an active inner subscription.
156
+ else if (kind === 'completing')
157
+ kind = 'unknown';
158
+ }
107
159
  return kind === 'completing' ? undefined : kind;
108
160
  }
109
161
  // --- React
@@ -361,7 +413,7 @@ function checkAngularClass(classNode, context) {
361
413
  const kind = unmanagedSubscription(node, context.checker);
362
414
  if (!kind)
363
415
  return;
364
- context.report(node, 'angular-subscribe-without-cleanup', 'This RxJS `.subscribe()` inside an Angular component/directive has no `takeUntil` / `takeUntilDestroyed` operator and no `ngOnDestroy` unsubscribe, leaking memory and running callbacks after the component is destroyed. Prefer the `async` pipe, `toSignal()`, or `takeUntilDestroyed()`.', kind === 'unknown' ? SUBSCRIBE_MAY_COMPLETE_REASON : undefined);
416
+ context.report(node, 'angular-subscribe-without-cleanup', 'This RxJS `.subscribe()` inside an Angular component/directive can outlive the component. Prefer the `async` pipe, `toSignal()`, or place `takeUntilDestroyed()` after operators that create inner subscriptions.', kind === 'unknown' ? SUBSCRIBE_MAY_COMPLETE_REASON : undefined);
365
417
  });
366
418
  }
367
419
  // --- Vue
@@ -380,7 +432,15 @@ function scopeRegistersUnmount(scope, checker) {
380
432
  if (!ts.isCallExpression(node))
381
433
  return;
382
434
  const name = importedName(node.expression, checker, VUE_MODULES);
383
- if (name === 'onUnmounted' || name === 'onBeforeUnmount' || name === 'onScopeDispose')
435
+ if (name !== 'onUnmounted' && name !== 'onBeforeUnmount' && name !== 'onScopeDispose')
436
+ return;
437
+ const cleanup = node.arguments[0] && ts.skipOuterExpressions(node.arguments[0]);
438
+ if (cleanup &&
439
+ (ts.isArrowFunction(cleanup) || ts.isFunctionExpression(cleanup)) &&
440
+ ts.isBlock(cleanup.body) &&
441
+ cleanup.body.statements.every(ts.isEmptyStatement))
442
+ return;
443
+ if (cleanup)
384
444
  registers = true;
385
445
  });
386
446
  return registers;
@@ -403,7 +463,7 @@ function checkVueMounted(call, context) {
403
463
  const leak = vueLeakInCallback(callback, context.checker);
404
464
  if (!leak)
405
465
  return;
406
- context.report(call, 'vue-watch-missing-cleanup', `\`onMounted\` registers \`${leak.label}\` without a matching \`onUnmounted\` / \`onBeforeUnmount\` cleanup, leaking resources when the Vue component unmounts.`, leak.reason);
466
+ context.report(call, 'vue-watch-missing-cleanup', `\`onMounted\` registers \`${leak.label}\` without an apparent unmount cleanup, leaking resources when the Vue component unmounts. Release it with \`onUnmounted\` or \`onScopeDispose\`.`, leak.reason);
407
467
  }
408
468
  function hasKeyProperty(propsArgument) {
409
469
  const props = ts.skipOuterExpressions(propsArgument);