"use strict";
/*
 * @poppinss/utils
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveDir = void 0;
const resolve_from_1 = __importDefault(require("resolve-from"));
const path_1 = require("path");
/**
 * Resolves path to a given directory. The method is similar to `require.resolve`,
 * but also works for directories with no `index.js` file.
 */
function resolveDir(fromLocation, dirPath) {
    if ((0, path_1.isAbsolute)(dirPath)) {
        return dirPath;
    }
    /**
     * Relative paths are made by joining the baseDir
     */
    if (dirPath.startsWith('./') || dirPath.startsWith(`.${path_1.sep}`)) {
        return (0, path_1.join)(fromLocation, dirPath);
    }
    /**
     * From here on, we are dealing with a package inside node module.
     */
    let packageName = '';
    const tokens = dirPath.replace(/\\/g, '/').split('/');
    if (tokens.length && tokens[0].startsWith('@')) {
        packageName = `${tokens.shift()}/`;
    }
    packageName += tokens.shift();
    const resolved = resolve_from_1.default.silent(fromLocation, (0, path_1.join)(packageName, 'package.json'));
    if (!resolved) {
        throw new Error(`Cannot locate directory "${dirPath}"`);
    }
    return (0, path_1.join)((0, path_1.dirname)(resolved), tokens.join('/'));
}
exports.resolveDir = resolveDir;
