import {z} from 'zod' export type ElementalContentSugar = {title: string, body: string}; export type TextAlign = 'left' | 'center' | 'right'; export type TextStyle = 'text' | 'h1' | 'h2' | 'subtext'; export type Locale = {content: string}; export type Locales = {[key: string]: Locale} | null; export type IAlignment = 'center' | 'left' | 'right' | 'full'; export type IActionButtonStyle = 'button' | 'link'; export type ElementalNode = {type: 'text', content: string, align: TextAlign, text_style?: TextStyle | undefined, color?: (string | null) | undefined, bold?: (string | null) | undefined, italic?: (string | null) | undefined, strikethrough?: (string | null) | undefined, underline?: (string | null) | undefined, font_size?: (string | null) | undefined, line_height?: (string | null) | undefined, locales?: Locales | undefined, format?: ('markdown' | null) | undefined, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'meta', title?: (string | null) | undefined, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'channel', channel: string, padding?: (string | null) | undefined, font_size?: (string | null) | undefined, line_height?: (string | null) | undefined, raw?: ({[key: string]: unknown} | null) | undefined, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'image', src: string, href?: (string | null) | undefined, align?: IAlignment | undefined, altText?: (string | null) | undefined, width?: (string | null) | undefined, border_color?: (string | null) | undefined, border_size?: (string | null) | undefined, padding?: (string | null) | undefined, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'action', content: string, href: string, action_id?: (string | null) | undefined, align?: (IAlignment | null) | undefined, background_color?: (string | null) | undefined, border_radius?: (string | null) | undefined, border_size?: (string | null) | undefined, font_size?: (string | null) | undefined, padding?: (string | null) | undefined, disable_tracking?: (boolean | null) | undefined, style?: (IActionButtonStyle | null) | undefined, locales: Locales, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'divider', color?: (string | null) | undefined, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'quote', content: string, align?: IAlignment | undefined, borderColor?: (string | null) | undefined, text_style: TextStyle, font_size?: (string | null) | undefined, line_height?: (string | null) | undefined, locales: Locales, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined} | {type: 'html', content: string, locales?: Locales | undefined, channels?: (Array | null) | undefined, ref?: (string | null) | undefined, if?: (string | null) | undefined, loop?: (string | null) | undefined}; export type ElementalContent = {version: string, elements: Array}; export type Content = ElementalContentSugar | ElementalContent; export type MessageData = {[key: string]: unknown}; export type RoutingMethod = 'all' | 'single'; export type Timeouts = {provider?: (number | null) | undefined, channel?: (number | null) | undefined}; export type UTM = {source?: (string | null) | undefined, medium?: (string | null) | undefined, campaign?: (string | null) | undefined, term?: (string | null) | undefined, content?: (string | null) | undefined}; export type ChannelMetadata = {utm?: UTM | undefined}; export type Channel = {brand_id?: (string | null) | undefined, providers?: (Array | null) | undefined, routing_method?: RoutingMethod | undefined, if?: (string | null) | undefined, timeouts?: Timeouts | undefined, override?: ({[key: string]: unknown} | null) | undefined, metadata?: ChannelMetadata | undefined}; export type MessageChannels = {[key: string]: Channel}; export type MessageContext = {tenant_id?: (string | null) | undefined}; export type MessageMetadata = {event?: (string | null) | undefined, tags?: (Array | null) | undefined, utm?: UTM | undefined, trace_id?: (string | null) | undefined}; export type MessagePreferences = {subscription_topic_id: string}; export type Metadata = {utm?: UTM | undefined}; export type MessageProvidersType = {override?: ({[key: string]: unknown} | null) | undefined, if?: (string | null) | undefined, timeouts?: (number | null) | undefined, metadata?: Metadata | undefined}; export type MessageProviders = {[key: string]: MessageProvidersType}; export type MessageRoutingMethod = 'all' | 'single'; export type MessageRouting = {method: MessageRoutingMethod, channels: Array}; export type MessageRoutingChannel = string | MessageRouting; export type Routing = {method: RoutingMethod, channels: Array}; export type Criteria = 'no-escalation' | 'delivered' | 'viewed' | 'engaged'; export type Timeout = {provider?: ({[key: string]: number} | null) | undefined, channel?: ({[key: string]: number} | null) | undefined, message?: (number | null) | undefined, escalation?: (number | null) | undefined, criteria?: Criteria | undefined}; export type Delay = {duration?: (number | null) | undefined, until?: (string | null) | undefined, timezone?: (string | null) | undefined}; export type ExpiresInType = string | number; export type Expiry = {expires_at?: (string | null) | undefined, expires_in: ExpiresInType}; export type UserRecipient = Record; export type AudienceFilter = {operator: 'MEMBER_OF', path: 'account_id', value: string}; export type AudienceRecipient = {audience_id: string, data?: MessageData | undefined, filters?: (Array | null) | undefined}; export type ListFilter = {operator: 'MEMBER_OF', path: 'account_id', value: string}; export type ListRecipient = {list_id?: (string | null) | undefined, data?: MessageData | undefined, filters?: (Array | null) | undefined}; export type ListPatternRecipient = {list_pattern?: (string | null) | undefined, data?: MessageData | undefined}; export type SendToSlackChannel = {access_token: string, channel: string}; export type SendToSlackEmail = {access_token: string, email: string}; export type SendToSlackUserId = {access_token: string, user_id: string}; export type Slack = SendToSlackChannel | SendToSlackEmail | SendToSlackUserId; export type SlackRecipient = {slack: Slack}; export type SendToMsTeamsUserId = {tenant_id: string, service_url: string, user_id: string}; export type SendToMsTeamsEmail = {tenant_id: string, service_url: string, email: string}; export type SendToMsTeamsChannelId = {tenant_id: string, service_url: string, channel_id: string}; export type SendToMsTeamsConversationId = {tenant_id: string, service_url: string, conversation_id: string}; export type SendToMsTeamsChannelName = {tenant_id: string, service_url: string, channel_name: string, team_id: string}; export type MsTeams = SendToMsTeamsUserId | SendToMsTeamsEmail | SendToMsTeamsChannelId | SendToMsTeamsConversationId | SendToMsTeamsChannelName; export type MsTeamsRecipient = {ms_teams: MsTeams}; export type Pagerduty = {routing_key?: (string | null) | undefined, event_action?: (string | null) | undefined, severity?: (string | null) | undefined, source?: (string | null) | undefined}; export type PagerdutyRecipient = {pagerduty: Pagerduty}; export type WebhookMethod = 'POST' | 'PUT'; export type WebhookAuthMode = 'none' | 'basic' | 'bearer'; export type WebhookAuthentication = {mode: WebhookAuthMode, username?: (string | null) | undefined, password?: (string | null) | undefined, token?: (string | null) | undefined}; export type WebhookProfileType = 'limited' | 'expanded'; export type WebhookProfile = {url: string, method?: WebhookMethod | undefined, headers?: ({[key: string]: string} | null) | undefined, authentication?: WebhookAuthentication | undefined, profile?: WebhookProfileType | undefined}; export type WebhookRecipient = {webhook: WebhookProfile}; export type Recipient = UserRecipient | AudienceRecipient | ListRecipient | ListPatternRecipient | SlackRecipient | MsTeamsRecipient | PagerdutyRecipient | WebhookRecipient; export type MessageRecipient = Recipient | Array; export type Message = {content?: Content | undefined, template?: (string | null) | undefined, data?: MessageData | undefined, brand_id?: (string | null) | undefined, channels?: MessageChannels | undefined, context?: MessageContext | undefined, metadata?: MessageMetadata | undefined, preferences?: MessagePreferences | undefined, providers?: MessageProviders | undefined, routing?: Routing | undefined, timeout?: Timeout | undefined, delay?: Delay | undefined, expiry?: Expiry | undefined, to?: MessageRecipient | undefined}; export type CreateApiSendArgs = {'Idempotency-Key'?: string | undefined, 'x-idempotency-expiration'?: string | undefined, body: {message: Message}}; export type CreateApiSendOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const sendMessageResponse = z.object({requestId: z.string()}); 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 a message * * POST /send */ export const createApiSend = async (args: CreateApiSendArgs, options?: CreateApiSendOptions) => { const {baseUrl = "https://api.courier.com", 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 (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args['x-idempotency-expiration'] != null) headers.set("x-idempotency-expiration", String(args['x-idempotency-expiration'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/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(sendMessageResponse, await res.json()) };