"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PacoteService = void 0;
const pacote = require("pacote");
const tar = require("tar");
const path = require("path");
const stream_1 = require("stream");
const _ = require("lodash");
const decorators_1 = require("../common/decorators");
const yok_1 = require("../common/yok");
const arborist_1 = require("@npmcli/arborist");
class PacoteService {
    constructor($fs, $injector, $logger, $npmConfigService, $proxyService) {
        this.$fs = $fs;
        this.$injector = $injector;
        this.$logger = $logger;
        this.$npmConfigService = $npmConfigService;
        this.$proxyService = $proxyService;
    }
    get $packageManager() {
        return this.$injector.resolve("packageManager");
    }
    async manifest(packageName, options) {
        this.$logger.trace(`Calling pacoteService.manifest for packageName: '${packageName}' and options: `, options);
        const manifestOptions = await this.getPacoteBaseOptions();
        if (options) {
            _.extend(manifestOptions, options);
        }
        packageName = this.getRealPackageName(packageName);
        this.$logger.trace(`Calling pacote.manifest for packageName: ${packageName} and manifestOptions:`, manifestOptions);
        const result = await pacote.manifest(packageName, manifestOptions);
        this.$logger.trace("pacote.manifest result:", result);
        return result;
    }
    async extractPackage(packageName, destinationDirectory, options) {
        this.$logger.trace(`Calling pacoteService.extractPackage for packageName: '${packageName}', destinationDir: '${destinationDirectory}' and options: ${options}`);
        const extractOptions = { strip: 1, C: destinationDirectory };
        if (options) {
            _.extend(extractOptions, options);
        }
        packageName = this.getRealPackageName(packageName);
        const pacoteOptions = await this.getPacoteBaseOptions();
        return new Promise(async (resolve, reject) => {
            this.$logger.trace(`Calling pacoteService.extractPackage for packageName: '${packageName}', destinationDir: '${destinationDirectory}' and options: ${options}`);
            const source = await pacote
                .tarball(packageName, pacoteOptions)
                .catch((err) => {
                this.$logger.trace(`Error in source while trying to extract stream from ${packageName}. Error is ${err}`);
                reject(err);
            });
            this.$logger.trace(`Creating extract tar stream with options: ${JSON.stringify(extractOptions, null, 2)}`);
            const destination = tar.x(extractOptions);
            const sourceStream = new stream_1.PassThrough();
            sourceStream.end(source);
            sourceStream.pipe(destination);
            destination.on("error", (err) => {
                this.$logger.trace(`Error in destination while trying to extract stream from ${packageName}. Error is ${err}`);
                reject(err);
            });
            destination.on("finish", () => {
                this.$logger.trace(`Successfully extracted '${packageName}' to ${destinationDirectory}`);
                resolve();
            });
        });
    }
    async getPacoteBaseOptions() {
        const cachePath = await this.$packageManager.getCachePath();
        const npmConfig = this.$npmConfigService.getConfig();
        const pacoteOptions = _.extend(npmConfig, { cache: cachePath, Arborist: arborist_1.Arborist });
        const proxySettings = await this.$proxyService.getCache();
        if (proxySettings) {
            _.extend(pacoteOptions, proxySettings);
        }
        return pacoteOptions;
    }
    getRealPackageName(packageName) {
        if (this.$fs.exists(packageName)) {
            this.$logger.trace(`Will resolve the full path to package ${packageName}.`);
            packageName = path.resolve(packageName);
        }
        return packageName;
    }
}
exports.PacoteService = PacoteService;
__decorate([
    (0, decorators_1.cache)()
], PacoteService.prototype, "$packageManager", null);
yok_1.injector.register("pacoteService", PacoteService);
