mock-server.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import type { Page, Route } from "@playwright/test"
  2. const emptyList = new Set([
  3. "/skill",
  4. "/command",
  5. "/lsp",
  6. "/formatter",
  7. "/permission",
  8. "/question",
  9. "/vcs/status",
  10. "/vcs/diff",
  11. ])
  12. const emptyObject = new Set(["/global/config", "/config", "/provider/auth", "/mcp", "/session/status"])
  13. export interface MockServerConfig {
  14. provider: unknown
  15. directory: string
  16. project: unknown
  17. sessions: ({ id: string } & Record<string, unknown>)[]
  18. pageMessages: (sessionId: string, limit: number, before?: string) => { items: unknown[]; cursor?: string }
  19. vcsDiff?: unknown[]
  20. messageDelay?: number
  21. onMessages?: (input: { sessionID: string; before?: string; phase: "start" | "end" }) => void
  22. events?: () => unknown[]
  23. eventRetry?: number
  24. }
  25. export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
  26. const cursors = new Map<string, string>()
  27. let nextCursor = 0
  28. const staticRoutes: Record<string, unknown> = {
  29. "/provider": config.provider,
  30. "/path": {
  31. state: config.directory,
  32. config: config.directory,
  33. worktree: config.directory,
  34. directory: config.directory,
  35. home: "C:/OpenCode",
  36. },
  37. "/project": [config.project],
  38. "/project/current": config.project,
  39. "/agent": [{ name: "build", mode: "primary" }],
  40. "/vcs": { branch: "main", default_branch: "main" },
  41. "/session": config.sessions,
  42. }
  43. await page.route("**/*", async (route) => {
  44. const url = new URL(route.request().url())
  45. const targetPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
  46. const appPort = new URL(
  47. process.env.PLAYWRIGHT_BASE_URL ?? `http://127.0.0.1:${process.env.PLAYWRIGHT_PORT ?? "3000"}`,
  48. ).port
  49. if (url.port !== targetPort && url.port !== appPort) return route.fallback()
  50. const path = url.pathname
  51. if (path === "/global/event" || path === "/event") return sse(route, config.events?.(), config.eventRetry)
  52. if (path === "/global/health") return json(route, { healthy: true })
  53. if (path === "/vcs/diff" && config.vcsDiff) return json(route, config.vcsDiff)
  54. if (emptyObject.has(path)) return json(route, {})
  55. if (emptyList.has(path)) return json(route, [])
  56. if (path in staticRoutes) return json(route, staticRoutes[path])
  57. const sessionMatch = path.match(/^\/session\/([^/]+)$/)
  58. if (sessionMatch) {
  59. const session = config.sessions.find((s) => s.id === sessionMatch[1])
  60. return json(route, session ?? {})
  61. }
  62. if (/^\/session\/[^/]+\/(children|todo|diff)$/.test(path)) return json(route, [])
  63. const messagesMatch = path.match(/^\/session\/([^/]+)\/message$/)
  64. if (messagesMatch) {
  65. const token = url.searchParams.get("before") ?? undefined
  66. const before = token ? cursors.get(token) : undefined
  67. if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
  68. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "start" })
  69. if (config.messageDelay) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
  70. const limit = Number(url.searchParams.get("limit") ?? 80)
  71. const pageData = config.pageMessages(messagesMatch[1], limit, before)
  72. config.onMessages?.({ sessionID: messagesMatch[1], before, phase: "end" })
  73. if (!pageData.cursor) return json(route, pageData.items)
  74. const cursor = `cursor_${++nextCursor}`
  75. cursors.set(cursor, pageData.cursor)
  76. return json(route, pageData.items, { "x-next-cursor": cursor })
  77. }
  78. if (url.port === targetPort && targetPort !== appPort) return json(route, {})
  79. return route.fallback()
  80. })
  81. }
  82. function json(route: Route, body: unknown, headers?: Record<string, string>, status = 200) {
  83. return route.fulfill({
  84. status,
  85. contentType: "application/json",
  86. headers: {
  87. "access-control-allow-origin": "*",
  88. "access-control-expose-headers": "x-next-cursor",
  89. ...headers,
  90. },
  91. body: JSON.stringify(body ?? null),
  92. })
  93. }
  94. function sse(route: Route, events?: unknown[], retry?: number) {
  95. return route.fulfill({
  96. status: 200,
  97. contentType: "text/event-stream",
  98. body: `${retry === undefined ? "" : `retry: ${retry}\n\n`}${events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n"}`,
  99. })
  100. }