/* Auto-generated CJS entry by build-cjs.mjs — DO NOT EDIT */
const __vext_esm_url = require("node:url").pathToFileURL(__filename).href;
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// dist/adapters/hono/index.js
var index_exports = {};
__export(index_exports, {
  createHonoAdapter: () => createHonoAdapter,
  honoAdapter: () => honoAdapter
});
module.exports = __toCommonJS(index_exports);

// dist/adapters/hono/adapter.js
var import_hono = require("hono");
var import_node_http = require("node:http");
var import_node_crypto = __toESM(require("node:crypto"), 1);

// dist/lib/middlewares/body-parser.js
var PayloadTooLargeError = class extends Error {
  static {
    __name(this, "PayloadTooLargeError");
  }
  maxBytes;
  status = 413;
  constructor(maxBytes) {
    super("Payload Too Large");
    this.maxBytes = maxBytes;
    this.name = "PayloadTooLargeError";
  }
};
function createPayloadTooLargeError(maxBytes) {
  return new PayloadTooLargeError(maxBytes);
}
__name(createPayloadTooLargeError, "createPayloadTooLargeError");
function assertBodySize(size, maxBytes) {
  if (maxBytes !== void 0 && size > maxBytes) {
    throw createPayloadTooLargeError(maxBytes);
  }
}
__name(assertBodySize, "assertBodySize");
function resolveRouteBodyParserConfig(routeOptions) {
  if (routeOptions?.bodyParser)
    return routeOptions.bodyParser;
  if (routeOptions?.override?.maxBodySize !== void 0) {
    return { maxBodySize: routeOptions.override.maxBodySize };
  }
  return void 0;
}
__name(resolveRouteBodyParserConfig, "resolveRouteBodyParserConfig");

