"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments)).next());
    });
};
const path = require("path");
const loadJsonFile = require("load-json-file");
/**
 * Check if a module exists (eg, `node_modules/node-pre-gyp`). This is the case when
 * it's part of bundleDependencies.
 *
 * This check is also responsible for stopping `pnpm i lodash` from doing anything when
 * 'node_modules/lodash' already exists.
 *
 * @example
 *     spec = { name: 'lodash', spec: '^3.0.2' }
 *     isAvailable(spec, 'path/to/node_modules')
 */
function isAvailable(spec, modules) {
    return __awaiter(this, void 0, void 0, function* () {
        const name = spec && spec.name;
        if (!name)
            return false;
        const packageJsonPath = path.join(modules, name, 'package.json');
        try {
            /* TODO: what to do with bundled deps?
            const stat = await fs.lstat(path.join(modules, name))
            if (stat.isDirectory()) {
              return true
            }*/
            const pkgJson = yield loadJsonFile(packageJsonPath);
            return verify(spec, pkgJson);
        }
        catch (err) {
            if (err.code !== 'ENOENT')
                throw err;
            return false;
        }
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = isAvailable;
function verify(spec, packageJson) {
    return packageJson.name === spec.name &&
        ((spec.type !== 'range' && spec.type !== 'version' && spec.type !== 'tag') ||
            packageJson.version === spec.spec);
}
//# sourceMappingURL=isAvailable.js.map