import {z} from 'zod' export type GroupSearchRequestObject = {schemas: Array, startIndex?: number | undefined, filter?: string | undefined}; export type CreateApiGroupsSearchArgs = {body: GroupSearchRequestObject}; export type CreateApiGroupsSearchOptions = {baseUrl?: string | undefined, OAuth2ClientCredentials?: string | undefined, fetch?: typeof fetch | undefined}; export const groupOb = z.object({displayName: z.string().optional(), meta: z.object({created: z.string().optional(), location: z.string().optional(), lastModified: z.string().optional()}).optional(), members: z.array(z.object({$ref: z.string().optional(), display: z.string().optional(), value: z.string().optional()})).optional(), roles: z.array(z.object({$ref: z.string().optional(), display: z.string().optional(), value: z.string().optional()})).optional(), id: z.string().optional()}); export const groupSearchResponseObject = z.object({totalResults: z.number().int().optional(), startIndex: z.number().int().optional(), itemsPerPage: z.number().int().optional(), schemas: z.array(z.string()).optional(), Resources: z.array(groupOb).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 }; /** * Search Groups * * POST /Groups/.search */ export const createApiGroupsSearch = async (args: CreateApiGroupsSearchArgs, options?: CreateApiGroupsSearchOptions) => { const {baseUrl = "https://api.asgardeo.io/t//scim2", fetch: fetchFn = fetch, OAuth2ClientCredentials} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/scim+json") headers.set('accept', "application/scim+json") if (OAuth2ClientCredentials !== undefined) headers.set('authorization', `Bearer ${OAuth2ClientCredentials}`) const url = `${baseUrl.replace(/\/+$/, '')}/Groups/.search${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(groupSearchResponseObject, await res.json()) };