Skip to content

[eslint-miner] feat(eslint): add require-fetch-try-catch rule - #47763

Merged
pelikhan merged 2 commits into
mainfrom
eslint-miner/require-fetch-try-catch-969145961c8050ba
Jul 24, 2026
Merged

pelikhan merged 2 commits into
mainfrom
eslint-miner/require-fetch-try-catch-969145961c8050ba

Conversation

@github-actions

@github-actions github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

test

Generated by PR Description Updater for #47763 · sonnet46 · 39.6 AIC · ⌖ 4.46 AIC · ⊞ 4.8K · ◷

Adds a new ESLint rule that requires `await fetch(...)` calls in
actions/setup/js to be wrapped in try/catch.

The Fetch API throws TypeError on network failures (DNS errors,
connection refused, request aborted, etc.). Without a try/catch,
these failures produce an unhandled exception that crashes the
action with no useful diagnostic.

Evidence in actions/setup/js:
- artifact_client.cjs lines 217, 269, 319, 335 — four fetch calls
  outside try/catch that the new rule flags as warnings.

Rule details:
- Flags any `await fetch(...)` expression not inside a try block
- Provides a fix suggestion for ExpressionStatement context
- Ignores non-fetch awaits (axios, octokit, etc.)
- Registered as 'warn' in eslint.config.cjs

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@pelikhan
pelikhan marked this pull request as ready for review July 24, 2026 15:10
Copilot AI review requested due to automatic review settings July 24, 2026 15:10
@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor Author

🧠 Matt Pocock Skills Reviewer has completed the skills-based review. ✅

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Design Decision Gate 🏗️ completed the design decision gate check.

No ADR enforcement needed: PR #47763 does not have the 'implementation' label and has 0 new lines of code in business logic directories (threshold: 100).

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ PR Code Quality Reviewer completed the code quality review.

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Test Quality Sentinel completed test quality analysis.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an ESLint rule requiring direct await fetch(...) calls to be protected by try/catch.

Changes:

  • Implements and registers require-fetch-try-catch.
  • Adds CommonJS and ES module tests.
  • Enables the rule for setup JavaScript linting.
Show a summary per file
File Description
eslint-factory/src/rules/require-fetch-try-catch.ts Implements detection and suggestions.
eslint-factory/src/rules/require-fetch-try-catch.test.ts Tests valid and invalid cases.
eslint-factory/src/index.ts Registers the rule.
eslint-factory/eslint.config.cjs Enables the rule as a warning.

Review details

Tip

Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

  • Files reviewed: 4/4 changed files
  • Comments generated: 2
  • Review effort level: Medium


