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

Upgrade package inquirer from 11.1.0 to 12.3 #3549

Merged

Conversation

MayankJha014
Copy link
Contributor

@MayankJha014 MayankJha014 commented Feb 6, 2025

Upgraing package inquirer from 11.1 tot 12.4

Issue: #3517

Summary by CodeRabbit

  • Chores
    • Upgraded the interactive prompt library to version 12 for improved stability and performance.
  • Refactor
    • Standardized the configuration flow prompts across setup features, including Docker configuration and port setup, maintaining a consistent user experience.
  • Tests
    • Enhanced test reliability with updated prompt mocking strategies to accurately simulate interactive responses.
    • Introduced new test cases for the API setup process based on user confirmation.

Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

Walkthrough

This pull request upgrades the inquirer dependency version from ^11.0.2 to ^12.4.1 and adjusts the usage of inquirer.prompt throughout the codebase. Specifically, prompt configurations that were once passed as a single object are now wrapped in an array. Additionally, the tests have been updated to dynamically import the actual inquirer module and override its prompt method, ensuring consistency with the new version. These changes affect both production code and test files while maintaining existing functionality.

Changes

File(s) Change Summary
package.json Updated inquirer dependency version from ^11.0.2 to ^12.4.1.
setup.ts, src/setup/askAndSetDockerOption/askAndSetDockerOption.ts, src/setup/askAndUpdatePort/askAndUpdatePort.ts, src/setup/askForDocker/askForDocker.ts, src/setup/askForCustomPort/askForCustomPort.ts Modified inquirer.prompt calls to accept an array of prompt objects instead of a single object; adjusted response handling (e.g., variable assignment changes in askForCustomPort.ts) while keeping functionality intact.
src/setup/askAndSetDockerOption/askAndSetDockerOption.spec.ts, src/setup/askForUpdatePort/askForUpdatePort.spec.ts, src/setup/askForCustomPort/askForCustomPort.spec.ts, src/setup/askForDocker/askForDocker.spec.ts Updated mocking of the inquirer module by replacing static mocks with an asynchronous import of the actual module and overriding the prompt method with vi.fn(), also standardizing mock return values to an array format.

Possibly related issues

Possibly related PRs

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes

Poem

In code, I hop with glee,
Upgrading packages merrily.
Prompts now arrayed with care,
Tests and flows in perfect pair.
With twitching ears and code so neat,
This rabbit's cheer is hard to beat!
🥕🐰

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

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.

@MayankJha014 MayankJha014 changed the base branch from main to develop-postgres February 6, 2025 19:04
Copy link

github-actions bot commented Feb 6, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 6, 2025
Copy link
Contributor

@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/setup/askForCustomPort/askForCustomPort.spec.ts (1)

5-14: LGTM! Consider enhancing the documentation.

The new mocking implementation correctly handles inquirer v12+ compatibility while preserving the actual module's functionality. The approach is robust and follows vitest best practices.

Consider expanding the comment to better document why this specific mocking approach is needed:

-// ✅ Fix Inquirer Mocking for v12+
+// ✅ Fix Inquirer Mocking for v12+
+// This approach preserves actual inquirer functionality while allowing prompt mocking.
+// Required due to ESM changes in inquirer v12.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 163791f and 70b1d41.

📒 Files selected for processing (1)
  • src/setup/askForCustomPort/askForCustomPort.spec.ts (1 hunks)
🔇 Additional comments (1)
src/setup/askForCustomPort/askForCustomPort.spec.ts (1)

23-25: Verify prompt response format compatibility with inquirer v12.

The AI summary indicates that inquirer v12 expects array-wrapped configuration objects, but the test mocks use direct object responses. Let's verify this is still compatible with the new version.

Also applies to: 32-34, 56-57, 65-70, 80-81, 89-91, 99-109

✅ Verification successful

🌐 Web query:

What is the expected response format for inquirer.prompt in version 12?

💡 Result:

Inquirer.js v12's `inquirer.prompt` returns responses as **a Promise resolving to an object** where answers are keyed by each question's `name` property. Here's the detailed structure:

## Response Format
- **Object keys** match the `name` field from your question definitions  
- **Values** contain user responses in appropriate data types:
  - Single-value inputs: `string`/`number`/`boolean`
  - Multi-select (checkbox): `array`
  - List selections: `string` (selected value)

Example response for a pizza ordering prompt:
```javascript
{
  pizzaType: 'Pepperoni',       // from list selection
  size: 'Large',                // from rawlist
  toppings: ['Cheese','Olives'],// from checkbox
  specialInstructions: 'Extra crispy' // from input
}
```

## Key Implementation Details
1. **Promise-based** (async/await compatible):
   ```javascript
   const answers = await inquirer.prompt(questions);
   ```

2. **Nested objects** supported through dot-notation names:
   ```javascript
   // Question definition
   { name: 'address.street', ... }
   
   // Response structure
   { address: { street: '123 Main St' } }
   ```

3. **Type preservation**:
   - `number` type questions return numeric values
   - `confirm` type returns boolean

4. **Error handling**:
   ```javascript
   try {
     const answers = await inquirer.prompt(...);
   } catch (error) {
     if (error.isTtyError) { /* Rendering error */ }
     else { /* Other errors */ }
   }
   ```

This format remains consistent across all prompt types (input, list, checkbox, etc.)[1][4][7]. The key evolution from older versions is the shift from callback-style to Promise-based responses[2][10].

Citations:

