"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compileSourceFiles = void 0;
const core_1 = require("@angular-devkit/core");
const nodes_1 = require("ng-packagr/lib/ng-package/nodes");
const cache_compiler_host_1 = require("ng-packagr/lib/ts/cache-compiler-host");
const ngcc_transform_compiler_host_1 = require("ng-packagr/lib/ts/ngcc-transform-compiler-host");
const log = __importStar(require("ng-packagr/lib/utils/log"));
const ng_compiler_cli_1 = require("ng-packagr/lib/utils/ng-compiler-cli");
const path_1 = __importDefault(require("path"));
const static_injector_1 = require("static-injector");
const typescript_1 = __importDefault(require("typescript"));
const mini_program_compiler_1 = require("../mini-program-compiler");
const platform_1 = require("../platform/platform");
const platform_inject_config_1 = require("../platform/platform-inject-config");
const add_declaration_metadata_service_1 = require("./add-declaration-metadata.service");
const output_template_metadata_service_1 = require("./output-template-metadata.service");
const setup_component_data_service_1 = require("./setup-component-data.service");
const token_1 = require("./token");
function compileSourceFiles(graph, tsConfig, moduleResolutionCache, extraOptions, stylesheetProcessor, ngccProcessor, watch) {
    return __awaiter(this, void 0, void 0, function* () {
        const { NgtscProgram, formatDiagnostics } = yield (0, ng_compiler_cli_1.ngCompilerCli)();
        const tsConfigOptions = Object.assign(Object.assign({}, tsConfig.options), extraOptions);
        const entryPoint = graph.find(
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (0, nodes_1.isEntryPointInProgress)());
        const ngPackageNode = graph.find(nodes_1.isPackage);
        const inlineStyleLanguage = ngPackageNode.data.inlineStyleLanguage;
        const tsCompilerHost = (0, ngcc_transform_compiler_host_1.ngccTransformCompilerHost)((0, cache_compiler_host_1.cacheCompilerHost)(graph, entryPoint, tsConfigOptions, moduleResolutionCache, stylesheetProcessor, inlineStyleLanguage), tsConfigOptions, ngccProcessor, moduleResolutionCache);
        // inject
        augmentLibraryMetadata(tsCompilerHost);
        const cache = entryPoint.cache;
        const sourceFileCache = cache.sourcesFileCache;
        // Create the Angular specific program that contains the Angular compiler
        const angularProgram = new NgtscProgram(tsConfig.rootNames, tsConfigOptions, tsCompilerHost, cache.oldNgtscProgram);
        const angularCompiler = angularProgram.compiler;
        const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;
        // SourceFile versions are required for builder programs.
        // The wrapped host inside NgtscProgram adds additional files that will not have versions.
        const typeScriptProgram = angularProgram.getTsProgram();
        (0, cache_compiler_host_1.augmentProgramWithVersioning)(typeScriptProgram);
        let builder;
        if (watch) {
            builder = cache.oldBuilder =
                typescript_1.default.createEmitAndSemanticDiagnosticsBuilderProgram(typeScriptProgram, tsCompilerHost, cache.oldBuilder);
            cache.oldNgtscProgram = angularProgram;
        }
        else {
            // When not in watch mode, the startup cost of the incremental analysis can be avoided by
            // using an abstract builder that only wraps a TypeScript program.
            builder = typescript_1.default.createAbstractBuilder(typeScriptProgram, tsCompilerHost);
        }
        // Update semantic diagnostics cache
        const affectedFiles = new Set();
        // Analyze affected files when in watch mode for incremental type checking
        if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {
            // eslint-disable-next-line no-constant-condition
            while (true) {
                const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, (sourceFile) => {
                    // If the affected file is a TTC shim, add the shim's original source file.
                    // This ensures that changes that affect TTC are typechecked even when the changes
                    // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes.
                    // For example, changing @Input property types of a directive used in another component's
                    // template.
                    if (ignoreForDiagnostics.has(sourceFile) &&
                        sourceFile.fileName.endsWith('.ngtypecheck.ts')) {
                        // This file name conversion relies on internal compiler logic and should be converted
                        // to an official method when available. 15 is length of `.ngtypecheck.ts`
                        const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';
                        const originalSourceFile = builder.getSourceFile(originalFilename);
                        if (originalSourceFile) {
                            affectedFiles.add(originalSourceFile);
                        }
                        return true;
                    }
                    return false;
                });
                if (!result) {
                    break;
                }
                affectedFiles.add(result.affected);
            }
        }
        // Collect program level diagnostics
        const allDiagnostics = [
            ...angularCompiler.getOptionDiagnostics(),
            ...builder.getOptionsDiagnostics(),
            ...builder.getGlobalDiagnostics(),
        ];
        // inject
        let injector = static_injector_1.Injector.create({
            providers: [
                ...(0, platform_inject_config_1.getBuildPlatformInjectConfig)(platform_1.PlatformType.library),
                {
                    provide: mini_program_compiler_1.MiniProgramCompilerService,
                    useFactory: (injector, buildPlatform) => {
                        return new mini_program_compiler_1.MiniProgramCompilerService(angularProgram, injector, buildPlatform);
                    },
                    deps: [static_injector_1.Injector, platform_1.BuildPlatform],
                },
                {
                    provide: token_1.ENTRY_FILE_TOKEN,
                    useValue: (0, core_1.join)((0, core_1.dirname)((0, core_1.normalize)(tsConfig.rootNames[0])), (0, core_1.normalize)(tsConfigOptions.flatModuleOutFile)),
                },
                {
                    provide: token_1.ENTRY_POINT_TOKEN,
                    useValue: entryPoint.data.entryPoint.moduleId,
                },
            ],
        });
        const miniProgramCompilerService = injector.get(mini_program_compiler_1.MiniProgramCompilerService);
        // Required to support asynchronous resource loading
        // Must be done before creating transformers or getting template diagnostics
        yield angularCompiler.analyzeAsync();
        // inject
        miniProgramCompilerService.init();
        const metaMap = yield miniProgramCompilerService.exportComponentBuildMetaMap();
        injector = static_injector_1.Injector.create({
            parent: injector,
            providers: [
                { provide: token_1.RESOLVED_DATA_GROUP_TOKEN, useValue: metaMap },
                { provide: add_declaration_metadata_service_1.AddDeclarationMetaDataService },
                { provide: output_template_metadata_service_1.OutputTemplateMetadataService },
                { provide: setup_component_data_service_1.SetupComponentDataService },
            ],
        });
        // Collect source file specific diagnostics
        for (const sourceFile of builder.getSourceFiles()) {
            if (!ignoreForDiagnostics.has(sourceFile)) {
                allDiagnostics.push(...builder.getSyntacticDiagnostics(sourceFile), ...builder.getSemanticDiagnostics(sourceFile));
            }
            if (sourceFile.isDeclarationFile) {
                continue;
            }
            // Collect sources that are required to be emitted
            if (!ignoreForEmit.has(sourceFile) &&
                !angularCompiler.incrementalDriver.safeToSkipEmit(sourceFile)) {
                // If required to emit, diagnostics may have also changed
                if (!ignoreForDiagnostics.has(sourceFile)) {
                    affectedFiles.add(sourceFile);
                }
            }
            else if (sourceFileCache &&
                !affectedFiles.has(sourceFile) &&
                !ignoreForDiagnostics.has(sourceFile)) {
                // Use cached Angular diagnostics for unchanged and unaffected files
                const angularDiagnostics = sourceFileCache.getAngularDiagnostics(sourceFile);
                if (angularDiagnostics === null || angularDiagnostics === void 0 ? void 0 : angularDiagnostics.length) {
                    allDiagnostics.push(...angularDiagnostics);
                }
            }
        }
        // Collect new Angular diagnostics for files affected by changes
        for (const affectedFile of affectedFiles) {
            const angularDiagnostics = angularCompiler.getDiagnosticsForFile(affectedFile, 
            /** OptimizeFor.WholeProgram */ 1);
            allDiagnostics.push(...angularDiagnostics);
            sourceFileCache.updateAngularDiagnostics(affectedFile, angularDiagnostics);
        }
        const otherDiagnostics = [];
        const errorDiagnostics = [];
        for (const diagnostic of allDiagnostics) {
            if (diagnostic.category === typescript_1.default.DiagnosticCategory.Error) {
                errorDiagnostics.push(diagnostic);
            }
            else {
                otherDiagnostics.push(diagnostic);
            }
        }
        if (otherDiagnostics.length) {
            log.msg(formatDiagnostics(errorDiagnostics));
        }
        if (errorDiagnostics.length) {
            throw new Error(formatDiagnostics(errorDiagnostics));
        }
        const transformers = angularCompiler.prepareEmit().transformers;
        for (const sourceFile of builder.getSourceFiles()) {
            if (!ignoreForEmit.has(sourceFile)) {
                builder.emit(sourceFile, undefined, undefined, undefined, transformers);
            }
        }
        function augmentLibraryMetadata(compilerHost) {
            const oldWriteFile = compilerHost.writeFile;
            compilerHost.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
                const entryFileName = injector.get(token_1.ENTRY_FILE_TOKEN);
                if (fileName.endsWith('.map')) {
                    return oldWriteFile.call(this, fileName, data, writeByteOrderMark, onError, sourceFiles);
                }
                if (fileName.endsWith('.d.ts')) {
                    const service = injector.get(add_declaration_metadata_service_1.AddDeclarationMetaDataService);
                    const result = service.run(fileName, data);
                    return oldWriteFile.call(this, fileName, result, writeByteOrderMark, onError, sourceFiles);
                }
                const sourceFile = sourceFiles && sourceFiles[0];
                if (sourceFile) {
                    if (entryFileName ===
                        (0, core_1.normalize)(sourceFile.fileName.replace(/\.ts$/, '.js'))) {
                        const service = injector.get(output_template_metadata_service_1.OutputTemplateMetadataService);
                        const result = service.run(fileName, data, sourceFiles[0]);
                        return oldWriteFile.call(this, fileName, result, writeByteOrderMark, onError, sourceFiles);
                    }
                    const originFileName = path_1.default.normalize(sourceFile.fileName);
                    const setupComponentDataService = injector.get(setup_component_data_service_1.SetupComponentDataService);
                    const result = setupComponentDataService.run(data, originFileName, stylesheetProcessor);
                    return oldWriteFile.call(this, fileName, result, writeByteOrderMark, onError, sourceFiles);
                }
                return oldWriteFile.call(this, fileName, data, writeByteOrderMark, onError, sourceFiles);
            };
        }
    });
}
exports.compileSourceFiles = compileSourceFiles;
