import {z} from 'zod' export type GetApiAnalyticsQueryArgs = {metrics: Array, groupBy?: Array | undefined, range?: string | undefined, start?: string | undefined, end?: string | undefined, asOf?: string | undefined, timeZone?: string | undefined, personaIds?: Array | undefined, memberIds?: Array | undefined, segmentIds?: Array | undefined, sepDestinations?: Array | undefined, repMetrics?: Array | undefined, sort?: string | undefined, direction?: ('asc' | 'desc') | undefined, limit?: number | undefined, cursor?: string | undefined}; export type GetApiAnalyticsQueryOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const analyticsColumn = z.object({name: z.string(), role: z.string(), type: z.string().optional(), unit: z.string().optional(), temporality: z.string().optional(), nullable: z.boolean().optional()}); export const analyticsQueryResponse = z.object({success: z.literal(true), data: z.array(z.record(z.string(), z.union([z.string().nullable(), z.number().nullable(), z.array(z.string()).nullable()]))), meta: z.object({entity: z.string(), groupBy: z.array(z.string()), time: z.object({start: z.string().optional(), end: z.string().optional(), timeZone: z.string().optional(), asOf: z.string().optional()}), scope: z.object({teams: z.array(z.object({id: z.string(), name: z.string()})), repCount: z.number().int()}), columns: z.array(analyticsColumn), rowCount: z.number().int(), totalRows: z.number().int(), nextCursor: z.string().optional(), notes: z.array(z.string())})}); 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 }; /** * Query analytics metrics * * GET /analytics/query */ export const getApiAnalyticsQuery = async (args: GetApiAnalyticsQueryArgs, options?: GetApiAnalyticsQueryOptions) => { const {baseUrl = "https://api.commonroom.io/api/v2", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.metrics ?? []) query.append("metrics", String(item)) for (const item of args.groupBy ?? []) query.append("groupBy", String(item)) if (args.range != null) query.append("range", String(args.range)) if (args.start != null) query.append("start", String(args.start)) if (args.end != null) query.append("end", String(args.end)) if (args.asOf != null) query.append("asOf", String(args.asOf)) if (args.timeZone != null) query.append("timeZone", String(args.timeZone)) for (const item of args.personaIds ?? []) query.append("personaIds", String(item)) for (const item of args.memberIds ?? []) query.append("memberIds", String(item)) for (const item of args.segmentIds ?? []) query.append("segmentIds", String(item)) for (const item of args.sepDestinations ?? []) query.append("sepDestinations", String(item)) for (const item of args.repMetrics ?? []) query.append("repMetrics", String(item)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.direction != null) query.append("direction", String(args.direction)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/analytics/query${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(analyticsQueryResponse, await res.json()) };