Skip to content

fix: prevent browserslist from reading pnpm shim files#2027

Open
HuiNeng6 wants to merge 1 commit intoasyncapi:masterfrom
HuiNeng6:fix-browserslist-pnpm-issue-1781
Open

fix: prevent browserslist from reading pnpm shim files#2027
HuiNeng6 wants to merge 1 commit intoasyncapi:masterfrom
HuiNeng6:fix-browserslist-pnpm-issue-1781

Conversation

@HuiNeng6
Copy link
Copy Markdown

@HuiNeng6 HuiNeng6 commented Mar 22, 2026

Description

This PR fixes an issue where using pnpm to install asyncapi/cli globally causes a browserslist error when generating documentation.

Problem

When using pnpm to install asyncapi/cli globally, the generator fails with the error:

Generator Error: Unknown browser query 'basedir=$(dirname "$(echo "$0" | sed -e 's'. Maybe you are using old Browserslist or made typo in query

This happens because pnpm creates shell script shims for globally installed packages, and browserslist incorrectly parses these shim files as configuration files during template compilation.

Solution

Set the BROWSERSLIST_ROOT_PATH environment variable during template compilation to restrict browserslist's search scope to the template directory only. This prevents browserslist from traversing to pnpm's shim directories and incorrectly parsing shell scripts as config files.

Related Issue

Fixes asyncapi/cli#1781

Testing

This fix has been tested with:

  • pnpm global installation of asyncapi/cli
  • HTML template generation with @asyncapi/html-template

Summary by CodeRabbit

  • Bug Fixes
    • Resolved "Unknown browser query" errors that occurred during template compilation when using pnpm.

Set BROWSERSLIST_ROOT_PATH environment variable during template compilation
to prevent browserslist from searching outside the template directory.

This fixes an issue where pnpm's shim files were incorrectly parsed as
browserslist configuration, causing 'Unknown browser query' errors.

Fixes: asyncapi/cli#1781
@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 22, 2026

🦋 Changeset detected

Latest commit: c40721c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@asyncapi/generator Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@asyncapi-bot
Copy link
Copy Markdown
Contributor

What reviewer looks at during PR review

The following are ideal points maintainers look for during review. Reviewing these points yourself beforehand can help streamline the review process and reduce time to merge.

  1. PR Title: Use a concise title that follows our Conventional Commits guidelines and clearly summarizes the change using imperative mood (it means spoken or written as if giving a command or instruction, like "add new helper for listing operations")

    Note - In Generator, prepend feat: or fix: in PR title only when PATCH/MINOR release must be triggered.

  2. PR Description: Clearly explain the issue being solved, summarize the changes made, and mention the related issue.

    Note - In Generator, we use Maintainers Work board to track progress. Ensure the PR Description includes Resolves #<issue-number> or Fixes #<issue-number> this will automatically close the linked issue when the PR is merged and helps automate the maintainers workflow.

  3. Documentation: Update the relevant Generator documentation to accurately reflect the changes introduced in the PR, ensuring users and contributors have up-to-date guidance.

  4. Comments and JSDoc: Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions, so others can easily understand and use the code.

  5. DRY Code: Ensure the code follows the Don't Repeat Yourself principle. Look out for duplicate logic that can be reused.

  6. Test Coverage: Ensure the new code is well-tested with meaningful test cases that pass consistently and cover all relevant edge cases.

  7. Commit History: Contributors should avoid force-pushing as much as possible. It makes it harder to track incremental changes and review the latest updates.

  8. Template Design Principles Alignment: While reviewing template-related changes in the packages/ directory, ensure they align with the Assumptions and Principles. If any principle feels outdated or no longer applicable, start a discussion these principles are meant to evolve with the project.

  9. Reduce Scope When Needed: If an issue or PR feels too large or complex, consider splitting it and creating follow-up issues. Smaller, focused PRs are easier to review and merge.

  10. Bot Comments: As reviewers, check that contributors have appropriately addressed comments or suggestions made by automated bots. If there are bot comments the reviewer disagrees with, react to them or mark them as resolved, so the review history remains clear and accurate.

