import {z} from 'zod' export type GetApiV1IdentityResolveArgs = {channel: string, external_id: string, org_external_end_user_id?: (string | null) | undefined}; export type GetApiV1IdentityResolveOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const resolveIdentityResponse = z.object({end_user_id: z.string(), org_id: z.string(), is_new: z.boolean(), context_level: z.string(), display_name: z.string().nullable().optional(), primary_email: z.string().nullable().optional(), primary_phone: z.string().nullable().optional(), org_external_end_user_id: z.string().nullable().optional(), external_id_ignored: z.string().nullable().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 }; /** * Look up an end user by channel + external_id (read-only, no mutation) * * GET /v1/identity/resolve */ export const getApiV1IdentityResolve = async (args: GetApiV1IdentityResolveArgs, options: GetApiV1IdentityResolveOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.channel != null) query.append("channel", String(args.channel)) if (args.external_id != null) query.append("external_id", String(args.external_id)) if (args.org_external_end_user_id != null) query.append("org_external_end_user_id", String(args.org_external_end_user_id)) if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/identity/resolve${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(resolveIdentityResponse, await res.json()) };