import {z} from 'zod' export type OffsetToken = string; export type MerchantReference = string; export type GetApiMerchantsArgs = {sortOrder?: ('asc' | 'desc') | undefined, limit?: number | undefined, offsetToken?: OffsetToken | undefined, merchantReference?: MerchantReference | undefined}; export type GetApiMerchantsOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const offsetToken = z.string().min(1).max(2048); export const moreItems = z.boolean(); export const merchantKey = z.string().min(5).max(120); export const merchantStatus = z.enum(["active", "archived"]); export const merchantReference = z.string().min(1).max(120); export const agentKey = z.string(); export const merchantLegalName = z.string().min(1).max(120); export const countryCodeAlpha3 = z.string().min(3).max(3); export const countryCodeAlpha2 = z.string().min(2).max(2); export const countryCodeNumeric = z.string().min(3).max(3); export const countryCode = z.object({alpha3: countryCodeAlpha3, alpha2: countryCodeAlpha2, numeric: countryCodeNumeric}); export const stateOrProvince = z.string().min(1).max(120); export const city = z.string().min(1).max(120); export const line1 = z.string().min(1).max(120); export const line2 = z.string().min(1).max(120); export const postalCode = z.string().min(1).max(10); export const address = z.object({countryCode: countryCode, stateOrProvince: stateOrProvince.optional(), city: city, line1: line1, line2: line2.optional(), postalCode: postalCode}); export const phoneNumber = z.string().min(5).max(33); export const url = z.string().min(8).max(2048); export const tags = z.record(z.string(), z.string().min(1).max(100)); export const created = z.string(); export const lastModified = z.string(); export const version = z.number().int(); export const taxRegistrationId = z.string().max(20); export const email = z.string(); export const businessType = z.enum(["corporation", "sole_proprietorship", "partnership", "non_profit_organization", "government_agency", "limited_liability_company"]); export const merchant = z.object({key: merchantKey, status: merchantStatus, merchantReference: merchantReference.optional(), agentKey: agentKey, name: z.string().min(1).max(120), description: z.string().min(1).max(160).optional(), legalName: merchantLegalName, registeredAddress: address, customerInquiry: phoneNumber, websiteUrl: url, tags: tags.optional(), created: created, lastModified: lastModified.optional(), version: version, taxRegistrationId: taxRegistrationId.optional(), sellerEmail: email.optional(), businessType: businessType.optional()}); export const merchantsPage = z.object({offsetToken: offsetToken.optional(), moreItems: moreItems.optional(), merchants: z.array(merchant)}); 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 Merchants * * GET /merchants * * Also accepts auth: BearerToken */ export const getApiMerchants = async (args: GetApiMerchantsArgs, options?: GetApiMerchantsOptions) => { const {baseUrl = "https://eu-west-1.api.silverflow.com/v1", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.sortOrder != null) query.append("sortOrder", String(args.sortOrder)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offsetToken != null) query.append("offsetToken", String(args.offsetToken)) if (args.merchantReference != null) query.append("merchantReference", String(args.merchantReference)) if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/merchants${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(merchantsPage, await res.json()) };