import {z} from 'zod' export type GetApiSubscriptionsArgs = {page?: number | undefined, per_page?: number | undefined, external_customer_id?: string | undefined, plan_code?: string | undefined, status?: (Array<'ACTIVE' | 'PENDING' | 'CANCELED' | 'TERMINATED'>) | undefined}; export type GetApiSubscriptionsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const subscriptionExternalId = z.string(); export const billingTime = z.enum(["CALENDAR", "ANNIVERSARY"]); export const subscriptionStatus = z.enum(["PENDING", "ACTIVE", "TERMINATED", "CANCELED"]); export const currency = z.string().min(3).max(3); export const amount = z.object({value: z.number().gte(0), currency_code: currency}); export const chargeModel = z.enum(["STANDARD", "GRADUATED", "PACKAGE", "PERCENTAGE", "VOLUME"]); export const taxCode = z.string(); export const taxResponse = z.object({name: z.string(), rate: z.string().optional(), description: z.string().optional(), code: taxCode.optional(), id: z.string().optional(), created_at: z.string().optional()}); export const usageBasedCharge = z.object({id: z.string(), metric_id: z.string(), charge_model: chargeModel.optional(), properties: z.object({}).optional(), taxes: z.array(taxResponse).optional(), min_amount: amount.optional()}); export const minimumCommitment = z.object({amount: amount, invoice_display_name: z.string().optional(), taxes: z.array(taxResponse).optional(), id: z.string().optional(), plan_code: z.string().optional(), created_at: z.string().optional(), updated_at: z.string().optional()}); export const dateTimeWithZone = z.string(); export const chargeUsageThresholdResponse = z.object({id: z.string().optional(), recurring: z.string().optional(), threshold_display_name: z.string().optional(), created_at: dateTimeWithZone.optional(), updated_at: dateTimeWithZone.optional(), amount: amount.optional()}); export const planOverridesResponse = z.object({amount: amount.optional(), description: z.string().optional(), invoice_display_name: z.string().optional(), name: z.string().optional(), charges: z.array(usageBasedCharge).optional(), minimum_commitment: minimumCommitment.optional(), chargeUsage: z.array(chargeUsageThresholdResponse).optional(), taxes: z.array(taxResponse).optional(), trial_period: z.number().int().optional()}); export const subscriptionResponse = z.object({name: z.string().optional(), start_date: z.string().optional(), end_date: z.string().optional(), external_customer_id: z.string(), external_id: subscriptionExternalId, plan_code: z.string(), billing_time: billingTime.optional(), id: z.string().optional(), status: subscriptionStatus.optional(), plan_overrides: planOverridesResponse.optional(), canceled_at: z.string().optional(), terminated_at: z.string().optional(), current_period_start: z.string().optional(), current_period_end: dateTimeWithZone.optional(), trial_ended_at: z.string().optional()}); export const paginationMetadata = z.object({total_count: z.number().int().optional(), total_pages: z.number().int().optional(), current_page: z.number().int().optional()}); export const getApiSubscriptionsResponse = z.object({subscriptions: z.array(subscriptionResponse).optional(), metadata: paginationMetadata.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 subscriptions * * GET /subscriptions */ export const getApiSubscriptions = async (args: GetApiSubscriptionsArgs, options?: GetApiSubscriptionsOptions) => { const {baseUrl = "https://api-m.sandbox.paypal.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.external_customer_id != null) query.append("external_customer_id", String(args.external_customer_id)) if (args.plan_code != null) query.append("plan_code", String(args.plan_code)) if (args.status != null) query.append("status", args.status.join(',')) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/subscriptions${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(getApiSubscriptionsResponse, await res.json()) };