import {z} from 'zod' export type PayloadChannel = {recipient: string, personalized_attributes?: {[key: string]: unknown} | undefined, sender_attributes?: Array | undefined, personalized_attachments?: {[key: string]: string} | undefined, live_activity_attributes?: ({la_type?: ('start' | 'update' | 'end') | undefined, attribute_info?: {[key: string]: unknown} | undefined, content_state?: {[key: string]: unknown} | undefined}) | undefined}; export type InformRequest = {alert_id?: string | undefined, alert_reference_name?: string | undefined, user_id?: string | undefined, transaction_id: string, payloads: {SMS?: PayloadChannel | undefined, EMAIL?: PayloadChannel | undefined, PUSH?: PayloadChannel | undefined}}; export type CreateApiAlertsSendArgs = {body: InformRequest}; export type CreateApiAlertsSendOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, moeAppKey?: string | undefined, fetch?: typeof fetch | undefined}; export const channelStatus = z.object({message: z.string().optional(), err_code: z.string().optional(), status_code: z.number().int().optional()}); export const informSuccessResponse = z.object({message: z.string().optional(), request_id: z.string().optional(), SMS: channelStatus.optional(), EMAIL: channelStatus.optional(), PUSH: channelStatus.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 Transactional Alert * * POST /alerts/send */ export const createApiAlertsSend = async (args: CreateApiAlertsSendArgs, options?: CreateApiAlertsSendOptions) => { const {baseUrl = "https://api-01.moengage.com/v1.0", fetch: fetchFn = fetch, basicAuth, moeAppKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) if (moeAppKey !== undefined) headers.set("MOE-APPKEY", moeAppKey) const url = `${baseUrl.replace(/\/+$/, '')}/alerts/send${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(informSuccessResponse, await res.json()) };