import {z} from 'zod' export type LineRecord = {line_id: number, message: string, level?: (string | null) | undefined, timestamp?: (string | null) | undefined, service?: (string | null) | undefined}; export type CapsuleRequest = {lines: Array, metadata?: ({[key: string]: unknown} | null) | undefined}; export type CreateApiV1CapsuleArgs = {body: CapsuleRequest}; export type CreateApiV1CapsuleOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const parseStats = z.object({llm_calls: z.number().int(), cache_hits: z.number().int(), unmatched: z.number().int(), elapsed_ms: z.number().int(), incident_family_hits: z.number().int().optional(), incident_induced_templates: z.number().int().optional(), global_cache_hits: z.number().int().optional(), global_shadow_hits: z.number().int().optional(), global_shadow_agreements: z.number().int().optional(), global_shadow_disagreements: z.number().int().optional(), total_patterns: z.number().int().optional(), candidate_patterns: z.number().int().optional(), dropped_patterns: z.number().int().optional(), cache_pattern_hits: z.number().int().optional(), global_cache_pattern_hits: z.number().int().optional()}); export const capsuleResponse = z.object({capsule: z.record(z.string(), z.unknown()), stats: parseStats}); 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 }; /** * Capsule Endpoint * * POST /v1/capsule */ export const createApiV1Capsule = async (args: CreateApiV1CapsuleArgs, options: CreateApiV1CapsuleOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/capsule${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(capsuleResponse, await res.json()) };