/* 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/native/index.js
var index_exports = {};
__export(index_exports, {
  createNativeAdapter: () => createNativeAdapter,
  nativeAdapter: () => nativeAdapter
});
module.exports = __toCommonJS(index_exports);

// dist/adapters/native/adapter.js
var import_node_http = require("node:http");
var import_node_crypto = __toESM(require("node:crypto"), 1);
var import_route_core = require("route-core");

// 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/native/request.js
function createVextRequest(incoming, app, params, parsedUrl) {
  const trustProxy = app.config.trustProxy ?? false;
  let closeHandlers = null;
  const { rawUrl, path: urlPath, queryString: rawQueryString } = parsedUrl;
  let _queryCache;
  let _rawBufferPromise;
  let _rawStringPromise;
  function getRawBodyBuffer(maxBytes) {
    if (_rawBufferPromise !== void 0) {
      return _rawBufferPromise.then((buf) => {
        assertBodySize(buf.byteLength, maxBytes);
        return buf;
      });
    }
    _rawBufferPromise = new Promise((resolve, reject) => {
      const method = incoming.method?.toUpperCase();
      if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
        resolve(Buffer.alloc(0));
        return;
      }
      const chunks = [];
      let total = 0;
      let settled = false;
      incoming.on("data", (chunk) => {
        if (settled)
          return;
        const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
        total += bufferChunk.byteLength;
        if (maxBytes !== void 0 && total > maxBytes) {
          settled = true;
          reject(createPayloadTooLargeError(maxBytes));
          return;
        }
        chunks.push(bufferChunk);
      });
      incoming.on("end", () => {
        if (settled)
          return;
        settled = true;
        const buffer = chunks.length > 0 ? Buffer.concat(chunks) : Buffer.alloc(0);
        assertBodySize(buffer.byteLength, maxBytes);
        resolve(buffer);
      });
      incoming.on("error", (err) => {
        if (settled)
          return;
        settled = true;
        reject(err);
      });
    });
    return _rawBufferPromise.then((buf) => {
      assertBodySize(buf.byteLength, maxBytes);
      return buf;
    });
  }
  __name(getRawBodyBuffer, "getRawBodyBuffer");
  function getRawBody(maxBytes) {
    if (_rawStringPromise !== void 0) {
      return _rawStringPromise.then((raw) => {
        assertBodySize(Buffer.byteLength(raw, "utf-8"), maxBytes);
        return raw;
      });
    }
    _rawStringPromise = getRawBodyBuffer(maxBytes).then((buf) => buf.toString("utf-8"));
    return _rawStringPromise;
  }
  __name(getRawBody, "getRawBody");
  let ip;
  if (trustProxy) {
    const xff = incoming.headers["x-forwarded-for"];
    if (typeof xff === "string") {
      const firstIp = xff.split(",")[0];
      ip = firstIp ? firstIp.trim() : incoming.socket.remoteAddress ?? "127.0.0.1";
    } else if (Array.isArray(xff) && xff.length > 0) {
      const firstEntry = xff[0];
      const firstIp = firstEntry ? firstEntry.split(",")[0] : void 0;
      ip = firstIp ? firstIp.trim() : incoming.socket.remoteAddress ?? "127.0.0.1";
    } else {
      ip = incoming.socket.remoteAddress ?? "127.0.0.1";
    }
  } else {
    ip = incoming.socket.remoteAddress ?? "127.0.0.1";
  }
  let protocol;
  if (trustProxy) {
    const proto = incoming.headers["x-forwarded-proto"];
    protocol = proto === "https" ? "https" : "http";
  } else {
    const encrypted = incoming.socket?.encrypted;
    protocol = encrypted ? "https" : "http";
  }
  const req = {
    // ── 原始数据 ────────────────────────────────────────
    // P1 优化：query 使用对象字面量 getter（替代 Object.defineProperty）
    get query() {
      if (_queryCache !== void 0)
        return _queryCache;
      if (!rawQueryString) {
        _queryCache = {};
        return _queryCache;
      }
      const searchParams = new URLSearchParams(rawQueryString);
      const result = {};
      for (const [key, value] of searchParams) {
        result[key] = value;
      }
      _queryCache = result;
      return _queryCache;
    },
    body: void 0,
    // body-parser 中间件负责填充
    params,
    headers: incoming.headers,
    method: (incoming.method ?? "GET").toUpperCase(),
    url: rawUrl,
    path: urlPath,
    route: "",
    // F-01: 由 registerRoute handler 在路由匹配后覆写为真实路由模板
    // ── 元信息 ──────────────────────────────────────────
    app,
    requestId: "",
    // requestId 中间件负责填充
    ip,
    protocol,
    // ── 生命周期 ────────────────────────────────────────
    // P4 优化：懒初始化 closeHandlers + 懒注册 'close' 事件监听
    onClose(handler) {
      if (closeHandlers === null) {
        closeHandlers = [];
        incoming.on("close", () => {
          if (closeHandlers) {
            for (const h of closeHandlers) {
              try {
                h();
              } catch {
              }
            }
            closeHandlers = null;
          }
        });
      }
      closeHandlers.push(handler);
    },
    // ── 校验数据 ────────────────────────────────────────
    //
    // validate 中间件将校验后的数据存储在 req._validated_<location> 上。
    // valid() 方法从对应的 key 中读取数据返回。
    //
    valid(location) {
      return req[`_validated_${location}`];
    },
    // ── 内部方法（body-parser 中间件使用）───────────────────
    //
    // 从 IncomingMessage 数据流读取原始 body 并转为 string/Buffer，
    // 供 body-parser 中间件解析。
    //
    _getRawBody: getRawBody,
    _getRawBodyBuffer: getRawBodyBuffer
  };
  return req;
}
__name(createVextRequest, "createVextRequest");

// dist/adapters/native/response.js
var _isProduction = process.env.NODE_ENV === "production";
var NativeVextResponse = class {
  static {
    __name(this, "NativeVextResponse");
  }
  /** Node.js 原始 ServerResponse */
  _serverResponse;
  /** 延迟获取 requestId 的来源；Native adapter 传入 request 对象，避免每请求 getter 闭包 */
  _requestIdSource;
  /** 当前 HTTP 状态码（默认 200，可通过 status() 修改） */
  _status = 200;
  /** 响应头缓冲区（通过 setHeader() 累积，在发送时一次性设置） */
  _headers = {};
  /** 出口包装开关（由 response-wrapper 中间件通过 _enableWrap() 开启） */
  _wrapEnabled = false;
  /** 重复发送保护标志（防止 handler 中多次调用 json/rawJson/text） */
  _sent = false;
  /** 发送前拦截钩子（缓存中间件在 MISS 时注册） @internal */
  _onSend;
  constructor(serverResponse, requestIdSource) {
    this._serverResponse = serverResponse;
    this._requestIdSource = requestIdSource;
  }
  // ── 内部辅助方法（原型上共享）──────────────────────────
  /**
   * 延迟读取 requestId。
   *
   * Native adapter 热路径传入 VextRequest 对象，避免每请求创建 `() => req.requestId`
   * 闭包；保留函数来源兼容内部测试或未来调用方。
   */
  _resolveRequestId() {
    const source = this._requestIdSource;
    return typeof source === "function" ? source() : source.requestId;
  }
  /**
   * 将累积的响应头设置到 ServerResponse 上
   *
   * 在每个发送方法中调用，将通过 setHeader() 累积的头信息
   * 一次性设置到 serverResponse 对象上。
   *
   * 使用原生 serverResponse.setHeader() 而非 writeHead()，
   * 因为 writeHead() 会立即发送 header，而 setHeader() 允许后续修改。
   * 最终的 statusCode 和 header 在 end() 调用时统一发送。
   */
  _applyHeaders() {
    const headers = this._headers;
    const sr = this._serverResponse;
    for (const key in headers) {
      sr.setHeader(key, headers[key]);
    }
  }
  /**
   * 检查是否已发送响应（重复发送保护）
   *
   * 第一次调用返回 false 并设置 _sent = true。
   * 后续调用返回 true（表示已发送，调用方应终止当前方法）。
   * dev 模式下打印警告，帮助开发者发现 handler 中的重复发送 bug。
   *
   * @param methodName 调用的方法名（用于警告消息）
   * @returns true 表示已发送（应终止当前方法），false 表示可以发送
   */
  _checkSent(methodName) {
    if (this._sent) {
      if (!_isProduction) {
        console.warn(`[vextjs] ⚠️ res.${methodName}() called after response already sent. This is a no-op. Check your handler for duplicate sends.`);
      }
      return true;
    }
    this._sent = true;
    return false;
  }
  /**
   * 发送 JSON 字符串响应（内部共用方法）
   *
   * 所有 JSON 发送路径（json / rawJson）最终都走此方法，
   * 减少代码重复，确保 statusCode / header / end 调用路径统一。
   *
   * @param body   已序列化的 JSON 字符串
   * @param status HTTP 状态码
   */
  _sendJsonString(body, status) {
    const sr = this._serverResponse;
    sr.statusCode = status;
    sr.setHeader("Content-Type", "application/json; charset=utf-8");
    sr.setHeader("Content-Length", Buffer.byteLength(body));
    this._applyHeaders();
    sr.end(body);
  }
  /**
   * 发送 204 No Content（无消息体）
   *
   * RFC 9110 §15.3.5 要求 204 不能有消息体。
   * 移除 Content-Type 避免混淆。
   */
  _send204() {
    const sr = this._serverResponse;
    sr.statusCode = 204;
    sr.removeHeader("Content-Type");
    this._applyHeaders();
    sr.end();
  }
  // ── VextResponse 接口实现（原型方法，所有实例共享）──────
  /**
   * 返回 JSON 响应
   *
   * 当出口包装开启时（response-wrapper 中间件已执行 _enableWrap()），
   * 自动包装为：{ code: 0, data, requestId }
   * 当包装未开启时，直接发送原始 data。
   *
   * 204 特殊处理：无论包装是否开启，204 均不发送消息体（RFC 9110 §15.3.5）。
   *
   * Native 特殊处理：
   *   直接调用 serverResponse.end(JSON.stringify(...))，
   *   没有任何框架中间层（Fastify 有 reply.send、Express 有 res.json、
   *   Koa 有 ctx.body 赋值），这是 Native Adapter 性能优势的关键来源。
   */
  json(data, status) {
    if (this._checkSent("json"))
      return;
    const finalStatus = status ?? this._status;
    this._status = finalStatus;
    if (this._onSend) {
      this._onSend(data, finalStatus, { ...this._headers });
    }
    if (this._wrapEnabled) {
      if (finalStatus === 204) {
        this._send204();
        return;
      }
      this._sendJsonString(JSON.stringify({
        code: 0,
        data,
        requestId: this._resolveRequestId()
      }), finalStatus);
      return;
    }
    if (finalStatus === 204) {
      this._send204();
      return;
    }
    this._sendJsonString(JSON.stringify(data), finalStatus);
  }
  /**
   * 返回原始 JSON（不经过出口包装）
   *
   * 仅框架内部错误处理使用，用户代码不应直接调用。
   * 通过 VextPublicResponse 类型从用户可见接口中排除。
   *
   * @internal
   */
  rawJson(data, status) {
    if (this._checkSent("rawJson"))
      return;
    const finalStatus = status ?? this._status;
    this._status = finalStatus;
    this._sendJsonString(JSON.stringify(data), finalStatus);
  }
  /**
   * 返回纯文本响应（不经过出口包装）
   */
  text(content, status) {
    if (this._checkSent("text"))
      return;
    const finalStatus = status ?? this._status;
    this._status = finalStatus;
    const sr = this._serverResponse;
    sr.statusCode = finalStatus;
    sr.setHeader("Content-Type", "text/plain; charset=utf-8");
    this._applyHeaders();
    sr.setHeader("Content-Length", Buffer.byteLength(content));
    sr.end(content);
  }
  /**
   * 流式响应（大文件传输、实时数据流）
   *
   * 直接将 ReadableStream pipe 到 ServerResponse。
   * Node.js 原生 pipe 机制，零框架开销。
   */
  stream(readable, contentType = "application/octet-stream") {
    if (this._checkSent("stream"))
      return;
    const sr = this._serverResponse;
    sr.statusCode = this._status;
    sr.setHeader("Content-Type", contentType);
    this._applyHeaders();
    readable.pipe(sr);
  }
  /**
   * 文件下载（触发浏览器下载行为）
   *
   * 自动设置 Content-Disposition: attachment 头，
   * 触发浏览器的文件下载对话框。
   */
  download(readable, filename, contentType) {
    if (this._checkSent("download"))
      return;
    const ct = contentType ?? "application/octet-stream";
    const sr = this._serverResponse;
    sr.statusCode = this._status;
    sr.setHeader("Content-Type", ct);
    sr.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
    this._applyHeaders();
    readable.pipe(sr);
  }
  /**
   * 重定向
   *
   * 直接设置 Location 响应头和状态码，然后 end()。
   * 不依赖任何框架的 redirect 方法。
   */
  redirect(url, status = 302) {
    if (this._checkSent("redirect"))
      return;
    const sr = this._serverResponse;
    sr.statusCode = status;
    sr.setHeader("Location", url);
    this._applyHeaders();
    sr.end();
  }
  /**
   * 设置 HTTP 状态码（链式调用）
   */
  status(code) {
    this._status = code;
    return this;
  }
  /**
   * 设置响应头（链式调用）
   */
  setHeader(name, value) {
    this._headers[name] = value;
    return this;
  }
  /**
   * 当前 HTTP 状态码（只读）
   *
   * 返回通过 .status() 设置的值，或 json/rawJson/text 等方法
   * 传入的 status 参数所确定的最终状态码。默认 200。
   *
   * 主要用途：洋葱模型 after-middleware 在 `await next()` 后
   * 读取响应状态码（如 access-log 中间件记录请求耗时与状态码）。
   */
  get statusCode() {
    return this._status;
  }
  /**
   * 开启出口包装标志（内部方法）
   *
   * 仅由 response-wrapper 中间件调用，用户代码不应直接调用。
   * 调用后 json() 将自动包装响应为 { code: 0, data, requestId }。
   *
   * @internal
   */
  _enableWrap() {
    this._wrapEnabled = true;
  }
};
function createVextResponse(serverResponse, requestIdSource) {
  return new NativeVextResponse(serverResponse, requestIdSource);
}
__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/native/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 createNativeAdapter(options, app) {
  const router = (0, import_route_core.createRouter)({
    ignoreTrailingSlash: options.ignoreTrailingSlash ?? true,
    caseSensitive: options.caseSensitive ?? false,
    maxParamLength: options.maxParamLength ?? 500
  });
  const routeStores = [];
  const preparedMethods = /* @__PURE__ */ new Map();
  const alsEnabled = app.config.requestContext?.enabled !== false;
  const globalMiddlewares = [];
  let errorHandler = null;
  let notFoundHandler = null;
  async function runMatchedChain(chain, req, res, nodeRes) {
    try {
      await executeChain(chain, req, res);
    } catch (err) {
      if (errorHandler) {
        try {
          errorHandler(err, req, res);
        } catch (_handlerError) {
          sendFallbackError(nodeRes);
        }
      } else {
        sendFallbackError(nodeRes);
      }
    }
  }
  __name(runMatchedChain, "runMatchedChain");
  function onRouteMatch(nodeReq, nodeRes, params, routePath, store, parsedUrl) {
    const routeParams = params ?? {};
    const req = createVextRequest(nodeReq, app, routeParams, parsedUrl);
    req._routeOptions = store.routeOptions;
    const routeBodyParser = store.routeBodyParser;
    if (routeBodyParser) {
      req._routeBodyParser = routeBodyParser;
    }
    req.route = routePath || store.routePath;
    const res = createVextResponse(nodeRes, req);
    if (store.chain === null) {
      store.chain = globalMiddlewares.concat(store.routeChain);
    }
    const chain = store.chain;
    if (alsEnabled) {
      requestContext.run({ requestId: "", locale: void 0 }, () => {
        void runMatchedChain(chain, req, res, nodeRes);
      });
    } else {
      void runMatchedChain(chain, req, res, nodeRes);
    }
  }
  __name(onRouteMatch, "onRouteMatch");
  function handleRequest(nodeReq, nodeRes) {
    const url = nodeReq.url ?? "/";
    const qIdx = url.indexOf("?");
    const pathname = qIdx === -1 ? url : url.slice(0, qIdx);
    const queryString = qIdx === -1 ? "" : url.slice(qIdx + 1);
    const parsedUrl = { rawUrl: url, path: pathname, queryString };
    const preparedPathname = router.preparePathname(pathname);
    if (!preparedPathname) {
      handleNotFound(nodeReq, nodeRes, parsedUrl);
      return;
    }
    const methodHandle = getPreparedMethod(nodeReq.method ?? "GET");
    const matched = methodHandle.lookup(preparedPathname, (storeId, params, routePath) => {
      const store = routeStores[storeId];
      if (!store) {
        return;
      }
      onRouteMatch(nodeReq, nodeRes, params, routePath, store, parsedUrl);
    });
    if (!matched) {
      handleNotFound(nodeReq, nodeRes, parsedUrl);
    }
  }
  __name(handleRequest, "handleRequest");
  function normalizeRouteMethod(method) {
    const normalized = method.toUpperCase();
    return normalized === "ALL" ? "ANY" : normalized;
  }
  __name(normalizeRouteMethod, "normalizeRouteMethod");
  function getPreparedMethod(method) {
    const normalized = normalizeRouteMethod(method);
    let methodHandle = preparedMethods.get(normalized);
    if (!methodHandle) {
      methodHandle = router.prepareMethod(normalized);
      preparedMethods.set(normalized, methodHandle);
    }
    return methodHandle;
  }
  __name(getPreparedMethod, "getPreparedMethod");
  function handleNotFound(nodeReq, nodeRes, parsedUrl) {
    if (!notFoundHandler) {
      nodeRes.statusCode = 404;
      nodeRes.setHeader("Content-Type", "application/json; charset=utf-8");
      const body = JSON.stringify({ code: 404, message: "Not Found" });
      nodeRes.setHeader("Content-Length", Buffer.byteLength(body));
      nodeRes.end(body);
      return;
    }
    const requestUrl = parsedUrl ?? parseUrl(nodeReq.url ?? "/");
    const req = createVextRequest(nodeReq, app, {}, requestUrl);
    const res = createVextResponse(nodeRes, req);
    if (!req.requestId) {
      const headerName = app.config.requestId?.header ?? "x-request-id";
      req.requestId = req.headers[headerName] || import_node_crypto.default.randomUUID();
    }
    const runNotFound = /* @__PURE__ */ __name(async () => {
      const noop = /* @__PURE__ */ __name(async () => {
      }, "noop");
      try {
        await notFoundHandler(req, res, noop);
      } catch {
        sendFallbackError(nodeRes);
      }
    }, "runNotFound");
    if (alsEnabled) {
      requestContext.run({ requestId: req.requestId, locale: void 0 }, runNotFound);
    } else {
      runNotFound();
    }
  }
  __name(handleNotFound, "handleNotFound");
  function parseUrl(url) {
    const qIdx = url.indexOf("?");
    return {
      rawUrl: url,
      path: qIdx === -1 ? url : url.slice(0, qIdx),
      queryString: qIdx === -1 ? "" : url.slice(qIdx + 1)
    };
  }
  __name(parseUrl, "parseUrl");
  function sendFallbackError(nodeRes) {
    if (!nodeRes.headersSent) {
      try {
        nodeRes.statusCode = 500;
        nodeRes.setHeader("Content-Type", "application/json; charset=utf-8");
        const body = JSON.stringify({
          code: 500,
          message: "Internal Server Error"
        });
        nodeRes.setHeader("Content-Length", Buffer.byteLength(body));
        nodeRes.end(body);
      } catch {
      }
    }
  }
  __name(sendFallbackError, "sendFallbackError");
  return {
    name: "native",
    // ── registerMiddleware ───────────────────────────────────
    //
    // 收集全局中间件。bootstrap 步骤⑥中注册的内置中间件
    // （requestId / cors / body-parser / rate-limit / response-wrapper / access-log）
    // 和插件通过 app.use() 注册的中间件都通过此方法收集。
    //
    // 执行时机：在每个路由的 handler 中，全局中间件拼接在路由级中间件之前执行。
    //
    registerMiddleware(middleware) {
      globalMiddlewares.push(middleware);
    },
    // ── registerRoute ───────────────────────────────────────
    //
    // 为每条路由注册到 route-core 路由器。
    //
    // 流程：
    //   1. 将 vext 路径注册进 route-core，并得到 numeric storeId
    //   2. 将路由级中间件链存储在 Native adapter 的 routeStores 中
    //   3. 预组装中间件链在首次请求时完成（延迟到 globalMiddlewares 收集完毕后）
    //
    // route-core 的 storeId 模型：
    //   router.add(method, path, storeId) 只保存数字 ID；
    //   lookup 命中后由 adapter 通过 routeStores[storeId] 找回 route metadata。
    //
    registerRoute(method, path, chain, routeOptions = {}) {
      const routeMethod = normalizeRouteMethod(method);
      const routePath = path;
      const routeBodyParser = resolveRouteBodyParserConfig(routeOptions);
      const store = {
        chain: null,
        // 延迟组装
        routeChain: chain,
        routePath,
        // F-01：路由模板，供 onRouteMatch 赋值到 req.route
        routeBodyParser,
        routeOptions
      };
      const storeId = routeStores.length;
      routeStores.push(store);
      try {
        router.add(routeMethod, routePath, storeId);
      } catch (err) {
        routeStores.pop();
        const message = err instanceof Error ? err.message : String(err);
        throw new Error(`[vextjs] Failed to register route: ${routeMethod} ${routePath}
         ${message}`);
      }
    },
    // ── registerErrorHandler ────────────────────────────────
    //
    // 注册全局错误处理函数。
    //
    // 中间件链执行过程中抛出的所有错误都由此函数处理。
    // 与 Fastify Adapter 不同，Native Adapter 没有框架层面的错误处理，
    // 完全由 handleRequest 内的 try-catch 捕获并转发到 errorHandler。
    //
    registerErrorHandler(handler) {
      errorHandler = handler;
    },
    // ── registerNotFound ────────────────────────────────────
    //
    // 注册 404 兜底处理函数。
    //
    // 当 route-core lookup 未命中时，由 handleRequest 调用此处理函数。
    //
    registerNotFound(handler) {
      notFoundHandler = handler;
    },
    // ── listen ──────────────────────────────────────────────
    //
    // 启动 HTTP 服务器。
    //
    // 流程：
    //   1. 创建 Node.js http.createServer（传入 handleRequest 作为 requestListener）
    //   2. 调用 server.listen() 开始监听端口
    //   3. 返回 VextServerHandle（含 close / port / host）
    //
    // 与 Fastify Adapter 的差异：
    //   - Fastify: 调用 fastify.listen() → 内部创建 http.createServer
    //   - Native: 直接调用 http.createServer()，无框架中间层
    //
    async listen(port, host = "0.0.0.0", options2) {
      const server = (0, import_node_http.createServer)(createNodeServerOptions(options2?.server), handleRequest);
      applyServerConfig(server, options2?.server);
      return new Promise((resolve, reject) => {
        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 ────────────────────────────────────────
    //
    // 构建完整的请求处理函数（不启动 server）。
    //
    // 返回的 handler 接受原始 Node.js req/res，内部完成：
    //   - 路由匹配（route-core prepared lookup）
    //   - 请求/响应对象转换（IncomingMessage → VextRequest / ServerResponse → VextResponse）
    //   - 中间件链执行（executeChain）
    //   - 错误处理 + 404 兜底
    //
    // 用途：dev 模式下 Hot Reload 每次创建 fresh adapter 后调用
    // buildHandler() 获取新 handler，由 HotSwappableHandler 原子替换。
    //
    // 与 Fastify Adapter 的差异：
    //   - Fastify: 返回 fastify.routing（需要先 fastify.ready()）
    //   - Native: 直接返回 handleRequest 函数，无需 ready 阶段
    //
    buildHandler() {
      return handleRequest;
    }
  };
}
__name(createNativeAdapter, "createNativeAdapter");

// dist/adapters/native/index.js
function nativeAdapter(options) {
  const opts = options ?? {};
  return (app) => {
    return createNativeAdapter(opts, app);
  };
}
__name(nativeAdapter, "nativeAdapter");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createNativeAdapter,
  nativeAdapter
});
