import {z} from 'zod' export type GetApiApiV1ProjectUsageArgs = {last_days?: number | undefined}; export type GetApiApiV1ProjectUsageOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const dailyUsage = z.object({date: z.string(), total_insert: z.number().int().optional(), total_success_insert: z.number().int().optional(), total_input_token: z.number().int().optional(), total_output_token: z.number().int().optional()}); export const cODE = z.union([z.literal(0), z.literal(400), z.literal(401), z.literal(403), z.literal(404), z.literal(405), z.literal(409), z.literal(422), z.literal(500), z.literal(501), z.literal(502), z.literal(503), z.literal(504), z.literal(520)]); export const usageResponse = z.object({data: z.array(dailyUsage).nullable().optional(), errno: cODE.optional(), errmsg: z.string().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 Project Usage * * GET /api/v1/project/usage */ export const getApiApiV1ProjectUsage = async (args: GetApiApiV1ProjectUsageArgs, options?: GetApiApiV1ProjectUsageOptions) => { const {baseUrl = "https://api.memobase.dev", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.last_days != null) query.append("last_days", String(args.last_days)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/project/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(usageResponse, await res.json()) };