@api-buddy/plugin-utils
Version:
Shared utilities for API Buddy plugins
72 lines (63 loc) • 1.95 kB
text/typescript
import { PackageJson } from 'type-fest';
import { fsUtils } from './fs.js';
import path from 'path';
/**
* Get the package.json content as an object
*/
export async function readPackageJson(dir: string): Promise<PackageJson> {
const packageJsonPath = path.join(dir, 'package.json');
const content = await fsUtils.readFile(packageJsonPath);
return JSON.parse(content) as PackageJson;
}
/**
* Update package.json with new content
*/
export async function updatePackageJson(
dir: string,
updater: (pkg: PackageJson) => PackageJson | Promise<PackageJson>
): Promise<void> {
const pkg = await readPackageJson(dir);
const updatedPkg = await updater(pkg);
const packageJsonPath = path.join(dir, 'package.json');
await fsUtils.writeFile(
packageJsonPath,
JSON.stringify(updatedPkg, null, 2) + '\n'
);
}
/**
* Install dependencies using the package manager used in the project
*/
export async function installDependencies(
dir: string,
deps: string[],
{ isDev = false, cwd = process.cwd() }: { isDev?: boolean; cwd?: string } = {}
): Promise<void> {
if (deps.length === 0) return;
const pkgManager = await detectPackageManager(cwd);
const args = [
pkgManager === 'yarn' ? 'add' : 'install',
...(pkgManager === 'npm' ? ['install'] : []),
...(isDev ? [pkgManager === 'npm' ? '--save-dev' : '-D'] : []),
...deps,
].filter(Boolean);
await fsUtils.runCommand(`${pkgManager} ${args.join(' ')}`, { cwd });
}
/**
* Detect the package manager used in the project
*/
export async function detectPackageManager(cwd: string): Promise<'npm' | 'yarn' | 'pnpm'> {
if (await fsUtils.exists(path.join(cwd, 'pnpm-lock.yaml'))) {
return 'pnpm';
}
if (await fsUtils.exists(path.join(cwd, 'yarn.lock'))) {
return 'yarn';
}
return 'npm';
}
export const packageUtils = {
readPackageJson,
updatePackageJson,
installDependencies,
detectPackageManager,
};
export default packageUtils;