import {z} from 'zod' export type CreateApiPipelinesOutputStreamArgs = {response_schema_v?: ('v1' | 'v2') | undefined, body: {sql: string}}; export type CreateApiPipelinesOutputStreamOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const resourceId = z.string(); export const streamType = z.enum(["APPEND", "CHANGE"]); export const recordSchema = z.array(z.object({name: z.string().optional(), type: z.string().optional()})); export const physicalField = z.object({kind: z.literal("physical"), name: z.string().optional(), type: z.string().optional()}); export const computedField = z.object({kind: z.literal("computed"), name: z.string().optional(), expression: z.string().optional()}); export const metadataField = z.object({kind: z.literal("metadata"), name: z.string().optional(), type: z.string().optional(), key: z.string().optional()}); export const schemaV2 = z.object({fields: z.array(z.discriminatedUnion("kind", [physicalField, computedField, metadataField])).optional(), watermarks: z.array(z.object({name: z.string().optional(), expression: z.string().optional()})).optional(), constraints: z.object({primary_key: z.array(z.string()).optional()}).optional()}); export const stream = z.union([z.object({id: resourceId.optional(), type: streamType.optional(), name: z.string().optional(), description: z.string().optional(), watermark: z.string().optional(), schema: recordSchema, schema_v2: schemaV2.optional(), properties: z.record(z.string(), z.string().nullable()).optional(), partition_key: z.array(z.string()).optional(), create_time: z.string().optional(), update_time: z.string().optional()}), z.object({id: resourceId.optional(), type: streamType.optional(), name: z.string().optional(), description: z.string().optional(), watermark: z.string().optional(), schema: recordSchema.optional(), schema_v2: schemaV2, properties: z.record(z.string(), z.string().nullable()).optional(), partition_key: z.array(z.string()).optional(), create_time: z.string().optional(), update_time: z.string().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 the output stream given a pipeline sql. * * POST /pipelines/outputStream * * Also accepts auth: oauth2 */ export const createApiPipelinesOutputStream = async (args: CreateApiPipelinesOutputStreamArgs, options?: CreateApiPipelinesOutputStreamOptions) => { const {baseUrl = "https://replace-with-account.api.decodable.co/v1alpha2", 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.response_schema_v != null) query.append("response_schema_v", String(args.response_schema_v)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/pipelines/outputStream${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(stream, await res.json()) };