import {z} from 'zod' export type ConsentRequestBody = {scopes: Array<'account_details' | 'holder_information' | 'transactions_details'>, from_date?: string | undefined, to_date?: (string | null) | undefined, period_days?: number | undefined}; export type AttemptRequestBody = {fetch_scopes?: (Array<'accounts' | 'accounts_without_balance' | 'holder_info' | 'transactions'>) | undefined, from_date?: string | undefined, to_date?: string | undefined, fetched_accounts_notify?: boolean | undefined, custom_fields?: Record | undefined, locale?: string | undefined, include_natures?: (Array | null) | undefined, customer_last_logged_at?: string | undefined, exclude_accounts?: Array | undefined, store_credentials: boolean, unduplication_strategy?: string | undefined, user_present?: boolean | undefined, return_to?: string | undefined}; export type CreateConnectionRequestBody = {data: {customer_id: string, country_code: string, provider_code: string, consent: ConsentRequestBody, attempt?: AttemptRequestBody | undefined, credentials: Record, daily_refresh?: boolean | undefined, include_fake_providers?: boolean | undefined, categorization?: ('none' | 'personal' | 'business') | undefined, file_url?: boolean | undefined}}; export type CreateApiConnectionsArgs = {body: CreateConnectionRequestBody}; export type CreateApiConnectionsOptions = {baseUrl?: string | undefined, appId?: string | undefined, secret?: string | undefined, fetch?: typeof fetch | undefined}; export const stage = z.object({created_at: z.string(), id: z.string(), interactive_fields_names: z.array(z.string()).nullable().optional(), interactive_html: z.string().nullable().optional(), name: z.enum(["start", "connect", "interactive", "fetch_holder_info", "fetch_accounts", "fetch_recent", "fetch_full", "disconnect", "finish"]), updated_at: z.string()}); export const simplifiedAttempt = z.object({api_mode: z.enum(["app", "service"]).optional(), api_version: z.string().optional(), automatic_fetch: z.boolean().optional(), daily_refresh: z.boolean().optional(), categorize: z.boolean().optional(), created_at: z.string().optional(), custom_fields: z.object({}).optional(), device_type: z.enum(["desktop", "tablet", "mobile"]).optional(), remote_ip: z.string().optional(), exclude_accounts: z.array(z.string()).optional(), user_present: z.boolean().optional(), customer_last_logged_at: z.string().optional(), fail_at: z.string().optional(), fail_error_class: z.string().optional(), fail_message: z.string().optional(), fetch_scopes: z.array(z.enum(["accounts", "holder_info", "transactions"])).optional(), finished: z.boolean().optional(), finished_recent: z.boolean().optional(), from_date: z.string().optional(), id: z.string().optional(), interactive: z.boolean().optional(), locale: z.string().optional(), partial: z.boolean().optional(), store_credentials: z.boolean().optional(), success_at: z.string().optional(), to_date: z.string().optional(), updated_at: z.string().optional(), show_consent_confirmation: z.boolean().optional(), include_natures: z.array(z.string()).optional(), last_stage: stage.optional()}); export const connection = z.object({id: z.string(), secret: z.string(), provider_id: z.string(), provider_code: z.string(), provider_name: z.string(), daily_refresh: z.boolean(), customer_id: z.string(), created_at: z.string(), updated_at: z.string(), last_success_at: z.string(), status: z.enum(["active", "inactive", "disabled"]), country_code: z.string(), next_refresh_possible_at: z.string().optional(), store_credentials: z.boolean(), last_attempt: simplifiedAttempt, show_consent_confirmation: z.boolean(), last_consent_id: z.string()}); export const connectionResponse = z.object({data: connection.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 }; /** * Create a connection * * POST /connections */ export const createApiConnections = async (args: CreateApiConnectionsArgs, options?: CreateApiConnectionsOptions) => { const {baseUrl = "https://www.saltedge.com/api/v5", fetch: fetchFn = fetch, appId, secret} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (appId !== undefined) headers.set("App-id", appId) if (secret !== undefined) headers.set("Secret", secret) const url = `${baseUrl.replace(/\/+$/, '')}/connections${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(connectionResponse, await res.json()) };