import {z} from 'zod' export type GetApiScimV2ResourceTypesOptions = {baseUrl?: string | undefined, OAuth2?: string | undefined, fetch?: typeof fetch | undefined}; export const scimSchemaExtension = z.object({schema: z.literal("urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"), required: z.boolean()}); 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 scimResourceTypeResponse = z.object({id: z.string().optional(), name: z.string(), endpoint: z.string(), description: z.string().optional(), schema: z.literal("urn:ietf:params:scim:schemas:core:2.0:User"), schemaExtensions: z.array(scimSchemaExtension).optional(), meta: scimMeta.optional()}); export const scimResourceTypeSearchResponse = z.object({Resources: z.array(scimResourceTypeResponse).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 }; /** * List Resource Types * * GET /scim/v2/ResourceTypes */ export const getApiScimV2ResourceTypes = async (options?: GetApiScimV2ResourceTypesOptions) => { const {baseUrl = "https://platform.ringcentral.com", fetch: fetchFn = fetch, OAuth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (OAuth2 !== undefined) headers.set('authorization', `Bearer ${OAuth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/scim/v2/ResourceTypes${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(scimResourceTypeSearchResponse, await res.json()) };