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

Update Care Apps Setup; API URL on window #9883

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open

Conversation

gigincg
Copy link
Member

@gigincg gigincg commented Jan 10, 2025

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • Configuration Updates

    • Modified environment variable REACT_ENABLED_APPS to use local development setup
    • Updated global window configuration to support API URL access
    • Improved remote module configuration parsing logic
  • Development Improvements

    • Simplified remote configuration handling
    • Enhanced modularity of configuration management scripts

@gigincg gigincg requested a review from a team as a code owner January 10, 2025 14:44
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

This pull request introduces changes to environment configuration and application setup across multiple files. The modifications focus on enhancing the handling of remote application configurations, particularly for the REACT_ENABLED_APPS environment variable. The changes include updating the .env file to use a local development setup, creating a new parseRemoteConfig function to handle configuration parsing, adding a global CARE_API_URL to the window interface, and refactoring the Vite configuration to support more flexible remote module configurations.

Changes

File Change Summary
.env Updated REACT_ENABLED_APPS from production URL to local development setup
scripts/setup-care-apps.ts Added ParsedRemoteConfig interface and parseRemoteConfig function for parsing app configurations
src/index.tsx Extended Window interface to include CARE_API_URL property
vite.config.mts Removed getPluginDependencies, added parseRemoteConfig function, simplified remote configuration handling

Possibly related PRs

Suggested Labels

needs review, tested

Suggested Reviewers

  • rithviknishad
  • khavinshankar
  • Jacobjeevan

Poem

🐰 A config rabbit hops with glee,
Parsing URLs with agility!
Local dev, remote dreams take flight,
Environment settings burning bright,
Code refactored, clean and light! 🚀

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.

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

netlify bot commented Jan 10, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 598433e
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6781323f7c929800089e0bab
😎 Deploy Preview https://deploy-preview-9883--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 598433e
Status: ✅  Deploy successful!
Preview URL: https://c9ac5317.care-fe.pages.dev
Branch Preview URL: https://care-apps-setup.care-fe.pages.dev

View logs

Copy link

cypress bot commented Jan 10, 2025

CARE    Run #4244

Run Properties:  status check failed Failed #4244  •  git commit 598433e970: Update Care Apps Setup; API URL on window
Project CARE
Branch Review care_apps_setup
Run status status check failed Failed #4244
Run duration 03m 48s
Commit git commit 598433e970: Update Care Apps Setup; API URL on window
Committer Gigin George
View all properties for this run ↗︎

Test results
Tests that failed  Failures 5
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 1
Tests that passed  Passing 0
View all changes introduced in this branch ↗︎

Tests for review

Failed  facility_spec/facility_creation.cy.ts • 1 failed test

View Output

Test Artifacts
Facility Management > Create a new facility using the admin role Test Replay Screenshots
Failed  patient_spec/patient_search.cy.ts • 1 failed test

View Output

Test Artifacts
Patient Search > search patient with phone number and verifies details Test Replay Screenshots
Failed  login_spec/loginpage.cy.ts • 3 failed tests

View Output

Test Artifacts
Login Page > should successfully login with admin credentials Test Replay Screenshots
Login Page > should display login form elements Test Replay Screenshots
Login Page > should show validation errors for empty fields Test Replay Screenshots

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

🧹 Nitpick comments (5)
vite.config.mts (1)

68-71: Consider extracting ParsedRemoteConfig to a shared module

The ParsedRemoteConfig interface is defined both here and in scripts/setup-care-apps.ts. To promote reusability and maintain consistency, consider moving this interface to a shared module that can be imported where needed.

src/index.tsx (1)

10-14: Avoid augmenting the global Window interface

Augmenting the global Window interface by adding CARE_API_URL may lead to potential conflicts and make the code harder to maintain. Consider using a configuration module or context provider to manage and distribute environment variables within your application.

scripts/setup-care-apps.ts (2)

19-23: Extract ParsedRemoteConfig to a shared module

The ParsedRemoteConfig interface is also defined in vite.config.mts. To maintain consistency and reduce duplication, consider moving this interface to a shared module that both scripts can import.


73-77: Use a reliable utility for converting repo names to camelCase

The current method for converting repository names to camelCase may not handle all edge cases, especially with complex names. Consider using a well-tested utility like lodash.camelCase to ensure consistent and accurate conversion.

Apply this diff to implement the utility:

+import camelCase from "lodash.camelcase";

 ...

 const plugins = process.env.REACT_ENABLED_APPS.split(",").map((app) => {
   const { repo } = parseRemoteConfig(app);
   return {
     repo,
-    // Convert repo name to camelCase for import
-    camelCaseName: repo
-      .replace(/[-_]/g, "")
-      .replace(/\b\w/g, (char, index) =>
-        index === 0 ? char.toLowerCase() : char.toUpperCase(),
-      ),
+    camelCaseName: camelCase(repo),
   };
 });

