import {z} from 'zod' export type GetApiSqlSqlIDOptions = {baseUrl?: string | undefined, ProfileToken?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiSqlSqlIDResponse = z.object({status: z.boolean().optional(), result: z.object({id: z.string().optional(), name: z.string().optional(), description: z.string().optional(), query: z.string().optional(), params: z.array(z.object({key: z.string().optional(), value: z.string().optional()})).optional(), cache_enabled: z.boolean().optional(), cache_ttl_seconds: z.number().int().optional(), rate_limit_rpm: z.number().int().optional(), active: z.boolean().optional(), tags: z.array(z.object({key: z.string().optional(), value: z.string().optional()})).optional(), session_context: z.boolean().optional(), version: z.number().int().optional(), cache_version: z.number().int().optional(), created_at: z.string().optional(), updated_at: z.string().optional()}).optional()}); 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 SQL Query * * GET /sql/{sqlID} */ export const getApiSqlSqlID = async (options?: GetApiSqlSqlIDOptions) => { const {baseUrl = "https://api.us-e1.tago.io", fetch: fetchFn = fetch, ProfileToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (ProfileToken !== undefined) headers.set("Profile-Token", ProfileToken) const url = `${baseUrl.replace(/\/+$/, '')}/sql/${encodeURIComponent(String(args.sqlID))}${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(getApiSqlSqlIDResponse, await res.json()) };