import {z} from 'zod' export type GetApiApiMessagesArgs = {cursor?: (string | null) | undefined, limit?: number | undefined, order_by?: ('created_datetime:asc' | 'created_datetime:desc') | undefined, ticket_id?: (number | null) | undefined}; export type GetApiApiMessagesOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const legacyChannelSlug = z.enum(["aircall", "api", "chat", "contact_form", "email", "facebook", "facebook-mention", "facebook-messenger", "facebook-recommendations", "help-center", "instagram-ad-comment", "instagram-comment", "instagram-direct-message", "instagram-mention", "internal-note", "phone", "sms", "twitter", "twitter-direct-message", "whatsapp", "yotpo-review"]); export const ticketVia = z.enum(["aircall", "api", "chat", "contact_form", "email", "facebook", "facebook-mention", "facebook-messenger", "facebook-recommendations", "form", "gorgias_chat", "help-center", "helpdesk", "instagram", "instagram-ad-comment", "instagram-comment", "instagram-direct-message", "instagram-mention", "internal-note", "offline_capture", "phone", "rule", "self_service", "shopify", "sms", "twilio", "twitter", "twitter-direct-message", "whatsapp", "yotpo", "yotpo-review", "zendesk"]); export const ticketMessageSourceAddress = z.object({name: z.string().optional(), address: z.string().optional()}); export const ticketMessageSource = z.object({type: z.string(), to: z.array(ticketMessageSourceAddress).optional(), cc: z.array(ticketMessageSourceAddress).optional(), bcc: z.array(ticketMessageSourceAddress).optional(), from: ticketMessageSourceAddress.optional(), extra: z.unknown()}); export const ticketMessageUserOrCustomer = z.object({id: z.number().int(), email: z.string(), name: z.string(), firstname: z.string(), lastname: z.string(), meta: z.unknown()}); export const ticketMessageAuthCustomerIdentityService = z.object({id: z.string(), name: z.string()}); export const ticketMessageAuthCustomerIdentity = z.object({service: ticketMessageAuthCustomerIdentityService, identifier: z.string()}); export const ticketMessageIntent = z.object({name: z.string(), rejected: z.boolean(), is_user_feedback: z.boolean()}); export const ticketMessageAttachment = z.object({url: z.string(), name: z.string().optional(), size: z.number().int().optional(), content_type: z.string(), public: z.boolean().optional(), extra: z.unknown()}); export const ticketMessageMacro = z.object({id: z.number().int().gt(0)}); export const ticketMessageSendingError = z.object({error: z.string()}); export const ticketMessageRepliedByOrTo = z.object({integration_id: z.number().int(), message_id: z.string(), created_datetime: z.string(), body_text: z.string(), source: ticketMessageSource, customer: ticketMessageUserOrCustomer, user: ticketMessageUserOrCustomer}); export const ticketMessage = z.object({id: z.number().int(), uri: z.string(), message_id: z.string(), ticket_id: z.number().int(), external_id: z.string(), public: z.boolean().optional(), channel: z.union([legacyChannelSlug, z.string()]), via: ticketVia, source: ticketMessageSource, sender: ticketMessageUserOrCustomer, auth_customer_identity: ticketMessageAuthCustomerIdentity, integration_id: z.number().int(), intents: z.array(ticketMessageIntent), rule_id: z.number().int(), from_agent: z.boolean(), receiver: ticketMessageUserOrCustomer, subject: z.string(), body_text: z.string(), body_html: z.string(), body_url: z.string(), stripped_text: z.string(), stripped_html: z.string(), stripped_signature: z.string(), attachments: z.array(ticketMessageAttachment), macros: z.array(ticketMessageMacro).optional(), actions: z.array(z.object({})), headers: z.object({}).optional(), imported: z.boolean(), meta: z.unknown(), created_datetime: z.string(), processed_datetime: z.string(), deleted_datetime: z.string().optional(), sent_datetime: z.string(), failed_datetime: z.string(), opened_datetime: z.string(), last_sending_error: ticketMessageSendingError, is_retriable: z.boolean(), replied_by: ticketMessageRepliedByOrTo.optional(), replied_to: ticketMessageRepliedByOrTo.optional()}); export const cursorPaginationMeta = z.object({prev_cursor: z.string(), next_cursor: z.string(), total_resources: z.number().int()}); export const getApiApiMessagesResponse = z.object({object: z.string(), uri: z.string(), data: z.array(ticketMessage), meta: cursorPaginationMeta}); 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 messages * * GET /api/messages */ export const getApiApiMessages = async (args: GetApiApiMessagesArgs, options?: GetApiApiMessagesOptions) => { const {baseUrl = "https://your-domain.gorgias.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.order_by != null) query.append("order_by", String(args.order_by)) if (args.ticket_id != null) query.append("ticket_id", String(args.ticket_id)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/messages${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(getApiApiMessagesResponse, await res.json()) };