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 cjs and esm both #13

Merged
merged 1 commit into from
Jun 22, 2024
Merged

feat: support cjs and esm both #13

merged 1 commit into from
Jun 22, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Jun 22, 2024

BREAKING CHANGE: drop Node.js < 18.19.0 support

eggjs/egg#5257

Summary by CodeRabbit

  • New Features

    • Introduced a Least Recently Used (LRU) cache implementation with enhanced functionalities.
  • Bug Fixes

    • Improved cache item expiration handling and test case accuracy.
  • Documentation

    • Updated README with new import syntax and method signatures.
    • LICENSE changed to MIT License.
  • Chores

    • Updated ESLint configuration, Node.js version in workflows, and .gitignore.
  • Refactor

    • Converted test cases to use async/await and updated module imports to ES module syntax.
  • Dependencies

    • Updated devDependencies and added new scripts in package.json.
  • Build Configuration

    • Updated tsconfig.json for stricter typing and ES2022 target.

BREAKING CHANGE: drop Node.js < 18.19.0 support

eggjs/egg#5257
Copy link

coderabbitai bot commented Jun 22, 2024

Walkthrough

The changes enhance the project’s TypeScript and ESLint configuration, refine workflow settings, update dependencies, and improve the LRU cache implementation. Additionally, documentation and license updates ensure clarity and compliance. The project now uses ES module syntax, ensuring modern JavaScript standards are met.

Changes

File(s) Change Summary
.eslintrc Extended ESLint configuration to include TypeScript rules and enforce node prefix.
.github/workflows/nodejs.yml Updated Node.js version and added CODECOV_TOKEN secret.
.gitignore Added dist directory and .tshy* files to ignore list.
LICENSE Updated to MIT License and updated copyright information.
README.md Changed require to import syntax and updated LRU initialization method.
package.json Updated engines, devDependencies, scripts, and module exports.
src/index.ts Introduced a new LRU cache implementation.
test/bench.cjs, test/fixtures/ts/check.ts Updated syntax and formatting, and removed a trailing newline.
test/ylru.test.ts Switched import syntax to ES modules and converted generator functions to async functions.
tsconfig.json Extended base configuration and modified compiler options for stricter typing.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LRUCache
    participant CacheItem
    
    User ->> LRUCache: new LRU(max)
    activate LRUCache
    
    User ->> LRUCache: set(key, value, { maxAge })
    activate LRUCache
    LRUCache ->> CacheItem: Create CacheItem
    activate CacheItem
    CacheItem ->> LRUCache: Return CacheItem
    deactivate CacheItem
    LRUCache ->> User: Acknowledge set
    
    User ->> LRUCache: get(key)
    activate LRUCache
    LRUCache ->> CacheItem: Retrieve CacheItem
    CacheItem ->> LRUCache: Check expiration
    LRUCache ->> User: Return value
    deactivate CacheItem
Loading

Poem

🐰
Amidst the code, the changes sing,
TypeScript rules and tests we bring!
LRU cache, fresh and bright,
With MIT, we set things right.
Node updates, configs refined,
A seamless flow, ingeniously designed. 🐇


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

socket-security bot commented Jun 22, 2024

Copy link

socket-security bot commented Jun 22, 2024

👍 Dependency issues cleared. Learn more about Socket for GitHub ↗︎

This PR previously contained dependency changes with security issues that have been resolved, removed, or ignored.

Ignoring: npm/egg-bin@6.10.0

View full report↗︎

Next steps

Take a deeper look at the dependency

Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support [AT] socket [DOT] dev.

Remove the package

If you happen to install a dependency that Socket reports as Known Malware you should immediately remove it and select a different dependency. For other alert types, you may may wish to investigate alternative packages or consider if there are other ways to mitigate the specific risk posed by the dependency.

Mark a package as acceptable risk

To ignore an alert, reply with a comment starting with @SocketSecurity ignore followed by a space separated list of ecosystem/package-name@version specifiers. e.g. @SocketSecurity ignore npm/foo@1.0.0 or ignore all packages with @SocketSecurity ignore-all

@fengmk2
Copy link
Member Author

fengmk2 commented Jun 22, 2024

@SocketSecurity ignore npm/egg-bin@6.10.0

Copy link

codecov bot commented Jun 22, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (25dcf3d) to head (eb4e87e).

Additional details and impacted files
@@            Coverage Diff            @@
##            master       #13   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            1         1           
  Lines           64       124   +60     
  Branches        15        32   +17     
