import {z} from 'zod' export type CreateUserGroupRequestBody = {user_group: {name?: string | undefined}}; export type CreateApiWorkspaceGroupsArgs = {workspace: string, body: CreateUserGroupRequestBody}; export type CreateApiWorkspaceGroupsOptions = {baseUrl?: string | undefined, accessTokenAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const link = z.object({href: z.string(), templated: z.boolean().optional()}); export const userGroupLinks = z.object({self: link, web: link, creator: link.optional(), group_memberships: link, membership_by_id: link, memberships_preview: link}); export const userGroupEmbeds = z.unknown(); export const userGroup = z.object({token: z.string(), group_type: z.string(), name: z.string(), description: z.string(), state: z.string(), member_count: z.string(), spaces_count: z.string(), data_sources_count: z.string(), managed: z.string(), _links: userGroupLinks, _embedded: userGroupEmbeds.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 a group * * POST /{workspace}/groups */ export const createApiWorkspaceGroups = async (args: CreateApiWorkspaceGroupsArgs, options?: CreateApiWorkspaceGroupsOptions) => { const {baseUrl = "https://modeanalytics.com/api", fetch: fetchFn = fetch, accessTokenAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/hal+json") if (accessTokenAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${accessTokenAuth.username}:${accessTokenAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(String(args.workspace))}/groups${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(userGroup, await res.json()) };