import {z} from 'zod' export type GetApiApi2JsonGenderFullGeoFullNameCountryIso2Args = {fullName: string, countryIso2: string}; export type GetApiApi2JsonGenderFullGeoFullNameCountryIso2Options = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const personalNameGenderedOut = z.object({script: z.string().optional(), id: z.string().optional(), explanation: z.string().optional(), name: z.string().optional(), likelyGender: z.enum(["male", "female", "unknown"]).optional(), genderScale: z.number().gte(-1).lte(1).optional(), score: z.number().gte(0).lte(100).optional(), probabilityCalibrated: z.number().gte(-1).lte(1).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 }; /** * Infer the likely gender of a full name, given a local context (ISO2 country code). * * GET /api2/json/genderFullGeo/{fullName}/{countryIso2} */ export const getApiApi2JsonGenderFullGeoFullNameCountryIso2 = async (args: GetApiApi2JsonGenderFullGeoFullNameCountryIso2Args, options?: GetApiApi2JsonGenderFullGeoFullNameCountryIso2Options) => { const {baseUrl = "https://v2.namsor.com/NamSorAPIv2", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("X-API-KEY", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/api2/json/genderFullGeo/${encodeURIComponent(String(args.fullName))}/${encodeURIComponent(String(args.countryIso2))}${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(personalNameGenderedOut, await res.json()) };