/**
 * Adapted from `get-monorepo-packages` by Lucas Azzola
 * @license MIT
 * @see https://github.com/azz/get-monorepo-packages/
 */
import { join } from 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import glob from 'glob';
const readJsonSync = (path) => {
    try {
        return JSON.parse(readFileSync(path, 'utf8'));
    }
    catch {
        return null;
    }
};
function loadPackage(packagePath) {
    const pkgJsonPath = join(packagePath, 'package.json');
    if (existsSync(pkgJsonPath)) {
        return readJsonSync(pkgJsonPath);
    }
}
function findPackages(packageSpecs, rootDirectory) {
    return packageSpecs
        .flatMap(pkgGlob => (glob.hasMagic(pkgGlob) ?
        glob.sync(join(rootDirectory, pkgGlob), { nodir: false })
        : [join(rootDirectory, pkgGlob)]))
        .map(location => ({ location, package: loadPackage(location) }))
        .filter((x) => !!x.package?.name);
}
export function getAllPackages(rootDir) {
    const rootPackagePath = join(rootDir, 'package.json');
    const rootPackage = readJsonSync(rootPackagePath);
    if (Array.isArray(rootPackage?.workspaces)) {
        return findPackages(rootPackage.workspaces, rootDir);
    }
    else if (rootPackage) {
        return [{ package: rootPackage, location: rootDir }];
    }
    else {
        return [];
    }
}
//# sourceMappingURL=get-all-packages.js.map