Skip to content

feat: support reading package.json from npm registry#21

Merged
JounQin merged 1 commit intomainfrom
feat/registry
Apr 26, 2025
Merged

feat: support reading package.json from npm registry#21
JounQin merged 1 commit intomainfrom
feat/registry

Conversation

@JounQin
Copy link
Member

@JounQin JounQin commented Apr 26, 2025

support yarn/pnpm seamlessly for webcontainer

close #17
close #20
close unrs/unrs-resolver#101


Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added seamless support for reading package.json from the npm registry.
    • Introduced compatibility with Yarn and pnpm package managers in relevant environments.
  • Bug Fixes

    • Improved error handling and version checks when preparing packages, reducing unnecessary errors for missing versions.
  • Chores

    • Switched package management tooling from npm to Yarn.
    • Updated development dependencies and configuration files for improved compatibility and workflow.
    • Enhanced .prettierignore and .gitignore to better manage ignored files.
    • Updated CI workflow to ensure Corepack is enabled before installing dependencies.
  • Tests

    • Added new test suites and fixtures for npm, pnpm, Yarn, and Yarn PnP environments to verify package manager support and installation workflows.
    • Adjusted existing tests to reflect improved package preparation logic.
  • Refactor

    • Refactored package preparation logic for improved clarity and flexibility.
    • Removed legacy and redundant files to streamline the codebase.
  • Documentation

    • Added and updated changeset files to document feature additions and improvements.

@JounQin JounQin added enhancement New feature or request feature New feature labels Apr 26, 2025
@JounQin JounQin requested a review from Copilot April 26, 2025 08:54
@JounQin JounQin self-assigned this Apr 26, 2025
@changeset-bot
Copy link

changeset-bot bot commented Apr 26, 2025

🦋 Changeset detected

Latest commit: 5bad3dd

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

This PR includes changesets to release 1 package
Name Type
napi-postinstall Minor

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

@coderabbitai
Copy link

coderabbitai bot commented Apr 26, 2025

Warning

Rate limit exceeded

@JounQin has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 40 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 e137781 and 5bad3dd.

