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: refactor with typescript to support esm and cjs both #56

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

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented May 29, 2024

BREAKING CHANGE: Drop Node.js < 16 support

  1. 使用 ts 重构
  2. 使用 tshy 支持 esm 和 cjs
  3. test 使用 test-runner (这里需要 node v18 版本)

merge from #51

Summary by CodeRabbit

  • New Features

    • Introduced waitPort function to wait for a specified port to become available.
    • Added CLI tool tests for version display, usage information, available ports, and verbose logging.
  • Bug Fixes

    • Improved detectPort function to handle different parameter combinations and enhance error handling.
  • Documentation

    • Updated .gitignore to include new patterns and files.
  • Chores

    • Updated Node.js versions in workflows to support newer versions (16, 18, 20, 22).
    • Refined ESLint configurations to extend TypeScript rules and enforce node prefix conventions.
    • Updated package.json dependencies and scripts for better development workflow.
  • Refactor

    • Migrated CommonJS require to ES module imports for better compliance with modern JavaScript standards.

Copy link

coderabbitai bot commented May 29, 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 31 minutes and 54 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 Files that changed from the base of the PR and between b7bcccf and 48abebe.

Walkthrough

The updates encompass a broad range of improvements and modernizations, including ESLint configurations, Node.js workflow updates, enhanced TypeScript support, and dependency upgrades. Key changes involve refactoring scripts to ES modules, updating package management, and introducing new functionalities like detectPort and waitPort with comprehensive testing. The modifications aim to improve code quality, maintainability, and compatibility with newer Node.js versions.

Changes

Files/Paths Change Summary
.eslintrc Introduced ESLint configurations for TypeScript and node prefix conventions, disabled TypeScript comment bans.
.github/workflows/nodejs.yml Updated Node.js version specifications from '14, 16, 18' to '16, 18, 20, 22'.
.github/workflows/release.yml Changed uses path for Node.js release job to a different repository and branch.
.gitignore Added .tshy*, dist/, and package-lock.json to ignore list.
bin/detect-port.ts Refactored to use ES module imports and updated to use detectPort function.
package.json Updated main entry, dependencies, scripts, and added module type definitions and export paths.
src/detect-port.ts Refactored detectPort function for better type safety and multiple parameter combinations.
src/index.ts Exported detectPort and waitPort functions.
src/wait-port.ts Introduced waitPort function for asynchronously waiting for a port to become available.
test/cli.test.ts Added tests for CLI tool functionality including version display, usage details, and port availability.
test/detect-port.test.ts Added tests for detectPort function with various scenarios and configurations.
test/wait-port.test.ts Introduced tests for waitPort function.
tsconfig.json Updated to extend configuration from @eggjs/tsconfig and set compiler options for ES2022 and NodeNext modules.

Sequence Diagram(s) (Beta)

Silently ignored as the changes are too varied for a single diagram to represent effectively.

Poem

In the code's vast land, changes bloom,
ESLint rules sweep away the gloom.
Node.js versions climb so high,
TypeScript soars, touching the sky.
Ports detected, waiting too,
With tests so fresh, our work's brand new.
🎉✨🐇


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 May 29, 2024

Copy link

socket-security bot commented May 29, 2024

🚨 Potential security issues detected. Learn more about Socket for GitHub ↗︎

To accept the risk, merge this PR and you will not be notified again.

Alert Package NoteSource
Install scripts npm/egg-bin@6.9.0
  • Install script: postinstall
  • Source: node scripts/postinstall.js

View full report↗︎

Next steps

What is an install script?

Install scripts are run when the package is installed. The majority of malware in npm is hidden in install scripts.

Packages should not be running non-essential scripts during install and there are often solutions to problems people solve with install scripts that can be run at publish time instead.

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

  • @SocketSecurity ignore npm/egg-bin@6.9.0

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

Outside diff range and nitpick comments (2)
bin/detect-port.ts (1)

Line range hint 49-49: Replace isNaN with Number.isNaN for more accurate checks that avoid type coercion.

