"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var node_request_response_exports = {};
__export(node_request_response_exports, {
  pipeResponseTo: () => pipeResponseTo,
  requestHeaders: () => requestHeaders,
  toApiRequest: () => toApiRequest
});
module.exports = __toCommonJS(node_request_response_exports);
function requestHeaders(headers) {
  const result = new Headers();
  for (const [key, value] of Object.entries(headers)) {
    if (value != null) {
      if (Array.isArray(value)) {
        value.forEach((v) => result.append(key, v));
      } else {
        result.append(key, value);
      }
    }
  }
  return result;
}
function toApiRequest(req) {
  return {
    headers: requestHeaders(req.headers),
    method: req.method ?? "GET",
    url: req.url ?? "",
    json() {
      return req.body;
    }
  };
}
async function pipeResponseTo(apiResponse, res) {
  const headers = responseHeaders(apiResponse.headers);
  Object.entries(headers).forEach(([key, value]) => {
    res.setHeader(key, value);
  });
  res.statusCode = apiResponse.status;
  try {
    if (apiResponse.body) {
      await pipeTo(apiResponse.body, res);
    }
    res.end();
  } catch (error) {
    if (!res.headersSent) {
      res.statusCode = 500;
      res.end();
    } else {
      res.destroy(error instanceof Error ? error : new Error(`${error}`));
    }
  }
}
function responseHeaders(headers) {
  return [...headers.entries()].reduce((acc, [key, value]) => {
    if (key in acc) {
      const existingValue = acc[key];
      if (Array.isArray(existingValue)) {
        existingValue.push(value);
      } else {
        acc[key] = [existingValue, value];
      }
    } else {
      acc[key] = value;
    }
    return acc;
  }, {});
}
async function pipeTo(stream, res) {
  const reader = stream.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done)
      break;
    res.write(value);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  pipeResponseTo,
  requestHeaders,
  toApiRequest
});
//# sourceMappingURL=node-request-response.js.map