import {z} from 'zod' export type ApiAuthTokenOption = 'administrator' | 'moderator' | 'allow_cycles' | 'extended_tx_status' | 'paid'; export type ApiCreateAuthTokenRequest = {name: string, hourly_limit?: number | undefined, options?: Array | undefined}; export type CreateApiV1AuthArgs = {body: ApiCreateAuthTokenRequest}; export type CreateApiV1AuthOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const apiAuthTokenOption = z.enum(["administrator", "moderator", "allow_cycles", "extended_tx_status", "paid"]); export const apiAuthToken = z.object({token: z.string(), name: z.string(), hourly_limit: z.number().int().optional(), options: z.array(apiAuthTokenOption).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 }; /** * Create new auth token * * POST /v1/auth */ export const createApiV1Auth = async (args: CreateApiV1AuthArgs, options?: CreateApiV1AuthOptions) => { const {baseUrl = "https://backend.swap.coffee", 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("X-Api-Key", ApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/auth${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(apiAuthToken, await res.json()) };