"use strict";
// Copyright 2026 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = run;
const mocha_1 = __importDefault(require("mocha"));
const path = __importStar(require("node:path"));
const node_url_1 = require("node:url");
const MochaHelpers_js_1 = require("../../front_end/testing/MochaHelpers.js");
const TestIdGeneration_js_1 = require("../../front_end/testing/TestIdGeneration.js");
const paths_js_1 = require("../conductor/paths.js");
const test_config_js_1 = require("../conductor/test_config.js");
const test_expectations_js_1 = require("../conductor/test_expectations.js");
function optionsWithDefalts(options) {
    const withDefaults = {
        // This should make mocha crash on uncaught errors.
        // See https://github.com/mochajs/mocha/blob/master/docs/index.md#--allow-uncaught.
        allowUncaught: true,
        retries: test_config_js_1.TestConfig.retries,
        reporter: path.join(__dirname, 'mocha-resultsdb-reporter.js'),
        slow: 1000,
        failZero: false,
        ...options,
        ...test_config_js_1.TestConfig.mochaGrep,
    };
    if (test_config_js_1.TestConfig.debug) {
        withDefaults.timeout = 0;
    }
    return withDefaults;
}
async function run(options) {
    const mocha = new mocha_1.default(optionsWithDefalts(options));
    // Load files
    const files = options.spec;
    if (Array.isArray(files)) {
        for (const file of files) {
            mocha.addFile(file);
        }
    }
    // Load requires if necessary (Mocha programmatic API might not automatically load requires,
    // we may need to import them manually).
    // eslint-disable-next-line  @typescript-eslint/no-unsafe-function-type
    const globalSetups = [];
    // eslint-disable-next-line  @typescript-eslint/no-unsafe-function-type
    const globalTeardowns = [];
    if (options.require) {
        const requires = Array.isArray(options.require) ? options.require : [options.require];
        for (const req of requires) {
            const importTarget = path.isAbsolute(req) ? (0, node_url_1.pathToFileURL)(req).href : req;
            const mod = await import(importTarget);
            const exportsObj = mod.default || mod;
            if (exportsObj.mochaGlobalSetup) {
                globalSetups.push(exportsObj.mochaGlobalSetup);
            }
            if (exportsObj.mochaGlobalTeardown) {
                globalTeardowns.push(exportsObj.mochaGlobalTeardown);
            }
            if (exportsObj.mochaHooks) {
                mocha.rootHooks(exportsObj.mochaHooks);
            }
        }
    }
    if (globalSetups.length > 0) {
        // @ts-expect-error unknown types
        mocha.globalSetup(globalSetups);
    }
    if (globalTeardowns.length > 0) {
        // @ts-expect-error unknown types
        mocha.globalTeardown(globalTeardowns);
    }
    await mocha.loadFilesAsync();
    const testIds = new Set(test_config_js_1.TestConfig.tests.filter(testId => paths_js_1.TEST_ID_REGEX.test(testId)));
    const seenTestIds = new Set();
    const skippedTests = (0, test_expectations_js_1.getSkippedTests)();
    function shouldIncludeTest(test) {
        if (!test.file) {
            throw new Error(`Test ${test.titlePath()} does not have a file.`);
        }
        const testId = (0, TestIdGeneration_js_1.computeBuildTestId)(test.file, test.titlePath());
        if (seenTestIds.has(testId)) {
            throw new Error(`Duplicate test ${testId}`);
        }
        seenTestIds.add(testId);
        const isSkipped = skippedTests.some((skippedTest) => {
            return testId === skippedTest || testId.startsWith(`${skippedTest}:`);
        });
        if (isSkipped) {
            test.pending = true;
        }
        if (testIds.size === 0) {
            return true;
        }
        return testIds.has(testId);
    }
    (0, MochaHelpers_js_1.pruneSuite)(mocha.suite, shouldIncludeTest);
    (0, MochaHelpers_js_1.duplicateTests)(mocha.suite, test_config_js_1.TestConfig.repetitions);
    mocha.enableGlobalSetup(true);
    mocha.enableGlobalTeardown(true);
    const failures = await new Promise(resolve => {
        mocha.run(resolve);
    });
    if (process.exitCode === undefined) {
        process.exitCode = failures > 0 ? 1 : 0;
    }
}
//# sourceMappingURL=run-mocha.js.map