import {z} from 'zod' export type GetApiAnalyticsCohortsArgs = {cohort_from?: number | undefined, cohort_to?: number | undefined, mode?: ('by_renewals' | 'by_days') | undefined, grouping?: ('day' | 'week' | 'month' | 'quarter' | 'year') | undefined, environment?: (0 | 1) | undefined, cohort_definition?: ('new_customers' | 'initial_conversions' | 'new_paying') | undefined, revenue_type?: ('gross' | 'net') | undefined, currency?: string | undefined, group_by?: string | undefined, 'filter[][]'?: Array | undefined}; export type GetApiAnalyticsCohortsOptions = {baseUrl?: string | undefined, secretAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const v4AnalyticsCohorts = z.object({object: z.literal("analytics_cohorts"), url: z.string(), mode: z.enum(["by_renewals", "by_days"]), grouping: z.enum(["day", "week", "month", "quarter", "year"]), cohort_from: z.number().int(), cohort_to: z.number().int(), currency: z.string(), period_labels: z.array(z.string()), cohorts: z.array(z.record(z.string(), z.unknown())), total: z.record(z.string(), z.unknown()).nullable().optional(), max_values: z.record(z.string(), z.number()), group_by: z.string().optional(), segments: z.array(z.record(z.string(), z.unknown())).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 cohort analytics data * * GET /analytics/cohorts */ export const getApiAnalyticsCohorts = async (args: GetApiAnalyticsCohortsArgs, options?: GetApiAnalyticsCohortsOptions) => { const {baseUrl = "https://api.qonversion.io/v4", fetch: fetchFn = fetch, secretAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cohort_from != null) query.append("cohort_from", String(args.cohort_from)) if (args.cohort_to != null) query.append("cohort_to", String(args.cohort_to)) if (args.mode != null) query.append("mode", String(args.mode)) if (args.grouping != null) query.append("grouping", String(args.grouping)) if (args.environment != null) query.append("environment", String(args.environment)) if (args.cohort_definition != null) query.append("cohort_definition", String(args.cohort_definition)) if (args.revenue_type != null) query.append("revenue_type", String(args.revenue_type)) if (args.currency != null) query.append("currency", String(args.currency)) if (args.group_by != null) query.append("group_by", String(args.group_by)) for (const item of args['filter[][]'] ?? []) query.append("filter[][]", String(item)) if (secretAuth !== undefined) headers.set('authorization', `Bearer ${secretAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/analytics/cohorts${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(v4AnalyticsCohorts, await res.json()) };