#! /usr/bin/env node
"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 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, 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 };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var got_1 = __importDefault(require("got"));
var commander_1 = __importDefault(require("commander"));
var fs_1 = require("fs");
var qs_1 = __importDefault(require("qs"));
var open_1 = __importDefault(require("open"));
var path_1 = __importDefault(require("path"));
var ora_1 = __importDefault(require("ora"));
var inquirer_1 = __importDefault(require("inquirer"));
var is_expo_running_1 = __importDefault(require("./is-expo-running"));
var is_rn_running_1 = __importDefault(require("./is-rn-running"));
var packageJson = require('../package.json');
commander_1.default
    .version(packageJson.version, '-v, --version')
    .option('-a, --android', 'Analyse Android bundle ')
    .option('-d, --dev', 'Analyse developement bundle')
    .parse(process.argv);
var sourceMapExplorer = require('source-map-explorer');
var query = qs_1.default.stringify({
    platform: commander_1.default.android ? 'android' : 'ios',
    sourceMap: 'true',
    dev: commander_1.default.dev ? 'true' : 'false',
    minify: 'false',
    hot: 'false'
});
var choices = [
    'React Native project running on port 8081',
    'Expo project running on port 19001'
];
var start = function () { return __awaiter(_this, void 0, void 0, function () {
    var _a, expoRunning, rnRunning, port, prompt_1, project, startTime, spinner, bundle, sourceMap, analysis, endTime, err_1;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                console.log(' ');
                process.stdout.write('Searching for running React Native app... ');
                return [4 /*yield*/, Promise.all([
                        is_expo_running_1.default(),
                        is_rn_running_1.default()
                    ])];
            case 1:
                _a = _b.sent(), expoRunning = _a[0], rnRunning = _a[1];
                port = expoRunning ? 19001 : 8081;
                if (expoRunning && !rnRunning) {
                    console.log('Found Expo app.');
                    console.log('');
                }
                if (!expoRunning && rnRunning) {
                    console.log('Found React Native app.');
                    console.log('');
                }
                if (!(expoRunning && rnRunning)) return [3 /*break*/, 3];
                console.log('Multiple found.');
                prompt_1 = inquirer_1.default.createPromptModule();
                return [4 /*yield*/, prompt_1([
                        {
                            type: 'list',
                            name: 'project',
                            message: 'Found both a React Native and an Expo project. Which one would you like to analyze?',
                            choices: choices
                        }
                    ])];
            case 2:
                project = (_b.sent()).project;
                port = project === choices[0] ? 8081 : 19001;
                _b.label = 3;
            case 3:
                if (!expoRunning && !rnRunning) {
                    console.log('None found.');
                    console.log("Could not find a React Native or Expo project running on port " + 8081 + " or " + 19001 + ". Start one and run 'npx visualize-bundle' again.");
                    console.log('');
                    process.exit(0);
                }
                startTime = Date.now();
                spinner = ora_1.default();
                spinner.start();
                spinner.text = "Getting bundle from port " + port + "...";
                return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })];
            case 4:
                _b.sent();
                _b.label = 5;
            case 5:
                _b.trys.push([5, 11, , 12]);
                return [4 /*yield*/, got_1.default((port === 19001
                        ? 'http://localhost:19001/node_modules/expo/AppEntry.bundle'
                        : 'http://localhost:8081/index.ios.bundle') + "?" + query, {
                        headers: {
                            'user-agent': 'npx-visualize-bundle'
                        }
                    })];
            case 6:
                bundle = _b.sent();
                spinner.text = "Getting map from port " + port + "...";
                return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })];
            case 7:
                _b.sent();
                return [4 /*yield*/, got_1.default((port === 19001
                        ? 'http://localhost:19001/node_modules/expo/AppEntry.map'
                        : 'http://localhost:8081/index.ios.map') + "?" + query, {
                        headers: {
                            'user-agent': 'npx-visualize-bundle'
                        }
                    })];
            case 8:
                sourceMap = _b.sent();
                fs_1.writeFileSync(path_1.default.join(__dirname, '..', 'bundle.js'), bundle.body);
                fs_1.writeFileSync(path_1.default.join(__dirname, '..', 'bundle.js.map'), sourceMap.body);
                spinner.text = 'Analysing bundle using source-map-explorer...';
                return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })];
            case 9:
                _b.sent();
                analysis = sourceMapExplorer(path_1.default.join(__dirname, '..', 'bundle.js'), path_1.default.join(__dirname, '..', 'bundle.js.map'), { html: true });
                fs_1.writeFileSync(path_1.default.join(__dirname, '..', 'report.html'), analysis.html);
                spinner.stop();
                endTime = Date.now();
                return [4 /*yield*/, open_1.default(path_1.default.join(__dirname, '..', 'report.html'))];
            case 10:
                _b.sent();
                console.log(' ');
                console.log("\u2747\uFE0F  Report generated in " + Math.floor((endTime - startTime) / 1000) + "s and opened in browser.");
                console.log(' ');
                fs_1.unlink(path_1.default.join(__dirname, '..', 'bundle.js'), function () {
                    fs_1.unlink(path_1.default.join(__dirname, '..', 'bundle.js.map'), function () {
                        process.exit(0);
                    });
                });
                return [3 /*break*/, 12];
            case 11:
                err_1 = _b.sent();
                console.log('');
                if (err_1.message.match(/500/)) {
                    console.log([
                        'The packager returned status code 500.',
                        'Your code might have an error that will prevent it from compilation.',
                        'Check the output of the packager.'
                    ].join('\n'));
                }
                else {
                    console.log('Could not do bundle analysis: ' + err_1.message);
                    console.log(err_1.stack);
                }
                spinner.stop();
                process.exit(1);
                return [3 /*break*/, 12];
            case 12: return [2 /*return*/];
        }
    });
}); };
start();