- 1: https://www.npmjs.com/package/inquirer
- 2: https://www.npmjs.com/package/inquirer/v/0.1.12
- 3: https://github.com/enquirer/enquirer
- 4: https://www.educative.io/answers/how-to-use-the-inquirer-node-package
- 5: https://python-inquirer.readthedocs.io/en/latest/
- 6: https://python-inquirer.readthedocs.io/_/downloads/en/latest/pdf/
- 7: https://javascript.plainenglish.io/how-to-inquirer-js-c10a4e05ef1f?gi=06ccc5b37523
- 8: https://github.com/SBoudrias/Inquirer.js/releases
- 9: https://www.digitalocean.com/community/tutorials/nodejs-interactive-command-line-prompts
- 10: https://geshan.com.np/blog/2023/03/inquirer-js/

Compatibility Verified for inquirer.prompt Response Format

The latest version of inquirer (v12) returns responses as a Promise that resolves to an object keyed by each question's name. This means the current test mock using a direct object (as shown on lines 23‑25 and elsewhere) is valid and compatible with inquirer v12.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 7, 2025
Copy link
Contributor

@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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70b1d41 and 178f952.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/setup/askAndSetDockerOption/askAndSetDockerOption.spec.ts (1 hunks)
  • src/setupTests.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • package.json
  • src/setup/askAndSetDockerOption/askAndSetDockerOption.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)

src/setupTests.ts Outdated Show resolved Hide resolved
Copy link

codecov bot commented Feb 7, 2025

Codecov Report

Attention: Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.

Project coverage is 85.91%. Comparing base (350b5df) to head (6d947ad).
Report is 1 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
setup.ts 0.00% 1 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3549      +/-   ##
====================================================
+ Coverage             85.69%   85.91%   +0.21%     
====================================================
  Files                   342      342              
  Lines                  8881     8882       +1     
  Branches               1911     1911              
====================================================
+ Hits                   7611     7631      +20     
+ Misses                  930      906      -24     
- Partials                340      345       +5     

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

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 7, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 7, 2025
Copy link
Contributor

@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 (3)
src/setup/askForDocker/askForDocker.spec.ts (3)

5-14: Good approach for mocking inquirer v12+, consider adding type safety.

The approach of importing the actual module and selectively overriding methods is robust and maintainable. However, consider these improvements:

 vi.mock('inquirer', async () => {
-  const actual = await vi.importActual('inquirer');
+  const actual = await vi.importActual<typeof import('inquirer')>('inquirer')
+    .catch(() => {
+      console.error('Failed to import inquirer');
+      return {};
+    });
   return {
     default: {
       ...actual,
       prompt: vi.fn(),
     },
   };
 });

80-88: Consider making mocks more flexible and explicit.

The mocks are well-structured, but could be improved for better testing flexibility:

 vi.mock('../askForTalawaApiUrl/askForTalawaApiUrl', () => ({
   askForTalawaApiUrl: vi
     .fn()
-    .mockResolvedValue('https://talawa-api.example.com'),
+    .mockResolvedValue(process.env.TEST_API_URL || 'https://talawa-api.example.com'),
 }));

 vi.mock('../updateEnvFile/updateEnvFile', () => ({
-  default: vi.fn(),
+  default: vi.fn().mockResolvedValue(undefined),
 }));

90-106: Enhance test coverage with assertions and edge cases.

While the tests cover the basic flows, consider these improvements:

 describe('askAndUpdateTalawaApiUrl', () => {
   test('should proceed with API setup when user confirms', async () => {
+    const mockUpdateEnvFile = vi.fn().mockResolvedValue(undefined);
+    vi.mock('../updateEnvFile/updateEnvFile', () => ({
+      default: mockUpdateEnvFile,
+    }));
+
     vi.spyOn(inquirer, 'prompt')
-      .mockResolvedValueOnce({ shouldSetTalawaApiUrlResponse: true }) // ✅ Covers line 35
+      .mockResolvedValueOnce({ shouldSetTalawaApiUrlResponse: true })
       .mockResolvedValueOnce({ dockerAppPort: '4321' });

     await expect(askAndUpdateTalawaApiUrl()).resolves.not.toThrow();
+    expect(mockUpdateEnvFile).toHaveBeenCalled();
   });

   test('should skip API setup when user declines', async () => {
+    const mockUpdateEnvFile = vi.fn().mockResolvedValue(undefined);
+    vi.mock('../updateEnvFile/updateEnvFile', () => ({
+      default: mockUpdateEnvFile,
+    }));
+
     vi.spyOn(inquirer, 'prompt').mockResolvedValueOnce({
       shouldSetTalawaApiUrlResponse: false,
     });

     await expect(askAndUpdateTalawaApiUrl()).resolves.not.toThrow();
+    expect(mockUpdateEnvFile).not.toHaveBeenCalled();
   });
+
+  test('should handle errors from askForTalawaApiUrl', async () => {
+    vi.spyOn(inquirer, 'prompt')
+      .mockResolvedValueOnce({ shouldSetTalawaApiUrlResponse: true });
+
+    const error = new Error('API URL validation failed');
+    vi.mock('../askForTalawaApiUrl/askForTalawaApiUrl', () => ({
+      askForTalawaApiUrl: vi.fn().mockRejectedValue(error),
+    }));
+
+    await expect(askAndUpdateTalawaApiUrl()).rejects.toThrow(error);
+  });
 });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8dd9294 and 6d947ad.

📒 Files selected for processing (1)
  • src/setup/askForDocker/askForDocker.spec.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)

@palisadoes palisadoes merged commit 232faf3 into PalisadoesFoundation:develop-postgres Feb 8, 2025
18 of 19 checks passed
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