// 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.
import { Code, ConnectError, createConnectRouter } from "@connectrpc/connect";
import { uResponseNotFound } from "@connectrpc/connect/protocol";
import { universalRequestFromNodeRequest, universalResponseToNodeResponse, } from "./node-universal-handler.js";
import { compressionBrotli, compressionGzip } from "./compression.js";
/**
 * Create a Node.js request handler from a ConnectRouter.
 *
 * The returned function is compatible with http.RequestListener and its equivalent for http2.
 */
export function connectNodeAdapter(options) {
    var _a;
    if (options.acceptCompression === undefined) {
        options.acceptCompression = [compressionGzip, compressionBrotli];
    }
    const router = 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 = universalRequestFromNodeRequest(req, res, undefined, (_d = options.contextValues) === null || _d === void 0 ? void 0 : _d.call(options, req));
        uHandler(uReq)
            .then((uRes) => universalResponseToNodeResponse(uRes, res))
            .catch((reason) => {
            if (ConnectError.from(reason).code == Code.Aborted) {
                return;
            }
            console.error(`handler for rpc ${uHandler.method.name} of ${uHandler.service.typeName} failed`, reason);
        });
    };
}
const fallback = (request, response) => {
    response.writeHead(uResponseNotFound.status);
    response.end();
};
