import {z} from 'zod' export type Snapshot = {vmId: string, ssId?: string | undefined, snapshot_type?: string | undefined, snapshot_path?: string | undefined, mem_file_path?: string | undefined, version?: string | undefined, record_regions?: boolean | undefined, size_threshold?: number | undefined, interval_threshold?: number | undefined}; export type CreateApiSnapshotsArgs = {body: Snapshot}; export type CreateApiSnapshotsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const snapshot = z.object({vmId: z.string(), ssId: z.string().optional(), snapshot_type: z.string().optional(), snapshot_path: z.string().optional(), mem_file_path: z.string().optional(), version: z.string().optional(), record_regions: z.boolean().optional(), size_threshold: z.number().int().optional(), interval_threshold: z.number().int().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 }; /** * Take a snapshot * * POST /snapshots */ export const createApiSnapshots = async (args: CreateApiSnapshotsArgs, options?: CreateApiSnapshotsOptions) => { const {baseUrl = "http://localhost:8080", 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(/\/+$/, '')}/snapshots${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(snapshot, await res.json()) };