Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion packages/angular/cli/src/package-managers/package-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* a flexible and secure abstraction over the various package managers.
*/

import { join, relative, resolve } from 'node:path';
import { dirname, join, relative, resolve } from 'node:path';
import npa from 'npm-package-arg';
import { maxSatisfying, valid } from 'semver';
import { PackageManagerError } from './error';
Expand Down Expand Up @@ -154,9 +154,63 @@ export class PackageManager {
this.descriptor.outputParsers.listDependencies(stdout, logger, { workspacePackageName }),
);

// `bun pm ls` has no per-workspace-member output. Run from a member, it lists the workspace
// root's dependencies, which are the members themselves (e.g. `app@workspace:app`).
if (
this.descriptor.binary === 'bun' &&
workspacePackageName &&
dependencies?.get(workspacePackageName)?.version.startsWith('workspace:')
) {
return (this.#dependencyCache = await this.#readDependenciesFromManifests());
}

return (this.#dependencyCache = dependencies ?? new Map());
}

/**
* Builds the dependency map of the project in the working directory from its `package.json`
* and the manifests of the packages installed in `node_modules`.
* @returns A map of the declared dependencies that are installed to their installed details.
*/
async #readDependenciesFromManifests(): Promise<Map<string, InstalledPackage>> {
const dependencies = new Map<string, InstalledPackage>();

let declared: Record<string, Record<string, string> | undefined>;
try {
declared = JSON.parse(await this.host.readFile(join(this.cwd, 'package.json')));
} catch {
return dependencies;
}

const names = new Set<string>();
for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
Object.keys(declared[field] ?? {}).forEach((name) => names.add(name));
}
Comment on lines +178 to +188

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

If package.json contains null or a non-object value (e.g., "null"), JSON.parse will succeed but declared will be null or a primitive. Accessing declared[field] will then throw a TypeError outside of the try-catch block, crashing the CLI.

Additionally, if a dependency field is malformed (e.g., a string or array instead of an object), Object.keys might return unexpected keys (like array indices or string character offsets).

We should add defensive checks to ensure declared is a non-null object and that each dependency field is also a valid object before extracting keys.

    let declared: unknown;
    try {
      declared = JSON.parse(await this.host.readFile(join(this.cwd, 'package.json')));
    } catch {
      return dependencies;
    }

    if (!declared || typeof declared !== 'object' || Array.isArray(declared)) {
      return dependencies;
    }

    const names = new Set<string>();
    for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {
      const deps = (declared as Record<string, unknown>)[field];
      if (deps && typeof deps === 'object' && !Array.isArray(deps)) {
        Object.keys(deps).forEach((name) => names.add(name));
      }
    }


for (const name of names) {
// Resolve the package like Node.js does: look in the `node_modules` of the project, then in
// those of its parent directories (hoisted workspace installs).
for (let dir = this.cwd; ; dir = dirname(dir)) {
const path = join(dir, 'node_modules', name);
try {
const { version } = JSON.parse(await this.host.readFile(join(path, 'package.json')));
if (typeof version === 'string') {
dependencies.set(name, { name, version, path });
}
break;
} catch {
// Not installed at this level.
}

if (dirname(dir) === dir) {
break;
}
}
}

return dependencies;
}

/**
* A private method to run a command using the package manager's binary.
* @param args The arguments to pass to the command.
Expand Down
32 changes: 32 additions & 0 deletions packages/angular/cli/src/package-managers/package-manager_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,38 @@ describe('PackageManager', () => {
expect([...dependencies.keys()]).toEqual(['@angular/core']);
expect(dependencies.get('@angular/core')?.version).toBe('22.0.0');
});

it('should list the dependencies of a bun workspace member', async () => {
const pm = new PackageManager(host, '/repo/app', SUPPORTED_PACKAGE_MANAGERS['bun']);
// `bun pm ls` run from a member prints the root's dependencies, i.e. the members themselves.
runCommandSpy.and.resolveTo({
stdout: '/repo node_modules (405 installed)\n└── app@workspace:app',
stderr: '',
});
const files: Record<string, string> = {
'/repo/app/package.json': JSON.stringify({
name: 'app',
dependencies: { '@angular/core': '^22.0.0' },
devDependencies: { typescript: '~5.9.0' },
}),
'/repo/node_modules/@angular/core/package.json':
'{"name":"@angular/core","version":"22.2.3"}',
'/repo/node_modules/typescript/package.json': '{"name":"typescript","version":"5.9.3"}',
};
spyOn(host, 'readFile').and.callFake((path: string) => {
const content = files[path.replace(/\\/g, '/')];

return content === undefined
? Promise.reject(new Error('ENOENT'))
: Promise.resolve(content);
});

const dependencies = await pm.getProjectDependencies();

expect([...dependencies.keys()].sort()).toEqual(['@angular/core', 'typescript']);
expect(dependencies.get('@angular/core')?.version).toBe('22.2.3');
expect(dependencies.get('typescript')?.version).toBe('5.9.3');
});
});

describe('initializationError', () => {
Expand Down
Loading