import {z} from 'zod' export type GetApiApiV1BillingReceiptsArgs = {page?: number | undefined, limit?: number | undefined}; export type GetApiApiV1BillingReceiptsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const receiptListEntry = z.object({id: z.string(), periodStart: z.string(), periodEnd: z.string(), status: z.enum(["open", "reconciling", "ready", "closing", "closed", "failed"]), totals: z.object({inputTokensUncached: z.string(), inputTokensCached: z.string(), inputTokensCacheCreation: z.string(), outputTokens: z.string(), requestCount: z.string(), providerCostUsd: z.number(), carbonKg: z.number(), electricityKwh: z.number()}), factorsVersions: z.array(z.string()), planTierAtClose: z.enum(["free", "starter", "growth", "scale", "enterprise", "payg"]).nullable(), closedAt: z.string().nullable(), createdAt: z.string(), stripeInvoiceId: z.string().nullable(), amountChargedCents: z.number().int().nullable(), failureReason: z.enum(["payment_failed", "aggregation_failed", "signing_failed"]).nullable(), paidAt: z.string().nullable(), readyAt: z.string().nullable(), closingAt: z.string().nullable(), carbonReceiptId: z.string().nullable(), statementId: z.string().nullable(), statementStatus: z.enum(["pending", "signing", "signed", "failed", "unavailable"]).nullable(), receipt: z.object({id: z.string(), co2Kg: z.number(), serialAllocations: z.array(z.object({serialNumber: z.string(), totalKgCo2e: z.number()})), verificationUrl: z.string(), previewUrl: z.string().nullable(), pdfUrl: z.string().nullable(), isSigned: z.boolean(), signedAt: z.string().nullable(), createdAt: z.string()}).nullable()}); export const paginationMeta = z.object({page: z.number().int().gte(0), limit: z.number().int().gt(0), total: z.number().int().gte(0), totalPages: z.number().int().gte(0)}); export const getApiApiV1BillingReceiptsResponse = z.object({success: z.literal(true), data: z.array(receiptListEntry), pagination: paginationMeta}); 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 }; /** * List billing periods with their carbon receipt and statement * * GET /api/v1/billing/receipts * * Also accepts auth: apiKey */ export const getApiApiV1BillingReceipts = async (args: GetApiApiV1BillingReceiptsArgs, options?: GetApiApiV1BillingReceiptsOptions) => { const {baseUrl = "https://api.crbonfree.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.limit != null) query.append("limit", String(args.limit)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/billing/receipts${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(getApiApiV1BillingReceiptsResponse, await res.json()) };