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

feat: support pkg.eggPlugin.exports property #274

Merged
merged 5 commits into from
Dec 17, 2024
Merged

feat: support pkg.eggPlugin.exports property #274

merged 5 commits into from
Dec 17, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 17, 2024

e.g.:

  "eggPlugin": {
    "name": "schedule",
    "exports": {
      "import": "./dist/esm",
      "require": "./dist/commonjs"
    }
  }

Summary by CodeRabbit

  • New Features

    • Added a Node.js version badge to the README for improved visibility.
    • Introduced a new asynchronous method to check for file existence.
    • Added support for Node.js version 23 in CI configuration.
    • New module export structure for plugin settings.
  • Bug Fixes

    • Enhanced error handling for plugin loading, providing clearer error messages.
  • Documentation

    • Updated comments and logging for better clarity and structure.

e.g.:

```json
  "eggPlugin": {
    "name": "schedule",
    "exports": {
      "import": "./dist/esm",
      "require": "./dist/commonjs"
    }
  }
```
Copy link

coderabbitai bot commented Dec 17, 2024

Warning

Rate limit exceeded

@fengmk2 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 7a3d32d and 048b1d7.

📒 Files selected for processing (2)
  • src/egg.ts (1 hunks)
  • src/lifecycle.ts (1 hunks)

Walkthrough

The pull request introduces enhancements to the Egg.js core library, focusing on improving the loader's asynchronous capabilities, error handling, and utility functions. The changes include adding a Node.js version badge to the README, modifying the EggLoader class to support asynchronous plugin configuration loading, and updating utility functions for file system operations and stack trace handling. Additionally, the CI configuration has been updated to support Node.js version 23, and several test cases have been adjusted to accommodate these changes.

Changes

File Changes
README.md Added Node.js version badge
src/loader/egg_loader.ts - Made #mergePluginConfig method asynchronous
- Added #formatPluginPathFromPackageJSON method
- Enhanced error handling and debug logging
src/utils/index.ts - Added existsPath method for async file existence checks
- Refactored getCalleeFromStack function
.github/workflows/nodejs.yml Updated Node.js version support to include version 23
test/fixtures/plugin-egg-plugin/config/plugin.js Removed strict mode directive
test/fixtures/plugin-pkg-exports/config/plugin.js Added new module export for configuration settings
test/fixtures/plugin-pkg-exports/package.json Created new package.json file for the plugin-pkg-exports package
test/loader/mixin/load_plugin.test.ts - Updated test cases for async handling
- Added new test case for loading plugins by pkg.eggPlugin.exports

Sequence Diagram

sequenceDiagram
    participant Loader as EggLoader
    participant Utils as Utils
    participant PluginConfig as Plugin Config

    Loader->>PluginConfig: loadPlugin()
    Loader->>Loader: #mergePluginConfig (async)
    Loader->>Utils: existsPath()
    Utils-->>Loader: File existence result
    Loader->>Loader: #formatPluginPathFromPackageJSON()
    Loader-->>PluginConfig: Resolved Plugin Configuration
Loading

Poem

🐰 A Rabbit's Ode to Egg.js Evolution 🥚
Async magic weaves through the code's domain,
Plugins dance with promises, no longer in chain,
Badges shine bright, versions clear as day,
Loader's path now smoother, errors kept at bay,
CodeRabbit's touch, making frameworks sway! 🌟


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

@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 (1)
src/utils/index.ts (1)

57-57: Consider the impact of removing console.trace on deprecation warnings

By commenting out console.trace, deprecation warnings will no longer include stack traces. Evaluate whether this change might make it harder for developers to locate the source of deprecated usage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7811cce and a840f92.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • src/loader/egg_loader.ts (7 hunks)
  • src/utils/index.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • README.md
🧰 Additional context used
🪛 Biome (1.9.4)
src/utils/index.ts

[error] 40-40: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (11)
src/loader/egg_loader.ts (8)

