import {z} from 'zod' export type V3CheckRequest = {object_id: string, object_type: string, relation: string, subject_id: string, subject_type: string, trace?: boolean | undefined}; export type V3ChecksRequest = {checks?: Array | undefined, default?: V3CheckRequest | undefined}; export type CreateApiApiV3DirectoryChecksArgs = {body: V3ChecksRequest}; export type CreateApiApiV3DirectoryChecksOptions = {baseUrl: string, DirectoryAPIKey?: string | undefined, TenantID?: string | undefined, fetch?: typeof fetch | undefined}; export const v3CheckResponse = z.object({check: z.boolean().optional(), context: z.object({}).optional(), trace: z.array(z.string()).optional()}); export const v3ChecksResponse = z.object({checks: z.array(v3CheckResponse).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 }; /** * Checks * * POST /api/v3/directory/checks */ export const createApiApiV3DirectoryChecks = async (args: CreateApiApiV3DirectoryChecksArgs, options: CreateApiApiV3DirectoryChecksOptions) => { const {baseUrl, fetch: fetchFn = fetch, DirectoryAPIKey, TenantID} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (DirectoryAPIKey !== undefined) headers.set("authorization", DirectoryAPIKey) if (TenantID !== undefined) headers.set("aserto-tenant-id", TenantID) const url = `${baseUrl.replace(/\/+$/, '')}/api/v3/directory/checks${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(v3ChecksResponse, await res.json()) };