import { describe, expect, it } from "vitest"; import { invalidIdResponse, jsonErrorWithCors, jsonWithCors, parseAppId } from "@/lib/api-route"; function contextWith(id: string) { return { params: Promise.resolve({ id }) }; } describe("parseAppId", () => { it("accepts numeric ids", async () => { await expect(parseAppId(contextWith("12345"))).resolves.toBe("12345"); }); it("rejects non-numeric ids", async () => { await expect(parseAppId(contextWith("abc"))).resolves.toBeNull(); await expect(parseAppId(contextWith(""))).resolves.toBeNull(); }); }); describe("invalidIdResponse", () => { it("returns a 400 JSON response", async () => { const response = invalidIdResponse(); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "Invalid application id" }); }); }); describe("jsonErrorWithCors", () => { it("sets status, cache, and CORS headers", async () => { const response = jsonErrorWithCors({ error: "Nope" }, 404); expect(response.status).toBe(404); expect(response.headers.get("Cache-Control")).toContain("s-maxage=60"); expect(response.headers.get("Access-Control-Allow-Origin")).toBe("https://fristy.dev"); await expect(response.json()).resolves.toEqual({ error: "Nope" }); }); }); describe("jsonWithCors", () => { it("sets cache and CORS headers", async () => { const response = jsonWithCors({ ok: true }, 3600); expect(response.headers.get("Cache-Control")).toContain("s-maxage=3600"); expect(response.headers.get("Access-Control-Allow-Origin")).toBe("https://fristy.dev"); await expect(response.json()).resolves.toEqual({ ok: true }); }); it("echoes a validated dev origin instead of the production URL", async () => { const response = jsonWithCors({ ok: true }, 3600, "http://localhost:3000"); expect(response.headers.get("Access-Control-Allow-Origin")).toBe("http://localhost:3000"); }); it("falls back to production for untrusted origins", async () => { const response = jsonWithCors({ ok: true }, 3600, "https://evil.example"); expect(response.headers.get("Access-Control-Allow-Origin")).toBe("https://fristy.dev"); }); });