import {z} from 'zod' export type GetApiV1UsageSeriesArgs = {to?: string | undefined, from?: string | undefined, accountIds?: (Array | null) | undefined, checkTypes?: (Array<'AGENTIC' | 'API' | 'BROWSER' | 'HEARTBEAT' | 'ICMP' | 'MULTI_STEP' | 'TCP' | 'PLAYWRIGHT' | 'URL' | 'DNS' | 'SSL' | 'GRPC' | 'TRACEROUTE'> | null) | undefined, interval?: ('total' | 'day' | 'week' | 'month') | undefined, groupBy?: ('account' | 'checkType' | 'account,checkType') | undefined, limit?: number | undefined, nextId?: string | undefined, 'x-checkly-account'?: string | undefined}; export type GetApiV1UsageSeriesOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const usageV1SeriesPeriod = z.object({from: z.string(), to: z.string(), interval: z.enum(["total", "day", "week", "month"]), groupBy: z.enum(["account", "checkType", "account,checkType"])}); export const usageV1Credits = z.object({used: z.number().gte(0).nullable(), percentOfBudget: z.number().gte(0).nullable()}); export const usageV1CheckRunMeter = z.object({meterType: z.literal("CHECK_RUN"), measures: z.object({totalRuns: z.number().int().gte(0), finalRuns: z.number().int().gte(0), retryRuns: z.number().int().gte(0), cancelledRuns: z.number().int().gte(0), multiStepRequests: z.number().int().gte(0), playwrightBillableDurationMs: z.number().int().gte(0), degradedRuns: z.number().int().gte(0), failedRuns: z.number().int().gte(0), errorRuns: z.number().int().gte(0), abortedRuns: z.number().int().gte(0), overMaxResponseTimeRuns: z.number().int().gte(0), standardBillableUnits: z.number().int().gte(0), premiumBillableUnits: z.number().int().gte(0)})}); export const usageV1AiInvocationMeter = z.object({meterType: z.literal("AI_INVOCATION"), measures: z.object({invocations: z.number().int().gte(0), durationMs: z.number().int().gte(0)})}); export const usageV1Meter = z.discriminatedUnion("meterType", [usageV1CheckRunMeter, usageV1AiInvocationMeter]); export const usageV1Row = z.object({credits: usageV1Credits, meters: z.array(usageV1Meter), periodStart: z.string(), periodEnd: z.string(), accountId: z.string().optional(), checkType: z.enum(["AGENTIC", "API", "BROWSER", "HEARTBEAT", "ICMP", "MULTI_STEP", "TCP", "PLAYWRIGHT", "URL", "DNS", "SSL", "GRPC", "TRACEROUTE"]).optional()}); export const usageV1SeriesResponse = z.object({usageTermsId: z.string().nullable(), period: usageV1SeriesPeriod, data: z.array(usageV1Row), length: z.number().int().gte(0), nextId: z.string().nullable()}); 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 paginated usage data grouped over time. * * GET /v1/usage/series */ export const getApiV1UsageSeries = async (args: GetApiV1UsageSeriesArgs, options?: GetApiV1UsageSeriesOptions) => { const {baseUrl = "https://api.checklyhq.com", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.to != null) query.append("to", String(args.to)) if (args.from != null) query.append("from", String(args.from)) for (const item of args.accountIds ?? []) query.append("accountIds", String(item)) for (const item of args.checkTypes ?? []) query.append("checkTypes", String(item)) if (args.interval != null) query.append("interval", String(args.interval)) if (args.groupBy != null) query.append("groupBy", String(args.groupBy)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.nextId != null) query.append("nextId", String(args.nextId)) if (args['x-checkly-account'] != null) headers.set("x-checkly-account", String(args['x-checkly-account'])) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/usage/series${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(usageV1SeriesResponse, await res.json()) };