import {z} from 'zod' export type GetApiFieldsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const classificationPercentage = z.object({classifications: z.array(z.string()), percentage: z.number()}); export const country = z.object({code: z.string(), name: z.string()}); export const jurisdiction = z.object({country: country, regions: z.array(z.string())}); export const languagePercentage = z.object({language: z.string(), percentage: z.number()}); export const fieldListResponseElement = z.object({bias: z.number(), description: z.string(), document_count: z.number().int(), document_types: z.array(classificationPercentage), f_score: z.number(), field_id: z.string(), file_ids: z.array(z.string()), is_custom: z.boolean(), is_trained: z.boolean(), jurisdictions: z.array(jurisdiction), languages: z.array(languagePercentage), name: z.string(), normalization_type: z.string(), precision: z.number(), recall: z.number(), tags: z.array(z.string())}); export const fieldListResponse = z.array(fieldListResponseElement); 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 }; /** * Get field list * * GET /fields */ export const getApiFields = async (options?: GetApiFieldsOptions) => { const {baseUrl = "https://us.app.zuva.ai/api/v2", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/fields${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(fieldListResponse, await res.json()) };