import {z} from 'zod' export type RelaySelection = {type?: ('header' | 'json' | 'form') | undefined, role?: string | undefined, selector: string}; export type RelayAction = {action: 'encrypt' | 'decrypt', selections: Array}; export type RelayRoute = {method?: ('GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH') | undefined, path: string, request: Array, response: Array}; export type CreateApiRelaysArgs = {body: {destinationDomain: string, routes: Array, encryptEmptyStrings?: boolean | undefined, authentication?: ('api-key' | 'null' | null) | undefined}}; export type CreateApiRelaysOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const relaySelection = z.object({type: z.enum(["header", "json", "form"]).optional(), role: z.string().optional(), selector: z.string()}); export const relayAction = z.object({action: z.enum(["encrypt", "decrypt"]), selections: z.array(relaySelection)}); export const relayRoute = z.object({method: z.enum(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"]).optional(), path: z.string(), request: z.array(relayAction), response: z.array(relayAction)}); export const relay = z.object({id: z.string(), destinationDomain: z.string(), evervaultDomain: z.string(), routes: z.array(relayRoute), authentication: z.enum(["api-key", "null"]).nullable(), encryptEmptyStrings: z.boolean(), app: z.string(), createdAt: z.number().int(), updatedAt: z.number().int()}); 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 a Relay * * POST /relays */ export const createApiRelays = async (args: CreateApiRelaysArgs, options?: CreateApiRelaysOptions) => { const {baseUrl = "https://api.evervault.com", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/relays${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(relay, await res.json()) };