import {z} from 'zod' export type GetApiV3ContactsSearchFirstArgs = {email?: string | undefined, phone?: string | undefined}; export type GetApiV3ContactsSearchFirstOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const contactable = z.object({id: z.string().optional(), type: z.string().optional(), attributes: z.object({locale: z.string().optional(), email: z.string().optional(), is_company: z.boolean().optional(), first_name: z.string().optional(), last_name: z.string().optional(), company: z.string().optional(), phone: z.string().optional(), mobile_phone: z.string().optional(), tags: z.array(z.string()).optional()}).optional(), links: z.object({url: z.string().optional()}).optional(), meta: z.object({temp_id: z.string().optional()}).optional()}); export const getApiV3ContactsSearchFirstResponse = z.object({data: contactable.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 }; /** * GET contacts/search/first * * GET /v3/contacts/search/first * * Also accepts auth: OAuth2 */ export const getApiV3ContactsSearchFirst = async (args: GetApiV3ContactsSearchFirstArgs, options?: GetApiV3ContactsSearchFirstOptions) => { const {baseUrl = "https://api.bookingexperts.com", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/vnd.api+json") if (args.email != null) query.append("email", String(args.email)) if (args.phone != null) query.append("phone", String(args.phone)) if (ApiKeyAuth !== undefined) headers.set("X-API-KEY", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/v3/contacts/search/first${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(getApiV3ContactsSearchFirstResponse, await res.json()) };