@usethrottle/subscriptions 3.6.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +1 -0
- package/README.md +27 -1
- package/dist/{chunk-QDARSRCR.js → chunk-GK6QY63F.js} +9 -5
- package/dist/chunk-GK6QY63F.js.map +1 -0
- package/dist/{errors-CfDCslmT.d.cts → errors-DyoAgada.d.cts} +28 -3
- package/dist/{errors-CfDCslmT.d.ts → errors-DyoAgada.d.ts} +28 -3
- package/dist/index.cjs +44 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.js +27 -1
- package/dist/index.js.map +1 -1
- package/dist/server.cjs +64 -8
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +27 -2
- package/dist/server.d.ts +27 -2
- package/dist/server.js +57 -5
- package/dist/server.js.map +1 -1
- package/package.json +3 -2
- package/dist/chunk-QDARSRCR.js.map +0 -1
package/dist/server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/errors.ts","../src/normalize.ts","../src/client.ts"],"sourcesContent":["import { SubscriptionsClient, createSubscriptionsClient } from './client';\nimport { ThrottleSubscriptionsError } from './errors';\nimport type { Subscription, SubscriptionsClientOptions } from './types';\n\nexport { SubscriptionsClient, createSubscriptionsClient, ThrottleSubscriptionsError };\nexport type {\n CheckoutSession,\n CreateCheckoutSessionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n Subscription,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n TrialEligibilityInput,\n TrialEligibilityResult,\n} from './types';\n\nexport interface SubscriptionProxyOptions {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n getExternalCustomerId: (request: Request) => string | null | Promise<string | null>;\n /** When supplied it replaces the default installment rule; ownership is always checked. */\n authorizeMutation?: (args: {\n request: Request;\n subscription: Subscription;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n}\n\nexport interface SubscriptionProxyContext {\n params?: {\n path?: string[] | Promise<string[]>;\n };\n path?: string[] | string;\n}\n\nconst ALLOWED_PATHS = [\n /^\\/api\\/v1\\/subscriptions(?:\\/[\\w.-]+)?(?:\\/(?:pause|resume|cancel|payment-method))?$/,\n /^\\/api\\/v1\\/subscriptions\\/eligibility-check$/,\n /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/,\n /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/,\n /^\\/api\\/v1\\/checkout\\/sessions$/,\n];\n\nexport function createSubscriptionProxyHandler(options: SubscriptionProxyOptions) {\n return async function subscriptionProxyHandler(\n request: Request,\n context: SubscriptionProxyContext = {},\n ): Promise<Response> {\n const path = await pathFromContext(context);\n return handleSubscriptionProxyRequest(request, path, options);\n };\n}\n\nexport async function handleSubscriptionProxyRequest(\n request: Request,\n pathParts: string[] | string,\n options: SubscriptionProxyOptions,\n): Promise<Response> {\n const externalCustomerId = await options.getExternalCustomerId(request);\n if (!externalCustomerId) return jsonError(401, 'unauthorized', 'Unauthorized');\n\n const path = normalizePath(pathParts);\n if (!ALLOWED_PATHS.some((pattern) => pattern.test(path))) {\n return jsonError(403, 'forbidden', 'Path is not allowed by the subscription proxy');\n }\n\n const method = request.method.toUpperCase();\n if (!['GET', 'POST', 'PATCH'].includes(method)) {\n return jsonError(405, 'method_not_allowed', 'Method not allowed');\n }\n\n const client = new SubscriptionsClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n } satisfies SubscriptionsClientOptions);\n\n if (isSubscriptionMutation(path, method)) {\n const subId = subscriptionIdFromPath(path);\n if (subId) {\n const subscription = await client.get(subId).catch((err) => {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n });\n if (!subscription) return jsonError(404, 'not_found', 'Subscription not found');\n\n const owned = await defaultMutationAuthorization(client, subscription, externalCustomerId);\n if (!owned) return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n if (options.authorizeMutation) {\n if (!(await options.authorizeMutation({ request, subscription, externalCustomerId }))) {\n return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n }\n } else if (subscription.totalPayments != null && !isPaymentMethodPath(path)) {\n // Same rule as the storefront buyer API (D33/D36): installment plans are merchant-only.\n // Changing the card is not one of the locked terms, so it stays allowed (F-2).\n return jsonError(\n 403,\n 'installment_plan_merchant_only',\n 'Installment plans can only be paused, resumed or cancelled by the merchant',\n );\n }\n }\n }\n\n const targetPath = await buildPinnedPathAndBody(request, path, externalCustomerId, client);\n if (targetPath instanceof Response) return targetPath;\n const upstream = await fetchWithApiKey(request, targetPath.path, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n body: targetPath.body,\n });\n\n return new Response(upstream.body, {\n status: upstream.status,\n headers: filterHeaders(upstream.headers),\n });\n}\n\nasync function buildPinnedPathAndBody(\n request: Request,\n path: string,\n externalCustomerId: string,\n client: SubscriptionsClient,\n): Promise<{ path: string; body?: string } | Response> {\n const url = new URL(request.url);\n const query = new URLSearchParams(url.search);\n\n if (request.method.toUpperCase() === 'GET' && path === '/api/v1/subscriptions') {\n query.set('externalCustomerId', externalCustomerId);\n query.delete('customerId');\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerByExternalPath(path)) {\n return {\n path: withQuery(\n `/api/v1/customers/by-external/${encodeURIComponent(externalCustomerId)}`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerPaymentMethodsPath(path)) {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n return {\n path: withQuery(\n `/api/v1/customers/${encodeURIComponent(customer.id)}/payment-methods`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() !== 'GET') {\n const raw = await request.text();\n if (path === '/api/v1/subscriptions' && request.method.toUpperCase() === 'POST') {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n\n const body = raw ? (JSON.parse(raw) as Record<string, any>) : {};\n body.customerId = customer.id;\n delete body.externalCustomerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n\n if (path === '/api/v1/checkout/sessions' && raw) {\n const body = JSON.parse(raw) as Record<string, any>;\n body.customer = {\n ...(body.customer ?? {}),\n externalCustomerId,\n };\n delete body.customer.customerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n return { path: withQuery(path, query), body: raw || undefined };\n }\n\n return { path: withQuery(path, query) };\n}\n\nasync function fetchWithApiKey(\n request: Request,\n path: string,\n opts: {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n body?: string;\n },\n) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('fetch is required');\n const baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n return fetchImpl(`${baseUrl}${path}`, {\n method: request.method,\n headers: {\n 'x-api-key': opts.apiKey,\n 'content-type': request.headers.get('content-type') ?? 'application/json',\n },\n body: request.method.toUpperCase() === 'GET' ? undefined : opts.body,\n });\n}\n\nasync function defaultMutationAuthorization(\n client: SubscriptionsClient,\n subscription: Subscription,\n externalCustomerId: string,\n): Promise<boolean> {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n return Boolean(customer?.id && customer.id === subscription.customerId);\n}\n\nasync function pathFromContext(context: SubscriptionProxyContext): Promise<string[] | string> {\n if (context.path) return context.path;\n const path = context.params?.path;\n if (!path) return [];\n return await path;\n}\n\nfunction normalizePath(pathParts: string[] | string): string {\n if (typeof pathParts === 'string') {\n return pathParts.startsWith('/') ? pathParts : `/${pathParts}`;\n }\n return `/${pathParts.map((part) => part.replace(/^\\/+|\\/+$/g, '')).join('/')}`;\n}\n\nfunction withQuery(path: string, query: URLSearchParams): string {\n const qs = query.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\nfunction isSubscriptionMutation(path: string, method: string): boolean {\n if (path === '/api/v1/subscriptions/eligibility-check') return false;\n return method !== 'GET' && /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+/.test(path);\n}\n\nfunction isCustomerByExternalPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/.test(path);\n}\n\nfunction isCustomerPaymentMethodsPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/.test(path);\n}\n\nfunction isPaymentMethodPath(path: string): boolean {\n return /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+\\/payment-method$/.test(path);\n}\n\nfunction subscriptionIdFromPath(path: string): string | null {\n return path.match(/^\\/api\\/v1\\/subscriptions\\/([\\w.-]+)/)?.[1] ?? null;\n}\n\nfunction filterHeaders(headers: Headers): Headers {\n const next = new Headers(headers);\n next.delete('content-encoding');\n next.delete('content-length');\n next.delete('transfer-encoding');\n return next;\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return Response.json({ error: { code, message } }, { status });\n}\n","import { ThrottleError, type ThrottleErrorArgs } from '@usethrottle/errors';\n\n/**\n * Thrown on a non-2xx response from the Throttle Subscriptions API.\n *\n * Extends the shared {@link ThrottleError} so a single\n * `catch (e) { if (e instanceof ThrottleError) … }` covers errors from every\n * Throttle SDK. `instanceof ThrottleSubscriptionsError` keeps working.\n */\nexport class ThrottleSubscriptionsError extends ThrottleError {\n constructor(args: {\n code: string;\n message: string;\n statusCode: number;\n details?: unknown;\n responseHeaders?: ThrottleErrorArgs['responseHeaders'];\n }) {\n super(args);\n this.name = 'ThrottleSubscriptionsError';\n }\n}\n\nexport { ThrottleError, isThrottleError } from '@usethrottle/errors';\n","import type {\n CheckoutSession,\n Customer,\n CustomerPaymentMethod,\n Pagination,\n Subscription,\n SubscriptionInterval,\n SubscriptionIntervalUnit,\n SubscriptionRenewalIssue,\n SubscriptionStatus,\n SubscriptionUsageItem,\n TrialEligibilityResult,\n} from './types';\n\nexport function normalizeSubscription(raw: any): Subscription {\n return {\n id: requiredString(raw?.id, 'subscription.id'),\n workspaceId: optionalString(raw?.workspaceId),\n applicationId: optionalString(raw?.applicationId),\n customerId: requiredString(raw?.customerId, 'subscription.customerId'),\n status: (raw?.status ?? 'active') as SubscriptionStatus,\n planReference: requiredString(raw?.planReference, 'subscription.planReference'),\n planName: optionalString(raw?.planName),\n interval: (raw?.interval ?? 'monthly') as SubscriptionInterval,\n intervalUnit: (optionalString(raw?.intervalUnit) as Subscription['intervalUnit']) ?? null,\n intervalCount: raw?.intervalCount == null ? null : Number(raw.intervalCount),\n totalPayments: raw?.totalPayments == null ? null : Number(raw.totalPayments),\n paymentsMade: Number(raw?.paymentsMade ?? 0),\n completedAt: optionalIsoDateString(raw?.completedAt),\n paymentSchedule: normalizePaymentSchedule(raw?.paymentSchedule),\n scheduleTotal: raw?.scheduleTotal == null ? null : Number(raw.scheduleTotal),\n nextPaymentAmount: raw?.nextPaymentAmount == null ? null : Number(raw.nextPaymentAmount),\n amount: Number(raw?.amount ?? 0),\n quantity: Number(raw?.quantity ?? 1),\n currency: optionalString(raw?.currency) ?? 'USD',\n currentPeriodStart: requiredDateString(\n raw?.currentPeriodStart,\n 'subscription.currentPeriodStart',\n ),\n currentPeriodEnd: requiredDateString(\n raw?.currentPeriodEnd,\n 'subscription.currentPeriodEnd',\n ),\n trialEnd: optionalDateString(raw?.trialEnd),\n cancelAtPeriodEnd: Boolean(raw?.cancelAtPeriodEnd ?? false),\n failureCount: Number(raw?.failureCount ?? 0),\n lastPaymentAt: optionalDateString(raw?.lastPaymentAt),\n pausedAt: optionalDateString(raw?.pausedAt),\n cancelledAt: optionalDateString(raw?.cancelledAt),\n metadata: objectOrEmpty(raw?.metadata),\n paymentMethodId: optionalString(raw?.paymentMethodId),\n renewalIssue: normalizeRenewalIssue(raw?.renewalIssue),\n proration: raw?.proration\n ? {\n creditCents: raw.proration.creditCents,\n chargedCents: raw.proration.chargedCents,\n fullAmount: raw.proration.fullAmount,\n }\n : undefined,\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nfunction normalizePaymentSchedule(raw: any): Subscription['paymentSchedule'] {\n if (!Array.isArray(raw)) return null;\n return raw.map((r: any) => ({\n index: Number(r?.index ?? 0),\n amount: Number(r?.amount ?? 0),\n discount: Number(r?.discount ?? 0),\n net: Number(r?.net ?? 0),\n intervalUnit: (optionalString(r?.intervalUnit) as SubscriptionIntervalUnit | null) ?? null,\n intervalCount: r?.intervalCount == null ? null : Number(r.intervalCount),\n status: r?.status as 'paid' | 'due' | 'upcoming',\n dueAt: optionalDateString(r?.dueAt),\n }));\n}\n\nfunction normalizeRenewalIssue(raw: any): SubscriptionRenewalIssue | null {\n if (!raw || typeof raw !== 'object') return null;\n return {\n kind: raw.kind,\n reason: raw.reason,\n count: Number(raw.count ?? 0),\n firstAt: optionalString(raw.firstAt) ?? undefined,\n lastAt: requiredString(raw.lastAt, 'subscription.renewalIssue.lastAt'),\n message: raw.message ?? '',\n alertedAt: optionalDateString(raw.alertedAt),\n charge: raw.charge\n ? {\n transactionId: optionalString(raw.charge.transactionId),\n amount: Number(raw.charge.amount ?? 0),\n currency: optionalString(raw.charge.currency) ?? 'USD',\n periodStart: optionalString(raw.charge.periodStart) ?? undefined,\n }\n : null,\n };\n}\n\nexport function normalizeUsageItem(raw: any): SubscriptionUsageItem {\n return {\n id: requiredString(raw?.id, 'usageItem.id'),\n subscriptionId: requiredString(raw?.subscriptionId, 'usageItem.subscriptionId'),\n kind: raw?.kind ?? '',\n unitCount: Number(raw?.unitCount ?? 0),\n unitPriceCents: Number(raw?.unitPriceCents ?? 0),\n totalCents: Number(raw?.totalCents ?? 0),\n periodStart: requiredDateString(raw?.periodStart, 'usageItem.periodStart'),\n periodEnd: requiredDateString(raw?.periodEnd, 'usageItem.periodEnd'),\n createdAt: requiredDateString(raw?.createdAt, 'usageItem.createdAt'),\n };\n}\n\nexport function normalizeCustomer(raw: any): Customer | null {\n if (!raw) return null;\n return {\n id: requiredString(raw?.id, 'customer.id'),\n externalId: optionalString(raw?.externalId),\n email: optionalString(raw?.email),\n firstName: optionalString(raw?.firstName),\n lastName: optionalString(raw?.lastName),\n phone: optionalString(raw?.phone),\n company: optionalString(raw?.company),\n metadata: objectOrEmpty(raw?.metadata),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCustomerPaymentMethod(raw: any): CustomerPaymentMethod {\n return {\n id: requiredString(raw?.id, 'paymentMethod.id'),\n processor: optionalString(raw?.processor),\n methodType: optionalString(raw?.methodType),\n cardBrand: optionalString(raw?.cardBrand),\n cardLastFour: optionalString(raw?.cardLastFour),\n isDefault: Boolean(raw?.isDefault ?? false),\n isActive: Boolean(raw?.isActive ?? true),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCheckoutSession(raw: any): CheckoutSession {\n const sessionId = raw?.sessionId ?? raw?.id;\n return {\n ...withoutUnderscoreKeys(raw),\n id: optionalString(raw?.id) ?? undefined,\n sessionId: requiredString(sessionId, 'checkoutSession.sessionId'),\n checkoutUrl: optionalString(raw?.checkoutUrl) ?? undefined,\n embedToken: optionalString(raw?.embedToken) ?? undefined,\n expiresAt: optionalDateString(raw?.expiresAt) ?? undefined,\n };\n}\n\nexport function normalizeTrialEligibility(raw: any): TrialEligibilityResult {\n return {\n eligible: Boolean(raw?.eligible),\n reason: raw?.reason,\n };\n}\n\nexport function normalizePagination(raw: any): Pagination | undefined {\n if (!raw) return undefined;\n return {\n cursor: raw.cursor ?? null,\n hasMore: Boolean(raw.hasMore ?? false),\n };\n}\n\nexport function toIso(value: string | Date | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalString(value: unknown): string | null {\n return typeof value === 'string' ? value : null;\n}\n\nfunction requiredDateString(value: unknown, label: string): string {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n return null;\n}\n\n/**\n * Like `optionalDateString`, but always reserializes to a full ISO string\n * (with milliseconds) rather than passing a raw string through unchanged.\n * `completedAt` is a fresh field with no legacy raw-string callers to stay\n * compatible with, so it normalizes cleanly instead of echoing whatever the\n * API sent.\n */\nfunction optionalIsoDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? value : d.toISOString();\n }\n return null;\n}\n\nfunction objectOrEmpty(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction withoutUnderscoreKeys(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return {};\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).filter(([key]) => !key.includes('_')),\n );\n}\n","import { ThrottleSubscriptionsError } from './errors';\nimport {\n normalizeCheckoutSession,\n normalizeCustomer,\n normalizeCustomerPaymentMethod,\n normalizePagination,\n normalizeSubscription,\n normalizeTrialEligibility,\n normalizeUsageItem,\n toIso,\n} from './normalize';\nimport type {\n ChangePlanInput,\n ChangeQuantityInput,\n CheckoutSession,\n CreateCheckoutSessionInput,\n CreateSubscriptionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n RecordUsageInput,\n Subscription,\n SubscriptionInvoiceRefund,\n SubscriptionUsageItem,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n ThrottleEnvelope,\n TrialEligibilityInput,\n TrialEligibilityResult,\n UpdateSubscriptionInput,\n WaivePeriodInput,\n} from './types';\n\nexport class SubscriptionsClient implements SubscriptionsClientContract {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly fetcher?: SubscriptionsClientOptions['fetcher'];\n private readonly timeoutMs: number;\n\n constructor(opts: SubscriptionsClientOptions = {}) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('SubscriptionsClient: fetch is required');\n if (!opts.apiKey && !opts.fetcher) {\n throw new Error('SubscriptionsClient: apiKey or fetcher is required');\n }\n\n this.apiKey = opts.apiKey;\n this.baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n this.fetchImpl = fetchImpl;\n this.fetcher = opts.fetcher;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n }\n\n async request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n const envelope = await this.requestEnvelope<T>(method, path, body);\n if (Object.prototype.hasOwnProperty.call(envelope, 'data')) {\n return envelope.data as T;\n }\n return envelope as T;\n }\n\n async requestEnvelope<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<ThrottleEnvelope<T>> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n\n try {\n const init: RequestInit = {\n method,\n headers: {\n 'content-type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: ctrl.signal,\n };\n\n const res = this.fetcher\n ? await this.fetcher(path, init)\n : await this.fetchImpl(toAbsoluteUrl(this.baseUrl, path), init);\n\n if (res.status === 204) return { data: undefined as T };\n\n const json = (await res.json().catch(() => ({}))) as ThrottleEnvelope<T>;\n if (!res.ok) {\n throw new ThrottleSubscriptionsError({\n code: json.error?.code ?? 'unknown_error',\n message: json.error?.message ?? `HTTP ${res.status}`,\n statusCode: res.status,\n details: json.error?.details,\n responseHeaders: res.headers,\n });\n }\n return json;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async create(input: CreateSubscriptionInput): Promise<Subscription> {\n const customerId = await this.resolveCustomerId(input.customerId, input.externalCustomerId);\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions', {\n applicationId: input.applicationId,\n customerId,\n planReference: input.planReference,\n planName: input.planName,\n interval: input.interval,\n intervalUnit: input.intervalUnit,\n intervalCount: input.intervalCount,\n totalPayments: input.totalPayments,\n amount: input.amount,\n allowZeroAmount: input.allowZeroAmount,\n schedule: input.schedule,\n currency: input.currency,\n currentPeriodStart: toIso(input.currentPeriodStart),\n currentPeriodEnd: toIso(input.currentPeriodEnd),\n trialEnd: toIso(input.trialEnd),\n metadata: input.metadata ?? {},\n orderId: input.orderId,\n });\n return normalizeSubscription(data);\n }\n\n async list(params: ListSubscriptionsParams = {}): Promise<PaginatedSubscriptions> {\n const query = new URLSearchParams();\n setQuery(query, 'customerId', params.customerId);\n setQuery(query, 'externalCustomerId', params.externalCustomerId);\n setQuery(query, 'status', params.status);\n setQuery(query, 'interval', params.interval);\n setQuery(query, 'installment', params.installment);\n setQuery(query, 'q', params.q);\n setQuery(query, 'cursor', params.cursor);\n setQuery(query, 'limit', params.limit);\n setQuery(query, 'sort', params.sort);\n setQuery(query, 'createdAfter', toIso(params.createdAfter));\n setQuery(query, 'createdBefore', toIso(params.createdBefore));\n\n const suffix = query.toString() ? `?${query}` : '';\n const envelope = await this.requestEnvelope<unknown[]>('GET', `/api/v1/subscriptions${suffix}`);\n return {\n data: (envelope.data ?? []).map(normalizeSubscription),\n pagination: normalizePagination(envelope.meta?.pagination),\n };\n }\n\n async get(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n );\n return normalizeSubscription(data);\n }\n\n /**\n * A term-only edit: rename the plan, correct the cadence or the amount on\n * the row — no proration, no charge, no period reset. Mirrors\n * `PATCH /api/v1/subscriptions/{id}`. This is what `changePlan()` did\n * before 3.0.0; use `changePlan()` now for an actual plan change.\n */\n async update(id: string, input: UpdateSubscriptionInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'PATCH',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n input,\n );\n return normalizeSubscription(data);\n }\n\n /**\n * A real plan change: prorated and charged immediately when\n * `effective: 'now'`, or scheduled for period end with no charge today.\n * Mirrors `POST /api/v1/subscriptions/{id}/change-plan`. The resolved\n * subscription carries `proration` when the server computed one.\n *\n * This is NOT the old `changePlan()` (a PATCH-style term edit with no\n * proration and no charge) — use `update()` for that.\n */\n async changePlan(input: ChangePlanInput): Promise<Subscription> {\n const { id, ...body } = input;\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/change-plan`,\n {\n planReference: body.planReference,\n planName: body.planName,\n interval: body.interval,\n intervalUnit: body.intervalUnit,\n intervalCount: body.intervalCount,\n amount: body.amount,\n allowZeroAmount: body.allowZeroAmount,\n effective: body.effective,\n },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Change the seat quantity: prorated and charged immediately when\n * `effective: 'now'`, or scheduled for period end with no charge today.\n * Mirrors `POST /api/v1/subscriptions/{id}/change-quantity`.\n */\n async changeQuantity(id: string, input: ChangeQuantityInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/change-quantity`,\n { quantity: input.quantity, effective: input.effective },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Charge a past-due subscription's card again now, instead of waiting for\n * the next scheduled dunning retry. Mirrors\n * `POST /api/v1/subscriptions/{id}/retry-charge`.\n */\n async retryCharge(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/retry-charge`,\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Forgive the current past-due period — the merchant is not collecting it.\n * Mirrors `POST /api/v1/subscriptions/{id}/waive-period`.\n */\n async waivePeriod(id: string, input: WaivePeriodInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/waive-period`,\n { reason: input.reason },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Set the saved card this one subscription renews on. Only this\n * subscription moves: the customer's default card and their other\n * subscriptions stay as they are. Nothing is charged now; the next renewal\n * (or dunning retry) charges the new card. Mirrors\n * `PATCH /api/v1/subscriptions/{id}/payment-method`.\n */\n async setPaymentMethod(id: string, paymentMethodId: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'PATCH',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/payment-method`,\n { paymentMethodId },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Record (upsert) a usage item for the subscription's current billing\n * period. Mirrors `POST /api/v1/subscriptions/{id}/usage`.\n */\n async recordUsage(id: string, input: RecordUsageInput): Promise<SubscriptionUsageItem> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/usage`,\n { kind: input.kind, unitCount: input.unitCount, unitPriceCents: input.unitPriceCents },\n );\n return normalizeUsageItem(data);\n }\n\n /**\n * List usage items recorded for the subscription's current billing period.\n * Mirrors `GET /api/v1/subscriptions/{id}/usage`.\n */\n async listUsage(id: string): Promise<SubscriptionUsageItem[]> {\n const envelope = await this.requestEnvelope<{ items?: unknown[] }>(\n 'GET',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/usage`,\n );\n // This route answers `{ items: [...] }`, not the usual `{ data, meta }`\n // envelope, so `request()`'s data-unwrap would just hand back the whole\n // body — read `items` off the raw envelope instead.\n const items = (envelope as unknown as { items?: unknown[] }).items ?? [];\n return items.map(normalizeUsageItem);\n }\n\n async pause(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/pause`,\n );\n return normalizeSubscription(data);\n }\n\n async resume(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/resume`,\n );\n return normalizeSubscription(data);\n }\n\n async cancel(\n id: string,\n input: { atPeriodEnd?: boolean; refund?: 'none' | 'prorated' | 'last_cycle' } = {},\n ): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/cancel`,\n { atPeriodEnd: input.atPeriodEnd ?? false, refund: input.refund ?? 'none' },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Refund one billing cycle.\n *\n * `intent` has no default: refunding money and ending the subscription are\n * separate decisions, and guessing either way is wrong often enough that the\n * API requires the caller to say which one they mean.\n */\n async refundInvoice(\n id: string,\n invoiceId: string,\n input: { intent: 'money_only' | 'refund_and_cancel'; amount?: number; reason?: string },\n ): Promise<SubscriptionInvoiceRefund> {\n return this.request<SubscriptionInvoiceRefund>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/invoices/${encodeURIComponent(invoiceId)}/refund`,\n input,\n );\n }\n\n async createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession> {\n const data = await this.request<unknown>('POST', '/api/v1/checkout/sessions', input);\n return normalizeCheckoutSession(data);\n }\n\n async checkTrialEligibility(input: TrialEligibilityInput): Promise<TrialEligibilityResult> {\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions/eligibility-check', {\n paymentMethodId: input.paymentMethodId,\n });\n return normalizeTrialEligibility(data);\n }\n\n async getCustomerByExternalId(externalId: string): Promise<Customer | null> {\n try {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/customers/by-external/${encodeURIComponent(externalId)}`,\n );\n return normalizeCustomer(data);\n } catch (err) {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n }\n }\n\n async listCustomerPaymentMethods(customerId: string): Promise<CustomerPaymentMethod[]> {\n const data = await this.request<unknown[]>(\n 'GET',\n `/api/v1/customers/${encodeURIComponent(customerId)}/payment-methods`,\n );\n return (data ?? []).map(normalizeCustomerPaymentMethod);\n }\n\n private async resolveCustomerId(\n customerId?: string,\n externalCustomerId?: string,\n ): Promise<string> {\n if (customerId) return customerId;\n if (!externalCustomerId) {\n throw new ThrottleSubscriptionsError({\n code: 'invalid_request',\n message: 'customerId or externalCustomerId is required',\n statusCode: 400,\n });\n }\n\n const customer = await this.getCustomerByExternalId(externalCustomerId);\n if (!customer) {\n throw new ThrottleSubscriptionsError({\n code: 'customer_not_found',\n message: 'Customer not found',\n statusCode: 404,\n });\n }\n return customer.id;\n }\n}\n\nexport function createSubscriptionsClient(opts: SubscriptionsClientOptions): SubscriptionsClient {\n return new SubscriptionsClient(opts);\n}\n\nfunction toAbsoluteUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n}\n\nfunction setQuery(query: URLSearchParams, key: string, value: unknown): void {\n if (value === undefined || value === null || value === '') return;\n query.set(key, String(value));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAsD;AAsBtD,IAAAA,iBAA+C;AAbxC,IAAM,6BAAN,cAAyC,4BAAc;AAAA,EAC5D,YAAY,MAMT;AACD,UAAM,IAAI;AACV,SAAK,OAAO;AAAA,EACd;AACF;;;ACNO,SAAS,sBAAsB,KAAwB;AAC5D,SAAO;AAAA,IACL,IAAI,eAAe,KAAK,IAAI,iBAAiB;AAAA,IAC7C,aAAa,eAAe,KAAK,WAAW;AAAA,IAC5C,eAAe,eAAe,KAAK,aAAa;AAAA,IAChD,YAAY,eAAe,KAAK,YAAY,yBAAyB;AAAA,IACrE,QAAS,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AkB;AAC9B,OAAK,OAAO,gBAAgB;AAC5B,OAAK,OAAO,mBAAmB;AAC/B,SAAO;AACT;AAEA,SAAS,UAAU,QAAgB,MAAc,SAA2B;AAC1E,SAAO,SAAS,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;AAC/D;","names":["import_errors"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/errors.ts","../src/normalize.ts","../src/client.ts"],"sourcesContent":["import { SubscriptionsClient, createSubscriptionsClient } from './client';\nimport { ThrottleSubscriptionsError } from './errors';\nimport type { Subscription, SubscriptionsClientOptions } from './types';\n\nexport { SubscriptionsClient, createSubscriptionsClient, ThrottleSubscriptionsError };\nexport type {\n CheckoutSession,\n CreateCheckoutSessionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n Subscription,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n TrialEligibilityInput,\n TrialEligibilityResult,\n} from './types';\n\nexport interface SubscriptionProxyOptions {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n getExternalCustomerId: (request: Request) => string | null | Promise<string | null>;\n /** When supplied it replaces the default installment rule; ownership is always checked. */\n authorizeMutation?: (args: {\n request: Request;\n subscription: Subscription;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n /**\n * Opt-in: lets a buyer create a subscription directly (`POST\n * /api/v1/subscriptions`). Refused by default (`403 create_not_allowed`):\n * the body names the plan and the price, and nothing is charged, so return\n * true only after checking `body` against your own price list. The\n * customer is always pinned to the authenticated buyer.\n */\n authorizeCreate?: (args: {\n request: Request;\n body: Record<string, unknown>;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n /**\n * Opt-in: lets a buyer `PATCH` fields of their own subscription beyond\n * `shippingAddress` (plan, cadence, amount, ...). Refused by default\n * (`403 field_not_allowed`): those are prices and terms, so return true only\n * after checking `body` against your own price list.\n */\n authorizeUpdate?: (args: {\n request: Request;\n subscription: Subscription;\n body: Record<string, unknown>;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n}\n\n/**\n * What a buyer may send on each mutation without a merchant hook. Anything\n * else is refused, never silently dropped, so a portal learns at once that a\n * field needs the merchant's say (4.0.0). `refund` on cancel is the reason\n * this exists: forwarding it let a buyer refund themselves.\n */\nconst BUYER_BODY_FIELDS: Record<string, readonly string[]> = {\n pause: [],\n resume: [],\n cancel: ['atPeriodEnd'],\n 'payment-method': ['paymentMethodId'],\n update: ['shippingAddress'],\n};\n\nexport interface SubscriptionProxyContext {\n params?: {\n path?: string[] | Promise<string[]>;\n };\n path?: string[] | string;\n}\n\nconst ALLOWED_PATHS = [\n /^\\/api\\/v1\\/subscriptions(?:\\/[\\w.-]+)?(?:\\/(?:pause|resume|cancel|payment-method))?$/,\n /^\\/api\\/v1\\/subscriptions\\/eligibility-check$/,\n /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/,\n /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/,\n /^\\/api\\/v1\\/checkout\\/sessions$/,\n];\n\nexport function createSubscriptionProxyHandler(options: SubscriptionProxyOptions) {\n return async function subscriptionProxyHandler(\n request: Request,\n context: SubscriptionProxyContext = {},\n ): Promise<Response> {\n const path = await pathFromContext(context);\n return handleSubscriptionProxyRequest(request, path, options);\n };\n}\n\nexport async function handleSubscriptionProxyRequest(\n request: Request,\n pathParts: string[] | string,\n options: SubscriptionProxyOptions,\n): Promise<Response> {\n const externalCustomerId = await options.getExternalCustomerId(request);\n if (!externalCustomerId) return jsonError(401, 'unauthorized', 'Unauthorized');\n\n const path = normalizePath(pathParts);\n if (!ALLOWED_PATHS.some((pattern) => pattern.test(path))) {\n return jsonError(403, 'forbidden', 'Path is not allowed by the subscription proxy');\n }\n\n const method = request.method.toUpperCase();\n if (!['GET', 'POST', 'PATCH'].includes(method)) {\n return jsonError(405, 'method_not_allowed', 'Method not allowed');\n }\n\n const client = new SubscriptionsClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n } satisfies SubscriptionsClientOptions);\n\n // Read once: every body rule below and the forwarded request share it.\n const raw = method === 'GET' ? '' : await request.text();\n let body: Record<string, unknown> = {};\n if (raw) {\n try {\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object');\n body = parsed as Record<string, unknown>;\n } catch {\n return jsonError(400, 'invalid_body', 'The request body must be a JSON object');\n }\n }\n\n // A direct create names its own plan and price and charges nothing.\n if (method === 'POST' && path === '/api/v1/subscriptions') {\n const allowed = options.authorizeCreate\n ? await options.authorizeCreate({ request, body, externalCustomerId })\n : false;\n if (!allowed) {\n return jsonError(403, 'create_not_allowed', 'Creating a subscription from the buyer portal is not allowed');\n }\n }\n\n // A read of one subscription is the buyer's own or nothing: 404 either way,\n // so an id that exists for someone else looks the same as one that does not.\n if (method === 'GET' && subscriptionIdFromPath(path) && path !== '/api/v1/subscriptions/eligibility-check') {\n const subscription = await client.get(subscriptionIdFromPath(path)!).catch((err) => {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n });\n if (!subscription || !(await defaultMutationAuthorization(client, subscription, externalCustomerId))) {\n return jsonError(404, 'not_found', 'Subscription not found');\n }\n }\n\n if (isSubscriptionMutation(path, method)) {\n const subId = subscriptionIdFromPath(path);\n if (subId) {\n const subscription = await client.get(subId).catch((err) => {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n });\n if (!subscription) return jsonError(404, 'not_found', 'Subscription not found');\n\n const owned = await defaultMutationAuthorization(client, subscription, externalCustomerId);\n if (!owned) return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n if (options.authorizeMutation) {\n if (!(await options.authorizeMutation({ request, subscription, externalCustomerId }))) {\n return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n }\n } else if (subscription.totalPayments != null && !isPaymentMethodPath(path) && !isShippingAddressOnly(path, method, body)) {\n // Same rule as the storefront buyer API (D33/D36): installment plans are merchant-only.\n // Changing the card is not one of the locked terms, so it stays allowed (F-2).\n return jsonError(\n 403,\n 'installment_plan_merchant_only',\n 'Installment plans can only be paused, resumed or cancelled by the merchant',\n );\n }\n\n const action = mutationAction(path, method);\n const extra = Object.keys(body).filter((key) => !(BUYER_BODY_FIELDS[action] ?? []).includes(key));\n if (extra.length > 0) {\n const merchantSays =\n action === 'update' && options.authorizeUpdate\n ? await options.authorizeUpdate({ request, subscription, body, externalCustomerId })\n : false;\n if (!merchantSays) {\n return jsonError(\n 403,\n 'field_not_allowed',\n `The buyer portal cannot change ${extra.join(', ')} on a subscription`,\n );\n }\n }\n }\n }\n\n const targetPath = await buildPinnedPathAndBody(request, path, externalCustomerId, client, raw);\n if (targetPath instanceof Response) return targetPath;\n const upstream = await fetchWithApiKey(request, targetPath.path, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n body: targetPath.body,\n });\n\n return new Response(upstream.body, {\n status: upstream.status,\n headers: filterHeaders(upstream.headers),\n });\n}\n\nasync function buildPinnedPathAndBody(\n request: Request,\n path: string,\n externalCustomerId: string,\n client: SubscriptionsClient,\n raw: string,\n): Promise<{ path: string; body?: string } | Response> {\n const url = new URL(request.url);\n const query = new URLSearchParams(url.search);\n\n if (request.method.toUpperCase() === 'GET' && path === '/api/v1/subscriptions') {\n query.set('externalCustomerId', externalCustomerId);\n query.delete('customerId');\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerByExternalPath(path)) {\n return {\n path: withQuery(\n `/api/v1/customers/by-external/${encodeURIComponent(externalCustomerId)}`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerPaymentMethodsPath(path)) {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n return {\n path: withQuery(\n `/api/v1/customers/${encodeURIComponent(customer.id)}/payment-methods`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() !== 'GET') {\n if (path === '/api/v1/subscriptions' && request.method.toUpperCase() === 'POST') {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n\n const body = raw ? (JSON.parse(raw) as Record<string, any>) : {};\n body.customerId = customer.id;\n delete body.externalCustomerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n\n if (path === '/api/v1/checkout/sessions' && raw) {\n const body = JSON.parse(raw) as Record<string, any>;\n body.customer = {\n ...(body.customer ?? {}),\n externalCustomerId,\n };\n delete body.customer.customerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n return { path: withQuery(path, query), body: raw || undefined };\n }\n\n return { path: withQuery(path, query) };\n}\n\nasync function fetchWithApiKey(\n request: Request,\n path: string,\n opts: {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n body?: string;\n },\n) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('fetch is required');\n const baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n return fetchImpl(`${baseUrl}${path}`, {\n method: request.method,\n headers: {\n 'x-api-key': opts.apiKey,\n 'content-type': request.headers.get('content-type') ?? 'application/json',\n },\n body: request.method.toUpperCase() === 'GET' ? undefined : opts.body,\n });\n}\n\nasync function defaultMutationAuthorization(\n client: SubscriptionsClient,\n subscription: Subscription,\n externalCustomerId: string,\n): Promise<boolean> {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n return Boolean(customer?.id && customer.id === subscription.customerId);\n}\n\nasync function pathFromContext(context: SubscriptionProxyContext): Promise<string[] | string> {\n if (context.path) return context.path;\n const path = context.params?.path;\n if (!path) return [];\n return await path;\n}\n\nfunction normalizePath(pathParts: string[] | string): string {\n if (typeof pathParts === 'string') {\n return pathParts.startsWith('/') ? pathParts : `/${pathParts}`;\n }\n return `/${pathParts.map((part) => part.replace(/^\\/+|\\/+$/g, '')).join('/')}`;\n}\n\nfunction withQuery(path: string, query: URLSearchParams): string {\n const qs = query.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\n/** Which BUYER_BODY_FIELDS rule a subscription mutation falls under. */\nfunction mutationAction(path: string, method: string): string {\n const suffix = /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+\\/([\\w-]+)$/.exec(path)?.[1];\n if (suffix) return suffix;\n return method === 'PATCH' ? 'update' : 'unknown';\n}\n\n/** A PATCH that only moves a physical subscription's box: allowed on an installment plan. */\nfunction isShippingAddressOnly(path: string, method: string, body: Record<string, unknown>): boolean {\n return mutationAction(path, method) === 'update' && Object.keys(body).length > 0 &&\n Object.keys(body).every((key) => key === 'shippingAddress');\n}\n\nfunction isSubscriptionMutation(path: string, method: string): boolean {\n if (path === '/api/v1/subscriptions/eligibility-check') return false;\n return method !== 'GET' && /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+/.test(path);\n}\n\nfunction isCustomerByExternalPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/.test(path);\n}\n\nfunction isCustomerPaymentMethodsPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/.test(path);\n}\n\nfunction isPaymentMethodPath(path: string): boolean {\n return /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+\\/payment-method$/.test(path);\n}\n\nfunction subscriptionIdFromPath(path: string): string | null {\n return path.match(/^\\/api\\/v1\\/subscriptions\\/([\\w.-]+)/)?.[1] ?? null;\n}\n\nfunction filterHeaders(headers: Headers): Headers {\n const next = new Headers(headers);\n next.delete('content-encoding');\n next.delete('content-length');\n next.delete('transfer-encoding');\n return next;\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return Response.json({ error: { code, message } }, { status });\n}\n","import { ThrottleError, type ThrottleErrorArgs } from '@usethrottle/errors';\n\n/**\n * Thrown on a non-2xx response from the Throttle Subscriptions API.\n *\n * Extends the shared {@link ThrottleError} so a single\n * `catch (e) { if (e instanceof ThrottleError) … }` covers errors from every\n * Throttle SDK. `instanceof ThrottleSubscriptionsError` keeps working.\n */\nexport class ThrottleSubscriptionsError extends ThrottleError {\n constructor(args: {\n code: string;\n message: string;\n statusCode: number;\n details?: unknown;\n responseHeaders?: ThrottleErrorArgs['responseHeaders'];\n }) {\n super(args);\n this.name = 'ThrottleSubscriptionsError';\n }\n}\n\nexport { ThrottleError, isThrottleError } from '@usethrottle/errors';\n","import type {\n CheckoutSession,\n Customer,\n CustomerPaymentMethod,\n Pagination,\n Subscription,\n SubscriptionInterval,\n SubscriptionIntervalUnit,\n SubscriptionRenewalIssue,\n SubscriptionStatus,\n SubscriptionUsageItem,\n TrialEligibilityResult,\n} from './types';\n\nexport function normalizeSubscription(raw: any): Subscription {\n return {\n id: requiredString(raw?.id, 'subscription.id'),\n workspaceId: optionalString(raw?.workspaceId),\n applicationId: optionalString(raw?.applicationId),\n customerId: requiredString(raw?.customerId, 'subscription.customerId'),\n status: (raw?.status ?? 'active') as SubscriptionStatus,\n planReference: requiredString(raw?.planReference, 'subscription.planReference'),\n planName: optionalString(raw?.planName),\n interval: (raw?.interval ?? 'monthly') as SubscriptionInterval,\n intervalUnit: (optionalString(raw?.intervalUnit) as Subscription['intervalUnit']) ?? null,\n intervalCount: raw?.intervalCount == null ? null : Number(raw.intervalCount),\n totalPayments: raw?.totalPayments == null ? null : Number(raw.totalPayments),\n paymentsMade: Number(raw?.paymentsMade ?? 0),\n completedAt: optionalIsoDateString(raw?.completedAt),\n paymentSchedule: normalizePaymentSchedule(raw?.paymentSchedule),\n scheduleTotal: raw?.scheduleTotal == null ? null : Number(raw.scheduleTotal),\n nextPaymentAmount: raw?.nextPaymentAmount == null ? null : Number(raw.nextPaymentAmount),\n amount: Number(raw?.amount ?? 0),\n quantity: Number(raw?.quantity ?? 1),\n // No USD fallback (MC2-R35): a subscription without a currency is a broken response.\n currency: requiredString(raw?.currency, 'subscription.currency'),\n currentPeriodStart: requiredDateString(\n raw?.currentPeriodStart,\n 'subscription.currentPeriodStart',\n ),\n currentPeriodEnd: requiredDateString(\n raw?.currentPeriodEnd,\n 'subscription.currentPeriodEnd',\n ),\n trialEnd: optionalDateString(raw?.trialEnd),\n cancelAtPeriodEnd: Boolean(raw?.cancelAtPeriodEnd ?? false),\n failureCount: Number(raw?.failureCount ?? 0),\n lastPaymentAt: optionalDateString(raw?.lastPaymentAt),\n pausedAt: optionalDateString(raw?.pausedAt),\n cancelledAt: optionalDateString(raw?.cancelledAt),\n metadata: objectOrEmpty(raw?.metadata),\n paymentMethodId: optionalString(raw?.paymentMethodId),\n deliveryMethod: raw?.deliveryMethod === 'shipment' ? 'shipment' : 'access_grant',\n shippingAddress:\n raw?.shippingAddress && typeof raw.shippingAddress === 'object' ? raw.shippingAddress : null,\n // `currency` above has already been checked.\n renewalIssue: normalizeRenewalIssue(raw?.renewalIssue, raw.currency),\n proration: raw?.proration\n ? {\n creditCents: raw.proration.creditCents,\n chargedCents: raw.proration.chargedCents,\n fullAmount: raw.proration.fullAmount,\n }\n : undefined,\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nfunction normalizePaymentSchedule(raw: any): Subscription['paymentSchedule'] {\n if (!Array.isArray(raw)) return null;\n return raw.map((r: any) => ({\n index: Number(r?.index ?? 0),\n amount: Number(r?.amount ?? 0),\n discount: Number(r?.discount ?? 0),\n net: Number(r?.net ?? 0),\n intervalUnit: (optionalString(r?.intervalUnit) as SubscriptionIntervalUnit | null) ?? null,\n intervalCount: r?.intervalCount == null ? null : Number(r.intervalCount),\n status: r?.status as 'paid' | 'due' | 'upcoming',\n dueAt: optionalDateString(r?.dueAt),\n }));\n}\n\nfunction normalizeRenewalIssue(raw: any, subscriptionCurrency: string): SubscriptionRenewalIssue | null {\n if (!raw || typeof raw !== 'object') return null;\n return {\n kind: raw.kind,\n reason: raw.reason,\n count: Number(raw.count ?? 0),\n firstAt: optionalString(raw.firstAt) ?? undefined,\n lastAt: requiredString(raw.lastAt, 'subscription.renewalIssue.lastAt'),\n message: raw.message ?? '',\n alertedAt: optionalDateString(raw.alertedAt),\n charge: raw.charge\n ? {\n transactionId: optionalString(raw.charge.transactionId),\n amount: Number(raw.charge.amount ?? 0),\n currency: optionalString(raw.charge.currency) || subscriptionCurrency,\n periodStart: optionalString(raw.charge.periodStart) ?? undefined,\n }\n : null,\n };\n}\n\nexport function normalizeUsageItem(raw: any): SubscriptionUsageItem {\n return {\n id: requiredString(raw?.id, 'usageItem.id'),\n subscriptionId: requiredString(raw?.subscriptionId, 'usageItem.subscriptionId'),\n kind: raw?.kind ?? '',\n unitCount: Number(raw?.unitCount ?? 0),\n unitPriceCents: Number(raw?.unitPriceCents ?? 0),\n totalCents: Number(raw?.totalCents ?? 0),\n periodStart: requiredDateString(raw?.periodStart, 'usageItem.periodStart'),\n periodEnd: requiredDateString(raw?.periodEnd, 'usageItem.periodEnd'),\n createdAt: requiredDateString(raw?.createdAt, 'usageItem.createdAt'),\n };\n}\n\nexport function normalizeCustomer(raw: any): Customer | null {\n if (!raw) return null;\n return {\n id: requiredString(raw?.id, 'customer.id'),\n externalId: optionalString(raw?.externalId),\n email: optionalString(raw?.email),\n firstName: optionalString(raw?.firstName),\n lastName: optionalString(raw?.lastName),\n phone: optionalString(raw?.phone),\n company: optionalString(raw?.company),\n metadata: objectOrEmpty(raw?.metadata),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCustomerPaymentMethod(raw: any): CustomerPaymentMethod {\n return {\n id: requiredString(raw?.id, 'paymentMethod.id'),\n processor: optionalString(raw?.processor),\n methodType: optionalString(raw?.methodType),\n cardBrand: optionalString(raw?.cardBrand),\n cardLastFour: optionalString(raw?.cardLastFour),\n isDefault: Boolean(raw?.isDefault ?? false),\n isActive: Boolean(raw?.isActive ?? true),\n createdAt: optionalDateString(raw?.createdAt) ?? undefined,\n updatedAt: optionalDateString(raw?.updatedAt) ?? undefined,\n };\n}\n\nexport function normalizeCheckoutSession(raw: any): CheckoutSession {\n const sessionId = raw?.sessionId ?? raw?.id;\n return {\n ...withoutUnderscoreKeys(raw),\n id: optionalString(raw?.id) ?? undefined,\n sessionId: requiredString(sessionId, 'checkoutSession.sessionId'),\n checkoutUrl: optionalString(raw?.checkoutUrl) ?? undefined,\n embedToken: optionalString(raw?.embedToken) ?? undefined,\n expiresAt: optionalDateString(raw?.expiresAt) ?? undefined,\n };\n}\n\nexport function normalizeTrialEligibility(raw: any): TrialEligibilityResult {\n return {\n eligible: Boolean(raw?.eligible),\n reason: raw?.reason,\n };\n}\n\nexport function normalizePagination(raw: any): Pagination | undefined {\n if (!raw) return undefined;\n return {\n cursor: raw.cursor ?? null,\n hasMore: Boolean(raw.hasMore ?? false),\n };\n}\n\nexport function toIso(value: string | Date | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction requiredString(value: unknown, label: string): string {\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalString(value: unknown): string | null {\n return typeof value === 'string' ? value : null;\n}\n\nfunction requiredDateString(value: unknown, label: string): string {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n throw new Error(`Invalid Throttle response: missing ${label}`);\n}\n\nfunction optionalDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) return value;\n return null;\n}\n\n/**\n * Like `optionalDateString`, but always reserializes to a full ISO string\n * (with milliseconds) rather than passing a raw string through unchanged.\n * `completedAt` is a fresh field with no legacy raw-string callers to stay\n * compatible with, so it normalizes cleanly instead of echoing whatever the\n * API sent.\n */\nfunction optionalIsoDateString(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string' && value.length > 0) {\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? value : d.toISOString();\n }\n return null;\n}\n\nfunction objectOrEmpty(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction withoutUnderscoreKeys(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return {};\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).filter(([key]) => !key.includes('_')),\n );\n}\n","import { ThrottleSubscriptionsError } from './errors';\nimport {\n normalizeCheckoutSession,\n normalizeCustomer,\n normalizeCustomerPaymentMethod,\n normalizePagination,\n normalizeSubscription,\n normalizeTrialEligibility,\n normalizeUsageItem,\n toIso,\n} from './normalize';\nimport type {\n ChangePlanInput,\n ChangeQuantityInput,\n CheckoutSession,\n CreateCheckoutSessionInput,\n CreateSubscriptionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n RecordUsageInput,\n Subscription,\n SubscriptionInvoiceRefund,\n SubscriptionUsageItem,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n ThrottleEnvelope,\n TrialEligibilityInput,\n TrialEligibilityResult,\n UpdateSubscriptionInput,\n WaivePeriodInput,\n} from './types';\n\nexport class SubscriptionsClient implements SubscriptionsClientContract {\n private readonly apiKey?: string;\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly fetcher?: SubscriptionsClientOptions['fetcher'];\n private readonly timeoutMs: number;\n\n constructor(opts: SubscriptionsClientOptions = {}) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('SubscriptionsClient: fetch is required');\n if (!opts.apiKey && !opts.fetcher) {\n throw new Error('SubscriptionsClient: apiKey or fetcher is required');\n }\n\n this.apiKey = opts.apiKey;\n this.baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n this.fetchImpl = fetchImpl;\n this.fetcher = opts.fetcher;\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n }\n\n async request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n const envelope = await this.requestEnvelope<T>(method, path, body);\n if (Object.prototype.hasOwnProperty.call(envelope, 'data')) {\n return envelope.data as T;\n }\n return envelope as T;\n }\n\n async requestEnvelope<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<ThrottleEnvelope<T>> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n\n try {\n const init: RequestInit = {\n method,\n headers: {\n 'content-type': 'application/json',\n ...(this.apiKey ? { 'x-api-key': this.apiKey } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: ctrl.signal,\n };\n\n const res = this.fetcher\n ? await this.fetcher(path, init)\n : await this.fetchImpl(toAbsoluteUrl(this.baseUrl, path), init);\n\n if (res.status === 204) return { data: undefined as T };\n\n const json = (await res.json().catch(() => ({}))) as ThrottleEnvelope<T>;\n if (!res.ok) {\n throw new ThrottleSubscriptionsError({\n code: json.error?.code ?? 'unknown_error',\n message: json.error?.message ?? `HTTP ${res.status}`,\n statusCode: res.status,\n details: json.error?.details,\n responseHeaders: res.headers,\n });\n }\n return json;\n } finally {\n clearTimeout(timer);\n }\n }\n\n async create(input: CreateSubscriptionInput): Promise<Subscription> {\n const customerId = await this.resolveCustomerId(input.customerId, input.externalCustomerId);\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions', {\n applicationId: input.applicationId,\n customerId,\n planReference: input.planReference,\n planName: input.planName,\n interval: input.interval,\n intervalUnit: input.intervalUnit,\n intervalCount: input.intervalCount,\n totalPayments: input.totalPayments,\n amount: input.amount,\n allowZeroAmount: input.allowZeroAmount,\n schedule: input.schedule,\n currency: input.currency,\n currentPeriodStart: toIso(input.currentPeriodStart),\n currentPeriodEnd: toIso(input.currentPeriodEnd),\n trialEnd: toIso(input.trialEnd),\n metadata: input.metadata ?? {},\n orderId: input.orderId,\n });\n return normalizeSubscription(data);\n }\n\n async list(params: ListSubscriptionsParams = {}): Promise<PaginatedSubscriptions> {\n const query = new URLSearchParams();\n setQuery(query, 'customerId', params.customerId);\n setQuery(query, 'externalCustomerId', params.externalCustomerId);\n setQuery(query, 'status', params.status);\n setQuery(query, 'interval', params.interval);\n setQuery(query, 'installment', params.installment);\n setQuery(query, 'q', params.q);\n setQuery(query, 'cursor', params.cursor);\n setQuery(query, 'limit', params.limit);\n setQuery(query, 'sort', params.sort);\n setQuery(query, 'createdAfter', toIso(params.createdAfter));\n setQuery(query, 'createdBefore', toIso(params.createdBefore));\n\n const suffix = query.toString() ? `?${query}` : '';\n const envelope = await this.requestEnvelope<unknown[]>('GET', `/api/v1/subscriptions${suffix}`);\n return {\n data: (envelope.data ?? []).map(normalizeSubscription),\n pagination: normalizePagination(envelope.meta?.pagination),\n };\n }\n\n async get(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n );\n return normalizeSubscription(data);\n }\n\n /**\n * A term-only edit: rename the plan, correct the cadence or the amount on\n * the row — no proration, no charge, no period reset. Mirrors\n * `PATCH /api/v1/subscriptions/{id}`. This is what `changePlan()` did\n * before 3.0.0; use `changePlan()` now for an actual plan change.\n */\n async update(id: string, input: UpdateSubscriptionInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'PATCH',\n `/api/v1/subscriptions/${encodeURIComponent(id)}`,\n input,\n );\n return normalizeSubscription(data);\n }\n\n /**\n * A real plan change: prorated and charged immediately when\n * `effective: 'now'`, or scheduled for period end with no charge today.\n * Mirrors `POST /api/v1/subscriptions/{id}/change-plan`. The resolved\n * subscription carries `proration` when the server computed one.\n *\n * This is NOT the old `changePlan()` (a PATCH-style term edit with no\n * proration and no charge) — use `update()` for that.\n */\n async changePlan(input: ChangePlanInput): Promise<Subscription> {\n const { id, ...body } = input;\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/change-plan`,\n {\n planReference: body.planReference,\n planName: body.planName,\n interval: body.interval,\n intervalUnit: body.intervalUnit,\n intervalCount: body.intervalCount,\n amount: body.amount,\n allowZeroAmount: body.allowZeroAmount,\n effective: body.effective,\n },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Change the seat quantity: prorated and charged immediately when\n * `effective: 'now'`, or scheduled for period end with no charge today.\n * Mirrors `POST /api/v1/subscriptions/{id}/change-quantity`.\n */\n async changeQuantity(id: string, input: ChangeQuantityInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/change-quantity`,\n { quantity: input.quantity, effective: input.effective },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Charge a past-due subscription's card again now, instead of waiting for\n * the next scheduled dunning retry. Mirrors\n * `POST /api/v1/subscriptions/{id}/retry-charge`.\n */\n async retryCharge(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/retry-charge`,\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Forgive the current past-due period — the merchant is not collecting it.\n * Mirrors `POST /api/v1/subscriptions/{id}/waive-period`.\n */\n async waivePeriod(id: string, input: WaivePeriodInput): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/waive-period`,\n { reason: input.reason },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Set the saved card this one subscription renews on. Only this\n * subscription moves: the customer's default card and their other\n * subscriptions stay as they are. Nothing is charged now; the next renewal\n * (or dunning retry) charges the new card. Mirrors\n * `PATCH /api/v1/subscriptions/{id}/payment-method`.\n */\n async setPaymentMethod(id: string, paymentMethodId: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'PATCH',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/payment-method`,\n { paymentMethodId },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Record (upsert) a usage item for the subscription's current billing\n * period. Mirrors `POST /api/v1/subscriptions/{id}/usage`.\n */\n async recordUsage(id: string, input: RecordUsageInput): Promise<SubscriptionUsageItem> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/usage`,\n { kind: input.kind, unitCount: input.unitCount, unitPriceCents: input.unitPriceCents },\n );\n return normalizeUsageItem(data);\n }\n\n /**\n * List usage items recorded for the subscription's current billing period.\n * Mirrors `GET /api/v1/subscriptions/{id}/usage`.\n */\n async listUsage(id: string): Promise<SubscriptionUsageItem[]> {\n const envelope = await this.requestEnvelope<{ items?: unknown[] }>(\n 'GET',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/usage`,\n );\n // This route answers `{ items: [...] }`, not the usual `{ data, meta }`\n // envelope, so `request()`'s data-unwrap would just hand back the whole\n // body — read `items` off the raw envelope instead.\n const items = (envelope as unknown as { items?: unknown[] }).items ?? [];\n return items.map(normalizeUsageItem);\n }\n\n async pause(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/pause`,\n );\n return normalizeSubscription(data);\n }\n\n async resume(id: string): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/resume`,\n );\n return normalizeSubscription(data);\n }\n\n async cancel(\n id: string,\n input: { atPeriodEnd?: boolean; refund?: 'none' | 'prorated' | 'last_cycle' } = {},\n ): Promise<Subscription> {\n const data = await this.request<unknown>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/cancel`,\n { atPeriodEnd: input.atPeriodEnd ?? false, refund: input.refund ?? 'none' },\n );\n return normalizeSubscription(data);\n }\n\n /**\n * Refund one billing cycle.\n *\n * `intent` has no default: refunding money and ending the subscription are\n * separate decisions, and guessing either way is wrong often enough that the\n * API requires the caller to say which one they mean.\n */\n async refundInvoice(\n id: string,\n invoiceId: string,\n input: { intent: 'money_only' | 'refund_and_cancel'; amount?: number; reason?: string },\n ): Promise<SubscriptionInvoiceRefund> {\n return this.request<SubscriptionInvoiceRefund>(\n 'POST',\n `/api/v1/subscriptions/${encodeURIComponent(id)}/invoices/${encodeURIComponent(invoiceId)}/refund`,\n input,\n );\n }\n\n async createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession> {\n const data = await this.request<unknown>('POST', '/api/v1/checkout/sessions', input);\n return normalizeCheckoutSession(data);\n }\n\n async checkTrialEligibility(input: TrialEligibilityInput): Promise<TrialEligibilityResult> {\n const data = await this.request<unknown>('POST', '/api/v1/subscriptions/eligibility-check', {\n paymentMethodId: input.paymentMethodId,\n });\n return normalizeTrialEligibility(data);\n }\n\n async getCustomerByExternalId(externalId: string): Promise<Customer | null> {\n try {\n const data = await this.request<unknown>(\n 'GET',\n `/api/v1/customers/by-external/${encodeURIComponent(externalId)}`,\n );\n return normalizeCustomer(data);\n } catch (err) {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n }\n }\n\n async listCustomerPaymentMethods(customerId: string): Promise<CustomerPaymentMethod[]> {\n const data = await this.request<unknown[]>(\n 'GET',\n `/api/v1/customers/${encodeURIComponent(customerId)}/payment-methods`,\n );\n return (data ?? []).map(normalizeCustomerPaymentMethod);\n }\n\n private async resolveCustomerId(\n customerId?: string,\n externalCustomerId?: string,\n ): Promise<string> {\n if (customerId) return customerId;\n if (!externalCustomerId) {\n throw new ThrottleSubscriptionsError({\n code: 'invalid_request',\n message: 'customerId or externalCustomerId is required',\n statusCode: 400,\n });\n }\n\n const customer = await this.getCustomerByExternalId(externalCustomerId);\n if (!customer) {\n throw new ThrottleSubscriptionsError({\n code: 'customer_not_found',\n message: 'Customer not found',\n statusCode: 404,\n });\n }\n return customer.id;\n }\n}\n\nexport function createSubscriptionsClient(opts: SubscriptionsClientOptions): SubscriptionsClient {\n return new SubscriptionsClient(opts);\n}\n\nfunction toAbsoluteUrl(baseUrl: string, path: string): string {\n if (/^https?:\\/\\//i.test(path)) return path;\n return `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n}\n\nfunction setQuery(query: URLSearchParams, key: string, value: unknown): void {\n if (value === undefined || value === null || value === '') return;\n query.set(key, String(value));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAsD;AAsBtD,IAAAA,iBAA+C;AAbxC,IAAM,6BAAN,cAAyC,4BAAc;AAAA,EAC5D,YAAY,MAMT;AACD,UAAM,IAAI;AACV,SAAK,OAAO;AAAA,EACd;AACF;;;ACNO,SAAS,sBAAsB,KAAwB;AAC5D,SAAO;AAAA,IACL,IAAI,eAAe,KAAK,IAAI,iBAAiB;AAAA,IAC7C,aAAa,eAAe,KAAK,WAAW;AAAA,IAC5C,eAAe,eAAe,KAAK,aAAa;AAAA,IAChD,YAAY,eAAe,KAAK,YAAY,yBAAyB;AAAA,IACrE,QAAS,KAAK,UAAU;AAAA,IACxB,eAAe,eAAe,KAAK,eAAe,4BAA4B;AAAA,IAC9E,UAAU,eAAe,KAAK,QAAQ;AAAA,IACtC,UAAW,KAAK,YAAY;AAAA,IAC5B,cAAe,eAAe,KAAK,YAAY,KAAsC;AAAA,IACrF,eAAe,KAAK,iBAAiB,OAAO,OAAO,OAAO,IAAI,aAAa;AAAA,IAC3E,eAAe,KAAK,iBAAiB,OAAO,OAAO,OAAO,IAAI,aAAa;AAAA,IAC3E,cAAc,OAAO,KAAK,gBAAgB,CAAC;AAAA,IAC3C,aAAa,sBAAsB,KAAK,WAAW;AAAA,IACnD,iBAAiB,yBAAyB,KAAK,eAAe;AAAA,IAC9D,eAAe,KAAK,iBAAiB,OAAO,OAAO,OAAO,IAAI,aAAa;AAAA,IAC3E,mBAAmB,KAAK,qBAAqB,OAAO,OAAO,OAAO,IAAI,iBAAiB;AAAA,IACvF,QAAQ,OAAO,KAAK,UAAU,CAAC;AAAA,IAC/B,UAA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;AAEA,SAAS,uBAAuB,MAA6B;AAC3D,SAAO,KAAK,MAAM,sCAAsC,IAAI,CAAC,KAAK;AACpE;AAEA,SAAS,cAAc,SAA2B;AAChD,QAAM,OAAO,IAAI,QAAQ,OAAO;AAChC,OAAK,OAAO,kBAAkB;AAC9B,OAAK,OAAO,gBAAgB;AAC5B,OAAK,OAAO,mBAAmB;AAC/B,SAAO;AACT;AAEA,SAAS,UAAU,QAAgB,MAAc,SAA2B;AAC1E,SAAO,SAAS,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;AAC/D;","names":["import_errors"]}
|
package/dist/server.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { S as Subscription } from './errors-
|
|
2
|
-
export { e as CheckoutSession, f as CreateCheckoutSessionInput, h as Customer, i as CustomerPaymentMethod, L as ListSubscriptionsParams, P as PaginatedSubscriptions,
|
|
1
|
+
import { S as Subscription } from './errors-DyoAgada.cjs';
|
|
2
|
+
export { e as CheckoutSession, f as CreateCheckoutSessionInput, h as Customer, i as CustomerPaymentMethod, L as ListSubscriptionsParams, P as PaginatedSubscriptions, B as SubscriptionsClient, E as SubscriptionsClientContract, F as SubscriptionsClientOptions, G as ThrottleSubscriptionsError, I as TrialEligibilityInput, K as TrialEligibilityResult, N as createSubscriptionsClient } from './errors-DyoAgada.cjs';
|
|
3
3
|
import 'react';
|
|
4
|
+
import '@usethrottle/money';
|
|
4
5
|
import '@usethrottle/errors';
|
|
5
6
|
|
|
6
7
|
interface SubscriptionProxyOptions {
|
|
@@ -14,6 +15,30 @@ interface SubscriptionProxyOptions {
|
|
|
14
15
|
subscription: Subscription;
|
|
15
16
|
externalCustomerId: string;
|
|
16
17
|
}) => boolean | Promise<boolean>;
|
|
18
|
+
/**
|
|
19
|
+
* Opt-in: lets a buyer create a subscription directly (`POST
|
|
20
|
+
* /api/v1/subscriptions`). Refused by default (`403 create_not_allowed`):
|
|
21
|
+
* the body names the plan and the price, and nothing is charged, so return
|
|
22
|
+
* true only after checking `body` against your own price list. The
|
|
23
|
+
* customer is always pinned to the authenticated buyer.
|
|
24
|
+
*/
|
|
25
|
+
authorizeCreate?: (args: {
|
|
26
|
+
request: Request;
|
|
27
|
+
body: Record<string, unknown>;
|
|
28
|
+
externalCustomerId: string;
|
|
29
|
+
}) => boolean | Promise<boolean>;
|
|
30
|
+
/**
|
|
31
|
+
* Opt-in: lets a buyer `PATCH` fields of their own subscription beyond
|
|
32
|
+
* `shippingAddress` (plan, cadence, amount, ...). Refused by default
|
|
33
|
+
* (`403 field_not_allowed`): those are prices and terms, so return true only
|
|
34
|
+
* after checking `body` against your own price list.
|
|
35
|
+
*/
|
|
36
|
+
authorizeUpdate?: (args: {
|
|
37
|
+
request: Request;
|
|
38
|
+
subscription: Subscription;
|
|
39
|
+
body: Record<string, unknown>;
|
|
40
|
+
externalCustomerId: string;
|
|
41
|
+
}) => boolean | Promise<boolean>;
|
|
17
42
|
}
|
|
18
43
|
interface SubscriptionProxyContext {
|
|
19
44
|
params?: {
|
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { S as Subscription } from './errors-
|
|
2
|
-
export { e as CheckoutSession, f as CreateCheckoutSessionInput, h as Customer, i as CustomerPaymentMethod, L as ListSubscriptionsParams, P as PaginatedSubscriptions,
|
|
1
|
+
import { S as Subscription } from './errors-DyoAgada.js';
|
|
2
|
+
export { e as CheckoutSession, f as CreateCheckoutSessionInput, h as Customer, i as CustomerPaymentMethod, L as ListSubscriptionsParams, P as PaginatedSubscriptions, B as SubscriptionsClient, E as SubscriptionsClientContract, F as SubscriptionsClientOptions, G as ThrottleSubscriptionsError, I as TrialEligibilityInput, K as TrialEligibilityResult, N as createSubscriptionsClient } from './errors-DyoAgada.js';
|
|
3
3
|
import 'react';
|
|
4
|
+
import '@usethrottle/money';
|
|
4
5
|
import '@usethrottle/errors';
|
|
5
6
|
|
|
6
7
|
interface SubscriptionProxyOptions {
|
|
@@ -14,6 +15,30 @@ interface SubscriptionProxyOptions {
|
|
|
14
15
|
subscription: Subscription;
|
|
15
16
|
externalCustomerId: string;
|
|
16
17
|
}) => boolean | Promise<boolean>;
|
|
18
|
+
/**
|
|
19
|
+
* Opt-in: lets a buyer create a subscription directly (`POST
|
|
20
|
+
* /api/v1/subscriptions`). Refused by default (`403 create_not_allowed`):
|
|
21
|
+
* the body names the plan and the price, and nothing is charged, so return
|
|
22
|
+
* true only after checking `body` against your own price list. The
|
|
23
|
+
* customer is always pinned to the authenticated buyer.
|
|
24
|
+
*/
|
|
25
|
+
authorizeCreate?: (args: {
|
|
26
|
+
request: Request;
|
|
27
|
+
body: Record<string, unknown>;
|
|
28
|
+
externalCustomerId: string;
|
|
29
|
+
}) => boolean | Promise<boolean>;
|
|
30
|
+
/**
|
|
31
|
+
* Opt-in: lets a buyer `PATCH` fields of their own subscription beyond
|
|
32
|
+
* `shippingAddress` (plan, cadence, amount, ...). Refused by default
|
|
33
|
+
* (`403 field_not_allowed`): those are prices and terms, so return true only
|
|
34
|
+
* after checking `body` against your own price list.
|
|
35
|
+
*/
|
|
36
|
+
authorizeUpdate?: (args: {
|
|
37
|
+
request: Request;
|
|
38
|
+
subscription: Subscription;
|
|
39
|
+
body: Record<string, unknown>;
|
|
40
|
+
externalCustomerId: string;
|
|
41
|
+
}) => boolean | Promise<boolean>;
|
|
17
42
|
}
|
|
18
43
|
interface SubscriptionProxyContext {
|
|
19
44
|
params?: {
|
package/dist/server.js
CHANGED
|
@@ -2,9 +2,16 @@ import {
|
|
|
2
2
|
SubscriptionsClient,
|
|
3
3
|
ThrottleSubscriptionsError,
|
|
4
4
|
createSubscriptionsClient
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-GK6QY63F.js";
|
|
6
6
|
|
|
7
7
|
// src/server.ts
|
|
8
|
+
var BUYER_BODY_FIELDS = {
|
|
9
|
+
pause: [],
|
|
10
|
+
resume: [],
|
|
11
|
+
cancel: ["atPeriodEnd"],
|
|
12
|
+
"payment-method": ["paymentMethodId"],
|
|
13
|
+
update: ["shippingAddress"]
|
|
14
|
+
};
|
|
8
15
|
var ALLOWED_PATHS = [
|
|
9
16
|
/^\/api\/v1\/subscriptions(?:\/[\w.-]+)?(?:\/(?:pause|resume|cancel|payment-method))?$/,
|
|
10
17
|
/^\/api\/v1\/subscriptions\/eligibility-check$/,
|
|
@@ -34,6 +41,32 @@ async function handleSubscriptionProxyRequest(request, pathParts, options) {
|
|
|
34
41
|
baseUrl: options.baseUrl,
|
|
35
42
|
fetch: options.fetch
|
|
36
43
|
});
|
|
44
|
+
const raw = method === "GET" ? "" : await request.text();
|
|
45
|
+
let body = {};
|
|
46
|
+
if (raw) {
|
|
47
|
+
try {
|
|
48
|
+
const parsed = JSON.parse(raw);
|
|
49
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
|
|
50
|
+
body = parsed;
|
|
51
|
+
} catch {
|
|
52
|
+
return jsonError(400, "invalid_body", "The request body must be a JSON object");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (method === "POST" && path === "/api/v1/subscriptions") {
|
|
56
|
+
const allowed = options.authorizeCreate ? await options.authorizeCreate({ request, body, externalCustomerId }) : false;
|
|
57
|
+
if (!allowed) {
|
|
58
|
+
return jsonError(403, "create_not_allowed", "Creating a subscription from the buyer portal is not allowed");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (method === "GET" && subscriptionIdFromPath(path) && path !== "/api/v1/subscriptions/eligibility-check") {
|
|
62
|
+
const subscription = await client.get(subscriptionIdFromPath(path)).catch((err) => {
|
|
63
|
+
if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;
|
|
64
|
+
throw err;
|
|
65
|
+
});
|
|
66
|
+
if (!subscription || !await defaultMutationAuthorization(client, subscription, externalCustomerId)) {
|
|
67
|
+
return jsonError(404, "not_found", "Subscription not found");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
37
70
|
if (isSubscriptionMutation(path, method)) {
|
|
38
71
|
const subId = subscriptionIdFromPath(path);
|
|
39
72
|
if (subId) {
|
|
@@ -48,16 +81,28 @@ async function handleSubscriptionProxyRequest(request, pathParts, options) {
|
|
|
48
81
|
if (!await options.authorizeMutation({ request, subscription, externalCustomerId })) {
|
|
49
82
|
return jsonError(403, "forbidden", "Subscription does not belong to this buyer");
|
|
50
83
|
}
|
|
51
|
-
} else if (subscription.totalPayments != null && !isPaymentMethodPath(path)) {
|
|
84
|
+
} else if (subscription.totalPayments != null && !isPaymentMethodPath(path) && !isShippingAddressOnly(path, method, body)) {
|
|
52
85
|
return jsonError(
|
|
53
86
|
403,
|
|
54
87
|
"installment_plan_merchant_only",
|
|
55
88
|
"Installment plans can only be paused, resumed or cancelled by the merchant"
|
|
56
89
|
);
|
|
57
90
|
}
|
|
91
|
+
const action = mutationAction(path, method);
|
|
92
|
+
const extra = Object.keys(body).filter((key) => !(BUYER_BODY_FIELDS[action] ?? []).includes(key));
|
|
93
|
+
if (extra.length > 0) {
|
|
94
|
+
const merchantSays = action === "update" && options.authorizeUpdate ? await options.authorizeUpdate({ request, subscription, body, externalCustomerId }) : false;
|
|
95
|
+
if (!merchantSays) {
|
|
96
|
+
return jsonError(
|
|
97
|
+
403,
|
|
98
|
+
"field_not_allowed",
|
|
99
|
+
`The buyer portal cannot change ${extra.join(", ")} on a subscription`
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
58
103
|
}
|
|
59
104
|
}
|
|
60
|
-
const targetPath = await buildPinnedPathAndBody(request, path, externalCustomerId, client);
|
|
105
|
+
const targetPath = await buildPinnedPathAndBody(request, path, externalCustomerId, client, raw);
|
|
61
106
|
if (targetPath instanceof Response) return targetPath;
|
|
62
107
|
const upstream = await fetchWithApiKey(request, targetPath.path, {
|
|
63
108
|
apiKey: options.apiKey,
|
|
@@ -70,7 +115,7 @@ async function handleSubscriptionProxyRequest(request, pathParts, options) {
|
|
|
70
115
|
headers: filterHeaders(upstream.headers)
|
|
71
116
|
});
|
|
72
117
|
}
|
|
73
|
-
async function buildPinnedPathAndBody(request, path, externalCustomerId, client) {
|
|
118
|
+
async function buildPinnedPathAndBody(request, path, externalCustomerId, client, raw) {
|
|
74
119
|
const url = new URL(request.url);
|
|
75
120
|
const query = new URLSearchParams(url.search);
|
|
76
121
|
if (request.method.toUpperCase() === "GET" && path === "/api/v1/subscriptions") {
|
|
@@ -96,7 +141,6 @@ async function buildPinnedPathAndBody(request, path, externalCustomerId, client)
|
|
|
96
141
|
};
|
|
97
142
|
}
|
|
98
143
|
if (request.method.toUpperCase() !== "GET") {
|
|
99
|
-
const raw = await request.text();
|
|
100
144
|
if (path === "/api/v1/subscriptions" && request.method.toUpperCase() === "POST") {
|
|
101
145
|
const customer = await client.getCustomerByExternalId(externalCustomerId);
|
|
102
146
|
if (!customer) return jsonError(404, "not_found", "Customer not found");
|
|
@@ -151,6 +195,14 @@ function withQuery(path, query) {
|
|
|
151
195
|
const qs = query.toString();
|
|
152
196
|
return qs ? `${path}?${qs}` : path;
|
|
153
197
|
}
|
|
198
|
+
function mutationAction(path, method) {
|
|
199
|
+
const suffix = /^\/api\/v1\/subscriptions\/[\w.-]+\/([\w-]+)$/.exec(path)?.[1];
|
|
200
|
+
if (suffix) return suffix;
|
|
201
|
+
return method === "PATCH" ? "update" : "unknown";
|
|
202
|
+
}
|
|
203
|
+
function isShippingAddressOnly(path, method, body) {
|
|
204
|
+
return mutationAction(path, method) === "update" && Object.keys(body).length > 0 && Object.keys(body).every((key) => key === "shippingAddress");
|
|
205
|
+
}
|
|
154
206
|
function isSubscriptionMutation(path, method) {
|
|
155
207
|
if (path === "/api/v1/subscriptions/eligibility-check") return false;
|
|
156
208
|
return method !== "GET" && /^\/api\/v1\/subscriptions\/[\w.-]+/.test(path);
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { SubscriptionsClient, createSubscriptionsClient } from './client';\nimport { ThrottleSubscriptionsError } from './errors';\nimport type { Subscription, SubscriptionsClientOptions } from './types';\n\nexport { SubscriptionsClient, createSubscriptionsClient, ThrottleSubscriptionsError };\nexport type {\n CheckoutSession,\n CreateCheckoutSessionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n Subscription,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n TrialEligibilityInput,\n TrialEligibilityResult,\n} from './types';\n\nexport interface SubscriptionProxyOptions {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n getExternalCustomerId: (request: Request) => string | null | Promise<string | null>;\n /** When supplied it replaces the default installment rule; ownership is always checked. */\n authorizeMutation?: (args: {\n request: Request;\n subscription: Subscription;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n}\n\nexport interface SubscriptionProxyContext {\n params?: {\n path?: string[] | Promise<string[]>;\n };\n path?: string[] | string;\n}\n\nconst ALLOWED_PATHS = [\n /^\\/api\\/v1\\/subscriptions(?:\\/[\\w.-]+)?(?:\\/(?:pause|resume|cancel|payment-method))?$/,\n /^\\/api\\/v1\\/subscriptions\\/eligibility-check$/,\n /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/,\n /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/,\n /^\\/api\\/v1\\/checkout\\/sessions$/,\n];\n\nexport function createSubscriptionProxyHandler(options: SubscriptionProxyOptions) {\n return async function subscriptionProxyHandler(\n request: Request,\n context: SubscriptionProxyContext = {},\n ): Promise<Response> {\n const path = await pathFromContext(context);\n return handleSubscriptionProxyRequest(request, path, options);\n };\n}\n\nexport async function handleSubscriptionProxyRequest(\n request: Request,\n pathParts: string[] | string,\n options: SubscriptionProxyOptions,\n): Promise<Response> {\n const externalCustomerId = await options.getExternalCustomerId(request);\n if (!externalCustomerId) return jsonError(401, 'unauthorized', 'Unauthorized');\n\n const path = normalizePath(pathParts);\n if (!ALLOWED_PATHS.some((pattern) => pattern.test(path))) {\n return jsonError(403, 'forbidden', 'Path is not allowed by the subscription proxy');\n }\n\n const method = request.method.toUpperCase();\n if (!['GET', 'POST', 'PATCH'].includes(method)) {\n return jsonError(405, 'method_not_allowed', 'Method not allowed');\n }\n\n const client = new SubscriptionsClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n } satisfies SubscriptionsClientOptions);\n\n if (isSubscriptionMutation(path, method)) {\n const subId = subscriptionIdFromPath(path);\n if (subId) {\n const subscription = await client.get(subId).catch((err) => {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n });\n if (!subscription) return jsonError(404, 'not_found', 'Subscription not found');\n\n const owned = await defaultMutationAuthorization(client, subscription, externalCustomerId);\n if (!owned) return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n if (options.authorizeMutation) {\n if (!(await options.authorizeMutation({ request, subscription, externalCustomerId }))) {\n return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n }\n } else if (subscription.totalPayments != null && !isPaymentMethodPath(path)) {\n // Same rule as the storefront buyer API (D33/D36): installment plans are merchant-only.\n // Changing the card is not one of the locked terms, so it stays allowed (F-2).\n return jsonError(\n 403,\n 'installment_plan_merchant_only',\n 'Installment plans can only be paused, resumed or cancelled by the merchant',\n );\n }\n }\n }\n\n const targetPath = await buildPinnedPathAndBody(request, path, externalCustomerId, client);\n if (targetPath instanceof Response) return targetPath;\n const upstream = await fetchWithApiKey(request, targetPath.path, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n body: targetPath.body,\n });\n\n return new Response(upstream.body, {\n status: upstream.status,\n headers: filterHeaders(upstream.headers),\n });\n}\n\nasync function buildPinnedPathAndBody(\n request: Request,\n path: string,\n externalCustomerId: string,\n client: SubscriptionsClient,\n): Promise<{ path: string; body?: string } | Response> {\n const url = new URL(request.url);\n const query = new URLSearchParams(url.search);\n\n if (request.method.toUpperCase() === 'GET' && path === '/api/v1/subscriptions') {\n query.set('externalCustomerId', externalCustomerId);\n query.delete('customerId');\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerByExternalPath(path)) {\n return {\n path: withQuery(\n `/api/v1/customers/by-external/${encodeURIComponent(externalCustomerId)}`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerPaymentMethodsPath(path)) {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n return {\n path: withQuery(\n `/api/v1/customers/${encodeURIComponent(customer.id)}/payment-methods`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() !== 'GET') {\n const raw = await request.text();\n if (path === '/api/v1/subscriptions' && request.method.toUpperCase() === 'POST') {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n\n const body = raw ? (JSON.parse(raw) as Record<string, any>) : {};\n body.customerId = customer.id;\n delete body.externalCustomerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n\n if (path === '/api/v1/checkout/sessions' && raw) {\n const body = JSON.parse(raw) as Record<string, any>;\n body.customer = {\n ...(body.customer ?? {}),\n externalCustomerId,\n };\n delete body.customer.customerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n return { path: withQuery(path, query), body: raw || undefined };\n }\n\n return { path: withQuery(path, query) };\n}\n\nasync function fetchWithApiKey(\n request: Request,\n path: string,\n opts: {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n body?: string;\n },\n) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('fetch is required');\n const baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n return fetchImpl(`${baseUrl}${path}`, {\n method: request.method,\n headers: {\n 'x-api-key': opts.apiKey,\n 'content-type': request.headers.get('content-type') ?? 'application/json',\n },\n body: request.method.toUpperCase() === 'GET' ? undefined : opts.body,\n });\n}\n\nasync function defaultMutationAuthorization(\n client: SubscriptionsClient,\n subscription: Subscription,\n externalCustomerId: string,\n): Promise<boolean> {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n return Boolean(customer?.id && customer.id === subscription.customerId);\n}\n\nasync function pathFromContext(context: SubscriptionProxyContext): Promise<string[] | string> {\n if (context.path) return context.path;\n const path = context.params?.path;\n if (!path) return [];\n return await path;\n}\n\nfunction normalizePath(pathParts: string[] | string): string {\n if (typeof pathParts === 'string') {\n return pathParts.startsWith('/') ? pathParts : `/${pathParts}`;\n }\n return `/${pathParts.map((part) => part.replace(/^\\/+|\\/+$/g, '')).join('/')}`;\n}\n\nfunction withQuery(path: string, query: URLSearchParams): string {\n const qs = query.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\nfunction isSubscriptionMutation(path: string, method: string): boolean {\n if (path === '/api/v1/subscriptions/eligibility-check') return false;\n return method !== 'GET' && /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+/.test(path);\n}\n\nfunction isCustomerByExternalPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/.test(path);\n}\n\nfunction isCustomerPaymentMethodsPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/.test(path);\n}\n\nfunction isPaymentMethodPath(path: string): boolean {\n return /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+\\/payment-method$/.test(path);\n}\n\nfunction subscriptionIdFromPath(path: string): string | null {\n return path.match(/^\\/api\\/v1\\/subscriptions\\/([\\w.-]+)/)?.[1] ?? null;\n}\n\nfunction filterHeaders(headers: Headers): Headers {\n const next = new Headers(headers);\n next.delete('content-encoding');\n next.delete('content-length');\n next.delete('transfer-encoding');\n return next;\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return Response.json({ error: { code, message } }, { status });\n}\n"],"mappings":";;;;;;;AAuCA,IAAM,gBAAgB;AAAA,E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KAAK,MAAM,sCAAsC,IAAI,CAAC,KAAK;AACpE;AAEA,SAAS,cAAc,SAA2B;AAChD,QAAM,OAAO,IAAI,QAAQ,OAAO;AAChC,OAAK,OAAO,kBAAkB;AAC9B,OAAK,OAAO,gBAAgB;AAC5B,OAAK,OAAO,mBAAmB;AAC/B,SAAO;AACT;AAEA,SAAS,UAAU,QAAgB,MAAc,SAA2B;AAC1E,SAAO,SAAS,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;AAC/D;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["import { SubscriptionsClient, createSubscriptionsClient } from './client';\nimport { ThrottleSubscriptionsError } from './errors';\nimport type { Subscription, SubscriptionsClientOptions } from './types';\n\nexport { SubscriptionsClient, createSubscriptionsClient, ThrottleSubscriptionsError };\nexport type {\n CheckoutSession,\n CreateCheckoutSessionInput,\n Customer,\n CustomerPaymentMethod,\n ListSubscriptionsParams,\n PaginatedSubscriptions,\n Subscription,\n SubscriptionsClientContract,\n SubscriptionsClientOptions,\n TrialEligibilityInput,\n TrialEligibilityResult,\n} from './types';\n\nexport interface SubscriptionProxyOptions {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n getExternalCustomerId: (request: Request) => string | null | Promise<string | null>;\n /** When supplied it replaces the default installment rule; ownership is always checked. */\n authorizeMutation?: (args: {\n request: Request;\n subscription: Subscription;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n /**\n * Opt-in: lets a buyer create a subscription directly (`POST\n * /api/v1/subscriptions`). Refused by default (`403 create_not_allowed`):\n * the body names the plan and the price, and nothing is charged, so return\n * true only after checking `body` against your own price list. The\n * customer is always pinned to the authenticated buyer.\n */\n authorizeCreate?: (args: {\n request: Request;\n body: Record<string, unknown>;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n /**\n * Opt-in: lets a buyer `PATCH` fields of their own subscription beyond\n * `shippingAddress` (plan, cadence, amount, ...). Refused by default\n * (`403 field_not_allowed`): those are prices and terms, so return true only\n * after checking `body` against your own price list.\n */\n authorizeUpdate?: (args: {\n request: Request;\n subscription: Subscription;\n body: Record<string, unknown>;\n externalCustomerId: string;\n }) => boolean | Promise<boolean>;\n}\n\n/**\n * What a buyer may send on each mutation without a merchant hook. Anything\n * else is refused, never silently dropped, so a portal learns at once that a\n * field needs the merchant's say (4.0.0). `refund` on cancel is the reason\n * this exists: forwarding it let a buyer refund themselves.\n */\nconst BUYER_BODY_FIELDS: Record<string, readonly string[]> = {\n pause: [],\n resume: [],\n cancel: ['atPeriodEnd'],\n 'payment-method': ['paymentMethodId'],\n update: ['shippingAddress'],\n};\n\nexport interface SubscriptionProxyContext {\n params?: {\n path?: string[] | Promise<string[]>;\n };\n path?: string[] | string;\n}\n\nconst ALLOWED_PATHS = [\n /^\\/api\\/v1\\/subscriptions(?:\\/[\\w.-]+)?(?:\\/(?:pause|resume|cancel|payment-method))?$/,\n /^\\/api\\/v1\\/subscriptions\\/eligibility-check$/,\n /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/,\n /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/,\n /^\\/api\\/v1\\/checkout\\/sessions$/,\n];\n\nexport function createSubscriptionProxyHandler(options: SubscriptionProxyOptions) {\n return async function subscriptionProxyHandler(\n request: Request,\n context: SubscriptionProxyContext = {},\n ): Promise<Response> {\n const path = await pathFromContext(context);\n return handleSubscriptionProxyRequest(request, path, options);\n };\n}\n\nexport async function handleSubscriptionProxyRequest(\n request: Request,\n pathParts: string[] | string,\n options: SubscriptionProxyOptions,\n): Promise<Response> {\n const externalCustomerId = await options.getExternalCustomerId(request);\n if (!externalCustomerId) return jsonError(401, 'unauthorized', 'Unauthorized');\n\n const path = normalizePath(pathParts);\n if (!ALLOWED_PATHS.some((pattern) => pattern.test(path))) {\n return jsonError(403, 'forbidden', 'Path is not allowed by the subscription proxy');\n }\n\n const method = request.method.toUpperCase();\n if (!['GET', 'POST', 'PATCH'].includes(method)) {\n return jsonError(405, 'method_not_allowed', 'Method not allowed');\n }\n\n const client = new SubscriptionsClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n } satisfies SubscriptionsClientOptions);\n\n // Read once: every body rule below and the forwarded request share it.\n const raw = method === 'GET' ? '' : await request.text();\n let body: Record<string, unknown> = {};\n if (raw) {\n try {\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object');\n body = parsed as Record<string, unknown>;\n } catch {\n return jsonError(400, 'invalid_body', 'The request body must be a JSON object');\n }\n }\n\n // A direct create names its own plan and price and charges nothing.\n if (method === 'POST' && path === '/api/v1/subscriptions') {\n const allowed = options.authorizeCreate\n ? await options.authorizeCreate({ request, body, externalCustomerId })\n : false;\n if (!allowed) {\n return jsonError(403, 'create_not_allowed', 'Creating a subscription from the buyer portal is not allowed');\n }\n }\n\n // A read of one subscription is the buyer's own or nothing: 404 either way,\n // so an id that exists for someone else looks the same as one that does not.\n if (method === 'GET' && subscriptionIdFromPath(path) && path !== '/api/v1/subscriptions/eligibility-check') {\n const subscription = await client.get(subscriptionIdFromPath(path)!).catch((err) => {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n });\n if (!subscription || !(await defaultMutationAuthorization(client, subscription, externalCustomerId))) {\n return jsonError(404, 'not_found', 'Subscription not found');\n }\n }\n\n if (isSubscriptionMutation(path, method)) {\n const subId = subscriptionIdFromPath(path);\n if (subId) {\n const subscription = await client.get(subId).catch((err) => {\n if (err instanceof ThrottleSubscriptionsError && err.statusCode === 404) return null;\n throw err;\n });\n if (!subscription) return jsonError(404, 'not_found', 'Subscription not found');\n\n const owned = await defaultMutationAuthorization(client, subscription, externalCustomerId);\n if (!owned) return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n if (options.authorizeMutation) {\n if (!(await options.authorizeMutation({ request, subscription, externalCustomerId }))) {\n return jsonError(403, 'forbidden', 'Subscription does not belong to this buyer');\n }\n } else if (subscription.totalPayments != null && !isPaymentMethodPath(path) && !isShippingAddressOnly(path, method, body)) {\n // Same rule as the storefront buyer API (D33/D36): installment plans are merchant-only.\n // Changing the card is not one of the locked terms, so it stays allowed (F-2).\n return jsonError(\n 403,\n 'installment_plan_merchant_only',\n 'Installment plans can only be paused, resumed or cancelled by the merchant',\n );\n }\n\n const action = mutationAction(path, method);\n const extra = Object.keys(body).filter((key) => !(BUYER_BODY_FIELDS[action] ?? []).includes(key));\n if (extra.length > 0) {\n const merchantSays =\n action === 'update' && options.authorizeUpdate\n ? await options.authorizeUpdate({ request, subscription, body, externalCustomerId })\n : false;\n if (!merchantSays) {\n return jsonError(\n 403,\n 'field_not_allowed',\n `The buyer portal cannot change ${extra.join(', ')} on a subscription`,\n );\n }\n }\n }\n }\n\n const targetPath = await buildPinnedPathAndBody(request, path, externalCustomerId, client, raw);\n if (targetPath instanceof Response) return targetPath;\n const upstream = await fetchWithApiKey(request, targetPath.path, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n body: targetPath.body,\n });\n\n return new Response(upstream.body, {\n status: upstream.status,\n headers: filterHeaders(upstream.headers),\n });\n}\n\nasync function buildPinnedPathAndBody(\n request: Request,\n path: string,\n externalCustomerId: string,\n client: SubscriptionsClient,\n raw: string,\n): Promise<{ path: string; body?: string } | Response> {\n const url = new URL(request.url);\n const query = new URLSearchParams(url.search);\n\n if (request.method.toUpperCase() === 'GET' && path === '/api/v1/subscriptions') {\n query.set('externalCustomerId', externalCustomerId);\n query.delete('customerId');\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerByExternalPath(path)) {\n return {\n path: withQuery(\n `/api/v1/customers/by-external/${encodeURIComponent(externalCustomerId)}`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() === 'GET' && isCustomerPaymentMethodsPath(path)) {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n return {\n path: withQuery(\n `/api/v1/customers/${encodeURIComponent(customer.id)}/payment-methods`,\n query,\n ),\n };\n }\n\n if (request.method.toUpperCase() !== 'GET') {\n if (path === '/api/v1/subscriptions' && request.method.toUpperCase() === 'POST') {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n if (!customer) return jsonError(404, 'not_found', 'Customer not found');\n\n const body = raw ? (JSON.parse(raw) as Record<string, any>) : {};\n body.customerId = customer.id;\n delete body.externalCustomerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n\n if (path === '/api/v1/checkout/sessions' && raw) {\n const body = JSON.parse(raw) as Record<string, any>;\n body.customer = {\n ...(body.customer ?? {}),\n externalCustomerId,\n };\n delete body.customer.customerId;\n return { path: withQuery(path, query), body: JSON.stringify(body) };\n }\n return { path: withQuery(path, query), body: raw || undefined };\n }\n\n return { path: withQuery(path, query) };\n}\n\nasync function fetchWithApiKey(\n request: Request,\n path: string,\n opts: {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n body?: string;\n },\n) {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new Error('fetch is required');\n const baseUrl = (opts.baseUrl ?? 'https://api.usethrottle.dev').replace(/\\/+$/, '');\n return fetchImpl(`${baseUrl}${path}`, {\n method: request.method,\n headers: {\n 'x-api-key': opts.apiKey,\n 'content-type': request.headers.get('content-type') ?? 'application/json',\n },\n body: request.method.toUpperCase() === 'GET' ? undefined : opts.body,\n });\n}\n\nasync function defaultMutationAuthorization(\n client: SubscriptionsClient,\n subscription: Subscription,\n externalCustomerId: string,\n): Promise<boolean> {\n const customer = await client.getCustomerByExternalId(externalCustomerId);\n return Boolean(customer?.id && customer.id === subscription.customerId);\n}\n\nasync function pathFromContext(context: SubscriptionProxyContext): Promise<string[] | string> {\n if (context.path) return context.path;\n const path = context.params?.path;\n if (!path) return [];\n return await path;\n}\n\nfunction normalizePath(pathParts: string[] | string): string {\n if (typeof pathParts === 'string') {\n return pathParts.startsWith('/') ? pathParts : `/${pathParts}`;\n }\n return `/${pathParts.map((part) => part.replace(/^\\/+|\\/+$/g, '')).join('/')}`;\n}\n\nfunction withQuery(path: string, query: URLSearchParams): string {\n const qs = query.toString();\n return qs ? `${path}?${qs}` : path;\n}\n\n/** Which BUYER_BODY_FIELDS rule a subscription mutation falls under. */\nfunction mutationAction(path: string, method: string): string {\n const suffix = /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+\\/([\\w-]+)$/.exec(path)?.[1];\n if (suffix) return suffix;\n return method === 'PATCH' ? 'update' : 'unknown';\n}\n\n/** A PATCH that only moves a physical subscription's box: allowed on an installment plan. */\nfunction isShippingAddressOnly(path: string, method: string, body: Record<string, unknown>): boolean {\n return mutationAction(path, method) === 'update' && Object.keys(body).length > 0 &&\n Object.keys(body).every((key) => key === 'shippingAddress');\n}\n\nfunction isSubscriptionMutation(path: string, method: string): boolean {\n if (path === '/api/v1/subscriptions/eligibility-check') return false;\n return method !== 'GET' && /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+/.test(path);\n}\n\nfunction isCustomerByExternalPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/by-external\\/[\\w.:%-]+$/.test(path);\n}\n\nfunction isCustomerPaymentMethodsPath(path: string): boolean {\n return /^\\/api\\/v1\\/customers\\/[\\w.-]+\\/payment-methods$/.test(path);\n}\n\nfunction isPaymentMethodPath(path: string): boolean {\n return /^\\/api\\/v1\\/subscriptions\\/[\\w.-]+\\/payment-method$/.test(path);\n}\n\nfunction subscriptionIdFromPath(path: string): string | null {\n return path.match(/^\\/api\\/v1\\/subscriptions\\/([\\w.-]+)/)?.[1] ?? null;\n}\n\nfunction filterHeaders(headers: Headers): Headers {\n const next = new Headers(headers);\n next.delete('content-encoding');\n next.delete('content-length');\n next.delete('transfer-encoding');\n return next;\n}\n\nfunction jsonError(status: number, code: string, message: string): Response {\n return Response.json({ error: { code, message } }, { status });\n}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AAe,MAAc,QAAwB;AAC5D,QAAM,SAAS,gDAAgD,KAAK,IAAI,IAAI,CAAC;AAC7E,MAAI,OAAQ,QAAO;AACnB,SAAO,WAAW,UAAU,WAAW;AACzC;AAGA,SAAS,sBAAsB,MAAc,QAAgB,MAAwC;AACnG,SAAO,eAAe,MAAM,MAAM,MAAM,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,KAC7E,OAAO,KAAK,IAAI,EAAE,MAAM,CAAC,QAAQ,QAAQ,iBAAiB;AAC9D;AAEA,SAAS,uBAAuB,MAAc,QAAyB;AACrE,MAAI,SAAS,0CAA2C,QAAO;AAC/D,SAAO,WAAW,SAAS,qCAAqC,KAAK,IAAI;AAC3E;AAEA,SAAS,yBAAyB,MAAuB;AACvD,SAAO,iDAAiD,KAAK,IAAI;AACnE;AAEA,SAAS,6BAA6B,MAAuB;AAC3D,SAAO,mDAAmD,KAAK,IAAI;AACrE;AAEA,SAAS,oBAAoB,MAAuB;AAClD,SAAO,sDAAsD,KAAK,IAAI;AACxE;AAEA,SAAS,uBAAuB,MAA6B;AAC3D,SAAO,KAAK,MAAM,sCAAsC,IAAI,CAAC,KAAK;AACpE;AAEA,SAAS,cAAc,SAA2B;AAChD,QAAM,OAAO,IAAI,QAAQ,OAAO;AAChC,OAAK,OAAO,kBAAkB;AAC9B,OAAK,OAAO,gBAAgB;AAC5B,OAAK,OAAO,mBAAmB;AAC/B,SAAO;AACT;AAEA,SAAS,UAAU,QAAgB,MAAc,SAA2B;AAC1E,SAAO,SAAS,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;AAC/D;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usethrottle/subscriptions",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"description": "React hooks, server proxy helpers, and primitive components for Throttle subscriptions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"CLAUDE.md"
|
|
25
25
|
],
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@usethrottle/errors": "^1.1.0"
|
|
27
|
+
"@usethrottle/errors": "^1.1.0",
|
|
28
|
+
"@usethrottle/money": "^1.0.0"
|
|
28
29
|
},
|
|
29
30
|
"peerDependencies": {
|
|
30
31
|
"react": ">=18"
|