import {z} from 'zod' export type CreateApiSubscriptionsArgs = {'x-idempotency-key'?: string | undefined, body: {name: string, description?: string | undefined, account_id: string, merchant_reference?: string | undefined, soft_descriptor?: string | undefined, country: string, amount: {currency: string, value: number}, plan_id?: string | undefined, additional_data?: ({order?: ({items?: (Array<{id?: string | undefined, name?: string | undefined, quantity?: number | undefined, unit_amount?: number | undefined, category?: ('art' | 'baby' | 'coupons' | 'beauty_&_personal_care' | 'donations' | 'computing' | 'books' | 'grocery_&_gourmet_food' | 'cameras' | 'video_games' | 'television' | 'car_electronics' | 'electronics' | 'automotive' | 'toys_&_games' | 'musical_instruments' | 'handmade' | 'garden_&_outdoor' | 'entertainment' | 'industrial_&_scientific' | 'fashion' | 'games' | 'pet_supplies' | 'home' | 'musical' | 'phones' | 'services' | 'learnings' | 'tickets' | 'travels' | 'virtual_goods' | 'others') | undefined, brand?: string | undefined, sku_code?: string | undefined, manufacture_part_number?: string | undefined}>) | undefined}) | undefined}) | undefined, frequency?: ({type: 'DAY' | 'WEEK' | 'MONTH' | 'YEAR', value?: number | undefined}) | undefined, billing_cycles?: ({total?: number | undefined}) | undefined, customer_payer?: ({id?: string | undefined}) | undefined, payment_method: {type: 'CARD', vaulted_token?: string | undefined, card?: ({installments?: number | undefined, network_transaction_id?: string | undefined, store_credentials?: ({usage?: ('FIRST' | 'USED') | undefined}) | undefined}) | undefined}, trial_period?: ({billing_cycles?: number | undefined, amount?: {currency: string, value: number} | undefined}) | undefined, availability?: ({start_at?: string | undefined, finish_at?: string | undefined}) | undefined, metadata?: (Array<{key?: string | undefined, value?: string | undefined}>) | undefined, retries?: ({retry_on_decline?: boolean | undefined, amount?: number | undefined, strategy?: ('DEFAULT' | 'CUSTOM_SCHEDULE') | undefined, schedule?: (Array<{attempt?: number | undefined, delay_seconds?: number | undefined}>) | undefined, stop_on_hard_decline?: boolean | undefined}) | undefined, initial_payment_validation?: boolean | undefined, billing_date?: ({type?: string | undefined, day?: number | undefined}) | undefined, subscription_agreement_id?: string | undefined}}; export type CreateApiSubscriptionsOptions = {baseUrl?: string | undefined, publicApiKey?: string | undefined, privateSecretKey?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiSubscriptionsResponse = z.object({id: z.string().optional(), name: z.string().optional(), account_id: z.string().optional(), country: z.string().optional(), description: z.string().optional(), merchant_reference: z.string().optional(), soft_descriptor: z.string().optional(), status: z.string().optional(), amount: z.object({currency: z.string().optional(), value: z.number().int().optional()}).optional(), frequency: z.object({type: z.string().optional(), value: z.number().int().optional()}).optional(), billing_cycles: z.object({total: z.number().int().optional(), current: z.number().int().optional(), next_at: z.string().optional()}).optional(), customer_payer: z.object({id: z.string().optional()}).optional(), payment_method: z.object({type: z.string().optional(), vaulted_token: z.string().optional()}).optional(), availability: z.object({start_at: z.string().optional(), finish_at: z.unknown()}).optional(), trial_period: z.object({billing_cycles: z.number().int().optional(), amount: z.object({value: z.number().int().optional(), currency: z.string().optional()}).optional()}).optional(), metadata: z.unknown(), plan_id: z.string().optional(), plan_assigned_at: z.string().optional(), previous_subscription_id: z.string().optional(), current_phase: z.string().optional(), billing_phases: z.array(z.object({order: z.number().int().optional(), type: z.string().optional(), name: z.string().optional(), amount: z.object({currency: z.string().optional(), value: z.number().optional()}).optional(), frequency: z.object({type: z.string().optional(), value: z.number().int().optional()}).optional(), start_cycle: z.number().int().optional(), end_cycle: z.number().int().optional()})).optional(), subscription_agreement_id: z.string().optional(), created_at: z.string().optional(), updated_at: 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 }; /** * Create Subscription * * POST /subscriptions */ export const createApiSubscriptions = async (args: CreateApiSubscriptionsArgs, options?: CreateApiSubscriptionsOptions) => { const {baseUrl = "https://api-sandbox.y.uno/v1", fetch: fetchFn = fetch, publicApiKey, privateSecretKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-idempotency-key'] != null) headers.set("x-idempotency-key", String(args['x-idempotency-key'])) if (publicApiKey !== undefined) headers.set("PUBLIC-API-KEY", publicApiKey) if (privateSecretKey !== undefined) headers.set("PRIVATE-SECRET-KEY", privateSecretKey) const url = `${baseUrl.replace(/\/+$/, '')}/subscriptions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiSubscriptionsResponse, await res.json()) };