"use strict";
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Object.defineProperty(exports, "__esModule", { value: true });
exports.processAndVerifyBaseRecording = void 0;
exports.record = record;
exports.getRecordingController = getRecordingController;
exports.onRecordingStateChanged = onRecordingStateChanged;
exports.onRecorderAttachedToTarget = onRecorderAttachedToTarget;
exports.onReplayFinished = onReplayFinished;
exports.enableUntrustedEventMode = enableUntrustedEventMode;
exports.enableAndOpenRecorderPanel = enableAndOpenRecorderPanel;
exports.createAndStartRecording = createAndStartRecording;
exports.changeNetworkConditions = changeNetworkConditions;
exports.openRecorderPanel = openRecorderPanel;
exports.startRecording = startRecording;
exports.stopRecording = stopRecording;
exports.clickSelectButtonItem = clickSelectButtonItem;
exports.setupRecorderWithScript = setupRecorderWithScript;
exports.setupRecorderWithScriptAndReplay = setupRecorderWithScriptAndReplay;
exports.getCurrentRecording = getCurrentRecording;
exports.startOrStopRecordingShortcut = startOrStopRecordingShortcut;
exports.fillCreateRecordingForm = fillCreateRecordingForm;
exports.startRecordingViaShortcut = startRecordingViaShortcut;
exports.replayShortcut = replayShortcut;
exports.toggleCodeView = toggleCodeView;
const chai_1 = require("chai");
const helper_js_1 = require("../../../test/shared/helper.js");
const quick_open_helpers_js_1 = require("./quick_open-helpers.js");
const RECORDER_CONTROLLER_TAG_NAME = 'devtools-recorder-controller';
const TEST_RECORDING_NAME = 'New Recording';
async function record(devToolsPage, inspectedPage) {
    await devToolsPage.bringToFront();
    await devToolsPage.page.waitForSelector('pierce/.settings');
    await inspectedPage.bringToFront();
    const element = await inspectedPage.waitForSelector('a[href="recorder2.html"]');
    await element?.click();
    await devToolsPage.bringToFront();
}
async function getRecordingController(devToolsPage) {
    return await devToolsPage.waitFor(RECORDER_CONTROLLER_TAG_NAME);
}
async function onRecordingStateChanged(devToolsPage) {
    const view = await getRecordingController(devToolsPage);
    return await view.evaluate(el => {
        return new Promise(resolve => {
            el.addEventListener('recordingstatechanged', (event) => resolve(event.recording), { once: true });
        });
    });
}
async function onRecorderAttachedToTarget(devToolsPage) {
    return await devToolsPage.evaluate(() => {
        return new Promise(resolve => {
            window.addEventListener('recorderAttachedToTarget', resolve, {
                once: true,
            });
        });
    });
}
async function onReplayFinished(devToolsPage) {
    const view = await getRecordingController(devToolsPage);
    return await view.evaluate(el => {
        return new Promise(resolve => {
            el.addEventListener('replayfinished', resolve, { once: true });
        });
    });
}
async function enableUntrustedEventMode(devToolsPage) {
    await devToolsPage.evaluate(`(async () => {
    // TODO: have an explicit UI setting or perhaps a special event to configure this
    // instead of having a global setting.
    const Common = await import('./core/common/common.js');
    Common.Settings.Settings.instance().createSetting('untrusted-recorder-events', true);
  })()`);
}
async function enableAndOpenRecorderPanel(path, devToolsPage, inspectedPage) {
    await inspectedPage.goToResource(path);
    await openRecorderPanel(devToolsPage);
}
async function createRecording(name, selectorAttribute, devToolsPage) {
    const newRecordingButton = await devToolsPage.waitForAria('Create recording');
    await newRecordingButton.click();
    const input = await devToolsPage.waitForAria('RECORDING NAME');
    await input.type(name);
    if (selectorAttribute) {
        const input = await devToolsPage.waitForAria('SELECTOR ATTRIBUTE Learn more');
        await input.type(selectorAttribute);
    }
}
async function createAndStartRecording(name, selectorAttribute, devToolsPage) {
    await createRecording(name ?? TEST_RECORDING_NAME, selectorAttribute, devToolsPage);
    const onRecordingStarted = onRecordingStateChanged(devToolsPage);
    await devToolsPage.click('.control-button');
    await devToolsPage.waitFor('.recording-view');
    await onRecordingStarted;
}
async function changeNetworkConditions(condition, devToolsPage) {
    await (0, quick_open_helpers_js_1.openCommandMenu)(devToolsPage);
    await devToolsPage.typeText('Show Network');
    await devToolsPage.pressKey('Enter');
    await devToolsPage.page.waitForSelector('pierce/select[aria-label="Throttling"]');
    await devToolsPage.page.select('pierce/select[aria-label="Throttling"]', condition);
}
async function openRecorderPanel(devToolsPage) {
    await (0, quick_open_helpers_js_1.openCommandMenu)(devToolsPage);
    await devToolsPage.typeText('Show Recorder');
    await devToolsPage.pressKey('Enter');
    await devToolsPage.waitFor(RECORDER_CONTROLLER_TAG_NAME);
}
async function startRecording(path, options = {
    networkCondition: '',
    untrustedEvents: false,
}, devToolsPage, inspectedPage) {
    await devToolsPage.bringToFront();
    if (options.networkCondition) {
        await changeNetworkConditions(options.networkCondition, devToolsPage);
    }
    await enableAndOpenRecorderPanel(path, devToolsPage, inspectedPage);
    if (options.untrustedEvents) {
        await enableUntrustedEventMode(devToolsPage);
    }
    await createAndStartRecording(TEST_RECORDING_NAME, options.selectorAttribute, devToolsPage);
}
async function stopRecording(devToolsPage) {
    await devToolsPage.bringToFront();
    await devToolsPage.raf();
    const onRecordingStopped = onRecordingStateChanged(devToolsPage);
    await devToolsPage.click('aria/End recording');
    return await onRecordingStopped;
}
const processAndVerifyBaseRecording = (recording, options = {}) => {
    const { offsets = false, expectCommon = true, resource = 'recorder/recorder.html', } = options;
    let value = JSON.stringify(recording)
        .replaceAll(/https:\/\/localhost:\d+/g, 'https://localhost:<test-port>')
        .replaceAll(/https:\/\/devtools.oopif.test:\d+/g, 'https://devtools.oopif.test:<test-port>');
    value = value.replaceAll('\u200b', '');
    if (!offsets) {
        value = value.replaceAll(/,?"(?:offsetY|offsetX)":[0-9]+(?:\.[0-9]+)?/g, '');
    }
    const parsed = JSON.parse(value.trim());
    if (expectCommon) {
        chai_1.assert.strictEqual(parsed.title, 'New Recording');
        delete parsed.title;
        chai_1.assert.deepEqual(parsed.steps[0], {
            type: 'setViewport',
            width: 1280,
            height: 720,
            deviceScaleFactor: 1,
            isMobile: false,
            hasTouch: false,
            isLandscape: false
        });
        chai_1.assert.deepEqual(parsed.steps[1], {
            type: 'navigate',
            url: `https://localhost:<test-port>/test/e2e/resources/${resource}`,
            assertedEvents: [{
                    type: 'navigation',
                    url: `https://localhost:<test-port>/test/e2e/resources/${resource}`,
                    title: '',
                }]
        });
        parsed.steps = parsed.steps.slice(2);
    }
    return parsed;
};
exports.processAndVerifyBaseRecording = processAndVerifyBaseRecording;
async function setCode(flow, devToolsPage) {
    const view = await getRecordingController(devToolsPage);
    await view.evaluate((el, flow) => {
        el.dispatchEvent(new CustomEvent('setrecording', { detail: flow }));
    }, flow);
}
async function clickSelectButtonItem(itemLabel, root, devToolsPage) {
    const selectMenu = await devToolsPage.waitFor(root);
    const selectMenuButton = await devToolsPage.waitFor('select', selectMenu);
    void (0, helper_js_1.selectOption)(await selectMenuButton.toElement('select'), itemLabel);
    await devToolsPage.click('devtools-button', { root: selectMenu });
}
async function setupRecorderWithScript(script, path = 'recorder/recorder.html', devToolsPage, inspectedPage) {
    await enableAndOpenRecorderPanel(path, devToolsPage, inspectedPage);
    await createAndStartRecording(script.title, undefined, devToolsPage);
    await stopRecording(devToolsPage);
    await setCode(JSON.stringify(script), devToolsPage);
}
async function setupRecorderWithScriptAndReplay(script, path = 'recorder/recorder.html', devToolsPage, inspectedPage) {
    await setupRecorderWithScript(script, path, devToolsPage, inspectedPage);
    const onceFinished = onReplayFinished(devToolsPage);
    await clickSelectButtonItem('Normal (Default)', '.select-button', devToolsPage);
    await onceFinished;
}
async function getCurrentRecording(devToolsPage) {
    await devToolsPage.bringToFront();
    const controller = await devToolsPage.$(RECORDER_CONTROLLER_TAG_NAME);
    const recording = (await controller?.evaluate(el => JSON.stringify(el.getUserFlow())));
    return JSON.parse(recording ?? '');
}
async function startOrStopRecordingShortcut(execute = 'devToolsPage', devToolsPage, inspectedPage) {
    const executeOn = execute === 'devToolsPage' ? devToolsPage : inspectedPage;
    const onRecordingStarted = onRecordingStateChanged(devToolsPage);
    await executeOn.bringToFront();
    await executeOn.pressKey('e', { control: true });
    await devToolsPage.waitFor('.recording-view');
    return await onRecordingStarted;
}
async function fillCreateRecordingForm(path, devToolsPage, inspectedPage) {
    await enableAndOpenRecorderPanel(path, devToolsPage, inspectedPage);
    await createRecording(TEST_RECORDING_NAME, undefined, devToolsPage);
}
async function startRecordingViaShortcut(path, devToolsPage, inspectedPage) {
    await enableAndOpenRecorderPanel(path, devToolsPage, inspectedPage);
    await startOrStopRecordingShortcut('devToolsPage', devToolsPage, inspectedPage);
}
async function replayShortcut(devToolsPage) {
    await devToolsPage.bringToFront();
    await devToolsPage.pressKey('Enter', { control: true });
}
async function toggleCodeView(devToolsPage) {
    await devToolsPage.bringToFront();
    await devToolsPage.pressKey('b', { control: true });
    await devToolsPage.drainTaskQueue();
}
//# sourceMappingURL=recorder-helpers.js.map