Skip to content

Conversation

@xpdota
Copy link
Contributor

@xpdota xpdota commented Nov 3, 2024

Fixes #29

I can't fully test, since it seems that some of the tests are broken on Windows as they expect a unix-style path, but I can confirm that it resolves the immediate issue. Beasties.readFile() only takes a single argument, which is the filename.

Summary by CodeRabbit

  • New Features

    • Improved handling of CSS assets within the plugin.
    • Enhanced logging for better traceability of asset management.
    • Added a new HTML fixture for testing external stylesheet access.
  • Bug Fixes

    • Updated error handling for missing stylesheets, including clearer warning messages.
  • Tests

    • Introduced a new test suite for verifying file system access functionality.

@coderabbitai
Copy link

coderabbitai bot commented Nov 3, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request focus on the getCssAsset method of the BeastiesWebpackPlugin class. The method's readFile call has been simplified from two arguments to one, maintaining existing error handling. Additionally, the checkInlineThreshold method now includes improved logging for missing style assets. A new HTML fixture has been added for testing, along with a new test suite to verify file system access functionality.

Changes

File Path Change Summary
packages/beasties-webpack-plugin/src/index.js Updated getCssAsset to simplify readFile call to one argument; enhanced logging in checkInlineThreshold.
packages/beasties-webpack-plugin/test/fixtures/fs-access/index.html Added new HTML fixture for testing stylesheet access from the filesystem.
packages/beasties-webpack-plugin/test/index.test.ts Introduced new test suite for verifying file system access functionality.

Assessment against linked issues

