import {z} from 'zod' export type GetApiApiV1UserOrgOptions = {baseUrl?: string | undefined, cookieAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const organizationMember = z.object({id: z.number().int(), name: z.string(), email: z.string(), role: z.enum(["owner", "admin", "member"])}); export const organizationInvite = z.object({id: z.number().int(), email: z.string(), role: z.string(), created_at: z.string(), expires_at: z.string()}); export const userOrganizationResponse = z.object({org: z.object({id: z.number().int(), name: z.string(), my_role: z.string()}).nullable().optional(), can_team: z.boolean().optional(), seats: z.object({used: z.number().int(), max: z.number().int()}).optional(), members: z.array(organizationMember).optional(), invites: z.array(organizationInvite).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 the current organization, seats and visible members * * GET /api/v1/user/org */ export const getApiApiV1UserOrg = async (options?: GetApiApiV1UserOrgOptions) => { const {baseUrl = "https://openmercantil.es", fetch: fetchFn = fetch, cookieAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (cookieAuth !== undefined) cookies.push("ob_sess=" + encodeURIComponent(cookieAuth)) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/user/org${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(userOrganizationResponse, await res.json()) };