import {z} from 'zod' export type BootstrapVerifyOTPRequest = {email: string, code: string, accept_terms: boolean, terms_version?: string | undefined, key_name?: string | undefined, scopes?: (Array<'read' | 'sites:write' | 'keys:manage' | 'billing:write'>) | undefined, expires_in_days?: number | undefined}; export type CreateApiAuthVerifyOtpArgs = {body: BootstrapVerifyOTPRequest}; export type CreateApiAuthVerifyOtpOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const aPIKey = z.object({id: z.number().int(), name: z.string(), prefix: z.string(), website_id: z.number().int().nullable(), scopes: z.string(), created_at: z.string(), created_ip: z.string().nullable().optional(), last_used_at: z.string().nullable().optional(), last_used_ip: z.string().nullable().optional(), expires_at: z.string().nullable().optional()}); export const bootstrapVerifyOTPResponse = z.object({token: z.string(), key: aPIKey, user: z.object({id: z.string(), email: z.string()}), created: z.boolean()}); 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 }; /** * Consume the code and receive the first API key * * POST /auth/verify-otp */ export const createApiAuthVerifyOtp = async (args: CreateApiAuthVerifyOtpArgs, options?: CreateApiAuthVerifyOtpOptions) => { const {baseUrl = "https://statable.com/api/v1", 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(/\/+$/, '')}/auth/verify-otp${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(bootstrapVerifyOTPResponse, await res.json()) };