return {
AwaitExpression(node) {
if (!isAwaitFetchCall(node)) return;
return {
AwaitExpression(node) {
if (!isAwaitFetchCall(node)) return;
if (isInsideTryBlock(sourceCode, node)) return;

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The require-fetch-try-catch rule is well-structured and follows existing patterns in the codebase. The implementation correctly identifies await fetch(...) outside try blocks, provides fix suggestions for ExpressionStatement contexts only (appropriately skipping VariableDeclaration where the binding would escape the try scope), and reuses shared utilities (isInsideTryBlock, buildTryCatchSuggestion). Tests cover valid/invalid cases, both CJS and ESM, nested try blocks, and loops. No issues found.

🧵 Reviewed using Impeccable skills by Impeccable Skills Reviewer · sonnet46 · 15.9 AIC · ⌖ 4.48 AIC · ⊞ 5K

@github-actions github-actions Bot mentioned this pull request Jul 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor Author

🧪 Test Quality Sentinel Report

⚠️ Test Quality Score: 76/100 — Acceptable

Analyzed 7 test(s): 6 design, 1 implementation, 0 violation(s).

📊 Metrics (7 tests)
Metric Value
Analyzed 7 (Go: 0, JS: 7)
✅ Design 6 (85.7%)
⚠️ Implementation 1 (14.3%)
Edge/error coverage 4 (57.1%)
Duplicate clusters 1
Inflation NO (1.49:1)
🚨 Violations 0
Test File Classification Status
valid: await fetch inside try block (CommonJS) require-fetch-try-catch.test.ts:18 Design (3 valid patterns) ✅
valid: await fetch inside try block (ES module) require-fetch-try-catch.test.ts:28 Design (cross-module) ✅
valid: non-fetch await calls are not flagged require-fetch-try-catch.test.ts:35 Design (false positive prevention) ✅
invalid: await fetch outside try block (CommonJS) require-fetch-try-catch.test.ts:45 Design (error + suggestion verification) ✅
invalid: await fetch outside try block (ES module) require-fetch-try-catch.test.ts:68 Implementation (duplicate variant) ⚠️
valid: await fetch inside nested try block require-fetch-try-catch.test.ts:76 Design (nested scope edge case) ✅
invalid: await fetch in loop outside try block require-fetch-try-catch.test.ts:87 Design (loop edge case) ⚠️
⚠️ Flagged Tests (2)

Test 5: "invalid: await fetch outside try block (ES module)" (line 68) — Implementation test, duplicate pattern

This test largely duplicates Test 4 (CommonJS variant) with only module system differences. Test 5 has minimal assertions (1 pattern vs 3), reducing diagnostic value. Consider:

  • Parametrizing Tests 4 & 5 with shared test data
  • Consolidating into a single parameterized test with describe.each or similar vitest patterns
  • Or add more comprehensive ES-module-specific edge cases to justify separate test

Test 7: "invalid: await fetch in loop outside try block" (line 87) — Partial suggestion coverage

This test verifies the error is reported but doesn't fully validate the suggestion/fixer output (unlike Test 4). For consistency, either:

  • Verify the full suggestions array and output property like Test 4 does
  • Or explicitly document why loop cases don't generate suggestions (if by design)
  • Current assertion: errors: [{ messageId: "requireTryCatch" }] should include suggestion details

Verdict

✅ Passed. 14.3% implementation tests (threshold: 30%). No coding guideline violations detected. Design coverage is strong with good edge-case handling.

🧪 Test quality analysis by Test Quality Sentinel · haiku45 · 15.2 AIC · ⌖ 12 AIC · ⊞ 7.1K · ◷
Comment /review to run again

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Test Quality Sentinel: 76/100 Acceptable. 85.7% design tests (6 of 7), 14.3% implementation tests (1 of 7, threshold: 30%). Strong behavioral contract coverage with good edge cases. Minor issue: Test 5 duplicates Test 4 with minimal ESM-specific coverage; Test 7 lacks suggestion verification unlike Test 4. See detailed analysis in comment above.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Skills-Based Review 🧠

Applied /tdd and /codebase-design — commenting with minor improvement opportunities, no blocking issues.

📋 Key Themes & Highlights

Positive Highlights

  • ✅ Strong test coverage: 7 test cases across CJS/ESM, nested try, loop, and VariableDeclaration contexts
  • ✅ Clean reuse of shared try-catch-rule-utils helpers — consistent with existing rules
  • ✅ Fix suggestion produces idiomatic new Error(..., { cause: err }) — good error hygiene
  • ✅ PR description includes real evidence (4 violations in artifact_client.cjs) — very helpful context

Issues Found (non-blocking)

  1. False positive with imported fetch — callee.name === "fetch" matches any identifier named fetch, including import fetch from "node-fetch". Worth documenting or adding a test for this boundary.
  2. Missing member-fetch boundary test — await client.fetch(url) is correctly ignored, but no test asserts this. Easy to add.
  3. Empty urlText fallback — fetch() with no arguments results in an empty string in the diagnostic message; a clearer placeholder like /* no url */ would improve the developer experience.

🧠 Reviewed using Matt Pocock's skills by Matt Pocock Skills Reviewer · sonnet46 · 36.9 AIC · ⌖ 4.86 AIC · ⊞ 6.7K
Comment /matt to run again

if (node.type !== AST_NODE_TYPES.AwaitExpression) return false;
const argument = node.argument;
if (argument.type !== AST_NODE_TYPES.CallExpression) return false;
const callee = argument.callee;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/tdd] The identifier-only check callee.name === "fetch" will produce false positives when fetch is an imported alias (e.g., import fetch from 'node-fetch' or const fetch = require('cross-fetch')). A custom wrapper may already handle errors.

💡 Suggested test + fix direction

Add a valid test case documenting the current behaviour:

// imported fetch — currently flagged even if it wraps error handling
import fetch from 'node-fetch';
async function f() { const res = await fetch(url); }

If scope analysis is out of scope, document the known false-positive in the rule description so consumers can suppress it per file.

@copilot please address this.

if (!isAwaitFetchCall(node)) return;
if (isInsideTryBlock(sourceCode, node)) return;

const fetchCall = node.argument as TSESTree.CallExpression;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/tdd] No test covers fetch called as a method/member (obj.fetch(url)) — the rule correctly ignores this since it checks only for a bare fetch identifier, but a test makes the boundary explicit and prevents future regressions if the detection logic is ever expanded.

💡 Suggested valid test case
it("valid: member fetch is not flagged", () => {
  cjsRuleTester.run("require-fetch-try-catch", requireFetchTryCatchRule, {
    valid: [
      `async function f() { const res = await client.fetch(url); }`,
    ],
    invalid: [],
  });
});

@copilot please address this.

const stmt = findEnclosingStatement(sourceCode, node);

context.report({
node,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/codebase-design] urlText falls back to "" when fetchCall.arguments[0] is undefined, which silently produces the message Wrap \await fetch()` in try/catch. fetch()with no arguments is already aTypeError` at call time, but the empty string makes the diagnostic misleading for other zero-arg cases.

💡 Suggested improvement
const urlText = firstArg !== undefined ? sourceCode.getText(firstArg as TSESTree.Node) : "/* no url */";

Or short-circuit with return when there are no arguments, since fetch() with no args is invalid JS anyway and the rule cannot usefully wrap it.

@copilot please address this.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One non-blocking issue; logic is sound

The rule implementation is correct: properly handles deferred async boundaries, intentionally omits suggestions for (where wrapping would break subsequent uses of the declared variable — documented in the tests), and the overall pattern follows established conventions in the plugin.

One medium issue with the message formatting — see inline comment.

Other items considered and dropped
  • ** deprecation**: pattern is used identically across all existing rules in the codebase; not a regression introduced here.
  • VariableDeclaration gets no suggestion: explicitly intentional and documented in the test comments — wrapping only the declaration leaves subsequent uses of the variable outside the try block.
  • Aliased fetch / globalThis.fetch: caller-controlled indirection is out of scope for identifier-based rules; consistent with how all other rules in the plugin work.
  • fire-and-forget fetch: explicitly out of scope per the rule name and docs.

🔎 Code quality review by PR Code Quality Reviewer · sonnet46 · 47.3 AIC · ⌖ 4.64 AIC · ⊞ 5.7K
Comment /review to run again


const fetchCall = node.argument as TSESTree.CallExpression;
const firstArg = fetchCall.arguments[0];
const urlText = firstArg !== undefined ? sourceCode.getText(firstArg as TSESTree.Node) : "";

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Untruncated URL text injected verbatim into the lint message — a complex first argument (template literal, function call, chained expression) produces multi-line or extremely long diagnostic output that breaks IDE lint overlays and CI log readability.

💡 Suggested fix

Truncate urlText before embedding it in the message:

const MAX_URL_LEN = 60;
const rawUrlText =
  firstArg !== undefined ? sourceCode.getText(firstArg as TSESTree.Node) : "";
const urlText =
  rawUrlText.length > MAX_URL_LEN ? rawUrlText.slice(0, MAX_URL_LEN) + "..." : rawUrlText;

This prevents template literals like `${baseUrl}/api/endpoint` or function calls like buildUrl(config.host, path, query) from producing garbled or truncated IDE tooltip text.

@pelikhan

Copy link
Copy Markdown
Collaborator

@copilot run pr-finisher skill

- Add hasLocalBinding() check to skip locally-shadowed fetch identifiers
  (e.g. async function f(fetch) { await fetch(url); }) — mirrors the same
  guard in require-new-url-try-catch.ts
- Replace shared isInsideTryBlock with a local version that stops at any
  function boundary (FunctionDeclaration, FunctionExpression,
  ArrowFunctionExpression); the shared helper only crossed deferred
  callbacks so named/stored async functions inside an outer try block were
  incorrectly treated as protected
- Add tests: valid local-binding cases and invalid nested-function cases

Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>

Copilot AI commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

@copilot run pr-finisher skill

Both review threads addressed in commit fix(eslint): address review feedback on require-fetch-try-catch:

Thread 1 (line 43 — local binding): Added hasLocalBinding() inside create() (mirrors require-new-url-try-catch.ts lines 29–38/113–114). fetch identifiers with local definitions (parameters, imports, variables) are now skipped.

Thread 2 (line 44 — function boundary): Replaced the shared isInsideTryBlock with a local version that stops at any function boundary (FunctionDeclaration, FunctionExpression, ArrowFunctionExpression). The shared helper only crossed deferred callbacks, so a named/stored async function nested inside an outer try was incorrectly treated as protected. The local version is simpler and correct for await semantics: a protecting try/catch must be in the same async function body.

Three new test cases cover the boundary scenarios; two existing test groups cover the local-binding case. All 9 tests pass.

@pelikhan
pelikhan merged commit 355259b into main Jul 24, 2026
@pelikhan
pelikhan deleted the eslint-miner/require-fetch-try-catch-969145961c8050ba branch July 24, 2026 17:10
@github-actions

Copy link
Copy Markdown
Contributor Author

🎉 This pull request is included in a new release.

Release: v0.83.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants