import {z} from 'zod' export type GetApiV2UsageSeriesArgs = {from?: string | undefined, to?: string | undefined, usageTermsIds?: Array | undefined, accountIds?: Array | undefined, pricingRuleKeys?: (Array<'apiChecks' | 'multistepChecks' | 'browserChecks' | 'playwrightCheckSuites' | 'uptimeMonitors' | 'aiInvocations' | 'statusPages' | 'statusPageAdditionalServices' | 'statusPageAdditionalSubscribers' | 'additionalSms' | 'additionalPhoneAlerts'>) | undefined, limit?: number | undefined, nextId?: string | undefined, interval?: ('total' | 'day' | 'week' | 'month') | undefined, groupBy?: (Array<'account' | 'usageTerm' | 'pricingRule' | 'checkType'>) | undefined, include?: (Array<'calculations' | 'runs' | 'monitorDays'>) | undefined, 'x-checkly-account'?: string | undefined}; export type GetApiV2UsageSeriesOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const usageV2PricingRule = z.union([z.object({method: z.literal("per_unit"), quantity: z.number().gt(0), unit: z.string().min(1), credits: z.number().gte(0), rates: z.array(z.object({when: z.string().min(1), credits: z.number().gte(0)})).optional(), included: z.object({quantity: z.number().gte(0), period: z.string().min(1).optional()}).optional()}), z.object({method: z.literal("per_period"), period: z.literal("day"), price: z.object({annualCredits: z.number().gte(0)})}), z.object({method: z.literal("capacity_blocks_per_period"), period: z.literal("day"), unit: z.string().min(1), included: z.object({quantity: z.number().gte(0)}), block: z.object({quantity: z.number().gt(0), annualCredits: z.number().gte(0)})})]); export const usageV2Calculation = z.union([z.object({rateCondition: z.string().nullable(), measuredQuantity: z.number().gte(0), includedQuantity: z.number().gte(0).nullable(), billableQuantity: z.number().gte(0).nullable(), creditsUsed: z.number().gte(0).nullable()}), z.object({billableResourceDays: z.number().gte(0), appliedDailyCredits: z.number().gte(0), proration: z.object({daysPerYear: z.literal(365)}), creditsUsed: z.number().gte(0).nullable()}), z.object({scope: z.literal("statusPage"), measuredQuantity: z.number().gte(0), includedQuantity: z.number().gte(0), billableBlockDays: z.number().gte(0), appliedDailyCreditsPerBlock: z.number().gte(0), proration: z.object({daysPerYear: z.literal(365)}), creditsUsed: z.number().gte(0).nullable()})]); export const usageV2Contribution = z.object({usageTermsId: z.string(), pricingRuleKey: z.enum(["apiChecks", "multistepChecks", "browserChecks", "playwrightCheckSuites", "uptimeMonitors", "aiInvocations", "statusPages", "statusPageAdditionalServices", "statusPageAdditionalSubscribers", "additionalSms", "additionalPhoneAlerts"]), creditsUsed: z.number().gte(0).nullable(), period: z.object({from: z.string(), to: z.string()}).optional(), pricingRule: usageV2PricingRule.optional(), calculations: z.array(usageV2Calculation).optional()}); export const usageV2SeriesRow = z.object({periodStart: z.string(), periodEnd: z.string(), dimensions: z.object({accountId: z.string().optional(), usageTermsId: z.string().optional(), pricingRuleKey: z.enum(["apiChecks", "multistepChecks", "browserChecks", "playwrightCheckSuites", "uptimeMonitors", "aiInvocations", "statusPages", "statusPageAdditionalServices", "statusPageAdditionalSubscribers", "additionalSms", "additionalPhoneAlerts"]).optional(), checkType: z.enum(["AGENTIC", "API", "BROWSER", "HEARTBEAT", "ICMP", "MULTI_STEP", "TCP", "PLAYWRIGHT", "URL", "DNS", "SSL", "GRPC", "TRACEROUTE", "null"]).nullable().optional()}), creditsUsed: z.number().gte(0).nullable(), contributions: z.array(usageV2Contribution), monitorDays: z.number().int().gte(0).nullable().optional(), runs: 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), 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)}).nullable().optional()}); export const usageV2SeriesResponse = z.object({period: z.object({from: z.string(), to: z.string()}), usageTermsIds: z.array(z.string()), interval: z.enum(["total", "day", "week", "month"]), groupBy: z.array(z.enum(["account", "usageTerm", "pricingRule", "checkType"])), data: z.array(usageV2SeriesRow), coverage: z.object({gaps: z.array(z.object({from: z.string(), to: z.string()}))}), 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 usage series * * GET /v2/usage/series */ export const getApiV2UsageSeries = async (args: GetApiV2UsageSeriesArgs, options?: GetApiV2UsageSeriesOptions) => { 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.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) for (const item of args.usageTermsIds ?? []) query.append("usageTermsIds", String(item)) for (const item of args.accountIds ?? []) query.append("accountIds", String(item)) for (const item of args.pricingRuleKeys ?? []) query.append("pricingRuleKeys", String(item)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.nextId != null) query.append("nextId", String(args.nextId)) if (args.interval != null) query.append("interval", String(args.interval)) for (const item of args.groupBy ?? []) query.append("groupBy", String(item)) for (const item of args.include ?? []) query.append("include", String(item)) 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(/\/+$/, '')}/v2/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(usageV2SeriesResponse, await res.json()) };