// dist/adapters/hono/request.js
function createVextRequest(c, app) {
  const trustProxy = app.config.trustProxy ?? false;
  const closeHandlers = [];
  let _queryCache;
  let _headersCache;
  let _paramsCache;
  let _rawBufferCache;
  let _rawStringCache;
  async function getRawBodyBuffer(maxBytes) {
    if (_rawBufferCache !== void 0) {
      assertBodySize(_rawBufferCache.byteLength, maxBytes);
      return _rawBufferCache;
    }
    const body = c.req.raw.body;
    if (body) {
      const reader = body.getReader();
      const chunks = [];
      let total = 0;
      while (true) {
        const { value, done } = await reader.read();
        if (done)
          break;
        const chunk = Buffer.from(value);
        total += chunk.byteLength;
        if (maxBytes !== void 0 && total > maxBytes) {
          throw createPayloadTooLargeError(maxBytes);
        }
        chunks.push(chunk);
      }
      _rawBufferCache = Buffer.concat(chunks);
      return _rawBufferCache;
    }
    const ab = await c.req.arrayBuffer();
    _rawBufferCache = Buffer.from(ab);
    assertBodySize(_rawBufferCache.byteLength, maxBytes);
    return _rawBufferCache;
  }
  __name(getRawBodyBuffer, "getRawBodyBuffer");
  async function getRawBody(maxBytes) {
    if (_rawStringCache !== void 0) {
      assertBodySize(Buffer.byteLength(_rawStringCache, "utf-8"), maxBytes);
      return _rawStringCache;
    }
    const buf = await getRawBodyBuffer(maxBytes);
    _rawStringCache = buf.toString("utf-8");
    return _rawStringCache;
  }
  __name(getRawBody, "getRawBody");
  function parseQuery() {
    if (_queryCache !== void 0)
      return _queryCache;
    try {
      const url = new URL(c.req.url);
      _queryCache = Object.fromEntries(url.searchParams);
    } catch {
      _queryCache = {};
    }
    return _queryCache;
  }
  __name(parseQuery, "parseQuery");
  function parseHeaders() {
    if (_headersCache !== void 0)
      return _headersCache;
    const record = {};
    c.req.raw.headers.forEach((value, key) => {
      record[key] = value;
    });
    _headersCache = record;
    return _headersCache;
  }
  __name(parseHeaders, "parseHeaders");
  function parseParams() {
    if (_paramsCache !== void 0)
      return _paramsCache;
    try {
      _paramsCache = c.req.param() ?? {};
    } catch {
      _paramsCache = {};
    }
    return _paramsCache;
  }
  __name(parseParams, "parseParams");
  const req = {
    // ── 占位符（立即被 defineProperty 覆盖）─────────────
    query: null,
    headers: null,
    params: null,
    // ── 立即可用字段 ────────────────────────────────────
    body: void 0,
    // body-parser 中间件负责填充
    method: c.req.method.toUpperCase(),
    url: c.req.url,
    path: c.req.path,
    route: "",
    // registerRoute handler 覆写为真实路由模板（F-01）
    // ── 元信息 ──────────────────────────────────────────
    app,
    requestId: "",
    // requestId 中间件负责填充
    ip: resolveIp(c, trustProxy),
    protocol: resolveProtocol(c, trustProxy),
    // ── 生命周期 ────────────────────────────────────────
    onClose(handler) {
      closeHandlers.push(handler);
    },
    // ── 校验数据 ────────────────────────────────────────
    valid(location) {
      return req[`_validated_${location}`];
    },
    // ── 内部方法（body-parser 中间件使用）───────────────────
    // 从 Hono Context 读取原始请求体，带缓存（流只能消费一次）。
    _getRawBody: getRawBody,
    _getRawBodyBuffer: getRawBodyBuffer,
    // ── 内部方法（body-parser multipart 解析用）────────────
    // 返回 Hono 原生 Web Request 对象，供 body-parser 直接调用
    // c.req.raw.formData()，跳过 Buffer 中转，性能更优。
    // 仅供框架内部使用，不建议用户代码直接调用。
    _getHonoRawRequest() {
      return c.req.raw;
    }
  };
  Object.defineProperty(req, "query", {
    get() {
      const value = parseQuery();
      Object.defineProperty(req, "query", {
        value,
        writable: true,
        configurable: true,
        enumerable: true
      });
      return value;
    },
    set(v) {
      _queryCache = v;
      Object.defineProperty(req, "query", {
        value: v,
        writable: true,
        configurable: true,
        enumerable: true
      });
    },
    configurable: true,
    enumerable: true
  });
  Object.defineProperty(req, "headers", {
    get() {
      const value = parseHeaders();
      Object.defineProperty(req, "headers", {
        value,
        writable: true,
        configurable: true,
        enumerable: true
      });
      return value;
    },
    set(v) {
      _headersCache = v;
      Object.defineProperty(req, "headers", {
        value: v,
        writable: true,
        configurable: true,
        enumerable: true
      });
    },
    configurable: true,
    enumerable: true
  });
  Object.defineProperty(req, "params", {
    get() {
      const value = parseParams();
      Object.defineProperty(req, "params", {
        value,
        writable: true,
        configurable: true,
        enumerable: true
      });
      return value;
    },
    set(v) {
      _paramsCache = v;
      Object.defineProperty(req, "params", {
        value: v,
        writable: true,
        configurable: true,
        enumerable: true
      });
    },
    configurable: true,
    enumerable: true
  });
  try {
    const signal = c.req.raw.signal;
    if (signal) {
      const onAbort = /* @__PURE__ */ __name(() => {
        for (const h of closeHandlers) {
          try {
            h();
          } catch {
          }
        }
        closeHandlers.length = 0;
      }, "onAbort");
      if (signal.aborted) {
        onAbort();
      } else {
        signal.addEventListener("abort", onAbort, { once: true });
      }
    }
  } catch {
  }
  return req;
}
__name(createVextRequest, "createVextRequest");
function resolveIp(c, trustProxy) {
  if (trustProxy) {
    const xff = c.req.header("x-forwarded-for");
    if (xff) {
      const firstIp = xff.split(",")[0];
      if (firstIp)
        return firstIp.trim();
    }
  }
  try {
    const env = c.env;
    const incoming = env?.incoming;
    if (incoming?.socket?.remoteAddress) {
      return incoming.socket.remoteAddress;
    }
  } catch {
  }
  return "127.0.0.1";
}
__name(resolveIp, "resolveIp");
function resolveProtocol(c, trustProxy) {
  if (trustProxy) {
    const proto = c.req.header("x-forwarded-proto");
    if (proto === "https")
      return "https";
  }
  return "http";
}
__name(resolveProtocol, "resolveProtocol");

