import {z} from 'zod' export type GetApiCrmLeadsArgs = {fields?: (string | null) | undefined, pageSize?: (string | null) | undefined, cursor?: (string | null) | undefined, associations?: (string | null) | undefined}; export type GetApiCrmLeadsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const commonResponseStatus = z.enum(["ok", "error"]); export const commonLead = z.object({id: z.string(), remoteId: z.string(), createdTimestamp: z.unknown(), updatedTimestamp: z.unknown(), additional: z.unknown(), firstName: z.string(), lastName: z.string(), phone: z.string(), email: z.string()}); export const crmGetLeadsResponse = z.object({status: commonResponseStatus, next: z.string().nullable().optional(), previous: z.string().nullable().optional(), results: z.array(commonLead)}); 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 }; /** * Get all the leads * * GET /crm/leads */ export const getApiCrmLeads = async (args: GetApiCrmLeadsArgs, options?: GetApiCrmLeadsOptions) => { const {baseUrl = "https://api.revert.dev", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.fields != null) query.append("fields", String(args.fields)) if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.associations != null) query.append("associations", String(args.associations)) const url = `${baseUrl.replace(/\/+$/, '')}/crm/leads${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(crmGetLeadsResponse, await res.json()) };