Skip to content

feat: try reading package.json from cwd#50

Closed
mrginglymus wants to merge 1 commit intoun-ts:mainfrom
mrginglymus:read-from-cwd
Closed

feat: try reading package.json from cwd#50
mrginglymus wants to merge 1 commit intoun-ts:mainfrom
mrginglymus:read-from-cwd

Conversation

@mrginglymus
Copy link
Contributor

@mrginglymus mrginglymus commented Aug 9, 2025


Important

Adds resolvePackageJson() to read package.json from cwd if initial require fails, updating checkAndPreparePackage() to use it, fixing two issues.

This description was created by Ellipsis for cb46bc5. You can customize this summary. It will automatically update as commits are pushed.

Summary by CodeRabbit

  • New Features

    • Improved handling for loading a package’s information, with enhanced fallback options if the standard method fails.
  • Refactor

    • Streamlined and centralized the process for resolving package details, resulting in a more reliable and maintainable experience.

@changeset-bot
Copy link

changeset-bot bot commented Aug 9, 2025

⚠️ No Changeset found

Latest commit: cb46bc5

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@coderabbitai
Copy link

coderabbitai bot commented Aug 9, 2025

Walkthrough

A new asynchronous function, resolvePackageJson, was added to centralize the logic for loading a package's package.json. This function tries multiple strategies: requiring the file from the installed package, reading from the current working directory, and finally fetching from the npm registry if needed. Existing code was refactored to use this helper.

Changes