Ensure that you have lodash.camelcase installed in your dependencies.

.env (1)

17-17: Consider adding development setup documentation.

The change to use localhost:4173 requires additional setup context for developers.

Consider:

  1. Document port requirements in README.md
  2. Add validation for port availability during setup
  3. Include fallback configuration for CI/CD environments
  4. Document the new format specification for remote apps configuration

Would you like me to help draft this documentation?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 86eba9b and 598433e.

📒 Files selected for processing (4)
  • .env (1 hunks)
  • scripts/setup-care-apps.ts (1 hunks)
  • src/index.tsx (1 hunks)
  • vite.config.mts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (3)
src/index.tsx (1)

17-17: Ensure safe exposure of environment variables

Assigning import.meta.env.REACT_CARE_API_URL directly to window.CARE_API_URL may expose sensitive information to the client-side, which could be a security concern. Verify that REACT_CARE_API_URL does not contain any sensitive data and that exposing it complies with security policies.

.env (2)

17-17: Validate development environment setup.

The use of a fixed port (4173) for local development could lead to port conflicts.

Let's check for potential port conflicts in the codebase:


17-17: Verify the new remote app configuration format.

The format change from URL-based to host-based configuration (@localhost:4173) appears to be a breaking change. This could impact other environments and developers.

Let's verify the usage and documentation of this new format:

