import {z} from 'zod' export type GetApiWhoisId4nArgs = {id4n: string}; export type GetApiWhoisId4nOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const organization = z.object({id: z.number().int().optional(), logoURL: z.string().optional(), name: z.string().min(3).max(254), namespace: z.string().min(3).max(255)}); export const organizationAddress = z.object({companyName: z.string().max(254).optional(), firstname: z.string().max(255), lastname: z.string().max(255), street: z.string().min(3).max(254), postCode: z.string().min(2).max(40), city: z.string().min(2).max(99), countryCode: z.string().max(2), countryName: z.string().optional(), telephone: z.string().max(99).optional()}); export const whoIsResponse = z.object({aliases: z.record(z.string(), z.string()).optional(), organization: organization.optional(), organizationAddress: organizationAddress.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 }; /** * Resolve owner of id4n * * GET /whois/{id4n} */ export const getApiWhoisId4n = async (args: GetApiWhoisId4nArgs, options: GetApiWhoisId4nOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/whois/${encodeURIComponent(String(args.id4n))}${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(whoIsResponse, await res.json()) };