bot-platform-fixture.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import {
  2. createRecordingFeishuFetch,
  3. type RecordedRequest,
  4. } from "../bots/helpers/bots-service-harness.js";
  5. /** 只替代平台边界,任务、协议、工具与 Host 不做 stub。 */
  6. export function installBotPlatformFixture() {
  7. const original = globalThis.fetch;
  8. const requests: RecordedRequest[] = [];
  9. const messages: Array<Record<string, unknown>> = [];
  10. const record = createRecordingFeishuFetch(requests);
  11. globalThis.fetch = async (input, init) => {
  12. const url = String(input);
  13. const method = init?.method ?? "GET";
  14. if (!url.startsWith("https://open.feishu.cn/"))
  15. throw new Error(`Unexpected platform request: ${url}`);
  16. const special = (payload: unknown) => {
  17. requests.push({ url, method });
  18. return Response.json({ code: 0, data: payload });
  19. };
  20. if (url.endsWith("/bot/v3/info"))
  21. return Response.json({ code: 0, bot: { open_id: "ou_current_bot" } });
  22. if (url.includes("/im/v1/chats/")) return special({ name: "Isolated topic group" });
  23. if (method === "GET" && url.includes("/im/v1/messages?"))
  24. return special({ items: [...messages].reverse(), has_more: false });
  25. if (url.includes("/resources/")) {
  26. requests.push({ url, method });
  27. return new Response("E2E_ARCHIVE_FILE_CONTENT", {
  28. headers: { "content-type": "text/plain" },
  29. });
  30. }
  31. if (method === "GET" && /\/im\/v1\/messages\/[^/?]+$/.test(url)) {
  32. return special({ items: messages.filter((m) => url.endsWith(`/${m.message_id}`)) });
  33. }
  34. return record(input, init);
  35. };
  36. return {
  37. requests,
  38. add(id: string, text: string, kind = "text") {
  39. messages.push({
  40. message_id: id,
  41. chat_id: "oc_worker",
  42. thread_id: "omt_worker",
  43. msg_type: kind,
  44. sender: { id: "ou_e2e_user", sender_type: "user" },
  45. create_time: String(messages.length + 1),
  46. body: {
  47. content: JSON.stringify(
  48. kind === "file" ? { file_key: "file_e2e", file_name: "archive.txt" } : { text },
  49. ),
  50. },
  51. });
  52. },
  53. restore() {
  54. globalThis.fetch = original;
  55. },
  56. };
  57. }