hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | /** |
| 2 | * Minimal live-backend client for the contract suite: a cookie jar (fetch keeps |
| 3 | * none of its own in bun/node) plus a hard timeout so a dead port fails fast |
| 4 | * instead of hanging the run. Boot recipe: see vitest.contract.config.ts. |
| 5 | */ |
| 6 | import { expect } from "vitest"; |
| 7 | |
| 8 | // The app's tsconfig has no node types (browser build), so reach env this way. |
| 9 | const env: Record<string, string | undefined> = |
| 10 | (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}; |
| 11 | |
| 12 | export const contractBaseUrl = (env.CONTRACT_BASE_URL ?? "").replace(/\/+$/, ""); |
| 13 | export const isLive = contractBaseUrl !== ""; |
| 14 | |
| 15 | export const SKIP_MESSAGE = |
| 16 | "[contract] CONTRACT_BASE_URL unset — skipping live contract tests. " + |
| 17 | "Boot a scratch backend (see vitest.contract.config.ts) and re-run with " + |
| 18 | "CONTRACT_BASE_URL=http://127.0.0.1:8081 bun run test:contract"; |
| 19 | |
| 20 | const TIMEOUT_MS = 10_000; |
| 21 | const MAX_RATE_LIMIT_RETRIES = 12; |
| 22 | let cookie = ""; |
| 23 | |
| 24 | const SCHOOL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; |
| 25 | |
| 26 | /** School cookie is `session=<uuid>.<token>`; operator cookie stays `session=builder.<token>`. */ |
| 27 | function sessionCookie(raw: string): string | null { |
| 28 | const pair = raw.split(";")[0] ?? ""; |
| 29 | if (!pair.startsWith("session=")) return null; |
| 30 | const value = pair.slice("session=".length); |
| 31 | const dot = value.indexOf("."); |
| 32 | if (dot <= 0 || dot === value.length - 1) return null; |
| 33 | const prefix = value.slice(0, dot); |
| 34 | if (prefix === "builder" || SCHOOL_UUID.test(prefix)) return pair; |
| 35 | return null; |
| 36 | } |
| 37 | |
| 38 | type Init = { method?: string; body?: unknown; headers?: Record<string, string> }; |
| 39 | |
| 40 | function retryDelayMs(response: Response, attempt: number): number { |
| 41 | const retryAfter = Number(response.headers.get("Retry-After")); |
| 42 | if (Number.isFinite(retryAfter) && retryAfter > 0) return retryAfter * 1_000; |
| 43 | return Math.min(1_000 * 2 ** attempt, 5_000); |
| 44 | } |
| 45 | |
| 46 | /** Raw request — returns the Response so tests can assert on status codes. */ |
| 47 | export async function api(path: string, init: Init = {}): Promise<Response> { |
| 48 | const headers: Record<string, string> = { ...init.headers }; |
| 49 | if (cookie) headers.Cookie = cookie; |
| 50 | |
| 51 | let body: BodyInit | undefined; |
| 52 | if (init.body instanceof FormData) { |
| 53 | body = init.body; |
| 54 | } else if (init.body !== undefined) { |
| 55 | headers["Content-Type"] = "application/json"; |
| 56 | body = JSON.stringify(init.body); |
| 57 | } |
| 58 | |
| 59 | let res: Response | undefined; |
| 60 | for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt += 1) { |
| 61 | res = await fetch(`${contractBaseUrl}${path}`, { |
| 62 | method: init.method ?? "GET", |
| 63 | headers, |
| 64 | body, |
| 65 | redirect: "manual", |
| 66 | signal: AbortSignal.timeout(TIMEOUT_MS), |
| 67 | }); |
| 68 | // A 429 has not executed the request, so retrying it is safe even for |
| 69 | // contract-suite POST/PATCH probes. Production calls remain unchanged. |
| 70 | if (res.status !== 429 || attempt === MAX_RATE_LIMIT_RETRIES) break; |
| 71 | await new Promise<void>((resolve) => setTimeout(resolve, retryDelayMs(res!, attempt))); |
| 72 | } |
| 73 | |
| 74 | const setCookies = res!.headers.getSetCookie?.() ?? []; |
| 75 | for (const raw of setCookies) { |
| 76 | const pair = sessionCookie(raw); |
| 77 | if (pair) cookie = pair; |
| 78 | } |
| 79 | return res!; |
| 80 | } |
| 81 | |
| 82 | /** Request + JSON body, throwing on a non-2xx so setup failures are loud. */ |
| 83 | export async function json<T>(path: string, init: Init = {}): Promise<T> { |
| 84 | const res = await api(path, init); |
| 85 | const text = await res.text(); |
| 86 | if (!res.ok) { |
| 87 | throw new Error(`${init.method ?? "GET"} ${path} → ${res.status} ${text}`); |
| 88 | } |
| 89 | return (text ? JSON.parse(text) : null) as T; |
| 90 | } |
| 91 | |
| 92 | /** Log in as the seeded admin; the session cookie lands in the jar. */ |
| 93 | export async function loginAdmin(): Promise<void> { |
| 94 | const result = await json<{ id: string } | { schools: Array<{ id: string }> }>("/auth/login", { |
| 95 | method: "POST", |
| 96 | body: { |
| 97 | username: env.ADMIN_USERNAME ?? "admin", |
| 98 | password: env.ADMIN_PASSWORD ?? "admin123", |
| 99 | }, |
| 100 | }); |
| 101 | if ("schools" in result) { |
| 102 | const school = env.SCHOOL_ID ?? result.schools[0]?.id; |
| 103 | if (!school) throw new Error("POST /auth/login returned an empty school choice list"); |
| 104 | await json("/auth/school", { method: "POST", body: { school } }); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /** Exam kinds are school policy, not a globally fixed enum. */ |
| 109 | export async function configuredExamKind(): Promise<string> { |
| 110 | const settings = await json<{ exam_kinds?: Array<{ name?: unknown }> }>("/settings"); |
| 111 | const kind = settings.exam_kinds?.find((entry) => typeof entry.name === "string" && entry.name.trim())?.name; |
| 112 | if (!kind || typeof kind !== "string") throw new Error("GET /settings returned no configured exam kind"); |
| 113 | return kind; |
| 114 | } |
| 115 | |
| 116 | /** Smallest valid 1x1 PNG, for the image-upload steps. */ |
| 117 | export function pngFile(name: string): File { |
| 118 | const bytes = Uint8Array.from( |
| 119 | atob( |
| 120 | "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", |
| 121 | ), |
| 122 | (c) => c.charCodeAt(0), |
| 123 | ); |
| 124 | return new File([bytes], name, { type: "image/png" }); |
| 125 | } |
| 126 | |
| 127 | /** Assert the list envelope shared by all paginated REST routes. */ |
| 128 | export function expectPage(data: unknown): asserts data is { |
| 129 | items: unknown[]; |
| 130 | total: number; |
| 131 | limit: number | null; |
| 132 | offset: number; |
| 133 | } { |
| 134 | expect(data).toMatchObject({}); |
| 135 | expect(Array.isArray((data as { items?: unknown }).items)).toBe(true); |
| 136 | expect(typeof (data as { total?: unknown }).total).toBe("number"); |
| 137 | const limit = (data as { limit?: unknown }).limit; |
| 138 | expect(limit === null || typeof limit === "number").toBe(true); |
| 139 | expect(typeof (data as { offset?: unknown }).offset).toBe("number"); |
| 140 | } |