import {z} from 'zod' export type EdubankSubscriptionCharge = {start_date: string, frequency: 'DAILY' | 'MONTHLY', duration: number, amount: number}; export type EdubankSubscriptionReferences = {due_date: string, reference_id: string}; export type EdubankSubscriptionProposalDto = {description: string, reference_id: string, expires_in: string, charge: EdubankSubscriptionCharge, notification_url: string, references?: Array | undefined}; export type CreateApiV1SubscriptionsProposalArgs = {body: EdubankSubscriptionProposalDto}; export type CreateApiV1SubscriptionsProposalOptions = {baseUrl: string, xApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const edubankSubscriptionCharge = z.object({start_date: z.string(), frequency: z.enum(["DAILY", "MONTHLY"]), duration: z.number(), amount: z.number()}); export const edubankSubscriptionPermission = z.object({authorized: z.boolean(), authorized_in: z.string(), card_id: z.string()}); export const edubankSubscriptionReferences = z.object({due_date: z.string(), reference_id: z.string()}); export const edubankSubscription = z.object({created_at: z.string().optional(), updated_at: z.string().optional(), seller_id: z.string(), subscription_id: z.string(), description: z.string(), reference_id: z.string(), buyer_id: z.string(), status: z.enum(["PROPOSAL", "ACTIVE", "EXPIRED", "CANCELED", "SUSPENDED", "REACTIVATED"]), expires_in: z.string(), charge: edubankSubscriptionCharge, notification_url: z.string(), subscription_permission: edubankSubscriptionPermission, references: z.array(edubankSubscriptionReferences).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 }; /** * Creates a subscription proposal that must be authorized by the buyer * * POST /v1/subscriptions/proposal * * Also accepts auth: authorization */ export const createApiV1SubscriptionsProposal = async (args: CreateApiV1SubscriptionsProposalArgs, options: CreateApiV1SubscriptionsProposalOptions) => { const {baseUrl, fetch: fetchFn = fetch, xApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (xApiKey !== undefined) headers.set("x-api-key", xApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/subscriptions/proposal${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(edubankSubscription, await res.json()) };