import {z} from 'zod' export type GetApiV4BillingUsageArgs = {unit?: ('MS' | 'TOK') | undefined, fromInterval: string, toInterval: string, userId?: (Array | null) | undefined}; export type GetApiV4BillingUsageOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const reportRow = z.object({day: z.string(), typ: z.string().nullable(), value: z.number().nullable()}); export const usageReport = z.object({rows: z.array(reportRow)}); export const responseMeta = z.object({requestId: z.string().optional(), timestamp: z.string().optional(), durationMs: z.number().int().nullable().optional()}); export const successResponseUsageReport = z.object({success: z.literal(true), data: usageReport, meta: responseMeta.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 usage * * GET /v4/billing/usage */ export const getApiV4BillingUsage = async (args: GetApiV4BillingUsageArgs, options: GetApiV4BillingUsageOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.unit != null) query.append("unit", String(args.unit)) if (args.fromInterval != null) query.append("fromInterval", String(args.fromInterval)) if (args.toInterval != null) query.append("toInterval", String(args.toInterval)) for (const item of args.userId ?? []) query.append("userId", String(item)) const url = `${baseUrl.replace(/\/+$/, '')}/v4/billing/usage${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(successResponseUsageReport, await res.json()) };