import {z} from 'zod' export type GetApiCustomFieldsArgs = {entityType?: string | undefined}; export type GetApiCustomFieldsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const apiFieldValue = z.union([z.object({type: z.literal("string"), value: z.string()}), z.object({type: z.literal("url"), value: z.string()}), z.object({type: z.literal("int"), value: z.number().int()}), z.object({type: z.literal("number"), value: z.number()}), z.object({type: z.literal("date"), value: z.string()}), z.object({type: z.literal("boolean"), value: z.boolean()})]); export const apiCustomField = z.object({id: z.string(), name: z.string(), entityTypes: z.array(z.enum(["contact", "object", "organization"])), keyField: z.boolean(), valueType: z.enum(["string", "url", "int", "number", "date", "boolean"]), sampleValues: z.array(apiFieldValue).optional(), description: z.string().nullable().optional(), targetSubTypes: z.array(z.string()).optional(), providedBy: z.string().nullable().optional(), objectTypeId: z.string().optional()}); export const customFieldList = z.object({success: z.literal(true), data: z.array(apiCustomField)}); 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 }; /** * List custom fields * * GET /custom-fields */ export const getApiCustomFields = async (args: GetApiCustomFieldsArgs, options?: GetApiCustomFieldsOptions) => { const {baseUrl = "https://api.commonroom.io/api/v2", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.entityType != null) query.append("entityType", String(args.entityType)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/custom-fields${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(customFieldList, await res.json()) };