"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 http_proxy_1 = __importDefault(require("http-proxy"));
const url_1 = __importDefault(require("url"));
class UpgradeHandler {
    constructor() {
        // 创建httpProxy
        this.proxy = http_proxy_1.default.createProxyServer({
            secure: false,
        });
        this.middleware = () => Promise.resolve(null);
    }
    setMiddleware(middleware) {
        this.middleware = middleware;
    }
    handle(req, socket, head) {
        return __awaiter(this, void 0, void 0, function* () {
            const ctx = {
                head,
                req,
                res: new http_1.default.ServerResponse(req),
                socket,
            };
            this.middleware(ctx).then(() => {
                const { hostname, port, protocol } = url_1.default.parse(req.url);
                this.proxy.ws(req, socket, head, {
                    target: {
                        hostname,
                        port,
                        protocol,
                    },
                });
            });
        });
    }
}
exports.UpgradeHandler = UpgradeHandler;
//# sourceMappingURL=upgrade.js.map