import {z} from 'zod' export type GetApiV1AccountMeOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV1AccountMeResponse = z.object({credits_balance: z.number().int().optional(), subscription_credits_balance: z.number().int().optional(), total_credits_balance: z.number().int().optional(), tier: z.enum(["free", "basic", "pro", "enterprise"]).optional(), rate_limit_per_minute: z.number().int().optional(), subscription: z.object({plan_code: z.string().optional(), plan_title: z.string().optional(), billing_cadence: z.enum(["monthly", "annual"]).optional(), status: z.enum(["active", "past_due"]).optional(), current_period_start: z.string().nullable().optional(), current_period_end: z.string().nullable().optional(), cancel_at_period_end: z.boolean().optional(), cancel_effective_at: z.string().nullable().optional(), monthly_credits: z.number().int().optional(), pending_plan_code: z.string().nullable().optional(), pending_plan_title: z.string().nullable().optional(), pending_change_effective_at: z.string().nullable().optional()}).nullable().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 Account Info * * GET /v1/account/me */ export const getApiV1AccountMe = async (options?: GetApiV1AccountMeOptions) => { const {baseUrl = "https://scrapebadger.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/account/me${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(getApiV1AccountMeResponse, await res.json()) };