import {z} from 'zod' export type BatchSendInput = {emails: Array<{from: string, to: Array, cc?: Array | undefined, bcc?: Array | undefined, reply_to?: string | undefined, subject?: string | undefined, html?: string | undefined, text?: string | undefined, headers?: {[key: string]: string} | undefined, tags?: Array | undefined, attachments?: (Array<{filename: string, content: string, content_type?: string | undefined, content_id?: string | undefined}>) | undefined, idempotency_key?: string | undefined, scheduled_at?: (string | string) | undefined, template_id?: string | undefined, variables?: {[key: string]: string} | undefined, unsubscribe?: boolean | undefined, signature?: ('auto' | 'none') | undefined, tracking?: ({opens?: boolean | undefined, clicks?: boolean | undefined}) | undefined, idempotency_window_hours?: number | undefined}>}; export type CreateApiEmailsBatchArgs = {'Idempotency-Key'?: string | undefined, body: BatchSendInput}; export type CreateApiEmailsBatchOptions = {baseUrl?: string | undefined, bearerApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const batchSendResult = z.union([z.object({id: z.string(), replayed: z.boolean().optional()}), z.object({error: z.string(), code: z.string().optional()})]); export const createApiEmailsBatchResponse = z.object({data: z.array(batchSendResult)}); 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 up to 100 emails * * POST /emails/batch * * Also accepts auth: bearerOAuth */ export const createApiEmailsBatch = async (args: CreateApiEmailsBatchArgs, options?: CreateApiEmailsBatchOptions) => { const {baseUrl = "https://api.poststack.dev", fetch: fetchFn = fetch, bearerApiKey} = 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 (bearerApiKey !== undefined) headers.set('authorization', `Bearer ${bearerApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/emails/batch${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(createApiEmailsBatchResponse, await res.json()) };