⛔ Files ignored due to path filters (19)
  • .yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • .yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • lib/cli.js.map is excluded by !**/*.map
  • lib/constants.js.map is excluded by !**/*.map
  • lib/helpers.js.map is excluded by !**/*.map
  • lib/index.js.map is excluded by !**/*.map
  • lib/target.js.map is excluded by !**/*.map
  • lib/types.js.map is excluded by !**/*.map
  • package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/npm-10/package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/npm/package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/pnpm/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • test/fixtures/yarn-pnp/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn-pnp/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn-pnp/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • test/fixtures/yarn/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (40)
  • .changeset/big-phones-chew.md (1 hunks)
  • .changeset/soft-cooks-stare.md (1 hunks)
  • .github/workflows/autofix.yml (1 hunks)
  • .github/workflows/ci.yml (1 hunks)
  • .github/workflows/pkg-pr-new.yml (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • .github/workflows/size-limit.yml (1 hunks)
  • .gitignore (1 hunks)
  • .prettierignore (1 hunks)
  • .simple-git-hooks.mjs (1 hunks)
  • .yarnrc.yml (1 hunks)
  • lib/cli.d.ts (0 hunks)
  • lib/cli.js (0 hunks)
  • lib/constants.d.ts (0 hunks)
  • lib/constants.js (0 hunks)
  • lib/helpers.d.ts (0 hunks)
  • lib/helpers.js (0 hunks)
  • lib/index.d.ts (0 hunks)
  • lib/index.js (0 hunks)
  • lib/target.d.ts (0 hunks)
  • lib/target.js (0 hunks)
  • lib/types.d.ts (0 hunks)
  • lib/types.js (0 hunks)
  • package.json (4 hunks)
  • src/cli.ts (1 hunks)
  • src/helpers.ts (1 hunks)
  • src/index.ts (1 hunks)
  • test/basic.spec.ts (1 hunks)
  • test/fixtures.spec.ts (1 hunks)
  • test/fixtures/npm-10/package.json (1 hunks)
  • test/fixtures/npm/package.json (1 hunks)
  • test/fixtures/pnpm/package.json (1 hunks)
  • test/fixtures/yarn-pnp/.gitignore (1 hunks)
  • test/fixtures/yarn-pnp/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn-pnp/package.json (1 hunks)
  • test/fixtures/yarn-pnp/postinstall.js (1 hunks)
  • test/fixtures/yarn/.gitignore (1 hunks)
  • test/fixtures/yarn/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn/package.json (1 hunks)
  • test/fixtures/yarn/postinstall.js (1 hunks)

Walkthrough

This update removes the entire legacy implementation from the lib/ directory, including CLI, helpers, constants, types, and core logic for native package preparation. The TypeScript-based source code in src/ is refactored, particularly the checkAndPreparePackage function, which now includes overloads and improved package metadata resolution. Test coverage is expanded with new fixtures for npm, pnpm, yarn, and yarn pnp environments. The project configuration shifts from npm to yarn, updates dependencies, and adds new ignore rules. Continuous integration and git hooks are updated to align with these changes, and new changeset files record recent feature additions.

Changes

Files/Paths Change Summary
lib/cli.js, lib/helpers.js, lib/index.d.ts, lib/index.js, lib/cli.d.ts, lib/constants.d.ts, lib/constants.js, lib/helpers.d.ts, lib/target.d.ts, lib/target.js, lib/types.d.ts, lib/types.js Entire legacy implementation deleted: CLI, helpers, constants, type declarations, and core logic removed.
src/index.ts Refactored checkAndPreparePackage with overloads; improved handling of package name vs. object and npm registry fallback.
src/cli.ts Removed isNpm check; updated argument handling for checkAndPreparePackage.
src/helpers.ts Modified error handling in getNapiInfoFromPackageJson to skip missing package versions instead of throwing.
.changeset/big-phones-chew.md, .changeset/soft-cooks-stare.md Added changeset metadata files documenting new minor features.
.github/workflows/ci.yml CI updated to enable Corepack before installing dependencies.
.prettierignore Added .yarn, .pnp.*, and pnpm-lock.yaml to ignored files.
.gitignore Removed exceptions for lib directory and .tsbuildinfo files.
.simple-git-hooks.mjs Simplified to default export from @1stg/simple-git-hooks.
.yarnrc.yml New Yarn configuration: disables scripts/telemetry, sets linker, adds plugin.
package.json Switched to yarn, updated scripts/dependencies, added resolutions, and new dev dependency.
test/basic.spec.ts Updated tests to match new argument structure and error handling.
test/fixtures.spec.ts New tests for npm, pnpm, yarn, and yarn-pnp fixture installs.
test/fixtures/npm/package.json, test/fixtures/pnpm/package.json, test/fixtures/yarn/package.json, test/fixtures/yarn-pnp/package.json Added fixture package.json files for each package manager.
test/fixtures/yarn/.yarnrc.yml, test/fixtures/yarn-pnp/.yarnrc.yml Added Yarn configuration files for test fixtures.
test/fixtures/yarn/postinstall.js, test/fixtures/yarn-pnp/postinstall.js Added postinstall scripts invoking checkAndPreparePackage.
test/fixtures/yarn-pnp/.gitignore Added .gitignore for yarn-pnp fixture.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI/Script
    participant checkAndPreparePackage
    participant LocalPackage
    participant NpmRegistry

    User->>CLI/Script: Run postinstall/prepare script
    CLI/Script->>checkAndPreparePackage: Call with (pkgName, version?, checkVersion?)
    alt pkgName is string
        checkAndPreparePackage->>LocalPackage: Try require(package.json)
        alt Success
            checkAndPreparePackage->>checkAndPreparePackage: Use loaded package.json
        else Failure
            checkAndPreparePackage->>NpmRegistry: Fetch package metadata (if version provided)
            NpmRegistry-->>checkAndPreparePackage: Return package.json
        end
    else pkgName is object
        checkAndPreparePackage->>checkAndPreparePackage: Use provided package.json
    end
    checkAndPreparePackage->>checkAndPreparePackage: Validate and prepare native deps
Loading

Assessment against linked issues

Objective Addressed Explanation
Use npm registry to get related package.json when require fails (#17) checkAndPreparePackage falls back to fetching package metadata from npm registry if require fails.
Support pnpm and yarn, drop string name only usage, require version for fallback (#20) Added support for yarn and pnpm in fixtures and CI; version argument required for npm registry fallback.
Webcontainer support (#101) Added changeset documenting webcontainer support; test fixtures and configurations for yarn and pnpm added.

Possibly related PRs

  • un-ts/napi-postinstall#3: Introduced the initial implementation of the core CLI, helpers, and package preparation logic that this PR now removes and refactors.
  • un-ts/napi-postinstall#6: Removed legacy helper functions including getNapiInfoFromPackageJson, related to the current PR's removal of helpers.
  • un-ts/napi-postinstall#18: Modified native package installation logic for wasm32-wasi target; related but mutually exclusive with the current PR's removal of that code.

Poem

In the warren of code, old files hop away,
New helpers and types now brighten the day.
Yarn and pnpm join npm in the race,
With fixtures and tests, each finds its place.
The rabbit refactors, with a satisfied grin—
Fresh fields of code, let the postinstall begin!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR updates the package installation and preparation flow by extending checkAndPreparePackage to fall back to fetching package.json from the npm registry when local resolution fails, thereby enhancing support for yarn/pnpm in webcontainer environments.

  • Updates function overloads and fallback logic in src/index.ts and lib/index.js.
  • Adjusts CLI argument parsing and test cases to align with the revised API.
  • Updates Yarn configuration and plugin files alongside minor CI adjustments.

Reviewed Changes

Copilot reviewed 19 out of 25 changed files in this pull request and generated no comments.

Show a summary per file
File Description
test/fixtures/yarn/postinstall.js Adds a postinstall script invoking the updated API
test/fixtures/yarn/.yarnrc.yml Configures Yarn with plugin and release settings
test/fixtures/yarn/plugins/plugin-prepare-lifecycle.cjs Introduces a plugin to hook into the prepare lifecycle
test/fixtures.spec.ts Adds tests for yarn and pnpm behavior
test/basic.spec.ts Updates tests to conform to the new overload signatures
src/index.ts Refactors checkAndPreparePackage to support registry fallback
src/helpers.ts Adjusts version checking logic within getNapiInfoFromPackageJson
src/cli.ts Modifies CLI parameter handling for better cross-tool support
lib/index.js Mirrors src/index.ts changes in the compiled JS implementation
lib/helpers.js Updates version consistency checks in helper functions
lib/cli.js Revises CLI parameter mapping
.github/workflows/ci.yml Updates CI steps to enable corepack before npm ci
Files not reviewed (6)
  • .prettierignore: Language not supported
  • package.json: Language not supported
  • test/fixtures/pnpm/package.json: Language not supported
  • test/fixtures/pnpm/pnpm-lock.yaml: Language not supported
  • test/fixtures/yarn/.gitignore: Language not supported
  • test/fixtures/yarn/package.json: Language not supported

@github-actions
Copy link
Contributor

github-actions bot commented Apr 26, 2025

Deploy preview for napi-postinstall ready!

✅ Preview
https://napi-postinstall-cqzs5szxq-1stg.vercel.app

Built with commit 5bad3dd.
This pull request is being automatically deployed with vercel-action

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

🧹 Nitpick comments (8)
test/fixtures/yarn/package.json (1)

1-11: Add private field and unify script usage.
Fixture packages should be private to avoid publishing. For consistency, consider using the same hook (postinstall vs prepare) across Yarn/​pnpm fixtures.

{
+ "private": true,
  "name": "napi-postinstall-yarn",
  "packageManager": "yarn@4.9.1",
  "scripts": {
-   "prepare": "node ./postinstall.js"
+   "postinstall": "node ./postinstall.js"
  },
  "devDependencies": {
    "napi-postinstall": "link:../../..",
    "rollup": "^4.40.0"
  }
}
🧰 Tools
🪛 GitHub Actions: Package Size Report

[error] 1-1: Failed to install dependencies during npm install step.

test/fixtures.spec.ts (3)

7-16: Consider adding a timeout for yarn command execution.

The test correctly verifies that the yarn command completes without errors. However, in CI environments, the command might take longer to complete, especially during first-time runs.

-  it('should just work', () =>
+  it('should just work', { timeout: 60000 }, () =>
     expect(
       exec('yarn', [], {
         nodeOptions: {
           cwd: path.resolve(fixtures, 'yarn'),
         },
       }),
     ).resolves.not.toThrow())

18-27: Consider adding a timeout for pnpm command execution.

Same as with the yarn test, consider adding a timeout to prevent CI failures on slower environments.

-  it('should just work', () =>
+  it('should just work', { timeout: 60000 }, () =>
     expect(
       exec('pnpm', ['install'], {
         nodeOptions: {
           cwd: path.resolve(fixtures, 'pnpm'),
         },
       }),
     ).resolves.not.toThrow())

1-28: Enhance test suite with more detailed assertions.

The current tests verify that commands don't throw errors, which is a good start. Consider enhancing them to verify that the actual functionality works as expected after package installation.

You could verify that:

  1. The expected files were created
  2. The package.json was correctly processed
  3. The postinstall script executed successfully

Example:

it('should install and process correctly', async () => {
  await exec('yarn', [], {
    nodeOptions: {
      cwd: path.resolve(fixtures, 'yarn'),
    },
  });
  
  // Verify expected files exist
  const nodeModulesExists = fs.existsSync(
    path.resolve(fixtures, 'yarn', 'node_modules')
  );
  expect(nodeModulesExists).toBe(true);
  
  // Additional verification logic here
});
lib/index.js (2)

103-109: Consider adding request timeout and error handling for network fetch.

When fetching from the npm registry, there's no timeout handling which could lead to hanging requests in poor network conditions. Additionally, the error handling could be more specific about network-related issues.

 const pkg = packageNameOrPackageJson;
-const packageJsonBuffer = await fetch(`${(0, helpers_js_1.getGlobalNpmRegistry)()}${pkg}/${versionOrCheckVersion}`);
-packageJson = JSON.parse(packageJsonBuffer.toString('utf8'));
+try {
+  const controller = new AbortController();
+  const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout
+  
+  const packageJsonBuffer = await fetch(
+    `${(0, helpers_js_1.getGlobalNpmRegistry)()}${pkg}/${versionOrCheckVersion}`,
+    { signal: controller.signal }
+  );
+  clearTimeout(timeoutId);
+  packageJson = JSON.parse(packageJsonBuffer.toString('utf8'));
+} catch (err) {
+  if (err.name === 'AbortError') {
+    throw new Error(`Timeout while fetching package.json for "${pkg}@${versionOrCheckVersion}" from npm registry.`);
+  }
+  if (err instanceof SyntaxError) {
+    throw new Error(`Invalid JSON in package.json for "${pkg}@${versionOrCheckVersion}".`);
+  }
+  throw new Error(`Failed to fetch package.json for "${pkg}@${versionOrCheckVersion}": ${(0, helpers_js_1.getErrorMessage)(err)}`);
+}

Note: This would require modifying the fetch function to accept AbortSignal, which may require additional changes.


96-163: Consider implementing caching for fetched package.json files.

For improved performance in scenarios with multiple calls to the same package, consider implementing a simple cache for fetched package.json files. This could significantly reduce network requests and improve performance.

You could implement this by adding a simple in-memory cache at the module level:

// Add at the top of the file
const packageJsonCache = new Map();

// In the checkAndPreparePackage function
// ...
const cacheKey = `${pkg}@${versionOrCheckVersion}`;
if (packageJsonCache.has(cacheKey)) {
  packageJson = packageJsonCache.get(cacheKey);
} else {
  const packageJsonBuffer = await fetch(`${(0, helpers_js_1.getGlobalNpmRegistry)()}${pkg}/${versionOrCheckVersion}`);
  packageJson = JSON.parse(packageJsonBuffer.toString('utf8'));
  packageJsonCache.set(cacheKey, packageJson);
}
// ...
src/index.ts (2)

190-191: Consider renaming the parameter for clarity

The dual-purpose parameter versionOrCheckVersion serves different roles depending on the calling context, which could be confusing for maintainers. Consider renaming it to something that better indicates its dual nature, or restructure the implementation to avoid this pattern.

- versionOrCheckVersion?: boolean | string,
+ versionOrCheckVersionFlag?: boolean | string,

208-213: Consider adding timeout for fetch operation

The current implementation doesn't specify a timeout for the npm registry fetch operation. In poor network conditions, this could cause the function to hang indefinitely. Consider adding a timeout option to the fetch call.

- const packageJsonBuffer = await fetch(
-   `${getGlobalNpmRegistry()}${pkg}/${versionOrCheckVersion}`,
- )
+ // Add timeout to prevent hanging in poor network conditions
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 seconds timeout
+ try {
+   const packageJsonBuffer = await fetch(
+     `${getGlobalNpmRegistry()}${pkg}/${versionOrCheckVersion}`,
+     { signal: controller.signal }
+   );
+   clearTimeout(timeoutId);
+ } catch (error) {
+   clearTimeout(timeoutId);
+   throw new Error(`Failed to fetch package info from npm registry: ${getErrorMessage(error)}`);
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b291762 and 0a3ae6a.

⛔ Files ignored due to path filters (8)
  • lib/cli.js.map is excluded by !**/*.map
  • lib/helpers.js.map is excluded by !**/*.map
  • lib/index.js.map is excluded by !**/*.map
  • package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/pnpm/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • test/fixtures/yarn/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (19)
  • .changeset/big-phones-chew.md (1 hunks)
  • .changeset/soft-cooks-stare.md (1 hunks)
  • .github/workflows/ci.yml (1 hunks)
  • .prettierignore (1 hunks)
  • lib/cli.js (1 hunks)
  • lib/helpers.js (1 hunks)
  • lib/index.d.ts (1 hunks)
  • lib/index.js (1 hunks)
  • package.json (2 hunks)
  • src/cli.ts (1 hunks)
  • src/helpers.ts (1 hunks)
  • src/index.ts (1 hunks)
  • test/basic.spec.ts (1 hunks)
  • test/fixtures.spec.ts (1 hunks)
  • test/fixtures/pnpm/package.json (1 hunks)
  • test/fixtures/yarn/.gitignore (1 hunks)
  • test/fixtures/yarn/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn/package.json (1 hunks)
  • test/fixtures/yarn/postinstall.js (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/cli.ts (1)
src/index.ts (1)
  • checkAndPreparePackage (188-301)
test/fixtures/yarn/postinstall.js (1)
src/index.ts (1)
  • checkAndPreparePackage (188-301)
test/basic.spec.ts (1)
src/index.ts (1)
  • checkAndPreparePackage (188-301)
🪛 GitHub Actions: Package Size Report
test/fixtures/pnpm/package.json

[error] 1-1: Failed to install dependencies during npm install step.

test/fixtures/yarn/package.json

[error] 1-1: Failed to install dependencies during npm install step.

package.json

[error] 1-1: Failed to install dependencies during npm install step.

🔇 Additional comments (24)
.prettierignore (1)

1-2: Appropriate Prettier ignore updates

The additions of .yarn, .pnp.*, and pnpm-lock.yaml ensure that Yarn v2+ and pnpm-related files are excluded from formatting. This aligns with the multi–package-manager support and prevents unintended diffs in lockfiles and PnP artifacts.

Also applies to: 6-6

test/fixtures/yarn/.gitignore (1)

1-5: Verify .pnp.* ignore semantics

The pattern .yarn/* with exceptions correctly tracks patches/plugins/releases, but the line .pnp.* will ignore all PnP manifest files. If your intent is to commit .pnp.* files (common in Yarn PnP setups), change this to !.pnp.*. Otherwise, confirm that ignoring these files is desired.

test/fixtures/yarn/.yarnrc.yml (1)

1-9: Yarn PnP fixture configuration looks sound

The .yarnrc.yml disables telemetry, loads the prepare-lifecycle plugin with the correct checksum and path, and pins yarnPath to yarn-4.9.1.cjs. This matches the fixture’s requirements for running checkAndPreparePackage.

package.json (1)

57-57: Bumped devDependencies to support new fixtures

Development dependencies for ESLint plugins, TypeScript types, react-router-dom, stylelint, tinyexec, and vite have been updated to their latest patch versions to power the new YAML/PNPM fixtures and tests. The exports["./package.json"] entry also enables direct consumption of metadata from the npm registry. These changes align with the PR’s objectives.

Also applies to: 61-61, 65-65, 82-82, 89-90, 93-93

.changeset/big-phones-chew.md (1)

1-6: Changeset file structure is correct and documents the feature.
The frontmatter and summary succinctly capture the addition of npm registry fallback for package.json.

.changeset/soft-cooks-stare.md (1)

1-6: Changeset file is well-formed and describes package manager support.
This succinctly records the new Yarn/​pnpm integration in webcontainer environments.

lib/cli.js (1)

5-5: Enhanced CLI argument handling.

The CLI now accepts a third argument for version checking (via process.argv[4]), aligning with the updated checkAndPreparePackage function signature. This allows the tool to support reading package information from the npm registry when local resolution fails, improving compatibility with package managers like Yarn and pnpm.

src/cli.ts (2)

3-3: Removed conditional import.

Removed the import of isNpm since the function is now called unconditionally.


5-9: Improved package manager compatibility.

The function call is now unconditional (previously guarded by isNpm()) and accepts three parameters instead of two:

  1. process.argv[2] - package name
  2. process.argv[3] - version (new parameter)
  3. Boolean flag derived from process.argv[4] - check version flag

This change allows the tool to work with any package manager by fetching metadata from the npm registry when local resolution fails.

src/helpers.ts (2)

85-88: Relaxed version checking for better compatibility.

The error for missing package versions is now removed, allowing the function to continue silently when a package version is missing for a target. This improves compatibility with different package managers that might structure dependencies differently.


90-95: Conditional version consistency check.

The version mismatch error is now only thrown when checkVersion is explicitly set to true. This makes the function more lenient by default while still allowing strict validation when needed.

test/basic.spec.ts (4)

6-7: Updated test to match new function signature.

The test for rollup now explicitly passes undefined as the version argument and true as the checkVersion flag, matching the updated function signature in src/index.ts.


10-12: Updated test for @swc/core.

Similarly, the test for @swc/core now uses the three-argument function signature, explicitly passing undefined for the version and true for the version check flag.


14-16: Updated test for unrs-resolver.

The test for unrs-resolver also adopts the new function signature, ensuring consistent testing across different packages.


18-22: Verification: existing error case remains unchanged.

The test for napi-postinstall still expects the same error message, confirming that the core validation of NAPI support is preserved despite the changes to version handling.

test/fixtures.spec.ts (1)

1-6: LGTM: Clean imports and setup.

The imports and fixtures path setup look good. Using path.resolve ensures proper path resolution regardless of the working directory.

lib/index.d.ts (1)

4-5: LGTM: Clear function overloads for better type safety.

The function overloads are well-defined and provide good type safety for both use cases:

  1. When providing a package name string with optional version and checkVersion params
  2. When providing a complete PackageJson object with optional checkVersion param

This improves the API's flexibility while maintaining type safety.

lib/helpers.js (2)

67-69: LGTM: Improved error handling for missing package versions.

This change makes the function more resilient by skipping iterations with missing package versions rather than throwing errors immediately. This is essential for supporting alternative package managers like Yarn and pnpm which may have different structures.


71-72: LGTM: Conditional version consistency check.

Adding the checkVersion condition for version consistency errors is a good improvement. This provides more flexibility while still ensuring version consistency when explicitly required.

lib/index.js (1)

96-117: LGTM: Enhanced package resolution with npm registry fallback.

The function now supports both package name strings and package.json objects, with a fallback to fetch from the npm registry when local resolution fails. This significantly improves compatibility with various package managers like Yarn and pnpm.

The type checking and error messages are clear and helpful.

src/index.ts (4)

178-186: Good API enhancement with function overloads

The addition of function overloads provides a more flexible API that can handle both package name strings and fully loaded PackageJson objects. This is a clean approach that maintains backward compatibility while adding new functionality.


195-214: Robust fallback mechanism for package resolution

The implementation correctly handles the case when local package resolution fails (common with pnpm, Yarn v2+) by fetching from the npm registry. The error handling is appropriate, requiring a version string for the fallback path and providing a clear error message if it's not available.


215-223: Correct handling of parameter reassignment

The code correctly handles parameter reassignment when the second overload is used, ensuring the checkVersion flag is properly set regardless of which overload signature is used.


201-206: 💡 Verification agent

🧩 Analysis chain

Verify error handling for network failures

While the TypeError for missing version is handled well, the code should also handle network failures when fetching from the npm registry. Make sure errors from the fetch operation are properly propagated with meaningful messages.


🏁 Script executed:

#!/bin/bash
# Check how fetch errors are handled in other parts of the codebase
grep -r "fetch.*catch" --include="*.ts" .

Length of output: 43


🏁 Script executed:

#!/bin/bash
# Search for all fetch calls to inspect error handling
rg --context 3 'fetch(' --glob '*.ts'

# Search for references to "registry" to locate npm registry-related logic
rg -i 'registry' --glob '*.ts'

Length of output: 1233


🏁 Script executed:

#!/bin/bash
# List all fetch usages with surrounding context to check error handling
rg --context 3 -n 'fetch' --glob '*.ts'

Length of output: 1253


🏁 Script executed:

#!/bin/bash
# Display the fetch implementation
sed -n '1,120p' src/index.ts

# Display usage around npm registry fetch (lines ~180-260)
sed -n '180,260p' src/index.ts

Length of output: 6881


Enhance fetch error handling with URL and status context

The current fetch function correctly rejects on non-200 status codes and network errors, but the error messages lack the URL and detailed context. Let’s improve this in src/index.ts within the fetch implementation:

• Location: src/index.ts, lines 22–35
• Change non-200 rejection to include the URL and status code
• Wrap network errors to prefix with the URL

Proposed diff:

 function fetch(url: string) {
   return new Promise<Buffer>((resolve, reject) => {
     https
       .get(url, res => {
-        if (res.statusCode !== 200) {
-          return reject(new Error(`Server responded with ${res.statusCode}`))
+        if (res.statusCode !== 200) {
+          return reject(new Error(
+            `Failed to fetch ${url}: server responded with ${res.statusCode}`
+          ))
         }
         const chunks: Buffer[] = []
         res.on('data', (chunk: Buffer) => chunks.push(chunk))
         res.on('end', () => resolve(Buffer.concat(chunks)))
       })
-      .on('error', reject)
+      .on('error', err =>
+        reject(new Error(`Network error when fetching ${url}: ${err.message}`))
+      )
   })
 }

This ensures any failure surfaces with a clear, actionable message.

Likely an incorrect or invalid review comment.

@JounQin JounQin force-pushed the feat/registry branch 5 times, most recently from 0d37b5e to 58a6013 Compare April 26, 2025 10:04
@pkg-pr-new
Copy link

pkg-pr-new bot commented Apr 26, 2025

Open in StackBlitz

npm i https://pkg.pr.new/napi-postinstall@21

commit: 5bad3dd

@github-actions
Copy link
Contributor

github-actions bot commented Apr 26, 2025

📊 Package size report   3%↑

File Before After
lib/cli.js 326 B -6.13%↓306 B
lib/cli.js.map 328 B -3.35%↓317 B
lib/helpers.js 7.1 kB -0.85%↓7.0 kB
lib/helpers.js.map 6.2 kB -0.86%↓6.1 kB
lib/index.d.ts 257 B 40%↑361 B
lib/index.js 6.4 kB 12%↑7.2 kB
lib/index.js.map 5.9 kB 9%↑6.5 kB
package.json 3.5 kB -1.16%↓3.4 kB
Total (Includes all files) 43.9 kB 3%↑45.2 kB
Tarball size 12.7 kB 2%↑13.0 kB
Unchanged files
File Size
lib/cli.d.ts 31 B
lib/constants.d.ts 382 B
lib/constants.js 749 B
lib/constants.js.map 479 B
lib/helpers.d.ts 685 B
lib/target.d.ts 101 B
lib/target.js 1.6 kB
lib/target.js.map 1.5 kB
lib/types.d.ts 825 B
lib/types.js 110 B
lib/types.js.map 102 B
LICENSE 1.1 kB
README.md 6.4 kB

🤖 This report was automatically generated by pkg-size-action

@codecov
Copy link

codecov bot commented Apr 26, 2025

Codecov Report

Attention: Patch coverage is 30.76923% with 27 lines in your changes missing coverage. Please review.

Project coverage is 39.02%. Comparing base (b291762) to head (5bad3dd).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/index.ts 30.00% 21 Missing ⚠️
src/cli.ts 0.00% 6 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main      #21       +/-   ##
===========================================
- Coverage   55.88%   39.02%   -16.87%     
===========================================
  Files           6        6               
  Lines         467      492       +25     
  Branches       67       55       -12     
===========================================
- Hits          261      192       -69     
- Misses        206      300       +94     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JounQin JounQin force-pushed the feat/registry branch 6 times, most recently from 409fc51 to d7c7c74 Compare April 26, 2025 10:27
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

🧹 Nitpick comments (1)
src/index.ts (1)

208-213: Security consideration for package metadata fetching.

When fetching package metadata from the npm registry, consider implementing a timeout to prevent hanging HTTP requests and rate limiting to prevent potential abuse.

You might want to enhance the fetch operation with a timeout:

-      const packageJsonBuffer = await fetch(
-        `${getGlobalNpmRegistry()}${pkg}/${versionOrCheckVersion}`,
-      )
+      // Add timeout to prevent hanging requests
+      const controller = new AbortController();
+      const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
+      try {
+        const packageJsonBuffer = await fetch(
+          `${getGlobalNpmRegistry()}${pkg}/${versionOrCheckVersion}`,
+          { signal: controller.signal }
+        )
+      } finally {
+        clearTimeout(timeoutId);
+      }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf94f40 and d7c7c74.

⛔ Files ignored due to path filters (19)
  • .yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • .yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • lib/cli.js.map is excluded by !**/*.map
  • lib/constants.js.map is excluded by !**/*.map
  • lib/helpers.js.map is excluded by !**/*.map
  • lib/index.js.map is excluded by !**/*.map
  • lib/target.js.map is excluded by !**/*.map
  • lib/types.js.map is excluded by !**/*.map
  • package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/npm-10/package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/npm/package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/pnpm/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • test/fixtures/yarn-pnp/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn-pnp/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn-pnp/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • test/fixtures/yarn/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (40)
  • .changeset/big-phones-chew.md (1 hunks)
  • .changeset/soft-cooks-stare.md (1 hunks)
  • .github/workflows/autofix.yml (1 hunks)
  • .github/workflows/ci.yml (1 hunks)
  • .github/workflows/pkg-pr-new.yml (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • .github/workflows/size-limit.yml (1 hunks)
  • .gitignore (1 hunks)
  • .prettierignore (1 hunks)
  • .simple-git-hooks.mjs (1 hunks)
  • .yarnrc.yml (1 hunks)
  • lib/cli.d.ts (0 hunks)
  • lib/cli.js (0 hunks)
  • lib/constants.d.ts (0 hunks)
  • lib/constants.js (0 hunks)
  • lib/helpers.d.ts (0 hunks)
  • lib/helpers.js (0 hunks)
  • lib/index.d.ts (0 hunks)
  • lib/index.js (0 hunks)
  • lib/target.d.ts (0 hunks)
  • lib/target.js (0 hunks)
  • lib/types.d.ts (0 hunks)
  • lib/types.js (0 hunks)
  • package.json (4 hunks)
  • src/cli.ts (1 hunks)
  • src/helpers.ts (1 hunks)
  • src/index.ts (1 hunks)
  • test/basic.spec.ts (1 hunks)
  • test/fixtures.spec.ts (1 hunks)
  • test/fixtures/npm-10/package.json (1 hunks)
  • test/fixtures/npm/package.json (1 hunks)
  • test/fixtures/pnpm/package.json (1 hunks)
  • test/fixtures/yarn-pnp/.gitignore (1 hunks)
  • test/fixtures/yarn-pnp/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn-pnp/package.json (1 hunks)
  • test/fixtures/yarn-pnp/postinstall.js (1 hunks)
  • test/fixtures/yarn/.gitignore (1 hunks)
  • test/fixtures/yarn/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn/package.json (1 hunks)
  • test/fixtures/yarn/postinstall.js (1 hunks)
💤 Files with no reviewable changes (12)
  • lib/types.js
  • lib/cli.d.ts
  • lib/cli.js
  • lib/index.js
  • lib/target.d.ts
  • lib/index.d.ts
  • lib/constants.js
  • lib/constants.d.ts
  • lib/types.d.ts
  • lib/target.js
  • lib/helpers.d.ts
  • lib/helpers.js
✅ Files skipped from review due to trivial changes (5)
  • test/fixtures/yarn/.gitignore
  • test/fixtures/yarn/.yarnrc.yml
  • test/fixtures/yarn-pnp/package.json
  • .yarnrc.yml
  • test/fixtures/npm-10/package.json
🚧 Files skipped from review as they are similar to previous changes (17)
  • .changeset/big-phones-chew.md
  • .changeset/soft-cooks-stare.md
  • .prettierignore
  • test/fixtures/yarn-pnp/.yarnrc.yml
  • test/fixtures/yarn/package.json
  • .gitignore
  • test/fixtures/yarn-pnp/.gitignore
  • test/fixtures/yarn/postinstall.js
  • .github/workflows/ci.yml
  • test/fixtures/pnpm/package.json
  • src/helpers.ts
  • test/basic.spec.ts
  • .simple-git-hooks.mjs
  • test/fixtures/yarn-pnp/postinstall.js
  • test/fixtures/npm/package.json
  • test/fixtures.spec.ts
  • package.json
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/cli.ts

[warning] 3-3: src/cli.ts#L3
Added line #L3 was not covered by tests


[warning] 5-9: src/cli.ts#L5-L9
Added lines #L5 - L9 were not covered by tests

src/index.ts

[warning] 202-214: src/index.ts#L202-L214
Added lines #L202 - L214 were not covered by tests


[warning] 216-223: src/index.ts#L216-L223
Added lines #L216 - L223 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
🔇 Additional comments (16)
.github/workflows/size-limit.yml (2)

22-22: Consistent package manager caching
Switching the Node setup cache from npm to Yarn aligns with your migration to Yarn; this should speed up dependency installation.


25-25: Use immutable Yarn installation
Replacing npm ci with yarn --immutable ensures that dependencies are installed strictly according to the lockfile, matching best practices for reproducible builds.

.github/workflows/autofix.yml (3)

25-25: Enable Yarn caching for faster CI runs
Updating the cache option to yarn is correct to leverage cached modules and speed up the workflow.


28-28: Install dependencies with Yarn
Using yarn --immutable here enforces the lockfile and aligns with the repository migration; good addition.


31-31: Update formatting command to Yarn
Switching from npm run format to yarn format is appropriate, assuming the format script is defined in package.json.

.github/workflows/release.yml (4)

32-32: Switch Node cache to Yarn
Changing cache: npm to cache: yarn is consistent with the overall package manager migration.


35-35: Adopt Yarn immutable install
Replacing npm ci with yarn --immutable ensures deterministic installs, which is crucial for reliable releases.


42-42: Use Yarn for publishing
Configuring the publish command as yarn release correctly replaces npm run release. Make sure the release script exists and performs the expected publish logic.


43-43: Use Yarn for version bump
Adjusting the version command to yarn run version mirrors the previous npm-based bump. Ensure this script has the proper side effects in your Changesets workflow.

.github/workflows/pkg-pr-new.yml (4)

22-22: Leverage Yarn cache
Switching the Node.js cache context to yarn correctly aligns with the migration to Yarn across workflows.


25-25: Install dependencies reproducibly
Using yarn --immutable replaces npm ci in enforcing lockfile consistency; good for build determinism.


28-28: Update build step to Yarn
Running yarn build instead of npm run build is the expected transition; ensure the build script is defined and invoked correctly.


31-31: Use Yarn dlx for CLI execution
Switching from npx to yarn dlx to run pkg-pr-new is a best practice for Yarn deployments and avoids potential PnP resolution issues.

src/index.ts (3)

178-186: Improved TypeScript function overload signatures.

The explicit function overloads provide better type safety and clearer API documentation for the two supported calling patterns. This is good TypeScript practice.


215-223: Handling for direct PackageJson object input.

The implementation now gracefully handles receiving a PackageJson object directly, which increases flexibility. The parameter assignment and type check are correctly implemented.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 216-223: src/index.ts#L216-L223
Added lines #L216 - L223 were not covered by tests


202-206: Appropriate error handling when version is missing.

The error message is clear and descriptive when the package.json can't be loaded locally and no version is provided. This provides good developer experience by explaining exactly what went wrong and how to fix it.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 202-214: src/index.ts#L202-L214
Added lines #L202 - L214 were not covered by tests

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

♻️ Duplicate comments (1)
src/index.ts (1)

195-214: Missing Test Coverage for npm Registry Fallback

The new fallback logic for fetching from the npm registry isn't currently covered by tests according to static analysis. Consider adding unit tests that verify both successful registry fetches and error handling when version is missing.

#!/bin/bash
# Check if any tests verify the npm registry fallback functionality
find test -type f -name "*.ts" -o -name "*.js" | xargs grep -l "registry" | xargs cat | grep -C 5 "registry"
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 202-214: src/index.ts#L202-L214
Added lines #L202 - L214 were not covered by tests

🧹 Nitpick comments (1)
src/index.ts (1)

202-206: Consider enhancing error message with examples

The error message could be more helpful by providing an example of how to correctly specify the version.

- throw new TypeError(
-   `Failed to load \`${PACKAGE_JSON}\` from "${packageNameOrPackageJson}", please provide a version.`,
- )
+ throw new TypeError(
+   `Failed to load \`${PACKAGE_JSON}\` from "${packageNameOrPackageJson}", please provide a version. Example: checkAndPreparePackage("${packageNameOrPackageJson}", "1.0.0")`,
+ )
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 202-214: src/index.ts#L202-L214
Added lines #L202 - L214 were not covered by tests

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7c7c74 and e137781.

⛔ Files ignored due to path filters (19)
  • .yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • .yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • lib/cli.js.map is excluded by !**/*.map
  • lib/constants.js.map is excluded by !**/*.map
  • lib/helpers.js.map is excluded by !**/*.map
  • lib/index.js.map is excluded by !**/*.map
  • lib/target.js.map is excluded by !**/*.map
  • lib/types.js.map is excluded by !**/*.map
  • package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/npm-10/package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/npm/package-lock.json is excluded by !**/package-lock.json
  • test/fixtures/pnpm/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • test/fixtures/yarn-pnp/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn-pnp/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn-pnp/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • test/fixtures/yarn/.yarn/plugins/plugin-prepare-lifecycle.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/.yarn/releases/yarn-4.9.1.cjs is excluded by !**/.yarn/**
  • test/fixtures/yarn/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (40)
  • .changeset/big-phones-chew.md (1 hunks)
  • .changeset/soft-cooks-stare.md (1 hunks)
  • .github/workflows/autofix.yml (1 hunks)
  • .github/workflows/ci.yml (1 hunks)
  • .github/workflows/pkg-pr-new.yml (1 hunks)
  • .github/workflows/release.yml (1 hunks)
  • .github/workflows/size-limit.yml (1 hunks)
  • .gitignore (1 hunks)
  • .prettierignore (1 hunks)
  • .simple-git-hooks.mjs (1 hunks)
  • .yarnrc.yml (1 hunks)
  • lib/cli.d.ts (0 hunks)
  • lib/cli.js (0 hunks)
  • lib/constants.d.ts (0 hunks)
  • lib/constants.js (0 hunks)
  • lib/helpers.d.ts (0 hunks)
  • lib/helpers.js (0 hunks)
  • lib/index.d.ts (0 hunks)
  • lib/index.js (0 hunks)
  • lib/target.d.ts (0 hunks)
  • lib/target.js (0 hunks)
  • lib/types.d.ts (0 hunks)
  • lib/types.js (0 hunks)
  • package.json (4 hunks)
  • src/cli.ts (1 hunks)
  • src/helpers.ts (1 hunks)
  • src/index.ts (1 hunks)
  • test/basic.spec.ts (1 hunks)
  • test/fixtures.spec.ts (1 hunks)
  • test/fixtures/npm-10/package.json (1 hunks)
  • test/fixtures/npm/package.json (1 hunks)
  • test/fixtures/pnpm/package.json (1 hunks)
  • test/fixtures/yarn-pnp/.gitignore (1 hunks)
  • test/fixtures/yarn-pnp/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn-pnp/package.json (1 hunks)
  • test/fixtures/yarn-pnp/postinstall.js (1 hunks)
  • test/fixtures/yarn/.gitignore (1 hunks)
  • test/fixtures/yarn/.yarnrc.yml (1 hunks)
  • test/fixtures/yarn/package.json (1 hunks)
  • test/fixtures/yarn/postinstall.js (1 hunks)
💤 Files with no reviewable changes (12)
  • lib/types.js
  • lib/cli.d.ts
  • lib/target.d.ts
  • lib/cli.js
  • lib/index.d.ts
  • lib/index.js
  • lib/constants.js
  • lib/target.js
  • lib/helpers.d.ts
  • lib/types.d.ts
  • lib/constants.d.ts
  • lib/helpers.js
✅ Files skipped from review due to trivial changes (2)
  • .github/workflows/size-limit.yml
  • test/fixtures/yarn/.yarnrc.yml
🚧 Files skipped from review as they are similar to previous changes (24)
  • .changeset/soft-cooks-stare.md
  • .changeset/big-phones-chew.md
  • test/fixtures/yarn/.gitignore
  • test/fixtures/pnpm/package.json
  • .prettierignore
  • .gitignore
  • .yarnrc.yml
  • test/fixtures/yarn/postinstall.js
  • .github/workflows/release.yml
  • test/basic.spec.ts
  • test/fixtures/yarn-pnp/.gitignore
  • .github/workflows/pkg-pr-new.yml
  • test/fixtures/yarn-pnp/postinstall.js
  • .github/workflows/autofix.yml
  • test/fixtures/yarn-pnp/package.json
  • test/fixtures.spec.ts
  • test/fixtures/yarn-pnp/.yarnrc.yml
  • src/helpers.ts
  • test/fixtures/npm/package.json
  • test/fixtures/yarn/package.json
  • .simple-git-hooks.mjs
  • test/fixtures/npm-10/package.json
  • package.json
  • .github/workflows/ci.yml
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/index.ts (3)
src/types.ts (1)
  • PackageJson (28-33)
src/constants.ts (2)
  • require (7-9)
  • PACKAGE_JSON (19-19)
src/helpers.ts (1)
  • getGlobalNpmRegistry (9-18)
🪛 GitHub Check: codecov/patch
src/cli.ts

[warning] 3-3: src/cli.ts#L3
Added line #L3 was not covered by tests


[warning] 5-9: src/cli.ts#L5-L9
Added lines #L5 - L9 were not covered by tests

src/index.ts

[warning] 202-214: src/index.ts#L202-L214
Added lines #L202 - L214 were not covered by tests


[warning] 216-223: src/index.ts#L216-L223
Added lines #L216 - L223 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
  • GitHub Check: Lint and Test with Node.js 22 on windows-latest
  • GitHub Check: Lint and Test with Node.js 18 on windows-latest
🔇 Additional comments (3)
src/cli.ts (1)

3-9:

Details

❓ Verification inconclusive

Streamlined CLI implementation for package manager agnostic operation

The CLI implementation has been simplified by removing the conditional check on isNpm() and now unconditionally calls checkAndPreparePackage with explicitly defined parameters. This aligns with the PR objective of supporting reading package.json from npm registry for better yarn/pnpm compatibility.

The boolean handling in the third parameter is clear and intuitive, supporting multiple affirmative values ('1', 'check', 'true', 'yes').


🏁 Script executed:

#!/bin/bash
# Verify that the e2e tests cover the CLI functionality with different package managers
find test -type f -name "*.ts" -o -name "*.js" | xargs grep -l "fixtures" | xargs cat | grep -C 5 "checkAndPreparePackage"

Length of output: 120


Ensure CLI e2e coverage across package managers

I searched the test suite for any invocations of checkAndPreparePackage and found no matches. Please verify that your end-to-end or integration tests exercise the new CLI behavior under npm, Yarn, and PNPM configurations to avoid regressions.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 3-3: src/cli.ts#L3
Added line #L3 was not covered by tests


[warning] 5-9: src/cli.ts#L5-L9
Added lines #L5 - L9 were not covered by tests

src/index.ts (2)

178-186: LGTM: Well-defined function overloads improve type safety

Adding explicit function overloads for the checkAndPreparePackage function provides better type safety and clearer API documentation. This makes it easier for consumers to understand the expected parameters and return types.


189-223:

Details

✅ Verification successful

Implementation now supports package manager agnostic operation

The refactored implementation properly handles both string package names and direct PackageJson objects, with a clear fallback mechanism for fetching package.json from the npm registry when local resolution fails. This directly addresses the PR objective to support yarn and pnpm in webcontainer environments.


🏁 Script executed:

#!/bin/bash
# Check if there are e2e tests that validate the package manager compatibility
echo "Looking for e2e tests that exercise different package managers:"
find test/fixtures -type d -maxdepth 1 | sort
echo "\nChecking for package manager specific test configurations:"
grep -r "packageManager" test/fixtures --include="*.json" || echo "No explicit package manager configurations found"

Length of output: 823


Package manager compatibility verified via E2E fixtures

The existing test suite already covers npm, pnpm, and Yarn (including PnP) under test/fixtures (with packageManager fields in each package.json), ensuring the new fallback logic is exercised. No further changes required.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 202-214: src/index.ts#L202-L214
Added lines #L202 - L214 were not covered by tests


[warning] 216-223: src/index.ts#L216-L223
Added lines #L216 - L223 were not covered by tests

support yarn/pnpm seamlessly for webcontainer
@JounQin JounQin merged commit 2d6c726 into main Apr 26, 2025
27 of 30 checks passed
@JounQin JounQin deleted the feat/registry branch April 26, 2025 11:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request feature New feature

Projects

None yet

2 participants