"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 path_1 = require("path");
require("reflect-metadata");
var typescript_1 = require("typescript");
var hybrid_file_system_factory_1 = require("../util/hybrid-file-system-factory");
var compiler_host_factory_1 = require("./compiler-host-factory");
var utils_1 = require("./utils");
var logger_1 = require("../logger/logger");
var logger_diagnostics_1 = require("../logger/logger-diagnostics");
var logger_typescript_1 = require("../logger/logger-typescript");
var transpile_1 = require("../transpile");
var errors_1 = require("../util/errors");
var helpers_1 = require("../util/helpers");
function runAot(context, options) {
    return __awaiter(this, void 0, void 0, function () {
        var tsConfig, angularCompilerOptions, aggregateCompilerOption, fileSystem, compilerHost, tsProgram, mailFilePath, mainFile, modifiedBootstrapContent;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tsConfig = transpile_1.getTsConfig(context);
                    angularCompilerOptions = Object.assign({}, {
                        basePath: options.rootDir,
                        genDir: options.rootDir,
                        entryPoint: options.entryPoint
                    });
                    aggregateCompilerOption = Object.assign(tsConfig.options, angularCompilerOptions);
                    fileSystem = hybrid_file_system_factory_1.getInstance(false);
                    compilerHost = compiler_host_factory_1.getInMemoryCompilerHostInstance(tsConfig.options);
                    tsProgram = typescript_1.createProgram(tsConfig.fileNames, tsConfig.options, compilerHost);
                    logger_diagnostics_1.clearDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript);
                    if (!isNg5(context.angularVersion)) return [3 /*break*/, 2];
                    return [4 /*yield*/, runNg5Aot(context, tsConfig, aggregateCompilerOption, compilerHost)];
                case 1:
                    _a.sent();
                    return [3 /*break*/, 4];
                case 2: return [4 /*yield*/, runNg4Aot({
                        angularCompilerOptions: aggregateCompilerOption,
                        cliOptions: {
                            i18nFile: undefined,
                            i18nFormat: undefined,
                            locale: undefined,
                            basePath: options.rootDir,
                            missingTranslation: null
                        },
                        program: tsProgram,
                        compilerHost: compilerHost,
                        compilerOptions: tsConfig.options
                    })];
                case 3:
                    _a.sent();
                    _a.label = 4;
                case 4:
                    errorCheckProgram(context, tsConfig, compilerHost, tsProgram);
                    mailFilePath = isNg5(context.angularVersion) ? helpers_1.changeExtension(options.entryPoint, '.js') : options.entryPoint;
                    mainFile = context.fileCache.get(mailFilePath);
                    modifiedBootstrapContent = replaceBootstrap(mainFile, options.appNgModulePath, options.appNgModuleClass, options);
                    mainFile.content = modifiedBootstrapContent;
                    if (isTranspileRequired(context.angularVersion)) {
                        transpileFiles(context, tsConfig, fileSystem);
                    }
                    return [2 /*return*/];
            }
        });
    });
}
exports.runAot = runAot;
function errorCheckProgram(context, tsConfig, compilerHost, cachedProgram) {
    // Create a new Program, based on the old one. This will trigger a resolution of all
    // transitive modules, which include files that might just have been generated.
    var program = typescript_1.createProgram(tsConfig.fileNames, tsConfig.options, compilerHost, cachedProgram);
    var globalDiagnostics = program.getGlobalDiagnostics();
    var tsDiagnostics = program.getSyntacticDiagnostics()
        .concat(program.getSemanticDiagnostics())
        .concat(program.getOptionsDiagnostics());
    if (globalDiagnostics.length) {
        var diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, globalDiagnostics);
        logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, false);
        throw new errors_1.BuildError(new Error('Failed to transpile TypeScript'));
    }
    if (tsDiagnostics.length) {
        var diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, tsDiagnostics);
        logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, false);
        throw new errors_1.BuildError(new Error('Failed to transpile TypeScript'));
    }
    return program;
}
function replaceBootstrap(mainFile, appNgModulePath, appNgModuleClass, options) {
    if (!mainFile) {
        throw new errors_1.BuildError(new Error("Could not find entry point (bootstrap file) " + options.entryPoint));
    }
    var modifiedFileContent = null;
    try {
        logger_1.Logger.debug('[AotCompiler] compile: Dynamically changing entry point content to AOT mode content');
        modifiedFileContent = utils_1.replaceBootstrapImpl(mainFile.path, mainFile.content, appNgModulePath, appNgModuleClass);
    }
    catch (ex) {
        logger_1.Logger.debug("Failed to parse bootstrap: ", ex.message);
        logger_1.Logger.warn("Failed to parse and update " + options.entryPoint + " content for AoT compilation.\n                For now, the default fallback content will be used instead.\n                Please consider updating " + options.entryPoint + " with the content from the following link:\n                https://github.com/ionic-team/ionic2-app-base/tree/master/src/app/main.ts");
        modifiedFileContent = utils_1.getFallbackMainContent();
    }
    return modifiedFileContent;
}
function isTranspileRequired(angularVersion) {
    return angularVersion.major <= 4;
}
exports.isTranspileRequired = isTranspileRequired;
function transpileFiles(context, tsConfig, fileSystem) {
    var tsFiles = context.fileCache.getAll().filter(function (file) { return path_1.extname(file.path) === '.ts' && file.path.indexOf('.d.ts') === -1; });
    for (var _i = 0, tsFiles_1 = tsFiles; _i < tsFiles_1.length; _i++) {
        var tsFile = tsFiles_1[_i];
        logger_1.Logger.debug("[AotCompiler] transpileFiles: Transpiling file " + tsFile.path + " ...");
        var transpileOutput = transpileFileContent(tsFile.path, tsFile.content, tsConfig.options);
        var diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, transpileOutput.diagnostics);
        if (diagnostics.length) {
            // darn, we've got some things wrong, transpile failed :(
            logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, true);
            throw new errors_1.BuildError(new Error('Failed to transpile TypeScript'));
        }
        var jsFilePath = helpers_1.changeExtension(tsFile.path, '.js');
        fileSystem.addVirtualFile(jsFilePath, transpileOutput.outputText);
        fileSystem.addVirtualFile(jsFilePath + '.map', transpileOutput.sourceMapText);
        logger_1.Logger.debug("[AotCompiler] transpileFiles: Transpiling file " + tsFile.path + " ... DONE");
    }
}
exports.transpileFiles = transpileFiles;
function transpileFileContent(fileName, sourceText, options) {
    var transpileOptions = {
        compilerOptions: options,
        fileName: fileName,
        reportDiagnostics: true
    };
    return typescript_1.transpileModule(sourceText, transpileOptions);
}
function isNg5(version) {
    return version.major >= 5;
}
exports.isNg5 = isNg5;
function runNg4Aot(options) {
    return __awaiter(this, void 0, void 0, function () {
        var module;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('@angular/compiler-cli'); })];
                case 1:
                    module = _a.sent();
                    return [4 /*yield*/, module.__NGTOOLS_PRIVATE_API_2.codeGen({
                            angularCompilerOptions: options.angularCompilerOptions,
                            basePath: options.cliOptions.basePath,
                            program: options.program,
                            host: options.compilerHost,
                            compilerOptions: options.compilerOptions,
                            i18nFile: options.cliOptions.i18nFile,
                            i18nFormat: options.cliOptions.i18nFormat,
                            locale: options.cliOptions.locale,
                            readResource: function (fileName) {
                                return helpers_1.readFileAsync(fileName);
                            }
                        })];
                case 2: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
