import {z} from 'zod' export type Address = {address_line1?: string | undefined, address_line2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, country?: string | undefined}; export type PhoneNumber = {country_code?: string | undefined, number?: string | undefined}; export type AccountHolder = {type: 'individual' | 'corporate' | 'government', first_name: string, last_name: string, tax_id?: string | undefined, date_of_birth?: string | undefined, country_of_birth?: string | undefined, residential_status?: ('resident' | 'non_resident') | undefined, billing_address: Address, phone?: PhoneNumber | undefined, identification?: ({type?: string | undefined, issuing_country?: string | undefined, number?: string | undefined}) | undefined} | {type: 'individual' | 'corporate' | 'government', company_name: string, tax_id?: string | undefined, billing_address?: Address | undefined} | {type: 'individual' | 'corporate' | 'government', company_name: string, tax_id?: string | undefined, billing_address?: Address | undefined}; export type BankDetails = {name?: string | undefined, branch?: string | undefined, address?: Address | undefined}; export type StoreCustomerInstrumentRequest = {id?: string | undefined, email?: string | undefined, name?: string | undefined, phone?: PhoneNumber | undefined, default?: boolean | undefined}; export type InstrumentMetadata = {[key: string]: string}; export type StoreAccountHolderTokenRequest = {first_name?: string | undefined, last_name?: string | undefined, billing_address?: Address | undefined, phone?: PhoneNumber | undefined}; export type ProvisionNetworkToken = {provision?: boolean | undefined}; export type StoreInstrumentRequest = {type: 'bank_account', account_type?: ('savings' | 'current' | 'cash') | undefined, account_number?: string | undefined, bank_code?: string | undefined, branch_code?: string | undefined, iban?: string | undefined, bban?: string | undefined, swift_bic?: string | undefined, currency: string, country: string, processing_channel_id?: string | undefined, account_holder?: AccountHolder | undefined, bank?: BankDetails | undefined, customer?: StoreCustomerInstrumentRequest | undefined, metadata?: InstrumentMetadata | undefined} | {type: 'card', number: unknown, expiry_month: number, expiry_year: number, name?: string | undefined, account_holder?: StoreAccountHolderTokenRequest | undefined, customer?: StoreCustomerInstrumentRequest | undefined, entity_id?: string | undefined, processing_channel_id?: string | undefined, network_token?: ProvisionNetworkToken | undefined, metadata?: InstrumentMetadata | undefined} | {type: 'token', token: string, account_holder?: StoreAccountHolderTokenRequest | undefined, customer?: StoreCustomerInstrumentRequest | undefined, metadata?: InstrumentMetadata | undefined} | {type: 'sepa', instrument_data: {type?: ('Core' | 'B2B') | undefined, account_number: string, country: string, currency: string, payment_type: 'recurring' | 'regular', mandate_id?: string | undefined, date_of_signature?: string | undefined}, account_holder: {first_name: string, last_name: string, billing_address: {address_line1: string, address_line2: string, city: string, zip: string, country: string}, company_name?: string | undefined, type?: ('individual' | 'corporate') | undefined}, customer?: StoreCustomerInstrumentRequest | undefined} | {type: 'ach', instrument_data: {account_type: 'savings' | 'checking', account_number: string, bank_code: string, currency: string, country: string}, account_holder: {first_name: string, last_name: string, company_name: string, type: 'individual' | 'corporate'}, customer?: StoreCustomerInstrumentRequest | undefined} | {type: 'bacs', account: {processing_channel_id: string}, instrument_data: {account_number: string, bank_code: string, country: string, currency: string, payment_type: 'Recurring' | 'Regular', allow_partial_match?: boolean | undefined}, account_holder: {first_name: string, last_name: string, billing_address: {address_line1?: string | undefined, address_line2?: string | undefined, city?: string | undefined, zip?: string | undefined, country: string}}, customer?: StoreCustomerInstrumentRequest | undefined}; export type CreateApiInstrumentsArgs = {body: StoreInstrumentRequest}; export type CreateApiInstrumentsOptions = {baseUrl: string, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const phoneNumber = z.object({country_code: z.string().min(1).max(7).optional(), number: z.string().max(25).optional()}); export const customerSummary = z.object({registration_date: z.string().optional(), first_transaction_date: z.string().optional(), last_payment_date: z.string().optional(), total_order_count: z.number().int().optional(), last_payment_amount: z.number().optional(), is_premium_customer: z.boolean().optional(), is_returning_customer: z.boolean().optional(), lifetime_value: z.number().optional()}); export const customerResponse = z.object({id: z.string(), email: z.string().optional(), name: z.string().optional(), phone: phoneNumber.optional(), summary: customerSummary.optional()}); export const address = z.object({address_line1: z.string().max(200).optional(), address_line2: z.string().max(200).optional(), city: z.string().max(50).optional(), state: z.string().max(3).optional(), zip: z.string().max(50).optional(), country: z.string().min(2).max(2).optional()}); export const bankDetails = z.object({name: z.string().max(128).optional(), branch: z.string().max(128).optional(), address: address.optional()}); export const instrumentMetadata = z.record(z.string(), z.string().max(100)); export const accountHolderResponse = z.object({first_name: z.string().optional(), last_name: z.string().optional(), billing_address: address.optional(), phone: phoneNumber.optional()}); export const networkToken = z.object({id: z.string(), state: z.enum(["active", "suspended", "inactive"]).optional()}); export const storeInstrumentResponse = z.discriminatedUnion("type", [z.object({type: z.literal("bank_account"), id: z.string(), fingerprint: z.string(), customer: customerResponse.optional(), bank: bankDetails.optional(), swift_bic: z.string().optional(), account_number: z.string().optional(), bank_code: z.string().optional(), iban: z.string().optional(), metadata: instrumentMetadata.optional()}), z.object({type: z.literal("card"), id: z.string(), fingerprint: z.string(), expiry_month: z.number().int().gte(1), expiry_year: z.number().int(), scheme: z.string().optional(), scheme_local: z.literal("cartes_bancaires").optional(), last4: z.string().min(4).max(4), bin: z.string(), card_type: z.enum(["CREDIT", "DEBIT", "PREPAID", "CHARGE"]).optional(), card_category: z.enum(["CONSUMER", "COMMERCIAL"]).optional(), issuer: z.string().optional(), issuer_country: z.string().min(2).max(2).optional(), product_id: z.string().optional(), product_type: z.string().optional(), account_holder: accountHolderResponse.optional(), customer: customerResponse.optional(), network_token: networkToken.optional(), metadata: instrumentMetadata.optional()}), z.object({type: z.literal("sepa"), id: z.string(), fingerprint: z.string()}), z.object({type: z.literal("ach"), id: z.string(), fingerprint: z.string()}), z.object({type: z.literal("bacs"), id: z.string(), fingerprint: 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 }; /** * Create an instrument * * POST /instruments * * Also accepts auth: ApiSecretKey */ export const createApiInstruments = async (args: CreateApiInstrumentsArgs, options: CreateApiInstrumentsOptions) => { const {baseUrl, fetch: fetchFn = fetch, OAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/instruments${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(storeInstrumentResponse, await res.json()) };