import {z} from 'zod' export type GetApiV1DocumentArgs = {company_id: string, document_category: 'current_printout' | 'chronological_printout' | 'historical_printout' | 'structured_information' | 'shareholder_list' | 'articles_of_association'}; export type GetApiV1DocumentOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const realtimeDocumentResponse = z.object({url: z.string(), category: z.enum(["current_printout", "chronological_printout", "historical_printout", "structured_information", "shareholder_list", "articles_of_association"]), file_date: z.string().nullable(), file_name: z.string().nullable()}); 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 }; /** * Fetch a document in realtime. * * GET /v1/document */ export const getApiV1Document = async (args: GetApiV1DocumentArgs, options?: GetApiV1DocumentOptions) => { const {baseUrl = "https://api.openregister.de", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.company_id != null) query.append("company_id", String(args.company_id)) if (args.document_category != null) query.append("document_category", String(args.document_category)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/document${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(realtimeDocumentResponse, await res.json()) };