Skip to content

fix: resolve package.json path correctly in bundled build#88

Merged
utkarsh232005 merged 2 commits into
KDM-cli:mainfrom
utkarsh232005:fix/version-check-path
May 23, 2026
Merged

fix: resolve package.json path correctly in bundled build#88
utkarsh232005 merged 2 commits into
KDM-cli:mainfrom
utkarsh232005:fix/version-check-path

Conversation

@utkarsh232005
Copy link
Copy Markdown
Member

@utkarsh232005 utkarsh232005 commented May 23, 2026

Resolves #47

This PR resolves the issue where the update notification displays Current Version : v0.0.0 instead of the actual installed version (e.g., 1.2.2).

  • Update getInstalledVersion inside src/utils/version-check.ts to probe multiple relative paths:
    1. dist/../package.json (production/bundled build)
    2. src/utils/../../package.json (development/testing)
  • Tested both contexts, ensuring the build outputs compile successfully and retrieve correct versions.

Summary by CodeRabbit

  • Bug Fixes
    • Improved version detection reliability by checking multiple runtime layouts and gracefully falling back to a default when version information is unavailable.
  • New Features
    • Exposed a utility to read the installed application version at runtime for broader visibility.
  • Tests
    • Added coverage validating version resolution across different layout and failure scenarios.

Review Change Stack

Copilot AI review requested due to automatic review settings May 23, 2026 14:12
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key(s) in object: 'pre_merge_checks'
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • 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
📝 Walkthrough

Walkthrough

getInstalledVersion() was exported and updated to probe two candidate runtime package.json paths (production and development), returning the first valid version string; read/parse failures or missing/non-string versions are ignored and the function falls back to '0.0.0'.

Changes

Version Detection Improvement

Layer / File(s) Summary
Multi-path version resolution
src/utils/version-check.ts
getInstalledVersion() exported and updated to iterate two candidate package.json paths (production build and development layout), parse each, return the first valid string version, and fall back to '0.0.0' if none succeed.
Tests for version resolution
src/__tests__/version-check.test.ts
Adds tests that mock node:fs.readFileSync, cover production vs development path selection, malformed JSON, missing/invalid version, and fallback behavior; ensures per-test mock reset for isolation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • KDM-cli/kdm-cli#29: Modifies the same version-check.ts utility and affects installed-version extraction used by update notifications.

Poem

Two package paths now take their chance,
read, parse, and gracefully advance—
when versions hide or files are shy,
a fallback hums: 0.0.0 nearby. ✨

🚥 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 title accurately describes the main change: exporting and updating getInstalledVersion() to resolve package.json from multiple paths in bundled builds.
Linked Issues check ✅ Passed The implementation directly addresses issue #47 by probing multiple package.json paths to correctly resolve the version in both production and development contexts, fixing the 0.0.0 display issue.
Out of Scope Changes check ✅ Passed All changes are strictly scoped to version resolution: exporting getInstalledVersion(), adding multi-path logic, and comprehensive test coverage—no unrelated modifications present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

📋 Issue Planner

Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).

View plan for ticket: #47

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

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

Copy link
Copy Markdown
Contributor

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

Fixes the update notification’s “Current Version : v0.0.0” bug by making runtime version detection locate the correct package.json in both bundled (dist) and source (src) execution contexts.

Changes:

  • Updated getInstalledVersion() to probe multiple candidate package.json locations relative to the runtime module path.
  • Falls back to 0.0.0 only after exhausting all candidate paths.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/utils/version-check.ts Outdated
