Skip to content

feat: [extensions] add error message instead of failing silently #403

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

Zamiell
Copy link
Contributor

@Zamiell Zamiell commented Jun 27, 2025

Related to #402 but does not close it.

Important

In extensions.ts, fix() now throws an error with a message if replaceImportPath() fails to change the import path, aiding debugging.

  • Behavior:
    • In extensions.ts, fix() in fixOrSuggest now throws an error if replaceImportPath() does not change the import path.
    • Error message suggests configuring the rule with an explicit extension if the autofixer fails.
  • Misc:
    • No other files or functions are affected by this change.

This description was created by Ellipsis for d587c0f. You can customize this summary. It will automatically update as commits are pushed.

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of missing file extensions in import paths to prevent silent failures and provide clearer error messages when the extension type cannot be determined automatically.
    • Enhanced error reporting to avoid applying ineffective automatic fixes when import paths cannot be resolved.

Copy link

changeset-bot bot commented Jun 27, 2025

⚠️ No Changeset found

Latest commit: 36eaa81

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented Jun 27, 2025

Walkthrough

A runtime check was added to the autofix function for adding missing file extensions in import paths. The function now verifies that the computed replacement import path differs from the original before applying the fix; if unchanged, it returns null to avoid silent no-op fixes. A new test case was added to confirm this behavior.

Changes

File(s) Change Summary
src/rules/extensions.ts Modified autofix logic to compute and compare new import paths, returning null if no change is detected.
test/rules/extensions.spec.ts Added test case verifying that no autofix is applied when the replacement import path is identical to original.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ESLintRule
    participant Fixer

    User->>ESLintRule: Triggers autofix for missing extension
    ESLintRule->>ESLintRule: Compute newImportPath
    ESLintRule->>ESLintRule: Compare newImportPath with original
    alt newImportPath is unchanged
        ESLintRule->>User: Return null (no fix applied)
    else newImportPath is different
        ESLintRule->>Fixer: Apply replacement with newImportPath
    end
Loading

Possibly related PRs

Suggested labels

enhancement

Poem

A rabbit hopped through code so neat,
Checking imports, swift on its feet.
No silent fixes, no hidden game—
Now errors speak their proper name.
Extensions found, or errors thrown,
The autofix is clearly shown!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/rules/extensions.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/lib/index.js' imported from /eslint.config.js
at finalizeResolution (node:internal/modules/esm/resolve:274:11)
at moduleResolve (node:internal/modules/esm/resolve:859:10)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)

test/rules/extensions.spec.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/lib/index.js' imported from /eslint.config.js
at finalizeResolution (node:internal/modules/esm/resolve:274:11)
at moduleResolve (node:internal/modules/esm/resolve:859:10)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d587c0f and 9369a10.

📒 Files selected for processing (2)
  • src/rules/extensions.ts (1 hunks)
  • test/rules/extensions.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/rules/extensions.ts
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#362
File: src/utils/create-rule.ts:0-0
Timestamp: 2025-05-31T03:10:38.972Z
Learning: When `rewriteRelativeImportExtensions` is enabled in TypeScript configuration, using `.ts` extensions in import paths is correct and necessary for Node.js ESM compatibility. TypeScript will rewrite these to `.js` during compilation.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#378
File: src/rules/imports-first.ts:10-19
Timestamp: 2025-06-08T12:09:38.535Z
Learning: The current implementation in eslint-plugin-import-x uses the correct ESLint core DeprecatedInfo structure: deprecatedSince field and replacedBy array with objects containing rule properties that match the ExternalSpecifier type with name and url fields.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#378
File: src/rules/imports-first.ts:10-19
Timestamp: 2025-06-08T12:09:38.535Z
Learning: ESLint core ExternalSpecifier interface has optional name and url string properties. The current eslint-plugin-import-x implementation correctly uses this structure for the rule property within replacedBy arrays in DeprecatedInfo objects.
test/rules/extensions.spec.ts (6)
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#362
File: src/utils/create-rule.ts:0-0
Timestamp: 2025-05-31T03:10:38.972Z
Learning: When `rewriteRelativeImportExtensions` is enabled in TypeScript configuration, using `.ts` extensions in import paths is correct and necessary for Node.js ESM compatibility. TypeScript will rewrite these to `.js` during compilation.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#378
File: src/rules/imports-first.ts:10-19
Timestamp: 2025-06-08T12:09:38.535Z
Learning: ESLint core ExternalSpecifier interface has optional name and url string properties. The current eslint-plugin-import-x implementation correctly uses this structure for the rule property within replacedBy arrays in DeprecatedInfo objects.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#271
File: test/rules/no-unused-modules.spec.ts:1528-1532
Timestamp: 2025-03-30T09:06:59.006Z
Learning: The import from 'eslint8.56/use-at-your-own-risk' has incorrect TypeScript types but works correctly at runtime, which is properly handled with a `@ts-expect-error` comment.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#378
File: src/rules/imports-first.ts:10-19
Timestamp: 2025-06-08T12:09:38.535Z
Learning: The current implementation in eslint-plugin-import-x uses the correct ESLint core DeprecatedInfo structure: deprecatedSince field and replacedBy array with objects containing rule properties that match the ExternalSpecifier type with name and url fields.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#386
File: src/rules/prefer-namespace-import.ts:41-46
Timestamp: 2025-06-18T15:22:38.532Z
Learning: In eslint-plugin-import-x, JounQin prefers to throw on invalid rule options rather than handling them gracefully with try/catch blocks and reporting configuration errors.
Learnt from: JounQin
PR: un-ts/eslint-plugin-import-x#272
File: test/rules/no-unresolved.spec.ts:293-325
Timestamp: 2025-05-30T13:24:29.760Z
Learning: Node.js ES6 import statements do not support plain Windows absolute paths like `C:\path\to\file.js` because import specifiers are resolved as URLs, not plain file paths. Plain Windows absolute paths conflict with URL schemes and create ambiguity. For absolute imports on Windows, you must use `file://` URLs instead.
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: Lint and Test with Node.js 24 and ESLint 9 on windows-latest
  • GitHub Check: Lint and Test with Node.js 24 and ESLint 8.56 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 and ESLint 8 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 and ESLint 8.56 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 and ESLint 8 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 9 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 8 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 8.56 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 8.56 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 24 and ESLint 8.56 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 22 and ESLint 8 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 18 and ESLint 8.56 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 18 and ESLint 9 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 9 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 8 on ubuntu-latest
  • GitHub Check: Lint and Test with Node.js 22 and ESLint 8 on macos-latest
  • GitHub Check: Lint and Test with Node.js 22 and ESLint 8.56 on macos-latest
  • GitHub Check: Lint and Test with Node.js 18 and ESLint 8 on macos-latest
  • GitHub Check: Lint and Test with Node.js 20 and ESLint 8.56 on macos-latest
  • GitHub Check: Lint and Test with Node.js 18 and ESLint 8.56 on macos-latest
