import {z} from 'zod' export type GetApiApiBillingStateOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const billingStateResponse = z.object({plan_tier: z.string(), subscription_status: z.string(), pro_enabled: z.boolean(), can_manage_billing: z.boolean(), monthly_price_cents: z.number().int(), monthly_mb_included: z.number().int(), overage_per_gb_cents: z.number().int(), used_bytes: z.number().int(), period_start: z.string().nullable(), period_end: z.string().nullable(), trial_ends_at: z.string().nullable(), cancel_at_period_end: z.boolean(), has_subscription: z.boolean().optional(), has_customer: z.boolean().optional(), refund_window_ends_at: z.string().nullable().optional(), refund_eligible: z.boolean().optional(), is_payg: z.boolean().optional(), credit_balance_bytes: z.number().int().optional(), credit_balance_credits: z.number().optional(), free_grant_credits: z.number().int().optional(), credit_price_cents: z.number().int().optional(), bytes_per_credit: z.number().int().optional(), payg_out_of_credits_mode: z.string().optional(), credit_pack_presets: z.array(z.number().int()).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 Billing State * * GET /api/billing/state */ export const getApiApiBillingState = async (options: GetApiApiBillingStateOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/billing/state${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(billingStateResponse, await res.json()) };