loadwise 0.5.0 → 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 (132) hide show
  1. package/README.md +543 -628
  2. package/bin/loadwise.js +5 -1
  3. package/lib/accessibility/frontend-detect.js +2 -1
  4. package/lib/accessibility/rule-ids.js +12 -9
  5. package/lib/accessibility/template-attributes.js +4 -2
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +16 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +20 -3
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +12 -19
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
@@ -0,0 +1,56 @@
1
+ import { ts } from './compiler.js';
2
+ const RULE_ID = 'llm-call-without-max-tokens';
3
+ // The OpenAI resources whose create() has an optional output cap. Anthropic's messages.create is
4
+ // absent on purpose: its types require max_tokens, so the call cannot omit it.
5
+ const RESOURCE_TYPES = ['Completions', 'Responses'];
6
+ const OUTPUT_CAP_KEYS = new Set(['max_tokens', 'max_completion_tokens', 'max_output_tokens']);
7
+ function isOpenAiCreate(call, context) {
8
+ const callee = call.expression;
9
+ if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'create')
10
+ return false;
11
+ const resource = callee.expression;
12
+ if (!ts.isPropertyAccessExpression(resource) || !['completions', 'responses'].includes(resource.name.text))
13
+ return false;
14
+ // The legacy `client.completions` resource takes only `max_tokens`, so the chat remedy would not apply.
15
+ if (resource.name.text === 'completions' && !isChatResource(resource.expression))
16
+ return false;
17
+ return context.isPackageType(resource, ['openai'], RESOURCE_TYPES);
18
+ }
19
+ function isChatResource(receiver) {
20
+ return ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'chat';
21
+ }
22
+ // `max_tokens: undefined` is dropped on serialization, so it sets no limit.
23
+ function isUnsetValue(property) {
24
+ if (!ts.isPropertyAssignment(property))
25
+ return false;
26
+ const value = ts.skipOuterExpressions(property.initializer);
27
+ return (value.kind === ts.SyntaxKind.NullKeyword ||
28
+ ts.isVoidExpression(value) ||
29
+ (ts.isIdentifier(value) && value.text === 'undefined'));
30
+ }
31
+ // True when the key set is fully known and holds no output cap. A spread or computed key may carry
32
+ // the cap from elsewhere, so those calls stay quiet.
33
+ function lacksOutputCap(options) {
34
+ for (const property of options.properties) {
35
+ if (ts.isSpreadAssignment(property))
36
+ return false;
37
+ const name = property.name;
38
+ if (!name)
39
+ return false;
40
+ if (ts.isComputedPropertyName(name))
41
+ return false;
42
+ if (OUTPUT_CAP_KEYS.has(name.text) && !isUnsetValue(property))
43
+ return false;
44
+ }
45
+ return true;
46
+ }
47
+ function check(call, context) {
48
+ const [firstArgument] = call.arguments;
49
+ const options = firstArgument && ts.skipOuterExpressions(firstArgument);
50
+ if (!options || !ts.isObjectLiteralExpression(options) || !lacksOutputCap(options))
51
+ return;
52
+ if (!isOpenAiCreate(call, context))
53
+ return;
54
+ context.report(call, RULE_ID, 'This OpenAI call sets no output token limit, so a long or runaway completion is billed in full and holds the request open. Set `max_completion_tokens` (chat completions) or `max_output_tokens` (responses) to a limit the feature can justify.');
55
+ }
56
+ export { check };
@@ -6,13 +6,16 @@ import { selectNativeSyntax } from './compiler.js';
6
6
  import { requireNative, executable } from './native-runtime.js';
7
7
  import { withWorkspaceSources } from './native-workspaces.js';
8
8
  import { recordSkippedFile } from './scan-outcome.js';
9
- import { noteUnscannedJavaScript } from './unscanned-javascript.js';
9
+ import { unscannedJavaScript } from './unscanned-javascript.js';
10
10
  import nativeSyntax from './native-syntax.js';