exports.runNg4Aot = runNg4Aot;
function runNg5Aot(context, tsConfig, aggregateCompilerOptions, compilerHost) {
    return __awaiter(this, void 0, void 0, function () {
        var ngTools2, angularCompilerHost, program, transformations, transformers, result, tsDiagnostics, angularDiagnostics, diagnostics, diagnostics;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('@angular/compiler-cli/ngtools2'); })];
                case 1:
                    ngTools2 = _a.sent();
                    angularCompilerHost = ngTools2.createCompilerHost({ options: aggregateCompilerOptions, tsHost: compilerHost });
                    program = ngTools2.createProgram({
                        rootNames: tsConfig.fileNames,
                        options: aggregateCompilerOptions,
                        host: angularCompilerHost,
                        oldProgram: null
                    });
                    return [4 /*yield*/, program.loadNgStructureAsync()];
                case 2:
                    _a.sent();
                    transformations = [];
                    transformers = {
                        beforeTs: transformations
                    };
                    result = program.emit({ emitFlags: ngTools2.EmitFlags.Default, customTransformers: transformers });
                    tsDiagnostics = program.getTsSyntacticDiagnostics()
                        .concat(program.getTsOptionDiagnostics())
                        .concat(program.getTsSemanticDiagnostics());
                    angularDiagnostics = program.getNgStructuralDiagnostics()
                        .concat(program.getNgOptionDiagnostics());
                    if (tsDiagnostics.length) {
                        diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, tsDiagnostics);
                        logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, false);
                        throw new errors_1.BuildError(new Error('The Angular AoT build failed. See the issues above'));
                    }
                    if (angularDiagnostics.length) {
                        diagnostics = logger_typescript_1.runTypeScriptDiagnostics(context, angularDiagnostics);
                        logger_diagnostics_1.printDiagnostics(context, logger_diagnostics_1.DiagnosticsType.TypeScript, diagnostics, true, false);
                        throw new errors_1.BuildError(new Error('The Angular AoT build failed. See the issues above'));
                    }
                    return [2 /*return*/];
            }
        });
    });
}
exports.runNg5Aot = runNg5Aot;
