import {z} from 'zod' export type ScimSearchRequest = {count?: number | undefined, filter?: string | undefined, schemas?: Array<'urn:ietf:params:scim:api:messages:2.0:SearchRequest'> | undefined, startIndex?: number | undefined}; export type CreateApiScimV2UsersSearchArgs = {body: ScimSearchRequest}; export type CreateApiScimV2UsersSearchOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const scimUserAddress = z.object({country: z.string().optional(), locality: z.string().optional(), postalCode: z.string().optional(), region: z.string().optional(), streetAddress: z.string().optional(), type: z.literal("work")}); export const scimEmail = z.object({type: z.literal("work"), value: z.string()}); export const scimName = z.object({familyName: z.string(), givenName: z.string()}); export const scimPhoneNumber = z.object({type: z.enum(["work", "mobile", "other"]), value: z.string()}); export const scimPhoto = z.object({type: z.literal("photo"), value: z.string()}); export const scimEnterpriseUser = z.object({department: z.string().optional()}); export const scimMeta = z.object({created: z.string().optional(), lastModified: z.string().optional(), location: z.string().optional(), resourceType: z.enum(["User", "Group", "ResourceType", "Schema"]).optional()}); export const scimUserResponse = z.object({active: z.boolean().optional(), addresses: z.array(scimUserAddress).optional(), emails: z.array(scimEmail), externalId: z.string().optional(), id: z.string().optional(), name: scimName, phoneNumbers: z.array(scimPhoneNumber).optional(), photos: z.array(scimPhoto).optional(), schemas: z.array(z.literal("urn:ietf:params:scim:schemas:core:2.0:User")), title: z.string().optional(), "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": scimEnterpriseUser.optional(), userName: z.string(), meta: scimMeta.optional()}); export const scimUserSearchResponse = z.object({Resources: z.array(scimUserResponse).optional(), itemsPerPage: z.number().int().optional(), schemas: z.array(z.literal("urn:ietf:params:scim:api:messages:2.0:ListResponse")).optional(), startIndex: z.number().int().optional(), totalResults: z.number().int().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/List Users * * POST /scim/v2/Users/.search */ export const createApiScimV2UsersSearch = async (args: CreateApiScimV2UsersSearchArgs, options?: CreateApiScimV2UsersSearchOptions) => { const {baseUrl = "https://platform.ringcentral.com", fetch: fetchFn = fetch, OAuth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (OAuth2 !== undefined) headers.set('authorization', `Bearer ${OAuth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/scim/v2/Users/.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(scimUserSearchResponse, await res.json()) };