Objective Addressed Explanation
Fix the stylesheet location issue (#29)
Ensure proper error logging for missing stylesheets

Possibly related PRs

Poem

🐇
In the code where stylesheets hide,
A rabbit hops with joy and pride.
With logs so clear and paths so bright,
The BeastiesPlugin now takes flight!
No more lost styles, just smooth delight!
🐇


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

🧹 Outside diff range and nitpick comments (2)
packages/beasties-webpack-plugin/src/index.js (2)

Line range hint 178-186: Consider enhancing path resolution logging.

While the error handling is solid, adding debug logs for path resolution steps would help troubleshoot future path-related issues.

Consider adding debug logging:

+        this.logger.debug(`Resolving stylesheet path: ${filename}`)
         sheet = await this.readFile(filename)
         this.logger.warn(
           `Stylesheet "${relativePath}" not found in assets, but a file was located on disk.${
             this.options.pruneSource
               ? ' This means pruneSource will not be applied.'
               : ''
           }`,
         )

Line range hint 133-186: Consider extracting path normalisation logic.

The path normalisation logic in getCssAsset is complex and could benefit from being extracted into a separate method for better maintainability and testing.

Consider refactoring like this:

+  /**
+   * Normalises asset paths for cross-platform compatibility
+   * @private
+   */
+  normaliseAssetPath(href, publicPath, outputPath) {
+    let normalizedPath = href.replace(/^\//, '')
+    const pathPrefix = `${(publicPath || '').replace(/(^\/|\/$)/g, '')}/`
+    if (normalizedPath.indexOf(pathPrefix) === 0) {
+      normalizedPath = normalizedPath
+        .substring(pathPrefix.length)
+        .replace(/^\//, '')
+    }
+    return path.resolve(outputPath, normalizedPath)
+  }

   async getCssAsset(href, style) {
     const outputPath = this.options.path
     const publicPath = this.options.publicPath

-    let normalizedPath = href.replace(/^\//, '')
-    const pathPrefix = `${(publicPath || '').replace(/(^\/|\/$)/g, '')}/`
-    if (normalizedPath.indexOf(pathPrefix) === 0) {
-      normalizedPath = normalizedPath
-        .substring(pathPrefix.length)
-        .replace(/^\//, '')
-    }
-    const filename = path.resolve(outputPath, normalizedPath)
+    const filename = this.normaliseAssetPath(href, publicPath, outputPath)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 769c574 and dee3b5d.

📒 Files selected for processing (1)
  • packages/beasties-webpack-plugin/src/index.js (1 hunks)
🔇 Additional comments (1)
packages/beasties-webpack-plugin/src/index.js (1)

178-178: LGTM! This change fixes the Windows path handling issue.

The simplified readFile call now correctly handles file paths across different operating systems. The removal of the unnecessary compilation argument aligns with the API design and resolves issue #29.

@codspeed-hq
Copy link

codspeed-hq bot commented Nov 12, 2024

CodSpeed Performance Report

Merging #30 will degrade performances by 48.53%

Comparing xpdota:fix-file-paths (01495ed) with main (caa5f8e)

Summary

⚡ 1 improvements
❌ 1 regressions
✅ 6 untouched benchmarks

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Benchmarks breakdown

Benchmark main xpdota:fix-file-paths Change
does not encode HTML 5.3 ms 1.1 ms ×5
run on HTML file 4.9 ms 9.5 ms -48.53%

@codecov-commenter
Copy link

codecov-commenter commented Nov 12, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.73%. Comparing base (769c574) to head (a0881e2).
Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #30      +/-   ##
==========================================
+ Coverage   83.70%   84.73%   +1.02%     
==========================================
  Files           7        7              
  Lines        1166     1166              
  Branches      269      271       +2     
==========================================
+ Hits          976      988      +12     
+ Misses        190      178      -12     

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

Copy link
Owner

@danielroe danielroe left a comment

Choose a reason for hiding this comment

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

thank you - this looks good to me (seems to have been introduced in GoogleChromeLabs/critters#61)

one more thing though: could you describe how to create a minimal reproduction? 🙏 I'll then convert that into a regression test + get it merged

@xpdota
Copy link
Contributor Author

xpdota commented Nov 12, 2024

Here you go: https://github.com/xpdota/beasties-bug-29-repro

npm run build should result in dist/index.html having some CSS injected, but the current release version results in nothing being injected.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dee3b5d and a0881e2.

⛔ Files ignored due to path filters (1)
  • packages/beasties-webpack-plugin/test/fixtures/fs-access/dist/style.css is excluded by !**/dist/**
📒 Files selected for processing (2)
  • packages/beasties-webpack-plugin/test/fixtures/fs-access/index.html (1 hunks)
  • packages/beasties-webpack-plugin/test/index.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/beasties-webpack-plugin/test/fixtures/fs-access/index.html

Comment on lines 201 to 209
describe('accessing file system', () => {
it('works', async () => {
const output = await compileToHtml('fs-access', configure, {
path: './dist/',
publicPath: '',
})
expect(output.html).toMatch(/\.foo/)
})
})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for filesystem path handling

The current test suite could benefit from more comprehensive coverage, particularly given the Windows path handling issues mentioned in PR #29. Consider adding these test cases:

  1. Platform-specific path testing
  2. Error handling scenarios
  3. Various path formats (relative, absolute)

Here's a suggested enhancement:

 describe('accessing file system', () => {
   it('works', async () => {
     const output = await compileToHtml('fs-access', configure, {
       path: './dist/',
       publicPath: '',
     })
     expect(output.html).toMatch(/\.foo/)
   })
+
+  it('handles Windows-style paths', async () => {
+    const output = await compileToHtml('fs-access', configure, {
+      path: '.\\dist\\',
+      publicPath: '',
+    })
+    expect(output.html).toMatch(/\.foo/)
+  })
+
+  it('handles absolute paths', async () => {
+    const output = await compileToHtml('fs-access', configure, {
+      path: path.resolve(__dirname, 'dist'),
+      publicPath: '',
+    })
+    expect(output.html).toMatch(/\.foo/)
+  })
+
+  it('handles missing stylesheet gracefully', async () => {
+    await expect(compileToHtml('fs-access', configure, {
+      path: './non-existent/',
+      publicPath: '',
+    })).rejects.toThrow()
+  })
 })

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 203 to 206
const output = await compileToHtml('fs-access', configure, {
path: './dist/',
publicPath: '',
})
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Hard-coded Path Separators Detected

The path handling implementation includes hard-coded path separators which may not resolve correctly across different platforms.

  • Affected files:
    • packages/beasties/test/beasties.test.ts
    • packages/beasties/test/beasties.bench.ts
    • packages/beasties/test/security.test.ts
    • packages/beasties/src/util.ts
    • packages/beasties-webpack-plugin/test/index.test.ts
    • packages/beasties-webpack-plugin/test/standalone.test.ts
    • packages/beasties-webpack-plugin/test/helpers.ts
    • packages/beasties/src/types.ts
    • packages/beasties/src/index.d.ts
    • packages/beasties/src/dom.ts
    • packages/beasties/src/index.ts
    • packages/beasties/src/css.ts
🔗 Analysis chain

Verify path handling implementation

Let's verify that the path handling implementation correctly resolves paths across different platforms.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for platform-specific path handling in the codebase

# Look for path handling logic
echo "Searching for path handling code..."
rg -l "path\.(resolve|join|normalize)" --type ts

# Check for Windows-specific path handling
echo "Checking for Windows path handling..."
rg -l "(\\\\|win32|process\.platform)" --type ts

# Look for filesystem operations
echo "Checking filesystem operations..."
ast-grep --pattern 'fs.$_($$$)'

Length of output: 1666


Script:

#!/bin/bash
# Description: Inspect path construction and platform-specific logic in the codebase

# Find implementations using path.resolve, path.join, path.normalize
echo "Searching for path construction implementations..."
ast-grep --pattern 'path.$_(...)' --type ts

# Check for hard-coded path separators
echo "Checking for hard-coded path separators..."
rg -l '["\']/["\']' --type ts

# Verify conditional logic based on process.platform
echo "Searching for platform-specific conditional statements..."
rg 'if\s*\(\s*process\.platform\s*===' --type ts

Length of output: 526


Script:

#!/bin/bash
# Description: Inspect path construction and platform-specific logic in the codebase

# Find implementations using path.resolve, path.join, path.normalize
echo "Searching for path construction implementations..."
ast-grep --pattern 'path.$_(...)' -- --type ts

# Check for hard-coded path separators
echo "Checking for hard-coded path separators..."
rg -l '["/\\\']' --type ts

# Verify conditional logic based on process.platform
echo "Searching for platform-specific conditional statements..."
rg 'if\s*\(\s*process\.platform\s*===' --type ts

Length of output: 453


Script:

#!/bin/bash
# Description: Inspect path construction and platform-specific logic in the codebase

# Find implementations using path.resolve, path.join, path.normalize
echo "Searching for path construction implementations..."
ast-grep --pattern 'path.$_($_)' --lang typescript

# Check for hard-coded path separators
echo "Checking for hard-coded path separators..."
rg -l '["/\\\\\']' --type ts

# Verify conditional logic based on process.platform
echo "Searching for platform-specific conditional statements..."
rg 'if\s*\(\s*process\.platform\s*===' --type ts

Length of output: 549


Script:

#!/bin/bash
# Description: Inspect path construction and platform-specific logic in the codebase

# Find implementations using path.resolve, path.join, path.normalize
echo "Searching for path construction implementations..."
ast-grep --pattern 'path.$_($_)' --lang typescript

# Check for hard-coded path separators
echo "Checking for hard-coded path separators..."
rg -l "['\"\\\\/]" --type ts

# Verify conditional logic based on process.platform
echo "Searching for platform-specific conditional statements..."
rg 'if\s*\(\s*process\.platform\s*===' --type ts

Length of output: 1123

@danielroe danielroe merged commit c4da3ce into danielroe:main Nov 12, 2024
5 of 6 checks passed
@danielroe
Copy link
Owner

thank you!

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.

"Unable to locate stylesheet" with WebPack plugin

3 participants