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

fix: updated docs about isolated declarations, moved sourcemapsPlugin… #63

Merged
merged 6 commits into from
Nov 17, 2024

Conversation

prisis
Copy link
Contributor

@prisis prisis commented Nov 17, 2024

… to a different position

Summary by CodeRabbit

  • New Features

    • Added documentation on "Isolated declaration types" for TypeScript 5.5 and above, highlighting performance benefits and configuration details.
    • Updated the configuration to include support for the isolated declaration transformer in the Rollup build process.
    • Enhanced functionality for adding CSS loaders, including user prompts and improved handling of Sass loaders and CSS minifiers.
  • Bug Fixes

    • Enhanced type safety for cssLoaderDependencies, clarifying its structure.
  • Documentation

    • Improved readability and organization of the README.md, including minor formatting adjustments.
    • Updated package.json files across examples to specify TypeScript version compatibility.
  • Chores

    • Streamlined management of Rollup plugins and source map generation for better configuration flexibility.

Copy link
Contributor

github-actions bot commented Nov 17, 2024

Thank you for following the naming conventions! 🙏

Copy link
Contributor

coderabbitai bot commented Nov 17, 2024

Walkthrough

The changes in this pull request include updates to the README.md for Visulima Packem, enhancing documentation about isolated declaration types in TypeScript 5.5 and higher. The configuration file packem.config.ts has been modified to include a new transformer for isolated declarations. Additionally, the cssLoaderDependencies constant in css-loader-dependencies.ts has been updated for type safety, and the get-rollup-options.ts file has been adjusted to manage Rollup plugins and source maps more effectively. Furthermore, several package.json files in example projects have been updated to reflect TypeScript version constraints.

Changes

File Path Change Summary
packages/packem/README.md - Added section on "Isolated declaration types" (TypeScript 5.5+).
- Updated features list for TypeScript version requirement.
- Expanded configuration section for isolated declaration transformer.
packages/packem/packem.config.ts - Added isolatedDeclarationTransformer to the configuration object in defineConfig.
- Updated typeScriptVersion from ">=5.0" to ">=5.5" in node10Compatibility.
packages/packem/src/commands/utils/css-loader-dependencies.ts - Updated type of cssLoaderDependencies to Record<string, string[]>.
packages/packem/src/rollup/get-rollup-options.ts - Added sourcemapsPlugin to plugins array.
- Updated logic for managing isolated declarations.
- Adjusted method signatures for getRollupOptions and getRollupDtsOptions.
examples/isolated-declarations-oxc/package.json - Updated typesVersions to ">=5.5" and changed types path to "./dist/index.d.cts".
examples/isolated-declarations-oxc/packem.config.ts - Added typeScriptVersion: ">=5.5" in rollup.node10Compatibility.
examples/isolated-declarations-swc/package.json - Updated typesVersions to ">=5.5" and changed types path to "./dist/index.d.cts".
examples/isolated-declarations-swc/packem.config.ts - Added typeScriptVersion: ">=5.5" in rollup.node10Compatibility.
examples/isolated-declarations-typescript/package.json - Updated typesVersions from ">=5.0" to ">=5.5" and removed previous entry for "*".
examples/isolated-declarations-typescript/packem.config.ts - Added typeScriptVersion: ">=5.5" in rollup.node10Compatibility.
packages/packem/package.json - Added types version mapping for >=5.5 in typesVersions section.
packages/packem/src/commands/add.ts - Enhanced createAddCommand function for CSS loaders, including user prompts and improved logic.
packages/packem/src/commands/init.ts - Updated createInitCommand to enhance type safety and user prompts for CSS loader dependencies.
packages/packem/tests/intigration/url.test.ts - Modified test suite for URL handling to maintain correct directory structure in expected output paths.

Possibly related PRs

🐰 "In the meadow, changes bloom,
With isolated types, there's more room.
Packem's config shines so bright,
CSS loaders, all just right.
Rollup dances, plugins play,
Happy coding, hip-hip-hooray!" 🌼

Warning

Rate limit exceeded

@prisis has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 3 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

Reviewing files that changed from the base of the PR and between 405a98b and ee0dbc6.


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

pkg-pr-new bot commented Nov 17, 2024

Open in Stackblitz

pnpm add https://pkg.pr.new/visulima/packem/@visulima/packem@63

commit: ee0dbc6

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

🧹 Outside diff range and nitpick comments (4)
packages/packem/src/commands/utils/css-loader-dependencies.ts (1)

1-1: LGTM! Type annotation improves type safety.

The addition of Record<string, string[]> type annotation enhances type safety and makes the structure of the dependencies mapping explicit.

Consider adding a JSDoc comment to document the purpose of this mapping, for example:

+/**
+ * Maps CSS preprocessors to their required npm dependencies.
+ * Used for automatic dependency installation when a preprocessor is configured.
+ */
const cssLoaderDependencies: Record<string, string[]> = {
packages/packem/packem.config.ts (1)

Line range hint 6-20: Consider adding configuration documentation.

The configuration now includes the isolatedDeclarationTransformer, but it might be helpful to add a comment explaining its purpose and requirements.

Consider adding a documentation comment:

 export default defineConfig({
     cjsInterop: true,
     externals: ["stylus", "less", "sass", "node-sass", "postcss", "lightningcss"],
     fileCache: true,
+    // Enable isolated declarations support (requires TypeScript >=5.5)
     isolatedDeclarationTransformer,
     rollup: {
packages/packem/README.md (2)

544-567: Consider enhancing the isolated declarations section.

While the section provides good information, it could benefit from:

  1. Adding specific performance metrics or benchmarks comparing isolated vs. non-isolated declarations
  2. Including a troubleshooting section for common issues
  3. Adding examples of when to use each supported transformer
 ### Isolated declaration types (in TypeScript 5.5)

 > Generating .d.ts files with the default `rollup-plugin-dts` is slow because the TypeScript compiler must perform costly type inference, but these files streamline type checking by removing unnecessary details, and while shipping raw TypeScript files could simplify workflows, it is impractical due to ecosystem assumptions and performance trade-offs, which isolated declarations aim to address.

 You need to choose of the supported transformer to use isolated declaration types.

 -   [oxc](https://github.com/oxc-project/oxc)
 -   [@swc/core](https://github.com/swc-project/swc)
 -   [typescript](https://github.com/microsoft/TypeScript)

 Default is `typescript`.

+### Performance Comparison
+
+Benchmark results comparing isolated vs. non-isolated declarations:
+- Build time: X% faster
+- Memory usage: Y% lower
+
+### Choosing a Transformer
+
+- **typescript**: Best for standard TypeScript projects
+- **@swc/core**: Optimized for large-scale projects
+- **oxc**: Experimental, offers fastest parsing
+
+### Troubleshooting
+
+Common issues and solutions when using isolated declarations:
+1. Issue: ...
+   Solution: ...
+2. Issue: ...
+   Solution: ...

 ```ts
 import { defineConfig } from "@visulima/packem/config";

870-883: Enhance transformer documentation with links and comparison.

The configuration section could be more helpful by:

  1. Adding direct links to each transformer's documentation
  2. Including a comparison table of transformer features
  3. Providing guidance on choosing the right transformer
 #### transformer

 You choose which one of the three supported transformer to use.

 -   [esbuild](https://github.com/evanw/esbuild)
 -   [@swc/core](https://github.com/swc-project/swc)
 -   [sucrase](https://github.com/alangpierce/sucrase)

+### Transformer Comparison
+
+| Feature | esbuild | @swc/core | sucrase |
+|---------|---------|-----------|----------|
+| Speed   | ⭐⭐⭐    | ⭐⭐       | ⭐        |
+| Config  | Simple  | Advanced  | Minimal  |
+| Size    | Large   | Medium    | Small    |
+
+### When to use each transformer:
+
+- **esbuild**: Best for production builds
+- **@swc/core**: Ideal for development
+- **sucrase**: Perfect for simple transformations
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8612ed8 and 81674b5.

📒 Files selected for processing (4)
  • packages/packem/README.md (3 hunks)
  • packages/packem/packem.config.ts (1 hunks)
  • packages/packem/src/commands/utils/css-loader-dependencies.ts (1 hunks)
  • packages/packem/src/rollup/get-rollup-options.ts (3 hunks)
🔇 Additional comments (4)
packages/packem/src/commands/utils/css-loader-dependencies.ts (1)

Line range hint 1-19: Verify package validity and completeness

Let's ensure all packages exist and check for any missing preprocessors or dependencies.

✅ Verification successful

Based on the verification results, I can now provide a final response:

All CSS preprocessor packages are valid and well-covered

All listed packages in cssLoaderDependencies exist on npm registry and the codebase shows comprehensive coverage of CSS preprocessing needs:

  • All core preprocessors are included: Less, Sass (with multiple implementations), Stylus, PostCSS
  • The PostCSS dependencies list is complete with all necessary modules for CSS modules functionality
  • The codebase usage patterns confirm the completeness of the dependencies through extensive imports and implementations
  • LightningCSS is correctly included as a modern CSS processor option
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify npm packages exist and check for common CSS preprocessors

# Check if all listed packages exist on npm
echo "Verifying package existence..."
packages=(
    "less"
    "lightningcss"
    "node-sass"
    "postcss"
    "postcss-load-config"
    "postcss-modules-extract-imports"
    "postcss-modules-local-by-default"
    "postcss-modules-scope"
    "postcss-modules-values"
    "postcss-value-parser"
    "icss-utils"
    "sass"
    "sass-embedded"
    "stylus"
)

for pkg in "${packages[@]}"; do
    if curl --silent "https://registry.npmjs.org/$pkg" | jq -e '.error' > /dev/null; then
        echo "❌ Package not found: $pkg"
    else
        echo "✅ Package exists: $pkg"
    fi
done

# Search for any CSS preprocessor imports in the codebase that might need dependencies
echo -e "\nSearching for potential missing preprocessors..."
rg -g '!node_modules' -g '*.{js,ts,json}' -i '(import|require).*\b(css|style|sass|less|stylus|postcss)\b'

Length of output: 23765

packages/packem/packem.config.ts (1)

3-3: Verify the transformer import usage across the codebase.

Let's ensure this new transformer is properly imported and used consistently.

✅ Verification successful

Let me check the actual usage and implementation to verify if the transformer is properly integrated.


Based on the gathered information, I can now provide a final response:

The transformer import is properly integrated and documented

The isolated declarations transformer is:

  • Correctly imported and used in the build pipeline
  • Well integrated with proper type definitions in types.ts
  • Properly documented in README.md with version requirements (TS 5.5+)
  • Used consistently across build, watch, and type generation processes
  • Has proper configuration options and examples
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other usages or references to the isolated declarations transformer

# Search for other potential uses of the transformer
rg -l "isolatedDeclarationTransformer|isolated-declarations-typescript-transformer"

# Check if the transformer is documented in any README or documentation files
rg -l "isolated declaration" -g "*.md"

Length of output: 755


Script:

#!/bin/bash
# Check the transformer implementation and its usage in build files
rg -A 5 "isolatedDeclarationTransformer" packages/packem/src/rollup/

# Check documentation
cat packages/packem/README.md | grep -A 10 "isolated declaration"

# Check configuration types
ast-grep --pattern 'interface $_ {
  $$$
  isolatedDeclarations?: $_
  $$$
}'

Length of output: 7969

packages/packem/README.md (1)

56-56: LGTM! Clear feature list addition.

The new feature is well-documented with the correct TypeScript version requirement.

packages/packem/src/rollup/get-rollup-options.ts (1)

530-540: 🛠️ Refactor suggestion

Verify TypeScript version compatibility for isolated declarations.

The isolated declarations feature requires TypeScript 5.5 or higher. However, there's no version check in the code to ensure compatibility.

Let's verify the TypeScript version requirements:

Add a version check before enabling isolated declarations:

if (context.options.declaration &&
    context.options.rollup.isolatedDeclarations &&
    context.options.isolatedDeclarationTransformer) {
  // Add version check
  const tsVersion = getTsVersion(); // implement this helper
  if (semver.lt(tsVersion, '5.5.0')) {
    context.logger.warn('Isolated declarations require TypeScript >= 5.5');
    return;
  }
  
  isolatedDeclarationsPlugin(
    join(context.options.rootDir, context.options.sourceDir),
    context.options.isolatedDeclarationTransformer,
    context.options.declaration,
    Boolean(context.options.rollup.cjsInterop),
    context.options.rollup.isolatedDeclarations,
  )
}

packages/packem/packem.config.ts Show resolved Hide resolved
Copy link

socket-security bot commented Nov 17, 2024

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/vite@5.4.11 Transitive: environment, filesystem, network, shell +1 3.4 MB antfu, patak, soda, ...2 more

View full report↗︎

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

🧹 Outside diff range and nitpick comments (6)
examples/isolated-declarations-swc/packem.config.ts (1)

12-12: Consider adding a code comment explaining the version requirement.

Since this is an example project demonstrating isolated declarations, it would be helpful to add a comment explaining why TypeScript >=5.5 is required.

 rollup: {
     node10Compatibility: {
+        // TypeScript >=5.5 is required for isolated declarations support
         typeScriptVersion: ">=5.5",
         writeToPackageJson: true,
     },
 },
examples/isolated-declarations-typescript/package.json (1)

22-26: Document TypeScript version requirement

Since this example specifically demonstrates isolated declarations which requires TypeScript >=5.5, consider adding a note in the package's README or adding a engines.typescript field to explicitly document this requirement.

Add the following to package.json:

{
    "name": "examples_packem_isolated_declarations_typescript",
+   "engines": {
+       "typescript": ">=5.5"
+   },
    ...
}
examples/isolated-declarations-oxc/package.json (1)

20-20: Consider updating the default types field for consistency.

The default types field points to ./dist/index.d.ts, while typesVersions points to ./dist/index.d.cts. Consider updating the default types field to match the CJS type definition for consistency with the package's dual-format setup.

-    "types": "./dist/index.d.ts",
+    "types": "./dist/index.d.cts",

Also applies to: 22-26

packages/packem/src/commands/add.ts (3)

132-132: Avoid unnecessary type assertions

At line 132, there is a type assertion using as string[]. Unnecessary type assertions can bypass TypeScript's type checking and potentially introduce runtime errors. Consider refining the types to avoid these assertions, which will improve type safety and code clarity.

You might adjust the code as follows to let TypeScript infer the correct type:

-packagesToInstall.push(...cssLoaderDependencies[loader as keyof typeof cssLoaderDependencies] as string[]);
+packagesToInstall.push(...cssLoaderDependencies[loader]);

Ensure that cssLoaderDependencies is properly typed so that TypeScript can infer the return type without assertions.


Line range hint 152-163: Ensure consistent handling of CSS minifier imports

In the block starting at line 152, when importing the CSS minifier, ensure that the logic for checking packemConfigFormat is consistent with how other imports are handled. This maintains consistency across the codebase and reduces potential import issues.

Consider aligning the import statements as follows:

if (packemConfigFormat === "cjs") {
    magic.prepend(
-       `const ${cssMinifier as string}Minifier = require("@visulima/packem/css/minifier/${cssMinifier.toLowerCase() as string}");\n`,
+       `const ${cssMinifier}Minifier = require("@visulima/packem/css/minifier/${cssMinifier}");\n`,
    );
} else {
    magic.prepend(
-       `import ${cssMinifier as string}Minifier from "@visulima/packem/css/minifier/${cssMinifier.toLowerCase() as string}";\n`,
+       `import ${cssMinifier}Minifier from "@visulima/packem/css/minifier/${cssMinifier}";\n`,
    );
}

This assumes that the directory naming matches the casing of ${cssMinifier}.


Line range hint 195-199: Handle optional chaining to prevent runtime errors

The replacement logic starting at line 195 might lead to issues if transformerPlaceholder is undefined or does not match the expected value. Consider using optional chaining or verifying that transformerPlaceholder is defined before using it.

Ensure that transformerPlaceholder exists and adjust the replacement logic to handle cases where it might not be found.

-   magic.replace(
+   if (transformerPlaceholder) {
+       magic.replace(
            transformerPlaceholder,
            `  transformer,\n    rollup: {\n        css: {${cssMinifier ? `\n            minifier: ${cssMinifier}Minifier,` : ""}\n            loaders: [${stringCssLoaders}],\n        },\n    },`,
        );
+   } else {
+       // Handle the case where transformerPlaceholder is not found
+   }

This prevents potential runtime errors due to undefined variables.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 81674b5 and 60a3985.

📒 Files selected for processing (10)
  • examples/isolated-declarations-oxc/package.json (1 hunks)
  • examples/isolated-declarations-oxc/packem.config.ts (1 hunks)
  • examples/isolated-declarations-swc/package.json (1 hunks)
  • examples/isolated-declarations-swc/packem.config.ts (1 hunks)
  • examples/isolated-declarations-typescript/package.json (1 hunks)
  • examples/isolated-declarations-typescript/packem.config.ts (1 hunks)
  • packages/packem/package.json (1 hunks)
  • packages/packem/packem.config.ts (1 hunks)
  • packages/packem/src/commands/add.ts (2 hunks)
  • packages/packem/src/rollup/get-rollup-options.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/packem/packem.config.ts
  • packages/packem/src/rollup/get-rollup-options.ts
🔇 Additional comments (9)
examples/isolated-declarations-oxc/packem.config.ts (2)

12-12: LGTM: TypeScript version constraint aligns with isolated declarations feature

The addition of typeScriptVersion: ">=5.5" correctly specifies the minimum TypeScript version required for isolated declarations support.


12-12: Verify version constraint consistency across example configs

Let's ensure this version constraint is consistent across all isolated declaration example configurations.

✅ Verification successful

TypeScript version constraints are consistent across configs

All packem configuration files in the examples directory specify the same TypeScript version constraint of ">=5.5", showing consistent version requirements across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check TypeScript version constraints across all example configs
# Expected: All isolated-declarations examples should specify the same version constraint

# Search for typeScriptVersion in all packem.config.ts files under examples/isolated-declarations-*
fd 'packem\.config\.ts$' examples/isolated-declarations- --exec grep -l "typeScriptVersion"

# Show the actual version constraints
fd 'packem\.config\.ts$' examples/isolated-declarations- --exec grep -A 1 "typeScriptVersion"

Length of output: 423


Script:

#!/bin/bash
# Let's try a different approach to find all packem config files
fd 'packem\.config\.ts$' examples --exec grep -A 1 "typeScriptVersion"

Length of output: 304

examples/isolated-declarations-swc/packem.config.ts (1)

12-12: LGTM! Verify version constraint propagation.

The TypeScript version constraint of ">=5.5" is correct for isolated declarations support. Since writeToPackageJson is enabled, this will be reflected in package.json.

Let's verify the version constraint is consistently set across related files:

✅ Verification successful

TypeScript version constraint is correctly aligned across isolated declaration examples

The version constraint ">=5.5" is consistently set in all three isolated declaration example configurations:

  • examples/isolated-declarations-typescript/packem.config.ts
  • examples/isolated-declarations-oxc/packem.config.ts
  • examples/isolated-declarations-swc/packem.config.ts

All three configs have the same settings:

rollup: {
    node10Compatibility: {
        typeScriptVersion: ">=5.5",
        writeToPackageJson: true,
    },
}

This aligns with the package.json TypeScript dependencies which show compatibility with TypeScript 5.6.x.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for TypeScript version constraints across config files and package.json
# Expected: All related files should specify >=5.5 for isolated declarations

# Check all packem config files for typeScriptVersion
echo "Checking packem config files:"
rg -l "typeScriptVersion.*5\.5" "examples/**/packem.config.ts"

# Check if documented in README
echo -e "\nChecking README for version requirement:"
rg "TypeScript.*5\.5" "README.md"

Length of output: 333


Script:

#!/bin/bash
# Let's try a different approach to find the config files and version constraints

# First, let's find all packem config files
echo "Finding all packem config files:"
fd "packem.config.ts"

# Then check their content for TypeScript version
echo -e "\nChecking TypeScript version in configs:"
fd "packem.config.ts" --exec cat {}

# Also check package.json for TypeScript version requirements
echo -e "\nChecking package.json for TypeScript version:"
fd "package.json" --exec cat {} | grep -i typescript

Length of output: 14867

examples/isolated-declarations-typescript/packem.config.ts (1)

12-12: LGTM! Version constraint aligns with isolated declarations feature requirements.

The TypeScript version constraint of ">=5.5" is correctly specified for the isolated declarations feature.

Let's verify the consistency of this version constraint across the codebase:

✅ Verification successful

Let me verify the content of these files to ensure the version constraints are consistent.


TypeScript version constraint is consistently implemented across the codebase

The version requirement typeScriptVersion: ">=5.5" is correctly and consistently specified in:

  • All isolated declarations example configurations (typescript, swc, oxc)
  • Main package configuration
  • Properly documented in the README.md with context about isolated declarations feature
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for TypeScript version constraints across the codebase
# Expected: All related files should specify TypeScript >=5.5 for isolated declarations

# Check package.json files for TypeScript version specifications
echo "Checking package.json files for TypeScript version constraints:"
fd package.json --exec rg -l "typescript.*5\.5"

# Check config files for TypeScript version constraints
echo "\nChecking config files for TypeScript version constraints:"
rg -l "typeScriptVersion.*5\.5"

# Check documentation for TypeScript version mentions
echo "\nChecking documentation for TypeScript version requirements:"
rg -l "TypeScript.*5\.5" -g "*.md"

Length of output: 741


Script:

#!/bin/bash
# Check the content of config files and README
echo "Content of packem.config.ts files:"
rg "typeScriptVersion.*5\.5" -A 2 -B 2

echo "\nContent of README.md TypeScript version mentions:"
rg "TypeScript.*5\.5" -A 2 -B 2 packages/packem/README.md

Length of output: 2268

examples/isolated-declarations-typescript/package.json (1)

22-26: Verify TypeScript declaration file configuration

The typesVersions configuration points to .d.cts file for TypeScript >=5.5, which is correct for CommonJS declaration files. However, since the package is of type "module", you might want to consider the following:

  1. The exports field correctly handles both .d.mts and .d.cts
  2. The typesVersions field could potentially include both formats for better compatibility
✅ Verification successful

TypeScript declaration configuration is correct for the package type

The current configuration is actually correct and well-structured:

  1. The exports field properly handles both ESM and CJS scenarios with their respective declaration files (.d.mts and .d.cts)
  2. Since this is a type="module" package, the typesVersions correctly points to .d.cts for CommonJS consumers using TypeScript >=5.5
  3. The setup aligns with the isolatedDeclarations: true in tsconfig.json, which requires TypeScript >=5.5
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence and format of declaration files

# Check if both .d.mts and .d.cts files are generated
fd -e d.mts -e d.cts . examples/isolated-declarations-typescript/dist

# Check if any other examples have similar configuration
rg -l "typesVersions.*>=5.5" examples/

Length of output: 246


Script:

#!/bin/bash
# Let's verify the package configuration and file structure

# Check if the directory exists and list its contents
ls -la examples/isolated-declarations-typescript/

# Check the package.json content to understand the full configuration
cat examples/isolated-declarations-typescript/package.json

# Look for any build scripts or configuration that generates declaration files
rg -A 5 "build" examples/isolated-declarations-typescript/package.json

# Check for tsconfig.json to understand the TypeScript configuration
cat examples/isolated-declarations-typescript/tsconfig.json

Length of output: 2094

examples/isolated-declarations-swc/package.json (1)

22-24: LGTM: TypeScript version constraint is appropriate.

The version constraint >=5.5 correctly aligns with TypeScript's isolated declarations feature introduction.

examples/isolated-declarations-oxc/package.json (1)

22-26: LGTM: TypeScript version constraint aligns with isolated declarations feature.

The version constraint >=5.5 correctly specifies the minimum TypeScript version required for isolated declarations support.

packages/packem/package.json (1)

315-369: Verify TypeScript version compatibility.

The new type definitions for TypeScript 5.5 are added while maintaining support for TypeScript 4.5 and 5.0 as specified in the peerDependencies. This ensures backward compatibility.

Let's verify the TypeScript version constraints:

#!/bin/bash
# Description: Check TypeScript version constraints

# Extract TypeScript version from peerDependencies
TS_VERSION=$(jq -r '.peerDependencies.typescript' package.json)
echo "TypeScript version constraint: $TS_VERSION"

# Verify if the version range includes 5.5
npx semver -r "$TS_VERSION" 5.5.0
if [ $? -eq 0 ]; then
    echo "Version range includes TypeScript 5.5"
else
    echo "Warning: Version range may not include TypeScript 5.5"
fi

Also applies to: 577-578

packages/packem/src/commands/add.ts (1)

Line range hint 232-235: Verify that all new dependencies are correctly installed

After modifying the list of packages to install, ensure that all required dependencies are correctly installed and added to package.json. This includes any new loaders or minifiers selected by the user.

Run the following script to verify that all dependencies are installed:

This script checks for the presence of the expected packages.

✅ Verification successful

Let me gather more information about the package dependencies and installation process.


Let me check the CSS loader dependencies and installation process.


Based on the review of the code and dependencies, I can now provide a final response:

All CSS-related dependencies are correctly configured and installed

The implementation correctly handles the installation of CSS dependencies through:

  1. Proper dependency definitions in cssLoaderDependencies
  2. Correct peer dependency specifications in package.json
  3. Automated installation via @antfu/install-pkg during the add command execution
  4. User-driven selection of loaders and minifiers with appropriate dependency resolution
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all required packages are installed and listed in package.json.

cd "$(dirname "$0")"

# List of packages to verify
packages=(
    "@visulima/packem/css/loader/*"
    "@visulima/packem/css/minifier/*"
    # Add other expected packages here
)

for package in "${packages[@]}"; do
    if ! npm ls "$package" >/dev/null 2>&1; then
        echo "Package $package is not installed."
    fi
done

Length of output: 533


Script:

#!/bin/bash
# Check package.json files for dependencies
echo "=== Checking package.json files ==="
fd package.json --exec cat {}

echo -e "\n=== Checking add command implementation ==="
# Check the implementation of the add command
cat packages/packem/src/commands/add.ts

Length of output: 147762


Script:

#!/bin/bash
# Check CSS loader dependencies and installation process
echo "=== Checking CSS loader dependencies ==="
cat packages/packem/src/commands/utils/css-loader-dependencies.ts

echo -e "\n=== Checking package.json for CSS-related dependencies ==="
cat packages/packem/package.json | grep -A 20 '"peerDependencies":'

Length of output: 1686

Comment on lines 22 to 26
">=5.5": {
".": [
"./dist/index.d.ts"
"./dist/index.d.cts"
]
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Type declarations configuration needs adjustment

The package.json configuration has inconsistencies in its type declarations:

  1. The types field points to "./dist/index.d.ts" but there's no corresponding file in the project
  2. The exports field correctly specifies dual-format type declarations:
    • ESM: "./dist/index.d.mts"
    • CJS: "./dist/index.d.cts"
  3. The typesVersions only includes CJS declarations but misses ESM declarations for TypeScript >=5.5

Recommendations:

  • Remove the types field since dual-format declarations are handled via exports
  • Update typesVersions to include both formats:
"typesVersions": {
    ">=5.5": {
        ".": [
            "./dist/index.d.mts",
            "./dist/index.d.cts"
        ]
    }
}
🔗 Analysis chain

Verify type declaration paths consistency.

While the CJS type declaration path is correctly updated, please verify:

  1. The types field still points to "./dist/index.d.ts"
  2. ESM type declarations might need similar versioning constraints

Let me gather more specific information about the package.json file in question.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check type declaration paths consistency across the project

# Check if there are any .d.ts files that should be .d.cts or .d.mts
fd -e d.ts -x echo "Found .d.ts file: {}"

# Check if other example projects have consistent typesVersions configuration
rg -l "typesVersions" "examples/**/package.json" | xargs cat

Length of output: 802


Script:

#!/bin/bash
# Check the complete package.json content to verify types field and ESM declarations
cat examples/isolated-declarations-swc/package.json

# Check if there are any .d.cts or .d.mts files in the project
fd -e d.cts -e d.mts -x echo "Found {}"

Length of output: 1099

packages/packem/package.json Show resolved Hide resolved
packages/packem/src/commands/add.ts Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (8)
packages/packem/src/commands/add.ts (4)

Line range hint 89-131: Consider extracting loader selection logic into separate functions

The loader selection logic is quite complex and would benefit from being broken down into smaller, more focused functions for better maintainability and testability.

Consider refactoring like this:

+ const selectMainCssLoader = async () => {
+   return select({
+     message: "Pick a css loader",
+     options: [
+       { label: "PostCSS", value: "postcss" },
+       { hint: "experimental", label: "Lightning CSS", value: "lightningcss" },
+     ],
+   }) as Promise<keyof typeof cssLoaderDependencies>;
+ };

+ const selectExtraLoaders = async () => {
+   return multiselect({
+     message: "Pick extra loaders",
+     options: [
+       { label: "Sass", value: "sass" },
+       { label: "Stylus", value: "stylus" },
+       { label: "Less", value: "less" },
+     ],
+     required: false,
+   }) as Promise<(keyof typeof cssLoaderDependencies)[]>;
+ };

+ const handleSassVariant = async (extraLoaders: (keyof typeof cssLoaderDependencies)[]) => {
+   if (!extraLoaders.includes("sass")) return extraLoaders;
+   
+   const sassLoader = await select({
+     message: "Pick a sass loader",
+     options: [
+       { hint: "recommended", label: "Sass embedded", value: "sass-embedded" },
+       { label: "Sass", value: "sass" },
+       { hint: "legacy", label: "Node Sass", value: "node-sass" },
+     ],
+   });
+   
+   if (sassLoader === "sass") return extraLoaders;
+   
+   return [
+     ...extraLoaders.filter((loader) => loader !== "sass"),
+     sassLoader as keyof typeof cssLoaderDependencies
+   ];
+ };

  const cssLoaders: (keyof typeof cssLoaderDependencies | "sourceMap")[] = [];
- const mainCssLoader = (await select({...})) as keyof typeof cssLoaderDependencies;
+ const mainCssLoader = await selectMainCssLoader();
  cssLoaders.push(mainCssLoader);

- let extraCssLoaders = (await multiselect({...})) as (keyof typeof cssLoaderDependencies)[];
+ let extraCssLoaders = await selectExtraLoaders();
- if (extraCssLoaders.includes("sass")) {
-   const sassLoader = await select({...});
-   if (sassLoader !== "sass") {
-     extraCssLoaders = extraCssLoaders.filter((loader) => loader !== "sass");
-     extraCssLoaders.push(sassLoader as keyof typeof cssLoaderDependencies);
-   }
- }
+ extraCssLoaders = await handleSassVariant(extraCssLoaders);
  cssLoaders.push(...extraCssLoaders);

132-132: Improve type safety by avoiding type assertion

The type assertion in the array spread operation can be avoided by properly typing the cssLoaderDependencies object.

Consider this approach:

- packagesToInstall.push(...cssLoaderDependencies[loader as keyof typeof cssLoaderDependencies] as string[]);
+ type LoaderKey = keyof typeof cssLoaderDependencies;
+ const dependencies = cssLoaderDependencies[loader as LoaderKey];
+ if (dependencies) {
+   packagesToInstall.push(...dependencies);
+ }

Line range hint 134-196: Consider using a template-based approach for config generation

The current string manipulation approach for generating the config is error-prone and hard to maintain. Consider using a template-based approach or a structured configuration builder.

Here's a suggested approach:

interface CssConfig {
  minifier?: string;
  loaders: string[];
}

const generateCssConfig = (cssLoaders: string[], minifier?: string): string => {
  const config: CssConfig = {
    loaders: cssLoaders.map(loader => 
      loader === "sass-embedded" || loader === "node-sass" ? "sass" : loader
    ).map(loader => `${loader}Loader`),
  };
  
  if (minifier) {
    config.minifier = `${minifier}Minifier`;
  }
  
  return `rollup: {
    css: ${JSON.stringify(config, null, 2).replace(/"/g, '')},
  },`;
};

This approach would:

  1. Make the config structure more explicit
  2. Reduce the risk of string manipulation errors
  3. Make it easier to maintain and modify the config structure

Line range hint 26-26: Consider breaking down the execute function to reduce complexity

The execute function has high cognitive complexity (as noted by the eslint-disable comment). Consider breaking it down into separate handlers for each feature type.

Example structure:

const handleTypedocFeature = async (config: MagicString, format: string, rootDirectory: string) => {
  // TypeDoc-specific logic
};

const handleCssFeature = async (config: MagicString, format: string, rootDirectory: string) => {
  // CSS-specific logic
};

const execute = async ({ argument, logger, options }): Promise<void> => {
  // Setup code...
  
  if (argument.includes("typedoc")) {
    await handleTypedocFeature(magic, packemConfigFormat, rootDirectory);
  }
  
  if (argument.includes("css")) {
    await handleCssFeature(magic, packemConfigFormat, rootDirectory);
  }
  
  // Cleanup code...
};

This would:

  1. Improve maintainability
  2. Make the code easier to test
  3. Make it easier to add new features in the future
packages/packem/src/commands/init.ts (2)

250-250: Consider improving type safety without explicit casting

The explicit type casting to string[] suggests potential type inference issues with cssLoaderDependencies. Consider improving the type definition of cssLoaderDependencies instead.

- packagesToInstall.push(...cssLoaderDependencies[loader as keyof typeof cssLoaderDependencies] as string[]);
+ packagesToInstall.push(...cssLoaderDependencies[loader as keyof typeof cssLoaderDependencies]);

This would require updating the type definition in css-loader-dependencies.ts to ensure proper type inference:

type CssLoaderDependencies = Record<string, readonly string[]>;

Line range hint 1-479: Consider refactoring to reduce complexity and improve maintainability

The initialization command has high cognitive complexity and handles multiple concerns. Consider breaking it down into smaller, focused functions:

  1. Package management (detecting/installing dependencies)
  2. TypeScript configuration
  3. CSS configuration
  4. Config file generation

This would improve:

  • Testability
  • Maintainability
  • Code reuse
  • Error handling

Example structure:

class PackemInitializer {
    private readonly rootDir: string;
    private readonly packageJson: PackageJson;
    
    async detectExistingDependencies(): Promise<string[]> {
        // Extract existing deps detection
    }
    
    async configureTypeScript(): Promise<TypeScriptConfig> {
        // Extract TypeScript setup
    }
    
    async configureCssProcessing(): Promise<CssConfig> {
        // Extract CSS setup
    }
    
    async generateConfigFile(config: PackemConfig): Promise<void> {
        // Extract config generation
    }
}
packages/packem/README.md (2)

544-555: Consider enhancing the isolated declarations documentation.

While the section provides good information about the feature, consider adding:

  1. A brief example showing the performance benefits
  2. A note about compatibility with existing TypeScript projects
  3. Clear prerequisites for using this feature

The explanation of why this feature is beneficial is well-written, but more practical guidance would help users adopt it effectively.


870-883: Consider restructuring the configuration section.

The configuration section could be improved by:

  1. Adding a brief introduction about when to use each transformer
  2. Including configuration examples for each transformer option
  3. Linking to the respective transformer documentation

This would help users make informed decisions about which transformer to use.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 60a3985 and 405a98b.

📒 Files selected for processing (14)
  • examples/isolated-declarations-oxc/package.json (1 hunks)
  • examples/isolated-declarations-oxc/packem.config.ts (1 hunks)
  • examples/isolated-declarations-swc/package.json (1 hunks)
  • examples/isolated-declarations-swc/packem.config.ts (1 hunks)
  • examples/isolated-declarations-typescript/package.json (1 hunks)
  • examples/isolated-declarations-typescript/packem.config.ts (1 hunks)
  • packages/packem/README.md (3 hunks)
  • packages/packem/__tests__/intigration/url.test.ts (1 hunks)
  • packages/packem/package.json (1 hunks)
  • packages/packem/packem.config.ts (1 hunks)
  • packages/packem/src/commands/add.ts (2 hunks)
  • packages/packem/src/commands/init.ts (1 hunks)
  • packages/packem/src/commands/utils/css-loader-dependencies.ts (1 hunks)
  • packages/packem/src/rollup/get-rollup-options.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (10)
  • examples/isolated-declarations-oxc/package.json
  • examples/isolated-declarations-oxc/packem.config.ts
  • examples/isolated-declarations-swc/package.json
  • examples/isolated-declarations-swc/packem.config.ts
  • examples/isolated-declarations-typescript/package.json
  • examples/isolated-declarations-typescript/packem.config.ts
  • packages/packem/package.json
  • packages/packem/packem.config.ts
  • packages/packem/src/commands/utils/css-loader-dependencies.ts
  • packages/packem/src/rollup/get-rollup-options.ts
🔇 Additional comments (2)
packages/packem/README.md (2)

56-56: LGTM: Feature list update is accurate and well-formatted.

The new feature "Supports isolated declaration types (experimental) (Typescript version 5.5 or higher)" is correctly added to the feature list with the appropriate version requirement.


556-566: LGTM: Configuration example is clear and well-structured.

The code example effectively demonstrates:

  • How to import the necessary components
  • How to configure the transformer
  • The correct syntax for the configuration

packages/packem/__tests__/intigration/url.test.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
packages/packem/__tests__/intigration/url.test.ts (1)

Line range hint 1-1: Fix typo in directory name

The directory name contains a typo: "intigration" should be "integration". This could affect test discovery and imports. Consider renaming the directory:

mv packages/packem/__tests__/intigration packages/packem/__tests__/integration

Remember to update any references to this path in other files.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 405a98b and ee0dbc6.

📒 Files selected for processing (5)
  • examples/isolated-declarations-oxc/package.json (1 hunks)
  • examples/isolated-declarations-swc/package.json (1 hunks)
  • examples/isolated-declarations-typescript/package.json (1 hunks)
  • packages/packem/__tests__/intigration/url.test.ts (4 hunks)
  • packages/packem/package.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • examples/isolated-declarations-swc/package.json
  • examples/isolated-declarations-typescript/package.json
  • packages/packem/package.json
🔇 Additional comments (2)
examples/isolated-declarations-oxc/package.json (2)

Line range hint 22-26: LGTM: TypeScript version constraint is appropriate

The >=5.5 constraint aligns with the isolated declarations feature requirement and matches the installed TypeScript version (^5.6.3).


Line range hint 6-15: Verify dual package hazard handling

The exports configuration correctly handles dual package hazards by providing separate paths for ESM (.mjs/.d.mts) and CJS (.cjs/.d.cts) consumers. Let's verify this setup across the codebase:

✅ Verification successful

Dual package hazard handling is consistently implemented across the codebase

The verification confirms proper dual package hazard handling:

  • Multiple packages in both examples/ and packages/ directories consistently implement the dual package pattern using .mts/.cts extensions
  • The type definitions are consistently declared in package.json files with proper extensions
  • The pattern matches the reviewed file's implementation, showing standardized handling across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent dual package hazard handling across example projects

# Check for similar export configurations in other example projects
echo "Checking export configurations in other example projects:"
fd -e json -x jq -r '.exports | select(.) | keys[]' {}

# Verify the existence of corresponding type definition files
echo "Verifying type definition files:"
fd -g "*.d.mts" -g "*.d.cts" -x echo "Found type definition: {}"

# Check for potential mismatches in type extensions
echo "Checking for type extension consistency:"
rg -g "*.json" '"types":\s*"[^"]+\.d\.(mts|cts)"'

Length of output: 6882

Comment on lines +270 to +271
const pngPath = join(basename(temporaryDirectoryPath), "/src/6b71fbe07b498a82.png");

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use path.join for safer path concatenation

While using basename improves cross-platform compatibility, the string concatenation with "/" could still cause issues on Windows. Consider using path.join for the entire path:

-const pngPath = join(basename(temporaryDirectoryPath), "/src/6b71fbe07b498a82.png");
+const pngPath = join(basename(temporaryDirectoryPath), "src", "6b71fbe07b498a82.png");

This ensures consistent path separators across all platforms.

📝 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
const pngPath = join(basename(temporaryDirectoryPath), "/src/6b71fbe07b498a82.png");
const pngPath = join(basename(temporaryDirectoryPath), "src", "6b71fbe07b498a82.png");

@prisis prisis merged commit d64d022 into main Nov 17, 2024
24 of 27 checks passed
@prisis prisis deleted the update-isolated-docs branch November 17, 2024 20:19
prisis pushed a commit that referenced this pull request Nov 17, 2024
…em [1.7.1](https://github.com/visulima/packem/compare/@visulima/packem@1.7.0...@visulima/packem@1.7.1) (2024-11-17)

### Bug Fixes

* updated docs about isolated declarations, moved sourcemapsPlugin… ([#63](#63)) ([d64d022](d64d022))
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