8-8: Imported readJSON for asynchronous JSON reading

The addition of readJSON facilitates asynchronous reading of JSON files, enhancing non-blocking operations.


465-465: Properly updated to await the asynchronous #mergePluginConfig method

The call to #mergePluginConfig has been correctly updated to use await, reflecting its new asynchronous nature.


541-541: Added debug logging for custom plugins

The debug statement improves visibility into the loading of custom plugins.


626-636: Transitioned #mergePluginConfig to asynchronous execution

The #mergePluginConfig method is now asynchronous, which allows non-blocking file I/O operations for plugin configurations.


630-637: Asynchronously reading plugin package configuration

Using await readJSON(pluginPackage) ensures that the plugin's package.json is read without blocking the event loop.


717-718: Logging implicitly enabled plugins for transparency

The code logs plugins that are enabled implicitly, which improves transparency and aids in debugging plugin dependencies.


791-810: Added #formatPluginPathFromPackageJSON method to handle plugin exports

The new method correctly resolves plugin paths based on the exports field in package.json, accommodating both CommonJS and ESM formats.


785-787: Verify Node.js version compatibility for Error constructor with cause property

The use of the cause option in the Error constructor is supported in Node.js v16 and above. Ensure that the project's minimum Node.js version requirement reflects this to prevent compatibility issues.

Run the following script to verify the Node.js engine version requirement:

✅ Verification successful

Node.js version requirement is compatible with Error cause property

The project requires Node.js version >= 18.19.0, which fully supports the Error constructor's cause property (introduced in Node.js 16.9.0). The code usage is safe and compatible with the project's minimum Node.js version requirement.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the Node.js version requirement specified in package.json

# Test: Display the Node.js version requirement
jq '.engines.node' package.json

Length of output: 44

src/utils/index.ts (3)

4-4: Imported stat from node:fs/promises for asynchronous file operations

The import allows the use of stat in an asynchronous manner, improving non-blocking file system checks.


22-53: Refactored getCalleeFromStack as a standalone function

The getCalleeFromStack function has been redefined as a standalone function, enhancing clarity and modularity of the code.

🧰 Tools
🪛 Biome (1.9.4)

[error] 40-40: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


64-71: Added existsPath method for asynchronous file existence checks

The new existsPath method provides an asynchronous way to check for file existence using stat, promoting non-blocking code execution.

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: 1

🧹 Nitpick comments (2)
src/utils/index.ts (1)

57-62: Consider using structured logging.

The current implementation could benefit from structured logging to make it easier to parse and analyze logs in production.

-    if (debug.enabled) {
-      console.trace('[@eggjs/core:deprecated] %s', message);
-    } else {
-      console.warn('[@eggjs/core:deprecated] %s', message);
-      console.warn('[@eggjs/core:deprecated] set NODE_DEBUG=@eggjs/core:utils can show call stack');
-    }
+    const logData = {
+      type: 'deprecation',
+      message,
+      stack: debug.enabled ? new Error().stack : undefined,
+    };
+    if (debug.enabled) {
+      console.trace('[@eggjs/core:deprecated]', logData);
+    } else {
+      console.warn('[@eggjs/core:deprecated]', logData);
+      console.warn('[@eggjs/core:deprecated] set NODE_DEBUG=@eggjs/core:utils can show call stack');
+    }
test/loader/mixin/load_plugin.test.ts (1)

27-35: Consider adding edge cases for plugin exports.

While the basic functionality is tested, consider adding test cases for:

  1. Invalid exports configuration
  2. Missing export paths
  3. Conflicting export formats

Example test case:

