"use strict";
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.execute = void 0;
const architect_1 = require("@angular-devkit/architect");
const build_angular_1 = require("@angular-devkit/build-angular");
const find_tests_plugin_1 = require("@angular-devkit/build-angular/src/builders/karma/find-tests-plugin");
const purge_cache_1 = require("@angular-devkit/build-angular/src/utils/purge-cache");
const version_1 = require("@angular-devkit/build-angular/src/utils/version");
const webpack_browser_config_1 = require("@angular-devkit/build-angular/src/utils/webpack-browser-config");
const configs_1 = require("@angular-devkit/build-angular/src/webpack/configs");
const path = __importStar(require("path"));
const path_1 = require("path");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
function initialize(options, context, webpackConfigurationTransformer) {
    return __awaiter(this, void 0, void 0, function* () {
        // Purge old build disk cache.
        yield (0, purge_cache_1.purgeStaleBuildCache)(context);
        const { config } = yield (0, webpack_browser_config_1.generateBrowserWebpackConfigFromContext)(Object.assign(Object.assign({}, options), { outputPath: '', budgets: undefined, optimization: false, buildOptimizer: false, aot: true, vendorChunk: true, namedChunks: true, extractLicenses: false, outputHashing: build_angular_1.OutputHashing.None, 
            // The webpack tier owns the watch behavior so we want to force it in the config.
            // When not in watch mode, webpack-dev-middleware will call `compiler.watch` anyway.
            // https://github.com/webpack/webpack-dev-middleware/blob/698c9ae5e9bb9a013985add6189ff21c1a1ec185/src/index.js#L65
            // https://github.com/webpack/webpack/blob/cde1b73e12eb8a77eb9ba42e7920c9ec5d29c2c9/lib/Compiler.js#L379-L388
            watch: true }), context, (wco) => [
            (0, configs_1.getCommonConfig)(wco),
            // getBrowserConfig(wco),
            (0, configs_1.getStylesConfig)(wco),
            // getTypeScriptConfig(wco),
        ]);
        const karma = yield Promise.resolve().then(() => __importStar(require('karma')));
        return [
            karma,
            webpackConfigurationTransformer
                ? yield webpackConfigurationTransformer(config)
                : config,
        ];
    });
}
/**
 * @experimental Direct usage of this function is considered experimental.
 */
function execute(options, context, transforms = {}) {
    // Check Angular version.
    (0, version_1.assertCompatibleAngularVersion)(context.workspaceRoot);
    let singleRun;
    if (options.watch !== undefined) {
        singleRun = !options.watch;
    }
    return (0, rxjs_1.from)(initialize(options, context, transforms.webpackConfiguration)).pipe((0, operators_1.switchMap)(([karma, webpackConfig]) => __awaiter(this, void 0, void 0, function* () {
        var _a, _b, _c, _d;
        const karmaOptions = {
            singleRun,
        };
        // Convert browsers from a string to an array
        if (options.browsers) {
            karmaOptions.browsers = options.browsers.split(',');
        }
        if (options.reporters) {
            // Split along commas to make it more natural, and remove empty strings.
            const reporters = options.reporters
                .reduce((acc, curr) => acc.concat(curr.split(',')), [])
                .filter((x) => !!x);
            if (reporters.length > 0) {
                karmaOptions.reporters = reporters;
            }
        }
        const projectName = (_a = context.target) === null || _a === void 0 ? void 0 : _a.project;
        if (!projectName) {
            throw new Error('The builder requires a target.');
        }
        const projectMetadata = yield context.getProjectMetadata(projectName);
        const sourceRoot = ((_c = (_b = projectMetadata.sourceRoot) !== null && _b !== void 0 ? _b : projectMetadata.root) !== null && _c !== void 0 ? _c : '');
        (_d = webpackConfig.plugins) !== null && _d !== void 0 ? _d : (webpackConfig.plugins = []);
        webpackConfig.plugins.push(new find_tests_plugin_1.FindTestsPlugin({
            // include: options.include,
            workspaceRoot: context.workspaceRoot,
            projectSourceRoot: path.join(context.workspaceRoot, sourceRoot),
        }));
        karmaOptions.buildWebpack = {
            options,
            webpackConfig,
            logger: context.logger,
        };
        const config = yield karma.config.parseConfig((0, path_1.resolve)(context.workspaceRoot, options.karmaConfig), transforms.karmaOptions
            ? transforms.karmaOptions(karmaOptions)
            : karmaOptions, { promiseConfig: true, throwErrors: true });
        return [karma, config];
    })), (0, operators_1.switchMap)(([karma, karmaConfig]) => new rxjs_1.Observable((subscriber) => {
        var _a, _b, _c;
        var _d, _e;
        // Pass onto Karma to emit BuildEvents.
        (_a = karmaConfig.buildWebpack) !== null && _a !== void 0 ? _a : (karmaConfig.buildWebpack = {});
        if (typeof karmaConfig.buildWebpack === 'object') {
            (_b = (_d = karmaConfig.buildWebpack).failureCb) !== null && _b !== void 0 ? _b : (_d.failureCb = () => subscriber.next({ success: false }));
            (_c = (_e = karmaConfig.buildWebpack).successCb) !== null && _c !== void 0 ? _c : (_e.successCb = () => subscriber.next({ success: true }));
            karmaConfig.buildWebpack.testContext = context.testContext;
        }
        // Complete the observable once the Karma server returns.
        const karmaServer = new karma.Server(karmaConfig, (exitCode) => {
            subscriber.next({ success: exitCode === 0 });
            subscriber.complete();
        });
        const karmaStart = karmaServer.start();
        // Cleanup, signal Karma to exit.
        return () => karmaStart.then(() => karmaServer.stop());
    })), (0, operators_1.defaultIfEmpty)({ success: false }));
}
exports.execute = execute;
exports.default = (0, architect_1.createBuilder)(execute);
