import {z} from 'zod' export type ContactChannelInput = {channel: 'sms' | 'whatsapp' | 'email' | 'telegram' | 'instagram' | 'messenger' | 'voice', identifier: string, countryCode?: string | undefined, label?: string | undefined, isPrimary?: boolean | undefined}; export type ContactCreateRequest = {displayName?: string | undefined, channels: Array, metadata?: {[key: string]: string} | undefined}; export type CreateApiV1ContactsArgs = {body: ContactCreateRequest}; export type CreateApiV1ContactsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const contactChannel = z.object({id: z.string(), channel: z.enum(["sms", "whatsapp", "email", "telegram", "instagram", "messenger", "voice"]), identifier: z.string(), countryCode: z.string().optional(), label: z.string().optional(), isPrimary: z.boolean(), verified: z.boolean(), metrics: z.object({successCount: z.number().int().optional(), failureCount: z.number().int().optional(), totalAttempts: z.number().int().optional(), avgDeliveryTimeMs: z.number().optional(), lastSuccessAt: z.string().optional()}).optional(), lastInboundAt: z.string().optional(), metadata: z.record(z.string(), z.string()).optional(), createdAt: z.string(), updatedAt: z.string().optional()}); export const contact = z.object({id: z.string(), displayName: z.string().optional(), phoneNumber: z.string().optional(), primaryPhone: z.string().optional(), primaryEmail: z.string().optional(), countryCode: z.string().optional(), profileName: z.string().nullable().optional(), whatsapp: z.object({bsuid: z.string(), username: z.string().optional()}).optional(), availableChannels: z.array(z.string()), defaultChannel: z.enum(["sms", "whatsapp", "telegram", "email", "instagram", "messenger", "voice"]).optional(), verified: z.boolean(), channels: z.array(contactChannel).optional(), metadata: z.record(z.string(), z.string()), createdAt: z.string(), updatedAt: z.string().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 }; /** * Create contact * * POST /v1/contacts */ export const createApiV1Contacts = async (args: CreateApiV1ContactsArgs, options?: CreateApiV1ContactsOptions) => { const {baseUrl = "https://api.zavu.dev", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/contacts${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(contact, await res.json()) };