loadwise 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import ts from 'typescript';
4
+ import { withNextEnvInventory } from '../../shared/analysis/next-env-config.js';
4
5
  import { analysisOptions, analyzeProgram, accessibilityAnalyzer, diagnosticText, reliabilityAnalyzers, resolveConfig, } from '../projects.js';
5
6
  function watchProject(configPath, { onResult, onError, policySource, securityAnalyzer }) {
6
7
  const config = resolveConfig(configPath ?? '.');
@@ -38,33 +39,36 @@ function watchProject(configPath, { onResult, onError, policySource, securityAna
38
39
  checkNode(node);
39
40
  }
40
41
  function refresh() {
41
- if (!program)
42
+ const currentProgram = program;
43
+ if (!currentProgram)
42
44
  return;
43
45
  let result;
44
46
  let security;
45
47
  try {
46
48
  if (!ts.sys.fileExists(config))
47
49
  throw new Error('Project config does not exist: ' + config);
48
- if (program.getProjectReferences()?.length) {
50
+ if (currentProgram.getProjectReferences()?.length) {
49
51
  throw new Error('Watch a leaf project with -p. This config contains project references.');
50
52
  }
51
- const configErrors = program.getConfigFileParsingDiagnostics();
53
+ const configErrors = currentProgram.getConfigFileParsingDiagnostics();
52
54
  if (configErrors.length)
53
55
  throw new Error(configErrors.map(diagnosticText).join('\n'));
54
56
  const policy = policySource?.read();
55
- result = analyzeProgram({
56
- program,
57
+ const nextEnvInputs = new Set();
58
+ result = withNextEnvInventory(() => analyzeProgram({
59
+ program: currentProgram,
57
60
  policy,
58
61
  forEachSourceCandidate,
59
62
  // The editor shows reliability and accessibility findings beside performance ones, from the same Program.
60
63
  analyzers: [...reliabilityAnalyzers, accessibilityAnalyzer],
61
- });
64
+ }), nextEnvInputs);
65
+ updateNextEnvWatches(nextEnvInputs);
62
66
  if (!result.scannedFiles)
63
67
  throw new Error('No JavaScript or TypeScript source files to check.');
64
68
  // A pass of its own reports exactly what `loadwise sec` finds, on the same Program and type checker. Every
65
69
  // refresh rechecks all files, so a change in one file also updates the taint findings of its importers.
66
70
  if (securityAnalyzer)
67
- security = analyzeProgram({ program, policy, analyzers: [securityAnalyzer] });
71
+ security = analyzeProgram({ program: currentProgram, policy, analyzers: [securityAnalyzer] });
68
72
  }
69
73
  catch (error) {
70
74
  onError(error);
@@ -82,10 +86,25 @@ function watchProject(configPath, { onResult, onError, policySource, securityAna
82
86
  if (current.nlink || previous.nlink)
83
87
  refresh();
84
88
  }
89
+ const watchedNextEnvInputs = new Set();
85
90
  for (const file of watchedPolicyFiles)
86
91
  fs.watchFile(file, { interval: 250 }, policyChanged);
92
+ function updateNextEnvWatches(inputs) {
93
+ for (const file of watchedNextEnvInputs) {
94
+ if (inputs.has(file))
95
+ continue;
96
+ fs.unwatchFile(file, policyChanged);
97
+ watchedNextEnvInputs.delete(file);
98
+ }
99
+ for (const file of inputs) {
100
+ if (watchedPolicyFiles.has(file) || watchedNextEnvInputs.has(file))
101
+ continue;
102
+ fs.watchFile(file, { interval: 250 }, policyChanged);
103
+ watchedNextEnvInputs.add(file);
104
+ }
105
+ }
87
106
  function unwatchPolicy() {
88
- for (const file of watchedPolicyFiles)
107
+ for (const file of [...watchedPolicyFiles, ...watchedNextEnvInputs])
89
108
  fs.unwatchFile(file, policyChanged);
90
109
  }
91
110
  let watcher;
@@ -193,12 +193,24 @@ function copiedFromSet(receiver, checker) {
193
193
  }
194
194
  return source !== undefined && nativeCollection(source, setTypes, checker);
195
195
  }
196
+ // `values.indexOf(value) === -1` and `< 0` ask whether the value is absent, so the Set lookup that
197
+ // replaces them is negated.
198
+ function testsAbsence(call) {
199
+ const comparison = call.parent;
200
+ if (!ts.isBinaryExpression(comparison) || comparison.left !== call)
201
+ return false;
202
+ const kind = comparison.operatorToken.kind;
203
+ return (kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
204
+ kind === ts.SyntaxKind.EqualsEqualsToken ||
205
+ kind === ts.SyntaxKind.LessThanToken);
206
+ }
196
207
  export function checkMembership(call, context) {
197
208
  if (call.arguments.length !== 1 || ts.isSpreadElement(call.arguments[0]))
198
209
  return;
199
210
  const owner = reusableArrayOwner(call, context.checker);
200
211
  if (!owner)
201
212
  return;
213
+ const method = call.expression.name.text;
202
214
  const input = iterationInput(owner);
203
215
  let reason;
204
216
  if (input &&
@@ -210,19 +222,18 @@ export function checkMembership(call, context) {
210
222
  ts.isPropertyAccessExpression(owner.parent.expression) &&
211
223
  ['every', 'some'].includes(owner.parent.expression.name.text)) {
212
224
  const statement = outerExpression(owner.parent).parent;
213
- const method = statement.parent?.parent;
225
+ const enclosingMethod = statement.parent?.parent;
214
226
  if (ts.isReturnStatement(statement) &&
215
227
  ts.isBlock(statement.parent) &&
216
- method &&
217
- ts.isMethodDeclaration(method) &&
218
- !ts.isPrivateIdentifier(method.name) &&
219
- !(ts.getCombinedModifierFlags(method) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) &&
228
+ enclosingMethod &&
229
+ ts.isMethodDeclaration(enclosingMethod) &&
230
+ !ts.isPrivateIdentifier(enclosingMethod.name) &&
231
+ !(ts.getCombinedModifierFlags(enclosingMethod) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) &&
220
232
  [input, call.expression.expression].every((collection) => {
221
233
  const collectionDeclaration = context.checker.getSymbolAtLocation(collection)?.valueDeclaration;
222
- return method.parameters.some((parameter) => parameter === collectionDeclaration);
234
+ return enclosingMethod.parameters.some((parameter) => parameter === collectionDeclaration);
223
235
  })) {
224
- reason =
225
- 'This public method receives both collections from its callers. Check how many keys they request; building a Set for a single lookup can cost more than includes().';
236
+ reason = `This public method receives both collections from its callers. Check how many keys they request; building a Set for a single lookup can cost more than ${method}().`;
226
237
  }
227
238
  }
228
239
  if (input &&
@@ -238,9 +249,15 @@ export function checkMembership(call, context) {
238
249
  reason = smallConfigListReason;
239
250
  }
240
251
  reason ??= isKnownDataSource(call.expression.expression, context.checker) ? undefined : unknownSizeReason;
252
+ // indexOf() uses strict equality, which never matches NaN; Set.has() does, so the advice says so
253
+ // when the searched value may be NaN.
254
+ const searched = context.checker.getTypeAtLocation(call.arguments[0]);
255
+ const mayBeNaN = typeParts(searched).some((part) => !(part.flags & neverNaNFlags));
256
+ const nanNote = method === 'indexOf' && mayBeNaN ? ' Unlike indexOf(), a Set also finds NaN.' : '';
257
+ const negation = method === 'indexOf' && testsAbsence(call) ? '!' : '';
241
258
  context.report(call.expression.name, 'array-repeated-membership', copiedFromSet(call.expression.expression, context.checker)
242
- ? 'This array was copied from a Set and is then searched with includes() repeatedly, scanning it each time. Keep the original Set and call `set.has(value)`; keep the array only where order matters.'
243
- : 'Each includes() can rescan this array, so many lookups cost quadratic time. Build `const lookup = new Set(values)` once outside the iteration and call `lookup.has(value)` if membership is stable.', reason);
259
+ ? `This array was copied from a Set and is then searched with ${method}() repeatedly, scanning it each time. Keep the original Set and call \`${negation}set.has(value)\`; keep the array only where order matters.${nanNote}`
260
+ : `Each ${method}() can rescan this array, so many lookups cost quadratic time. Build \`const lookup = new Set(values)\` once outside the iteration and call \`${negation}lookup.has(value)\` if membership is stable.${nanNote}`, reason);
244
261
  }
245
262
  export function checkRebuiltLookup(call, context) {
246
263
  const constructed = ts.skipOuterExpressions(call.expression.expression);
@@ -2,6 +2,7 @@ import { ts, isDefaultLibrary } from '../engine/compiler.js';
2
2
  import { isStandardArrayCall, standardInterface } from './repeated.js';
3
3
  import { clientHookContext, clientSourcePattern, isTestSource } from '../analysis/review-context.js';
4
4
  import { classifyExecutionContext } from '../../shared/analysis/execution-context.js';
5
+ import { allProjectCallers } from '../../shared/analysis/hot-path-graph.js';
5
6
  import { constantListLimit, constantTableLimit, fallbackOperators, finiteDomainLimit, isConstAssertion, listsProperties, maxBoundDepth, mayChange, mayChangeBefore, resolvedSymbol, sameIdentifier, smallLiteralLimit, syncCallback, typeParts, unchangedConstant, writtenBindings, } from './collection-bindings.js';
6
7
  import { arraySizeBound, isLiteralList } from './collection-bounds.js';
7
8
  import { addsAnotherItem, addsDynamicKey, growingConcat, objectAssignCopy } from './collection-copy.js';
@@ -15,7 +16,10 @@ const schemaPropertiesReason = 'Reduces over the properties of one JSON Schema o
15
16
  const enumListReason = 'Reduces over a list of enum or literal values, which holds about one entry per declared member; assess only if the list can repeat values at scale.';
16
17
  const moduleLoadReason = 'Runs once when the module loads, not per request, so the accumulator copy is paid at startup; assess only if the input grows with data.';
17
18
  const uiReduceReason = 'Runs in a JSX component module over UI state rather than on a server request path. Review in a front-end context if the list can grow large.';
19
+ const shortCallerListsReason = 'Every call to this function in the project passes a short array literal here, so the accumulator copy stays bounded; assess only if a new caller passes stored data.';
18
20
  const jsonSchemaMembers = ['type', 'properties', 'required'];
21
+ // The longest array literal a caller can pass and still count as a short, hand-written list.
22
+ const maxCallerListLength = 16;
19
23
  function usesIterationParameter(expression, parameters, checker) {
20
24
  function visit(node) {
21
25
  if (ts.isIdentifier(node)) {
@@ -132,6 +136,30 @@ function hasSmallConstAssertedList(input, checker) {
132
136
  ts.isArrayLiteralExpression(literal) &&
133
137
  isLiteralList(literal, constantListLimit));
134
138
  }
139
+ function isShortListArgument(argument) {
140
+ const list = argument && ts.skipOuterExpressions(argument);
141
+ return (list !== undefined &&
142
+ ts.isArrayLiteralExpression(list) &&
143
+ list.elements.length <= maxCallerListLength &&
144
+ !list.elements.some(ts.isSpreadElement));
145
+ }
146
+ // `function keys(frame, options: string[]) { return options.reduce(...) }` where every resolved
147
+ // caller writes `keys(frame, ['include', 'fields'])`. An unresolved or uncounted caller keeps the finding.
148
+ function hasShortListCallers(input, checker, program) {
149
+ if (!ts.isIdentifier(input))
150
+ return false;
151
+ const symbol = checker.getSymbolAtLocation(input);
152
+ const parameter = symbol?.valueDeclaration;
153
+ if (!parameter || !ts.isParameter(parameter) || parameter.dotDotDotToken)
154
+ return false;
155
+ const owner = parameter.parent;
156
+ if (!ts.isFunctionLike(owner) || !('body' in owner) || !owner.body || mayChange(symbol, owner.body, checker))
157
+ return false;
158
+ const index = owner.parameters.indexOf(parameter);
159
+ const callers = allProjectCallers(owner, program);
160
+ return (!!callers?.length &&
161
+ callers.every((caller) => !caller.arguments.slice(0, index).some(ts.isSpreadElement) && isShortListArgument(caller.arguments[index])));
162
+ }
135
163
  // `createParamDecorator((data, ctx) => data.reduce(...))`: `data` is what the developer wrote at
136
164
  // the decorator use site.
137
165
  function isDecoratorArgument(input, checker) {
@@ -237,7 +265,7 @@ function hasClosedAccumulatorType(spread, callback, checker) {
237
265
  const keyCount = type.getProperties().length;
238
266
  return keyCount > 0 && keyCount <= finiteDomainLimit;
239
267
  }
240
- function boundedReduceReason(call, input, checker) {
268
+ function boundedReduceReason(call, input, checker, program) {
241
269
  if (hasSmallFixedInput(input, checker) ||
242
270
  arraySizeBound(input, checker) <= smallLiteralLimit ||
243
271
  hasSmallConstAssertedList(input, checker) ||
@@ -246,6 +274,8 @@ function boundedReduceReason(call, input, checker) {
246
274
  return smallInputReason;
247
275
  if (isDecoratorArgument(input, checker))
248
276
  return decoratorArgumentReason;
277
+ if (hasShortListCallers(input, checker, program))
278
+ return shortCallerListsReason;
249
279
  if (isTestSource(input.getSourceFile().fileName))
250
280
  return testSourceReason;
251
281
  if (runsAtModuleLoad(call))
@@ -330,7 +360,7 @@ export function checkReducer(call, context) {
330
360
  if (!isStandardArrayCall(call, checker) ||
331
361
  (ts.isBlock(callback.body) && mayChange(checker.getSymbolAtLocation(accumulator), callback.body, checker)))
332
362
  return;
333
- context.report(spread, 'reduce-copy-accumulator', 'Spreading the accumulator copies it on every reduction step, which takes quadratic time. Mutate one fresh accumulator instead (`acc.push(item)` or `acc[key] = value`) if intermediate versions are unobserved.', boundedReduceReason(call, input, checker) ??
363
+ context.report(spread, 'reduce-copy-accumulator', 'Spreading the accumulator copies it on every reduction step, which takes quadratic time. Mutate one fresh accumulator instead (`acc.push(item)` or `acc[key] = value`) if intermediate versions are unobserved.', boundedReduceReason(call, input, checker, context.program) ??
334
364
  (hasFiniteAccumulatorKeys(spread, checker) ? finiteKeyReason : undefined) ??
335
365
  (hasClosedAccumulatorType(spread, callback, checker) ? closedAccumulatorReason : undefined));
336
366
  }
@@ -6,6 +6,30 @@ import { checkCollectionAssignment } from './collection-copy.js';
6
6
  import { checkFind, checkMembership, checkRebuiltLookup } from './collection-lookups.js';
7
7
  import { checkReducer } from './collection-reduce.js';
8
8
  import { checkArrayDrain } from './array-drains.js';
9
+ // The bound `indexOf()` is compared with when the comparison only asks whether the value is present. The kinds are
10
+ // read per call because the native engine swaps `ts` after modules load and numbers its SyntaxKind values differently.
11
+ function membershipBound(operator) {
12
+ switch (operator) {
13
+ case ts.SyntaxKind.EqualsEqualsEqualsToken:
14
+ case ts.SyntaxKind.ExclamationEqualsEqualsToken:
15
+ case ts.SyntaxKind.EqualsEqualsToken:
16
+ case ts.SyntaxKind.ExclamationEqualsToken:
17
+ case ts.SyntaxKind.GreaterThanToken:
18
+ return '-1';
19
+ case ts.SyntaxKind.GreaterThanEqualsToken:
20
+ case ts.SyntaxKind.LessThanToken:
21
+ return '0';
22
+ }
23
+ }
24
+ // `values.indexOf(value) !== -1` and its variants only ask whether the value is present, so a Set
25
+ // answers them; a position that is read or stored has no Set equivalent.
26
+ function isMembershipTest(call) {
27
+ const comparison = call.parent;
28
+ if (!ts.isBinaryExpression(comparison) || comparison.left !== call)
29
+ return false;
30
+ const bound = membershipBound(comparison.operatorToken.kind);
31
+ return bound !== undefined && comparison.right.getText() === bound;
32
+ }
9
33
  function checkCollectionCall(call, context) {
10
34
  if (!isMemberCall(call) || ts.isOptionalChain(call))
11
35
  return;
@@ -20,6 +44,10 @@ function checkCollectionCall(call, context) {
20
44
  return checkFind(call, context);
21
45
  case 'includes':
22
46
  return checkMembership(call, context);
47
+ case 'indexOf':
48
+ if (isMembershipTest(call))
49
+ return checkMembership(call, context);
50
+ return;
23
51
  case 'reduce':
24
52
  return checkReducer(call, context);
25
53
  case 'shift':
@@ -134,6 +134,30 @@ function findRepeatOwner(node, checker) {
134
134
  function isRepeated(node, checker) {
135
135
  return findRepeatOwner(node, checker) !== undefined;
136
136
  }
137
+ const ITERATING_METHODS = new Set(['map', 'forEach', 'flatMap']);
138
+ const UNTYPED_COLLECTION_REASON = 'The iterated collection is untyped, so its size is unknown. Review whether it can grow large.';
139
+ // A callback passed to `.map`/`.forEach` on a receiver of type `any` is not recognised as an array
140
+ // iteration, so its queries would never count as per-item. The callback is still the repeating
141
+ // scope, at lower precision.
142
+ function untypedIterationCallback(call, checker) {
143
+ const callback = ts.findAncestor(call, ts.isFunctionLike);
144
+ if (!callback ||
145
+ (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback) && !ts.isMethodDeclaration(callback)) ||
146
+ callback.asteriskToken)
147
+ return;
148
+ let argument = callback;
149
+ while (ts.isOuterExpression(argument.parent) && argument.parent.expression === argument)
150
+ argument = argument.parent;
151
+ const iteration = argument.parent;
152
+ if (!ts.isCallExpression(iteration) ||
153
+ iteration.arguments[0] !== argument ||
154
+ !ts.isPropertyAccessExpression(iteration.expression) ||
155
+ !ITERATING_METHODS.has(iteration.expression.name.text))
156
+ return;
157
+ const receiverType = checker.getTypeAtLocation(iteration.expression.expression);
158
+ if (receiverType.flags & ts.TypeFlags.Any)
159
+ return callback;
160
+ }
137
161
  const promiseCombinators = new Set(['all', 'allSettled', 'any', 'race']);
138
162
  const mappingMethods = new Set(['map', 'flatMap']);
139
163
  function combinatorName(call, argument) {
@@ -191,4 +215,4 @@ function elementBinding(owner) {
191
215
  if (ts.isFunctionLike(owner))
192
216
  return owner.parameters[0]?.name;
193
217
  }
194
- export { elementBinding, findRepeatOwner, isRepeated, isStandardArrayCall, isStandardCallback, outerExpression, promiseCombinatorOf, standardInterface, };
218
+ export { elementBinding, findRepeatOwner, isRepeated, isStandardArrayCall, isStandardCallback, outerExpression, promiseCombinatorOf, standardInterface, UNTYPED_COLLECTION_REASON, untypedIterationCallback, };
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { compareDto, controllerTypeUsages } from './dto.js';
7
7
  import { OperationDocumentError, compareGraphql } from './graphql.js';
8
- import { OpenApiSymlinkError, changedSince, insideNodeModules, listBaselineFiles, listProjectFiles, readAtBase, readOpenApiAtBase, trpcBaselineCandidates, } from './git-files.js';
8
+ import { OpenApiSymlinkError, changedSince, insideNodeModules, listBaselineFiles, listProjectFiles, readAtBase, readManyAtBase, readOpenApiAtBase, trpcBaselineCandidates, } from './git-files.js';
9
9
  import { compareOpenApi } from './openapi.js';
10
10
  import { compareProtobuf, protobufRpcNames } from './protobuf.js';
11
11
  import { compareTrpc, hasTrpcInitializerImport, traceBaselineTrpcModules } from './trpc.js';
@@ -16,6 +16,7 @@ import { findProjectRoot } from '../schema/context.js';
16
16
  import { loadSettings } from '../../shared/config.js';
17
17
  import { annotateImpact, filterMinImpact, parseMinImpact } from '../../shared/reporting/impact-levels.js';
18
18
  import { printTerminalLine, terminalSafe } from '../../shared/system/terminal-safe.js';
19
+ import { reportTextFindings } from '../../shared/reporting/automatic-fix-signal.js';
19
20
  import { impactByRule } from '../../reliability/rule-ids.js';
20
21
  import { discoverWorkspaces } from '../../shared/workspaces.js';
21
22
  import { isPathInsideOrEqual } from '../../shared/system/path-inside.js';
@@ -95,19 +96,24 @@ function cacheContractReads(read) {
95
96
  const maxCachedCharacters = 4 * 1024 * 1024;
96
97
  const maxFilesPerSide = 256;
97
98
  let cachedCharacters = 0;
98
- return (side, file) => {
99
+ // Texts read elsewhere, such as by a batched base read, are remembered under the same limits.
100
+ const remember = (side, file, text) => {
99
101
  const snapshot = documents[side];
100
- const saved = snapshot.get(file);
101
- if (saved !== undefined)
102
- return saved;
103
- const text = read(side, file);
104
102
  const characters = text?.length ?? 0;
105
103
  if (snapshot.size < maxFilesPerSide && cachedCharacters + characters <= maxCachedCharacters) {
106
104
  snapshot.set(file, text);
107
105
  cachedCharacters += characters;
108
106
  }
107
+ };
108
+ const lookup = (side, file) => {
109
+ const saved = documents[side].get(file);
110
+ if (saved !== undefined)
111
+ return saved;
112
+ const text = read(side, file);
113
+ remember(side, file, text);
109
114
  return text;
110
115
  };
116
+ return Object.assign(lookup, { remember });
111
117
  }
112
118
  function openApiFindings(context, projectFiles, inScope) {
113
119
  const root = fs.realpathSync.native(context.cwd);
@@ -430,10 +436,15 @@ function mightUseTrpc(context, read) {
430
436
  const candidates = trpcBaselineCandidates(context.base, context.cwd);
431
437
  if (!candidates)
432
438
  return true;
433
- return candidates.some((file) => {
434
- const source = read('old', file);
435
- return source === null || hasTrpcInitializerImport(source, file);
436
- });
439
+ // An excluded path reads as unavailable, which cannot rule tRPC out.
440
+ if (candidates.some(excludedContractPath))
441
+ return true;
442
+ for (const [file, source] of readManyAtBase(context.base, candidates, context.cwd)) {
443
+ read.remember('old', file, source);
444
+ if (source === null || hasTrpcInitializerImport(source, file))
445
+ return true;
446
+ }
447
+ return false;
437
448
  }
438
449
  // `side` says which version the finding's line belongs to; removals point at the base version.
439
450
  function describe({ side, ...finding }, ref) {
@@ -459,7 +470,6 @@ function checkContracts({ cwd, ref, reportRoot = cwd, includesFile = () => true,
459
470
  const comparedFormats = new Set();
460
471
  context.forbidsUnknownInput = controllers.length > 0 && projectForbidsUnknownInput(context, files);
461
472
  const tsFiles = byFormat('.ts');
462
- // Reuse preflight reads when the same initializer is needed by the comparison.
463
473
  const readTrpc = cacheContractReads((side, file) => readProjectFile(context, side, file));
464
474
  const trpcFiles = tsFiles.length && mightUseTrpc(context, readTrpc) ? tsFiles : [];
465
475
  const protobufFiles = byFormat('.proto');
@@ -523,6 +533,7 @@ async function run(argv) {
523
533
  console.log(JSON.stringify(result, null, 2));
524
534
  else {
525
535
  printText(result);
536
+ reportTextFindings(result.findings);
526
537
  const note = settings.warningNote(result.findings);
527
538
  if (note)
528
539
  console.log(note);
@@ -1,6 +1,7 @@
1
1
  // What changed since the comparison base, and the base's version of a file. Read-only git, no
2
2
  // network.
3
3
  import { git, mergeBaseSince } from '../migrations/enforce.js';
4
+ import { gitBytes } from '../../shared/system/git.js';
4
5
  class OpenApiSymlinkError extends Error {
5
6
  constructor(file) {
6
7
  super(`symbolic links are unsupported: ${file}`);
@@ -68,6 +69,50 @@ function readAtBase(base, file, cwd) {
68
69
  return null;
69
70
  }
70
71
  }
72
+ // One `git cat-file --batch` per chunk replaces a `git show` process per file; spawning git dominated
73
+ // changed-line scans of large repositories. Each text matches readAtBase, null for a missing file.
74
+ const batchReadChunk = 64;
75
+ const batchOutputLimit = 64 * 1024 * 1024;
76
+ function* readManyAtBase(base, files, cwd) {
77
+ for (let start = 0; start < files.length; start += batchReadChunk) {
78
+ const chunk = files.slice(start, start + batchReadChunk);
79
+ const texts = batchBlobTexts(base, chunk, cwd);
80
+ for (const [index, file] of chunk.entries()) {
81
+ // null is the batch's answer that the file is missing at the base; only undefined needs `git show`.
82
+ const text = texts?.[index];
83
+ yield [file, text === undefined ? readAtBase(base, file, cwd) : text];
84
+ }
85
+ }
86
+ }
87
+ // Texts in request order. An entry is undefined where the batch cannot stand in for `git show` (a name with a
88
+ // line break, or an object other than a blob), and the whole result is undefined when git fails.
89
+ function batchBlobTexts(base, files, cwd) {
90
+ const requested = files.filter((file) => !/[\r\n]/.test(file));
91
+ if (!requested.length)
92
+ return files.map(() => undefined);
93
+ const input = requested.map((file) => `${base}:./${file}\n`).join('');
94
+ const output = gitBytes(cwd, ['cat-file', '--batch'], { input, useCwd: true, maxBuffer: batchOutputLimit });
95
+ if (!output)
96
+ return undefined;
97
+ const texts = new Map();
98
+ let offset = 0;
99
+ for (const file of requested) {
100
+ const headerEnd = output.indexOf(0x0a, offset);
101
+ if (headerEnd < 0)
102
+ return undefined;
103
+ const header = output.toString('utf8', offset, headerEnd);
104
+ offset = headerEnd + 1;
105
+ const object = /^[0-9a-f]+ (\w+) (\d+)$/.exec(header);
106
+ if (!object) {
107
+ texts.set(file, header.endsWith(' missing') ? null : undefined);
108
+ continue;
109
+ }
110
+ const size = Number(object[2]);
111
+ texts.set(file, object[1] === 'blob' ? output.toString('utf8', offset, offset + size) : undefined);
112
+ offset += size + 1;
113
+ }
114
+ return files.map((file) => texts.get(file));
115
+ }
71
116
  function readOpenApiAtBase(base, file, cwd) {
72
117
  const treeEntry = git(['--literal-pathspecs', 'ls-tree', '-z', base, '--', file], cwd);
73
118
  if (!treeEntry)
@@ -86,4 +131,4 @@ function readOpenApiAtBase(base, file, cwd) {
86
131
  function insideNodeModules(file) {
87
132
  return file.split('/').includes('node_modules');
88
133
  }
89
- export { OpenApiSymlinkError, changedSince, insideNodeModules, listBaselineFiles, listProjectFiles, readAtBase, readOpenApiAtBase, trpcBaselineCandidates, };
134
+ export { OpenApiSymlinkError, changedSince, insideNodeModules, listBaselineFiles, listProjectFiles, readAtBase, readManyAtBase, readOpenApiAtBase, trpcBaselineCandidates, };
@@ -1,7 +1,7 @@
1
1
  import { ts } from '../engine/compiler.js';
2
2
  import { findRepeatOwner, outerExpression } from '../collections/repeated.js';
3
3
  import { isSessionIndependentCheckoutQuery } from './pg-integrity.js';
4
- import { resolveImportedBinding, staticMemberName, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
4
+ import { importedMember, staticMemberName, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
5
5
  import { normalizeSlashes } from '../../shared/system/posix-path.js';
6
6
  const pgDriver = { member: 'Pool', declarations: ['pg', '@types/pg', 'pg-pool', '@types/pg-pool'] };
7
7
  const drivers = new Map([
@@ -40,22 +40,6 @@ function mayLoadDriver(file) {
40
40
  }
41
41
  return mayLoad;
42
42
  }
43
- // The module export a callee names, through aliased, default, namespace and require bindings:
44
- // exported is a named export, 'default', or '*' for a whole required module. A member of a
45
- // namespace, required module or default import (`pg.Pool`, `pg['Pool']`) is that module's export.
46
- function importedMember(target, checker) {
47
- const callee = unwrapExpression(target);
48
- if (ts.isIdentifier(callee)) {
49
- return resolveImportedBinding(callee, checker, { includeNamespaceImports: false, includeDefaultMembers: true });
50
- }
51
- if (!ts.isPropertyAccessExpression(callee) && !ts.isElementAccessExpression(callee))
52
- return;
53
- const member = staticMemberName(callee);
54
- const owner = resolveImportedBinding(unwrapExpression(callee.expression), checker, { includeDefaultMembers: true });
55
- if (member === undefined || !owner || (owner.exported !== '*' && owner.exported !== 'default'))
56
- return;
57
- return { module: owner.module, exported: member };
58
- }
59
43
  // A package that also exports the class as its default is constructed through a default import
60
44
  // (`import OpenAI from 'openai'`) or a whole required module (`const Stripe = require('stripe')`).
61
45
  function isDriverExport(exported, driver) {
@@ -1,6 +1,6 @@
1
1
  import { ts } from '../engine/compiler.js';
2
2
  import { shouldReportLoopQuery } from '../query-loops/query-loops.js';
3
- import { findRepeatOwner } from '../collections/repeated.js';
3
+ import { findRepeatOwner, UNTYPED_COLLECTION_REASON, untypedIterationCallback } from '../collections/repeated.js';
4
4
  import { isSequentialByDesign } from '../query-loops/sequential-loops.js';
5
5
  import { awaitedResult, clientSideQuery, firstElementRead, isDiscardedValue, outsideWrappers, } from '../query-loops/query-results.js';
6
6
  const PG_PACKAGES = ['pg', '@types/pg', 'pg-pool', '@types/pg-pool'];
@@ -155,46 +155,54 @@ function checkPostgresCall(call, context) {
155
155
  if (!method || !call.arguments.length)
156
156
  return;
157
157
  const repeated = context.isRepeated(call);
158
+ // pg ships no types, so untyped JavaScript leaves `result.rows.map(...)` unrecognised as an array.
159
+ const untypedOwner = repeated ? undefined : untypedIterationCallback(call, context.checker);
158
160
  const awaited = awaitedResult(call);
159
161
  const rows = awaited && accessedProperty(awaited, 'rows');
160
- const count = rows && directRowCount(rows);
161
- const first = rows && firstElementRead(rows);
162
- const clientSide = rows && clientSideQuery(rows);
163
- if (!repeated && !count && !first && !clientSide)
162
+ const reads = rows
163
+ ? { count: directRowCount(rows), first: firstElementRead(rows), clientSide: clientSideQuery(rows) }
164
+ : {};
165
+ const readsRows = Boolean(reads.count || reads.first || reads.clientSide);
166
+ if (!repeated && !untypedOwner && !readsRows)
164
167
  return;
165
168
  if (!context.isPackageType(method.expression, PG_PACKAGES, PG_RECEIVERS))
166
169
  return;
167
- const owner = repeated ? findRepeatOwner(call, context.checker) : undefined;
168
- if (repeated &&
169
- !runsNonBatchableCommand(call.arguments[0]) &&
170
+ const owner = repeated ? findRepeatOwner(call, context.checker) : untypedOwner;
171
+ if (owner && reportsLoopQuery(call, owner, context)) {
172
+ context.report(ts.isPropertyAccessExpression(method) ? method.name : method.argumentExpression, 'pg-query-in-loop', 'This pg query can run once per iteration, adding a round trip per item. Batch independent reads into one query such as `WHERE id = ANY($1)` and map rows by key; keep scope predicates and the transaction client.', untypedOwner ? UNTYPED_COLLECTION_REASON : undefined);
173
+ }
174
+ if (readsRows)
175
+ reportRowMaterialization(call, reads, context);
176
+ }
177
+ function reportsLoopQuery(call, owner, context) {
178
+ return (!runsNonBatchableCommand(call.arguments[0]) &&
170
179
  !runsLoopItemAsSql(call, context.checker) &&
171
- !(owner && appliesOrderedStatements(owner, context)) &&
180
+ !appliesOrderedStatements(owner, context) &&
172
181
  !isSequentialByDesign(call, owner) &&
173
- shouldReportLoopQuery(call, context.checker)) {
174
- context.report(ts.isPropertyAccessExpression(method) ? method.name : method.argumentExpression, 'pg-query-in-loop', 'This pg query can run once per iteration, adding a round trip per item. Batch independent reads into one query such as `WHERE id = ANY($1)` and map rows by key; keep scope predicates and the transaction client.');
182
+ shouldReportLoopQuery(call, context.checker, { owner }));
183
+ }
184
+ function reportRowMaterialization(call, reads, context) {
185
+ const queryText = literalQueryText(call.arguments[0]);
186
+ if (!queryText)
187
+ return;
188
+ if (reads.count && countRead.test(queryText)) {
189
+ context.report(reads.count.name, 'pg-count-materialization', 'This SELECT transfers every matching row just to count them. Use `SELECT count(*) AS total ...` and convert the bigint string result with `Number()` or `BigInt()`.');
175
190
  }
176
- if (count || first || clientSide) {
177
- const queryText = literalQueryText(call.arguments[0]);
178
- if (!queryText)
179
- return;
180
- if (count && countRead.test(queryText)) {
181
- context.report(count.name, 'pg-count-materialization', 'This SELECT transfers every matching row just to count them. Use `SELECT count(*) AS total ...` and convert the bigint string result with `Number()` or `BigInt()`.');
182
- }
183
- if (first && firstRead.test(queryText)) {
184
- context.report(first.argumentExpression, 'pg-first-materialization', 'This SELECT transfers every matching row but only the first is read. Add `LIMIT 1` to the query and keep a deterministic `ORDER BY` when the chosen row matters.');
185
- }
186
- if (clientSide) {
187
- const query = firstRead.exec(queryText);
188
- const projectionText = query?.groups?.projection;
189
- if (projectionText === undefined || !readsProjectedField(call.arguments[0], projectionText, clientSide.field))
190
- return;
191
- if (clientSide.method.text === 'filter') {
192
- context.report(clientSide.method, 'pg-filter-materialization', 'This SELECT transfers rows that JavaScript then filters by one field. Move the test into SQL with `WHERE field = $1`; check type, NULL and collation semantics match the JavaScript comparison.');
193
- }
194
- else {
195
- context.report(clientSide.method, 'pg-top-k-materialization', 'This SELECT transfers all rows that JavaScript then sorts and truncates. Use `ORDER BY column DESC, id ASC LIMIT $1` in SQL; keep numeric conversion, NULL ordering and tie-breaking.');
196
- }
197
- }
191
+ if (reads.first && firstRead.test(queryText)) {
192
+ context.report(reads.first.argumentExpression, 'pg-first-materialization', 'This SELECT transfers every matching row but only the first is read. Add `LIMIT 1` to the query and keep a deterministic `ORDER BY` when the chosen row matters.');
193
+ }
194
+ if (reads.clientSide)
195
+ reportClientSideQuery(call, queryText, reads.clientSide, context);
196
+ }
197
+ function reportClientSideQuery(call, queryText, clientSide, context) {
198
+ const projectionText = firstRead.exec(queryText)?.groups?.projection;
199
+ if (projectionText === undefined || !readsProjectedField(call.arguments[0], projectionText, clientSide.field))
200
+ return;
201
+ if (clientSide.method.text === 'filter') {
202
+ context.report(clientSide.method, 'pg-filter-materialization', 'This SELECT transfers rows that JavaScript then filters by one field. Move the test into SQL with `WHERE field = $1`; check type, NULL and collation semantics match the JavaScript comparison.');
203
+ }
204
+ else {
205
+ context.report(clientSide.method, 'pg-top-k-materialization', 'This SELECT transfers all rows that JavaScript then sorts and truncates. Use `ORDER BY column DESC, id ASC LIMIT $1` in SQL; keep numeric conversion, NULL ordering and tie-breaking.');
198
206
  }
199
207
  }
200
208
  export { checkPostgresCall };
@@ -13,7 +13,9 @@ import { remainingSyntaxFailures } from '../../shared/analysis/valid-javascript.
13
13
  import { withCallNameInventory } from '../../shared/analysis/caller-name-inventory.js';
14
14
  import { withPrismaPackageInventory } from '../schema/prisma-owners.js';
15
15
  import { withManifestInventory } from '../../reliability/manifest-snapshot.js';
16
+ import { withNextEnvInventory } from '../../shared/analysis/next-env-config.js';
16
17
  import { terminalSafe } from '../../shared/system/terminal-safe.js';
18
+ import { noteSourcesRead } from '../../shared/analysis/scan-cache-sources.js';
17
19
  import { unscannedJavaScript } from '../analysis/unscanned-javascript.js';
18
20
  import nativeSyntax from './native-syntax.js';
19
21
  import * as nativeChecker from './native-checker.js';
@@ -125,7 +127,7 @@ function withoutRemovedOptions(options, { ModuleKind, ModuleResolutionKind }) {
125
127
  // one's
126
128
  // `analyzeFile` must load its rules lazily, after the native syntax is selected.
127
129
  function analyzeNative(options) {
128
- return withManifestInventory(() => withPrismaPackageInventory(() => withCallNameInventory(() => scanNative(options))));
130
+ return withManifestInventory(() => withNextEnvInventory(() => withPrismaPackageInventory(() => withCallNameInventory(() => scanNative(options)))));
129
131
  }
130
132
  function scanNative({ project, ownership, files = [], standaloneFiles = [], standaloneScope, standaloneExcluded, policy, fallback = false, allowNoSourceFiles = false, onlyFiles, analyzers, }) {
131
133
  let compiler;
@@ -207,6 +209,8 @@ function scanNative({ project, ownership, files = [], standaloneFiles = [], stan
207
209
  return;
208
210
  const program = api.createProgram(roots, { ...withoutRemovedOptions(options, binding), noEmit: true });
209
211
  try {
212
+ // The native compiler reads the disk itself, out of reach of the scan cache's read watch.
213
+ noteSourcesRead(program.getSourceFileNames());
210
214
  checkErrors(program.getProgramDiagnostics());
211
215
  // The native service accepts an array, saving a round-trip per input.
212
216
  const syntaxErrorsByFile = Map.groupBy(program.getSyntacticDiagnostics(inputs), (diagnostic) => canonical(diagnostic.fileName));