import {z} from 'zod' export type FetchResourcesOfdaBrazil = Array<'ACCOUNTS' | 'TRANSACTIONS' | 'OWNERS' | 'BILLS' | 'INVESTMENTS' | 'INVESTMENT_TRANSACTIONS' | 'EXCHANGES' | 'INCOMES' | 'RECURRING_EXPENSES' | 'RISK_INSIGHTS'>; export type StaleIn = string; export type WidgetTokenRequestBankingBrazil = {id: string, password: string, scopes: string, fetch_resources: FetchResourcesOfdaBrazil, stale_in: StaleIn, widget: {openfinance_feature: string, callback_urls: {success: string, exit: string, event: string}, branding: {company_icon: string, company_logo: string, company_name: string, company_terms_url: string, overlay_background_color?: string | undefined, social_proof?: boolean | undefined, show_belvo_middle_logo?: boolean | undefined}, theme?: Array<{css_key: string, value: string}> | undefined, consent: {purpose: string, terms_and_conditions_url: string, permissions: Array<'REGISTER' | 'ACCOUNTS' | 'CREDIT_CARDS' | 'CREDIT_OPERATIONS'>, identification_info: Array<{type: string, number: string, name: string}>, default_consent_duration_days?: number | undefined}}}; export type FetchResourcesEmploymentBrazil = Array<'EMPLOYMENTS' | 'OWNERS'>; export type CredentialsStorage = string; export type WidgetTokenRequestEmploymentBrazil = {id: string, password: string, scopes: string, fetch_resources: FetchResourcesEmploymentBrazil, stale_in: StaleIn, credentials_storage?: CredentialsStorage | undefined, widget: {callback_urls?: {success: string, exit: string, event: string} | undefined, branding: {company_icon: string, company_logo: string, company_name: string, company_terms_url: string, company_terms_version?: string | undefined, overlay_background_color?: string | undefined, social_proof?: boolean | undefined}, theme?: Array<{css_key: string, value: string}> | undefined}}; export type FetchResourcesEmploymentMexico = Array<'EMPLOYMENT_RECORDS' | 'CURRENT_EMPLOYMENTS' | 'EMPLOYMENT_METRICS'>; export type WidgetTokenRequestEmploymentMexico = {id: string, password: string, scopes: string, fetch_resources: FetchResourcesEmploymentMexico, stale_in: StaleIn, credentials_storage?: CredentialsStorage | undefined, widget: {callback_urls?: {success: string, exit: string, event: string} | undefined, branding: {company_icon: string, company_logo: string, company_name: string, company_terms_url: string, company_terms_version?: string | undefined, overlay_background_color?: string | undefined, social_proof?: boolean | undefined}, theme?: Array<{css_key: string, value: string}> | undefined}}; export type FetchResourcesFiscalMexico = Array<'FINANCIAL_STATEMENTS' | 'INVOICES' | 'TAX_COMPLIANCE_STATUS' | 'TAX_RETENTIONS' | 'TAX_RETURNS' | 'TAX_STATUS'>; export type WidgetTokenRequestFiscalMexico = {id: string, password: string, scopes: string, fetch_resources: FetchResourcesFiscalMexico, stale_in: StaleIn, credentials_storage?: CredentialsStorage | undefined, widget: {callback_urls?: {success: string, exit: string, event: string} | undefined, branding: {company_icon: string, company_logo: string, company_name: string, company_terms_url: string, company_terms_version?: string | undefined, overlay_background_color?: string | undefined, social_proof?: boolean | undefined}, theme?: Array<{css_key: string, value: string}> | undefined}}; export type CreateApiApiTokenArgs = {body: WidgetTokenRequestBankingBrazil | WidgetTokenRequestEmploymentBrazil | WidgetTokenRequestEmploymentMexico | WidgetTokenRequestFiscalMexico}; export type CreateApiApiTokenOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const widgetToken = z.object({access: z.string().optional(), refresh: z.string().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 }; /** * Generate a widget access token * * POST /api/token/ */ export const createApiApiToken = async (args: CreateApiApiTokenArgs, options?: CreateApiApiTokenOptions) => { const {baseUrl = "https://sandbox.belvo.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/token/${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(widgetToken, await res.json()) };