import {z} from 'zod' export type InteractiveRow = {id: string, title: string, description?: (string | null) | undefined}; export type InteractiveSection = {title: string, rows: Array}; export type InteractiveButton = {id: string, title: string}; export type ChargeItem = {name: string, amountCents: number, quantity?: number | undefined, id?: (string | null) | undefined, imageUrl?: (string | null) | undefined}; export type ChargePayload = {referenceId: string, items: Array, pix?: ({code: string, key: string, keyType: 'CPF' | 'CNPJ' | 'EMAIL' | 'PHONE' | 'EVP', merchantName: string} | null) | undefined, paymentLink?: ({url: string} | null) | undefined, boleto?: ({digitableLine: string} | null) | undefined, shippingCents?: number | undefined, discountCents?: number | undefined, expiresAt?: (number | null) | undefined, expiresDescription?: (string | null) | undefined, imageUrl?: (string | null) | undefined}; export type ChargeStatusPayload = {referenceId: string, status: 'PAID' | 'FAILED' | 'CANCELED' | 'EXPIRED', description?: (string | null) | undefined}; export type InteractivePayload = {type: 'button' | 'list' | 'flow' | 'charge' | 'charge_status', body: string, buttonText?: (string | null) | undefined, sections?: (Array | null) | undefined, buttons?: (Array | null) | undefined, flowId?: (string | null) | undefined, charge?: (ChargePayload | null) | undefined, chargeStatus?: (ChargeStatusPayload | null) | undefined}; export type LocationPayload = {latitude: number, longitude: number, name?: (string | null) | undefined, address?: (string | null) | undefined}; export type ReactionPayload = {emoji: string, messageId: string}; export type SendMessageRequest = {receiver: string, templateName?: (string | null) | undefined, templateVariables?: (Array | null) | undefined, body?: (string | null) | undefined, interactive?: (InteractivePayload | null) | undefined, location?: (LocationPayload | null) | undefined, reaction?: (ReactionPayload | null) | undefined, charge?: (ChargePayload | null) | undefined, sender?: (string | null) | undefined, replyTo?: (string | null) | undefined, scheduled_at?: (string | null) | undefined, smartLinkParam?: (string | null) | undefined, smartLinkUrl?: (string | null) | undefined, type?: ('template' | 'text' | 'interactive' | 'location' | 'reaction' | null) | undefined, mode?: ('LIVE' | null) | undefined, media_url?: (string | null) | undefined}; export type CreateApiV1MessagesArgs = {'Idempotency-Key'?: string | undefined, body: SendMessageRequest}; export type CreateApiV1MessagesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const messageResponse = z.object({id: z.string().nullable().optional(), status: z.enum(["PENDING", "SCHEDULED", "PROCESSING", "SENT", "DELIVERED", "READ", "FAILED", "CANCELED"]), mode: z.literal("LIVE"), sender: z.string(), receiver: z.string(), body: z.string().nullable().optional(), cost: z.number().nullable().optional(), reason: z.string().nullable().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 }; /** * Enviar mensagem * * POST /v1/messages */ export const createApiV1Messages = async (args: CreateApiV1MessagesArgs, options?: CreateApiV1MessagesOptions) => { const {baseUrl = "https://api.ararahq.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/messages${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(messageResponse, await res.json()) };