// dist/adapters/hono/response.js
function createResponseBox() {
  return { value: null };
}
__name(createResponseBox, "createResponseBox");
function createVextResponse(c, getRequestId, box) {
  let _status = 200;
  const _headers = {};
  let _wrapEnabled = false;
  let _sent = false;
  function applyHeaders() {
    for (const [k, v] of Object.entries(_headers)) {
      c.header(k, v);
    }
  }
  __name(applyHeaders, "applyHeaders");
  function checkSent(methodName) {
    if (_sent) {
      if (process.env.NODE_ENV !== "production") {
        console.warn(`[vextjs] ⚠️ res.${methodName}() called after response already sent. This is a no-op. Check your handler for duplicate sends.`);
      }
      return true;
    }
    _sent = true;
    return false;
  }
  __name(checkSent, "checkSent");
  function captureResponse(response) {
    box.value = response;
  }
  __name(captureResponse, "captureResponse");
  const res = {
    json(data, status) {
      if (checkSent("json"))
        return;
      const finalStatus = status ?? _status;
      _status = finalStatus;
      if (res._onSend) {
        res._onSend(data, finalStatus, { ..._headers });
      }
      c.status(finalStatus);
      applyHeaders();
      if (_wrapEnabled) {
        if (finalStatus === 204) {
          captureResponse(c.body(null));
          return;
        }
        captureResponse(c.json({
          code: 0,
          data,
          requestId: getRequestId()
        }));
        return;
      }
      if (finalStatus === 204) {
        captureResponse(c.body(null));
        return;
      }
      captureResponse(c.json(data));
    },
    rawJson(data, status) {
      if (checkSent("rawJson"))
        return;
      const finalStatus = status ?? _status;
      _status = finalStatus;
      c.status(finalStatus);
      applyHeaders();
      captureResponse(c.json(data));
    },
    text(content, status) {
      if (checkSent("text"))
        return;
      const finalStatus = status ?? _status;
      _status = finalStatus;
      c.status(finalStatus);
      c.header("Content-Type", "text/plain; charset=utf-8");
      applyHeaders();
      captureResponse(c.body(content));
    },
    stream(readable, contentType = "application/octet-stream") {
      if (checkSent("stream"))
        return;
      c.status(_status);
      c.header("Content-Type", contentType);
      applyHeaders();
      captureResponse(c.body(readable));
    },
    download(readable, filename, contentType) {
      if (checkSent("download"))
        return;
      const ct = contentType ?? "application/octet-stream";
      c.status(_status);
      c.header("Content-Type", ct);
      c.header("Content-Disposition", `attachment; filename="${filename}"`);
      applyHeaders();
      captureResponse(c.body(readable));
    },
    redirect(url, status = 302) {
      if (checkSent("redirect"))
        return;
      applyHeaders();
      captureResponse(c.redirect(url, status));
    },
    status(code) {
      _status = code;
      return res;
    },
    setHeader(name, value) {
      _headers[name] = value;
      return res;
    },
    get statusCode() {
      return _status;
    },
    _enableWrap() {
      _wrapEnabled = true;
    }
  };
  return res;
}
__name(createVextResponse, "createVextResponse");

// dist/lib/request-context.js
var import_node_async_hooks = require("node:async_hooks");
var GLOBAL_KEY = /* @__PURE__ */ Symbol.for("vextjs.requestContext");
function getOrCreateRequestContext() {
  const existing = globalThis[GLOBAL_KEY];
  if (existing instanceof import_node_async_hooks.AsyncLocalStorage) {
    return existing;
  }
  const instance = new import_node_async_hooks.AsyncLocalStorage();
  globalThis[GLOBAL_KEY] = instance;
  return instance;
}
__name(getOrCreateRequestContext, "getOrCreateRequestContext");
var requestContext = getOrCreateRequestContext();

