'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installModules = installModules;
const joi_1 = __importDefault(require("joi"));
const path = __importStar(require("path"));
const hdbError_ts_1 = require("./errors/hdbError.js");
const { HTTP_STATUS_CODES } = hdbError_ts_1.hdbErrors;
const validator = __importStar(require("../validation/validationWrapper.js"));
const harper_logger_ts_1 = __importDefault(require("./logging/harper_logger.js"));
const hdbTerms_ts_1 = require("./hdbTerms.js");
const configUtils_js_1 = require("../config/configUtils.js");
const Application_ts_1 = require("../components/Application.js");
/**
 * Executes npm install against specified custom function projects
 * @param {Object} req
 * @returns {Promise<{}>}
 */
async function installModules(req) {
    const deprecationWarning = 'install_node_modules is deprecated. Dependencies are automatically installed on' +
        ' deploy, and install_node_modules can lead to inconsistent behavior';
    harper_logger_ts_1.default.warn(deprecationWarning, req.projects);
    const validation = modulesValidator(req);
    if (validation) {
        throw (0, hdbError_ts_1.handleHDBError)(validation, validation.message, HTTP_STATUS_CODES.BAD_REQUEST);
    }
    let { projects, dryRun } = req;
    const componentsRootDirPath = (0, configUtils_js_1.getConfigPath)(hdbTerms_ts_1.CONFIG_PARAMS.COMPONENTSROOT);
    const responseObject = {};
    const args = ['install', '--force', '--omit=dev', '--json'];
    if (dryRun)
        args.push('--dry-run');
    for (const project of projects) {
        responseObject[project] = { npm_output: null, npm_error: null };
        const projectPath = path.join(componentsRootDirPath, project);
        try {
            let { stdout, stderr } = await (0, Application_ts_1.nonInteractiveSpawn)(project, 'npm', args, projectPath);
            stdout = stdout ? stdout.replace('\n', '') : null;
            stderr = stderr ? stderr.replace('\n', '') : null;
            try {
                responseObject[project].npm_output = JSON.parse(stdout);
            }
            catch {
                responseObject[project].npm_output = stdout;
            }
            try {
                responseObject[project].npm_error = JSON.parse(stderr);
            }
            catch {
                responseObject[project].npm_error = stderr;
            }
        }
        catch (error) {
            if (error.stderr) {
                responseObject[project].npm_error = parseNPMStdErr(error.stderr);
            }
            else {
                responseObject[project].npm_error = error.message;
            }
            continue;
        }
    }
    harper_logger_ts_1.default.info(`finished installModules with response ${responseObject}`);
    responseObject.warning = deprecationWarning;
    return responseObject;
}
function parseNPMStdErr(stderr) {
    //npm returns errors inconsistently, on 6 it returns json, on 8 it returns json stringified inside of a larger string
    let startSearchString = '"error": {';
    let start = stderr.indexOf('"error": {');
    let end = stderr.indexOf('}\n');
    if (start > -1 && end > -1) {
        return JSON.parse(stderr.substring(start + startSearchString.length - 1, end + 1));
    }
    else {
        return stderr;
    }
}
/**
 * Validator for both installModules & auditModules
 * @param {Object} req
 * @returns {*}
 */
function modulesValidator(req) {
    const funcSchema = joi_1.default.object({
        projects: joi_1.default.array().min(1).items(joi_1.default.string()).required(),
        dry_run: joi_1.default.boolean().default(false),
    });
    return validator.validateBySchema(req, funcSchema);
}
//# sourceMappingURL=npmUtilities.js.map