"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyService = void 0;
const uniproxy_1 = require("@ubio/uniproxy");
const fs_1 = require("fs");
const inversify_1 = require("inversify");
const path_1 = __importDefault(require("path"));
const config_js_1 = require("../../config.js");
const logger_js_1 = require("../../logger.js");
const session_js_1 = require("../session.js");
const PROXY_PORT = (0, config_js_1.numberConfig)('PROXY_PORT', 3128);
const CA_CERTIFICATES = (0, config_js_1.stringConfig)('CA_CERTIFICATES', '');
const caCert = (0, fs_1.readFileSync)(path_1.default.join(__dirname, '../../../../ca.crt'), 'utf-8');
let ProxyService = class ProxyService extends uniproxy_1.RoutingProxy {
    constructor(config, logger) {
        super({
            logger,
        });
        this.config = config;
    }
    getCACertificates() {
        const defaults = super.getCACertificates();
        const ca = this.config.get(CA_CERTIFICATES);
        return [...defaults, ca, caCert].filter(Boolean);
    }
    async onSessionStart() {
        await this.init();
    }
    async onSessionFinish() {
        await this.shutdown(true);
    }
    getProxyPort() {
        return this.config.get(PROXY_PORT);
    }
    setup(proxyUpstream) {
        this.clearRoutes();
        this.defaultUpstream = proxyUpstream;
        this.insertRoute({
            label: 'bypass-chrome-internals',
            hostPattern: '(\\.google\\.com|\\.gvt1\\.com|update\\.googleapis\\.com)(:443)?$',
            upstream: null,
        });
    }
    addRoute(hostRegexp, upstream, label = 'default') {
        this.insertRoute({
            hostPattern: hostRegexp.source,
            upstream,
            label,
        }, 0);
    }
    async init() {
        if (this.isRunning()) {
            return;
        }
        const port = this.getProxyPort();
        try {
            await this.start(port);
            this.logger.info(`Local proxy listening on ${port}`);
        }
        catch (err) {
            if (err.code === 'EADDRINUSE') {
                this.logger.warn(`Local proxy port is busy`, { err, port });
                return;
            }
            throw err;
        }
    }
};
ProxyService = __decorate([
    (0, inversify_1.injectable)(),
    (0, session_js_1.SessionHandler)(),
    __param(0, (0, inversify_1.inject)(config_js_1.Configuration)),
    __param(1, (0, inversify_1.inject)(logger_js_1.Logger)),
    __metadata("design:paramtypes", [config_js_1.Configuration,
        logger_js_1.Logger])
], ProxyService);
exports.ProxyService = ProxyService;
//# sourceMappingURL=proxy.js.map