import {z} from 'zod' export type Geofences = {name: string, latitude: string, longitude: string, radius: string, dwell_time_value?: string | undefined, dwell_time_granularity?: ('MINUTES' | 'HOURS' | 'DAYS') | undefined, response_time_value: string, response_time_granularity: 'MINUTES' | 'HOURS' | 'DAYS', triggered_at: 'ENTRY' | 'EXIT' | 'dwell'}; export type PlatformSpecificDetails = {android?: ({push_amp_plus_enabled?: boolean | undefined}) | undefined, ios?: ({send_to_all_eligible_device?: boolean | undefined, exclude_provisional_push_devices?: boolean | undefined, send_to_only_provisional_push_enabled_devices?: boolean | undefined}) | undefined}; export type PushBasicDetails = {name: string, business_event?: string | undefined, tags?: Array | undefined, team?: string | undefined, platforms: Array<'ANDROID' | 'IOS' | 'WEB'>, broadcast_live_activity_id?: string | undefined, geofences?: Geofences | undefined, send_to_triggered_platform_only?: boolean | undefined, platform_specific_details: PlatformSpecificDetails}; export type UserAttributeFilter = {filter_type: 'user_attributes', data_type: 'string' | 'double' | 'datetime' | 'bool', category?: string | undefined, name: string, operator: string, value: unknown, case_sensitive?: boolean | undefined, negate?: boolean | undefined, project_name?: string | undefined}; export type ActionFilter = {filter_type: 'actions', action_name: string, execution?: ({type?: ('atleast' | 'atmost' | 'exactly') | undefined, count?: number | undefined}) | undefined, executed?: boolean | undefined, attributes?: FilterGroup | undefined, condition?: string | undefined}; export type CustomSegmentFilter = {filter_type: 'custom_segments', name?: string | undefined, id: string}; export type FilterGroup = {filter_operator: 'and' | 'or', filters: Array}; export type PushTriggerCondition = {included_filters?: FilterGroup | undefined, secondary_included_filters?: FilterGroup | undefined, trigger_delay_type?: ('DELAY' | 'ASAP' | 'INTELLIGENT_DELAY') | undefined, trigger_delay_value?: number | undefined, trigger_delay_granularity?: ('MINUTES' | 'HOURS' | 'DAYS') | undefined, trigger_relation?: ('BEFORE' | 'AFTER') | undefined, trigger_attr?: Record | undefined, intelligent_delay_optimization?: ({min_delay_value?: number | undefined, min_delay_granularity?: ('MINUTES' | 'HOURS') | undefined, max_delay_value?: number | undefined, max_delay_granularity?: ('HOURS' | 'DAYS') | undefined}) | undefined}; export type VariationDetails = {distribution_type: 'SHERPA' | 'MANUAL', no_of_variations: number, manual_distribution_percentage?: {[key: string]: string} | undefined, sherpa_campaign_duration?: number | undefined, sherpa_distribution_metric?: ('OPEN RATE' | 'CLICK RATE' | 'BOTH') | undefined}; export type KeyValuePair = {key: string, value: string}; export type CarouselContent = {slider_transition: 'manual' | 'automatic', slide_data: Array<{image_url: string, image_click_action?: ('DEEPLINKING' | 'RICH_LANDING' | 'NAVIGATE_TO_A_SCREEN') | undefined, image_click_action_value?: string | undefined, key_value_pairs?: Array | undefined}>}; export type AndroidBasicDetails = {notification_channel: string, include_app_name_and_time?: boolean | undefined, background_color_code?: string | undefined, app_name_color_code?: string | undefined, notification_control_color?: ('LIGHT' | 'DARK') | undefined, include_title_and_message?: boolean | undefined, apply_background_color_in_text_editor?: boolean | undefined, title: string, message: string, summary?: string | undefined, image_url?: string | undefined, image_scaling?: ('FIT_INSIDE_IMAGE_CONTAINER' | 'FILL_IMAGE_CONTAINER') | undefined, banner_image_url?: string | undefined, input_gif_url?: string | undefined, collapsed_push_notification?: string | undefined, carousel_content?: CarouselContent | undefined, default_click_action: 'DEEPLINKING' | 'NAVIGATE_TO_A_SCREEN' | 'RICH_LANDING', default_click_action_value: string, key_value_pairs?: Array | undefined}; export type AndroidTimer = {timer_ends_at: 'DURATION' | 'SPECIFIC_TIME_USER_TIMEZONE' | 'SPECIFIC_TIME_CAMPAIGN_TIMEZONE', specific_time?: string | undefined, time_period?: string | undefined, personalized_value: boolean, duration_hour?: string | undefined, duration_minute?: string | undefined}; export type AndroidButton = {btn_name: string, click_action_type: 'DEEPLINKING' | 'NAVIGATE_TO_A_SCREEN' | 'RICH_LANDING' | 'CALL' | 'SHARE' | 'COPY' | 'SET_USER_ATTRIBUTE' | 'TRACK_EVENT' | 'CUSTOM_ACTION', click_action_name?: string | undefined, click_action_value: string, key_value_pairs?: Array | undefined}; export type AndroidAdvanced = {coupon_code?: string | undefined, icon_type_in_notification?: string | undefined, use_large_icon?: boolean | undefined, make_notification_sticky?: boolean | undefined, dismiss_button_text?: string | undefined, auto_dismiss_notification?: boolean | undefined, auto_dismiss_notification_time_value?: number | undefined, auto_dismiss_notification_time_granularity?: ('DAYS' | 'HOURS' | 'MINUTES') | undefined, group_key?: string | undefined, collapse_replace_key?: string | undefined}; export type AndroidTemplateBackup = {title: string, message: string, summary?: string | undefined, image_url?: string | undefined, default_click_action: 'DEEPLINKING' | 'NAVIGATE_TO_A_SCREEN' | 'RICH_LANDING', default_click_action_value: string, key_value_pairs?: Array | undefined}; export type AndroidPushContent = {template_type: 'BASIC' | 'STYLIZED_BASIC' | 'SIMPLE_IMAGE_CAROUSEL' | 'IMAGE_BANNER_WITH_TEXT' | 'TIMER' | 'TIMER_WITH_PROGRESS_BAR' | 'Custom', custom_template_id?: string | undefined, custom_template_version?: number | undefined, basic_details?: AndroidBasicDetails | undefined, timer?: AndroidTimer | undefined, buttons?: Array | undefined, advanced?: AndroidAdvanced | undefined, template_backup?: AndroidTemplateBackup | undefined}; export type IOSCarouselContent = {slider_transition: 'MANUAL' | 'AUTOMATIC', slide_data: Array<{image_url: string, image_click_action?: ('DEEPLINKING' | 'RICH_LANDING' | 'NAVIGATE_TO_A_SCREEN') | undefined, image_click_action_value?: string | undefined, key_value_pairs?: Array | undefined}>}; export type IOSBasicDetails = {background_color_code?: string | undefined, apply_background_color_in_text_editor?: boolean | undefined, title: string, message: string, subtitle?: string | undefined, allow_bg_refresh?: boolean | undefined, rich_media_type?: ('Image' | 'Video' | 'GIF') | undefined, rich_media_value?: string | undefined, image_url?: string | undefined, input_gif_url?: string | undefined, carousel_content?: IOSCarouselContent | undefined, default_click_action?: ('DEEPLINKING' | 'NAVIGATE_TO_A_SCREEN' | 'RICH_LANDING') | undefined, default_click_action_value?: string | undefined, key_value_pairs?: Array | undefined}; export type IOSButton = {button_category: string}; export type IOSAdvanced = {coupon_code?: string | undefined, sound_file?: string | undefined, enable_ios_badge?: boolean | undefined, group_key?: string | undefined, collapse_replace_key?: string | undefined}; export type IOSTemplateBackup = {title: string, message: string, subtitle?: string | undefined, allow_bg_refresh?: boolean | undefined, rich_media_type?: ('Image' | 'Video' | 'GIF') | undefined, rich_media_value?: string | undefined, default_click_action?: ('DEEPLINKING' | 'NAVIGATE_TO_A_SCREEN' | 'RICH_LANDING') | undefined, default_click_action_value?: string | undefined, key_value_pairs?: Array | undefined}; export type IOSPushContent = {template_type: 'BASIC' | 'STYLIZED_BASIC' | 'SIMPLE_IMAGE_CAROUSEL' | 'Custom', custom_template_id?: string | undefined, custom_template_version?: number | undefined, basic_details?: IOSBasicDetails | undefined, buttons?: Array | undefined, advanced?: IOSAdvanced | undefined, template_backup?: IOSTemplateBackup | undefined}; export type WebBasicDetails = {title: string, message: string, redirect_url: string, image_url?: string | undefined, auto_dismiss_notification?: boolean | undefined}; export type WebButton = {title: string, icon_url?: string | undefined, url?: string | undefined}; export type WebAdvanced = {icon_image_type?: ('DEFAULT' | 'ICON_URL') | undefined, icon_url?: string | undefined}; export type WebPushContent = {template_type: 'BASIC', basic_details: WebBasicDetails, buttons?: Array | undefined, advanced?: WebAdvanced | undefined}; export type PushContent = {android?: AndroidPushContent | undefined, ios?: IOSPushContent | undefined, web?: WebPushContent | undefined}; export type PushCampaignContent = {locales?: Array | undefined, variation_details?: VariationDetails | undefined, content: {push: PushContent}}; export type SegmentationDetails = {included_filters?: FilterGroup | undefined, excluded_filters?: FilterGroup | undefined, is_all_user_campaign?: boolean | undefined, send_campaign_to_opt_out_users?: boolean | undefined}; export type PeriodicDetails = {sending_frequency?: ('DAILY' | 'WEEKLY' | 'MONTHLY') | undefined, repeat_frequency?: number | undefined, no_of_occurences?: number | undefined, repeat_on_date_of_month?: Array | undefined, repeat_on_days_of_week?: (Array<'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY'>) | undefined, repeat_on_days_of_week_for_month?: (Array<{week_granularity?: ('FIRST' | 'SECOND' | 'THIRD' | 'FOURTH' | 'LAST') | undefined, repeat_on_days_of_week?: (Array<'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY'>) | undefined}>) | undefined}; export type BTSDetails = {send_in_bts?: boolean | undefined, if_user_bts_is_not_available?: string | undefined, if_user_bts_outside_time_window?: string | undefined, window_end_time?: string | undefined}; export type UserTimezoneDetails = {send_in_user_timezone?: boolean | undefined, send_if_user_timezone_has_passed?: boolean | undefined}; export type SchedulingDetails = {delivery_type: 'ASAP' | 'AT_FIXED_TIME' | 'SEND_IN_BTS' | 'SEND_IN_USER_TIMEZONE', start_time?: string | undefined, expiry_time?: string | undefined, periodic_details?: PeriodicDetails | undefined, bts_details?: BTSDetails | undefined, user_timezone_details?: UserTimezoneDetails | undefined}; export type PushDeliveryControls = {bypass_dnd?: boolean | undefined, campaign_throttle_rpm?: number | undefined, count_for_frequency_capping?: boolean | undefined, ignore_frequency_capping?: boolean | undefined, minimum_delay_between_two_notification_in_hour?: number | undefined, max_time_to_show_message_of_same_camapign?: string | undefined, expiry_time_of_sync_data_in_hour?: string | undefined, send_message_in_offline_mode?: boolean | undefined, send_limit_value?: string | undefined, send_limit_granularity_in_hours?: string | undefined}; export type AdvancedDetails = {expiration_settings?: ({expire_notification_after_value?: number | undefined, expire_notification_after_type?: ('HOUR' | 'DAY') | undefined, remove_from_inbox_after_value?: number | undefined, remove_from_inbox_after_type?: 'DAY' | undefined}) | undefined, platform_level_priority?: ({android_specific_priority?: ({send_with_priority?: boolean | undefined}) | undefined, ios_specific_priority?: ({apns_priority?: ('1' | '5' | '10') | undefined, interruption_level?: ('Passive' | 'Active' | 'Time sensitive' | 'Critical') | undefined, relevance_score?: number | undefined}) | undefined}) | undefined}; export type GoalEventAttribute = {name?: string | undefined, condition?: string | undefined, data_type?: ('STRING' | 'DOUBLE' | 'BOOL' | 'NUMBER' | 'GEOPOINT' | 'DATETIME' | 'ARRAY_DOUBLE' | 'ARRAY_STRING' | 'OBJECT' | 'ARRAY_OBJECT') | undefined, value?: string | undefined, value1?: string | undefined, negate?: boolean | undefined, value_type?: string | undefined, array_filter_type?: string | undefined, filters?: Array> | undefined, is_case_sensitive?: boolean | undefined}; export type Goal = {goal_name?: string | undefined, goal_event_name?: string | undefined, goal_event_attribute?: GoalEventAttribute | undefined, is_primary_goal?: boolean | undefined, revenue_attribute?: string | undefined, revenue_currency?: string | undefined}; export type ConversionGoalDetails = {attribution_window_in_hours?: number | undefined, goals?: Array | undefined}; export type ControlGroupDetails = {is_campaign_control_group_enabled?: boolean | undefined, campaign_control_group_percentage?: number | undefined, is_global_control_group_enabled?: boolean | undefined}; export type UTMParams = {utm_source: string, utm_medium: string, utm_campaign?: string | undefined, utm_term?: string | undefined, utm_content?: string | undefined, utm_custom?: string | undefined}; export type PushCampaignRequest = {request_id: string, channel: 'PUSH', campaign_delivery_type: 'ONE_TIME' | 'PERIODIC' | 'EVENT_TRIGGERED' | 'BUSINESS_EVENT_TRIGGERED' | 'DEVICE_TRIGGERED' | 'LOCATION_TRIGGERED' | 'BROADCAST_LIVE_ACTIVITY', created_by: string, basic_details: PushBasicDetails, trigger_condition?: PushTriggerCondition | undefined, campaign_content: PushCampaignContent, segmentation_details: SegmentationDetails, scheduling_details: SchedulingDetails, delivery_controls: PushDeliveryControls, advanced: AdvancedDetails, conversion_goal_details?: ConversionGoalDetails | undefined, control_group_details?: ControlGroupDetails | undefined, utm_params?: UTMParams | undefined}; export type EmailBasicDetails = {name: string, business_event?: string | undefined, content_type: 'PROMOTIONAL' | 'TRANSACTIONAL', subscription_category?: string | undefined, tags?: Array | undefined, team?: string | undefined, user_attribute_identifier: string, send_only_double_opt_in_users?: boolean | undefined, deduplication_attribute?: string | undefined}; export type EmailTriggerCondition = {included_filters?: FilterGroup | undefined, secondary_included_filters?: FilterGroup | undefined, trigger_delay_type?: ('DELAY' | 'ASAP') | undefined, trigger_delay_value?: number | undefined, trigger_delay_granularity?: ('MINUTES' | 'HOURS' | 'DAYS') | undefined, trigger_relation?: ('BEFORE' | 'AFTER') | undefined, trigger_attr?: Record | undefined}; export type Connector = {connector_type: string, connector_name: string}; export type GmailAnnotationsDealCard = {description: string, discount_code: string, availability_starts: string, availability_ends: string}; export type GmailAnnotationsProductCarouselManualProduct = {id: string, headline: string, original_price: string, discount_value: string, discount_type: 'PERCENT' | 'VALUE', promo_url: string, product_image: string}; export type GmailAnnotationsProductCarouselManualData = {currency: string, products: Array}; export type GmailAnnotationsProductCarouselProductSetData = {product_set: string, image_url: string, headline: string, promo_url: string, product_count: number}; export type GmailAnnotationsProductCarousel = {type: 'MANUAL' | 'PRODUCT_SET', manual_data?: GmailAnnotationsProductCarouselManualData | undefined, product_set_data?: GmailAnnotationsProductCarouselProductSetData | undefined}; export type GmailAnnotations = {send_email_if_personalization_fails: boolean, sender_logo: string, sender_logo_type: 'image_url' | 'uploaded_image', deal_card?: GmailAnnotationsDealCard | undefined, product_carousel?: GmailAnnotationsProductCarousel | undefined}; export type EmailCreateContent = {subject: string, preview_text?: string | undefined, sender_name: string, from_address: string, reply_to_address: string, cc_ids?: Array | undefined, bcc_ids?: Array | undefined, html_content?: string | undefined, email_editor?: ('Froala Editor' | 'Ace Editor') | undefined, custom_template_id?: string | undefined, custom_template_version?: number | undefined, attachments?: (Array<{file_type?: ('URL' | 'PERSONALIZED_ATTACHMENT') | undefined, url?: string | undefined, s3_keys?: Array | undefined}>) | undefined, gmail_annotations?: GmailAnnotations | undefined, link_branding_domain?: string | undefined, deep_link_domain?: string | undefined}; export type EmailCampaignCreateContent = {locales?: Array | undefined, variation_details?: VariationDetails | undefined, content: {email: EmailCreateContent}}; export type EmailDeliveryControls = {bypass_dnd?: boolean | undefined, campaign_throttle_rpm?: number | undefined, count_for_frequency_capping?: boolean | undefined, ignore_frequency_capping?: boolean | undefined, minimum_delay_between_two_notification_in_hour?: number | undefined}; export type CampaignAudienceLimit = {limit?: number | undefined, metrics?: string | undefined, frequency?: string | undefined}; export type EmailCampaignRequest = {request_id: string, channel: 'EMAIL', campaign_delivery_type: 'ONE_TIME' | 'PERIODIC' | 'EVENT_TRIGGERED' | 'BUSINESS_EVENT_TRIGGERED', created_by: string, basic_details: EmailBasicDetails, trigger_condition?: EmailTriggerCondition | undefined, connector: Connector, campaign_content: EmailCampaignCreateContent, segmentation_details: SegmentationDetails, scheduling_details: SchedulingDetails, delivery_controls?: EmailDeliveryControls | undefined, conversion_goal_details?: ConversionGoalDetails | undefined, control_group_details?: ControlGroupDetails | undefined, utm_params?: UTMParams | undefined, campaign_audience_limit?: CampaignAudienceLimit | undefined}; export type CampaignCreateRequest = PushCampaignRequest | EmailCampaignRequest; export type CreateApiCampaignsArgs = {'MOE-APPKEY': string, 'MOE-PROJECT-CODE'?: string | undefined, body: CampaignCreateRequest}; export type CreateApiCampaignsOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const campaignCreateSuccessResponse = z.object({campaign_id: 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 }; /** * Create Campaign * * POST /campaigns */ export const createApiCampaigns = async (args: CreateApiCampaignsArgs, options?: CreateApiCampaignsOptions) => { 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['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(/\/+$/, '')}/campaigns${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(campaignCreateSuccessResponse, await res.json()) };