"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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs-extra");
var path = require("path");
var Walker = (function () {
    function Walker(modulePath) {
        this.prodPaths = new Set();
        this.rootModule = modulePath;
    }
    Walker.prototype.relativeModule = function (rootPath, moduleName) {
        return path.resolve(rootPath, 'node_modules', moduleName);
    };
    Walker.prototype.loadPackageJSON = function (modulePath) {
        return __awaiter(this, void 0, void 0, function () {
            var pJPath;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        pJPath = path.resolve(modulePath, 'package.json');
                        return [4 /*yield*/, fs.pathExists(pJPath)];
                    case 1:
                        if (!_a.sent()) return [3 /*break*/, 3];
                        return [4 /*yield*/, fs.readJson(pJPath)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3: return [2 /*return*/, null];
                }
            });
        });
    };
    Walker.prototype.loadProductionDependenciesForModuleInModule = function (moduleName, modulePath, allowMissing) {
        if (allowMissing === void 0) { allowMissing = false; }
        return __awaiter(this, void 0, void 0, function () {
            var testPath, discoveredPath, lastRelative;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        testPath = modulePath;
                        discoveredPath = null;
                        lastRelative = null;
                        _a.label = 1;
                    case 1:
                        if (!(!discoveredPath && this.relativeModule(testPath, moduleName) !== lastRelative)) return [3 /*break*/, 3];
                        lastRelative = this.relativeModule(testPath, moduleName);
                        return [4 /*yield*/, fs.pathExists(lastRelative)];
                    case 2:
                        if (_a.sent()) {
                            discoveredPath = lastRelative;
                        }
                        else {
                            if (path.basename(path.dirname(testPath)) !== 'node_modules') {
                                testPath = path.dirname(testPath);
                            }
                            testPath = path.dirname(path.dirname(testPath));
                        }
                        return [3 /*break*/, 1];
                    case 3:
                        // If we can't find it the install is probably buggered
                        if (!discoveredPath && !allowMissing) {
                            throw new Error("Failed to locate module \"" + moduleName + "\" from \"" + modulePath + "\"\n\n        This normally means that either you have deleted this package already somehow (check your ignore settings if using electron-packager).  Or your module installation failed.");
                        }
                        if (!discoveredPath) return [3 /*break*/, 5];
                        return [4 /*yield*/, this.loadProductionDependenciesForModule(discoveredPath, allowMissing)];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    Walker.prototype.loadProductionDependenciesForModule = function (modulePath, allowMissing) {
        if (allowMissing === void 0) { allowMissing = false; }
        return __awaiter(this, void 0, void 0, function () {
            var pJ, _a, _b, _i, moduleName, _c, _d, _e, moduleName;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        // We have already traversed this module
                        if (this.prodPaths.has(modulePath))
                            return [2 /*return*/];
                        // Record this module as a production dependency
                        this.prodPaths.add(modulePath);
                        return [4 /*yield*/, this.loadPackageJSON(modulePath)];
                    case 1:
                        pJ = _f.sent();
                        // If the module doesn't have a package.json file it is probably a
                        // dead install from yarn (they dont clean up for some reason)
                        if (!pJ)
                            return [2 /*return*/];
                        _a = [];
                        for (_b in pJ.dependencies)
                            _a.push(_b);
                        _i = 0;
                        _f.label = 2;
                    case 2:
                        if (!(_i < _a.length)) return [3 /*break*/, 5];
                        moduleName = _a[_i];
                        return [4 /*yield*/, this.loadProductionDependenciesForModuleInModule(moduleName, modulePath, allowMissing)];
                    case 3:
                        _f.sent();
                        _f.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5:
                        _c = [];
                        for (_d in pJ.optionalDependencies)
                            _c.push(_d);
                        _e = 0;
                        _f.label = 6;
                    case 6:
                        if (!(_e < _c.length)) return [3 /*break*/, 9];
                        moduleName = _c[_e];
                        return [4 /*yield*/, this.loadProductionDependenciesForModuleInModule(moduleName, modulePath, true)];
                    case 7:
                        _f.sent();
                        _f.label = 8;
                    case 8:
                        _e++;
                        return [3 /*break*/, 6];
                    case 9: return [2 /*return*/];
                }
            });
        });
    };
    Walker.prototype.loadProductionDependencies = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.prodPaths = new Set();
                        return [4 /*yield*/, this.loadProductionDependenciesForModule(this.rootModule)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.prodPaths];
                }
            });
        });
    };
    Walker.prototype.pruneModule = function (modulePath) {
        return __awaiter(this, void 0, void 0, function () {
            var nodeModulesPath, _i, _a, subModuleName, _b, _c, subScopedModuleName;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        if (!this.prodPaths.has(modulePath)) return [3 /*break*/, 13];
                        nodeModulesPath = path.resolve(modulePath, 'node_modules');
                        return [4 /*yield*/, fs.pathExists(nodeModulesPath)];
                    case 1:
                        if (!(_d.sent()))
                            return [2 /*return*/];
                        _i = 0;
                        return [4 /*yield*/, fs.readdir(nodeModulesPath)];
                    case 2:
                        _a = _d.sent();
                        _d.label = 3;
                    case 3:
                        if (!(_i < _a.length)) return [3 /*break*/, 12];
                        subModuleName = _a[_i];
                        if (!subModuleName.startsWith('@')) return [3 /*break*/, 9];
                        _b = 0;
                        return [4 /*yield*/, fs.readdir(path.resolve(nodeModulesPath, subModuleName))];
                    case 4:
                        _c = _d.sent();
                        _d.label = 5;
                    case 5:
                        if (!(_b < _c.length)) return [3 /*break*/, 8];
                        subScopedModuleName = _c[_b];
                        return [4 /*yield*/, this.pruneModule(path.resolve(nodeModulesPath, subModuleName, subScopedModuleName))];
                    case 6:
                        _d.sent();
                        _d.label = 7;
                    case 7:
                        _b++;
                        return [3 /*break*/, 5];
                    case 8: return [3 /*break*/, 11];
                    case 9: return [4 /*yield*/, this.pruneModule(path.resolve(nodeModulesPath, subModuleName))];
                    case 10:
                        _d.sent();
                        _d.label = 11;
                    case 11:
                        _i++;
                        return [3 /*break*/, 3];
                    case 12: return [3 /*break*/, 15];
                    case 13: return [4 /*yield*/, fs.remove(modulePath)];
                    case 14:
                        _d.sent();
                        _d.label = 15;
                    case 15: return [2 /*return*/];
                }
            });
        });
    };
    Walker.prototype.prune = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.loadProductionDependencies()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.pruneModule(this.rootModule)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return Walker;
}());
exports.Walker = Walker;
//# sourceMappingURL=Walker.js.map