import {z} from 'zod' export type PageLimit = number; export type PageCursor = string; export type CurrencyCode = string; export type ProductType = 'PRODUCT' | 'BUNDLE'; export type GetApiProductsArgs = {status?: string | undefined, limit?: PageLimit | undefined, cursor?: PageCursor | undefined, currency?: CurrencyCode | undefined, type?: Array | undefined}; export type GetApiProductsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const productType = z.enum(["PRODUCT", "BUNDLE"]); export const currencyCode = z.string(); export const monetaryAmount = z.object({amount: z.string(), currency: currencyCode}); export const fixedRecurringPrice = z.object({amount: monetaryAmount, interval_months: z.number().int().gte(1).lte(12), type: z.string()}); export const oneTimePrice = z.object({amount: monetaryAmount, type: z.string()}); export const perUnitBilling = z.object({type: z.string(), amount: monetaryAmount, units: z.number().int().gte(1)}); export const tier = z.object({up_to: z.number().int().gte(1), flat_price: monetaryAmount.optional(), per_unit_price: monetaryAmount.optional()}); export const tieredBilling = z.object({type: z.string(), mode: z.enum(["GRADUATED", "METERED"]), tiers: z.array(tier)}); export const billingScheme = z.discriminatedUnion("type", [perUnitBilling, tieredBilling]); export const usagePrice = z.object({interval_months: z.number().int().gte(1).lte(12), type: z.string(), billing_scheme: billingScheme}); export const price = z.discriminatedUnion("type", [fixedRecurringPrice, oneTimePrice, usagePrice]); export const revenuePattern = z.enum(["DAILY", "EVEN_PERIOD", "PROGRESS"]); export const progressMeasure = z.literal("MILESTONES"); export const milestoneValueMode = z.enum(["PERCENTAGE", "AMOUNT"]); export const milestoneExpectedOffset = z.object({count: z.number().int().gte(0), unit: z.enum(["DAYS", "MONTHS", "YEARS"])}); export const milestoneTemplate = z.object({key: z.string(), name: z.string().min(1), sequence: z.number().int().gte(1), value: z.string(), expected_offset: milestoneExpectedOffset.nullable().optional(), id: z.string()}); export const progressPlanTemplate = z.object({measure: progressMeasure, value_mode: milestoneValueMode, milestones: z.array(milestoneTemplate)}); export const externalReference = z.object({type: z.string(), id: z.string(), url: z.string().optional()}); export const fieldAssignments = z.array(z.object({field_id: z.string(), field_value_id: z.string()})); export const accountCode = z.string(); export const bundleInvoiceDisplay = z.enum(["BUNDLE_AND_COMPONENTS", "BUNDLE_LINE_ONLY"]); export const bundleComponent = z.object({product_id: z.string(), quantity: z.string()}); export const bundleDetails = z.object({invoice_display: bundleInvoiceDisplay, components: z.array(bundleComponent)}); export const product = z.object({id: z.string(), type: productType, name: z.string(), description: z.string(), price: price, include_in_arr_mrr: z.boolean(), include_in_ssp: z.boolean().optional(), revenue_pattern: revenuePattern.optional(), progress_plan_template: progressPlanTemplate.nullable().optional(), external_references: z.array(externalReference).optional(), fields: fieldAssignments, status: z.enum(["ACTIVE", "INACTIVE"]), account_code: accountCode.optional(), bundle: bundleDetails.optional()}); export const pageCursor = z.string(); export const pagination = z.object({next_cursor: pageCursor.optional()}); export const getApiProductsResponse = z.object({products: z.array(product), pagination: pagination}); 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 }; /** * Lists all products * * GET /products */ export const getApiProducts = async (args: GetApiProductsArgs, options?: GetApiProductsOptions) => { const {baseUrl = "https://api.rillet.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.status != null) query.append("status", String(args.status)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.currency != null) query.append("currency", String(args.currency)) if (args.type != null) query.append("type", args.type.join(',')) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/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(getApiProductsResponse, await res.json()) };