import {z} from 'zod' export type GetApiKnowledgeBasesDashboardOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const connectionStatsResponse = z.object({total_avatars: z.number().int(), total_voices: z.number().int(), total_integrations: z.number().int()}); export const insightsResponse = z.object({rate_success: z.number().int(), flagged_messages: z.number().int(), stats: z.record(z.string(), z.number().int())}); export const safetyResponse = z.object({enabled: z.boolean(), credit_limit: z.number().int(), message_limit: z.number().int()}); export const kbCustomizationOverviewResponse = z.object({kb_id: z.string(), name: z.string(), icon: z.string(), connection_stats: connectionStatsResponse, insights: insightsResponse, safety: safetyResponse}); export const kbDashboardResponse = z.object({results: z.array(kbCustomizationOverviewResponse), message: z.string()}); 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 Kb Dashboard * * GET /knowledge-bases/dashboard * * Also accepts auth: OAuth2PasswordBearer */ export const getApiKnowledgeBasesDashboard = async (options: GetApiKnowledgeBasesDashboardOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/knowledge-bases/dashboard${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(kbDashboardResponse, await res.json()) };