import {z} from 'zod' export type Name = string; export type Email = string; export type UserPatch = {name?: Name | undefined, phone?: string | undefined, email?: Email | undefined, preferences?: Record | undefined, mfa_secret?: (string | null) | undefined}; export type PatchApiUsersIdArgs = {id: string, body: UserPatch}; export type PatchApiUsersIdOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const name = z.string().min(1); export const email = z.string().min(1).max(255); export const roles = z.array(z.string().min(1)); export const timestamp = z.string(); export const group = z.object({name: z.string().min(1).max(50).optional(), description: z.string().max(100).optional(), roles: z.array(z.string()).optional(), href: z.string().optional(), created: timestamp.optional(), updated: timestamp.optional()}); export const user = z.object({name: name.optional(), phone: z.string().optional(), email: email.optional(), preferences: z.object({}).optional(), mfa_secret: z.string().nullable().optional(), roles: z.array(roles).optional(), groups: z.array(group).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 }; /** * Update the current user * * PATCH /users/{id} */ export const patchApiUsersId = async (args: PatchApiUsersIdArgs, options?: PatchApiUsersIdOptions) => { const {baseUrl = "https://api.webscale.com/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/users/${encodeURIComponent(String(args.id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PATCH", 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(user, await res.json()) };