Copy link
Copy Markdown
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our contributors guide useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out this issue.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 22, 2026

📝 Walkthrough

Walkthrough

This patch fixes a browserslist resolution issue when using pnpm by setting the BROWSERSLIST_ROOT_PATH environment variable to the template directory during template compilation. This prevents pnpm shim files from being misinterpreted as browserslist configuration, which previously caused "Unknown browser query" errors.

Changes

Cohort / File(s) Summary
Changeset Metadata
.changeset/fix-browserslist-pnpm.md
Documents patch-level release note for @asyncapi/generator describing the BROWSERSLIST_ROOT_PATH fix and its impact on pnpm compatibility.
Generator Implementation
apps/generator/lib/generator.js
Modified configureTemplate() to temporarily set process.env.BROWSERSLIST_ROOT_PATH to this.templateDir during configureReact() invocation when compilation is enabled, with try/finally block ensuring environment restoration.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title uses the 'fix:' prefix as required by Conventional Commits, clearly summarizes the main change in imperative mood, and directly addresses the core issue of preventing browserslist from reading pnpm shim files.
Linked Issues check ✅ Passed The PR successfully implements the required fix by setting BROWSERSLIST_ROOT_PATH during template compilation to prevent browserslist from traversing into pnpm shim directories, directly addressing the coding requirement from issue #1781.
Out of Scope Changes check ✅ Passed All changes are narrowly scoped to the specific issue: modifying generator.js to set the environment variable and adding a changesets entry documenting the patch release, with no extraneous modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (3)
apps/generator/lib/generator.js (3)

399-402: Tighten configureTemplate JSDoc to include return and error behavior.

The function behavior now includes temporary env mutation and restoration around async compilation; document @returns and failure behavior to match project JSDoc expectations.

As per coding guidelines: "**/*.{js,ts,jsx,tsx}: Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/lib/generator.js` around lines 399 - 402, Update the JSDoc for
async function configureTemplate() to explicitly document its return and error
behavior: add an `@returns` {Promise<void>} noting it resolves when template
configuration and async compilation complete, describe that it temporarily
mutates process.env (or the relevant env object) during compilation and restores
the original environment afterwards, and state the error condition/throws
behavior (e.g., it will reject/throw if template compilation fails). Reference
the configureTemplate method name and mention the temporary env
mutation/restoration so the comment matches the implementation.

402-422: Add a regression test for the pnpm shim/browserslist case.

This fix is important and env-sensitive; please add a test in the template test suite that exercises compile mode and verifies pnpm-like shim content is not treated as browserslist config.

Based on learnings: "Template features should be tested using the react-template in apps/generator/test/test-templates before committing".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/lib/generator.js` around lines 402 - 422, Add a regression
test that runs the generator in compile mode (so configureTemplate calls
configureReact with TRANSPILED_TEMPLATE_LOCATION) using the react-template test
fixture, and assert that a file containing pnpm-like shim content in the
templateContentDir is not detected/parsed as a browserslist config when
BROWSERSLIST_ROOT_PATH is set to the templateDir; specifically create a test
that creates a pnpm-shim-like file in the template, invokes the compile flow
that triggers configureTemplate/configureReact, and verifies output/behavior
shows the shim was ignored (no browserslist parsing error and expected compiled
output exists).

404-419: Process-wide env mutation is race-prone under concurrent generation.

This mutates process.env.BROWSERSLIST_ROOT_PATH globally during an await. If two generations run in parallel (different templates), one run can observe the other run’s root path.

Possible hardening (serialize the env-scoped compile section)
+let compileEnvLock = Promise.resolve();

 class Generator {
   async configureTemplate() {
     if (this.compile) {
+      const previousLock = compileEnvLock;
+      let releaseLock;
+      compileEnvLock = new Promise(resolve => { releaseLock = resolve; });
+      await previousLock;
+
       const previousRootPath = process.env.BROWSERSLIST_ROOT_PATH;
       process.env.BROWSERSLIST_ROOT_PATH = this.templateDir;
       try {
         await configureReact(this.templateDir, this.templateContentDir, TRANSPILED_TEMPLATE_LOCATION);
       } finally {
         if (previousRootPath === undefined) {
           delete process.env.BROWSERSLIST_ROOT_PATH;
         } else {
           process.env.BROWSERSLIST_ROOT_PATH = previousRootPath;
         }
+        releaseLock();
       }
     }
   }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/lib/generator.js` around lines 404 - 419, The code temporarily
