import {z} from 'zod' export type GetApiV1AnalyticsSessionsTurnDepthArgs = {start_date: string, end_date: string}; export type GetApiV1AnalyticsSessionsTurnDepthOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const turnDepthRow = z.object({total_sessions: z.number().int(), avg_turns_per_session: z.number(), single_turn_rate_pct: z.number(), p50_turns: z.number(), p90_turns: z.number(), p95_turns: z.number()}); export const getApiV1AnalyticsSessionsTurnDepthResponse = z.array(turnDepthRow); 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 }; /** * Turn-depth summary (avg / single-turn rate / quantiles) * * GET /v1/analytics/sessions/turn-depth */ export const getApiV1AnalyticsSessionsTurnDepth = async (args: GetApiV1AnalyticsSessionsTurnDepthArgs, options: GetApiV1AnalyticsSessionsTurnDepthOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start_date != null) query.append("start_date", String(args.start_date)) if (args.end_date != null) query.append("end_date", String(args.end_date)) if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/analytics/sessions/turn-depth${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(getApiV1AnalyticsSessionsTurnDepthResponse, await res.json()) };