it('should handle invalid plugin exports configuration', async () => {
  app = createApp('plugin-pkg-exports-invalid');
  const loader = app.loader;
  await assert.rejects(async () => {
    await loader.loadPlugin();
  }, /Invalid exports configuration/);
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a840f92 and 7a3d32d.

⛔ Files ignored due to path filters (3)
  • test/fixtures/plugin-pkg-exports/node_modules/a/foo_dist/commonjs/config/config.default.js is excluded by !**/node_modules/**
  • test/fixtures/plugin-pkg-exports/node_modules/a/foo_dist/esm/config/config.default.js is excluded by !**/node_modules/**
  • test/fixtures/plugin-pkg-exports/node_modules/a/package.json is excluded by !**/node_modules/**
📒 Files selected for processing (6)
  • .github/workflows/nodejs.yml (1 hunks)
  • src/utils/index.ts (3 hunks)
  • test/fixtures/plugin-egg-plugin/config/plugin.js (0 hunks)
  • test/fixtures/plugin-pkg-exports/config/plugin.js (1 hunks)
  • test/fixtures/plugin-pkg-exports/package.json (1 hunks)
  • test/loader/mixin/load_plugin.test.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • test/fixtures/plugin-egg-plugin/config/plugin.js
✅ Files skipped from review due to trivial changes (2)
  • test/fixtures/plugin-pkg-exports/config/plugin.js
  • test/fixtures/plugin-pkg-exports/package.json
🧰 Additional context used
🪛 Biome (1.9.4)
src/utils/index.ts

[error] 40-40: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
.github/workflows/nodejs.yml (2)

14-14: LGTM! Adding Node.js v23 testing is beneficial.

Testing against Node.js v23 is particularly relevant for this PR as it enhances support for package exports, which aligns with the PR's objective of supporting the pkg.eggPlugin.exports property.


14-14: Verify Node.js version compatibility in package.json

Since we're adding Node.js v23 to the test matrix, we should ensure the package.json's engines field reflects the supported Node.js versions correctly.

✅ Verification successful

Node.js version compatibility is correctly configured

The package.json's engines field specifies ">= 18.19.0" which aligns perfectly with the Node.js versions being tested (18.19.0, 18, 20, 22, 23) in the workflow. No explicit version checks were found in the codebase that might conflict with these versions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check Node.js version compatibility settings

# Check if package.json exists and contains engines field
echo "Checking package.json for Node.js version constraints..."
if [ -f package.json ]; then
    jq '.engines.node' package.json
fi

# Look for any explicit version checks in the codebase
echo "Checking for explicit Node.js version checks in the code..."
rg -l "process\.version" 

Length of output: 349

src/utils/index.ts (1)

68-75: LGTM! Clean async implementation.

The implementation correctly uses async/await with proper error handling.

test/loader/mixin/load_plugin.test.ts (1)

17-25: LGTM! Good test coverage for plugin exports.

The test case properly verifies the presence of essential plugin properties.

src/utils/index.ts Show resolved Hide resolved
Copy link

pkg-pr-new bot commented Dec 17, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/egg-core/@eggjs/core@274

commit: 048b1d7

Copy link

codecov bot commented Dec 17, 2024

Codecov Report

Attention: Patch coverage is 65.38462% with 36 lines in your changes missing coverage. Please review.

Project coverage is 92.88%. Comparing base (16274e7) to head (048b1d7).
Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/utils/index.ts 34.00% 33 Missing ⚠️
src/loader/egg_loader.ts 92.85% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #274      +/-   ##
==========================================
- Coverage   92.98%   92.88%   -0.10%     
==========================================
  Files          10       10              
  Lines        3238     3291      +53     
  Branches      508      528      +20     
==========================================
+ Hits         3011     3057      +46     
- Misses        227      234       +7     

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

@fengmk2 fengmk2 merged commit df9efed into master Dec 17, 2024
21 of 23 checks passed
@fengmk2 fengmk2 deleted the support-esm branch December 17, 2024 05:33
fengmk2 pushed a commit that referenced this pull request Dec 17, 2024
[skip ci]

## [6.1.0](v6.0.3...v6.1.0) (2024-12-17)

### Features

* support `pkg.eggPlugin.exports` property ([#274](#274)) ([df9efed](df9efed))
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