import {z} from 'zod' export type GetApiApiV3SubmissionsIdResultsArgs = {id: string, cursor?: string | undefined, limit?: number | undefined}; export type GetApiApiV3SubmissionsIdResultsOptions = {baseUrl: string, submissionBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const submissionApiPhase = z.object({state: z.enum(["pending", "running", "not_started", "dispatching", "dispatched", "complete", "failed", "skipped", "unknown"]), message: z.string().min(1).optional()}).and(z.record(z.string(), z.unknown())); export const submissionApiResultRow = z.object({clientRowId: z.string().min(1), encounterIds: z.array(z.string()), occurrenceIds: z.array(z.string().min(1)), individualIds: z.array(z.string().min(1)), mediaAssetIds: z.array(z.number().int().gte(0))}).and(z.record(z.string(), z.unknown())); export const submissionApiIssue = z.object({code: z.string().min(1), message: z.string().min(1), clientRowId: z.string().min(1).optional(), rowIndex: z.number().int().gte(0).optional(), field: z.string().min(1).optional(), reason: z.string().min(1).optional(), limit: z.number().optional()}).and(z.record(z.string(), z.unknown())); export const submissionApiResults = z.object({submissionId: z.string(), state: z.enum(["draft", "validated", "queued", "importing", "imported", "failed", "needs_reconciliation", "cancelled", "expired"]), indexing: submissionApiPhase, detection: submissionApiPhase, identification: submissionApiPhase, rows: z.array(submissionApiResultRow), nextCursor: z.string().min(1).optional(), errors: z.array(submissionApiIssue), links: z.record(z.string(), z.string()).optional(), derivatives: submissionApiPhase.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 }; /** * Stable row-order pagination; records may share entities. Downstream failure does not undo successful import. Before results exist returns empty rows and current state. * * GET /api/v3/submissions/{id}/results */ export const getApiApiV3SubmissionsIdResults = async (args: GetApiApiV3SubmissionsIdResultsArgs, options: GetApiApiV3SubmissionsIdResultsOptions) => { const {baseUrl, fetch: fetchFn = fetch, submissionBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.limit != null) query.append("limit", String(args.limit)) if (submissionBearer !== undefined) headers.set('authorization', `Bearer ${submissionBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v3/submissions/${encodeURIComponent(String(args.id))}/results${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(submissionApiResults, await res.json()) };