"use strict";
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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * E2E: launches real headless chromium via SessionManager and verifies
 * screencast frames are delivered. Skipped if chromium binary missing.
 *
 * Run: npx vitest run src/__tests__/browser-chrome-e2e.test.ts
 */
const vitest_1 = require("vitest");
const http = __importStar(require("http"));
const playwright_1 = require("playwright");
const session_manager_1 = require("../browser-chrome/session-manager");
const screencast_1 = require("../browser-chrome/screencast");
// Skip if chromium binary not installed locally — keeps CI green when
// `npx playwright install chromium` hasn't run.
let chromiumAvailable = false;
try {
    const path = playwright_1.chromium.executablePath();
    chromiumAvailable = !!path;
}
catch {
    chromiumAvailable = false;
}
vitest_1.describe.skipIf(!chromiumAvailable)('browser-chrome e2e (real chromium)', () => {
    let upstream;
    let upstreamPort = 0;
    // Minimal mock WS that captures sent messages — avoids needing a real
    // server/client pair just to verify screencast delivers frames.
    function mockWs() {
        const sent = [];
        const ws = {
            readyState: 1, // OPEN
            bufferedAmount: 0,
            send: (data) => sent.push(data),
            close: () => { ws.readyState = 3; },
        };
        return { sent, ws };
    }
    (0, vitest_1.afterAll)(async () => {
        await session_manager_1.browserChromeSessions.destroyAll();
        if (upstream)
            await new Promise(r => upstream.close(() => r()));
    }, 30000);
    (0, vitest_1.it)('starts chromium, navigates to local server, and delivers screencast frames', async () => {
        upstream = http.createServer((req, res) => {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            // Animated page is required — CDP screencast only emits frames on
            // visual change, a fully static page yields zero frames.
            res.end(`<html><body style="background:#f00;font-size:48px">
        <div id="c">0</div>
        <script>let n=0;setInterval(()=>{document.getElementById('c').textContent=++n},50)</script>
      </body></html>`);
        });
        await new Promise(r => upstream.listen(0, '127.0.0.1', r));
        upstreamPort = upstream.address().port;
        const session = await session_manager_1.browserChromeSessions.getOrCreate('e2e-user');
        (0, vitest_1.expect)(session.sid).toBeTruthy();
        (0, vitest_1.expect)(session.username).toBe('e2e-user');
        await session.page.goto(`http://127.0.0.1:${upstreamPort}/`, { waitUntil: 'load' });
        (0, vitest_1.expect)(session.page.url()).toContain('127.0.0.1');
        const { sent, ws } = mockWs();
        const stop = await (0, screencast_1.startScreencast)(session, ws);
        // Wait for at least 1 frame (chromium usually emits within 200ms after page paints).
        await new Promise((resolve, reject) => {
            const t = setTimeout(() => reject(new Error('no frame in 3s')), 3000);
            const i = setInterval(() => {
                if (sent.length > 0) {
                    clearTimeout(t);
                    clearInterval(i);
                    resolve();
                }
            }, 50);
        });
        (0, vitest_1.expect)(sent.length).toBeGreaterThan(0);
        const msg = JSON.parse(sent[0]);
        (0, vitest_1.expect)(msg.type).toBe('frame');
        (0, vitest_1.expect)(msg.format).toBe('jpeg');
        (0, vitest_1.expect)(typeof msg.data).toBe('string');
        (0, vitest_1.expect)(msg.data.length).toBeGreaterThan(100);
        await stop();
    }, 30000);
    (0, vitest_1.it)('reuses session for same user', async () => {
        const a = await session_manager_1.browserChromeSessions.getOrCreate('reuse-user');
        const b = await session_manager_1.browserChromeSessions.getOrCreate('reuse-user');
        (0, vitest_1.expect)(a.sid).toBe(b.sid);
    }, 30000);
});
//# sourceMappingURL=browser-chrome-e2e.test.js.map