"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.networkLogsAfterAllHook = exports.networkLogsBeforeAllHook = void 0;
const utils_1 = require("./utils");
const chrome_har_1 = __importDefault(require("@testim/chrome-har"));
const hooksHandlersDisposersHelper_1 = require("./hooksHandlersDisposersHelper");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const messagesForPageMap = new WeakMap();
const cdpEventsToListenOn = [
    'Network.loadingFailed',
    'Network.loadingFinished',
    'Network.requestServedFromCache',
    'Network.requestWillBeSent',
    'Network.resourceChangedPriority',
    'Network.responseReceived',
    'Page.domContentEventFired',
    'Page.frameAttached',
    'Page.frameNavigated',
    'Page.frameScheduledNavigation',
    'Page.frameStartedLoading',
    'Page.loadEventFired',
    'Page.navigatedWithinDocument',
];
function getMessagesForTestContextMap(textContext) {
    let messages = messagesForPageMap.get(textContext);
    if (!messages) {
        messages = [];
        messagesForPageMap.set(textContext, messages);
    }
    return messages;
}
const DISPOSERS_TOPIC = 'network-logs';
exports.networkLogsBeforeAllHook = async function networkLogsBeforeAllHook({ testContext, rootPage, }) {
    if (utils_1.isNotPlaywrightPage(rootPage)) {
        return networkLogsBeforeAllHookPuppeteer({
            testContext,
            page: rootPage,
        });
    }
    return networkLogsBeforeAllHookPlaywright({
        testContext,
        page: rootPage,
    });
};
async function networkLogsBeforeAllHookPuppeteer({ testContext, page, }) {
    const cdpSession = page._client;
    for (const eventToListenOn of cdpEventsToListenOn) {
        function listener(params) {
            getMessagesForTestContextMap(testContext).push({
                method: eventToListenOn,
                params,
            });
        }
        cdpSession.on(eventToListenOn, listener);
        hooksHandlersDisposersHelper_1.addDisposer(testContext, DISPOSERS_TOPIC, () => {
            cdpSession.off(eventToListenOn, listener);
        });
    }
}
function networkLogsBeforeAllHookPlaywright({ testContext, page, }) {
    const context = page.context();
    if (utils_1.isPlaywrightChromiumBrowserContext(context)) {
        const cdpSession = page._delegate._mainFrameSession._client;
        for (const eventToListenOn of cdpEventsToListenOn) {
            function listener(params) {
                getMessagesForTestContextMap(testContext).push({
                    method: eventToListenOn,
                    params,
                });
            }
            cdpSession.on(eventToListenOn, listener);
            hooksHandlersDisposersHelper_1.addDisposer(testContext, DISPOSERS_TOPIC, () => {
                cdpSession.off(eventToListenOn, listener);
            });
        }
    }
}
exports.networkLogsAfterAllHook = async function networkLogsAfterAllHook({ testContext, }) {
    const messages = getMessagesForTestContextMap(testContext);
    const harFileContents = chrome_har_1.default.harFromMessages(messages, {});
    await fs_extra_1.default.writeFile(path_1.default.resolve(testContext.testArtifactsFolder, 'networkLogs.har'), JSON.stringify(harFileContents, null, 2));
    testContext.addTestMetadata({ hasNetworkLogs: true });
    hooksHandlersDisposersHelper_1.runAllDisposers(testContext, DISPOSERS_TOPIC);
};