Comment on lines +12 to +19
const paths = [
join(__dirname, '..', 'package.json'), // production: dist/../package.json
join(__dirname, '..', '..', 'package.json') // development: src/utils/../../package.json
];
for (const pkgPath of paths) {
try {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
if (pkg.version) return pkg.version;
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/utils/version-check.ts`:
- Around line 16-23: The loop that reads package.json files currently returns
pkg.version without type-checking; update the code in the for-loop that reads
pkgPath/JSON.parse so that you only return pkg.version if typeof pkg.version ===
'string' (otherwise continue to next path), ensuring compareSemver (which calls
.replace()) always receives a string; do not coerce non-string values—skip them
and try the next path or fall back to the existing default behavior.
- Around line 11-25: Add Vitest tests that exercise every branch of
getInstalledVersion(): mock node:fs.readFileSync with vi.mock('node:fs') and
return fixture contents for the "production" path (valid package.json with
version) and the "development" path (valid package.json with version) to assert
correct version is returned; add mocks that return malformed JSON to assert the
try/catch advances to the next path; add mocks that return valid JSON without a
version field to assert it continues searching; and add mocks that throw for
both paths to assert the function falls back to '0.0.0'. Reference
getInstalledVersion() in src/utils/version-check.ts and use fixtures/return
values keyed to the two join(__dirname, ...) paths to ensure each branch is
covered.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 72ddbb32-1dee-4528-ba57-cc845dee9d05

📥 Commits

Reviewing files that changed from the base of the PR and between 1baeab7 and 4ac1845.

📒 Files selected for processing (1)
  • src/utils/version-check.ts

Comment thread src/utils/version-check.ts Outdated
Comment thread src/utils/version-check.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/__tests__/version-check.test.ts`:
- Around line 113-115: The mocked readFileSync implementation uses
path.endsWith(...) assuming POSIX separators; normalize the incoming path before
the suffix checks to make tests OS-portable by converting backslashes to forward
slashes or using path.normalize()/path.posix methods. Update the
vi.mocked(readFileSync).mockImplementation callback (and the other similar mock
implementations at the other locations) to coerce the path (e.g., const p =
String(path).replace(/\\\\/g, '/')) and then use p.endsWith('src/package.json')
(and the other suffixes) so the tests pass on Windows.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3ab71436-a6c8-48ee-8283-6b9b5c91f84c

📥 Commits

Reviewing files that changed from the base of the PR and between 4ac1845 and 0f626c6.

📒 Files selected for processing (2)
  • src/__tests__/version-check.test.ts
  • src/utils/version-check.ts

Comment on lines +113 to +115
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.endsWith('src/package.json')) {
return JSON.stringify({ version: '2.3.4' });
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize mocked file paths before suffix checks.

Line 114/125/136/150 style checks assume / separators, so these tests can fail on Windows (\). Normalize path before endsWith() to make tests portable.

💡 Suggested fix
+const normalizePath = (p: unknown) => String(p).replace(/\\/g, '/');

     it('should resolve and return the version if package.json in production path is valid', () => {
       vi.mocked(readFileSync).mockImplementation((path) => {
-        if (typeof path === 'string' && path.endsWith('src/package.json')) {
+        const normalized = normalizePath(path);
+        if (normalized.endsWith('src/package.json')) {
           return JSON.stringify({ version: '2.3.4' });
         }
         throw new Error('File not found');
       });

       expect(getInstalledVersion()).toBe('2.3.4');
     });

Also applies to: 125-126, 136-140, 150-154

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/__tests__/version-check.test.ts` around lines 113 - 115, The mocked
readFileSync implementation uses path.endsWith(...) assuming POSIX separators;
normalize the incoming path before the suffix checks to make tests OS-portable
by converting backslashes to forward slashes or using
path.normalize()/path.posix methods. Update the
vi.mocked(readFileSync).mockImplementation callback (and the other similar mock
implementations at the other locations) to coerce the path (e.g., const p =
String(path).replace(/\\\\/g, '/')) and then use p.endsWith('src/package.json')
(and the other suffixes) so the tests pass on Windows.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

An unexpected error occurred while generating fixes: Not Found - https://docs.github.com/rest/git/refs#get-a-reference

@utkarsh232005 utkarsh232005 merged commit 670dd7a into KDM-cli:main May 23, 2026
17 checks passed
@utkarsh232005 utkarsh232005 deleted the fix/version-check-path branch May 23, 2026 20:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Incorrect version showing

2 participants