import {z} from 'zod' export type GetApiV2UsersArgs = {scope?: (string | null) | undefined}; export type GetApiV2UsersOptions = {baseUrl?: string | undefined, HEADER?: string | undefined, fetch?: typeof fetch | undefined}; export const userResponse = z.object({email: z.string(), first_name: z.string(), last_logged_in: z.string(), last_name: z.string(), locked: z.boolean(), scopes: z.array(z.enum(["CLIENT_ADMIN", "CLIENT_SUPERUSER", "SELF_SERVICE", "USER_SUPPORT"])), user_id: z.string()}); export const getApiV2UsersResponse = z.array(userResponse); 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 users * * GET /v2/users * * Also accepts auth: QUERY, COOKIE */ export const getApiV2Users = async (args: GetApiV2UsersArgs, options?: GetApiV2UsersOptions) => { const {baseUrl = "https://api.extole.io", fetch: fetchFn = fetch, HEADER} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.scope != null) query.append("scope", String(args.scope)) if (HEADER !== undefined) headers.set("Authorization", HEADER) const url = `${baseUrl.replace(/\/+$/, '')}/v2/users${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(getApiV2UsersResponse, await res.json()) };