Cohort / File(s) Change Summary
Package.json Resolution Refactor
src/index.ts
Introduced and exported resolvePackageJson async function to encapsulate multi-strategy resolution of package.json. Replaced inline logic in checkAndPreparePackage with a call to this new helper.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant resolvePackageJson
    participant InstalledPackage
    participant CWD
    participant NpmRegistry

    Caller->>resolvePackageJson: Call with packageName, versionOrCheckVersion
    resolvePackageJson->>InstalledPackage: Try require(package.json)
    alt Success
        resolvePackageJson-->>Caller: Return package.json
    else Fail
        resolvePackageJson->>CWD: Try read package.json from cwd
        alt Success
            resolvePackageJson-->>Caller: Return package.json
        else Fail
            resolvePackageJson->>NpmRegistry: Fetch package.json from npm registry (needs version)
            alt Success
                resolvePackageJson-->>Caller: Return package.json
            else Fail
                resolvePackageJson-->>Caller: Throw error
            end
        end
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Read package.json from process.cwd() as a fallback (#49)
Improve package.json resolution for Yarn PnP and avoid unnecessary registry fetches (#184)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Suggested labels

feature

Poem

In the warren of code, a new path is spun,
To find package.json, three ways, not one!
From node_modules, cwd, or the npm sky—
Now postinstalls hop and never run dry.
With clever resolve, our builds never stall,
This bunny’s quite proud—good work, one and all! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate unit tests to generate unit tests for 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.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 9, 2025

Open in StackBlitz

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

commit: cb46bc5

Copy link

@ellipsis-dev ellipsis-dev bot left a comment

Choose a reason for hiding this comment

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

Important

Looks good to me! 👍

Reviewed everything up to cb46bc5 in 48 seconds. Click for details.
  • Reviewed 72 lines of code in 1 files
  • Skipped 0 files when reviewing.
  • Skipped posting 3 draft comments. View those below.
  • Modify your settings and rules to customize what types of comments Ellipsis leaves. And don't forget to react with 👍 or 👎 to teach Ellipsis.
1. src/index.ts:256
  • Draft comment:
    Consider using an explicit absolute path (e.g. path.join(process.cwd(), PACKAGE_JSON)) when reading from the filesystem. This avoids ambiguity about the file’s location.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
2. src/index.ts:247
  • Draft comment:
    The 'versionOrCheckVersion' parameter is overloaded as a boolean or string. Consider splitting it into two separate parameters for clarity.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None
3. src/index.ts:268
  • Draft comment:
    Ensure that 'packageName' and the version string are URL-encoded when constructing the registry URL for fetching package.json.
  • Reason this comment was not posted:
    Confidence changes required: 33% <= threshold 50% None

Workflow ID: wflow_k8R3EluPUEk0qplu

You can customize Ellipsis by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.

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

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

256-259: Non-blocking I/O inside async function

Use fs.promises to avoid blocking the event loop during postinstall.

-      return JSON.parse(fs.readFileSync(PACKAGE_JSON, 'utf8')) as PackageJson
+      return JSON.parse(
+        await fs.promises.readFile(PACKAGE_JSON, 'utf8'),
+      ) as PackageJson

256-259: Guard against reading the wrong package.json from CWD

If the CWD package.json doesn't match the requested packageName, log and proceed to the next fallback instead of silently returning a mismatched manifest.

-      return JSON.parse(fs.readFileSync(PACKAGE_JSON, 'utf8')) as PackageJson
+      const pkgJson = JSON.parse(
+        await fs.promises.readFile(PACKAGE_JSON, 'utf8'),
+      ) as PackageJson
+      if (pkgJson?.name && pkgJson.name !== packageName) {
+        errorLog(
+          `Read ${PACKAGE_JSON} from CWD but name (${pkgJson.name}) does not match requested package (${packageName}); proceeding with fallback`,
+        )
+      } else {
+        return pkgJson
+      }

294-297: LGTM: centralizes resolution logic

Replacing the inline logic with resolvePackageJson simplifies the flow and aligns with the PR’s objective. Consider passing only strings for the second arg to avoid accidentally threading boolean values, though your helper currently defends against that.

-    packageJson = await resolvePackageJson(
-      packageNameOrPackageJson,
-      versionOrCheckVersion,
-    )
+    packageJson = await resolvePackageJson(
+      packageNameOrPackageJson,
+      typeof versionOrCheckVersion === 'string'
+        ? versionOrCheckVersion
+        : undefined,
+    )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35b8970 and cb46bc5.

📒 Files selected for processing (1)
  • src/index.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/index.ts (3)
src/types.ts (1)
  • PackageJson (28-33)
src/constants.ts (1)
  • PACKAGE_JSON (21-21)
src/helpers.ts (2)
  • errorMessage (280-282)
  • getGlobalNpmRegistry (9-18)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Lint and Test with Node.js 24 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
  • GitHub Check: Lint and Test with Node.js 20 on windows-latest
🔇 Additional comments (1)
src/index.ts (1)

247-274: Should this helper be exported?

resolvePackageJson is introduced but not exported. If the intent is to make it reusable outside this module (as the PR summary suggests), export it.

-async function resolvePackageJson(
+export async function resolvePackageJson(
   packageName: string,
   versionOrCheckVersion?: boolean | string,
 ): Promise<PackageJson> {

Likely an incorrect or invalid review comment.

Comment on lines +261 to +271
if (typeof versionOrCheckVersion !== 'string') {
throw new TypeError(
errorMessage(
`Failed to load \`${PACKAGE_JSON}\` from \`${packageName}\`, please provide a version.`,
),
)
}
const packageJsonBuffer = await fetch(
`${getGlobalNpmRegistry()}${packageName}/${versionOrCheckVersion}`,
)
return JSON.parse(packageJsonBuffer.toString('utf8')) as PackageJson
Copy link

@coderabbitai coderabbitai bot Aug 9, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix scoped package URL encoding and respect offline/PnP to avoid unwanted network access

Two issues:

  • For scoped packages, the registry path must encode the slash (e.g. @scope%2fname) or requests can fail.
  • To fully address offline/PnP concerns from the linked issues, gate the network fallback under PnP/offline environments and surface a clear error instead of attempting fetches.
-      const packageJsonBuffer = await fetch(
-        `${getGlobalNpmRegistry()}${packageName}/${versionOrCheckVersion}`,
-      )
+      // Avoid unwanted network calls in restricted environments
+      if (
+        isPnp() ||
+        process.env.npm_config_offline === 'true' ||
+        process.env.npm_config_offline === '1'
+      ) {
+        throw new Error(
+          errorMessage(
+            `Network fetch disabled in PnP/offline environment; ensure \`${PACKAGE_JSON}\` is available locally.`,
+          ),
+        )
+      }
+      // Encode scoped names for registry API, e.g. @scope%2fname
+      const encodedName = packageName.startsWith('@')
+        ? `@${packageName.slice(1).replace(/\//g, '%2f')}`
+        : packageName
+      const packageJsonBuffer = await fetch(
+        `${getGlobalNpmRegistry()}${encodedName}/${versionOrCheckVersion}`,
+      )

If you'd prefer, I can wire this behind an explicit allowNetwork flag instead of env/PnP detection.

📝 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
if (typeof versionOrCheckVersion !== 'string') {
throw new TypeError(
errorMessage(
`Failed to load \`${PACKAGE_JSON}\` from \`${packageName}\`, please provide a version.`,
),
)
}
const packageJsonBuffer = await fetch(
`${getGlobalNpmRegistry()}${packageName}/${versionOrCheckVersion}`,
)
return JSON.parse(packageJsonBuffer.toString('utf8')) as PackageJson
if (typeof versionOrCheckVersion !== 'string') {
throw new TypeError(
errorMessage(
`Failed to load \`${PACKAGE_JSON}\` from \`${packageName}\`, please provide a version.`,
),
)
}
// Avoid unwanted network calls in restricted environments
if (
isPnp() ||
process.env.npm_config_offline === 'true' ||
process.env.npm_config_offline === '1'
) {
throw new Error(
errorMessage(
`Network fetch disabled in PnP/offline environment; ensure \`${PACKAGE_JSON}\` is available locally.`,
),
)
}
// Encode scoped names for registry API, e.g. @scope%2fname
const encodedName = packageName.startsWith('@')
? `@${packageName.slice(1).replace(/\//g, '%2f')}`
: packageName
const packageJsonBuffer = await fetch(
`${getGlobalNpmRegistry()}${encodedName}/${versionOrCheckVersion}`,
)
return JSON.parse(packageJsonBuffer.toString('utf8')) as PackageJson
🤖 Prompt for AI Agents
In src/index.ts around lines 261 to 271, the code does not encode scoped package
names in the URL, causing fetch failures, and it attempts network fetches
without checking for offline or PnP environments. Fix this by URL-encoding the
packageName when constructing the fetch URL to handle scoped packages correctly.
Additionally, add a condition to detect offline or PnP environments and prevent
network fetches in those cases, throwing a clear error instead of attempting the
fetch. Optionally, consider adding an explicit allowNetwork flag to control
network access.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Bad robot - you've suggested the exact opposite of what works. Under the current system you are guaranteed to need to access the network when in PnP mode.

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@mrginglymus
Copy link
Contributor Author

Tested locally and it works as expected.

@mrginglymus
Copy link
Contributor Author

I wonder if this should be the primary means of fetching the package.json? Assuming it holds true (that postinstall scripts have a cwd of the given package) it's then going to guarantee picking up the correct version of the package if multiple are present.

@JounQin
Copy link
Member

JounQin commented Aug 9, 2025

I think it should be used only as last fallback and within cli.ts maybe. The index script itself is not guaranteed to be executed in correct pwd, for example, involve checkAndPreparePackage programmably.

@mrginglymus
Copy link
Contributor Author

Ah, good point. I'll raise another PR with the loading in cli.

@mrginglymus
Copy link
Contributor Author

@JounQin see #51

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.

Consider reading package.json from process.cwd() Unable to install on CI - 401 http error [Yarn PnP]

2 participants