- } else if (isNaN(port)) {
+ } else if (Number.isNaN(port)) {
src/detect-port.ts (1)

Line range hint 19-47: Refactor to avoid reassigning function parameters.

Reassigning function parameters can lead to confusing bugs and harder-to-maintain code. Consider using local variables instead.

- export default function detectPort(port?: number | string | PortConfig | DetectPortCallback, callback?: DetectPortCallback) {
+ export default function detectPort(inputPort?: number | string | PortConfig | DetectPortCallback, inputCallback?: DetectPortCallback) {
+   let port = inputPort;
+   let callback = inputCallback;
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 5e8f3ed and b7bcccf.
Files selected for processing (13)
  • .eslintrc (1 hunks)
  • .github/workflows/nodejs.yml (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • .gitignore (1 hunks)
  • bin/detect-port.ts (3 hunks)
  • package.json (2 hunks)
  • src/detect-port.ts (5 hunks)
  • src/index.ts (1 hunks)
  • src/wait-port.ts (1 hunks)
  • test/cli.test.ts (1 hunks)
  • test/detect-port.test.ts (1 hunks)
  • test/wait-port.test.ts (1 hunks)
  • tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (4)
  • .eslintrc
  • .github/workflows/release.yml
  • .gitignore
  • tsconfig.json
Additional Context Used
Biome (29)
bin/detect-port.ts (2)

31-31: Use Number.parseInt instead of the equivalent global.


49-49: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

src/detect-port.ts (15)

49-49: Unexpected any. Specify a different type.


64-64: Unexpected any. Specify a different type.


94-94: Unexpected any. Specify a different type.


112-112: Unexpected any. Specify a different type.


119-119: Unexpected any. Specify a different type.


24-24: Reassigning a function parameter is confusing.


28-28: Reassigning a function parameter is confusing.


32-32: Reassigning a function parameter is confusing.


23-23: Reassigning a function parameter is confusing.


27-27: Reassigning a function parameter is confusing.


32-32: Use Number.parseInt instead of the equivalent global.


51-51: Reassigning a function parameter is confusing.


54-54: Reassigning a function parameter is confusing.


55-55: Reassigning a function parameter is confusing.


128-128: Reassigning a function parameter is confusing.

src/wait-port.ts (3)

21-21: Unexpected any. Specify a different type.


22-22: Unexpected any. Specify a different type.


14-14: Use Number.Infinity instead of the equivalent global.

test/cli.test.ts (3)

51-51: Template literals are preferred over string concatenation.


45-45: Use Number.parseInt instead of the equivalent global.


52-52: Use Number.parseInt instead of the equivalent global.

test/detect-port.test.ts (4)

51-51: Prefer for...of instead of forEach.


84-84: Unexpected any. Specify a different type.


90-90: Unexpected any. Specify a different type.


103-103: Template literals are preferred over string concatenation.

test/wait-port.test.ts (2)

11-11: Prefer for...of instead of forEach.


28-28: Unexpected any. Specify a different type.

GitHub Check Runs (3)
Node.js / Test (ubuntu-latest, 22) failure (2)

bin/detect-port.ts: [failure] 8-8:
The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

Node.js / Test (ubuntu-latest, 20) failure (2)

bin/detect-port.ts: [failure] 8-8:
The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

Node.js / Test (ubuntu-latest, 18) failure (2)

bin/detect-port.ts: [failure] 8-8:
The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

Additional comments not posted (5)
src/index.ts (2)

1-2: The imports are correctly updated to use ES module syntax.


4-6: The export statements are correctly updated to support both default and named exports, aligning with the PR's objectives to support ESM and CJS.

.github/workflows/nodejs.yml (1)

12-15: The workflow file has been updated to use the latest versions of Node.js, ensuring compatibility with the new features and dropping support for older versions as per the PR description.

package.json (1)

13-13: The updates to the package.json align with the PR's objectives, including the update of dependencies and scripts to support TypeScript and the new module structure.

Also applies to: 24-39, 42-74

bin/detect-port.ts (1)

8-8: Ensure the TypeScript configuration allows the use of import.meta. This might require setting the module option to nodenext or similar in tsconfig.json.

Verification successful

The TypeScript configuration in tsconfig.json has the module option set to nodenext, which supports the use of import.meta.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the TypeScript configuration for module option.

# Test: Search for the TypeScript configuration. Expect: Module option set to support 'import.meta'.
cat tsconfig.json | jq '.compilerOptions.module'

Length of output: 59

try {
const port = 9093;
await waitPort(port, { retries: 3, retryInterval: 100 });
} catch (err:any) {
Copy link

Choose a reason for hiding this comment

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

Avoid using any as a type for error handling. Specify a more precise type for better type safety.

- } catch (err:any) {
+ } catch (err: Error) {

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.

Suggested change
} catch (err:any) {
} catch (err: Error) {

describe('wait for port', () => {
const servers: net.Server[] = [];
after(() => {
servers.forEach(server => server.close());
Copy link

Choose a reason for hiding this comment

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

Consider using a for...of loop for better readability and performance when iterating over arrays.

- servers.forEach(server => server.close());
+ for (const server of servers) {
+   server.close();
+ }

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.

Suggested change
servers.forEach(server => server.close());
for (const server of servers) {
server.close();
}

}

export default async function waitPort(port: number, options: WaitPortOptions = {}) {
const { retryInterval = 1000, retries = Infinity } = options;
Copy link

Choose a reason for hiding this comment

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

Use Number.Infinity instead of the global Infinity for better clarity and consistency in TypeScript.

- const { retryInterval = 1000, retries = Infinity } = options;
+ const { retryInterval = 1000, retries = Number.Infinity } = options;

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.

Suggested change
const { retryInterval = 1000, retries = Infinity } = options;
const { retryInterval = 1000, retries = Number.Infinity } = options;

Comment on lines +21 to +22
(err as any).retries = retries;
(err as any).count = count;
Copy link

Choose a reason for hiding this comment

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

Avoid using any as a type. Use a more specific type or define a custom error type to enhance type safety.

- (err as any).retries = retries;
- (err as any).count = count;
+ interface RetryError extends Error {
+   retries: number;
+   count: number;
+ }
+ const err: RetryError = new Error('retries exceeded') as RetryError;
+ err.retries = retries;
+ err.count = count;

Committable suggestion was skipped due low confidence.

@@ -21,18 +28,15 @@
}
};

const main = require('..');

const port = parseInt(arg_0, 10);
Copy link

Choose a reason for hiding this comment

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

Use Number.parseInt instead of the global parseInt for better clarity and consistency in TypeScript.

- const port = parseInt(arg_0, 10);
+ const port = Number.parseInt(arg_0, 10);

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.

Suggested change
const port = parseInt(arg_0, 10);
const port = Number.parseInt(arg_0, 10);

}
}

port = parseInt(port) || 0;
port = parseInt(port as unknown as string) || 0;
Copy link

Choose a reason for hiding this comment

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

Use Number.parseInt for parsing integers.

- port = parseInt(port as unknown as string) || 0;
+ port = Number.parseInt(port as unknown as string) || 0;

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.

Suggested change
port = parseInt(port as unknown as string) || 0;
port = Number.parseInt(port as unknown as string) || 0;

@@ -50,7 +61,7 @@
if (hostname) {
listen(port, hostname, (err, realPort) => {
if (err) {
if (err.code === 'EADDRNOTAVAIL') {
if ((err as any).code === 'EADDRNOTAVAIL') {
Copy link

Choose a reason for hiding this comment

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

Specify a more precise type than any.

Using any defeats the purpose of TypeScript's static typing. It's better to define a more specific type or use TypeScript's utility types if the exact shape is not known.

- if ((err as any).code === 'EADDRNOTAVAIL') {
+ if ((err as NodeJS.ErrnoException).code === 'EADDRNOTAVAIL') {

Also applies to: 94-94, 119-119


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.

Suggested change
if ((err as any).code === 'EADDRNOTAVAIL') {
if ((err as NodeJS.ErrnoException).code === 'EADDRNOTAVAIL') {

t.mock.reset();
});

it('work with listening next port 4001 because 4000 was listened to ' + ip(), async () => {
Copy link

Choose a reason for hiding this comment

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

Use template literals for string operations.

- it('work with listening next port 4001 because 4000 was listened to ' + ip(), async () => {
+ it(`work with listening next port 4001 because 4000 was listened to ${ip()}`, async () => {

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.

Suggested change
it('work with listening next port 4001 because 4000 was listened to ' + ip(), async () => {
it(`work with listening next port 4001 because 4000 was listened to ${ip()}`, async () => {

}
});
after(() => {
servers.forEach(server => server.close());
Copy link

Choose a reason for hiding this comment

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

Use modern JavaScript loops for better readability.

- servers.forEach(server => server.close());
+ for (const server of servers) {
+   server.close();
+ }

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.

Suggested change
servers.forEach(server => server.close());
for (const server of servers) {
server.close();
}

});

it('should listen next port 4001 when localhost is not binding', async t => {
t.mock.method(dns, 'lookup', (address: string, callback: (...args: any[]) => void) => {
Copy link

Choose a reason for hiding this comment

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

Specify a more precise type than any.

Using any defeats the purpose of TypeScript's static typing. It's better to define a more specific type or use TypeScript's utility types if the exact shape is not known.

- t.mock.method(dns, 'lookup', (address: string, callback: (...args: any[]) => void) => {
+ t.mock.method(dns, 'lookup', (address: string, callback: (err: NodeJS.ErrnoException | null, address: string[]) => void) => {

Also applies to: 90-90


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.

Suggested change
t.mock.method(dns, 'lookup', (address: string, callback: (...args: any[]) => void) => {
t.mock.method(dns, 'lookup', (address: string, callback: (err: NodeJS.ErrnoException | null, address: string[]) => void) => {

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