import {z} from 'zod' export type CreateApiServeArgs = {body: {serve_id: string, continuation_token?: string | undefined, max_events?: number | undefined, min_events?: number | undefined, timeout?: string | undefined, schema?: ('exact' | 'never' | 'name_and_type') | undefined}}; export type CreateApiServeOptions = {baseUrl: string, TenzirToken?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiServeResponse = z.object({next_continuation_token: z.string().nullable(), state: z.enum(["running", "completed", "failed"]), schemas: z.array(z.object({schema_id: z.string().optional(), type_id: z.string().optional(), definition: z.unknown()})).optional(), events: z.array(z.object({schema_id: z.string().optional(), schema: z.string().optional(), type_id: z.string().optional(), data: z.object({}).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 }; /** * Read pipeline output * * POST /serve */ export const createApiServe = async (args: CreateApiServeArgs, options: CreateApiServeOptions) => { const {baseUrl, fetch: fetchFn = fetch, TenzirToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (TenzirToken !== undefined) headers.set("X-Tenzir-Token", TenzirToken) const url = `${baseUrl.replace(/\/+$/, '')}/serve${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(createApiServeResponse, await res.json()) };