=========================================
+ Hits            64       124   +60     

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

Outside diff range and nitpick comments (2)
test/ylru.test.ts (2)

Line range hint 139-153: Check consistency in expiration handling.

The tests for maxAge with sleep intervals are intended to verify that items do not expire prematurely. However, the repeated assertions for non-expired values might be redundant. Consider simplifying these assertions to improve test clarity and efficiency.

- assert(lru.get(1, { maxAge }) !== undefined);
- assert(lru.get('k2', { maxAge }) !== undefined);
- assert(lru.get('k3', { maxAge }) !== undefined);
+ // Assert that values are still retrievable shortly before expiration
+ assert(lru.get(1) !== undefined);
+ assert(lru.get('k2') !== undefined);
+ assert(lru.get('k3') !== undefined);

[!TIP]
Codebase Verification

Verify cache behavior consistency.

The implementation of the LRU class in src/index.ts shows that the cache management logic deviates from typical LRU behavior. Instead of evicting the least recently used items, the cache moves items to a secondary cache (#_cache) and resets the primary cache (#cache) when the size limit is reached. This behavior does not align with the expected behavior of an LRU cache.

  • src/index.ts:
    • get method: Retrieves items from #cache and #_cache, checks for expiration, and updates expiration times.
    • set method: Inserts items into #cache, updates expiration times, and calls _update.
    • _update method: Manages cache size, moves items to #_cache, and resets #cache when the size limit is reached.

Please review and ensure the cache behavior aligns with the expected LRU cache functionality.

Analysis chain

Line range hint 80-95: Verify cache behavior consistency.

The assertions on cache sizes seem to imply that the cache is not behaving as a typical LRU cache, where the size should reflect the number of items that have not expired or been evicted. Please verify that the cache implementation aligns with the expected behavior of an LRU cache.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the LRU cache behavior by checking the source code implementation of cache management.

# Test: Search for cache management logic in the source code. Expect: Clear explanation or comments on cache behavior.
rg --type typescript $'LRU' --glob src/**/*.ts

Length of output: 82



Script:

#!/bin/bash
# Description: Verify the LRU cache behavior by checking the source code implementation of cache management.

# Test: Search for cache management logic in the source code. Expect: Clear explanation or comments on cache behavior.
rg --type ts LRU --glob 'src/**/*.ts'

Length of output: 282



Script:

#!/bin/bash
# Description: Extract the implementation of the LRU class from the source code.

# Test: Extract the full implementation of the LRU class.
ast-grep --lang typescript --pattern $'class LRU {
  $$$
}' src/index.ts

Length of output: 4651

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 25dcf3d and eb4e87e.

Files selected for processing (11)
  • .eslintrc (1 hunks)
  • .github/workflows/nodejs.yml (2 hunks)
  • .gitignore (1 hunks)
  • LICENSE (1 hunks)
  • README.md (4 hunks)
  • package.json (1 hunks)
  • src/index.ts (1 hunks)
  • test/bench.cjs (2 hunks)
  • test/fixtures/ts/check.ts (1 hunks)
  • test/ylru.test.ts (10 hunks)
  • tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (6)
  • .github/workflows/nodejs.yml
  • .gitignore
  • LICENSE
  • test/bench.cjs
  • test/fixtures/ts/check.ts
  • tsconfig.json
Additional context used
LanguageTool
README.md

[grammar] ~21-~21: The word “checkout” is a noun. The verb is spelled with a space. (NOUN_VERB_CONFUSION)
Context: ...r, faster LRU cache algorithm.** Please checkout [algorithm](https://github.com/dominict...


[uncategorized] ~51-~51: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ...alue | null - {Number} options.maxAge: update expire time when get, value will...


[grammar] ~51-~51: The conjunction “when” requires the past participle “got”, “gotten”. Or did you mean “you get”? (IF_VB_PCT)
Context: ...ptions.maxAge: update expire time when get, value will become undefinedafterm...


[uncategorized] ~57-~57: Loose punctuation mark. (UNLIKELY_OPENING_PUNCTUATION)
Context: ..., options]) - {Number} options.maxAge: value will become undefined after `ma...


[style] ~58-~58: The adverb ‘never’ is usually put between ‘will’ and ‘be’. (ADVERB_WORD_ORDER)
Context: ...axAgepass. IfmaxAge` not set, value will be never expired. Set the value for key. ### l...


