import {z} from 'zod' export type CreateKmsKeyRequest = {name: string, description?: string | undefined, usage?: 'encrypt-decrypt' | undefined, 'multi-zone'?: boolean | undefined}; export type CreateApiKmsKeyArgs = {body: CreateKmsKeyRequest}; export type CreateApiKmsKeyOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const revisionStamp = z.object({at: z.string(), seq: z.number().int().gte(0)}); export const createKmsKeyResponse = z.object({description: z.string().optional(), revision: revisionStamp, 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(), "origin-zone": z.string(), "created-at": 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 }; /** * Create KMS Key * * POST /kms-key */ export const createApiKmsKey = async (args: CreateApiKmsKeyArgs, options?: CreateApiKmsKeyOptions) => { const {baseUrl = "https://api-ch-gva-2.exoscale.com/v2", 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(/\/+$/, '')}/kms-key${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(createKmsKeyResponse, await res.json()) };