import {z} from 'zod' export type AlertThresholdInput = {code?: (string | null) | undefined, notify_on?: (Array<'triggered' | 'resolved'>) | undefined, recurring?: boolean | undefined, value: number | string}; export type AlertCreateInput = {alert: {code: string, name?: (string | null) | undefined, thresholds: Array, alert_type: 'current_usage_amount' | 'billable_metric_current_usage_amount' | 'billable_metric_current_usage_units' | 'lifetime_usage_amount' | 'billable_metric_lifetime_usage_units', billable_metric_code?: (string | null) | undefined}}; export type AlertBatchCreateInput = {alerts: Array<{code: string, name?: (string | null) | undefined, thresholds: Array, alert_type: 'current_usage_amount' | 'billable_metric_current_usage_amount' | 'billable_metric_current_usage_units' | 'lifetime_usage_amount' | 'billable_metric_lifetime_usage_units', billable_metric_code?: (string | null) | undefined}>}; export type CreateApiSubscriptionsExternalIdAlertsArgs = {subscription_status?: ('pending' | 'active' | 'terminated' | 'canceled' | 'incomplete') | undefined, body: AlertCreateInput | AlertBatchCreateInput}; export type CreateApiSubscriptionsExternalIdAlertsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const billableMetricFilterObject = z.object({key: z.string(), values: z.array(z.string())}); export const billableMetricObject = z.object({lago_id: z.string(), name: z.string(), code: z.string(), description: z.string().nullable(), recurring: z.boolean(), rounding_function: z.enum(["ceil", "floor", "round", "null"]).nullable(), rounding_precision: z.number().int().nullable(), created_at: z.string(), expression: z.string().nullable(), field_name: z.string().nullable(), aggregation_type: z.enum(["count_agg", "sum_agg", "max_agg", "unique_count_agg", "weighted_sum_agg", "latest_agg"]), weighted_interval: z.enum(["seconds", "null"]).nullable(), filters: z.array(billableMetricFilterObject)}); export const alertThresholdObject = z.object({code: z.string().nullable(), notify_on: z.array(z.enum(["triggered", "resolved"])), recurring: z.boolean(), value: z.string()}); export const alertObject = z.object({lago_id: z.string(), lago_organization_id: z.string(), external_subscription_id: z.string(), lago_wallet_id: z.unknown(), wallet_code: z.unknown(), billable_metric: billableMetricObject.nullable(), alert_type: z.enum(["current_usage_amount", "billable_metric_current_usage_amount", "billable_metric_current_usage_units", "lifetime_usage_amount", "billable_metric_lifetime_usage_units"]), code: z.string(), name: z.string().nullable(), direction: z.enum(["increasing", "decreasing"]), previous_value: z.string(), last_processed_at: z.string().nullable(), thresholds: z.array(alertThresholdObject), created_at: z.string()}); export const alert = z.object({alert: alertObject}); export const paginationMeta = z.object({current_page: z.number().int(), next_page: z.number().int().nullable().optional(), prev_page: z.number().int().nullable().optional(), total_pages: z.number().int(), total_count: z.number().int()}); export const alerts = z.object({alerts: z.array(alertObject), meta: paginationMeta.optional()}); export const createApiSubscriptionsExternalIdAlertsResponse = z.union([alert, alerts]); 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 }; /** * Create subscription alert(s) * * POST /subscriptions/{external_id}/alerts */ export const createApiSubscriptionsExternalIdAlerts = async (args: CreateApiSubscriptionsExternalIdAlertsArgs, options?: CreateApiSubscriptionsExternalIdAlertsOptions) => { const {baseUrl = "https://api.getlago.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.subscription_status != null) query.append("subscription_status", String(args.subscription_status)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/subscriptions/${encodeURIComponent(String(args.external_id))}/alerts${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiSubscriptionsExternalIdAlertsResponse, await res.json()) };