import {z} from 'zod' export type GetApiTestFraudPreventionHeadersValidateArgs = {Accept: string, Authorization: string, 'Gov-*': string}; export type GetApiTestFraudPreventionHeadersValidateOptions = {baseUrl?: string | undefined, applicationRestricted?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiTestFraudPreventionHeadersValidateResponse = z.object({specVersion: z.string(), message: z.string(), errors: z.array(z.object({code: z.union([z.literal("INVALID_HEADER"), z.literal("INVALID_HEADERS"), z.literal("MISSING_HEADER"), z.literal("EMPTY_HEADER")]), message: z.string(), headers: z.array(z.string())})).optional(), warnings: z.array(z.object({code: z.union([z.literal("POTENTIALLY_INVALID_HEADER"), z.literal("UNEXPECTED_HEADER")]), message: z.string(), headers: z.array(z.string())})).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Validate fraud prevention headers * * GET /test/fraud-prevention-headers/validate */ export const getApiTestFraudPreventionHeadersValidate = async (args: GetApiTestFraudPreventionHeadersValidateArgs, options?: GetApiTestFraudPreventionHeadersValidateOptions) => { const {baseUrl = "https://test-api.service.hmrc.gov.uk", fetch: fetchFn = fetch, applicationRestricted} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.Accept != null) headers.set("Accept", String(args.Accept)) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args['Gov-*'] != null) headers.set("Gov-*", String(args['Gov-*'])) if (applicationRestricted !== undefined) headers.set('authorization', `Bearer ${applicationRestricted}`) const url = `${baseUrl.replace(/\/+$/, '')}/test/fraud-prevention-headers/validate${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiTestFraudPreventionHeadersValidateResponse, await res.json()) };