"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = __importDefault(require("http"));
const https_1 = __importDefault(require("https"));
const lodash_1 = require("lodash");
const convert_1 = __importDefault(require("./convert"));
class Forwarder {
    forward(ctx) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                const { req, res } = ctx;
                if (!res.writable ||
                    res.finished ||
                    !(lodash_1.isUndefined(res.body) || lodash_1.isNull(res.body))) {
                    return resolve(false);
                }
                const options = convert_1.default(req);
                let client = http_1.default;
                if (options.protocol && options.protocol.startsWith('https')) {
                    client = https_1.default;
                }
                if (req.body && req.body.length) {
                    options.headers['content-length'] = req.body.length;
                }
                // decode暂不支持 brolti 算法
                options.headers['accept-encoding'] = 'gzip, deflate';
                const proxyReq = client.request(options, proxyRes => {
                    res.statusCode = proxyRes.statusCode;
                    Object.keys(proxyRes.headers).forEach(k => {
                        const v = proxyRes.headers[k];
                        res.setHeader(k, v);
                    });
                    ctx.res.body = proxyRes;
                    return resolve(proxyRes);
                });
                if (req.body) {
                    proxyReq.end(req.body);
                }
                else {
                    req.pipe(proxyReq);
                }
                proxyReq.on('error', e => reject(e));
            });
        });
    }
}
exports.Forwarder = Forwarder;
//# sourceMappingURL=index.js.map