import {z} from 'zod' export type SplitInstanceKey = {description: string, name: string, required?: boolean | undefined}; export type SplitSubclass = {description?: string | undefined, id: string, label: string}; export type SplitCategory = {description?: string | undefined, id: string, instance_key?: (SplitInstanceKey | null) | undefined, label: string, subclasses?: Array | undefined}; export type WorkspaceFileSource = {file_id: string, type?: 'workspace_file' | undefined, workspace_id: string}; export type SplitOutputOptions = {include_content?: boolean | undefined, materialize_files?: boolean | undefined}; export type PageRange = {end: number, start: number}; export type DocumentSplitRequest = {classes: Array, corpus_sources?: Array | undefined, name?: (string | null) | undefined, output?: SplitOutputOptions | undefined, overlap_policy?: ('exclusive' | 'shared_boundary_page') | undefined, page_ranges?: (Array | null) | undefined, parse_mode?: ('low' | 'medium' | 'high') | undefined, project_id?: (string | null) | undefined, quality?: ('auto' | 'fast' | 'accurate') | undefined, source: Record, split_rules?: (string | null) | undefined, unknown_policy?: ('include' | 'force' | 'error') | undefined}; export type CreateApiV1DocumentsSplitArgs = {'Idempotency-Key'?: string | undefined, wait_seconds?: number | undefined, body: DocumentSplitRequest}; export type CreateApiV1DocumentsSplitOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const documentTimingBreakdown = z.object({preparation_ms: z.number().int().gte(0).nullable(), queue_ms: z.number().int().gte(0).nullable(), ndi_processing_ms: z.number().int().gte(0).nullable(), result_preparation_ms: z.number().int().gte(0).nullable(), delivery_wait_ms: z.number().int().gte(0).nullable(), document_finalization_ms: z.number().int().gte(0).nullable()}); export const documentTiming = z.object({received_at: z.string(), observed_at: z.string(), completed_at: z.string().nullable(), elapsed_ms: z.number().int().nullable(), total_ms: z.number().int().nullable(), first_response_ms: z.number().int().nullable(), breakdown: documentTimingBreakdown}); export const documentCostLine = z.object({operation: z.enum(["parse", "split", "classify", "extract", "ground"]), quantity: z.number().int().gte(0), unit: z.enum(["page", "target"]), execution: z.enum(["fresh", "reused"]), unit_price_usd: z.string(), amount_usd: z.string(), reuse_reason: z.string().nullable()}); export const documentCost = z.object({currency: z.literal("USD"), pricing_version: z.string(), total_usd: z.string(), lines: z.array(documentCostLine)}); export const documentJob = z.object({job_id: z.string(), kind: z.enum(["parse", "split", "classify", "extract", "ground"]), status: z.enum(["queued", "running", "succeeded", "failed", "cancelled"]), result: z.unknown(), credits: z.number().int().nullable().optional(), usage_final: z.boolean().optional(), timing: documentTiming.optional(), cost: documentCost.nullable().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * Split a document * * POST /v1/documents/split */ export const createApiV1DocumentsSplit = async (args: CreateApiV1DocumentsSplitArgs, options?: CreateApiV1DocumentsSplitOptions) => { const {baseUrl = "https://console.nace.ai", 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['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args.wait_seconds != null) query.append("wait_seconds", String(args.wait_seconds)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/documents/split${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(documentJob, await res.json()) };