import {z} from 'zod' export type GetApiJurisdictionsArgs = {countryCode?: string | undefined, fallbackToFATF?: boolean | undefined, division?: string | undefined}; export type GetApiJurisdictionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const field = z.object({field: z.string().optional()}); export const condition: z.ZodType = z.object({type: z.string().optional(), fields: z.array(field).optional(), conditions: z.array(z.lazy(() => condition)).optional()}); export const rule = z.object({type: z.string().optional(), fields: z.array(field).optional(), conditions: z.array(condition).optional()}); export const threshold = z.object({rules: z.array(rule).optional(), threshold: z.number().optional()}); export const jurisdictionList = z.array(z.object({thresholds: z.array(threshold), countryCode: z.string(), currency: z.string()})); 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 all Jurisdictions * * GET /jurisdictions */ export const getApiJurisdictions = async (args: GetApiJurisdictionsArgs, options?: GetApiJurisdictionsOptions) => { const {baseUrl = "https://api.eu1.notabene.id", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.countryCode != null) query.append("countryCode", String(args.countryCode)) if (args.fallbackToFATF != null) query.append("fallbackToFATF", String(args.fallbackToFATF)) if (args.division != null) query.append("division", String(args.division)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/jurisdictions${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(jurisdictionList, await res.json()) };