import { apiUrl } from '../http/apiUrl'; import { fetchJson } from '../http/fetchJson'; import { parseProblem } from '../http/problem'; import type { ContactClient, ContactErrorCode, ContactField, ContactFieldErrors, ContactPayload, ContactToken, SubmitResult, TokenResult, } from './types'; const TOKEN_PATH = '/api/v1/contact-messages/token'; const SUBMIT_PATH = '/api/v1/contact-messages'; const FIELDS: ContactField[] = ['name', 'email', 'subject', 'message']; const CODES: ContactErrorCode[] = ['required', 'tooLong', 'invalid', 'expired']; function parseToken(body: unknown): ContactToken | null { if (!body || typeof body !== 'object') { return null; } const { token, minSeconds, captcha } = body as Record; if (typeof token !== 'string' || token.length === 0 || typeof minSeconds !== 'number') { return null; } let parsedCaptcha: ContactToken['captcha'] = null; if (captcha && typeof captcha === 'object') { const { provider, siteKey, apiEndpoint } = captcha as Record; if (typeof provider !== 'string' || typeof siteKey !== 'string') { return null; } // Additive field: absent or unknown means the default (global) endpoint. parsedCaptcha = { provider, siteKey, apiEndpoint: apiEndpoint === 'eu' ? 'eu' : 'global' }; } return { token, minSeconds, captcha: parsedCaptcha }; } function mapFieldErrors(errors: Record): ContactFieldErrors { const result: ContactFieldErrors = {}; for (const field of FIELDS) { const code = errors[field]?.find((c): c is ContactErrorCode => (CODES as string[]).includes(c)); if (code) { result[field] = code; } } return result; } /** * Client for the contact endpoints of the CMS API (contract v0.3.x). Never throws: every outcome * is a typed result. Request and response bodies are never logged. */ export function createContactClient( options: { baseUrl?: string; fetch?: typeof fetch } = {}, ): ContactClient { const fetchImpl = options.fetch ?? ((...args) => fetch(...args)); return { async getToken(): Promise { try { const response = await fetchJson(fetchImpl, apiUrl(TOKEN_PATH, options.baseUrl), { method: 'GET', headers: { Accept: 'application/json' }, }); if (response.status === 200) { const token = parseToken(response.body); return token ? { kind: 'ok', token } : { kind: 'failed' }; } return response.status === 404 ? { kind: 'closed' } : { kind: 'failed' }; } catch { return { kind: 'failed' }; } }, async submit(payload: ContactPayload, context): Promise { try { const response = await fetchJson(fetchImpl, apiUrl(SUBMIT_PATH, options.baseUrl), { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': context.idempotencyKey, }, body: JSON.stringify(payload), }); switch (response.status) { case 202: return { kind: 'ok' }; case 400: { const problem = parseProblem(400, response.body, response.retryAfter); const fields = mapFieldErrors(problem.errors); const tokenExpired = Boolean(problem.errors.token?.includes('expired')); if (tokenExpired || Object.keys(fields).length > 0) { return { kind: 'invalid', fields, tokenExpired }; } return { kind: 'failed' }; } case 404: return { kind: 'closed' }; case 413: return { kind: 'tooLarge' }; case 429: return { kind: 'rateLimited', retryAfterSeconds: parseProblem(429, response.body, response.retryAfter) .retryAfterSeconds, }; default: return { kind: 'failed' }; } } catch { return { kind: 'failed' }; } }, }; }