import {z} from 'zod' export type GetApiV1AdsPerformanceArgs = {accountId: string, adAccountId?: string | undefined, fromDate: string, toDate: string, platform?: ('facebook' | 'instagram' | 'tiktok' | 'linkedin' | 'pinterest' | 'google' | 'twitter' | 'openai' | 'reddit' | 'microsoft') | undefined, sortBy?: ('spend' | 'impressions' | 'clicks' | 'conversions' | 'roas') | undefined, limit?: number | undefined}; export type GetApiV1AdsPerformanceOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const adsPerformanceResponse = z.object({ads: z.array(z.object({adId: z.string().optional(), platformAdId: z.string().nullable().optional(), platform: z.string().optional(), name: z.string().optional(), status: z.string().nullable().optional(), campaignName: z.string().nullable().optional(), adSetName: z.string().nullable().optional(), currency: z.string().nullable().optional(), creative: z.object({type: z.enum(["image", "video", "carousel", "document", "text", "null"]).nullable().optional(), thumbnailUrl: z.string().nullable().optional(), headline: z.string().nullable().optional(), body: z.string().nullable().optional(), linkUrl: z.string().nullable().optional()}).optional(), metrics: z.object({spend: z.number().optional(), impressions: z.number().int().optional(), clicks: z.number().int().optional(), ctr: z.number().optional(), conversions: z.number().optional(), costPerConversion: z.number().optional(), purchaseValue: z.number().optional(), roas: z.number().optional(), conversionsByType: z.record(z.string(), z.number()).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 }; /** * Rank ads by performance * * GET /v1/ads/performance */ export const getApiV1AdsPerformance = async (args: GetApiV1AdsPerformanceArgs, options?: GetApiV1AdsPerformanceOptions) => { const {baseUrl = "https://zernio.com/api", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.accountId != null) query.append("accountId", String(args.accountId)) if (args.adAccountId != null) query.append("adAccountId", String(args.adAccountId)) if (args.fromDate != null) query.append("fromDate", String(args.fromDate)) if (args.toDate != null) query.append("toDate", String(args.toDate)) if (args.platform != null) query.append("platform", String(args.platform)) if (args.sortBy != null) query.append("sortBy", String(args.sortBy)) if (args.limit != null) query.append("limit", String(args.limit)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/ads/performance${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(adsPerformanceResponse, await res.json()) };