[grammar] ~64-~64: The word ‘greater’ is a noun or an adjective. A verb is missing or misspelled, or maybe a comma is missing. (MD_JJ)
Context: ...trategy of ylru, the keys' length may greater than max. ```ts const lru = new LRU(...


[uncategorized] ~118-~118: It appears that a hyphen is missing (if ‘auto’ is not used in the context of ‘cars’). (AUTO_HYPHEN)
Context: ...//github.com/xudafeng/git-contributor), auto updated at Thu Mar 28 2024 11:52:18 GMT+0800....

Markdownlint
README.md

18-18: null (MD036, no-emphasis-as-heading)
Emphasis used instead of a heading


114-114: null (MD045, no-alt-text)
Images should have alternate text (alt text)


114-114: null (MD045, no-alt-text)
Images should have alternate text (alt text)


114-114: null (MD045, no-alt-text)
Images should have alternate text (alt text)


114-114: null (MD045, no-alt-text)
Images should have alternate text (alt text)


114-114: null (MD045, no-alt-text)
Images should have alternate text (alt text)


114-114: null (MD045, no-alt-text)
Images should have alternate text (alt text)


116-116: null (MD045, no-alt-text)
Images should have alternate text (alt text)


116-116: null (MD045, no-alt-text)
Images should have alternate text (alt text)


116-116: Expected: leading_and_trailing; Actual: no_leading_or_trailing; Missing leading pipe (MD055, table-pipe-style)
Table pipe style


116-116: Expected: leading_and_trailing; Actual: no_leading_or_trailing; Missing trailing pipe (MD055, table-pipe-style)
Table pipe style


116-116: Expected: 6; Actual: 2; Too few cells, row will be missing data (MD056, table-column-count)
Table column count

Additional comments not posted (15)
.eslintrc (1)

2-5: Approved ESLint Configuration Update

The update to the ESLint configuration properly extends additional TypeScript rules and enforces node prefix rules, aligning with the project's goals of enhancing TypeScript support and maintaining consistent coding standards.

package.json (6)

5-7: Approved Node Version Requirement Update

The updated Node version requirement to >= 18.19.0 is necessary to support the new features and breaking changes introduced in this PR.


14-29: Approved Dependency Updates

The updates to the devDependencies ensure that the project uses the latest and potentially more secure versions of these packages.


33-39: Approved Script Updates and Additions

The addition of new scripts like bench, ci, and prepublishOnly enhances the project's automation and CI/CD capabilities, aligning with modern development practices.


50-63: Approved Updates to Module Exports

The updates to the exports field to support different module formats are crucial for the dual support of CommonJS and ECMAScript modules, aligning with the PR's objectives.


65-68: Approved Updates to Included Files

The updates to the files field to include dist and src ensure that the necessary files are packaged, supporting the new structure of the project.


69-70: Approved Updates to Main and Types Configuration

The updates to the main and types fields to point to the new paths in the dist directory align with the changes in the project structure and support the new module formats.

src/index.ts (2)

1-8: Approved Introduction of Interfaces

The introduction of the YLRUOptions and CacheItem interfaces enhances typing and clarity in the LRU cache implementation, aligning with the project's enhanced TypeScript support.


10-124: Approved Class Definition and Methods

The LRU class is well-defined with appropriate methods for managing the cache. The use of private fields and methods enhances encapsulation and aligns with modern JavaScript practices.

README.md (2)

Line range hint 30-68: Approved Updated Import Statements and Usage Examples

The updated import statements and usage examples in the README.md reflect the new ECMAScript module syntax and the use of the new keyword, aligning with the PR's objectives of supporting both CommonJS and ECMAScript Modules.


Line range hint 45-89: Approved Updated API Documentation

The updated API documentation, including the use of the new keyword, provides clarity on how to initialize and use the LRU object, aligning with the updated implementation and module format support.

Tools
LanguageTool

[grammar] ~64-~64: The word ‘greater’ is a noun or an adjective. A verb is missing or misspelled, or maybe a comma is missing. (MD_JJ)
Context: ...trategy of ylru, the keys' length may greater than max. ```ts const lru = new LRU(...

test/ylru.test.ts (4)

1-3: Approved import changes for ESM compatibility.

The imports have been updated to use ECMAScript module syntax, aligning with the PR objectives to support both CommonJS and ECMAScript modules.


46-71: Approved async function updates and assert adjustments.

The test cases have been updated to asynchronous functions using async and await for handling sleep operations, which is a modern approach to handling asynchronous code in JavaScript. The use of assert.equal for checking cache sizes is appropriate for ensuring correctness in cache behavior.