11
11
  import * as nativeChecker from './native-checker.js';
12
12
  import * as performanceAnalyze from './analyze.js';
13
13
  import { sourcePillarOf } from '../shared/rule-registry.js';
14
14
  import { repositoryRoot, standaloneFindings } from '../reliability/standalone-sources.js';
15
15
  import * as schemaTooling from './schema-tooling.js';
16
+ // What a caller passes: one config or several, or explicit files; `onlyFiles` keeps just the
17
+ // changed ones.
18
+ const noInputsCode = 18003;
16
19
  function openCompiler() {
17
20
  const [major, minor] = process.versions.node.split('.').map(Number);
18
21
  if (major < 22 || (major === 22 && minor < 13))
@@ -110,7 +113,7 @@ function withoutRemovedOptions(options, { ModuleKind, ModuleResolutionKind }) {
110
113
  // imports still resolve through the config. `analyzers` defaults to the performance rules; each
111
114
  // one's
112
115
  // `analyzeFile` must load its rules lazily, after the native syntax is selected.
113
- function analyzeNative({ project, files = [], policy, fallback = false, onlyFiles, analyzers, }) {
116
+ function analyzeNative({ project, files = [], standaloneFiles = [], policy, fallback = false, onlyFiles, analyzers, }) {
114
117
  let compiler;
115
118
  try {
116
119
  compiler = openCompiler();
@@ -127,7 +130,7 @@ function analyzeNative({ project, files = [], policy, fallback = false, onlyFile
127
130
  let selectedAnalyzers = [];
128
131
  const visitedConfigs = new Set();
129
132
  // Folders scanned with a config that leaves JavaScript out.
130
- const scopesWithoutJs = new Set();
133
+ const scopesWithoutJs = new Map();
131
134
  // Folders whose files no program may have analyzed, listed once the programs are done.
132
135
  const standaloneRoots = new Set();
133
136
  const scanned = new Set();
@@ -244,20 +247,34 @@ function analyzeNative({ project, files = [], policy, fallback = false, onlyFile
244
247
  return fileFindings;
245
248
  }
246
249
  // Collects every config with source inputs, in scan order, after validating its options.
247
- function visitConfig(filename, projects, scope, companion) {
250
+ function visitConfig(filename, projects, scope, companion, explicit) {
248
251
  // realpath resolves the reference even before the native API initializes.
249
252
  const key = fs.realpathSync.native(filename);
250
- if (visitedConfigs.has(key))
253
+ // A companion already visited as a reference still sets its folder's JavaScript boundary.
254
+ if (visitedConfigs.has(key)) {
255
+ if (companion)
256
+ scopesWithoutJs.delete(scope ?? path.dirname(filename));
251
257
  return;
258
+ }
252
259
  visitedConfigs.add(key);
253
260
  const parsed = api.parseConfigFile(filename);
254
- checkConfig(parsed.errors?.filter((diagnostic) => !isIgnorableUnknownOption(diagnostic)));
261
+ // `checkJs` turns JavaScript on when `allowJs` is unset. A discovered config that lists no inputs because it
262
+ // leaves the JavaScript out still has that JavaScript checked, so TS18003 waits for the final source count.
263
+ const allowsJs = parsed.options.allowJs ?? parsed.options.checkJs;
264
+ checkConfig(parsed.errors?.filter((diagnostic) => !isIgnorableUnknownOption(diagnostic) && !(diagnostic.code === noInputsCode && !allowsJs && !explicit)));
255
265
  const options = withWorkspaceSources(withoutRemovedOptions(withoutBaseUrl(withoutEmitOptions(parsed.options)), binding), path.dirname(filename));
256
266
  for (const reference of parsed.projectReferences ?? []) {
257
- visitConfig(resolveConfig(reference.path), projects, scope);
267
+ visitConfig(resolveConfig(reference.path), projects, scope, false, explicit);
268
+ }
269
+ // The companion jsconfig names the JavaScript the project checks, so its folder needs no fallback.
270
+ if (companion)
271
+ scopesWithoutJs.delete(scope ?? path.dirname(filename));
272
+ else if (!allowsJs) {
273
+ const jsScope = scope ?? path.dirname(filename);
274
+ const leftOut = scopesWithoutJs.get(jsScope) ?? { configs: [], checksLeftOut: !explicit };
275
+ leftOut.configs.push(filename);
276
+ scopesWithoutJs.set(jsScope, leftOut);
258
277
  }
259
- if (!parsed.options.allowJs && !onlyFiles)
260
- scopesWithoutJs.add(scope ?? path.dirname(filename));
261
278
  standaloneRoots.add(scope ?? repositoryRoot(path.dirname(filename)));
262
279
  const rootFiles = onlyFiles ? parsed.fileNames.filter(onlyFiles) : parsed.fileNames;
263
280
  if (!rootFiles.some((filename) => isSourceInput(filename) && isInScope(scope, filename)))
@@ -282,6 +299,17 @@ function analyzeNative({ project, files = [], policy, fallback = false, onlyFile
282
299
  }
283
300
  try {
284
301
  const projects = [];
302
+ // Explicit files, and JavaScript a config without `allowJs` leaves out, have no config of their own.
303
+ const { ScriptTarget } = requireNative('typescript/ast');
304
+ const standaloneOptions = {
305
+ target: ScriptTarget.ES2022,
306
+ module: binding.ModuleKind.NodeNext,
307
+ allowJs: true,
308
+ checkJs: false,
309
+ skipLibCheck: true,
310
+ jsx: binding.JsxEmit.Preserve,
311
+ ...(policy && { strictNullChecks: true }),
312
+ };
285
313
  if (files.length) {
286
314
  const roots = files.map((filename) => {
287
315
  if (!isSourceInput(filename) || !fs.statSync(filename, { throwIfNoEntry: false })?.isFile()) {
@@ -289,29 +317,22 @@ function analyzeNative({ project, files = [], policy, fallback = false, onlyFile
289
317
  }
290
318
  return path.resolve(filename);
291
319
  });
292
- const { ScriptTarget } = requireNative('typescript/ast');
293
- projects.push([
294
- roots,
295
- {
296
- target: ScriptTarget.ES2022,
297
- module: binding.ModuleKind.NodeNext,
298
- allowJs: true,
299
- checkJs: false,
300
- skipLibCheck: true,
301
- jsx: binding.JsxEmit.Preserve,
302
- ...(policy && { strictNullChecks: true }),
303
- },
304
- () => true,
305
- ]);
320
+ projects.push([roots, standaloneOptions, () => true]);
306
321
  }
307
322
  else {
308
- for (const { config, scope, companion } of scanEntries(project)) {
309
- visitConfig(config, projects, scope, companion);
323
+ for (const { config, scope, companion, explicit } of scanEntries(project)) {
324
+ visitConfig(config, projects, scope, companion, explicit);
310
325
  }
311
326
  }
312
327
  selectSyntax();
313
328
  for (const [roots, options, analyzes] of projects)
314
329
  scan(roots, options, analyzes);
330
+ // The native API starts with the first program, so a scan of only configless sources has nothing to look up.
331
+ const isScanned = (filename) => scanned.size > 0 && scanned.has(canonical(filename));
332
+ const leftOut = unscannedJavaScript(scopesWithoutJs, isScanned, onlyFiles);
333
+ const configless = standaloneFiles.filter((filename) => !isScanned(filename) && (!onlyFiles || onlyFiles(filename)));
334
+ scan([...leftOut.files, ...configless], standaloneOptions, () => true);
335
+ leftOut.note();
315
336
  if (!scanned.size && !onlyFiles && !skippedFiles.length)
316
337
  throw new Error('No JavaScript or TypeScript source files to check.');
317
338
  if (!files.length && !onlyFiles && selectedAnalyzers.some((analyzer) => analyzer.pillar === 'reliability')) {
@@ -323,7 +344,6 @@ function analyzeNative({ project, files = [], policy, fallback = false, onlyFile
323
344
  mergeFinding(findings, `${canonical(file)}\0${finding.line}\0${finding.column}\0${finding.ruleId}\0${finding.message}`, finding);
324
345
  }
325
346
  }
326
- noteUnscannedJavaScript([...scopesWithoutJs], (filename) => scanned.has(canonical(filename)));
327
347
  return {
328
348
  scannedFiles: scanned.size,
329
349
  findings: [...findings.values()].sort(compareFindings),
@@ -48,6 +48,21 @@ export async function resolveAstGrepBinary() {
48
48
  throw error;
49
49
  }
50
50
  }
51
+ export async function diskCasedPath(input) {
52
+ const { root } = path.parse(input);
53
+ let current = root;
54
+ for (const segment of input.slice(root.length).split(path.sep).filter(Boolean)) {
55
+ const candidate = path.join(current, segment);
56
+ // A symlink's target basename is not an entry of its parent directory, so the given name stays.
57
+ if ((await fs.promises.lstat(candidate)).isSymbolicLink()) {
58
+ current = candidate;
59
+ continue;
60
+ }
61
+ const actualName = path.basename(await realpathNative(candidate));
62
+ current = path.join(current, actualName.toLowerCase() === segment.toLowerCase() ? actualName : segment);
63
+ }
64
+ return current;
65
+ }
51
66
  async function resolveInputs(paths) {
52
67
  const inputs = new Set();
53
68
  const explicitFiles = new Set();
@@ -63,7 +78,13 @@ async function resolveInputs(paths) {
63
78
  if (!stat.isDirectory() && !(stat.isFile() && extensions.has(path.extname(input).toLowerCase()))) {
64
79
  throw new Error('Expected a directory or a .py, .go, .java, .cs or .rs file: ' + input);
65
80
  }
66
- if (process.platform === 'win32') {
81
+ if (process.platform === 'darwin') {
82
+ // The default macOS volume ignores case, so a differently cased spelling of the same file
83
+ // must not be scanned twice. Every component takes its on-disk case, so a directory input and
84
+ // a file inside it share one spelling; symlinked components keep the name they were given.
85
+ input = await diskCasedPath(input);
86
+ }
87
+ else if (process.platform === 'win32') {
67
88
  // Preserve symlinks and distinct entries in case-sensitive directories.
68
89
  const actual = await realpathNative(input);
69
90
  if (actual.toLowerCase() === input.toLowerCase())
@@ -7,6 +7,10 @@ const drivers = new Map([
7
7
  ['@prisma/client', { member: 'PrismaClient', declarations: ['@prisma/client', '.prisma/client'] }],
8
8
  ['redis', { member: 'createClient', declarations: ['redis', '@redis/client'] }],
9
9
  ['@redis/client', { member: 'createClient', declarations: ['@redis/client'] }],
10
+ ['@aws-sdk/client-s3', { member: 'S3Client', declarations: ['@aws-sdk/client-s3'] }],
11
+ ['openai', { member: 'OpenAI', declarations: ['openai'], defaultExport: true }],
12
+ ['@anthropic-ai/sdk', { member: 'Anthropic', declarations: ['@anthropic-ai/sdk'], defaultExport: true }],
13
+ ['stripe', { member: 'Stripe', declarations: ['stripe'], defaultExport: true }],
10
14
  ]);
11
15
  const httpModules = new Set(['http', 'https', 'node:http', 'node:https']);
12
16
  const routeMethods = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all']);
@@ -17,6 +21,30 @@ const cachingOperators = () => [
17
21
  ts.SyntaxKind.QuestionQuestionToken,
18
22
  ts.SyntaxKind.BarBarToken,
19
23
  ];
24
+ function indexImports(file) {
25
+ const bindings = new Map();
26
+ for (const statement of file.statements) {
27
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier))
28
+ continue;
29
+ const moduleName = statement.moduleSpecifier.text;
30
+ if (!drivers.has(moduleName) && !httpModules.has(moduleName))
31
+ continue;
32
+ const clause = statement.importClause;
33
+ if (!clause || clause.isTypeOnly)
34
+ continue;
35
+ if (clause.name)
36
+ bindings.set(clause.name.text, { moduleName, declaration: clause });
37
+ const names = clause.namedBindings;
38
+ if (!names)
39
+ continue;
40
+ if (ts.isNamespaceImport(names)) {
41
+ bindings.set(names.name.text, { moduleName, declaration: names });
42
+ continue;
43
+ }
44
+ registerNamedImports(names, bindings, moduleName);
45
+ }
46
+ return bindings;
47
+ }
20
48
  // An identifier in a large project rarely names a driver. Index import spellings once,
21
49
  // then ask the checker about scope only for candidates with a matching local name.
22
50
  function importedMember(target, checker) {
@@ -27,31 +55,17 @@ function importedMember(target, checker) {
27
55
  const file = local.getSourceFile();
28
56
  let bindings = importsByFile.get(file);
29
57
  if (!bindings) {
30
- bindings = new Map();
31
- for (const statement of file.statements) {
32
- if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier))
33
- continue;
34
- const moduleName = statement.moduleSpecifier.text;
35
- if (!drivers.has(moduleName) && !httpModules.has(moduleName))
36
- continue;
37
- const clause = statement.importClause;
38
- if (!clause || clause.isTypeOnly)
39
- continue;
40
- if (clause.name)
41
- bindings.set(clause.name.text, { moduleName, declaration: clause });
42
- const names = clause.namedBindings;
43
- if (!names)
44
- continue;
45
- if (ts.isNamespaceImport(names)) {
46
- bindings.set(names.name.text, { moduleName, declaration: names });
47
- continue;
48
- }
49
- registerNamedImports(names, bindings, moduleName);
50
- }
58
+ bindings = indexImports(file);
51
59
  importsByFile.set(file, bindings);
52
60
  }
53
61
  const binding = bindings.get(local.text);
54
- if (!binding || qualified === Boolean(binding.member))
62
+ if (!binding)
63
+ return;
64
+ // A bare default import names the class itself, as in `new OpenAI()`.
65
+ const bareDefault = !qualified &&
66
+ (ts.isImportClause(binding.declaration) || ts.isImportSpecifier(binding.declaration)) &&
67
+ drivers.get(binding.moduleName)?.defaultExport;
68
+ if (qualified === Boolean(binding.member) && !bareDefault)
55
69
  return;
56
70
  if (!checker.getSymbolAtLocation(local)?.declarations?.includes(binding.declaration))
57
71
  return;
@@ -190,7 +204,8 @@ function checkPoolCreation(node, context) {
190
204
  }
191
205
  const imported = importedMember(target, context.checker);
192
206
  const driver = imported && drivers.get(imported.moduleName);
193
- if (!driver || imported.member !== driver.member || constructing === (driver.member === 'createClient'))
207
+ const isDriverMember = imported?.member === driver?.member || (!imported?.member && driver?.defaultExport);
208
+ if (!driver || !isDriverMember || constructing === (driver.member === 'createClient'))
194
209
  return;
195
210
  const owner = findRepeatOwner(node, context.checker) || requestHandlerOwner(node, context);
196
211
  if (!owner || cachedInitialization(node, owner, context.checker) || !verifiedDriver(target, driver, context.checker))
@@ -12,12 +12,13 @@ import { collectUninstalledDependencies, collectUnresolvedPackages, formatMissin
12
12
  import { compareFindings, isInScope, isSourceInput, mergeFinding, scanEntries, relativeToWorkingDirectory, resolveConfig, } from './source-inputs.js';
13
13
  import { recordSkippedFile } from './scan-outcome.js';
14
14
  import { missingPackageBase, workspacePackagesAround, workspaceSourceEntry } from '../shared/workspaces.js';
15
- import { noteUnscannedJavaScript } from './unscanned-javascript.js';
15
+ import { unscannedJavaScript } from './unscanned-javascript.js';
16
16
  import { fileURLToPath } from 'node:url';
17
17
  const compilerLibDirectory = path.dirname(fileURLToPath(import.meta.resolve('typescript')));
18
18
  const bundledLibPattern = /^lib(?:\.[\w.-]+)?\.d\.ts$/;
19
19
  const docMode = ts.JSDocParsingMode.ParseForTypeErrors;
20
20
  const canonicalFileName = ts.createCompilerHost({}).getCanonicalFileName;
21
+ const noInputsCode = 18003;
21
22
  // Limit filesystem probe reuse to a single one-shot run. Watch uses TypeScript's live host.
22
23
  function cachePathTest(test) {
23
24
  const results = new Map();
@@ -282,13 +283,13 @@ function standaloneReliabilityFindings(roots, scanned, analyzers) {
282
283
  }
283
284
  // `project` is one config or an array of them. `onlyFiles` limits the roots of each config to the changed files;
284
285
  // imports still resolve through the config.
285
- function analyzeSources({ project, files, policy, onlyFiles, analyzers, preRead }) {
286
+ function analyzeSources({ project, files, standaloneFiles = [], policy, onlyFiles, analyzers, preRead, }) {
286
287
  const findings = [];
287
288
  const scanned = new Set();
288
289
  const configs = new Set();
289
290
  const notedBases = new Set();
290
291
  // Folders scanned with a config that leaves JavaScript out.
291
- const scopesWithoutJs = new Set();
292
+ const scopesWithoutJs = new Map();
292
293
  // Folders whose files no program may have analyzed, listed once the programs are done.
293
294
  const standaloneRoots = new Set();
294
295
  const referenceFindings = new Map();
@@ -344,10 +345,14 @@ function analyzeSources({ project, files, policy, onlyFiles, analyzers, preRead
344
345
  findings.push(finding);
345
346
  }
346
347
  }
347
- function visitConfig(filename, scope, companion) {
348
+ function visitConfig(filename, scope, companion, explicit) {
348
349
  const canonical = fs.realpathSync(filename);
349
- if (configs.has(canonical))
350
+ // A companion already visited as a reference still sets its folder's JavaScript boundary.
351
+ if (configs.has(canonical)) {
352
+ if (companion)
353
+ scopesWithoutJs.delete(scope ?? path.dirname(filename));
350
354
  return;
355
+ }
351
356
  configs.add(canonical);
352
357
  const parsed = ts.getParsedCommandLineOfConfigFile(filename, {}, {
353
358
  ...ts.sys,
@@ -359,7 +364,10 @@ function analyzeSources({ project, files, policy, onlyFiles, analyzers, preRead
359
364
  if (!parsed)
360
365
  throw new Error('Unable to read project: ' + filename);
361
366
  const missingBases = uninstalledBaseConfigs(parsed);
362
- const configErrors = parsed.errors.filter((diagnostic) => !missingBases.includes(diagnostic));
367
+ // `checkJs` turns JavaScript on when `allowJs` is unset. A discovered config that lists no inputs because it
368
+ // leaves the JavaScript out still has that JavaScript checked, so TS18003 waits for the final source count.
369
+ const allowsJs = parsed.options.allowJs ?? parsed.options.checkJs;
370
+ const configErrors = parsed.errors.filter((diagnostic) => !missingBases.includes(diagnostic) && !(diagnostic.code === noInputsCode && !allowsJs && !explicit));
363
371
  if (configErrors.length)
364
372
  throw new Error(configErrors.map(diagnosticText).join('\n'));
365
373
  for (const diagnostic of missingBases) {
@@ -375,15 +383,32 @@ function analyzeSources({ project, files, policy, onlyFiles, analyzers, preRead
375
383
  sharedLibs ??= createSharedLibs();
376
384
  }
377
385
  for (const reference of parsed.projectReferences ?? []) {
378
- visitConfig(resolveConfig(ts.resolveProjectReferencePath(reference)), scope);
386
+ visitConfig(resolveConfig(ts.resolveProjectReferencePath(reference)), scope, false, explicit);
387
+ }
388
+ // The companion jsconfig names the JavaScript the project checks, so its folder needs no fallback.
389
+ if (companion)
390
+ scopesWithoutJs.delete(scope ?? path.dirname(filename));
391
+ else if (!allowsJs) {
392
+ const jsScope = scope ?? path.dirname(filename);
393
+ const leftOut = scopesWithoutJs.get(jsScope) ?? { configs: [], checksLeftOut: !explicit };
394
+ leftOut.configs.push(filename);
395
+ scopesWithoutJs.set(jsScope, leftOut);
379
396
  }
380
- if (!parsed.options.allowJs && !onlyFiles)
381
- scopesWithoutJs.add(scope ?? path.dirname(filename));
382
397
  standaloneRoots.add(scope ?? repositoryRoot(path.dirname(filename)));
383
398
  // The companion jsconfig only adds what the tsconfig left out.
384
399
  const isNew = (filename) => !companion || !scanned.has(canonicalFileName(path.resolve(filename)));
385
400
  scan(onlyFiles ? parsed.fileNames.filter(onlyFiles) : parsed.fileNames, parsed.options, (filename) => isInScope(scope, filename) && isNew(filename));
386
401
  }
402
+ // Explicit files, and JavaScript a config without `allowJs` leaves out, have no config of their own.
403
+ const standaloneOptions = {
404
+ target: ts.ScriptTarget.ES2022,
405
+ module: ts.ModuleKind.NodeNext,
406
+ allowJs: true,
407
+ checkJs: false,
408
+ skipLibCheck: true,
409
+ jsx: ts.JsxEmit.Preserve,
410
+ ...(policy && { strictNullChecks: true }),
411
+ };
387
412
  if (files.length) {
388
413
  const paths = files.map((filename) => {
389
414
  if (!ts.sys.fileExists(filename) || !isSourceInput(filename)) {
@@ -391,23 +416,19 @@ function analyzeSources({ project, files, policy, onlyFiles, analyzers, preRead
391
416
  }
392
417
  return path.resolve(filename);
393
418
  });
394
- scan(paths, {
395
- target: ts.ScriptTarget.ES2022,
396
- module: ts.ModuleKind.NodeNext,
397
- allowJs: true,
398
- checkJs: false,
399
- skipLibCheck: true,
400
- jsx: ts.JsxEmit.Preserve,
401
- ...(policy && { strictNullChecks: true }),
402
- });
419
+ scan(paths, standaloneOptions);
403
420
  }
404
421
  else {
405
- for (const { config, scope, companion } of entries)
406
- visitConfig(config, scope, companion);
422
+ for (const { config, scope, companion, explicit } of entries)
423
+ visitConfig(config, scope, companion, explicit);
424
+ const isScanned = (filename) => scanned.has(canonicalFileName(filename));
425
+ const leftOut = unscannedJavaScript(scopesWithoutJs, isScanned, onlyFiles);
426
+ const configless = standaloneFiles.filter((filename) => !isScanned(filename) && (!onlyFiles || onlyFiles(filename)));
427
+ scan([...leftOut.files, ...configless], standaloneOptions);
428
+ leftOut.note();
407
429
  }
408
430
  if (!scanned.size && !onlyFiles && !skippedFiles.length)
409
431
  throw new Error('No JavaScript or TypeScript source files to check.');
410
- noteUnscannedJavaScript([...scopesWithoutJs], (filename) => scanned.has(canonicalFileName(filename)));
411
432
  for (const packageName of unresolvedPackages)
412
433
  console.error(formatMissingPackagesNote(packageName));
413
434
  const uninstalled = new Set();