"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const pnpm_logger_1 = require("pnpm-logger");
const path = require("path");
const rimraf = require("rimraf-then");
const resolve_1 = require("./resolve");
const mkdirp = require("mkdirp-promise");
const writeJsonFile = require("write-json-file");
const pkgIdToFilename_1 = require("./fs/pkgIdToFilename");
const readPkg_1 = require("./fs/readPkg");
const exists = require("path-exists");
const fetchResolution_1 = require("./fetchResolution");
const logInstallStatus_1 = require("./logging/logInstallStatus");
const pkgIsUntouched_1 = require("./pkgIsUntouched");
const symlinkDir = require("symlink-dir");
const renameOverwrite = require("rename-overwrite");
const loadJsonFile = require("load-json-file");
function fetch(spec, options) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            let pkg = undefined;
            let resolution = options.shrinkwrapResolution;
            let pkgId = options.pkgId;
            if (!resolution || options.update) {
                const resolveResult = yield resolve_1.default(spec, {
                    loggedPkg: options.loggedPkg,
                    prefix: options.prefix,
                    got: options.got,
                    storePath: options.storePath,
                    registry: options.registry,
                    metaCache: options.metaCache,
                    offline: options.offline,
                    downloadPriority: options.downloadPriority,
                });
                // keep the shrinkwrap resolution when possible
                // to keep the original shasum
                if (pkgId !== resolveResult.id || !resolution) {
                    resolution = resolveResult.resolution;
                }
                pkgId = resolveResult.id;
                pkg = resolveResult.package;
            }
            const id = pkgId;
            logInstallStatus_1.default({ status: 'resolved', pkgId: id, pkg: options.loggedPkg });
            if (resolution.type === 'directory') {
                if (!pkg) {
                    throw new Error(`Couldn't read package.json of local dependency ${spec}`);
                }
                return {
                    isLocal: true,
                    id,
                    pkg,
                    resolution,
                };
            }
            const targetRelative = pkgIdToFilename_1.default(id);
            const target = path.join(options.storePath, targetRelative);
            if (!options.fetchingLocker[id]) {
                options.fetchingLocker[id] = fetchToStore({
                    target,
                    targetRelative,
                    resolution: resolution,
                    pkgId: id,
                    got: options.got,
                    storePath: options.storePath,
                    offline: options.offline,
                    pkg,
                    storeIndex: options.storeIndex,
                    verifyStoreIntegrity: options.verifyStoreIntegrity,
                });
            }
            return {
                isLocal: false,
                fetchingPkg: options.fetchingLocker[id].fetchingPkg,
                fetchingFiles: options.fetchingLocker[id].fetchingFiles,
                calculatingIntegrity: options.fetchingLocker[id].calculatingIntegrity,
                id,
                resolution,
                path: target,
            };
        }
        catch (err) {
            logInstallStatus_1.default({ status: 'error', pkg: options.loggedPkg });
            throw err;
        }
    });
}
exports.default = fetch;
function fetchToStore(opts) {
    const fetchingPkg = differed();
    const fetchingFiles = differed();
    const calculatingIntegrity = differed();
    fetch();
    return {
        fetchingFiles: fetchingFiles.promise,
        fetchingPkg: opts.pkg && Promise.resolve(opts.pkg) || fetchingPkg.promise,
        calculatingIntegrity: calculatingIntegrity.promise,
    };
    function fetch() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                logInstallStatus_1.default({
                    status: 'resolving_content',
                    pkgId: opts.pkgId,
                });
                let target = opts.target;
                const linkToUnpacked = path.join(target, 'package');
                // We can safely assume that if there is no data about the package in `store.json` then
                // it is not in the store yet.
                // In case there is record about the package in `store.json`, we check it in the file system just in case
                const targetExists = opts.storeIndex[opts.targetRelative] && (yield exists(path.join(linkToUnpacked, 'package.json')));
                if (targetExists) {
                    // if target exists and it wasn't modified, then no need to refetch it
                    const satisfiedIntegrity = opts.verifyStoreIntegrity
                        ? yield pkgIsUntouched_1.default(linkToUnpacked)
                        : yield loadJsonFile(path.join(path.dirname(linkToUnpacked), 'integrity.json'));
                    if (satisfiedIntegrity) {
                        logInstallStatus_1.default({
                            status: 'found_in_store',
                            pkgId: opts.pkgId,
                        });
                        fetchingFiles.resolve({
                            isNew: false,
                            index: satisfiedIntegrity,
                        });
                        if (!opts.pkg) {
                            readPkg_1.fromDir(linkToUnpacked)
                                .then(pkg => fetchingPkg.resolve(pkg))
                                .catch(err => fetchingPkg.reject(err));
                        }
                        calculatingIntegrity.resolve(undefined);
                        return;
                    }
                    pnpm_logger_1.default.warn(`Refetching ${target} to store, as it was modified`);
                }
                // We fetch into targetStage directory first and then fs.rename() it to the
                // target directory.
                const targetStage = `${target}_stage`;
                yield rimraf(targetStage);
                let packageIndex = {};
                yield Promise.all([
                    function () {
                        return __awaiter(this, void 0, void 0, function* () {
                            packageIndex = yield fetchResolution_1.default(opts.resolution, targetStage, {
                                got: opts.got,
                                pkgId: opts.pkgId,
                                storePath: opts.storePath,
                                offline: opts.offline,
                            });
                        });
                    }(),
                    // removing only the folder with the unpacked files
                    // not touching tarball and integrity.json
                    targetExists && (yield rimraf(path.join(target, 'node_modules')))
                ]);
                logInstallStatus_1.default({
                    status: 'fetched',
                    pkgId: opts.pkgId,
                });
                // fetchingFilse shouldn't care about when this is saved at all
                if (!targetExists) {
                    (function () {
                        return __awaiter(this, void 0, void 0, function* () {
                            const integrity = opts.verifyStoreIntegrity
                                ? yield packageIndex.integrityPromise
                                : yield packageIndex.headers;
                            writeJsonFile(path.join(target, 'integrity.json'), integrity, { indent: null });
                            calculatingIntegrity.resolve(undefined);
                        });
                    })();
                }
                else {
                    calculatingIntegrity.resolve(undefined);
                }
                let pkg;
                if (opts.pkg) {
                    pkg = opts.pkg;
                }
                else {
                    pkg = yield readPkg_1.fromDir(targetStage);
                    fetchingPkg.resolve(pkg);
                }
                const unpacked = path.join(target, 'node_modules', pkg.name);
                yield mkdirp(path.dirname(unpacked));
                // rename(oldPath, newPath) is an atomic operation, so we do it at the
                // end
                yield renameOverwrite(targetStage, unpacked);
                yield symlinkDir(unpacked, linkToUnpacked);
                fetchingFiles.resolve({
                    isNew: true,
                    index: packageIndex.headers,
                });
            }
            catch (err) {
                fetchingFiles.reject(err);
                if (!opts.pkg) {
                    fetchingPkg.reject(err);
                }
            }
        });
    }
}
function differed() {
    let pResolve = () => { };
    let pReject = () => { };
    const promise = new Promise((resolve, reject) => {
        pResolve = resolve;
        pReject = reject;
    });
    return {
        promise,
        resolve: pResolve,
        reject: pReject,
    };
}
//# sourceMappingURL=fetch.js.map