import {z} from 'zod' export type BillingUsageGranularity = 'week' | 'month'; export type GetApiV1BillingUsageArgs = {granularity?: BillingUsageGranularity | undefined, periods?: number | undefined, stripe_account_identifier?: (string | null) | undefined}; export type GetApiV1BillingUsageOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const billingUsageGranularity = z.enum(["week", "month"]); export const billingUsagePoint = z.object({period_start: z.string(), period_end: z.string(), billable_orders: z.number().int().nullable(), billable_deliveries: z.number().int(), is_final: z.boolean()}); export const billingUsageResponse = z.object({granularity: billingUsageGranularity, points: z.array(billingUsagePoint)}); 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 usage * * GET /v1/billing/usage */ export const getApiV1BillingUsage = async (args: GetApiV1BillingUsageArgs, options?: GetApiV1BillingUsageOptions) => { const {baseUrl = "https://api.sandbox.usenash.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.granularity != null) query.append("granularity", String(args.granularity)) if (args.periods != null) query.append("periods", String(args.periods)) if (args.stripe_account_identifier != null) query.append("stripe_account_identifier", String(args.stripe_account_identifier)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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(billingUsageResponse, await res.json()) };