import {z} from 'zod' export type GetApiV2RolesOptions = {baseUrl: string, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV2RolesResponse = z.array(z.object({id: z.number().int().optional(), name: z.string().optional(), description: z.string().optional(), nodeClass: z.enum(["WINDOWS_SERVER", "WINDOWS_WORKSTATION", "LINUX_WORKSTATION", "MAC", "ANDROID", "APPLE_IOS", "APPLE_IPADOS", "AOSP", "CHROMEOS", "VMWARE_VM_HOST", "VMWARE_VM_GUEST", "HYPERV_VMM_HOST", "HYPERV_VMM_GUEST", "LINUX_SERVER", "MAC_SERVER", "CLOUD_MONITOR_TARGET", "NMS_SWITCH", "NMS_ROUTER", "NMS_FIREWALL", "NMS_PRIVATE_NETWORK_GATEWAY", "NMS_PRINTER", "NMS_SCANNER", "NMS_DIAL_MANAGER", "NMS_WAP", "NMS_IPSLA", "NMS_COMPUTER", "NMS_VM_HOST", "NMS_APPLIANCE", "NMS_OTHER", "NMS_SERVER", "NMS_PHONE", "NMS_VIRTUAL_MACHINE", "NMS_NETWORK_MANAGEMENT_AGENT", "UNMANAGED_DEVICE", "MANAGED_DEVICE"]).optional(), custom: z.boolean().optional(), chassisType: z.enum(["UNKNOWN", "DESKTOP", "LAPTOP", "MOBILE"]).optional(), created: z.number().optional(), nodeRoleParentId: z.number().int().optional(), icon: z.string().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 device roles * * GET /v2/roles * * Also accepts auth: sessionKey */ export const getApiV2Roles = async (options: GetApiV2RolesOptions) => { const {baseUrl, 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(/\/+$/, '')}/v2/roles${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(getApiV2RolesResponse, await res.json()) };