import {z} from 'zod' export type ConversationMessageTextPostDto = {text?: string | undefined, attachmentIds?: Array | undefined}; export type ConversationPostDto = {id?: string | undefined, attachedEntityId?: string | undefined, subject: string, status?: ('ACTIVE' | 'INACTIVE' | 'REMOVED') | undefined, readStatus?: ('READ' | 'UNREAD') | undefined, resolutionStatus?: ('OPEN' | 'CLOSED' | 'DRAFT') | undefined, message: ConversationMessageTextPostDto}; export type MultiParamConversationPostDto = {data: Array}; export type CreateApiV6ConversationsArgs = {body: MultiParamConversationPostDto}; export type CreateApiV6ConversationsOptions = {baseUrl?: string | undefined, EmbedToken?: string | undefined, fetch?: typeof fetch | undefined}; export const httpStatus = z.union([z.literal(200), z.literal(400), z.literal(401), z.literal(403), z.literal(404), z.literal(500)]); export const companyExpanded = z.object({id: z.string(), name: z.string().optional()}); export const authorInfo = z.object({userId: z.string(), email: z.string().nullable()}); export const latestMessageDto = z.object({id: z.string(), author: authorInfo, text: z.string()}); export const conversationGetDto = z.object({id: z.string(), attachedEntityId: z.string().nullable(), company: companyExpanded, subject: z.string(), author: authorInfo, latestMessage: latestMessageDto, status: z.enum(["ACTIVE", "INACTIVE", "REMOVED"]), readStatus: z.enum(["READ", "UNREAD"]), resolutionStatus: z.enum(["OPEN", "CLOSED", "DRAFT"]), createdDateTime: z.string(), lastUpdatedDateTime: z.string()}); export const errorItem = z.object({type: z.enum(["UNKNOWN_ERROR", "INVALID_TOKEN", "EXPIRED_TOKEN", "FORBIDDEN", "BAD_REQUEST", "JSON_ERROR", "DUPLICATE", "REQUIRED", "INVALID_VALUE", "NOT_MODIFIABLE", "INVALID_FORMAT", "NOT_FOUND"]).optional(), message: z.string().optional(), param: z.string().optional()}); export const multiResponseConversationGetDto = z.object({result: z.enum(["SUCCESS", "FAILURE"]).optional(), statusCode: httpStatus.optional(), data: conversationGetDto.optional(), error: z.array(errorItem).optional()}); export const responseListMultiResponseConversationGetDto = z.object({result: z.enum(["SUCCESS", "FAILURE"]).optional(), data: z.array(multiResponseConversationGetDto).optional(), error: z.array(errorItem).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 }; /** * Save conversations * * POST /v6/conversations */ export const createApiV6Conversations = async (args: CreateApiV6ConversationsArgs, options?: CreateApiV6ConversationsOptions) => { const {baseUrl = "https://sandbox.tight.com", fetch: fetchFn = fetch, EmbedToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (EmbedToken !== undefined) headers.set('authorization', `Bearer ${EmbedToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/v6/conversations${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(responseListMultiResponseConversationGetDto, await res.json()) };