import {z} from 'zod' export type RateLimitDomain = 'VEHICLE'; export type GetApiV1RateLimitsArgs = {objectId: string, domain: RateLimitDomain}; export type GetApiV1RateLimitsOptions = {baseUrl?: string | undefined, OAuth2ClientCredentialsBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const rateLimitDomain = z.literal("VEHICLE"); export const rateLimitKey = z.enum(["BMW_ENERGY_API_COMMANDS", "BMW_ENERGY_API_STOP_COMMANDS", "BMW_ENERGY_API_COMMANDS_AND_FETCH_STATE"]); export const rateLimit = z.object({remainingRequests: z.number().int(), maxRequests: z.number().int(), domain: rateLimitDomain, windowSizeSeconds: z.number().int(), objectId: z.string(), key: rateLimitKey}); export const getApiV1RateLimitsResponse = z.array(rateLimit); 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 Rate Limits * * GET /v1/rate-limits */ export const getApiV1RateLimits = async (args: GetApiV1RateLimitsArgs, options?: GetApiV1RateLimitsOptions) => { const {baseUrl = "https://api.volteras.com", fetch: fetchFn = fetch, OAuth2ClientCredentialsBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.objectId != null) query.append("objectId", String(args.objectId)) if (args.domain != null) query.append("domain", String(args.domain)) if (OAuth2ClientCredentialsBearer !== undefined) headers.set('authorization', `Bearer ${OAuth2ClientCredentialsBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/rate-limits${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(getApiV1RateLimitsResponse, await res.json()) };