Skip to content
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

fix: support resolve from scoped package parent node_modules #36

Merged
merged 1 commit into from
Jan 3, 2025

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Jan 3, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new ImportResolveError class for more detailed import resolution error handling
    • Enhanced module resolution process to check parent node_modules directories
  • Bug Fixes

    • Improved error reporting for import resolution failures
  • Tests

    • Added test cases for ImportResolveError and expanded module resolution testing
  • Documentation

    • Improved error messaging for import-related issues

Copy link

vercel bot commented Jan 3, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
egg-utils ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 3, 2025 5:15am

Copy link

coderabbitai bot commented Jan 3, 2025

Walkthrough

A new error handling mechanism for import resolution has been introduced. The changes include creating an ImportResolveError class to provide detailed error information during module imports. The implementation enhances module resolution by adding support for finding modules in parent node_modules directories and improving error reporting. The changes span multiple files to integrate this new error handling approach, including updates to the main import logic, error definitions, and test cases.

Changes

File Change Summary
src/error/ImportResolveError.ts Added new ImportResolveError class extending Error with properties for filepath and attempted paths
src/error/index.ts Re-exported ImportResolveError entities for centralized access
src/import.ts Updated import resolution logic to use new ImportResolveError, added checks for parent node_modules directories
src/index.ts Added export for error-related entities
test/import.test.ts Added test cases for ImportResolveError and expanded module resolution tests

Sequence Diagram

sequenceDiagram
    participant Caller
    participant ImportResolver
    participant ModuleResolver
    participant ErrorHandler

    Caller->>ImportResolver: Request module import
    ImportResolver->>ModuleResolver: Attempt to resolve path
    alt Path resolution successful
        ModuleResolver-->>ImportResolver: Return resolved path
        ImportResolver-->>Caller: Return imported module
    else Path resolution fails
        ModuleResolver->>ErrorHandler: Create ImportResolveError
        ErrorHandler-->>ImportResolver: Throw detailed error
        ImportResolver->>Caller: Throw ImportResolveError
    end
Loading

Poem

🐰 In the realm of imports, a new error takes flight,
Resolving paths with precision and might.
From modules near and modules far,
Our ImportResolveError shines like a star!
Debugging made clear, no path left behind. 🔍


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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

pkg-pr-new bot commented Jan 3, 2025

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/utils/@eggjs/utils@36

commit: f8f50ab

Copy link

codecov bot commented Jan 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 88.25%. Comparing base (7d3cda5) to head (f8f50ab).
Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master      #36      +/-   ##
==========================================
+ Coverage   87.50%   88.25%   +0.75%     
==========================================
  Files           6        8       +2     
  Lines         696      741      +45     
  Branches      120      130      +10     
==========================================
+ Hits          609      654      +45     
  Misses         87       87              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/import.ts (2)

208-239: Consider deeper or repeated parent traversal.

Currently, the code checks two levels of parent node_modules directories for scoped and non-scoped packages. If a library or framework requires deeper nesting, a loop might be needed. Otherwise, this approach is sufficient for typical use cases.


249-255: Use consistent error messages for better user experience.

The test validates error messages against /Cannot find package/. This depends on the underlying system error text from import.meta.resolve. To avoid fragile tests in future Node versions, consider providing a clearer, custom prefix or clarifying text in the final error message instead of relying on the underlying message alone.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7d3cda5 and f8f50ab.

⛔ Files ignored due to path filters (1)
  • test/fixtures/cjs/node_modules/@foo/bar/index.js is excluded by !**/node_modules/**
📒 Files selected for processing (5)
  • src/error/ImportResolveError.ts (1 hunks)
  • src/error/index.ts (1 hunks)
  • src/import.ts (3 hunks)
  • src/index.ts (1 hunks)
  • test/import.test.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/error/index.ts
🔇 Additional comments (6)
src/error/ImportResolveError.ts (2)

1-3: Robust custom error implementation.

This class definition is well thought out, with typed fields for filepath and paths, ensuring that relevant context is captured whenever an import resolve error occurs.


5-7: Verify Node.js compatibility for the cause option.

Passing the original error as { cause: error } is a good approach for debugging, but be aware that this feature was introduced in Node.js 16.9.0. If this library must support earlier Node versions, consider a fallback strategy.

✅ Verification successful

Based on the shell script results, I can see that the package.json specifies Node.js version requirement as:

"engines": {
  "node": ">=18.19.0"
}

The cause option in Error constructor is fully compatible with the codebase's Node.js requirements.

The Error constructor's cause option was introduced in Node.js 16.9.0, and this codebase requires Node.js 18.19.0 or higher, which means the feature is fully supported in all supported Node.js versions for this library. No fallback strategy is needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for minimum required Node version or engine constraints in the repo.
rg "engines"
rg "node" -A 5

Length of output: 27446

src/index.ts (1)

12-12: Good re-export for consolidated error handling.

Re-exporting artifacts from ./error/index.js is a convenient way to maintain a flat API surface, especially for consumers who only want to import from src/index.ts.

test/import.test.ts (3)

3-3: Clear usage of ImportResolveError.

Adding ImportResolveError to the test scope demonstrates robust coverage for the new error handling logic. Good job integrating it into existing tests.


40-48: Sufficient verification of parent node_modules resolution.

This test confirms the new fallback logic for searching parent node_modules. The approach is straightforward and ensures that resolution logic meets user expectations.


50-63: Avoid matching system error messages to ensure stable tests.

Matching err.message with /Cannot find package/ could break if Node error strings change. For consistent test outcomes, consider including a stable prefix in your thrown error message (e.g., "ImportResolveError: Cannot find package").

@fengmk2 fengmk2 merged commit 7c9cc42 into master Jan 3, 2025
26 checks passed
@fengmk2 fengmk2 deleted the fix-tsconfig-paths-register branch January 3, 2025 05:43
fengmk2 pushed a commit that referenced this pull request Jan 3, 2025
[skip ci]

## [4.2.3](v4.2.2...v4.2.3) (2025-01-03)

### Bug Fixes

* support resolve from scoped package parent node_modules ([#36](#36)) ([7c9cc42](7c9cc42))
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.

1 participant