import {z} from 'zod' export type AggFunction = 'avg' | 'min' | 'max' | 'sum' | 'count' | 'median' | 'p50' | 'p75' | 'p90' | 'p95' | 'p99'; export type Operator = '=' | '!=' | '>' | '>=' | '<' | '<=' | 'contains' | 'not_contains' | 'is_null' | 'is_not_null' | 'is_empty' | 'is_not_empty'; export type Condition = {column: string, ignore_case?: boolean | undefined, operator: Operator, value: Record}; export type Aggregation = {function: AggFunction, group_by?: (Array | null) | undefined, having: Condition, multi_alert?: boolean | undefined, warning_value?: (number | null) | undefined}; export type CompareHistoricData = {offSet: string}; export type SearchEventType = 'ui' | 'dashboards' | 'reports' | 'alerts' | 'values' | 'other' | 'rum' | 'derivedstream' | 'searchjob' | 'download' | 'insights' | 'public_dashboard'; export type SloAlertKind = 'error_budget' | 'burn_rate'; export type SloCondition = {critical: number, kind: SloAlertKind, long_window_secs?: (number | null) | undefined, multi_alert?: boolean | undefined, operator: Operator, short_window_secs?: (number | null) | undefined, slo_id: string, warning?: (number | null) | undefined}; export type QueryType = 'custom' | 'sql' | 'promql' | 'slo'; export type QueryCondition = {aggregation?: (Aggregation | null) | undefined, conditions?: (Record | null) | undefined, multi_time_range?: (Array | null) | undefined, promql?: (string | null) | undefined, promql_condition?: (Condition | null) | undefined, promql_multi_alert?: boolean | undefined, promql_rule_mode?: boolean | undefined, promql_warning_value?: (number | null) | undefined, search_event_type?: (SearchEventType | null) | undefined, slo_condition?: (SloCondition | null) | undefined, sql?: (string | null) | undefined, type?: QueryType | undefined, vrl_function?: (string | null) | undefined}; export type StreamType = 'logs' | 'metrics' | 'traces' | 'profiles' | 'service_graph' | 'enrichment_tables' | 'file_list' | 'metadata' | 'index'; export type CreateApiApiV2OrgIdAlertsGenerateSqlArgs = {org_id: string, body: {query_condition: QueryCondition, stream_name: string, stream_type: StreamType}}; export type CreateApiApiV2OrgIdAlertsGenerateSqlOptions = {baseUrl: string, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const generateSqlMetadata = z.object({has_aggregation: z.boolean(), has_conditions: z.boolean(), has_group_by: z.boolean()}); export const createApiApiV2OrgIdAlertsGenerateSqlResponse = z.object({metadata: generateSqlMetadata.nullable().optional(), sql: z.string()}); 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 }; /** * Generate SQL from alert query parameters * * POST /api/v2/{org_id}/alerts/generate_sql */ export const createApiApiV2OrgIdAlertsGenerateSql = async (args: CreateApiApiV2OrgIdAlertsGenerateSqlArgs, options: CreateApiApiV2OrgIdAlertsGenerateSqlOptions) => { const {baseUrl, fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/${encodeURIComponent(String(args.org_id))}/alerts/generate_sql${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(createApiApiV2OrgIdAlertsGenerateSqlResponse, await res.json()) };