import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable, wrapSync } from "@tsus/runtime/boundary";export type Request = { method: string; headers: Record<string, string>; body: string };export type Response = { status: number; body: Record<string, unknown> };const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;type User = { name: string; email: string; age: Option<number> };const invalidField = (field: string): Response => ({ status: 422, body: { error: "invalid_field", field } });const contentType = (headers: Record<string, string>): Option<string> => fromNullable(Object.entries(headers).find(([k]) => k.toLowerCase() === "content-type")).map(([, v]) => v);const isJson = (ct: Option<string>): boolean => match (ct) { Some(v) => typeof v === "string" && v.split(";")[0].trim().toLowerCase() === "application/json", None => false, };const asObject = (data: unknown): Option<Record<string, unknown>> => fromNullable(data).andThen((d) => (typeof d === "object" && !Array.isArray(d) ? Some(d as Record<string, unknown>) : None));const parseAge = (v: Option<unknown>): Result<Option<number>, Response> => match (v) { None => Ok(None), Some(a) => typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 150 ? Ok(Some(a)) : Err(invalidField("age")), };const parseUser = (obj: Record<string, unknown>): Result<User, Response> => { const name = obj.name; if (typeof name !== "string" || name.trim() === "") { return Err(invalidField("name")); } const email = obj.email; if (typeof email !== "string" || !EMAIL.test(email)) { return Err(invalidField("email")); } return parseAge(fromNullable(obj.age)).map((age) => ({ name: name.trim(), email, age }));};const created = (user: User, nextId: () => string): Response => { const base: Record<string, unknown> = { id: nextId(), name: user.name, email: user.email }; return { status: 201, body: match (user.age) { Some(a) => ({ ...base, age: a }), None => base, }, };};const fromBody = (raw: string, nextId: () => string): Response => match (wrapSync(JSON.parse)(raw)) { Err(_e) => ({ status: 400, body: { error: "invalid_json" } }), Ok(data) => match (asObject(data)) { None => invalidField("body"), Some(obj) => match (parseUser(obj)) { Ok(user) => created(user, nextId), Err(res) => res, }, }, };export const handleCreateUser = (req: Request, nextId: () => string): Response => req.method !== "POST" ? { status: 405, body: { error: "method_not_allowed" } } : !isJson(contentType(req.headers)) ? { status: 415, body: { error: "unsupported_media_type" } } : fromBody(req.body, nextId);