import {z} from 'zod' export type GetApiV1CollectionsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const getApiV1CollectionsResponse = z.object({type: z.literal("sql_endpoint"), data: z.object({columns: z.array(z.object({col: z.string(), data_type: z.enum(["CHAR", "BIGINT", "DECIMAL", "INT", "UNSIGNED BIGINT", "TINYINT", "TIMESTAMP", "TEXT", "VARCHAR", "DATETIME", "DOUBLE", "FLOAT", "DATE", "TIME", "YEAR", "MEDIUMINT", "SMALLINT", "BIT", "BINARY", "VARBINARY", "JSON", "ENUM", "SET", "TINYTEXT", "MEDIUMTEXT", "LONGTEXT", "TINYBLOB", "MEDIUMBLOB", "BLOB", "LONGBLOB"]), nullable: z.boolean()}).and(z.record(z.string(), z.unknown()))), rows: z.array(z.object({repo_id: z.string().optional(), repo_name: z.string().optional()}).and(z.record(z.string(), z.unknown()))), result: z.object({code: z.number().optional(), message: z.string().optional(), start_ms: z.number().optional(), end_ms: z.number().optional(), latency: z.string().optional(), row_count: z.number().optional(), row_affect: z.number().optional(), limit: z.number().optional(), databases: z.array(z.string()).optional()}).and(z.record(z.string(), z.unknown()))})}); 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 collections * * GET /v1/collections/ */ export const getApiV1Collections = async (options: GetApiV1CollectionsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/collections/${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(getApiV1CollectionsResponse, await res.json()) };