import {z} from 'zod' export type GetApiKmsKeyOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const keyRotationConfig = z.object({"manual-count": z.number().int(), automatic: z.boolean(), "rotation-period": z.number().int(), "next-at": z.string()}); export const revisionStamp = z.object({at: z.string(), seq: z.number().int().gte(0)}); export const keyMaterial = z.object({version: z.number().int(), "created-at": z.string(), automatic: z.boolean()}); export const listKmsKeysResponseEntry = z.object({description: z.string().optional(), rotation: keyRotationConfig, revision: revisionStamp, "delete-at": z.string().optional(), name: z.string(), "multi-zone": z.boolean(), source: z.literal("exoscale-kms"), usage: z.string(), status: z.enum(["enabled", "disabled", "pending-deletion"]), "status-since": z.string(), id: z.string(), replicas: z.array(z.string()).optional(), material: keyMaterial, "origin-zone": z.string(), "created-at": z.string()}); export const listKmsKeysResponse = z.object({"kms-keys": z.array(listKmsKeysResponseEntry)}); 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 }; /** * List KMS Keys * * GET /kms-key */ export const getApiKmsKey = async (options?: GetApiKmsKeyOptions) => { const {baseUrl = "https://api-ch-gva-2.exoscale.com/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/kms-key${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(listKmsKeysResponse, await res.json()) };