import {z} from 'zod' export type GetApiApiV2HistoryArgs = {limit?: number | undefined, lastId?: number | undefined, query?: string | undefined, orderBy?: ('id' | 'phone' | 'sender' | 'firstName' | 'lastName' | 'messageTime') | undefined, direction?: ('asc' | 'desc') | undefined}; export type GetApiApiV2HistoryOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const messageOut = z.object({id: z.number().int(), sender: z.string().nullable().optional(), receiver: z.string().optional(), text: z.string(), status: z.enum(["q", "s", "e", "r", "a", "d", "b", "f", "u", "j", "i", "p", "h"]), rejectReason: z.enum(["a", "f", "l", "c", "u", "b", "s", "m", "n", "i", "if", "d", "t", "e", "h", "k", "r", "g", "j", "w", "v", "q", "x", "o", "p"]).optional(), contactId: z.number().int().nullable(), sessionId: z.number().int().nullable(), messageTime: z.string(), avatar: z.string().nullable(), deleted: z.boolean().optional(), deliveredAt: z.string().nullable().optional(), charset: z.string().nullable(), charsetLabel: z.string().nullable(), firstName: z.string().nullable(), lastName: z.string().nullable(), country: z.string().nullable(), phone: z.string().nullable().optional(), price: z.number().nullable().optional(), partsCount: z.number().int().nullable(), fromEmail: z.string().nullable().optional(), fromNumber: z.string().nullable().optional(), senderSource: z.object({id: z.number().int().nullable().optional(), phone: z.string().nullable().optional(), type: z.string().nullable().optional(), countryId: z.string().nullable().optional(), label: z.string().nullable().optional(), status: z.string().nullable().optional(), carrierStatus: z.string().nullable().optional()}).optional(), session: z.object({id: z.number().int().nullable().optional(), startTime: z.string().nullable().optional(), text: z.string().nullable().optional(), price: z.number().nullable().optional(), numbersCount: z.number().int().nullable().optional(), destination: z.string().nullable().optional(), source: z.string().nullable().optional(), referenceId: z.string().nullable().optional(), initiatorId: z.number().int().nullable().optional()}).optional()}); export const getOutboundMessagesHistoryPaginatedResponse = z.object({lastId: z.number().int().nullable(), nextLastId: z.number().int(), limit: z.number().int(), resources: z.array(messageOut)}); 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 }; /** * Get history * * GET /api/v2/history */ export const getApiApiV2History = async (args: GetApiApiV2HistoryArgs, options?: GetApiApiV2HistoryOptions) => { const {baseUrl = "https://rest.textmagic.com", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.lastId != null) query.append("lastId", String(args.lastId)) if (args.query != null) query.append("query", String(args.query)) if (args.orderBy != null) query.append("orderBy", String(args.orderBy)) if (args.direction != null) query.append("direction", String(args.direction)) if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/history${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(getOutboundMessagesHistoryPaginatedResponse, await res.json()) };