import {z} from 'zod' export type ChatMeta = {type: 'phone' | 'widgetUser' | 'username' | 'facebook' | 'instagram' | 'telegram' | 'twitter' | 'viber' | 'whatsapp', value: string}; export type UpdateChatDto = {id: string, ownerId?: number | undefined, name?: string | undefined, pictureUrl?: string | undefined, groupId?: number | undefined, portals?: Array | undefined, members?: Array | undefined, active?: boolean | undefined, externalLines?: Array | undefined, meta?: Array | undefined}; export type PatchApiMessengerV1ChatsArgs = {body: UpdateChatDto}; export type PatchApiMessengerV1ChatsOptions = {baseUrl: string, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const externalLineResponseDto = z.object({id: z.string(), name: z.string(), icon: z.string(), externalId: z.string(), timestamp: z.number(), portal: z.string(), phoneNumber: z.string()}); export const attachedFile = z.object({id: z.object({}), entityId: z.string(), entityType: z.string(), lastModified: z.number(), originalFilename: z.string(), size: z.string(), url: z.string()}); export const messageRelation = z.object({action: z.enum(["create", "update", "delete"]), service: z.literal("crm"), entity: z.enum(["lead", "contact", "deal"]), name: z.string(), pictureUrl: z.string(), entityId: z.string()}); export const reference = z.object({chatId: z.string(), authorId: z.number(), messageId: z.string()}); export const metaBody = z.object({text: z.string(), attachedFiles: z.array(z.string()), url: z.string()}); export const messageMeta = z.object({entity: z.string(), type: z.string(), accountName: z.string(), accountImage: z.string(), body: z.array(metaBody)}); export const messageResponseDto = z.object({id: z.string().optional(), timestamp: z.number().optional(), message: z.string(), type: z.enum(["MESSAGE", "AUDIO", "VIDEO", "GIF", "SYSTEM"]).optional(), chatId: z.string(), readBy: z.array(z.number()).optional(), externalLine: externalLineResponseDto, attachedFiles: z.array(attachedFile).optional(), relations: z.array(messageRelation).optional(), externalAuthorId: z.string().optional(), externalId: z.string().optional(), ref: reference.optional(), meta: messageMeta.optional()}); export const chatMeta = z.object({type: z.enum(["phone", "widgetUser", "username", "facebook", "instagram", "telegram", "twitter", "viber", "whatsapp"]), value: z.string()}); export const chatSettingsDto = z.object({muteUntil: z.array(z.number())}); export const chatResponseDto = z.object({id: z.string(), members: z.string(), timestamp: z.number(), ownerId: z.number(), name: z.string(), pictureUrl: z.string(), type: z.enum(["PRIVATE", "PUBLIC", "GROUP", "DIRECT", "EXTERNAL"]), groupId: z.number(), portals: z.array(z.string()), externalLines: z.array(externalLineResponseDto), lastMessage: messageResponseDto, meta: z.array(chatMeta), active: z.boolean(), unreadCount: z.number(), pinned: z.boolean(), pinnedTimestamp: z.number(), setting: chatSettingsDto}); 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 }; /** * Update a chat * * PATCH /messenger/v1/chats */ export const patchApiMessengerV1Chats = async (args: PatchApiMessengerV1ChatsArgs, options: PatchApiMessengerV1ChatsOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/messenger/v1/chats${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PATCH", 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(chatResponseDto, await res.json()) };