import {z} from 'zod' export type GetApi30ListsArgs = {fields?: Array | undefined, exclude_fields?: Array | undefined, count?: number | undefined, offset?: number | undefined, before_date_created?: string | undefined, since_date_created?: string | undefined, before_campaign_last_sent?: string | undefined, since_campaign_last_sent?: string | undefined, email?: string | undefined, sort_field?: 'date_created' | undefined, sort_dir?: ('ASC' | 'DESC') | undefined, has_ecommerce_store?: boolean | undefined, include_total_contacts?: boolean | undefined}; export type GetApi30ListsOptions = {baseUrl?: string | undefined, bearerToken?: string | undefined, fetch?: typeof fetch | undefined}; export const getApi30ListsResponse = z.object({_links: z.array(z.object({href: z.string().optional(), method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]).optional(), rel: z.string().optional(), schema: z.string().optional(), targetSchema: z.string().optional()})).optional(), constraints: z.object({current_total_instances: z.number().int().optional(), max_instances: z.number().int(), may_create: z.boolean()}).optional(), lists: z.array(z.object({_links: z.array(z.object({href: z.string().optional(), method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]).optional(), rel: z.string().optional(), schema: z.string().optional(), targetSchema: z.string().optional()})).optional(), beamer_address: z.string().optional(), campaign_defaults: z.object({from_email: z.string().optional(), from_name: z.string().optional(), language: z.string().optional(), subject: z.string().optional()}).optional(), contact: z.object({address1: z.string().optional(), address2: z.string().optional(), city: z.string().optional(), company: z.string().optional(), country: z.string().optional(), phone: z.string().optional(), state: z.string().optional(), zip: z.string().optional()}).optional(), date_created: z.string().optional(), double_optin: z.boolean().optional(), email_type_option: z.boolean().optional(), has_welcome: z.boolean().optional(), id: z.string().optional(), list_rating: z.number().int().optional(), marketing_permissions: z.boolean().optional(), modules: z.array(z.string()).optional(), name: z.string().optional(), notify_on_subscribe: z.string().optional(), notify_on_unsubscribe: z.string().optional(), permission_reminder: z.string().optional(), stats: z.object({avg_sub_rate: z.number().optional(), avg_unsub_rate: z.number().optional(), campaign_count: z.number().int().optional(), campaign_last_sent: z.string().optional(), cleaned_count: z.number().int().optional(), cleaned_count_since_send: z.number().int().optional(), click_rate: z.number().optional(), last_sub_date: z.string().optional(), last_unsub_date: z.string().optional(), member_count: z.number().int().optional(), member_count_since_send: z.number().int().optional(), merge_field_count: z.number().int().optional(), open_rate: z.number().optional(), target_sub_rate: z.number().optional(), total_contacts: z.number().int().optional(), unsubscribe_count: z.number().int().optional(), unsubscribe_count_since_send: z.number().int().optional()}).optional(), subscribe_url_long: z.string().optional(), subscribe_url_short: z.string().optional(), use_archive_bar: z.boolean().optional(), visibility: z.enum(["pub", "prv"]).optional(), web_id: z.number().int().optional()})), total_items: z.number().int().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 }; /** * Get lists info * * GET /3.0/lists * * Also accepts auth: oauth2 */ export const getApi30Lists = async (args: GetApi30ListsArgs, options?: GetApi30ListsOptions) => { const {baseUrl = "https://api.mailchimp.com", fetch: fetchFn = fetch, bearerToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.fields != null) query.append("fields", args.fields.join(',')) if (args.exclude_fields != null) query.append("exclude_fields", args.exclude_fields.join(',')) if (args.count != null) query.append("count", String(args.count)) if (args.offset != null) query.append("offset", String(args.offset)) if (args.before_date_created != null) query.append("before_date_created", String(args.before_date_created)) if (args.since_date_created != null) query.append("since_date_created", String(args.since_date_created)) if (args.before_campaign_last_sent != null) query.append("before_campaign_last_sent", String(args.before_campaign_last_sent)) if (args.since_campaign_last_sent != null) query.append("since_campaign_last_sent", String(args.since_campaign_last_sent)) if (args.email != null) query.append("email", String(args.email)) if (args.sort_field != null) query.append("sort_field", String(args.sort_field)) if (args.sort_dir != null) query.append("sort_dir", String(args.sort_dir)) if (args.has_ecommerce_store != null) query.append("has_ecommerce_store", String(args.has_ecommerce_store)) if (args.include_total_contacts != null) query.append("include_total_contacts", String(args.include_total_contacts)) if (bearerToken !== undefined) headers.set('authorization', `Bearer ${bearerToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/3.0/lists${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(getApi30ListsResponse, await res.json()) };