feat: try reading package.json from cwd#50
Conversation
|
WalkthroughA new asynchronous function, Changes
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changesNo out-of-scope changes found. Suggested labels
Poem
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 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
commit: |
There was a problem hiding this comment.
Important
Looks good to me! 👍
Reviewed everything up to cb46bc5 in 48 seconds. Click for details.
- Reviewed
72lines of code in1files - Skipped
0files when reviewing. - Skipped posting
3draft 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%<= threshold50%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%<= threshold50%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%<= threshold50%None
Workflow ID: wflow_k8R3EluPUEk0qplu
You can customize by changing your verbosity settings, reacting with 👍 or 👎, replying to comments, or adding code review rules.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/index.ts (3)
256-259: Non-blocking I/O inside async functionUse 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 CWDIf 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 logicReplacing 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
📒 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.
| 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 |
There was a problem hiding this comment.
🛠️ 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.
| 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
|
Tested locally and it works as expected. |
|
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. |
|
I think it should be used only as last fallback and within |
|
Ah, good point. I'll raise another PR with the loading in cli. |
process.cwd()#49Important
Adds
resolvePackageJson()to readpackage.jsonfrom cwd if initial require fails, updatingcheckAndPreparePackage()to use it, fixing two issues.resolvePackageJson()insrc/index.tsto readpackage.jsonfrom the current working directory if initial require fails.checkAndPreparePackage()to useresolvePackageJson()for resolvingpackage.json.process.cwd()#49.This description was created by
for cb46bc5. You can customize this summary. It will automatically update as commits are pushed.
Summary by CodeRabbit
New Features
Refactor