|
| 1 | +import { afterEach, describe, expect, it } from "bun:test"; |
| 2 | +import { mkdtempSync, rmSync } from "node:fs"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import { createProxyClient } from "@/client"; |
| 6 | + |
| 7 | +type BunServer = ReturnType<typeof Bun.serve>; |
| 8 | + |
| 9 | +const activeServers: BunServer[] = []; |
| 10 | +const cleanupPaths: string[] = []; |
| 11 | + |
| 12 | +afterEach(() => { |
| 13 | + for (const server of activeServers.splice(0, activeServers.length)) { |
| 14 | + server.stop(true); |
| 15 | + } |
| 16 | + for (const path of cleanupPaths.splice(0, cleanupPaths.length)) { |
| 17 | + rmSync(path, { recursive: true, force: true }); |
| 18 | + } |
| 19 | +}); |
| 20 | + |
| 21 | +describe("proxy client", () => { |
| 22 | + it("routes HTTP proxy requests through configured base URL", async () => { |
| 23 | + let seenPath = ""; |
| 24 | + let seenAuthorization: string | null = null; |
| 25 | + |
| 26 | + const upstream = Bun.serve({ |
| 27 | + hostname: "127.0.0.1", |
| 28 | + port: 0, |
| 29 | + fetch: (request) => { |
| 30 | + const url = new URL(request.url); |
| 31 | + seenPath = `${url.pathname}${url.search}`; |
| 32 | + seenAuthorization = request.headers.get("authorization"); |
| 33 | + return Response.json({ ok: true }); |
| 34 | + }, |
| 35 | + }); |
| 36 | + activeServers.push(upstream); |
| 37 | + |
| 38 | + const client = createProxyClient("prod", { |
| 39 | + address: `http://127.0.0.1:${upstream.port}`, |
| 40 | + }); |
| 41 | + |
| 42 | + const response = await client.fetch("/v1/me?x=1", { method: "GET" }); |
| 43 | + expect(response.ok).toBe(true); |
| 44 | + expect(seenPath).toBe("/v1/me?x=1"); |
| 45 | + expect(seenAuthorization).toBeNull(); |
| 46 | + }); |
| 47 | + |
| 48 | + it("routes unix socket proxy requests with unix fetch option", async () => { |
| 49 | + let seenPath = ""; |
| 50 | + const dir = mkdtempSync(join(tmpdir(), "bee-cli-proxy-client-")); |
| 51 | + cleanupPaths.push(dir); |
| 52 | + const socketPath = join(dir, "proxy.sock"); |
| 53 | + |
| 54 | + const upstream = Bun.serve({ |
| 55 | + unix: socketPath, |
| 56 | + fetch: (request) => { |
| 57 | + const url = new URL(request.url); |
| 58 | + seenPath = url.pathname; |
| 59 | + return Response.json({ ok: true }); |
| 60 | + }, |
| 61 | + }); |
| 62 | + activeServers.push(upstream); |
| 63 | + |
| 64 | + const client = createProxyClient("prod", { address: socketPath }); |
| 65 | + const response = await client.fetch("/v1/me", { method: "GET" }); |
| 66 | + |
| 67 | + expect(response.ok).toBe(true); |
| 68 | + expect(seenPath).toBe("/v1/me"); |
| 69 | + expect(client.isProxy).toBe(true); |
| 70 | + }); |
| 71 | +}); |
0 commit comments