Comment on lines +74 to +97
function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
// Handle custom URLs (both localhost and custom hosted)
if (appConfig.includes("@")) {
const [package_, url] = appConfig.split("@");
const [org, repo] = package_.split("/");

// Check if the module is an entry point
if (modInfo.isEntry) {
return true;
}
// Add appropriate protocol based on whether it's localhost
const protocol = url.includes("localhost") ? "http://" : "https://";
const fullUrl = url.startsWith("http") ? url : `${protocol}${url}`;

// Check all static importers
for (const importerId of modInfo.importers) {
if (isStaticallyImportedByEntry(getModuleInfo, importerId, visited)) {
return true;
}
return {
url: `${fullUrl}/assets/remoteEntry.js`,
org,
repo,
};
}

return false;
// Handle GitHub Pages URLs
const [org, repo] = appConfig.split("/");
return {
url: `https://${org}.github.io/${repo}/assets/remoteEntry.js`,
org,
repo,
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for invalid appConfig formats in parseRemoteConfig

The parseRemoteConfig function assumes that appConfig is always in the correct format ("org/repo" or "org/repo@url"). If appConfig is malformed or missing expected delimiters, the destructuring assignments may result in undefined values for org, repo, or url, leading to runtime errors.

Apply this diff to add validation checks:

 function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
+  if (!appConfig.includes("/")) {
+    throw new Error(`Invalid app configuration format: ${appConfig}. Expected 'org/repo' or 'org/repo@url'.`);
+  }

   // Handle custom URLs (both localhost and custom hosted)
   if (appConfig.includes("@")) {
     const [package_, url] = appConfig.split("@");
     const [org, repo] = package_.split("/");
+    if (!org || !repo || !url) {
+      throw new Error(`Invalid custom URL configuration: ${appConfig}. Expected 'org/repo@url'.`);
+    }

     // Add appropriate protocol based on whether it's localhost
     const protocol = url.includes("localhost") ? "http://" : "https://";
     const fullUrl = url.startsWith("http") ? url : `${protocol}${url}`;

     return {
       url: `${fullUrl}/assets/remoteEntry.js`,
       org,
       repo,
     };
   }

   // Handle GitHub Pages URLs
   const [org, repo] = appConfig.split("/");
+  if (!org || !repo) {
+    throw new Error(`Invalid GitHub Pages configuration: ${appConfig}. Expected 'org/repo'.`);
+  }

   return {
     url: `https://${org}.github.io/${repo}/assets/remoteEntry.js`,
     org,
     repo,
   };
 }
📝 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
function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
// Handle custom URLs (both localhost and custom hosted)
if (appConfig.includes("@")) {
const [package_, url] = appConfig.split("@");
const [org, repo] = package_.split("/");
// Check if the module is an entry point
if (modInfo.isEntry) {
return true;
}
// Add appropriate protocol based on whether it's localhost
const protocol = url.includes("localhost") ? "http://" : "https://";
const fullUrl = url.startsWith("http") ? url : `${protocol}${url}`;
// Check all static importers
for (const importerId of modInfo.importers) {
if (isStaticallyImportedByEntry(getModuleInfo, importerId, visited)) {
return true;
}
return {
url: `${fullUrl}/assets/remoteEntry.js`,
org,
repo,
};
}
return false;
// Handle GitHub Pages URLs
const [org, repo] = appConfig.split("/");
return {
url: `https://${org}.github.io/${repo}/assets/remoteEntry.js`,
org,
repo,
};
function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
if (!appConfig.includes("/")) {
throw new Error(`Invalid app configuration format: ${appConfig}. Expected 'org/repo' or 'org/repo@url'.`);
}
// Handle custom URLs (both localhost and custom hosted)
if (appConfig.includes("@")) {
const [package_, url] = appConfig.split("@");
const [org, repo] = package_.split("/");
if (!org || !repo || !url) {
throw new Error(`Invalid custom URL configuration: ${appConfig}. Expected 'org/repo@url'.`);
}
// Add appropriate protocol based on whether it's localhost
const protocol = url.includes("localhost") ? "http://" : "https://";
const fullUrl = url.startsWith("http") ? url : `${protocol}${url}`;
return {
url: `${fullUrl}/assets/remoteEntry.js`,
org,
repo,
};
}
// Handle GitHub Pages URLs
const [org, repo] = appConfig.split("/");
if (!org || !repo) {
throw new Error(`Invalid GitHub Pages configuration: ${appConfig}. Expected 'org/repo'.`);
}
return {
url: `https://${org}.github.io/${repo}/assets/remoteEntry.js`,
org,
repo,
};
}

Comment on lines +41 to +60
function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
// Handle custom URLs (both localhost and custom hosted)
if (appConfig.includes("@")) {
const [package_] = appConfig.split("@");
const [org, repo] = package_.split("/");
return {
url: "", // URL not needed for plugin setup
org,
repo,
};
}

// Handle GitHub Pages URLs
const [org, repo] = appConfig.split("/");
return {
url: "", // URL not needed for plugin setup
org,
repo,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for malformed appConfig in parseRemoteConfig

The parseRemoteConfig function assumes a specific format for appConfig. If the input is malformed, destructuring may result in undefined values for org and repo. This can cause unexpected behavior or runtime errors.

Apply this diff to include validation:

 function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
+  if (!appConfig.includes("/")) {
+    throw new Error(`Invalid app configuration format: ${appConfig}. Expected 'org/repo' or 'org/repo@url'.`);
+  }

   // Handle custom URLs (both localhost and custom hosted)
   if (appConfig.includes("@")) {
     const [package_] = appConfig.split("@");
     const [org, repo] = package_.split("/");
+    if (!org || !repo) {
+      throw new Error(`Invalid custom URL configuration: ${appConfig}. Expected 'org/repo@url'.`);
+    }

     return {
       url: "", // URL not needed for plugin setup
       org,
       repo,
     };
   }

   // Handle GitHub Pages URLs
   const [org, repo] = appConfig.split("/");
+  if (!org || !repo) {
+    throw new Error(`Invalid GitHub Pages configuration: ${appConfig}. Expected 'org/repo'.`);
+  }

   return {
     url: "", // URL not needed for plugin setup
     org,
     repo,
   };
 }
📝 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
function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
// Handle custom URLs (both localhost and custom hosted)
if (appConfig.includes("@")) {
const [package_] = appConfig.split("@");
const [org, repo] = package_.split("/");
return {
url: "", // URL not needed for plugin setup
org,
repo,
};
}
// Handle GitHub Pages URLs
const [org, repo] = appConfig.split("/");
return {
url: "", // URL not needed for plugin setup
org,
repo,
};
}
function parseRemoteConfig(appConfig: string): ParsedRemoteConfig {
if (!appConfig.includes("/")) {
throw new Error(`Invalid app configuration format: ${appConfig}. Expected 'org/repo' or 'org/repo@url'.`);
}
// Handle custom URLs (both localhost and custom hosted)
if (appConfig.includes("@")) {
const [package_] = appConfig.split("@");
const [org, repo] = package_.split("/");
if (!org || !repo) {
throw new Error(`Invalid custom URL configuration: ${appConfig}. Expected 'org/repo@url'.`);
}
return {
url: "", // URL not needed for plugin setup
org,
repo,
};
}
// Handle GitHub Pages URLs
const [org, repo] = appConfig.split("/");
if (!org || !repo) {
throw new Error(`Invalid GitHub Pages configuration: ${appConfig}. Expected 'org/repo'.`);
}
return {
url: "", // URL not needed for plugin setup
org,
repo,
};
}

@@ -14,4 +14,4 @@ ESLINT_NO_DEV_ERRORS=true
CARE_CDN_URL="https://egov-s3-facility-10bedicu.s3.amazonaws.com https://egov-s3-patient-data-10bedicu.s3.amazonaws.com http://localhost:4566"
REACT_ALLOWED_LOCALES="en,hi,ta,ml,mr,kn"

REACT_ENABLED_APPS="https://care-scribe-fe.pages.dev|ohcnetwork/care_scribe_fe"
REACT_ENABLED_APPS="ohcnetwork/care_scribe_fe@localhost:4173"
Copy link
Member

Choose a reason for hiding this comment

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

other than this, lgtm

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