mutates process.env.BROWSERSLIST_ROOT_PATH around an await in the call to
configureReact, which is race-prone for concurrent generations; to fix it, avoid
in-process global env mutation by either (A) running the configureReact step in
a separate child process with an overridden env that sets BROWSERSLIST_ROOT_PATH
(so each generation gets its own env), or (B) if staying in-process, serialize
access by adding a mutex/lock around the section that sets/restores
BROWSERSLIST_ROOT_PATH so only one caller at a time performs the set -> await
configureReact(...) -> restore sequence; update the call sites using
templateDir, templateContentDir, and TRANSPILED_TEMPLATE_LOCATION accordingly
and ensure the lock is acquired before setting BROWSERSLIST_ROOT_PATH and
released after restoring it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/generator/lib/generator.js`:
- Around line 399-402: Update the JSDoc for async function configureTemplate()
to explicitly document its return and error behavior: add an `@returns`
{Promise<void>} noting it resolves when template configuration and async
compilation complete, describe that it temporarily mutates process.env (or the
relevant env object) during compilation and restores the original environment
afterwards, and state the error condition/throws behavior (e.g., it will
reject/throw if template compilation fails). Reference the configureTemplate
method name and mention the temporary env mutation/restoration so the comment
matches the implementation.
- Around line 402-422: Add a regression test that runs the generator in compile
mode (so configureTemplate calls configureReact with
TRANSPILED_TEMPLATE_LOCATION) using the react-template test fixture, and assert
that a file containing pnpm-like shim content in the templateContentDir is not
detected/parsed as a browserslist config when BROWSERSLIST_ROOT_PATH is set to
the templateDir; specifically create a test that creates a pnpm-shim-like file
in the template, invokes the compile flow that triggers
configureTemplate/configureReact, and verifies output/behavior shows the shim
was ignored (no browserslist parsing error and expected compiled output exists).
- Around line 404-419: The code temporarily mutates
process.env.BROWSERSLIST_ROOT_PATH around an await in the call to
configureReact, which is race-prone for concurrent generations; to fix it, avoid
in-process global env mutation by either (A) running the configureReact step in
a separate child process with an overridden env that sets BROWSERSLIST_ROOT_PATH
(so each generation gets its own env), or (B) if staying in-process, serialize
access by adding a mutex/lock around the section that sets/restores
BROWSERSLIST_ROOT_PATH so only one caller at a time performs the set -> await
configureReact(...) -> restore sequence; update the call sites using
templateDir, templateContentDir, and TRANSPILED_TEMPLATE_LOCATION accordingly
and ensure the lock is acquired before setting BROWSERSLIST_ROOT_PATH and
released after restoring it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25c633fc-8b80-4ff1-aacd-2d83534feb6f

📥 Commits

Reviewing files that changed from the base of the PR and between adfb30f and c40721c.

📒 Files selected for processing (2)
  • .changeset/fix-browserslist-pnpm.md
  • apps/generator/lib/generator.js

@derberg
Copy link
Copy Markdown
Member

derberg commented Mar 25, 2026

which generator, cli and html-templates versions were you testing this PR with

@derberg derberg moved this to In Progress in Maintainers work Mar 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

[BUG] Generator error when using pnpm to create documentation

3 participants