loadwise 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +542 -627
  2. package/bin/loadwise.js +4 -0
  3. package/lib/accessibility/frontend-detect.js +2 -1
  4. package/lib/accessibility/rule-ids.js +12 -9
  5. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  6. package/lib/editor/actions.js +117 -0
  7. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  8. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  9. package/lib/editor/diagnostics.js +365 -0
  10. package/lib/editor/dismissals.js +111 -0
  11. package/lib/editor/editor-document.js +99 -0
  12. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  13. package/lib/editor/fix-edits.js +200 -0
  14. package/lib/editor/language-server.js +437 -0
  15. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  16. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  17. package/lib/editor/perf-watch.js +78 -0
  18. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  19. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  20. package/lib/editor/scan-session.js +334 -0
  21. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  22. package/lib/editor/server-commands.js +232 -0
  23. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  24. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  25. package/lib/editor/types/dismissal.js +1 -0
  26. package/lib/editor/types/fix-example.js +1 -0
  27. package/lib/editor/types/source-document.js +1 -0
  28. package/lib/editor/workspace-files.js +78 -0
  29. package/lib/editor/workspace-paths.js +22 -0
  30. package/lib/maintainability/analyze-source.js +2 -0
  31. package/lib/maintainability/apply-fix.js +1 -1
  32. package/lib/maintainability/cli.js +1 -1
  33. package/lib/maintainability/examples.js +58 -41
  34. package/lib/maintainability/rule-ids.js +29 -14
  35. package/lib/maintainability/scan-changed.js +3 -0
  36. package/lib/maintainability/scan.js +13 -9
  37. package/lib/maintainability/tsconfig-strict.js +69 -0
  38. package/lib/maintainability/type-safety-hygiene.js +204 -0
  39. package/lib/performance/analyze.js +2 -0
  40. package/lib/performance/cli-arguments.js +0 -2
  41. package/lib/performance/cli-policy.js +17 -9
  42. package/lib/performance/cli-scan.js +10 -8
  43. package/lib/performance/cli.js +4 -23
  44. package/lib/performance/editor-signal.js +1 -1
  45. package/lib/performance/finding-text.js +3 -3
  46. package/lib/performance/fix-cli.js +1 -1
  47. package/lib/performance/frontend-perf.js +7 -0
  48. package/lib/performance/frontend-render-perf.js +200 -0
  49. package/lib/performance/llm-max-tokens.js +56 -0
  50. package/lib/performance/native.js +46 -26
  51. package/lib/performance/polyglot.js +22 -1
  52. package/lib/performance/pooling.js +38 -23
  53. package/lib/performance/projects.js +42 -21
  54. package/lib/performance/rule-ids.js +236 -222
  55. package/lib/performance/site-fixes/database.js +3 -1
  56. package/lib/performance/site-fixes/integrity.js +15 -1
  57. package/lib/performance/source-inputs.js +18 -6
  58. package/lib/performance/unscanned-javascript.js +66 -19
  59. package/lib/reliability/analyze.js +12 -0
  60. package/lib/reliability/child-process.js +106 -0
  61. package/lib/reliability/error-values.js +177 -0
  62. package/lib/reliability/pool-timeout.js +79 -0
  63. package/lib/reliability/react-bugs.js +602 -0
  64. package/lib/reliability/resource-leaks.js +3 -6
  65. package/lib/reliability/rule-ids.js +169 -127
  66. package/lib/reliability/switch-exhaustive.js +284 -0
  67. package/lib/reliability/uncaught-exception.js +223 -0
  68. package/lib/security/auth-crypto/rule-ids.js +3 -2
  69. package/lib/security/cli.js +6 -5
  70. package/lib/security/deps/rule-ids.js +1 -0
  71. package/lib/security/examples/auth-crypto.cjs +5 -4
  72. package/lib/security/examples/deps.cjs +1 -0
  73. package/lib/security/examples/exposure.cjs +55 -42
  74. package/lib/security/examples/files.cjs +1 -0
  75. package/lib/security/examples/injection.cjs +1 -0
  76. package/lib/security/examples/moved.cjs +5 -4
  77. package/lib/security/examples/request-forgery.cjs +1 -0
  78. package/lib/security/exposure/client-env.js +113 -0
  79. package/lib/security/exposure/frontend-security.js +12 -10
  80. package/lib/security/exposure/index.js +14 -3
  81. package/lib/security/exposure/jsx-url.js +267 -0
  82. package/lib/security/exposure/next-image-config.js +34 -0
  83. package/lib/security/exposure/package-manifest.js +45 -0
  84. package/lib/security/exposure/react-version.js +45 -0
  85. package/lib/security/exposure/rule-ids.js +16 -12
  86. package/lib/security/files/index.js +1 -1
  87. package/lib/security/files/rule-ids.js +1 -0
  88. package/lib/security/injection/code.js +24 -10
  89. package/lib/security/injection/command.js +81 -28
  90. package/lib/security/injection/nosql.js +109 -22
  91. package/lib/security/injection/redos.js +152 -308
  92. package/lib/security/injection/regex-pattern.js +290 -0
  93. package/lib/security/injection/regex.js +30 -11
  94. package/lib/security/injection/rule-ids.js +2 -1
  95. package/lib/security/injection/shared.js +19 -1
  96. package/lib/security/injection/sql.js +83 -2
  97. package/lib/security/request-forgery/rule-ids.js +1 -0
  98. package/lib/security/rule-descriptions.js +36 -32
  99. package/lib/security/rule-ids.js +74 -67
  100. package/lib/security/taint/filename-guard.js +3 -1
  101. package/lib/security/taint/guards.js +84 -10
  102. package/lib/security/taint/index.js +124 -13
  103. package/lib/security/taint/propagate.js +10 -7
  104. package/lib/security/taint/sanitizers.js +7 -3
  105. package/lib/security/taint/sources.js +6 -3
  106. package/lib/security/taint/summaries.js +13 -1
  107. package/lib/security/taint/url-parts.js +14 -5
  108. package/lib/shared/agent-session.js +2 -2
  109. package/lib/shared/check.js +9 -6
  110. package/lib/shared/explain.js +5 -5
  111. package/lib/shared/fix-convergence.js +1 -1
  112. package/lib/shared/formats/finding-location.js +6 -2
  113. package/lib/shared/formats/sarif.js +3 -3
  114. package/lib/shared/heap-limit.js +6 -0
  115. package/lib/shared/pillars.js +7 -7
  116. package/lib/shared/rule-docs.js +12 -0
  117. package/lib/shared/scan-cache.js +0 -1
  118. package/lib/shared/workspaces.js +31 -9
  119. package/package.json +9 -16
  120. package/plugin/.claude-plugin/plugin.json +1 -1
  121. package/schema/loadwise.config.schema.json +44 -0
  122. package/editor/README.md +0 -47
  123. package/examples/redis-keys.otlp.json +0 -22
  124. package/lib/maintainability/notify-editor.js +0 -1
  125. package/lib/performance/editor-report.js +0 -191
  126. package/lib/performance/editor-setup.js +0 -189
  127. package/lib/performance/editor-watch-supervisor.js +0 -104
  128. package/lib/performance/editor-watch.js +0 -193
  129. package/lib/performance/notify-editor.js +0 -1
  130. package/lib/performance/recursive-watch.js +0 -181
  131. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -10,7 +10,7 @@ import { propagation } from './propagate.js';
