import {z} from 'zod' export type CreateApiReportsArgs = {customer_id: string, report_types: Array, include_account_natures?: Array | undefined, currency_code: string, from_date: string, to_date: string}; export type CreateApiReportsOptions = {baseUrl?: string | undefined, appId?: string | undefined, secret?: string | undefined, fetch?: typeof fetch | undefined}; export const basicReport = z.object({id: z.string(), customer_id: z.string(), customer_identifier: z.string(), status: z.enum(["initialized", "calculating", "success", "failed"]), connection_ids: z.array(z.string()), include_account_natures: z.array(z.string()).optional()}); export const createdReportResponse = z.object({data: basicReport.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 Financial Insights report * * POST /reports */ export const createApiReports = async (args: CreateApiReportsArgs, options?: CreateApiReportsOptions) => { const {baseUrl = "https://www.saltedge.com/api/v5", fetch: fetchFn = fetch, appId, secret} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.customer_id != null) query.append("customer_id", String(args.customer_id)) for (const item of args.report_types ?? []) query.append("report_types", String(item)) for (const item of args.include_account_natures ?? []) query.append("include_account_natures", String(item)) if (args.currency_code != null) query.append("currency_code", String(args.currency_code)) if (args.from_date != null) query.append("from_date", String(args.from_date)) if (args.to_date != null) query.append("to_date", String(args.to_date)) if (appId !== undefined) headers.set("App-id", appId) if (secret !== undefined) headers.set("Secret", secret) const url = `${baseUrl.replace(/\/+$/, '')}/reports${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createdReportResponse, await res.json()) };