// dist/lib/server-config.js
function createNodeServerOptions(config) {
  const options = {};
  if (config?.requestTimeout !== void 0) {
    options.requestTimeout = config.requestTimeout;
  }
  if (config?.headersTimeout !== void 0) {
    options.headersTimeout = config.headersTimeout;
  }
  if (config?.keepAliveTimeout !== void 0) {
    options.keepAliveTimeout = config.keepAliveTimeout;
  }
  if (config?.maxHeaderSize !== void 0) {
    options.maxHeaderSize = config.maxHeaderSize;
  }
  if (config?.connectionsCheckingInterval !== void 0) {
    options.connectionsCheckingInterval = config.connectionsCheckingInterval;
  }
  return options;
}
__name(createNodeServerOptions, "createNodeServerOptions");
function applyServerConfig(server, config) {
  if (!config) {
    return;
  }
  if (config.requestTimeout !== void 0) {
    server.requestTimeout = config.requestTimeout;
  }
  if (config.headersTimeout !== void 0) {
    server.headersTimeout = config.headersTimeout;
  }
  if (config.keepAliveTimeout !== void 0) {
    server.keepAliveTimeout = config.keepAliveTimeout;
  }
  if (config.socketTimeout !== void 0) {
    server.timeout = config.socketTimeout;
  }
  if (config.maxRequestsPerSocket !== void 0) {
    server.maxRequestsPerSocket = config.maxRequestsPerSocket;
  }
}
__name(applyServerConfig, "applyServerConfig");

