import type { Subscription } from '../base.js'; import { products } from '../plans.js'; const planCatalogs = ['builder', 'cli', 'legacy'] as const; const stages = ['dev', 'prod'] as const; const productCatalogLabels = { builder: 'Builder', cli: 'CLI', legacy: 'Legacy', } as const; export interface SubscriptionProductMatch { catalog: (typeof planCatalogs)[number]; key: string; label: string; priceKey?: string; stage: (typeof stages)[number]; } export function resolveSubscriptionProduct( subscription?: Pick, ): null | SubscriptionProductMatch { if (!subscription) { return null; } for (const stage of stages) { for (const catalog of planCatalogs) { const catalogProducts = products[stage][catalog]; for (const [key, product] of Object.entries(catalogProducts)) { const priceEntries = Object.entries(product.prices) as Array< [string, { id: string }] >; if (subscription.productId && subscription.productId === product.id) { return { catalog, key, label: `${productCatalogLabels[catalog]} ${humanizeProductKey(key)}`, stage, }; } const matchingPriceEntries = priceEntries.filter( ([, price]) => price.id === subscription.planId, ); if (matchingPriceEntries.length > 0) { return { catalog, key, label: `${productCatalogLabels[catalog]} ${humanizeProductKey(key)}`, priceKey: matchingPriceEntries.length === 1 ? matchingPriceEntries[0][0] : undefined, stage, }; } } } } return null; } function humanizeProductKey(value: string): string { return value .replace(/([a-z0-9])([A-Z])/g, '$1 $2') .replace(/_/g, ' ') .replace(/\b\w/g, (char) => char.toUpperCase()); }