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: css support crossorigin #50

Merged
merged 3 commits into from
Jan 23, 2025

Conversation

WynterDing
Copy link
Contributor

@WynterDing WynterDing commented Jan 22, 2025

Support cross-origin for style

Summary by CodeRabbit

  • New Features
    • Enhanced stylesheet and script loading with configurable cross-origin settings.
    • Added support for dynamically setting crossorigin attribute for external resources.
  • Tests
    • Expanded test coverage to verify the inclusion of the crossorigin attribute in generated HTML for styles and scripts.

Copy link

coderabbitai bot commented Jan 22, 2025

Walkthrough

The changes in lib/assets_context.js focus on enhancing the Assets class's getStyle and getScript methods by introducing a crossorigin parameter. This modification allows dynamic configuration of the crossorigin attribute for stylesheet and script elements, providing more flexibility in handling cross-origin resource sharing (CORS) when loading external resources.

Changes

File Change Summary
lib/assets_context.js - Updated linkTpl function signature to include crossorigin parameter
- Updated scriptTpl function signature to include crossorigin parameter
- Enhanced getStyle and getScript methods to support dynamic crossorigin attribute configuration
test/assets.test.js - Added assertions to check for the presence of the crossorigin attribute in generated styles and scripts

Poem

🐰 Hop, hop, through the code's domain,
CORS barriers now we'll break and tame!
Crossorigin dancing, scripts take flight,
Assets loading with newfound might.
A rabbit's web magic, clean and bright! 🌐

✨ 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

@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 comments (1)
lib/assets_context.js (1)

Line range hint 44-47: Enhance crossorigin attribute handling for better compatibility.

The current implementation only adds the crossorigin attribute without its value. For better compatibility and security, it should support the standard values 'anonymous' and 'use-credentials'.

-  return '<script' + (crossorigin ? ' crossorigin' : '') + ` src="${url}"></script>`;
+  const crossAttr = crossorigin === true ? ' crossorigin="anonymous"' :
+    (crossorigin ? ` crossorigin="${crossorigin}"` : '');
+  return '<script' + crossAttr + ` src="${url}"></script>`;
🧹 Nitpick comments (1)
lib/assets_context.js (1)

Line range hint 15-15: Add validation for crossorigin configuration.

The crossorigin attribute can be a boolean or accept specific string values ('anonymous' or 'use-credentials'). Consider adding validation to ensure the configured value is valid.

this.config = ctx.app.config.assets;
+ // Validate crossorigin value
+ if (this.config.crossorigin !== undefined && 
+     this.config.crossorigin !== true &&
+     this.config.crossorigin !== 'anonymous' &&
+     this.config.crossorigin !== 'use-credentials') {
+   throw new Error('Invalid crossorigin value. Must be true, "anonymous", or "use-credentials"');
+ }
this.crossorigin = this.config.crossorigin;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a4fd2b and 2543b0f.

📒 Files selected for processing (1)
  • lib/assets_context.js (1 hunks)
🔇 Additional comments (1)
lib/assets_context.js (1)

Line range hint 58-72: Consider URL sanitization for security.

While the getURL method validates URL format, it doesn't sanitize the URLs. When using the crossorigin attribute with external resources, it's important to ensure URLs are properly sanitized to prevent XSS attacks.

Consider adding URL sanitization:

  if (urlpath.startsWith('http://') || urlpath.startsWith('https://')) {
+   // Sanitize external URLs
+   try {
+     const url = new URL(urlpath);
+     urlpath = url.toString();
+   } catch (e) {
+     throw new Error(`Invalid URL: ${urlpath}`);
+   }
    return urlpath;
  }

Let's verify the current URL handling in the codebase:

lib/assets_context.js Show resolved Hide resolved
@fengmk2 fengmk2 self-assigned this Jan 22, 2025
@fengmk2
Copy link
Member

fengmk2 commented Jan 22, 2025

Nice feature, can you add a unit test for this change?

@WynterDing WynterDing closed this Jan 23, 2025
@WynterDing WynterDing reopened this Jan 23, 2025
@WynterDing
Copy link
Contributor Author

Nice feature, can you add a unit test for this change?

Wait a moment, I'll add it.

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)
test/assets.test.js (1)

557-558: Enhance test coverage for crossorigin attribute.

While the basic functionality is tested, consider adding the following test cases for more comprehensive coverage:

  1. Verify the actual value of the crossorigin attribute
  2. Test when crossorigin is disabled/not configured
  3. Test with different crossorigin values (e.g., 'anonymous', 'use-credentials')
 const style = ctx.helper.assets.getStyle();
-assert(style.includes('crossorigin'));
-assert(script.includes('crossorigin'));
+assert(style.includes('crossorigin="anonymous"'), 'Style should have crossorigin="anonymous"');
+assert(script.includes('crossorigin="anonymous"'), 'Script should have crossorigin="anonymous"');
+
+// Test when crossorigin is disabled
+mock(app.config.assets, 'crossorigin', false);
+const styleWithoutCrossorigin = ctx.helper.assets.getStyle();
+const scriptWithoutCrossorigin = ctx.helper.assets.getScript();
+assert(!styleWithoutCrossorigin.includes('crossorigin'), 'Style should not have crossorigin when disabled');
+assert(!scriptWithoutCrossorigin.includes('crossorigin'), 'Script should not have crossorigin when disabled');
+
+// Test with use-credentials
+mock(app.config.assets, 'crossorigin', 'use-credentials');
+const styleWithCredentials = ctx.helper.assets.getStyle();
+const scriptWithCredentials = ctx.helper.assets.getScript();
+assert(styleWithCredentials.includes('crossorigin="use-credentials"'), 'Style should have crossorigin="use-credentials"');
+assert(scriptWithCredentials.includes('crossorigin="use-credentials"'), 'Script should have crossorigin="use-credentials"');
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2543b0f and d3cc65c.

📒 Files selected for processing (2)
  • lib/assets_context.js (2 hunks)
  • test/assets.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/assets_context.js
🔇 Additional comments (1)
test/assets.test.js (1)

Line range hint 546-562: Verify test configuration in the fixture app.

The test relies on configuration from the 'apps/crossorigin' fixture. Let's verify its setup:

✅ Verification successful

Test configuration in the crossorigin fixture app is properly set up

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the configuration in the crossorigin fixture app

echo "Checking config.default.js for crossorigin configuration..."
cat test/fixtures/apps/crossorigin/config/config.default.js

echo -e "\nChecking package.json for dependencies..."
cat test/fixtures/apps/crossorigin/package.json

Length of output: 694

@WynterDing
Copy link
Contributor Author

@fengmk2 PTAL

Copy link
Member

@fengmk2 fengmk2 left a comment

Choose a reason for hiding this comment

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

LGTM

@fengmk2 fengmk2 merged commit bbb2794 into eggjs:master Jan 23, 2025
13 of 16 checks passed
fengmk2 pushed a commit that referenced this pull request Jan 23, 2025
[skip ci]

## [1.10.0](v1.9.0...v1.10.0) (2025-01-23)

### Features

* css support crossorigin ([#50](#50)) ([bbb2794](bbb2794))
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.

2 participants