// dist/adapters/hono/adapter.js
async function executeChain(chain, req, res) {
  const len = chain.length;
  if (len === 1) {
    await chain[0](req, res, _noop);
    return;
  }
  if (len === 2) {
    await chain[0](req, res, async () => {
      await chain[1](req, res, _noop);
    });
    return;
  }
  if (len === 3) {
    await chain[0](req, res, async () => {
      await chain[1](req, res, async () => {
        await chain[2](req, res, _noop);
      });
    });
    return;
  }
  if (len === 4) {
    await chain[0](req, res, async () => {
      await chain[1](req, res, async () => {
        await chain[2](req, res, async () => {
          await chain[3](req, res, _noop);
        });
      });
    });
    return;
  }
  async function dispatch(i) {
    if (i >= len)
      return;
    const middleware = chain[i];
    await middleware(req, res, () => dispatch(i + 1));
  }
  __name(dispatch, "dispatch");
  await dispatch(0);
}
__name(executeChain, "executeChain");
var _noop = /* @__PURE__ */ __name(async () => {
}, "_noop");
function createHonoAdapter(app) {
  const hono = new import_hono.Hono();
  const globalMiddlewares = [];
  let errorHandler = null;
  const _globalFrozen = false;
  const alsEnabled = app.config.requestContext?.enabled !== false;
  return {
    name: "hono",
    registerMiddleware(middleware) {
      globalMiddlewares.push(middleware);
    },
    registerRoute(method, path, chain, routeOptions = {}) {
      const upperMethod = method.toUpperCase();
      let prebuiltChain = null;
      hono.on(upperMethod, path, async (c) => {
        const req = createVextRequest(c, app);
        req._routeOptions = routeOptions;
        const routeBodyParser = resolveRouteBodyParserConfig(routeOptions);
        if (routeBodyParser) {
          req._routeBodyParser = routeBodyParser;
        }
        req.route = path;
        const box = createResponseBox();
        const res = createVextResponse(c, () => req.requestId, box);
        const runChain = /* @__PURE__ */ __name(async () => {
          try {
            if (prebuiltChain === null) {
              prebuiltChain = globalMiddlewares.concat(chain);
            }
            await executeChain(prebuiltChain, req, res);
          } catch (err) {
            if (errorHandler) {
              try {
                errorHandler(err, req, res);
              } catch (handlerError) {
                try {
                  res.rawJson({ code: 500, message: "Internal Server Error" }, 500);
                } catch {
                  throw handlerError;
                }
              }
            } else {
              throw err;
            }
          }
          return box.value ?? c.body(null);
        }, "runChain");
        if (alsEnabled) {
          return requestContext.run({ requestId: "", locale: void 0 }, runChain);
        } else {
          return runChain();
        }
      });
    },
    registerErrorHandler(handler) {
      errorHandler = handler;
    },
    registerNotFound(handler) {
      hono.notFound(async (c) => {
        const req = createVextRequest(c, app);
        const box = createResponseBox();
        if (!req.requestId) {
          const headerName = app.config.requestId?.header ?? "x-request-id";
          req.requestId = req.headers[headerName] || import_node_crypto.default.randomUUID();
        }
        const res = createVextResponse(c, () => req.requestId, box);
        const runNotFound = /* @__PURE__ */ __name(async () => {
          const noop = /* @__PURE__ */ __name(async () => {
          }, "noop");
          await handler(req, res, noop);
        }, "runNotFound");
        if (alsEnabled) {
          await requestContext.run({ requestId: req.requestId, locale: void 0 }, runNotFound);
        } else {
          await runNotFound();
        }
        return box.value ?? c.json({ code: 404, message: "Not Found" }, 404);
      });
    },
    async listen(port, host = "0.0.0.0", options) {
      const requestHandler = this.buildHandler();
      return new Promise((resolve, reject) => {
        const server = (0, import_node_http.createServer)(createNodeServerOptions(options?.server), requestHandler);
        applyServerConfig(server, options?.server);
        server.on("error", (err) => {
          reject(err);
        });
        server.listen(port, host, () => {
          const addr = server.address();
          const actualPort = typeof addr === "object" && addr !== null ? addr.port : port;
          const actualHost = typeof addr === "object" && addr !== null ? addr.address ?? host : host;
          resolve({
            port: actualPort,
            host: actualHost,
            close() {
              return new Promise((resolveClose, rejectClose) => {
                server.close((err) => {
                  if (err) {
                    rejectClose(err);
                  } else {
                    resolveClose();
                  }
                });
              });
            }
          });
        });
      });
    },
    buildHandler() {
      return (nodeReq, nodeRes) => {
        const protocol = "http";
        const host = nodeReq.headers.host ?? `localhost:${nodeReq.socket.address()?.port ?? 3e3}`;
        const url = `${protocol}://${host}${nodeReq.url ?? "/"}`;
        const method = (nodeReq.method ?? "GET").toUpperCase();
        const hasBody = method !== "GET" && method !== "HEAD";
        let body = null;
        if (hasBody) {
          body = new ReadableStream({
            start(controller) {
              nodeReq.on("data", (chunk) => {
                controller.enqueue(new Uint8Array(chunk));
              });
              nodeReq.on("end", () => {
                controller.close();
              });
              nodeReq.on("error", (err) => {
                controller.error(err);
              });
            }
          });
        }
        const headers = new Headers();
        const rawHeaders = nodeReq.rawHeaders;
        for (let i = 0; i < rawHeaders.length; i += 2) {
          const key = rawHeaders[i];
          const value = rawHeaders[i + 1];
          if (key && value) {
            headers.append(key, value);
          }
        }
        const requestInit = {
          method,
          headers
        };
        if (body) {
          requestInit.body = body;
          requestInit.duplex = "half";
        }
        const webRequest = new Request(url, requestInit);
        const env = { incoming: nodeReq, outgoing: nodeRes };
        const result = hono.fetch(webRequest, env);
        const responsePromise = result instanceof Promise ? result : Promise.resolve(result);
        responsePromise.then(async (webResponse) => {
          nodeRes.statusCode = webResponse.status;
          webResponse.headers.forEach((value, key) => {
            nodeRes.setHeader(key, value);
          });
          if (webResponse.body) {
            const reader = webResponse.body.getReader();
            try {
              while (true) {
                const { done, value } = await reader.read();
                if (done)
                  break;
                nodeRes.write(value);
              }
            } catch {
            } finally {
              nodeRes.end();
            }
          } else {
            nodeRes.end();
          }
        }).catch(() => {
          if (!nodeRes.headersSent) {
            nodeRes.statusCode = 500;
            nodeRes.setHeader("Content-Type", "application/json");
            nodeRes.end(JSON.stringify({
              code: 500,
              message: "Internal Server Error"
            }));
          }
        });
      };
    }
  };
}
__name(createHonoAdapter, "createHonoAdapter");

// dist/adapters/hono/index.js
function honoAdapter() {
  return (app) => createHonoAdapter(app);
}
__name(honoAdapter, "honoAdapter");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createHonoAdapter,
  honoAdapter
});
