"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveBrowserRuntimeEnv = exports.resolveConfiguredBrowserProfileDir = exports.resolveDefaultChromeUserDataDir = void 0;
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const helpers_1 = require("../helpers");
const DEVTOOLS_HOST = '127.0.0.1';
const DEVTOOLS_ACTIVE_PORT_FILE = 'DevToolsActivePort';
function resolveDefaultChromeUserDataDir(platform = process.platform, env = process.env) {
    switch (platform) {
        case 'darwin':
            return path.join(env.HOME || env.USERPROFILE || '', 'Library', 'Application Support', 'Google', 'Chrome');
        case 'linux':
            return path.join(env.HOME || env.USERPROFILE || '', '.config', 'google-chrome');
        case 'win32': {
            const localAppData = env.LOCALAPPDATA;
            if (!localAppData) {
                throw new Error('LOCALAPPDATA is required to resolve the default Chrome user-data-dir on Windows');
            }
            return path.join(localAppData, 'Google', 'Chrome', 'User Data');
        }
        default:
            return path.join(env.HOME || env.USERPROFILE || '', '.config', 'google-chrome');
    }
}
exports.resolveDefaultChromeUserDataDir = resolveDefaultChromeUserDataDir;
function resolveConfiguredBrowserProfileDir(profileDir) {
    return profileDir?.trim() ? (0, helpers_1.expandPath)(profileDir) : undefined;
}
exports.resolveConfiguredBrowserProfileDir = resolveConfiguredBrowserProfileDir;
async function resolveBrowserRuntimeEnv(options) {
    const requestedProfileDir = options.profileDir || resolveDefaultChromeUserDataDir();
    const userDataDir = (0, helpers_1.expandPath)(requestedProfileDir);
    const directoryStat = await safeStat(userDataDir);
    if (!directoryStat?.isDirectory()) {
        throw new Error(`Chrome profile directory is invalid: ${userDataDir}`);
    }
    const metadataPath = path.join(userDataDir, DEVTOOLS_ACTIVE_PORT_FILE);
    const port = await resolveDevToolsPort({
        userDataDir,
        metadataPath,
        explicitPort: options.devtoolsPort || process.env.CCS_BROWSER_DEVTOOLS_PORT,
    });
    const httpUrl = `http://${DEVTOOLS_HOST}:${port}`;
    const versionUrl = `${httpUrl}/json/version`;
    let versionPayload;
    try {
        const response = await fetch(versionUrl);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        versionPayload = await response.json();
    }
    catch {
        throw new Error(`Chrome DevTools endpoint is unreachable: ${httpUrl}`);
    }
    const websocketUrl = typeof versionPayload === 'object' &&
        versionPayload !== null &&
        typeof versionPayload.webSocketDebuggerUrl === 'string'
        ? versionPayload.webSocketDebuggerUrl
        : '';
    if (!websocketUrl) {
        throw new Error(`Chrome DevTools endpoint did not provide a websocket target: ${versionUrl}`);
    }
    return {
        CCS_BROWSER_USER_DATA_DIR: userDataDir,
        CCS_BROWSER_DEVTOOLS_HOST: DEVTOOLS_HOST,
        CCS_BROWSER_DEVTOOLS_PORT: port,
        CCS_BROWSER_DEVTOOLS_HTTP_URL: httpUrl,
        CCS_BROWSER_DEVTOOLS_WS_URL: websocketUrl,
    };
}
exports.resolveBrowserRuntimeEnv = resolveBrowserRuntimeEnv;
function parseDevToolsPort(metadataPath, metadata) {
    const [rawPort] = metadata
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line.length > 0);
    if (!rawPort || !/^\d+$/.test(rawPort)) {
        throw new Error(`Chrome reuse metadata is invalid: ${metadataPath}`);
    }
    const port = Number.parseInt(rawPort, 10);
    if (!Number.isInteger(port) || port < 1 || port > 65535) {
        throw new Error(`Chrome reuse metadata is invalid: ${metadataPath}`);
    }
    return String(port);
}
async function resolveDevToolsPort(options) {
    if (options.explicitPort?.trim()) {
        return parsePortValue(options.explicitPort.trim(), 'CCS_BROWSER_DEVTOOLS_PORT');
    }
    let metadata;
    try {
        metadata = await fs.promises.readFile(options.metadataPath, 'utf8');
    }
    catch (error) {
        const code = error.code;
        if (code && code !== 'ENOENT') {
            throw new Error(`Chrome reuse metadata is unreadable: ${options.metadataPath}`);
        }
    }
    if (metadata !== undefined) {
        return parseDevToolsPort(options.metadataPath, metadata);
    }
    const discoveredPort = discoverDevToolsPortFromChromeProcess(options.userDataDir);
    if (discoveredPort) {
        return discoveredPort;
    }
    throw new Error(`Chrome reuse metadata not found: ${options.metadataPath}`);
}
function parsePortValue(rawPort, sourceLabel) {
    if (!/^\d+$/.test(rawPort)) {
        throw new Error(`Chrome reuse metadata is invalid: ${sourceLabel}`);
    }
    const port = Number.parseInt(rawPort, 10);
    if (!Number.isInteger(port) || port < 1 || port > 65535) {
        throw new Error(`Chrome reuse metadata is invalid: ${sourceLabel}`);
    }
    return String(port);
}
function discoverDevToolsPortFromChromeProcess(userDataDir) {
    try {
        const processList = (0, child_process_1.execFileSync)('ps', ['-axww', '-o', 'command='], {
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'],
        });
        const lines = processList
            .split(/\r?\n/)
            .map((line) => line.trim())
            .filter(Boolean);
        const normalizedDir = normalizePathForComparison(userDataDir);
        for (const line of lines) {
            if (!line.includes('Chrome') && !line.includes('chromium')) {
                continue;
            }
            if (!matchesUserDataDir(line, normalizedDir)) {
                continue;
            }
            const match = line.match(/--remote-debugging-port=(\d+)/);
            if (match?.[1]) {
                return parsePortValue(match[1], 'process-list');
            }
        }
    }
    catch {
        return undefined;
    }
    return undefined;
}
function matchesUserDataDir(commandLine, normalizedDir) {
    const candidates = [
        `--user-data-dir=${normalizedDir}`,
        `--user-data-dir="${normalizedDir}"`,
        `--user-data-dir='${normalizedDir}'`,
    ];
    const normalizedCommand = normalizePathForComparison(commandLine);
    return candidates.some((candidate) => normalizedCommand.includes(candidate));
}
function normalizePathForComparison(value) {
    return process.platform === 'win32' ? value.toLowerCase() : value;
}
async function safeStat(targetPath) {
    try {
        return await fs.promises.stat(targetPath);
    }
    catch {
        return null;
    }
}
//# sourceMappingURL=chrome-reuse.js.map