import {z} from 'zod' export type GetApiApiV1UsageSummaryArgs = {range?: ('7d' | '30d' | '90d' | '365d') | undefined, startDate?: string | undefined, endDate?: string | undefined, projectId?: string | undefined}; export type GetApiApiV1UsageSummaryOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const costCoverage = z.object({reportedEvents: z.number().int().gte(0), totalEvents: z.number().int().gte(0)}); export const usageSummary = z.object({range: z.object({start: z.string(), end: z.string()}), totals: z.object({totalTokens: z.number(), promptTokens: z.number(), completionTokens: z.number(), totalCostUsd: z.number(), requestCount: z.number(), carbonKg: z.number(), electricityKwh: z.number(), waterLiters: z.number(), waterLowerBoundL: z.number(), waterUpperBoundL: z.number(), offsetCostUsd: z.number().nullable(), costCoverage: costCoverage}), chart: z.object({labels: z.array(z.string()), datasets: z.array(z.object({label: z.string(), data: z.array(z.number())})), costCoverage: z.array(costCoverage)})}); export const getApiApiV1UsageSummaryResponse = z.object({success: z.literal(true), data: usageSummary}); 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 usage summary * * GET /api/v1/usage/summary * * Also accepts auth: apiKey */ export const getApiApiV1UsageSummary = async (args: GetApiApiV1UsageSummaryArgs, options?: GetApiApiV1UsageSummaryOptions) => { const {baseUrl = "https://api.crbonfree.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.range != null) query.append("range", String(args.range)) if (args.startDate != null) query.append("startDate", String(args.startDate)) if (args.endDate != null) query.append("endDate", String(args.endDate)) if (args.projectId != null) query.append("projectId", String(args.projectId)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/usage/summary${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(getApiApiV1UsageSummaryResponse, await res.json()) };