import {z} from 'zod' export type UserPreferences = {customer_id?: string | undefined, email_id?: string | undefined, categories?: {[key: string]: boolean} | undefined, opt_in_status: 'DOUBLE_OPTED_IN' | 'OPTED_OUT' | 'OPT_IN_PENDING', channel: 'email'}; export type OptinRequest = {user_preferences: UserPreferences}; export type UpdateApiV10OptInManagementUserPreferencesArgs = {'MOE-APPKEY': string, 'MOE-PROJECT-CODE'?: string | undefined, body: OptinRequest}; export type UpdateApiV10OptInManagementUserPreferencesOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const optinSuccessResponse = z.object({message: z.string().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 }; /** * Update User Email Opt-in Preferences * * PUT /v1.0/opt-in-management/user-preferences */ export const updateApiV10OptInManagementUserPreferences = async (args: UpdateApiV10OptInManagementUserPreferencesArgs, options?: UpdateApiV10OptInManagementUserPreferencesOptions) => { const {baseUrl = "https://api-01.moengage.com", 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['MOE-PROJECT-CODE'] != null) headers.set("MOE-PROJECT-CODE", String(args['MOE-PROJECT-CODE'])) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1.0/opt-in-management/user-preferences${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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(optinSuccessResponse, await res.json()) };