import {z} from 'zod' export type CreateApiDocumentsUploadArgs = {author?: (string | null) | undefined, tags?: (string | null) | undefined, source_url?: (string | null) | undefined, description?: (string | null) | undefined, original_date?: (string | null) | undefined, effective_from?: (string | null) | undefined, pot_id?: (string | null) | undefined, body: BodyInit}; export type CreateApiDocumentsUploadOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const documentUploadResponse = z.object({document_id: z.string(), filename: z.string(), size_bytes: z.number().int(), stored_bytes: z.number().int(), type: z.string(), conversion_status: z.string(), message: 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 }; /** * Upload a document file * * POST /documents/upload */ export const createApiDocumentsUpload = async (args: CreateApiDocumentsUploadArgs, options: CreateApiDocumentsUploadOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.author != null) query.append("author", String(args.author)) if (args.tags != null) query.append("tags", String(args.tags)) if (args.source_url != null) query.append("source_url", String(args.source_url)) if (args.description != null) query.append("description", String(args.description)) if (args.original_date != null) query.append("original_date", String(args.original_date)) if (args.effective_from != null) query.append("effective_from", String(args.effective_from)) if (args.pot_id != null) query.append("pot_id", String(args.pot_id)) const url = `${baseUrl.replace(/\/+$/, '')}/documents/upload${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(documentUploadResponse, await res.json()) };