🔇 Additional comments (1)
test/rules/extensions.spec.ts (1)

253-264: LGTM! Test case properly validates the new autofix behavior.

This test case correctly verifies that the autofix function returns null when the computed fix would be ineffective, preventing no-op fixes for unresolved imports. The test name is descriptive, and the expectation of output: null aligns perfectly with the PR's objective of avoiding silent failures.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codesandbox-ci bot commented Jun 27, 2025

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Copy link

pkg-pr-new bot commented Jun 27, 2025

Open in StackBlitz

npm i https://pkg.pr.new/eslint-plugin-import-x@403

commit: 9369a10

Copy link

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to d587c0f in 1 minute and 13 seconds. Click for details.
  • Reviewed 26 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 1 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. src/rules/extensions.ts:378
  • Draft comment:
    Throwing an error in the fixer (when newImportPath === source.raw) can abruptly halt ESLint execution. Consider handling this case more gracefully (e.g. reporting a configuration error via context.report) instead of throwing an exception.
  • Reason this comment was not posted:
    Decided after close inspection that this draft comment was likely wrong and/or not actionable: usefulness confidence = 20% vs. threshold = 50% This is a tricky case. On one hand, throwing errors in fixers can be disruptive. However, this seems like a legitimate error case where the fixer cannot proceed - it's a configuration issue that needs user attention. Using context.report here wouldn't make sense because we're already inside a fix function that was called as part of handling a reported issue. The error message is also very helpful in explaining exactly what the user needs to do. I could be wrong about the impact of throwing errors in fixers - maybe it does cause more serious problems than I realize. Also, there might be a more graceful way to handle this that I'm not seeing. While throwing errors in fixers isn't ideal, in this case it's appropriate - this is a true error condition where the fixer cannot proceed, and the error message provides clear guidance on how to fix it. Using context.report wouldn't help since we're already in a fix function. The comment should be deleted. The current error-throwing approach is appropriate given the context, and the suggested alternative wouldn't work well in this situation.

Workflow ID: wflow_RJPh9kdQWje85H4s

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

Copy link
Member

@JounQin JounQin left a comment

Choose a reason for hiding this comment

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

Please add a failing test case as the first commit.

@Zamiell
Copy link
Contributor Author

Zamiell commented Jun 27, 2025

I spent some time today working on this, but got stuck.

  1. I changed it like you said:
              fix(fixer: TSESLint.RuleFixer) {
                const newImportPath = replaceImportPath(
                  source.raw,
                  fixedImportPath,
                )
                return source.raw === newImportPath
                  ? null // Surface that something has gone wrong with extension detection.
                  : fixer.replaceText(source, newImportPath)
              },

But now I am confused, because returning null does not actually surface any errors to the end-user, right? Which was the whole point of the PR.

  1. I tried to add a test:
    tInvalid({
      name: 'extensions should not autofix when the fix is identical',
      code: 'import foo from "./unresolved"',
      options: ['always', { fix: true }],
      errors: [
        {
          messageId: 'missing',
          data: { extension: 'js', importPath: './unresolved' },
        },
      ],
      output: null,
    }),

But this doesn't work, I'm not really sure why. (By "not work", I mean that it passes by default, but when I remove my new code, it still passes.) I'm not really sure how to test for a null output in an ESLint test.

@JounQin
Copy link
Member

JounQin commented Jun 28, 2025

So my guess could be wrong, I'll take deeper look ASAP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants