import {z} from 'zod' export type WebhookDeliveryStatus = 'delivered' | 'failed'; export type WebhookEventType = 'trade.pending' | 'trade.completed' | 'trade.flagged' | 'trade.deleted' | 'withdrawal.pending' | 'withdrawal.processing' | 'withdrawal.rejected' | 'withdrawal.completed' | 'withdrawal.reversed'; export type GetApiTransactionsWebhooksArgs = {page?: number | undefined, size?: number | undefined, sort?: string | undefined, filter?: string | undefined, exports?: boolean | undefined, search?: string | undefined, startDate?: string | undefined, endDate?: string | undefined, reference?: string | undefined, status?: WebhookDeliveryStatus | undefined, eventName?: WebhookEventType | undefined}; export type GetApiTransactionsWebhooksOptions = {baseUrl?: string | undefined, appId?: string | undefined, appSecret?: string | undefined, breetEnv?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookEventType = z.enum(["trade.pending", "trade.completed", "trade.flagged", "trade.deleted", "withdrawal.pending", "withdrawal.processing", "withdrawal.rejected", "withdrawal.completed", "withdrawal.reversed"]); export const webhookDeliveryStatus = z.enum(["delivered", "failed"]); export const webhookDeliveryAttempt = z.object({attemptedAt: z.string().optional(), responseStatus: z.number().int().optional(), responseBody: z.unknown(), errorMessage: z.string().optional(), errorStatusCode: z.number().int().optional()}); export const webhookEvent = z.object({id: z.string().optional(), integration: z.string().optional(), reference: z.string().optional(), eventType: webhookEventType.optional(), payload: z.unknown(), url: z.string().optional(), status: webhookDeliveryStatus.optional(), attemptsCount: z.number().int().optional(), attempts: z.array(webhookDeliveryAttempt).optional(), deliveredAt: z.string().nullable().optional(), lastAttemptAt: z.string().nullable().optional(), expireAt: z.string().optional(), createdAt: z.string().optional(), updatedAt: z.string().optional()}); export const paginationMeta = z.object({pages: z.number().int().optional(), prevPage: z.number().int().nullable().optional(), nextPage: z.number().int().nullable().optional(), page: z.number().int().optional(), totalDocs: z.number().int().optional(), hasPrevPage: z.boolean().optional(), hasNextPage: z.boolean().optional()}); export const getApiTransactionsWebhooksResponse = z.object({success: z.boolean().optional(), data: z.array(webhookEvent).optional(), meta: paginationMeta.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 }; /** * List outgoing webhook events * * GET /transactions/webhooks */ export const getApiTransactionsWebhooks = async (args: GetApiTransactionsWebhooksArgs, options?: GetApiTransactionsWebhooksOptions) => { const {baseUrl = "https://api.breet.io/v1", fetch: fetchFn = fetch, appId, appSecret, breetEnv} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.size != null) query.append("size", String(args.size)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.filter != null) query.append("filter", String(args.filter)) if (args.exports != null) query.append("exports", String(args.exports)) if (args.search != null) query.append("search", String(args.search)) if (args.startDate != null) query.append("startDate", String(args.startDate)) if (args.endDate != null) query.append("endDate", String(args.endDate)) if (args.reference != null) query.append("reference", String(args.reference)) if (args.status != null) query.append("status", String(args.status)) if (args.eventName != null) query.append("eventName", String(args.eventName)) if (appId !== undefined) headers.set("x-app-id", appId) if (appSecret !== undefined) headers.set("x-app-secret", appSecret) if (breetEnv !== undefined) headers.set("X-Breet-Env", breetEnv) const url = `${baseUrl.replace(/\/+$/, '')}/transactions/webhooks${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiTransactionsWebhooksResponse, await res.json()) };