conversation-share-mock-route.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { IncomingMessage, ServerResponse } from "node:http";
  2. import type { ApiClient } from "@zcode/shared";
  3. /** 复用已有分享契约 fake,发布、preview、continuation 全程留在隔离测试控制面。 */
  4. export async function createConversationShareMockRoute() {
  5. // 根因:首个预检请求才加载契约 fake,Windows 冷加载会超过 UI 等待预算。
  6. // 服务器监听前等待模块就绪;保留测试期 URL 装载,避免编入产品或越过 TS rootDir。
  7. const fixtureUrl = new URL(
  8. "../../../../services/test/helpers/conversationShareMockApiClient.ts",
  9. import.meta.url,
  10. );
  11. const { ConversationShareMockApiClient } = await import(fixtureUrl.href);
  12. let client: ApiClient | undefined;
  13. return async (request: IncomingMessage, response: ServerResponse): Promise<boolean> => {
  14. if (!request.url?.startsWith("/api/v1/shares")) return false;
  15. const origin = `http://${request.headers.host}`;
  16. client ??= new ConversationShareMockApiClient({
  17. shareBaseUrl: `${origin}/cn/share`,
  18. contentBlockVersions: { workflow: 2, "tool-presentation": 1 },
  19. });
  20. const chunks: Buffer[] = [];
  21. for await (const chunk of request) chunks.push(Buffer.from(chunk));
  22. const headers = Object.fromEntries(
  23. Object.entries(request.headers).flatMap(([name, value]) =>
  24. typeof value === "string" ? [[name, value]] : [],
  25. ),
  26. );
  27. const bytes = Buffer.concat(chunks);
  28. // HTTP 上传是二进制 multipart;转成 UTF-8 会丢失 FormData 类型并破坏文件摘要。
  29. // 用标准解析器还原服务契约 fake 接收的 FormData,JSON 请求仍保留原字符串。
  30. const body = request.headers["content-type"]?.startsWith("multipart/form-data")
  31. ? await new Response(bytes, { headers }).formData()
  32. : bytes.toString("utf8");
  33. const result = await client!.request(new URL(request.url, origin), {
  34. method: request.method,
  35. headers,
  36. ...(chunks.length ? { body } : {}),
  37. });
  38. response.writeHead(result.status, Object.fromEntries(result.headers));
  39. response.end(Buffer.from(await result.arrayBuffer()));
  40. return true;
  41. };
  42. }