"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.FirefoxBrowserEngine = void 0;
const mobileEmulationUtil_1 = require("../browserLauncher/mobileEmulationUtil");
const path_1 = __importDefault(require("path"));
const fs = __importStar(require("fs-extra"));
const browserEngine_1 = require("./browserEngine");
const async_retry_1 = __importDefault(require("async-retry"));
class FirefoxBrowserEngine {
    name() {
        return 'firefox';
    }
    getBrowserLaunchOptions(options) {
        return {
            commandLineArgs: [],
            ignoreCommandLineDefaultArgs: [],
            defaultDeviceDescriptor: (0, mobileEmulationUtil_1.getDeviceDescriptorForEmulation)(options.emulationConfig),
            permissions: ['geolocation', 'notifications'],
        };
    }
    getExecutionEngineBrowserLaunchOptions(options, proxyInfo) {
        if (Object.keys(this.getProxyPreferences(proxyInfo)).length === 0) {
            throw new Error('no proxy provided for cloud run');
        }
        return {
            commandLineArgs: [],
            defaultDeviceDescriptor: (0, mobileEmulationUtil_1.getDeviceDescriptorForEmulation)(options.emulationConfig),
            permissions: ['geolocation', 'notifications'],
        };
    }
    getProxyPreferences(proxyInfo) {
        const proxyPreferences = {};
        proxyPreferences['network.proxy.allow_hijacking_localhost'] = true;
        proxyPreferences['network.proxy.testing_localhost_is_secure_when_hijacked'] = true;
        if (proxyInfo?.pacProxy) {
            proxyPreferences['network.proxy.autoconfig_url'] = proxyInfo.pacProxy;
            proxyPreferences['network.proxy.type'] = 2;
        }
        else if (proxyInfo?.socksProxy) {
            const socksUrl = new URL(proxyInfo.socksProxy);
            proxyPreferences['network.proxy.socks'] = socksUrl.hostname;
            proxyPreferences['network.proxy.socks_port'] = Number.parseInt(socksUrl.port);
            proxyPreferences['network.proxy.socks_version'] = 5;
            proxyPreferences['network.proxy.type'] = 1;
        }
        else if (proxyInfo?.httpProxy) {
            const proxyUrl = new URL(proxyInfo.httpProxy);
            proxyPreferences['network.proxy.http'] = proxyUrl.hostname;
            proxyPreferences['network.proxy.http_port'] = Number.parseInt(proxyUrl.port);
            proxyPreferences['network.proxy.ssl'] = proxyUrl.hostname;
            proxyPreferences['network.proxy.ssl_port'] = Number.parseInt(proxyUrl.port);
            proxyPreferences['network.proxy.share_proxy_settings'] = true;
            proxyPreferences['network.proxy.type'] = 1;
        }
        if (proxyInfo) {
            proxyPreferences['network.proxy.no_proxies_on'] = 'localhost,127.0.0.1';
        }
        return proxyPreferences;
    }
    prepareBrowserPreferencesDirectory(_windowPlacement, proxyInfo) {
        const customPreferences = this.getProxyPreferences(proxyInfo);
        return (0, async_retry_1.default)(() => {
            const preferenceFileName = 'user.js';
            const tempBrowserPreferencesDirectory = (0, browserEngine_1.getTempBrowserPrefDirectory)(this.name());
            const prefFilePath = path_1.default.normalize(`${tempBrowserPreferencesDirectory}/${preferenceFileName}`);
            fs.writeFileSync(prefFilePath, this.generatePreferencesInfo(customPreferences));
            return tempBrowserPreferencesDirectory;
        }, {
            retries: 5,
        });
    }
    findBrowserExecutable() {
        return Promise.resolve('');
    }
    generatePreferencesInfo(customPrefs = {}) {
        const lines = [];
        const prefs = { ...this.getFirefoxUserPrefs(), ...customPrefs };
        for (const [name, value] of Object.entries(prefs)) {
            lines.push(`user_pref(${JSON.stringify(name)}, ${JSON.stringify(value)});`);
        }
        return lines.join('\n');
    }
    getFirefoxUserPrefs() {
        return {
            'xpinstall.signatures.required': false,
            'browser.preferences.defaultPerformanceSettings.enabled': false,
            'layers.acceleration.disabled': true,
            'browser.cache.memory.enable': false,
            'browser.cache.offline.enable': false,
            'browser.cache.disk.capacity': 262144,
            'browser.sessionhistory.max_entries': 1,
            'browser.sessionhistory.max_total_viewers': 0,
            'media.memory_caches_combined_limit_kb': 65536,
            'media.memory_caches_combined_limit_pc_sysmem': 1,
            'pdfjs.enabledCache.state': false,
            'plugin.disable_full_page_plugin_for_types': 'application/pdf,application/vnd.adobe.xfdf,application/vnd.adobe.xdp+xml',
            'browser.helperApps.alwaysAsk.force': true,
            'browser.helperApps.neverAsk.saveToDisk': [
                'application/csv',
                'application/force-download',
                'application/gzip',
                'application/pdf',
                'application/vnd.ms-excel',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/x-7z-compressed',
                'application/x-bzip',
                'application/x-bzip2',
                'application/x-gzip',
                'application/zip',
                'binary/octet-stream',
                'application/octet-stream',
                'image/png',
                'image/jpeg',
                'image/gif',
                'text/csv',
                'text/comma-separated-values',
                'text/plain',
            ].join(','),
            'media.navigator.permission.disabled': true,
            'media.navigator.streams.fake': true,
            'dom.webnotifications.enabled': true,
            'network.proxy.socks_remote_dns': true,
            'security.fileuri.strict_origin_policy': false,
            'security.mixed_content.block_active_content': false,
            'security.mixed_content.block_display_content': false,
        };
    }
    getProxySpec(_proxyInfo) {
        return;
    }
}
exports.FirefoxBrowserEngine = FirefoxBrowserEngine;
