import {z} from 'zod' export type RequestSegmentV3 = {id: string, source: string, target: string}; export type LocaleCode = string; export type EvaluationV3Request = {contentGroupId: string, segments: Array, sourceLocaleCode: LocaleCode, targetLocaleCode: LocaleCode}; export type CreateApiV3EvaluationArgs = {'Content-Type': string, body: EvaluationV3Request}; export type CreateApiV3EvaluationOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const evaluationItemType = z.enum(["AI_CHECK", "QA_CHECK"]); export const checkEvaluationV3 = z.object({isValid: z.boolean().optional(), explanation: z.string().optional(), hasError: z.boolean().optional(), errorMessage: z.string().optional()}); export const checkResultV3 = z.object({type: evaluationItemType, ruleUid: z.string().optional(), evaluation: checkEvaluationV3}); export const evaluatedSegmentV3 = z.object({id: z.string(), source: z.string(), target: z.string(), results: z.array(checkResultV3)}); export const evaluationV3Response = z.object({contentGroupId: z.string().optional(), segments: z.array(evaluatedSegmentV3)}); 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 }; /** * Evaluate segments * * POST /v3/evaluation */ export const createApiV3Evaluation = async (args: CreateApiV3EvaluationArgs, options?: CreateApiV3EvaluationOptions) => { const {baseUrl = "https://eu.phrase.com/control-hub", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) const url = `${baseUrl.replace(/\/+$/, '')}/v3/evaluation${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(evaluationV3Response, await res.json()) };