"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.playwrightTest = void 0;
const playwright_1 = require("../playwright/playwright");
const node_fs_1 = __importDefault(require("node:fs"));
const mergeChromeArgs_1 = __importDefault(require("../utils/mergeChromeArgs"));
const writeVariables_1 = __importDefault(require("../utils/writeVariables"));
const checkUserArgs_1 = require("../utils/checkUserArgs");
const constantsNode_1 = require("../utils/constantsNode");
const validateHeadlessPlaywright_1 = __importDefault(require("../utils/validateHeadlessPlaywright"));
const createDebugger_1 = __importDefault(require("../createDebugger"));
const writeSessionFile_1 = __importDefault(require("../utils/writeSessionFile"));
const debugLogger = (0, createDebugger_1.default)('playwrightTest');
const playwrightTest = (options) => {
    let controller = null;
    const { axe, ...config } = options;
    (0, validateHeadlessPlaywright_1.default)({
        isPlaywrightTest: true,
        playwrightConfig: options
    });
    let base;
    let chromium;
    try {
        ;
        ({ test: base, chromium } = require('@playwright/test'));
    }
    catch (error) {
        throw new Error('Unable to load @playwright/test: ' + error.message);
    }
    (0, checkUserArgs_1.checkUserArgs)(config.args || []);
    (0, writeSessionFile_1.default)({ buildID: axe.buildID });
    (0, writeVariables_1.default)({ ...axe, isPlaywrightTest: true });
    const test = base.extend({
        context: async ({}, use) => {
            const context = await chromium.launchPersistentContext('', {
                ...config,
                args: (0, mergeChromeArgs_1.default)(config.args || [], {
                    disableOtherExtensions: true
                })
            });
            await use(context);
            try {
                node_fs_1.default.unlinkSync(constantsNode_1.PATH_TO_SESSION_FILE);
            }
            catch (e) {
                debugLogger(`Ignoring this error thrown by fs.unlinkSync: ${e.message}`);
            }
            await context.close();
        },
        page: async ({ page }, use) => {
            controller = page.axeWatcher;
            if (!controller) {
                controller = new playwright_1.PlaywrightController(page);
                page.axeWatcher = controller;
                page = (0, playwright_1.wrapPlaywrightPage)(page, controller);
            }
            await use(page);
            await controller.flush();
        }
    });
    const expect = test.expect;
    return { test, expect };
};
exports.playwrightTest = playwrightTest;
//# sourceMappingURL=playwrightTest.js.map