import {z} from 'zod' export type GetApiV2BillingProductsArgs = {name?: string | undefined, quantityType?: string | undefined, accountCode?: string | undefined}; export type GetApiV2BillingProductsOptions = {baseUrl: string, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV2BillingProductsResponse = z.array(z.object({id: z.number().int().optional(), name: z.string().optional(), description: z.string().optional(), quantityType: z.enum(["MANUAL", "DEVICE_COUNTS", "TIME_ENTRIES", "END_USER_COUNTS", "BACKUP_STORAGE_COUNTS", "SOFTWARE_LICENSE"]).optional(), content: z.object({}).optional(), createTime: z.number().optional(), updateTime: z.number().optional(), accountId: z.number().int().optional(), group: z.boolean().optional(), taxId: z.number().int().nullable().optional(), inheritTaxFromAgreement: z.boolean().optional(), active: z.boolean().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 }; /** * Get all products * * GET /v2/billing/products * * Also accepts auth: sessionKey */ export const getApiV2BillingProducts = async (args: GetApiV2BillingProductsArgs, options: GetApiV2BillingProductsOptions) => { const {baseUrl, fetch: fetchFn = fetch, oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.name != null) query.append("name", String(args.name)) if (args.quantityType != null) query.append("quantityType", String(args.quantityType)) if (args.accountCode != null) query.append("accountCode", String(args.accountCode)) if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/billing/products${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(getApiV2BillingProductsResponse, await res.json()) };