import {z} from 'zod' export type SubmissionEntry = {from?: ({type: 'INTERNATIONAL' | 'ALPHANUMERIC' | 'SHORTCODE' | 'REPLIABLE', address?: string | undefined}) | undefined, to: Array<{type?: ('INTERNATIONAL' | 'GROUP') | undefined, address?: string | undefined, name?: string | undefined, id?: string | undefined, fields?: Array | undefined}>, routingGroup?: ('ECONOMY' | 'STANDARD' | 'PREMIUM') | undefined, encoding?: ('TEXT' | 'UNICODE' | 'BINARY') | undefined, longMessageMaxParts?: number | undefined, body: string, userSuppliedId?: string | undefined, protocolId?: ('IMPLICIT' | 'SHORT_MESSAGE_TYPE_0' | 'REPLACE_MESSAGE_1' | 'REPLACE_MESSAGE_2' | 'REPLACE_MESSAGE_3' | 'REPLACE_MESSAGE_4' | 'REPLACE_MESSAGE_5' | 'REPLACE_MESSAGE_6' | 'REPLACE_MESSAGE_7' | 'RETURN_CALL' | 'ME_DOWNLOAD' | 'ME_DEPERSONALIZE' | 'SIM_DOWNLOAD') | undefined, messageClass?: ('FLASH_SMS' | 'ME_SPECIFIC' | 'SIM_SPECIFIC' | 'TE_SPECIFIC') | undefined, deliveryReports?: ('ALL' | 'ERRORS' | 'NONE') | undefined}; export type CreateApiMessagesArgs = {'deduplication-id'?: number | undefined, 'auto-unicode'?: boolean | undefined, 'schedule-date'?: string | undefined, 'schedule-description'?: string | undefined, body: Array}; export type CreateApiMessagesOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const message = z.object({id: z.string(), type: z.enum(["SENT", "RECEIVED"]), from: z.string().optional(), to: z.string(), body: z.string(), encoding: z.enum(["TEXT", "UNICODE", "BINARY"]).optional(), protocolId: z.number().int().optional(), messageClass: z.number().int().optional(), numberOfParts: z.number().int().optional(), creditCost: z.number().optional(), submission: z.object({id: z.string(), date: z.string()}).optional(), status: z.object({id: z.string(), type: z.enum(["ACCEPTED", "SCHEDULED", "SENT", "DELIVERED", "UNKNOWN", "FAILED"]), subtype: z.enum(["EXPIRED", "HANDSET_ERROR", "BLOCKED", "NOT_SENT"]).optional()}), relatedSentMessageId: z.string().optional(), userSuppliedId: z.string().optional()}); export const createApiMessagesResponse = z.array(message); 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 }; /** * Send Messages * * POST /messages */ export const createApiMessages = async (args: CreateApiMessagesArgs, options?: CreateApiMessagesOptions) => { const {baseUrl = "https://api.bulksms.com/v1", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['deduplication-id'] != null) query.append("deduplication-id", String(args['deduplication-id'])) if (args['auto-unicode'] != null) query.append("auto-unicode", String(args['auto-unicode'])) if (args['schedule-date'] != null) query.append("schedule-date", String(args['schedule-date'])) if (args['schedule-description'] != null) query.append("schedule-description", String(args['schedule-description'])) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/messages${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(createApiMessagesResponse, await res.json()) };