10
10
  import { isNumericCall, isPrunedType, isGuarded, stringIsSafe, isRegexEscape } from './sanitizers.js';
11
11
  import { validatedField, schemaCall, schemaShape } from './validators.js';
12
12
  import { createSummaries, argumentValidations } from './summaries.js';
13
- import { assignmentsTo } from './guards.js';
13
+ import { assignmentsTo, fieldWritesTo, alwaysOverwrites } from './guards.js';
14
14
  import { createUrlControl, isUrlConstructor } from './url-parts.js';
15
15
  const sinkKinds = new Set([
16
16
  'sql',
@@ -52,6 +52,17 @@ function oneLine(text, limit) {
52
52
  const line = text.replaceAll(/\s+/g, ' ').trim();
53
53
  return line.length > limit ? line.slice(0, limit - 3) + '...' : line;
54
54
  }
55
+ // The taint of a field that holds either its earlier value or the written one.
56
+ function eitherField(earlier, written) {
57
+ if (!earlier?.objectFields)
58
+ return earlier ?? written;
59
+ if (!written.objectFields)
60
+ return written;
61
+ const fields = new Map(earlier.objectFields);
62
+ for (const [name, field] of written.objectFields)
63
+ fields.set(name, eitherField(fields.get(name), field));
64
+ return { ...written, objectFields: fields };
65
+ }
55
66
  function step(node) {
56
67
  const sourceFile = node.getSourceFile();
57
68
  const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
@@ -119,6 +130,8 @@ function createTaint(program) {
119
130
  return result;
120
131
  }
121
132
  }
133
+ const pending = [];
134
+ let lowestPendingHit = Infinity;
122
135
  const summaryFnIds = new WeakMap();
123
136
  let nextSummaryFnId = 1;
124
137
  function summaryFnId(fn) {
@@ -139,14 +152,44 @@ function createTaint(program) {
139
152
  let byKey = results.get(expression);
140
153
  if (!byKey)
141
154
  results.set(expression, (byKey = new Map()));
142
- if (byKey.has(key))
143
- return byKey.get(key);
155
+ if (byKey.has(key)) {
156
+ const cached = byKey.get(key);
157
+ if (!cached)
158
+ lowestPendingHit = Math.min(lowestPendingHit, pendingIndex(byKey, key));
159
+ return cached;
160
+ }
144
161
  // A cycle (`let a = b; b = a`) resolves to clean.
145
162
  byKey.set(key, undefined);
146
- const result = isPrunedType(expression, checker) ? undefined : resolveExpression(expression, state);
147
- byKey.set(key, result);
163
+ const depth = pending.push({ byKey, key }) - 1;
164
+ const outerLowestHit = lowestPendingHit;
165
+ lowestPendingHit = Infinity;
166
+ let result;
167
+ try {
168
+ result = isPrunedType(expression, checker) ? undefined : resolveExpression(expression, state);
169
+ }
170
+ catch (error) {
171
+ // The cycle marker set above would otherwise answer the next query as a clean value.
172
+ byKey.delete(key);
173
+ lowestPendingHit = outerLowestHit;
174
+ throw error;
175
+ }
176
+ finally {
177
+ pending.pop();
178
+ }
179
+ // A miss that leaned on a node still being resolved above this one is not final: the outer
180
+ // query may still find a source there, so a later query must re-resolve instead of reusing it.
181
+ if (!result && lowestPendingHit < depth)
182
+ byKey.delete(key);
183
+ else
184
+ byKey.set(key, result);
185
+ lowestPendingHit = Math.min(outerLowestHit, lowestPendingHit);
148
186
  return result;
149
187
  }
188
+ // The depth of an in-progress resolution, or Infinity when the cached miss is a completed one.
189
+ function pendingIndex(byKey, key) {
190
+ const index = pending.findIndex((entry) => entry.byKey === byKey && entry.key === key);
191
+ return index < 0 ? Infinity : index;
192
+ }
150
193
  function resolveExpression(expression, state) {
151
194
  const next = (node) => resolve(node, state);
152
195
  if (ts.isTemplateExpression(expression)) {
@@ -183,9 +226,15 @@ function createTaint(program) {
183
226
  const operator = expression.operatorToken.kind;
184
227
  if (operator === ts.SyntaxKind.PlusToken)
185
228
  return first([expression.left, expression.right], next);
186
- if (operator === ts.SyntaxKind.QuestionQuestionToken || operator === ts.SyntaxKind.BarBarToken)
229
+ if (operator === ts.SyntaxKind.PlusEqualsToken)
230
+ return first([expression.left, expression.right], next);
231
+ if (operator === ts.SyntaxKind.QuestionQuestionToken ||
232
+ operator === ts.SyntaxKind.BarBarToken ||
233
+ operator === ts.SyntaxKind.QuestionQuestionEqualsToken ||
234
+ operator === ts.SyntaxKind.BarBarEqualsToken)
187
235
  return first([expression.left, expression.right], next, true);
188
236
  if (operator === ts.SyntaxKind.AmpersandAmpersandToken ||
237
+ operator === ts.SyntaxKind.AmpersandAmpersandEqualsToken ||
189
238
  operator === ts.SyntaxKind.CommaToken ||
190
239
  operator === ts.SyntaxKind.EqualsToken)
191
240
  return next(expression.right);
@@ -257,8 +306,14 @@ function createTaint(program) {
257
306
  for (const property of expression.properties) {
258
307
  if (ts.isSpreadAssignment(property)) {
259
308
  const spread = partOf(next(property.expression), true);
260
- if (spread)
309
+ if (!spread)
310
+ continue;
311
+ // A spread with unknown fields taints every field, so later properties add nothing.
312
+ if (!spread.objectFields)
261
313
  return spread;
314
+ whole ??= { ...spread, objectFields: undefined };
315
+ for (const [name, field] of spread.objectFields)
316
+ fields.set(name, field);
262
317
  continue;
263
318
  }
264
319
  const value = ts.isPropertyAssignment(property)
@@ -267,10 +322,15 @@ function createTaint(program) {
267
322
  ? property.name
268
323
  : undefined;
269
324
  const result = value && partOf(next(value), true);
270
- if (!result)
325
+ const name = propertyKey(property.name);
326
+ if (!result) {
327
+ // A clean later property overrides the same field of an earlier spread. A getter or method
328
+ // is not modelled, so the spread's taint for that field stays.
329
+ if (value && name !== undefined)
330
+ fields.delete(name);
271
331
  continue;
332
+ }
272
333
  whole ??= partOf(result);
273
- const name = propertyKey(property.name);
274
334
  if (name === undefined)
275
335
  return whole;
276
336
  fields.set(name, result);
@@ -329,7 +389,7 @@ function createTaint(program) {
329
389
  for (const call of summaries.callSites(fn)) {
330
390
  const argument = call.arguments[index];
331
391
  const result = argument && resolve(argument, { ...state, hops: state.hops + 1 });
332
- if (result?.taint || result?.sourceKind === 'archive-entry')
392
+ if (result?.taint || result?.container || result?.sourceKind === 'archive-entry')
333
393
  return { ...result, steps: [...result.steps, step(call), step(parameter)] };
334
394
  }
335
395
  }
@@ -408,8 +468,12 @@ function createTaint(program) {
408
468
  return withStep(loop, declaration);
409
469
  }
410
470
  else {
411
- const initial = resolve(declaration.initializer, state);
412
- if (initial || declaration.parent.flags & ts.NodeFlags.Const)
471
+ const initial = withFieldWrites(resolve(declaration.initializer, state), declaration, state);
472
+ if (declaration.parent.flags & ts.NodeFlags.Const)
473
+ return withStep(initial, declaration);
474
+ if (initial?.objectFields)
475
+ return withStep(withLaterFields(initial, declaration, identifier, state), declaration);
476
+ if (initial)
413
477
  return withStep(initial, declaration);
414
478
  }
415
479
  // `let` and `var`: any write in the same function can taint the variable.
@@ -424,8 +488,55 @@ function createTaint(program) {
424
488
  return assigned;
425
489
  }
426
490
  }
491
+ // A `let` object literal that is later reassigned another literal: a field is tainted when any
492
+ // write that can reach the use taints it.
493
+ function withLaterFields(initial, declaration, identifier, state) {
494
+ const scope = ts.findAncestor(declaration, (node) => ts.isFunctionLike(node) || ts.isSourceFile(node));
495
+ if (!scope || !initial.objectFields)
496
+ return initial;
497
+ const fields = new Map(initial.objectFields);
498
+ for (const assignment of assignmentsTo(declaration, scope, checker)) {
499
+ if (assignment.left === identifier)
500
+ continue;
501
+ const assigned = partOf(resolve(assignment.right, state), true);
502
+ // `record = req.body`: a value with unknown fields taints every field.
503
+ if (assigned && !assigned.objectFields)
504
+ return withStep(assigned, assignment);
505
+ for (const [name, field] of assigned?.objectFields ?? [])
506
+ fields.set(name, eitherField(fields.get(name), field));
507
+ }
508
+ return { ...initial, objectFields: fields };
509
+ }
510
+ // `const record = {}; record.name = req.body.name`: the literal is not the whole value once a field
511
+ // is written, so each tainted write adds its field. A tainted computed-key write taints every
512
+ // field. A value tainted as a whole already covers every field.
513
+ function withFieldWrites(initial, declaration, state) {
514
+ if (initial && !initial.objectFields)
515
+ return initial;
516
+ const initializer = strip(declaration.initializer);
517
+ if (!initializer || !ts.isObjectLiteralExpression(initializer))
518
+ return initial;
519
+ const scope = ts.findAncestor(declaration, (node) => ts.isFunctionLike(node) || ts.isSourceFile(node));
520
+ if (!scope)
521
+ return initial;
522
+ let result = initial;
523
+ for (const { name, assignment } of fieldWritesTo(declaration, scope, checker)) {
524
+ const written = withStep(partOf(resolve(assignment.right, state), true), assignment);
525
+ if (!written)
526
+ continue;
527
+ if (name === undefined)
528
+ return partOf(written);
529
+ const base = result ?? partOf(written);
530
+ if (!base)
531
+ continue;
532
+ const fields = new Map(result?.objectFields);
533
+ fields.set(name, alwaysOverwrites(assignment, declaration) ? written : eitherField(fields.get(name), written));
534
+ result = { ...base, objectFields: fields, objectSteps: result?.objectSteps ?? base.steps.length };
535
+ }
536
+ return result;
537
+ }
427
538
  function resolveCall(call, state) {
428
- if (isNumericCall(call))
539
+ if (isNumericCall(call, checker))
429
540
  return;
430
541
  if (state.sinkKind === 'regex' && isRegexEscape(call, checker))
431
542
  return;
@@ -44,7 +44,8 @@ const globalFunctions = new Set(['String', 'decodeURI', 'decodeURIComponent', 'e
44
44
  // Module or global namespaces: exported function -> 'first' (argument 0), 'any' (any argument), or
45
45
  // 'keep' (argument 0 with its `whole` flag kept, for copies of the whole object).
46
46
  const namespaceFunctions = {
47
- JSON: { parse: 'first', stringify: 'first' },
47
+ // Parsing a whole body yields a whole object, which a Mongo filter can take as operators.
48
+ JSON: { parse: 'keep', stringify: 'first' },
48
49
  Buffer: { from: 'first' },
49
50
  Promise: { resolve: 'keep', all: 'first', allSettled: 'first', race: 'first' },
50
51
  Array: { from: 'first' },
@@ -61,20 +62,22 @@ function isGlobal(identifier, checker) {
61
62
  return !declaration || declaration.getSourceFile().isDeclarationFile;
62
63
  }
63
64
  // `ids.map(() => '?')` or `ids.map((_, i) => '$' + (i + 1))`: the result is built without reading
64
- // the element. Any identifier with the element's name counts as a read, shadowed or not, so the
65
- // answer errs towards propagating.
65
+ // the element. The third parameter is the whole array, so reading it reads the elements too. Any
66
+ // identifier with such a name counts as a read, shadowed or not, so the answer errs towards
67
+ // propagating.
66
68
  function ignoresElement(callback) {
67
69
  const fn = callback && ts.skipOuterExpressions(callback);
68
70
  if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
69
71
  return false;
70
- const [element] = fn.parameters;
72
+ const [element, , array] = fn.parameters;
71
73
  if (!element)
72
74
  return true;
73
- if (!ts.isIdentifier(element.name))
75
+ const elementNames = [element, array].filter((parameter) => parameter !== undefined);
76
+ if (!elementNames.every((parameter) => ts.isIdentifier(parameter.name)))
74
77
  return false;
75
- const name = element.name.text;
78
+ const names = new Set(elementNames.map((parameter) => parameter.name.getText()));
76
79
  return !(function reads(node) {
77
- return (ts.isIdentifier(node) && node.text === name) || ts.forEachChild(node, reads);
80
+ return (ts.isIdentifier(node) && names.has(node.text)) || ts.forEachChild(node, reads);
78
81
  })(fn.body);
79
82
  }
80
83
  // How a call propagates: { from: 'receiver' } or { from: 'first' | 'any' | 'keep' | 'keep-any',
@@ -1,15 +1,19 @@
1
1
  // Values that cannot carry injectable text (design section 2.4).
2
2
  import { ts } from '../../performance/compiler.js';
3
- import { isGuardedUse } from './guards.js';
3
+ import { isBuiltinReference, isGuardedUse } from './guards.js';
4
4
  // Functions whose result is a number or boolean for every input.
5
5
  const numericFunctions = new Set(['Number', 'parseInt', 'parseFloat', 'BigInt', 'Boolean']);
6
6
  const regexMetacharacters = /[.*+?^${}()|[\]\\]/g;
7
- function isNumericCall(call) {
7
+ // A name that a project declaration shadows (`const parseInt = (v) => v`) is not the built-in and
8
+ // earns no credit.
9
+ function isNumericCall(call, checker) {
8
10
  const callee = ts.skipOuterExpressions(call.expression);
11
+ const isBuiltin = (identifier) => isBuiltinReference(identifier, checker);
9
12
  if (ts.isIdentifier(callee))
10
- return numericFunctions.has(callee.text);
13
+ return numericFunctions.has(callee.text) && isBuiltin(callee);
11
14
  return (ts.isPropertyAccessExpression(callee) &&
12
15
  ts.isIdentifier(callee.expression) &&
16
+ isBuiltin(callee.expression) &&
13
17
  (callee.expression.text === 'Math' ||
14
18
  (callee.expression.text === 'Number' && ['parseInt', 'parseFloat'].includes(callee.name.text))));
15
19
  }
@@ -174,9 +174,12 @@ function decoratorCall(decorator) {
174
174
  const expression = decorator.expression;
175
175
  return ts.isCallExpression(expression) && ts.isIdentifier(expression.expression) ? expression : undefined;
176
176
  }
177
- function isParsingPipe(argument) {
177
+ // A same-named pipe of the project can return its input unchanged, so only the `@nestjs/common`
178
+ // export counts, under whatever local name it is imported.
179
+ function isParsingPipe(argument, checker) {
178
180
  const node = ts.isNewExpression(argument) ? argument.expression : argument;
179
- return ts.isIdentifier(node) && parsingPipes.has(node.text);
181
+ const binding = importedFrom(node, checker);
182
+ return binding?.module === '@nestjs/common' && binding.exported !== undefined && parsingPipes.has(binding.exported);
180
183
  }
181
184
  // The parameter's NestJS source decorator, or undefined. A parsing pipe makes the value clean
182
185
  // (null).
@@ -186,7 +189,7 @@ function nestSource(parameter, checker) {
186
189
  const binding = call && importedFrom(call.expression, checker);
187
190
  if (!call || !binding || binding.exported === undefined || !nestDecorators[binding.module]?.has(binding.exported))
188
191
  continue;
189
- if (call.arguments.some(isParsingPipe))
192
+ if (call.arguments.some((argument) => isParsingPipe(argument, checker)))
190
193
  return null;
191
194
  const label = `@${binding.exported}(${call.arguments[0] && ts.isStringLiteralLike(call.arguments[0]) ? call.arguments[0].getText() : ''}) ${parameter.name.getText()}`;
192
195
  if (binding.exported === 'Req' || binding.exported === 'Request')
@@ -114,6 +114,8 @@ function createSummaries(program) {
114
114
  const callSitesByDeclaration = new WeakMap();
115
115
  const resolvedByName = new Map();
116
116
  let callsByName;
117
+ // `import { consume as run }`: a call spelled `run` can still resolve to `consume`.
118
+ const aliasSpellings = new Map();
117
119
  // Parameter indexes whose value can flow to a return of `fn` for a sink kind. `flows(expression,
118
120
  // parameterIndex)` resolves an expression inside `fn` with only that parameter treated as
119
121
  // tainted.
@@ -149,6 +151,13 @@ function createSummaries(program) {
149
151
  if (!isProjectSource(sourceFile))
150
152
  continue;
151
153
  (function visit(node) {
154
+ if (ts.isImportSpecifier(node) && node.propertyName) {
155
+ const spellings = aliasSpellings.get(node.propertyName.text);
156
+ if (spellings)
157
+ spellings.push(node.name.text);
158
+ else
159
+ aliasSpellings.set(node.propertyName.text, [node.name.text]);
160
+ }
152
161
  if (ts.isCallExpression(node)) {
153
162
  const calledName = calleeName(node);
154
163
  if (calledName) {
@@ -166,7 +175,10 @@ function createSummaries(program) {
166
175
  let byDeclaration = resolvedByName.get(name);
167
176
  if (!byDeclaration) {
168
177
  byDeclaration = new Map();
169
- for (const call of callsByName.get(name) ?? []) {
178
+ // Several files can import the same alias; each spelling is collected once.
179
+ const spellings = new Set([name, ...(aliasSpellings.get(name) ?? [])]);
180
+ const candidates = [...spellings].flatMap((spelling) => callsByName?.get(spelling) ?? []);
181
+ for (const call of candidates) {
170
182
  const target = checker.getResolvedSignature(call)?.declaration ?? constructorMethod(call, checker);
171
183
  if (!target)
172
184
  continue;
@@ -81,12 +81,15 @@ function singleBlockAssignment(declaration, usage, checker) {
81
81
  let assigned;
82
82
  let count = 0;
83
83
  (function visit(node) {
84
+ // A compound write (`target += x`) also changes the value, so it rules out the shortcut.
84
85
  if (ts.isBinaryExpression(node) &&
85
- node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
86
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
87
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
86
88
  ts.isIdentifier(node.left) &&
87
89
  node.end < usage.pos &&
88
90
  checker.getSymbolAtLocation(node.left) === symbol) {
89
- assigned = node.right;
91
+ if (node.operatorToken.kind === ts.SyntaxKind.EqualsToken)
92
+ assigned = node.right;
90
93
  count++;
91
94
  }
92
95
  ts.forEachChild(node, visit);
@@ -97,10 +100,16 @@ function stripEmpty(node) {
97
100
  const value = ts.skipOuterExpressions(node);
98
101
  return ts.isStringLiteralLike(value) ? value.text : undefined;
99
102
  }
100
- // The text a list of pieces starts with, when it starts with literal text.
103
+ // The text a list of pieces starts with, when it starts with literal text: adjacent literal pieces
104
+ // read as one string, as they would in the source.
101
105
  function leadingText(pieces) {
102
- const first = pieces?.[0];
103
- return first && 'text' in first ? first.text : undefined;
106
+ let text;
107
+ for (const piece of pieces ?? []) {
108
+ if (!('text' in piece))
109
+ break;
110
+ text = (text ?? '') + piece.text;
111
+ }
112
+ return text;
104
113
  }
105
114
  function isUrlConstructor(callee, checker) {
106
115
  if (!ts.isIdentifier(callee))
@@ -15,9 +15,9 @@ function promptReview(args) {
15
15
  if (!isAgentSession())
16
16
  return;
17
17
  const [command = '', subcommand = ''] = args;
18
- if (['agent', 'explain', '--version', '-v'].includes(command))
18
+ if (['agent', 'explain', 'lsp', '--version', '-v'].includes(command))
19
19
  return;
20
- if (['perf', 'maint'].includes(command) && ['editor', 'agent'].includes(subcommand))
20
+ if (['perf', 'maint'].includes(command) && subcommand === 'agent')
21
21
  return;
22
22
  const end = args.indexOf('--');
23
23
  const options = end === -1 ? args : args.slice(0, end);
@@ -3,11 +3,12 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { parseArgs } from 'node:util';
5
5
  import { loadSettings } from './config.js';
6
+ import { realTarget } from './real-target.js';
6
7
  import { selectPillars, runPillars } from './pillars.js';
7
8
  import { parseMinImpact } from './impact-levels.js';
8
9
  import { extractBaselineFlags, resolveBaselineFile } from './baseline.js';
9
10
  import { resolveFormat, renderReports } from './formats/index.js';
10
- import { discoverWorkspaces, projectConfig } from './workspaces.js';
11
+ import { discoverWorkspaces, projectConfig, uncheckedWorkspaces } from './workspaces.js';
11
12
  import { writeReviewHandoff } from './review-delivery.js';
12
13
  const invalidInputCode = 2;
13
14
  const thresholdMetCode = 1;
@@ -162,8 +163,9 @@ async function runInSequence(selected, optionsFor) {
162
163
  }
163
164
  async function scanCheck({ values, format, directory, selected, settings, baselineOptions, }) {
164
165
  // Relative paths keep the fix commands the checkers print short and runnable from the same
165
- // folder.
166
- const relative = (target) => path.relative(process.cwd(), target).split(path.sep).join('/') || '.';
166
+ // folder. The working directory is already resolved, so resolve the target too: otherwise a
167
+ // symlinked parent (macOS /var -> /private/var) turns a sibling folder into a chain of "../".
168
+ const relative = (target) => path.relative(realTarget(process.cwd()), realTarget(target)).split(path.sep).join('/') || '.';
167
169
  const flags = sharedArgs(values, format, settings, baselineOptions, directory);
168
170
  const contractFlags = contractArgs(values, format, settings);
169
171
  const optionsFor = (pillar) => ({
@@ -181,10 +183,11 @@ async function scanCheck({ values, format, directory, selected, settings, baseli
181
183
  async function scanForFixes(checkers) {
182
184
  const options = parseCheckArgs(checkers ? ['--json', '--only', checkers.join(',')] : ['--json']);
183
185
  if (options.selected.some(({ name }) => name !== 'maint') && !projectConfig(options.directory)) {
184
- const { packages, withoutConfig } = discoverWorkspaces(options.directory);
185
- if (packages.length && withoutConfig.length) {
186
+ // A package the scan skips could hold callers a fix breaks.
187
+ const unchecked = uncheckedWorkspaces(discoverWorkspaces(options.directory).withoutConfig);
188
+ if (unchecked.length) {
186
189
  throw new Error('Workspace packages are missing a source config: ' +
187
- withoutConfig.map(({ name }) => name).join(', ') +
190
+ unchecked.map(({ name }) => name).join(', ') +
188
191
  '. No fixes applied.');
189
192
  }
190
193
  }
@@ -1,9 +1,9 @@
1
1
  import { pillarOfRule, rulesByPillar } from './rule-registry.js';
2
- import { exampleFor } from '../../editor/performance-examples.cjs';
3
- import { exampleFor as exampleForReliabilityExamples } from '../../editor/reliability-examples.cjs';
4
- import { exampleFor as exampleForMaintainabilityExamples } from '../../editor/maintainability-examples.cjs';
5
- import { exampleFor as exampleForSecurityExamples } from '../../editor/security-examples.cjs';
6
- import { exampleFor as exampleForAccessibilityExamples } from '../../editor/accessibility-examples.cjs';
2
+ import { exampleFor } from '../editor/performance-examples.js';
3
+ import { exampleFor as exampleForReliabilityExamples } from '../editor/reliability-examples.js';
4
+ import { exampleFor as exampleForMaintainabilityExamples } from '../editor/maintainability-examples.js';
5
+ import { exampleFor as exampleForSecurityExamples } from '../editor/security-examples.js';
6
+ import { exampleFor as exampleForAccessibilityExamples } from '../editor/accessibility-examples.js';
7
7
  const explainedPillars = {
8
8
  performance: { name: 'Performance', exampleFor },
9
9
  reliability: { name: 'Reliability', exampleFor: exampleForReliabilityExamples },
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import * as ts from 'typescript';
5
- import { applyFix } from '../../editor/apply-fix.cjs';
5
+ import { applyFix } from '../editor/apply-fix.js';
6
6
  import { renameWithRetry } from './atomic-write.js';
7
7
  import { realTarget } from './real-target.js';
8
8
  import { introducedSyntaxError, refusalReason } from './fix-safety.js';
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { contractRules } from './contract-rules.js';
5
+ import { realTarget } from '../real-target.js';
5
6
  function findingLevel(pillar, finding) {
6
7
  if (finding.level === 'warn')
7
8
  return 'warning';
@@ -21,10 +22,13 @@ function findRepositoryRoot(start) {
21
22
  return path.resolve(start);
22
23
  }
23
24
  }
25
+ // Both sides are resolved: a checker may report from a resolved working directory while the
26
+ // repository was found through a symlinked parent (macOS /var -> /private/var), which would turn the
27
+ // path into a chain of "../".
24
28
  function repositoryPathFor(findingRoot, repositoryDirectory = findingRoot) {
25
- const repository = findRepositoryRoot(repositoryDirectory);
29
+ const repository = realTarget(findRepositoryRoot(repositoryDirectory));
26
30
  return (file) => path
27
- .relative(repository, path.resolve(findingRoot, file ?? ''))
31
+ .relative(repository, realTarget(path.resolve(findingRoot, file ?? '')))
28
32
  .split(path.sep)
29
33
  .join('/');
30
34
  }
@@ -2,8 +2,8 @@ import packageManifest from '../../../package.json' with { type: 'json' };
2
2
  const { version: toolVersion } = packageManifest;
3
3
  import { findingLevel, repositoryPathFor } from './finding-location.js';
4
4
  import { rulesByPillar } from '../rule-registry.js';
5
+ import { repositoryUrl, ruleDocUrl } from '../rule-docs.js';
5
6
  const sarifSchema = 'https://json.schemastore.org/sarif-2.1.0.json';
6
- const documentationUrl = 'https://github.com/IbrahimHafez1/loadwise';
7
7
  const fingerprintKey = 'loadwise/findingId/v1';
8
8
  const sourceRootId = '%SRCROOT%';
9
9
  // Messages carry per-site detail, so a rule without a registered description is summarized by its
@@ -19,7 +19,7 @@ function rulesFor(pillar, findings) {
19
19
  rules.set(ruleId, {
20
20
  id: ruleId,
21
21
  shortDescription: { text: shortDescription(pillar, ruleId, message) },
22
- helpUri: `${documentationUrl}#${ruleId}`,
22
+ helpUri: ruleDocUrl(ruleId) ?? repositoryUrl,
23
23
  });
24
24
  }
25
25
  return [...rules.values()];
@@ -70,7 +70,7 @@ function runFor({ pillar, root, repositoryDirectory, report }) {
70
70
  driver: {
71
71
  name: 'loadwise',
72
72
  version: toolVersion,
73
- informationUri: documentationUrl,
73
+ informationUri: repositoryUrl,
74
74
  rules: rulesFor(pillar, findings),
75
75
  },
76
76
  },
@@ -57,6 +57,12 @@ function respawnWithLargerHeap(scriptPath, args) {
57
57
  const forward = (signal) => child.kill(signal);
58
58
  for (const signal of forwardedSignals)
59
59
  process.on(signal, forward);
60
+ child.on('error', (error) => {
61
+ for (const signal of forwardedSignals)
62
+ process.off(signal, forward);
63
+ process.stderr.write(`loadwise: could not restart with a larger heap: ${error.message}\n`);
64
+ process.exitCode = 2;
65
+ });
60
66
  child.on('exit', (code) => {
61
67
  for (const signal of forwardedSignals)
62
68
  process.off(signal, forward);
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { spawn } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
6
  import { allowedHeapMegabytes, childHeapFlags, isHeapExhaustion } from './heap-limit.js';
7
- import { coveringConfig, discoverWorkspaces, projectConfig, plainJavaScriptSources } from './workspaces.js';
7
+ import { configlessSources, coveringConfig, hasWorkspaceSources, projectConfig } from './workspaces.js';
8
8
  import { cachedRun } from './scan-cache.js';
9
9
  import { isRecord } from './is-record.js';
10
10
  import { rulesByPillar } from './rule-registry.js';
@@ -145,8 +145,8 @@ function runSourceChecker(command, { directory, flags, workspaces, relative }) {
145
145
  // folder inside a package is checked with the ancestor config that covers it, and reports only its
146
146
  // own files.
147
147
  if (workspaces.length ||
148
- discoverWorkspaces(directory).packages.length ||
149
- plainJavaScriptSources(directory) ||
148
+ hasWorkspaceSources(directory) ||
149
+ configlessSources(directory) ||
150
150
  coveringConfig(directory)) {
151
151
  return runChecker([command, '-p', relative(directory), ...workspaceFlags, ...flags]);
152
152
  }
@@ -236,8 +236,8 @@ const pillars = [
236
236
  if (config && !workspaces.length)
237
237
  return runChecker(['sec', '-p', relative(config), ...flags, ...onlineFlags]);
238
238
  if (workspaces.length ||
239
- discoverWorkspaces(directory).packages.length ||
240
- plainJavaScriptSources(directory) ||
239
+ hasWorkspaceSources(directory) ||
240
+ configlessSources(directory) ||
241
241
  coveringConfig(directory)) {
242
242
  const workspaceFlags = workspaces.flatMap((selector) => ['--workspace', selector]);
243
243
  return runChecker(['sec', '-p', relative(directory), ...workspaceFlags, ...flags, ...onlineFlags]);
@@ -331,8 +331,8 @@ async function runSharedSourceCheck(shared, options) {
331
331
  const config = ownProject(directory);
332
332
  if (!workspaces.length &&
333
333
  !config &&
334
- !discoverWorkspaces(directory).packages.length &&
335
- !plainJavaScriptSources(directory) &&
334
+ !hasWorkspaceSources(directory) &&
335
+ !configlessSources(directory) &&
336
336
  !coveringConfig(directory)) {
337
337
  return runWithoutSourceConfig(shared, options, directory);
338
338
  }
@@ -0,0 +1,12 @@
1
+ import { pillarOfRule } from './rule-registry.js';
2
+ const repositoryUrl = 'https://github.com/IbrahimHafez1/loadwise';
3
+ const rulePagesUrl = `${repositoryUrl}/blob/main/docs/rules`;
4
+ // syntax-error skips the unparsable file instead of becoming a finding, so it has no page.
5
+ const undocumentedRules = new Set(['syntax-error']);
6
+ /** The documentation page of a registered rule, or undefined for an id with no page. */
7
+ function ruleDocUrl(ruleId) {
8
+ if (!pillarOfRule(ruleId) || undocumentedRules.has(ruleId))
9
+ return undefined;
10
+ return `${rulePagesUrl}/${ruleId}.md`;
11
+ }
12
+ export { repositoryUrl, ruleDocUrl, undocumentedRules };
@@ -53,7 +53,6 @@ function loadwiseFingerprint() {
53
53
  ...listSources(path.join(root, 'lib')),
54
54
  ...listSources(path.join(root, 'bin')),
55
55
  ...listSources(path.join(root, 'polyglot'), true),
56
- ...listSources(path.join(root, 'editor')),
57
56
  ].sort();
58
57
  const hash = crypto.createHash('sha1').update(`${version}\n`);
59
58
  for (let index = 0; index < sources.length; index++) {