import {z} from 'zod' export type PersonalizedPreviewRequest = {request_id: string, personalization_content: {payload?: {[key: string]: unknown} | undefined, custom_template_data?: ({template_id?: string | undefined, version?: string | undefined}) | undefined}, user_details?: ({identifier?: string | undefined, identifier_value?: string | undefined}) | undefined, personalization_details: {channel: 'EMAIL' | 'PUSH' | 'SMS', event_name?: string | undefined, user_attributes?: {[key: string]: unknown} | undefined, event_attributes?: {[key: string]: unknown} | undefined}}; export type CreateApiPersonalizationPreviewArgs = {'MOE-APPKEY': string, 'data-compression'?: boolean | undefined, body: PersonalizedPreviewRequest}; export type CreateApiPersonalizationPreviewOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const personalizedPreviewResponse = z.object({personalized_content: z.object({payload: z.record(z.string(), z.unknown()).optional()}).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 }; /** * Personalized Preview * * POST /personalization/preview */ export const createApiPersonalizationPreview = async (args: CreateApiPersonalizationPreviewArgs, options?: CreateApiPersonalizationPreviewOptions) => { const {baseUrl = "https://api-01.moengage.com/core-services/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['MOE-APPKEY'] != null) headers.set("MOE-APPKEY", String(args['MOE-APPKEY'])) if (args['data-compression'] != null) headers.set("data-compression", String(args['data-compression'])) if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/personalization/preview${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(personalizedPreviewResponse, await res.json()) };