import {z} from 'zod' export type MemoryVisibility = 'private' | 'org'; export type SourcePayload = {content: string, content_type?: ('text' | 'markdown' | 'conversation' | 'html' | 'json' | 'pdf' | 'image' | 'audio' | 'video') | undefined, role?: string | undefined, visibility?: MemoryVisibility | undefined, meta?: ({[key: string]: unknown} | null) | undefined}; export type IngestSourcesRequest = {space_id: string, sources: Array}; export type CreateApiApiV1SourcesArgs = {body: IngestSourcesRequest}; export type CreateApiApiV1SourcesOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const ingestAcceptedResponse = z.object({job_id: z.string(), status: z.literal("pending"), source_ids: z.array(z.string()), jobs: z.array(z.object({job_id: z.string(), source_ids: z.array(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 }; /** * Ingest Sources * * POST /api/v1/sources */ export const createApiApiV1Sources = async (args: CreateApiApiV1SourcesArgs, options: CreateApiApiV1SourcesOptions) => { const {baseUrl, 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 (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/sources${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(ingestAcceptedResponse, await res.json()) };