import {z} from 'zod' export type CardDetailsRequest = {number: string, expiry_month: number, expiry_year: number}; export type Instrument = {id: string}; export type AccountUpdaterRequest = {source_options?: ({card?: CardDetailsRequest | undefined, instrument?: Instrument | undefined}) | undefined}; export type CreateApiAccountUpdaterCardsArgs = {body: AccountUpdaterRequest}; export type CreateApiAccountUpdaterCardsOptions = {baseUrl: string, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cardDetailsResponse = z.object({encrypted_card_number: z.string().optional(), bin: z.string().optional(), last4: z.string().optional(), expiry_month: z.number().int().gte(1).lte(12), expiry_year: z.number().int(), fingerprint: z.string().optional()}); export const accountUpdaterResponse = z.object({account_update_status: z.enum(["CARD_UPDATED", "CARD_EXPIRY_UPDATED", "CARD_CLOSED", "UPDATE_FAILED"]), account_update_failure_code: z.enum(["CARDHOLDER_OPT_OUT", "UP_TO_DATE", "NON_PARTICIPATING_BIN", "UNKNOWN"]).optional(), card: cardDetailsResponse.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 }; /** * Get updated card credentials * * POST /account-updater/cards */ export const createApiAccountUpdaterCards = async (args: CreateApiAccountUpdaterCardsArgs, options: CreateApiAccountUpdaterCardsOptions) => { 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(/\/+$/, '')}/account-updater/cards${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(accountUpdaterResponse, await res.json()) };