import type { IncomingMessage, ServerResponse } from 'node:http' /** 读取 Node HTTP 请求体(供 dev API 中间件转为 Fetch Request) */ export async function readIncomingBody(req: IncomingMessage): Promise { const chunks: Buffer[] = [] for await (const chunk of req) { chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk) } return Buffer.concat(chunks) } /** 将 Node IncomingMessage 转为 Web Fetch Request(含 POST/PUT body 与 headers) */ export async function toFetchRequest(req: IncomingMessage, path: string): Promise { const host = req.headers.host ?? '127.0.0.1' const method = req.method ?? 'GET' const headers = new Headers() for (const [key, value] of Object.entries(req.headers)) { if (value == null) continue if (Array.isArray(value)) { for (const v of value) headers.append(key, v) } else { headers.set(key, value) } } const hasBody = method !== 'GET' && method !== 'HEAD' const rawBody = hasBody ? await readIncomingBody(req) : Buffer.alloc(0) return new Request(`http://${host}${path}`, { method, headers, body: hasBody && rawBody.length > 0 ? new Uint8Array(rawBody) : undefined, }) } /** 将 Fetch Response 写回 Node ServerResponse */ export async function writeFetchResponse( res: ServerResponse, response: Response ): Promise { res.statusCode = response.status response.headers.forEach((value, key) => { if (key === 'transfer-encoding') return res.setHeader(key, value) }) const body = Buffer.from(await response.arrayBuffer()) res.end(body) }