import {z} from 'zod' export type GetApiApiV2SchedulesArgs = {page?: number | undefined, limit?: number | undefined, status?: ('a' | 'c' | 'x') | undefined, orderBy?: ('id' | 'nextSend' | 'lastSend') | undefined, direction?: ('asc' | 'desc') | undefined}; export type GetApiApiV2SchedulesOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const messageSession = z.object({id: z.number().int(), startTime: z.string().nullable(), text: z.string().nullable(), source: z.string().nullable(), referenceId: z.string().nullable(), price: z.number().nullable(), numbersCount: z.number().int().nullable(), destination: z.enum(["t", "s", "v"]).nullable(), initiatorId: z.number().int().nullable(), title: z.string().nullable()}).nullable(); export const messagesIcs = z.object({id: z.number().int(), nextSend: z.string(), rrule: z.string().nullable(), session: messageSession, lastSent: z.string().nullable(), contactName: z.string(), parameters: z.object({text: z.string(), recipients: z.object({contacts: z.array(z.number().int()), groups: z.array(z.number().int()), numbers: z.array(z.string()), filteredViews: z.array(z.number().int())})}), type: z.enum(["Once", "Hourly", "Daily", "Weekly", "Monthly", "Yearly"]), summary: z.string(), textParameters: z.object({cost: z.number().nullable(), parts: z.number().int().nullable(), chars: z.number().int().nullable(), encoding: z.enum(["ISO-8859-1", "UTF-16BE"]).nullable(), countries: z.array(z.string()).nullable(), charsetLabel: z.string().nullable()}), firstOccurrence: z.string().nullable(), lastOccurrence: z.string().nullable(), recipientsCount: z.number().int().nullable(), timezone: z.string(), completed: z.boolean(), avatar: z.string().nullable(), createdAt: z.string()}); export const getAllScheduledMessagesPaginatedResponse = z.object({page: z.number().int(), pageCount: z.number().int(), limit: z.number().int(), resources: z.array(messagesIcs)}); 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 all scheduled messages * * GET /api/v2/schedules */ export const getApiApiV2Schedules = async (args: GetApiApiV2SchedulesArgs, options?: GetApiApiV2SchedulesOptions) => { 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.page != null) query.append("page", String(args.page)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.status != null) query.append("status", String(args.status)) 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/schedules${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(getAllScheduledMessagesPaginatedResponse, await res.json()) };