import {z} from 'zod' export type GetApiContactsIdActivityArgs = {id: string, limit?: number | undefined, since?: string | undefined}; export type GetApiContactsIdActivityOptions = {baseUrl?: string | undefined, bearerApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiContactsIdActivityResponse = z.object({contact_id: z.string().optional(), email: z.string().optional(), total: z.number().int().optional(), events: z.object({sent: z.array(z.object({})).optional(), delivered: z.array(z.object({})).optional(), opened: z.array(z.object({})).optional(), clicked: z.array(z.object({})).optional(), bounced: z.array(z.object({})).optional(), complained: z.array(z.object({})).optional(), failed: z.array(z.object({})).optional(), other: z.array(z.object({})).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 }; /** * Email events for a contact, grouped * * GET /contacts/{id}/activity * * Also accepts auth: bearerOAuth */ export const getApiContactsIdActivity = async (args: GetApiContactsIdActivityArgs, options?: GetApiContactsIdActivityOptions) => { const {baseUrl = "https://api.poststack.dev", fetch: fetchFn = fetch, bearerApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.since != null) query.append("since", String(args.since)) if (bearerApiKey !== undefined) headers.set('authorization', `Bearer ${bearerApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/contacts/${encodeURIComponent(String(args.id))}/activity${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiContactsIdActivityResponse, await res.json()) };