UNPKG

@paykit-sdk/core

Version:

The Payment Toolkit for Typescript

529 lines (506 loc) 16.8 kB
import { z } from 'zod'; declare const metadataSchema: z.ZodRecord<z.ZodString, z.ZodString>; type PaykitMetadata = z.infer<typeof metadataSchema>; declare const billingModeSchema: z.ZodEnum<["one_time", "recurring"]>; type BillingMode = z.infer<typeof billingModeSchema>; declare const createCheckoutSchema: z.ZodObject<{ /** * The ID of the customer. */ customer_id: z.ZodString; /** * The metadata of the checkout. */ metadata: z.ZodRecord<z.ZodString, z.ZodString>; /** * The mode of the checkout. */ session_type: z.ZodEnum<["one_time", "recurring"]>; /** * The item ID of the checkout. */ item_id: z.ZodString; /** * Extra information to be sent to the provider e.g tax, trial days, etc. */ provider_metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>; }, "strip", z.ZodTypeAny, { customer_id: string; metadata: Record<string, string>; session_type: "one_time" | "recurring"; item_id: string; provider_metadata?: Record<string, unknown> | undefined; }, { customer_id: string; metadata: Record<string, string>; session_type: "one_time" | "recurring"; item_id: string; provider_metadata?: Record<string, unknown> | undefined; }>; type CreateCheckoutParams = z.infer<typeof createCheckoutSchema>; declare const retrieveCheckoutSchema: z.ZodObject<{ id: z.ZodString; }, "strip", z.ZodTypeAny, { id: string; }, { id: string; }>; type RetrieveCheckoutParams = z.infer<typeof retrieveCheckoutSchema>; type Checkout = { /** * The ID of the checkout. */ id: string; /** * The ID of the customer. */ customer_id: string; /** * The payment URL where customer completes the transaction. */ payment_url: string; /** * The metadata of the checkout. */ metadata: PaykitMetadata | null; /** * The mode of the checkout. */ session_type: BillingMode; /** * The products of the checkout. */ products: Array<{ id: string; quantity: number; }>; /** * The currency code (ISO 4217). */ currency: string; /** * Total amount in the smallest currency unit (e.g., cents). */ amount: number; }; interface Customer { /** * The ID of the customer. */ id: string; /** * The email of the customer. */ email?: string; /** * The name of the customer. */ name?: string; /** * The metadata of the customer. */ metadata?: PaykitMetadata; } declare const createCustomerSchema: z.ZodObject<{ /** * The email of the customer. */ email: z.ZodString; /** * The name of the customer. */ name: z.ZodOptional<z.ZodString>; /** * The metadata of the customer. */ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>; }, "strip", z.ZodTypeAny, { email: string; metadata?: Record<string, string> | undefined; name?: string | undefined; }, { email: string; metadata?: Record<string, string> | undefined; name?: string | undefined; }>; type CreateCustomerParams = z.infer<typeof createCustomerSchema>; declare const updateCustomerSchema: z.ZodObject<{ /** * The email of the customer. */ email: z.ZodOptional<z.ZodString>; /** * The name of the customer. */ name: z.ZodOptional<z.ZodString>; /** * The metadata of the customer. */ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>; }, "strip", z.ZodTypeAny, { email?: string | undefined; metadata?: Record<string, string> | undefined; name?: string | undefined; }, { email?: string | undefined; metadata?: Record<string, string> | undefined; name?: string | undefined; }>; type UpdateCustomerParams = z.infer<typeof updateCustomerSchema>; declare const retrieveCustomerSchema: z.ZodObject<{ id: z.ZodString; }, "strip", z.ZodTypeAny, { id: string; }, { id: string; }>; type RetrieveCustomerParams = z.infer<typeof retrieveCustomerSchema>; type SubscriptionStatus = 'active' | 'past_due' | 'canceled' | 'expired'; interface Subscription { /** * The ID of the subscription. */ id: string; /** * The ID of the customer. */ customer_id: string; /** * The status of the subscription. */ status: SubscriptionStatus; /** * The current period start of the subscription. */ current_period_start: Date; /** * The current period end of the subscription. */ current_period_end: Date; /** * The metadata of the subscription. */ metadata: PaykitMetadata; } declare const updateSubscriptionSchema: z.ZodObject<{ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>; }, "strip", z.ZodTypeAny, { metadata?: Record<string, string> | undefined; }, { metadata?: Record<string, string> | undefined; }>; type UpdateSubscriptionParams = z.infer<typeof updateSubscriptionSchema>; declare const retrieveSubscriptionSchema: z.ZodObject<{ id: z.ZodString; }, "strip", z.ZodTypeAny, { id: string; }, { id: string; }>; type RetrieveSubscriptionParams = z.infer<typeof retrieveSubscriptionSchema>; type Invoice = { /** * The ID of the invoice. */ id: string; /** * The billing mode of the invoice. */ billing_mode: BillingMode; /** * The amount of the invoice. */ amount: number; /** * The currency of the invoice. */ currency: string; /** * The metadata of the invoice. */ metadata: PaykitMetadata; /** * The customer ID of the invoice. */ customer_id: string; }; type WebhookEventLiteral = '$customerCreated' | '$customerUpdated' | '$customerDeleted' | '$subscriptionCreated' | '$subscriptionUpdated' | '$subscriptionCancelled' | '$checkoutCreated' | '$invoicePaid'; interface WebhookEvent<T extends any> { /** * The ID of the webhook event. */ id: string; /** * The type of the webhook event. */ type: WebhookEventLiteral; /** * The created timestamp of the webhook event. */ created: number; /** * The data of the webhook event. */ data: T; } type CustomerCreated = WebhookEvent<Customer>; type CustomerUpdated = WebhookEvent<Customer | null>; type CustomerDeleted = WebhookEvent<null>; type SubscriptionCreated = WebhookEvent<Subscription>; type SubscriptionUpdated = WebhookEvent<Subscription>; type subscriptionCancelled = WebhookEvent<Subscription>; type CheckoutCreated = WebhookEvent<Checkout>; type InvoicePaid = WebhookEvent<Invoice>; type WebhookEventPayload = CustomerCreated | CustomerUpdated | CustomerDeleted | SubscriptionCreated | SubscriptionUpdated | subscriptionCancelled | InvoicePaid | CheckoutCreated; declare const toPaykitEvent: <Resource>(event: WebhookEvent<Resource>) => WebhookEvent<Resource>; type WebhookEventHandlers = Partial<{ $customerCreated: (event: CustomerCreated) => Promise<void>; $customerUpdated: (event: CustomerUpdated) => Promise<void>; $customerDeleted: (event: CustomerDeleted) => Promise<void>; $subscriptionCreated: (event: SubscriptionCreated) => Promise<void>; $subscriptionUpdated: (event: SubscriptionUpdated) => Promise<void>; $subscriptionCancelled: (event: subscriptionCancelled) => Promise<void>; $checkoutCreated: (event: CheckoutCreated) => Promise<void>; $invoicePaid: (event: InvoicePaid) => Promise<void>; }>; type WebhookEventType = keyof WebhookEventHandlers; type WebhookSetupConfig = { webhookSecret: string; provider: PayKitProvider; }; type WebhookHandlerConfig = { body: string; headers: Record<string, string | string[]>; }; interface HandleWebhookParams extends WebhookHandlerConfig, Pick<WebhookSetupConfig, 'webhookSecret'> { } declare class Webhook { private handlers; private config; setup(config: WebhookSetupConfig): Webhook; on<T extends WebhookEventType>(eventType: T, handler: NonNullable<WebhookEventHandlers[T]>): Webhook; handle(dto: WebhookHandlerConfig): Promise<void>; } interface PayKitProvider { /** * Checkout sessions */ createCheckout(params: CreateCheckoutParams): Promise<Checkout>; retrieveCheckout(id: string): Promise<Checkout | null>; /** * Customer management */ createCustomer(params: CreateCustomerParams): Promise<Customer>; updateCustomer(id: string, params: UpdateCustomerParams): Promise<Customer>; retrieveCustomer(id: string): Promise<Customer | null>; /** * Subscription management */ updateSubscription(id: string, params: UpdateSubscriptionParams): Promise<Subscription>; cancelSubscription(id: string): Promise<null>; retrieveSubscription(id: string): Promise<Subscription | null>; /** * Webhook management */ handleWebhook(payload: HandleWebhookParams): Promise<WebhookEventPayload>; } type PaykitProviderOptions<T extends object = {}> = { debug?: boolean; } & T; type OverrideProps<T, V> = V & Omit<T, keyof V>; type LooseAutoComplete<T extends string> = T | Omit<string, T>; /** * Base class for all HTTP errors. */ declare class HTTPError extends Error { readonly cause: unknown; name: string; constructor(message: string, opts: { cause?: unknown; }); } declare class UnauthorizedError extends HTTPError { readonly name = "PaykitUnauthorizedError"; } declare class ConnectionError extends HTTPError { readonly name = "PaykitConnectionError"; } declare class AbortedError extends HTTPError { readonly name = "PaykitAbortedError"; } declare class TimeoutError extends HTTPError { readonly name = "PaykitTimeoutError"; } declare class ValidationError extends HTTPError { readonly name = "PaykitValidationError"; } declare class UnknownError extends HTTPError { readonly name = "PaykitUnknownError"; } type Result$1<T, E = unknown> = { ok: true; value: T; error?: never; } | { ok: false; value?: never; error: E; }; declare const OK: <V>(value: V) => Result$1<V, never>; declare const ERR: <E>(error: E) => Result$1<never, E>; /** * unwrapAsync is a convenience function for resolving a value from a Promise * of a result or rejecting if an error occurred. */ declare const unwrapAsync: <T>(pr: Promise<Result$1<T, unknown>>) => Promise<T>; declare function safeParse<Inp, Out>(rawValue: Inp, fn: (value: Inp) => Out, errorMessage: string): Result$1<Out, ValidationError>; declare const safeEncode: <T>(value: T) => Result$1<string, ValidationError>; declare const safeDecode: <T>(value: string) => Result$1<T, ValidationError>; /** * Inspired by @polar-sh/sdk * https://github.com/polarsource */ declare function isConnectionError(err: unknown): boolean; /** * Uses various heurisitics to determine if an error is a timeout error. */ declare function isTimeoutError(err: unknown): boolean; /** * Uses various heurisitics to determine if an error is a abort error. */ declare function isAbortError(err: unknown): boolean; declare function isUnauthorizedError(err: unknown): boolean; declare const headersExtractor: (headers: Record<string, string | string[]>, requiredHeaders: string[]) => Array<{ key: string; value: string | string[]; }>; type Success<T> = [T, undefined]; type Failure<E = Error> = [undefined, E]; type Result<T, E = Error> = Success<T> | Failure<E>; declare function tryCatchAsync<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>>; declare function tryCatchSync<T, E = Error>(fn: () => T): Result<T, E>; declare const __IS_CLIENT__: boolean; declare const delay: (ms: number) => Promise<unknown>; declare const truncate: (str: string, num: number, suffix?: string) => string; declare const stringifyObjectValues: (obj: Record<string, any>) => { [k: string]: string; }; declare const validateEnvVars: <K extends string>(requiredKeys: readonly K[], source: Record<string, string | undefined>) => Record<K, string>; interface LoggerOptions { silent?: boolean; verbose?: boolean; } declare class Logger { private silent; private verbose; private spinnerInterval; private spinnerFrames; private currentSpinnerFrame; constructor(options?: LoggerOptions); /** * Success messages (dark green) */ success(message: string): void; /** * Info messages (dark green) */ info(message: string): void; /** * Warning messages (amber) */ warn(message: string): void; /** * Error messages (red) */ error(message: string): void; /** * Debug messages (gray, only in verbose mode) */ debug(message: string): void; /** * Tip messages (dark green) */ tip(message: string): void; /** * Code block styling */ code(code: string): void; /** * Section headers */ section(title: string): void; /** * Progress indicator with spinning animation */ progress(message: string): void; /** * Start the spinner animation */ private startSpinner; /** * Stop the spinner animation */ private stopSpinner; /** * Clear progress line */ clearProgress(): void; /** * Table-like output for key-value pairs */ table(data: Record<string, string>): void; /** * List items */ list(items: string[], bullet?: string): void; /** * Divider line */ divider(char?: string, length?: number): void; /** * Spacer */ spacer(lines?: number): void; /** * Brand header */ brand(): void; } declare const logger: Logger; type HTTPClientConfig = { baseUrl: string; headers: Record<string, string>; }; declare class HTTPClient { private config; constructor(config: HTTPClientConfig); private errorHandler; private getFullUrl; private getRequestOptions; get<T>(endpoint: string, options?: Omit<RequestInit, 'method'>): Promise<Result$1<T>>; post<T>(endpoint: string, options?: Omit<RequestInit, 'method'>): Promise<Result$1<T>>; delete<T>(endpoint: string, options?: Omit<RequestInit, 'method'>): Promise<Result$1<T>>; put<T>(endpoint: string, options?: Omit<RequestInit, 'method'>): Promise<Result$1<T>>; patch<T>(endpoint: string, options?: Omit<RequestInit, 'method'>): Promise<Result$1<T>>; } declare class PayKit { private provider; constructor(provider: PayKitProvider); checkouts: { create: (params: CreateCheckoutParams) => Promise<Checkout>; retrieve: (id: string) => Promise<Checkout | null>; }; customers: { create: (params: CreateCustomerParams) => Promise<Customer>; update: (id: string, params: UpdateCustomerParams) => Promise<Customer>; retrieve: (id: string) => Promise<Customer | null>; }; subscriptions: { update: (id: string, params: UpdateSubscriptionParams) => Promise<Subscription>; cancel: (id: string) => Promise<null>; }; webhooks: { setup: (config: Omit<WebhookSetupConfig, "provider">) => Webhook; }; } export { AbortedError, type BillingMode, type Checkout, type CheckoutCreated, ConnectionError, type CreateCheckoutParams, type CreateCustomerParams, type Customer, type CustomerCreated, type CustomerDeleted, type CustomerUpdated, ERR, HTTPClient, type HTTPClientConfig, HTTPError, type HandleWebhookParams, type Invoice, type InvoicePaid, Logger, type LoggerOptions, type LooseAutoComplete, OK, type OverrideProps, PayKit, type PayKitProvider, type PaykitMetadata, type PaykitProviderOptions, type Result$1 as Result, type RetrieveCheckoutParams, type RetrieveCustomerParams, type RetrieveSubscriptionParams, type Subscription, type SubscriptionCreated, type SubscriptionStatus, type SubscriptionUpdated, TimeoutError, UnauthorizedError, UnknownError, type UpdateCustomerParams, type UpdateSubscriptionParams, ValidationError, Webhook, type WebhookEvent, type WebhookEventHandlers, type WebhookEventLiteral, type WebhookEventPayload, type WebhookEventType, type WebhookHandlerConfig, type WebhookSetupConfig, __IS_CLIENT__, billingModeSchema, createCheckoutSchema, createCustomerSchema, delay, headersExtractor, isAbortError, isConnectionError, isTimeoutError, isUnauthorizedError, logger, metadataSchema, retrieveCheckoutSchema, retrieveCustomerSchema, retrieveSubscriptionSchema, safeDecode, safeEncode, safeParse, stringifyObjectValues, type subscriptionCancelled, toPaykitEvent, truncate, tryCatchAsync, tryCatchSync, unwrapAsync, updateCustomerSchema, updateSubscriptionSchema, validateEnvVars };