import {z} from 'zod' export type MessageType = 'audio' | 'contacts' | 'document' | 'hsm' | 'image' | 'location' | 'text' | 'video' | 'voice' | 'unknown'; export type Text = {body: string}; export type Provider = {name: string}; export type Audio = {id: string} | {provider: Provider, link: string}; export type Image = {caption: string, id: string} | {provider: Provider, link: string, caption: string}; export type Document = {caption: string, id: string, filename: string} | {provider: Provider, caption: string, link: string, filename: string}; export type Video = {caption: string, id: string} | {provider: Provider, caption: string, link: string}; export type Language = {policy: 'fallback' | 'deterministic', code: string}; export type Currency = {currency_code: string, amount_1000: number}; export type DateTimeComponent = {day_of_week?: number | undefined, day_of_month?: number | undefined, year?: number | undefined, month?: number | undefined, hour?: number | undefined, minute?: number | undefined}; export type DateTimeUnixEpoch = {timestamp?: number | undefined}; export type DateTimeObject = {component?: DateTimeComponent | undefined, unix_epoch?: DateTimeUnixEpoch | undefined}; export type LocalizableParam = {default: string, currency?: Currency | undefined, date_time?: DateTimeObject | undefined}; export type Hsm = {namespace: string, element_name: string, language: Language, localizable_params: Array}; export type Address = {city: string, country: string, country_code: string, state: string, street: string, type: string, zip: string}; export type Email = {email: string, type: string}; export type Name = {first_name?: string | undefined, formatted_name: string, last_name?: string | undefined, suffix?: string | undefined, prefix?: string | undefined}; export type Org = {company: string, department?: string | undefined, title?: string | undefined}; export type Phone = {phone?: string | undefined, type?: string | undefined, wa_id?: string | undefined}; export type Url = {url?: string | undefined, type?: string | undefined}; export type Contact = {addresses?: Array
| undefined, birthday?: string | undefined, emails?: Array | undefined, ims?: Array | undefined, name?: Name | undefined, org?: Org | undefined, phones?: Array | undefined, urls?: Array | undefined}; export type Location = {longitude: string, latitude: string, name: string, address: string}; export type SendMessageRequestBody = {to: string, type?: MessageType | undefined, recipient_type?: ('individual' | 'group') | undefined, text?: Text | undefined, audio?: Audio | undefined, image?: Image | undefined, document?: Document | undefined, video?: Video | undefined, hsm?: Hsm | undefined, ttl?: Record | undefined, contacts?: Array | undefined, location?: Location | undefined, preview_url?: boolean | undefined}; export type CreateApiMessagesArgs = {body: SendMessageRequestBody}; export type CreateApiMessagesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const meta = z.object({version: z.string().optional(), api_status: z.enum(["deprecated", "experimental", "stable"]).optional()}); export const error = z.object({code: z.number().int().optional(), title: z.string().optional(), details: z.string().optional(), href: z.string().optional()}); export const message = z.object({id: z.string().optional()}); export const messageResponse = z.object({meta: meta.optional(), errors: z.array(error).optional(), messages: z.array(message).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 }; /** * Send-Message * * POST /messages */ export const createApiMessages = async (args: CreateApiMessagesArgs, options?: CreateApiMessagesOptions) => { const {baseUrl = "http://example.com/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) 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(messageResponse, await res.json()) };