import {z} from 'zod' export type GetApiTldsArgs = {sort?: ('tld:asc' | 'tld:desc') | undefined}; export type GetApiTldsOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const tLDType = z.union([z.literal(1), z.literal(2), z.literal(3)]); export const tLD = z.object({tld: z.string(), tld_type: tLDType, whois_privacy: z.boolean(), auto_renew_only: z.boolean(), idn: z.boolean(), minimum_registration: z.number().int(), registration_enabled: z.boolean(), renewal_enabled: z.boolean(), transfer_enabled: z.boolean(), dnssec_interface_type: z.enum(["ds", "key"]), name_server_min: z.number().int(), name_server_max: z.number().int(), trustee_service_enabled: z.boolean(), trustee_service_required: z.boolean()}); export const pagination = z.object({current_page: z.number().int(), per_page: z.number().int(), total_entries: z.number().int(), total_pages: z.number().int()}); export const getApiTldsResponse = z.object({data: z.array(tLD), pagination: pagination}); 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 TLDs * * GET /tlds * * Also accepts auth: bearerAuth */ export const getApiTlds = async (args: GetApiTldsArgs, options?: GetApiTldsOptions) => { const {baseUrl = "https://api.dnsimple.com/v2", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.sort != null) query.append("sort", String(args.sort)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/tlds${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(getApiTldsResponse, await res.json()) };