"use strict";
// Copyright 2021-2025 The Connect Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.connectNodeAdapter = connectNodeAdapter;
const connect_1 = require("@connectrpc/connect");
const protocol_1 = require("@connectrpc/connect/protocol");
const node_universal_handler_js_1 = require("./node-universal-handler.js");
const compression_js_1 = require("./compression.js");
/**
 * Create a Node.js request handler from a ConnectRouter.
 *
 * The returned function is compatible with http.RequestListener and its equivalent for http2.
 */
function connectNodeAdapter(options) {
    var _a;
    if (options.acceptCompression === undefined) {
        options.acceptCompression = [compression_js_1.compressionGzip, compression_js_1.compressionBrotli];
    }
    const router = (0, connect_1.createConnectRouter)(options);
    options.routes(router);
    const prefix = (_a = options.requestPathPrefix) !== null && _a !== void 0 ? _a : "";
    const paths = new Map();
    for (const uHandler of router.handlers) {
        paths.set(prefix + uHandler.requestPath, uHandler);
    }
    return function nodeRequestHandler(req, res) {
        var _a, _b, _c, _d;
        // Strip the query parameter when matching paths.
        const uHandler = paths.get((_b = (_a = req.url) === null || _a === void 0 ? void 0 : _a.split("?", 2)[0]) !== null && _b !== void 0 ? _b : "");
        if (!uHandler) {
            ((_c = options.fallback) !== null && _c !== void 0 ? _c : fallback)(req, res);
            return;
        }
        const uReq = (0, node_universal_handler_js_1.universalRequestFromNodeRequest)(req, res, undefined, (_d = options.contextValues) === null || _d === void 0 ? void 0 : _d.call(options, req));
        uHandler(uReq)
            .then((uRes) => (0, node_universal_handler_js_1.universalResponseToNodeResponse)(uRes, res))
            .catch((reason) => {
            if (connect_1.ConnectError.from(reason).code == connect_1.Code.Aborted) {
                return;
            }
            console.error(`handler for rpc ${uHandler.method.name} of ${uHandler.service.typeName} failed`, reason);
        });
    };
}
const fallback = (request, response) => {
    response.writeHead(protocol_1.uResponseNotFound.status);
    response.end();
};