Line range hint 117-126: Approved maxAge tests for cache expiration.

The test cases for maxAge properly simulate scenarios where cache items expire after a specified duration. This ensures that the LRU cache handles time-based expiration correctly, which is crucial for caches in production environments.


199-209: Approved tests for cache expiration handling.

The tests effectively simulate scenarios where multiple items expire at different times, which is essential for validating the robustness of the LRU cache's expiration logic.

Comment on lines +163 to +179
it('can update expired to 0', async () => {
const lru = new LRU(10);
lru.set('foo', 'bar', { maxAge: 100 });
lru.get('foo', { maxAge: 0 });
yield sleep(200);
await sleep(200);
assert(lru.get('foo') === 'bar');
});

it('can update expired when item in _cache', function* () {
it('can update expired when item in _cache', async () => {
const lru = new LRU(2);
lru.set('foo1', 'bar');
lru.set('foo2', 'bar', { maxAge: 100 });
lru.get('foo1', { maxAge: 100 });
yield sleep(50);
await sleep(50);
assert(lru.get('foo1') === 'bar');
assert(lru.get('foo2', { maxAge: 0 }) === 'bar');
yield sleep(120);
await sleep(120);
Copy link

Choose a reason for hiding this comment

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

Clarify behavior when updating expired items.

The tests for updating expired cache items to zero maxAge and checking their availability afterwards are crucial for understanding cache behavior under dynamic conditions. However, the logic seems complex and might benefit from additional inline comments explaining the expected outcomes.

+ // Test updating expired items to zero maxAge and verify they are still retrievable
lru.set('foo', 'bar', { maxAge: 100 });
lru.get('foo', { maxAge: 0 });
await sleep(200);
assert(lru.get('foo') === 'bar');
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('can update expired to 0', async () => {
const lru = new LRU(10);
lru.set('foo', 'bar', { maxAge: 100 });
lru.get('foo', { maxAge: 0 });
yield sleep(200);
await sleep(200);
assert(lru.get('foo') === 'bar');
});
it('can update expired when item in _cache', function* () {
it('can update expired when item in _cache', async () => {
const lru = new LRU(2);
lru.set('foo1', 'bar');
lru.set('foo2', 'bar', { maxAge: 100 });
lru.get('foo1', { maxAge: 100 });
yield sleep(50);
await sleep(50);
assert(lru.get('foo1') === 'bar');
assert(lru.get('foo2', { maxAge: 0 }) === 'bar');
yield sleep(120);
await sleep(120);
it('can update expired to 0', async () => {
const lru = new LRU(10);
// Test updating expired items to zero maxAge and verify they are still retrievable
lru.set('foo', 'bar', { maxAge: 100 });
lru.get('foo', { maxAge: 0 });
await sleep(200);
assert(lru.get('foo') === 'bar');
});
it('can update expired when item in _cache', async () => {
const lru = new LRU(2);
lru.set('foo1', 'bar');
lru.set('foo2', 'bar', { maxAge: 100 });
lru.get('foo1', { maxAge: 100 });
await sleep(50);
assert(lru.get('foo1') === 'bar');
assert(lru.get('foo2', { maxAge: 0 }) === 'bar');
await sleep(120);

@fengmk2 fengmk2 merged commit 73e07bf into master Jun 22, 2024
9 checks passed
@fengmk2 fengmk2 deleted the esm branch June 22, 2024 15:22
fengmk2 pushed a commit that referenced this pull request Jun 22, 2024
[skip ci]

## [2.0.0](v1.4.0...v2.0.0) (2024-06-22)

### ⚠ BREAKING CHANGES

* drop Node.js < 18.19.0 support

eggjs/egg#5257

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Introduced a Least Recently Used (LRU) cache implementation with
enhanced functionalities.

- **Bug Fixes**
  - Improved cache item expiration handling and test case accuracy.

- **Documentation**
  - Updated `README` with new import syntax and method signatures.
  - LICENSE changed to MIT License.

- **Chores**
- Updated ESLint configuration, Node.js version in workflows, and
`.gitignore`.

- **Refactor**
- Converted test cases to use async/await and updated module imports to
ES module syntax.

- **Dependencies**
  - Updated `devDependencies` and added new scripts in `package.json`.

- **Build Configuration**
  - Updated `tsconfig.json` for stricter typing and ES2022 target.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

### Features

* support cjs and esm both ([#13](#13)) ([73e07bf](73e07bf))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant