/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
import { step } from './baseTest';
import path from 'path';
let TraceViewerPage = (() => {
    let _instanceExtraInitializers = [];
    let _showAllActions_decorators;
    let _expandAction_decorators;
    let _selectAction_decorators;
    let _hoverAction_decorators;
    let _selectSnapshot_decorators;
    let _snapshotFrame_decorators;
    return class TraceViewerPage {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
            _showAllActions_decorators = [step];
            _expandAction_decorators = [step];
            _selectAction_decorators = [step];
            _hoverAction_decorators = [step];
            _selectSnapshot_decorators = [step];
            _snapshotFrame_decorators = [step];
            __esDecorate(this, null, _showAllActions_decorators, { kind: "method", name: "showAllActions", static: false, private: false, access: { has: obj => "showAllActions" in obj, get: obj => obj.showAllActions }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _expandAction_decorators, { kind: "method", name: "expandAction", static: false, private: false, access: { has: obj => "expandAction" in obj, get: obj => obj.expandAction }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _selectAction_decorators, { kind: "method", name: "selectAction", static: false, private: false, access: { has: obj => "selectAction" in obj, get: obj => obj.selectAction }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _hoverAction_decorators, { kind: "method", name: "hoverAction", static: false, private: false, access: { has: obj => "hoverAction" in obj, get: obj => obj.hoverAction }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _selectSnapshot_decorators, { kind: "method", name: "selectSnapshot", static: false, private: false, access: { has: obj => "selectSnapshot" in obj, get: obj => obj.selectSnapshot }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _snapshotFrame_decorators, { kind: "method", name: "snapshotFrame", static: false, private: false, access: { has: obj => "snapshotFrame" in obj, get: obj => obj.snapshotFrame }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        page = __runInitializers(this, _instanceExtraInitializers);
        process;
        actionTitles;
        actionsTree;
        callLines;
        consoleLines;
        logLines;
        errorMessages;
        consoleLineMessages;
        consoleStacks;
        networkRequests;
        metadataTab;
        snapshotContainer;
        sourceCodeTab;
        networkTab;
        settingsDialog;
        themeSetting;
        displayCanvasContentSetting;
        constructor(page, process) {
            this.page = page;
            this.process = process;
            this.actionTitles = page.locator('.action-title');
            this.actionsTree = page.getByTestId('actions-tree');
            this.callLines = page.locator('.call-tab .call-line');
            this.logLines = page.getByRole('listbox', { name: 'Log entries' }).getByRole('option');
            this.consoleLines = page.getByRole('tabpanel', { name: 'Console' }).getByRole('option');
            this.consoleLineMessages = page.locator('.console-line-message');
            this.errorMessages = page.locator('.error-message');
            this.consoleStacks = page.locator('.console-stack');
            this.networkRequests = page.getByRole('listbox', { name: 'Network requests' }).getByRole('option');
            this.snapshotContainer = page.locator('.snapshot-container iframe.snapshot-visible[name=snapshot]');
            this.metadataTab = page.getByRole('tabpanel', { name: 'Metadata' });
            this.sourceCodeTab = page.getByRole('tabpanel', { name: 'Source' });
            this.networkTab = page.getByRole('tabpanel', { name: 'Network' });
            this.settingsDialog = page.getByTestId('settings-toolbar-dialog');
            this.themeSetting = this.settingsDialog.getByRole('combobox', { name: 'Theme' });
            this.displayCanvasContentSetting = page.locator('.setting').getByText('Display canvas content');
        }
        async showAllActions() {
            await this.page.getByRole('button', { name: 'Filter actions' }).click();
            await this.page.locator('.setting').getByText('Network routes').click();
            await this.page.locator('.setting').getByText('Getters').click();
            await this.page.locator('.setting').getByText('Configuration').click();
            await this.page.getByRole('button', { name: 'Filter actions' }).click();
        }
        stackFrames(options = {}) {
            return this.page.getByRole('listbox', { name: 'Stack trace' }).getByRole('option', options);
        }
        actionIconsText(action) {
            const entry = this.actionsTree.getByRole('treeitem', { name: action });
            return entry.locator('.action-icon-value').filter({ visible: true });
        }
        actionIcons(action) {
            return this.actionsTree.getByRole('treeitem', { name: action }).locator('.action-icons').filter({ visible: true });
        }
        async expandAction(title) {
            await this.actionsTree.getByRole('treeitem', { name: title }).locator('.codicon-chevron-right').click();
        }
        async selectAction(title, ordinal = 0) {
            await this.actionsTree.getByTitle(title).nth(ordinal).click();
        }
        async hoverAction(title, ordinal = 0) {
            await this.actionsTree.getByRole('treeitem', { name: title }).nth(ordinal).hover();
        }
        async selectSnapshot(name) {
            await this.page.getByRole('tab', { name }).click();
        }
        async showErrorsTab() {
            await this.page.getByRole('tab', { name: 'Errors' }).click();
        }
        async showConsoleTab() {
            await this.page.getByRole('tab', { name: 'Console' }).click();
        }
        async showSourceTab() {
            await this.page.getByRole('tab', { name: 'Source' }).click();
        }
        async showNetworkTab() {
            await this.page.getByRole('tab', { name: 'Network' }).click();
        }
        async showMetadataTab() {
            await this.page.getByRole('tab', { name: 'Metadata' }).click();
        }
        async showSettings() {
            await this.page.getByRole('button', { name: 'Settings' }).click();
        }
        async snapshotFrame(actionName, ordinal = 0, hasSubframe = false) {
            await this.selectAction(actionName, ordinal);
            while (this.page.frames().length < (hasSubframe ? 4 : 3))
                await this.page.waitForEvent('frameattached');
            return this.page.frameLocator('iframe.snapshot-visible[name=snapshot]');
        }
    };
})();
export const traceViewerFixtures = {
    showTraceViewer: async ({ playwright, childProcess, browserName }, use, testInfo) => {
        const browsers = [];
        const tracings = [];
        await use(async (trace, { host, port, stdin } = {}) => {
            const command = [
                'node',
                path.join(__dirname, '../../packages/playwright-core/cli.js'),
                'show-trace',
                '--port', '' + (port ?? '0'),
            ];
            if (host)
                command.push('--host', host);
            if (stdin)
                command.push('--stdin');
            if (trace)
                command.push(trace);
            const cp = childProcess({ command });
            await cp.waitForOutput('Listening on');
            const browser = await playwright.chromium.launch({
                ...(browserName === 'chromium' ? {} : { channel: 'chromium' }),
                executablePath: process.env.CRPATH, // without this, setting FFPATH makes us launch Firefox with Chromium args
            });
            browsers.push(browser);
            const page = await browser.newPage();
            if (process.env.PWTEST_DEBUG_TRACE_VIEWER) {
                const tracing = page.context().tracing;
                await tracing.start({ snapshots: true, screenshots: true });
                tracings.push(tracing);
            }
            const url = cp.output.match(/Listening on (http:\/\/[^\s]+)/)[1];
            await page.goto(url);
            return new TraceViewerPage(page, cp);
        });
        for (const [index, tracing] of tracings.entries()) {
            const path = testInfo.outputPath(`viewer-trace-${index}.zip`);
            await tracing.stop({ path });
            await testInfo.attach(`viewer-trace-${index}.zip`, { path, contentType: 'application/zip' });
        }
        for (const browser of browsers)
            await browser.close();
    },
    runAndTrace: async ({ context, showTraceViewer }, use, testInfo) => {
        await use(async (body, optsOverrides = {}) => {
            const traceFile = testInfo.outputPath('trace.zip');
            await context.tracing.start({ snapshots: true, screenshots: true, sources: true, ...optsOverrides });
            await body();
            await context.tracing.stop({ path: traceFile });
            if (process.env.PWTEST_DEBUG_TRACE_VIEWER)
                await testInfo.attach('recorded-trace.zip', { path: traceFile, contentType: 'application/zip' });
            return showTraceViewer(traceFile);
        });
    },
};
//# sourceMappingURL=traceViewerFixtures.js.map