"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChromiumBrowserEngine = void 0;
const path_1 = __importDefault(require("path"));
const async_retry_1 = __importDefault(require("async-retry"));
const fs = __importStar(require("fs-extra"));
const mobileEmulationUtil_1 = require("../browserLauncher/mobileEmulationUtil");
const resourceUtil_1 = require("../util/resourceUtil");
const browserEngine_1 = require("./browserEngine");
const cliConfigProvider_1 = require("../providers/cliConfigProvider");
const loggingProvider_1 = require("../providers/logging/loggingProvider");
const chromeFinder_1 = require("./chromeFinder");
const baseExecutionEngineLaunchArgs = [
    '--unlimited-storage',
    '--disable-dev-shm-usage',
    '--enable-print-preview-register-promos',
    '--kiosk-printing',
    '--disable-infobars',
    '--enable-logging',
    '--v=0',
    '--enable-features=NetworkService,NetworkServiceInProcess',
    '--disable-component-update',
];
const ExecutionEngineFakeAudioFilePath = '/opt/media/mabl_test_audio.wav';
const ExecutionEngineFakeVideoFilePath = '/opt/media/mabl_test_pattern.y4m';
class ChromiumBrowserEngine {
    name() {
        return 'chromium';
    }
    getBrowserLaunchOptions(options) {
        const commandLineArgs = [];
        const ignoreCommandLineDefaultArgs = [];
        const disableFeaturesFlags = [];
        if (options.containerTesting) {
            commandLineArgs.push('--no-sandbox');
        }
        if (options.disableIsolation) {
            disableFeaturesFlags.push('IsolateOrigins');
            disableFeaturesFlags.push('site-per-process');
        }
        if (disableFeaturesFlags.length) {
            commandLineArgs.push(`--disable-features=${disableFeaturesFlags.join(',')}`);
        }
        if (options.autoOpenDevtoolsForTabs) {
            commandLineArgs.push('--auto-open-devtools-for-tabs');
        }
        const fakeMicrophoneMedia = (0, resourceUtil_1.findResource)('media/mabl_test_audio.wav', options.resourcesDirectoryOverride);
        const fakeWebcamMedia = (0, resourceUtil_1.findResource)('media/mabl_test_pattern.y4m', options.resourcesDirectoryOverride);
        const defaultDeviceDescriptor = (0, mobileEmulationUtil_1.getDeviceDescriptorForEmulation)(options.emulationConfig);
        this.addBasicLaunchArgs(commandLineArgs, options.browserWidth, options.browserHeight, fakeMicrophoneMedia, fakeWebcamMedia, options.ignoreCertificateErrors, defaultDeviceDescriptor);
        const allowlistArg = this.getAuthServerAllowlistArg(options.authServerPolicy);
        if (allowlistArg) {
            commandLineArgs.push(allowlistArg);
        }
        if (options.enableExtensions) {
            ignoreCommandLineDefaultArgs.push('--disable-extensions');
        }
        if (options.additionalCommandLineArgs) {
            commandLineArgs.push(...options.additionalCommandLineArgs);
        }
        return {
            commandLineArgs,
            defaultDeviceDescriptor,
            ignoreCommandLineDefaultArgs,
            permissions: ['geolocation', 'notifications', 'local-network-access'],
        };
    }
    getExecutionEngineBrowserLaunchOptions(options, proxyInfo) {
        const commandLineArgs = [...baseExecutionEngineLaunchArgs];
        if (proxyInfo.pacProxy) {
            commandLineArgs.push(`--proxy-pac-url=${proxyInfo.pacProxy}`);
        }
        else if (proxyInfo.socksProxy) {
            commandLineArgs.push(`--proxy-server=socks=${proxyInfo.socksProxy}`);
        }
        else if (proxyInfo.httpProxy) {
            const proxyUrl = new URL(proxyInfo.httpProxy);
            const proxyAddress = `${proxyUrl.hostname}:${proxyUrl.port}`;
            commandLineArgs.push(`--proxy-server=http=${proxyAddress};https=${proxyAddress}`);
        }
        else {
            throw new Error('no proxy provided for cloud run');
        }
        const defaultDeviceDescriptor = (0, mobileEmulationUtil_1.getDeviceDescriptorForEmulation)(options.emulationConfig);
        this.addBasicLaunchArgs(commandLineArgs, options.browserWidth, options.browserHeight, ExecutionEngineFakeAudioFilePath, ExecutionEngineFakeVideoFilePath, true, defaultDeviceDescriptor);
        const allowlistArg = this.getAuthServerAllowlistArg(options.authServerPolicy);
        if (allowlistArg) {
            commandLineArgs.push(allowlistArg);
        }
        loggingProvider_1.logger.debug(`launchArgs: ${JSON.stringify(commandLineArgs)}`);
        return {
            commandLineArgs,
            defaultDeviceDescriptor,
            permissions: ['geolocation', 'notifications', 'local-network-access'],
        };
    }
    addBasicLaunchArgs(launchArgs, browserWidth, browserHeight, fakeMicrophoneMediaPath, fakeWebcamMediaPath, ignoreCertificateErrors, deviceDescriptor) {
        launchArgs.push(`--window-size=${deviceDescriptor?.width ?? browserWidth},${deviceDescriptor?.height ?? browserHeight}`);
        launchArgs.push('--use-fake-ui-for-media-stream');
        launchArgs.push('--use-fake-device-for-media-stream');
        launchArgs.push(`--use-file-for-fake-audio-capture=${fakeMicrophoneMediaPath}`);
        launchArgs.push(`--use-file-for-fake-video-capture=${fakeWebcamMediaPath}`);
        if (ignoreCertificateErrors) {
            launchArgs.push('--ignore-certificate-errors');
        }
    }
    getAuthServerAllowlistArg(policy) {
        if (policy === 'none') {
            return '--auth-server-allowlist="_"';
        }
        if (policy === 'all') {
            return '--auth-server-allowlist="*"';
        }
        return;
    }
    prepareBrowserPreferencesDirectory(windowPlacement) {
        return (0, async_retry_1.default)(() => {
            const tempBrowserPreferencesDirectory = (0, browserEngine_1.getTempBrowserPrefDirectory)();
            fs.ensureDirSync(path_1.default.normalize(`${tempBrowserPreferencesDirectory}/Default`));
            const prefFilePath = path_1.default.normalize(`${tempBrowserPreferencesDirectory}/Default/Preferences`);
            fs.writeFileSync(prefFilePath, JSON.stringify(this.generateChromiumPreferencesFile(windowPlacement), null, 3));
            fs.chmodSync(path_1.default.normalize(`${tempBrowserPreferencesDirectory}/Default`), 0o777);
            fs.chmodSync(prefFilePath, 0o777);
            return tempBrowserPreferencesDirectory;
        }, {
            retries: 5,
        });
    }
    generateChromiumPreferencesFile(windowPlacement, _proxyInfo) {
        const preferences = {
            download: {
                open_pdf_in_system_reader: true,
                prompt_for_download: false,
            },
            profile: {
                avatar_index: 5,
                name: 'mabl',
            },
            plugins: {
                always_open_pdf_externally: true,
            },
        };
        if (windowPlacement) {
            preferences.browser = {
                window_placement: {
                    always_on_top: false,
                    ...windowPlacement,
                },
            };
        }
        return preferences;
    }
    async findBrowserExecutable() {
        const existingLocation = await cliConfigProvider_1.CliConfigProvider.getConfigProperty(cliConfigProvider_1.BROWSER_CONFIG_KEY);
        if (typeof existingLocation === 'string' &&
            existingLocation &&
            fs.existsSync(existingLocation)) {
            return existingLocation;
        }
        const chromePath = this.searchForChrome();
        if (!chromePath) {
            throw new Error('No stable Google Chrome installation was found on this system.');
        }
        await cliConfigProvider_1.CliConfigProvider.setConfigProperty(cliConfigProvider_1.BROWSER_CONFIG_KEY, chromePath);
        return chromePath;
    }
    searchForChrome() {
        return (0, chromeFinder_1.searchForChrome)();
    }
    getProxySpec(_proxyInfo) {
        return;
    }
}
exports.ChromiumBrowserEngine = ChromiumBrowserEngine;
