@metamask-previews/subscription-controller 0.0.0-preview-1f079244 → 0.0.0-preview-c896a02b

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.
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionController.mjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EAKf,kCAAkC;AAGnC,OAAO,EACL,cAAc,EACd,kCAAkC,EACnC,wBAAoB;AAUrB,OAAO,EACL,WAAW,EACX,kBAAkB,EAMnB,oBAAgB;AA4FjB;;;;GAIG;AACH,MAAM,UAAU,qCAAqC;IACnD,OAAO;QACL,aAAa,EAAE,EAAE;KAClB,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,8BAA8B,GAClC;IACE,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEJ,MAAM,OAAO,sBAAuB,SAAQ,cAI3C;IAGC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,KAAK,EACL,mBAAmB,GACW;QAC9B,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,8BAA8B;YACxC,KAAK,EAAE;gBACL,GAAG,qCAAqC,EAAE;gBAC1C,GAAG,KAAK;aACT;YACD,SAAS;SACV,CAAC,CAAC;;QAvBI,8DAA2C;QAyBlD,uBAAA,IAAI,+CAAwB,mBAAmB,MAAA,CAAC;QAChD,uBAAA,IAAI,0FAAyB,MAA7B,IAAI,CAA2B,CAAC;IAClC,CAAC;IA2CD;;;;OAIG;IACH,KAAK,CAAC,UAAU;Q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,WAAW,CAAC;AACrB,CAAC,iHAE0B,EAAE,QAAQ,EAA+B;IAClE,IACE,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAC7C,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,CAAC;KAC3E;AACH,CAAC,2GAYuB,OAAmC;IACzD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAC5B,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,KAAK,OAAO,CAAC,cAAc,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,CAAC;KACvE;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type StateMetadata,\n type ControllerStateChangeEvent,\n type ControllerGetStateAction,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport {\n controllerName,\n SubscriptionControllerErrorMessage,\n} from './constants';\nimport type {\n BillingPortalResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodOpts,\n} from './types';\nimport {\n PaymentType,\n SubscriptionStatus,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n subscriptions: Subscription[];\n pricing?: PricingResponse;\n};\n\n// Messenger Actions\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `${typeof controllerName}:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `${typeof controllerName}:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\nexport type SubscriptionControllerStartShieldSubscriptionWithCardAction = {\n type: `${typeof controllerName}:startShieldSubscriptionWithCard`;\n handler: SubscriptionController['startShieldSubscriptionWithCard'];\n};\nexport type SubscriptionControllerGetPricingAction = {\n type: `${typeof controllerName}:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `${typeof controllerName}:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `${typeof controllerName}:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\nexport type SubscriptionControllerUpdatePaymentMethodAction = {\n type: `${typeof controllerName}:updatePaymentMethod`;\n handler: SubscriptionController['updatePaymentMethod'];\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerStartShieldSubscriptionWithCardAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction\n | SubscriptionControllerUpdatePaymentMethodAction;\n\nexport type AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerPerformSignOut;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n AuthenticationController.AuthenticationControllerStateChangeEvent;\n\n// Messenger\nexport type SubscriptionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Subscription service to use for the subscription controller.\n */\n subscriptionService: ISubscriptionService;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n pricing: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n };\n\nexport class SubscriptionController extends BaseController<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n readonly #subscriptionService: ISubscriptionService;\n\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.subscriptionService - The subscription service for communicating with subscription server.\n */\n constructor({\n messenger,\n state,\n subscriptionService,\n }: SubscriptionControllerOptions) {\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.#subscriptionService = subscriptionService;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getSubscriptions',\n this.getSubscriptions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:cancelSubscription',\n this.cancelSubscription.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startShieldSubscriptionWithCard',\n this.startShieldSubscriptionWithCard.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getPricing',\n this.getPricing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getCryptoApproveTransactionParams',\n this.getCryptoApproveTransactionParams.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startSubscriptionWithCrypto',\n this.startSubscriptionWithCrypto.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:updatePaymentMethod',\n this.updatePaymentMethod.bind(this),\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n const pricing = await this.#subscriptionService.getPricing();\n this.update((state) => {\n state.pricing = pricing;\n });\n return pricing;\n }\n\n async getSubscriptions() {\n const { subscriptions } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n await this.#subscriptionService.cancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, status: SubscriptionStatus.canceled }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(request: StartSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response =\n await this.#subscriptionService.startSubscriptionWithCard(request);\n\n this.triggerAccessTokenRefresh();\n\n return response;\n }\n\n async startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n const response =\n await this.#subscriptionService.startSubscriptionWithCrypto(request);\n this.triggerAccessTokenRefresh();\n return response;\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n async getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): Promise<GetCryptoApproveTransactionResponse> {\n const pricing = await this.getPricing();\n const product = pricing.products.find(\n (p) => p.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find((p) => p.interval === request.interval);\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = pricing.paymentMethods.find(\n (t) => t.type === PaymentType.byCrypto,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (t) => t.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (t) => t.address === request.paymentTokenAddress,\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.#getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount.toString(),\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(opts: UpdatePaymentMethodOpts) {\n if (opts.paymentType === PaymentType.byCard) {\n const { paymentType, ...cardRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCard(cardRequest);\n } else if (opts.paymentType === PaymentType.byCrypto) {\n const { paymentType, ...cryptoRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCrypto(cryptoRequest);\n } else {\n throw new Error('Invalid payment type');\n }\n await this.getSubscriptions();\n }\n\n /**\n * Calculate total subscription price amount from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice) {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount =\n (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n #getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ) {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // conversion rate is a float string e.g: \"1.0\"\n // We need to handle float conversion rates with integer math for BigInt.\n // We'll scale the conversion rate to an integer by multiplying by 10^4.\n // conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)\n // So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)\n // This allows us to avoid floating point math and keep precision.\n const SCALE = 10n ** 4n;\n const conversionRateScaled =\n BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;\n // price of the product\n const priceAmount = this.#getSubscriptionPriceAmount(price);\n const priceAmountScaled =\n BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;\n\n const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);\n\n const tokenAmount =\n (priceAmountScaled * tokenDecimal) / conversionRateScaled;\n return tokenAmount;\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }) {\n if (\n this.state.subscriptions.find((subscription) =>\n subscription.products.some((p) => products.includes(p.name)),\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh() {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }) {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n\n /**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n return await this.#subscriptionService.getBillingPortalUrl();\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionController.mjs","sourceRoot":"","sources":["../src/SubscriptionController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EAKf,kCAAkC;AAGnC,OAAO,EACL,cAAc,EACd,kCAAkC,EACnC,wBAAoB;AAUrB,OAAO,EACL,aAAa,EAMd,oBAAgB;AA8FjB;;;;GAIG;AACH,MAAM,UAAU,qCAAqC;IACnD,OAAO;QACL,aAAa,EAAE,EAAE;QACjB,eAAe,EAAE,EAAE;KACpB,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,8BAA8B,GAClC;IACE,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEJ,MAAM,OAAO,s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yC0B,EAAE,QAAQ,EAA+B;IAClE,IACE,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE,CAC7C,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,CAAC;KAC3E;AACH,CAAC,2GAYuB,OAAmC;IACzD,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAC5B,CAAC,YAAY,EAAE,EAAE,CAAC,YAAY,CAAC,EAAE,KAAK,OAAO,CAAC,cAAc,CAC7D,EACD;QACA,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,CAAC;KACvE;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type StateMetadata,\n type ControllerStateChangeEvent,\n type ControllerGetStateAction,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\n\nimport {\n controllerName,\n SubscriptionControllerErrorMessage,\n} from './constants';\nimport type {\n BillingPortalResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n ProductPrice,\n StartCryptoSubscriptionRequest,\n TokenPaymentInfo,\n UpdatePaymentMethodOpts,\n} from './types';\nimport {\n PAYMENT_TYPES,\n type ISubscriptionService,\n type PricingResponse,\n type ProductType,\n type StartSubscriptionRequest,\n type Subscription,\n} from './types';\n\nexport type SubscriptionControllerState = {\n customerId?: string;\n trialedProducts: ProductType[];\n subscriptions: Subscription[];\n pricing?: PricingResponse;\n};\n\n// Messenger Actions\nexport type SubscriptionControllerGetSubscriptionsAction = {\n type: `${typeof controllerName}:getSubscriptions`;\n handler: SubscriptionController['getSubscriptions'];\n};\nexport type SubscriptionControllerCancelSubscriptionAction = {\n type: `${typeof controllerName}:cancelSubscription`;\n handler: SubscriptionController['cancelSubscription'];\n};\nexport type SubscriptionControllerStartShieldSubscriptionWithCardAction = {\n type: `${typeof controllerName}:startShieldSubscriptionWithCard`;\n handler: SubscriptionController['startShieldSubscriptionWithCard'];\n};\nexport type SubscriptionControllerGetPricingAction = {\n type: `${typeof controllerName}:getPricing`;\n handler: SubscriptionController['getPricing'];\n};\nexport type SubscriptionControllerGetCryptoApproveTransactionParamsAction = {\n type: `${typeof controllerName}:getCryptoApproveTransactionParams`;\n handler: SubscriptionController['getCryptoApproveTransactionParams'];\n};\nexport type SubscriptionControllerStartSubscriptionWithCryptoAction = {\n type: `${typeof controllerName}:startSubscriptionWithCrypto`;\n handler: SubscriptionController['startSubscriptionWithCrypto'];\n};\nexport type SubscriptionControllerUpdatePaymentMethodAction = {\n type: `${typeof controllerName}:updatePaymentMethod`;\n handler: SubscriptionController['updatePaymentMethod'];\n};\n\nexport type SubscriptionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerActions =\n | SubscriptionControllerGetSubscriptionsAction\n | SubscriptionControllerCancelSubscriptionAction\n | SubscriptionControllerStartShieldSubscriptionWithCardAction\n | SubscriptionControllerGetPricingAction\n | SubscriptionControllerGetStateAction\n | SubscriptionControllerGetCryptoApproveTransactionParamsAction\n | SubscriptionControllerStartSubscriptionWithCryptoAction\n | SubscriptionControllerUpdatePaymentMethodAction;\n\nexport type AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerToken\n | AuthenticationController.AuthenticationControllerPerformSignOut;\n\n// Events\nexport type SubscriptionControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SubscriptionControllerState\n>;\nexport type SubscriptionControllerEvents =\n SubscriptionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n AuthenticationController.AuthenticationControllerStateChangeEvent;\n\n// Messenger\nexport type SubscriptionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SubscriptionControllerActions | AllowedActions,\n SubscriptionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Subscription Controller Options.\n */\nexport type SubscriptionControllerOptions = {\n messenger: SubscriptionControllerMessenger;\n\n /**\n * Initial state to set on this controller.\n */\n state?: Partial<SubscriptionControllerState>;\n\n /**\n * Subscription service to use for the subscription controller.\n */\n subscriptionService: ISubscriptionService;\n};\n\n/**\n * Get the default state for the Subscription Controller.\n *\n * @returns The default state for the Subscription Controller.\n */\nexport function getDefaultSubscriptionControllerState(): SubscriptionControllerState {\n return {\n subscriptions: [],\n trialedProducts: [],\n };\n}\n\n/**\n * Seedless Onboarding Controller State Metadata.\n *\n * This allows us to choose if fields of the state should be persisted or not\n * using the `persist` flag; and if they can be sent to Sentry or not, using\n * the `anonymous` flag.\n */\nconst subscriptionControllerMetadata: StateMetadata<SubscriptionControllerState> =\n {\n subscriptions: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n customerId: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n trialedProducts: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n pricing: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n };\n\nexport class SubscriptionController extends BaseController<\n typeof controllerName,\n SubscriptionControllerState,\n SubscriptionControllerMessenger\n> {\n readonly #subscriptionService: ISubscriptionService;\n\n /**\n * Creates a new SubscriptionController instance.\n *\n * @param options - The options for the SubscriptionController.\n * @param options.messenger - A restricted messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.subscriptionService - The subscription service for communicating with subscription server.\n */\n constructor({\n messenger,\n state,\n subscriptionService,\n }: SubscriptionControllerOptions) {\n super({\n name: controllerName,\n metadata: subscriptionControllerMetadata,\n state: {\n ...getDefaultSubscriptionControllerState(),\n ...state,\n },\n messenger,\n });\n\n this.#subscriptionService = subscriptionService;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getSubscriptions',\n this.getSubscriptions.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:cancelSubscription',\n this.cancelSubscription.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startShieldSubscriptionWithCard',\n this.startShieldSubscriptionWithCard.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getPricing',\n this.getPricing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:getCryptoApproveTransactionParams',\n this.getCryptoApproveTransactionParams.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:startSubscriptionWithCrypto',\n this.startSubscriptionWithCrypto.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'SubscriptionController:updatePaymentMethod',\n this.updatePaymentMethod.bind(this),\n );\n }\n\n /**\n * Gets the pricing information from the subscription service.\n *\n * @returns The pricing information.\n */\n async getPricing(): Promise<PricingResponse> {\n const pricing = await this.#subscriptionService.getPricing();\n this.update((state) => {\n state.pricing = pricing;\n });\n return pricing;\n }\n\n async getSubscriptions() {\n const { subscriptions, customerId, trialedProducts } =\n await this.#subscriptionService.getSubscriptions();\n\n this.update((state) => {\n state.subscriptions = subscriptions;\n state.customerId = customerId;\n state.trialedProducts = trialedProducts;\n });\n\n return subscriptions;\n }\n\n async cancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const cancelledSubscription =\n await this.#subscriptionService.cancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...cancelledSubscription }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async unCancelSubscription(request: { subscriptionId: string }) {\n this.#assertIsUserSubscribed({ subscriptionId: request.subscriptionId });\n\n const uncancelledSubscription =\n await this.#subscriptionService.unCancelSubscription({\n subscriptionId: request.subscriptionId,\n });\n\n this.update((state) => {\n state.subscriptions = state.subscriptions.map((subscription) =>\n subscription.id === request.subscriptionId\n ? { ...subscription, ...uncancelledSubscription }\n : subscription,\n );\n });\n\n this.triggerAccessTokenRefresh();\n }\n\n async startShieldSubscriptionWithCard(request: StartSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n\n const response =\n await this.#subscriptionService.startSubscriptionWithCard(request);\n\n this.triggerAccessTokenRefresh();\n\n return response;\n }\n\n async startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest) {\n this.#assertIsUserNotSubscribed({ products: request.products });\n const response =\n await this.#subscriptionService.startSubscriptionWithCrypto(request);\n this.triggerAccessTokenRefresh();\n return response;\n }\n\n /**\n * Get transaction params to create crypto approve transaction for subscription payment\n *\n * @param request - The request object\n * @param request.chainId - The chain ID\n * @param request.tokenAddress - The address of the token\n * @param request.productType - The product type\n * @param request.interval - The interval\n * @returns The crypto approve transaction params\n */\n async getCryptoApproveTransactionParams(\n request: GetCryptoApproveTransactionRequest,\n ): Promise<GetCryptoApproveTransactionResponse> {\n const pricing = await this.getPricing();\n const product = pricing.products.find(\n (p) => p.name === request.productType,\n );\n if (!product) {\n throw new Error('Product price not found');\n }\n\n const price = product.prices.find((p) => p.interval === request.interval);\n if (!price) {\n throw new Error('Price not found');\n }\n\n const chainsPaymentInfo = pricing.paymentMethods.find(\n (t) => t.type === PAYMENT_TYPES.byCrypto,\n );\n if (!chainsPaymentInfo) {\n throw new Error('Chains payment info not found');\n }\n const chainPaymentInfo = chainsPaymentInfo.chains?.find(\n (t) => t.chainId === request.chainId,\n );\n if (!chainPaymentInfo) {\n throw new Error('Invalid chain id');\n }\n const tokenPaymentInfo = chainPaymentInfo.tokens.find(\n (t) => t.address === request.paymentTokenAddress,\n );\n if (!tokenPaymentInfo) {\n throw new Error('Invalid token address');\n }\n\n const tokenApproveAmount = this.getTokenApproveAmount(\n price,\n tokenPaymentInfo,\n );\n\n return {\n approveAmount: tokenApproveAmount,\n paymentAddress: chainPaymentInfo.paymentAddress,\n paymentTokenAddress: request.paymentTokenAddress,\n chainId: request.chainId,\n };\n }\n\n async updatePaymentMethod(opts: UpdatePaymentMethodOpts) {\n if (opts.paymentType === PAYMENT_TYPES.byCard) {\n const { paymentType, ...cardRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCard(cardRequest);\n } else if (opts.paymentType === PAYMENT_TYPES.byCrypto) {\n const { paymentType, ...cryptoRequest } = opts;\n await this.#subscriptionService.updatePaymentMethodCrypto(cryptoRequest);\n } else {\n throw new Error('Invalid payment type');\n }\n await this.getSubscriptions();\n }\n\n /**\n * Calculate total subscription price amount from price info\n * e.g: $8 per month * 12 months min billing cycles = $96\n *\n * @param price - The price info\n * @returns The price amount\n */\n #getSubscriptionPriceAmount(price: ProductPrice) {\n // no need to use BigInt since max unitDecimals are always 2 for price\n const amount =\n (price.unitAmount / 10 ** price.unitDecimals) * price.minBillingCycles;\n return amount;\n }\n\n /**\n * Calculate token approve amount from price info\n *\n * @param price - The price info\n * @param tokenPaymentInfo - The token price info\n * @returns The token approve amount\n */\n getTokenApproveAmount(\n price: ProductPrice,\n tokenPaymentInfo: TokenPaymentInfo,\n ): string {\n const conversionRate =\n tokenPaymentInfo.conversionRate[\n price.currency as keyof typeof tokenPaymentInfo.conversionRate\n ];\n if (!conversionRate) {\n throw new Error('Conversion rate not found');\n }\n // conversion rate is a float string e.g: \"1.0\"\n // We need to handle float conversion rates with integer math for BigInt.\n // We'll scale the conversion rate to an integer by multiplying by 10^4.\n // conversionRate is in usd decimal. In most currencies, we only care about 2 decimals (cents)\n // So, scale must be max of 10 ** 4 (most exchanges trade with max 4 decimals of usd)\n // This allows us to avoid floating point math and keep precision.\n const SCALE = 10n ** 4n;\n const conversionRateScaled =\n BigInt(Math.round(Number(conversionRate) * Number(SCALE))) / SCALE;\n // price of the product\n const priceAmount = this.#getSubscriptionPriceAmount(price);\n const priceAmountScaled =\n BigInt(Math.round(priceAmount * Number(SCALE))) / SCALE;\n\n const tokenDecimal = BigInt(10) ** BigInt(tokenPaymentInfo.decimals);\n\n const tokenAmount =\n (priceAmountScaled * tokenDecimal) / conversionRateScaled;\n return tokenAmount.toString();\n }\n\n #assertIsUserNotSubscribed({ products }: { products: ProductType[] }) {\n if (\n this.state.subscriptions.find((subscription) =>\n subscription.products.some((p) => products.includes(p.name)),\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserAlreadySubscribed);\n }\n }\n\n /**\n * Triggers an access token refresh.\n */\n triggerAccessTokenRefresh() {\n // We perform a sign out to clear the access token from the authentication\n // controller. Next time the access token is requested, a new access token\n // will be fetched.\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n #assertIsUserSubscribed(request: { subscriptionId: string }) {\n if (\n !this.state.subscriptions.find(\n (subscription) => subscription.id === request.subscriptionId,\n )\n ) {\n throw new Error(SubscriptionControllerErrorMessage.UserNotSubscribed);\n }\n }\n\n /**\n * Gets the billing portal URL.\n *\n * @returns The billing portal URL\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n return await this.#subscriptionService.getBillingPortalUrl();\n }\n}\n"]}
@@ -30,8 +30,12 @@ class SubscriptionService {
30
30
  return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
31
31
  }
32
32
  async cancelSubscription(params) {
33
- const path = `subscriptions/${params.subscriptionId}`;
34
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'DELETE');
33
+ const path = `subscriptions/${params.subscriptionId}/cancel`;
34
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', {});
35
+ }
36
+ async unCancelSubscription(params) {
37
+ const path = `subscriptions/${params.subscriptionId}/uncancel`;
38
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', {});
35
39
  }
36
40
  async startSubscriptionWithCard(request) {
37
41
  if (request.products.length === 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.cjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAAyD;AAEzD,+CAIqB;AACrB,yCAAoD;AAoB7C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,IAAA,sBAAU,EAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AADxC,QAAA,gBAAgB,oBACwB;AAErD,MAAa,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,MAAkC;QACzD,MAAM,IAAI,GAAG,iBAAiB,MAAM,CAAC,cAAc,EAAE,CAAC;QACtD,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IAED,KAAK,CAAC,yBAAyB,CAC7B,OAAiC;QAEjC,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,MAAM,IAAI,iCAAwB,CAChC,8CAAkC,CAAC,yBAAyB,CAC7D,CAAC;SACH;QACD,MAAM,IAAI,GAAG,oBAAoB,CAAC;QAElC,OA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IAAI,mFAAwB,MAA5B,IAAI,CAA0B,CAAC;QACrD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAA,wBAAgB,EAAC,uBAAA,IAAI,gCAAK,EAAE,IAAI,CAAC,CAAC,CAAC;QAEvD,MAAM,QAAQ,GAAG,MAAM,IAAA,8BAAW,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE;YACjD,MAAM;YACN,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;aACX;YACD,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;KACjB;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAExE,MAAM,IAAI,iCAAwB,CAChC,2BAA2B,YAAY,EAAE,CAC1C,CAAC;KACH;AACH,CAAC,gDAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n BillingPortalResponse,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCryptoRequest,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: { subscriptionId: string }): Promise<void> {\n const path = `subscriptions/${params.subscriptionId}`;\n return await this.#makeRequest(path, 'DELETE');\n }\n\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const path = 'billing-portal';\n return await this.#makeRequest<BillingPortalResponse>(path);\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionService.cjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAAyD;AAEzD,+CAIqB;AACrB,yCAAoD;AAqB7C,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,IAAA,sBAAU,EAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AADxC,QAAA,gBAAgB,oBACwB;AAErD,MAAa,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,MAExB;QACC,MAAM,IAAI,GAAG,iBAAiB,MAAM,CAAC,cAAc,SAAS,CAAC;QAC7D,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI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AW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n BillingPortalResponse,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n Subscription,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCryptoRequest,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n return await this.#makeRequest(path, 'POST', {});\n }\n\n async unCancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/uncancel`;\n return await this.#makeRequest(path, 'POST', {});\n }\n\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const path = 'billing-portal';\n return await this.#makeRequest<BillingPortalResponse>(path);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type Env } from "./constants.cjs";
2
- import type { AuthUtils, BillingPortalResponse, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCryptoRequest } from "./types.cjs";
2
+ import type { AuthUtils, BillingPortalResponse, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, Subscription, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCryptoRequest } from "./types.cjs";
3
3
  export type SubscriptionServiceConfig = {
4
4
  env: Env;
5
5
  auth: AuthUtils;
@@ -12,7 +12,10 @@ export declare class SubscriptionService implements ISubscriptionService {
12
12
  getSubscriptions(): Promise<GetSubscriptionsResponse>;
13
13
  cancelSubscription(params: {
14
14
  subscriptionId: string;
15
- }): Promise<void>;
15
+ }): Promise<Subscription>;
16
+ unCancelSubscription(params: {
17
+ subscriptionId: string;
18
+ }): Promise<Subscription>;
16
19
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
17
20
  startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
18
21
  updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.d.cts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,GAAG,EACT,wBAAoB;AAErB,OAAO,KAAK,EACV,SAAS,EACT,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,8BAA8B,EAC9B,gCAAgC,EACjC,oBAAgB;AAEjB,MAAM,MAAM,yBAAyB,GAAG;IACtC,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAS,GAAG,QAAQ,MAAM,WACH,CAAC;AAErD,qBAAa,mBAAoB,Y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C/B,cAAc,EAAE,MAAM,CAAC;KACxB,GAAG,OAAO,CAAC,YAAY,CAAC;IAKnB,oBAAoB,CAAC,MAAM,EAAE;QACjC,cAAc,EAAE,MAAM,CAAC;KACxB,GAAG,OAAO,CAAC,YAAY,CAAC;IAKnB,yBAAyB,CAC7B,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC;IAW/B,2BAA2B,CAC/B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,+BAA+B,CAAC;IAKrC,uBAAuB,CAAC,OAAO,EAAE,8BAA8B;IAQ/D,yBAAyB,CAAC,OAAO,EAAE,gCAAgC;IAyCnE,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;IAKtC,mBAAmB,IAAI,OAAO,CAAC,qBAAqB,CAAC;CAI5D"}
@@ -1,5 +1,5 @@
1
1
  import { type Env } from "./constants.mjs";
2
- import type { AuthUtils, BillingPortalResponse, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCryptoRequest } from "./types.mjs";
2
+ import type { AuthUtils, BillingPortalResponse, GetSubscriptionsResponse, ISubscriptionService, PricingResponse, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, Subscription, UpdatePaymentMethodCardRequest, UpdatePaymentMethodCryptoRequest } from "./types.mjs";
3
3
  export type SubscriptionServiceConfig = {
4
4
  env: Env;
5
5
  auth: AuthUtils;
@@ -12,7 +12,10 @@ export declare class SubscriptionService implements ISubscriptionService {
12
12
  getSubscriptions(): Promise<GetSubscriptionsResponse>;
13
13
  cancelSubscription(params: {
14
14
  subscriptionId: string;
15
- }): Promise<void>;
15
+ }): Promise<Subscription>;
16
+ unCancelSubscription(params: {
17
+ subscriptionId: string;
18
+ }): Promise<Subscription>;
16
19
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
17
20
  startSubscriptionWithCrypto(request: StartCryptoSubscriptionRequest): Promise<StartCryptoSubscriptionResponse>;
18
21
  updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.d.mts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,GAAG,EACT,wBAAoB;AAErB,OAAO,KAAK,EACV,SAAS,EACT,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,8BAA8B,EAC9B,gCAAgC,EACjC,oBAAgB;AAEjB,MAAM,MAAM,yBAAyB,GAAG;IACtC,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAS,GAAG,QAAQ,MAAM,WACH,CAAC;AAErD,qBAAa,mBAAoB,YAAW,oBAAoB;;IAGvD,SAAS,EAAE,SAAS,CAAC;gBAEhB,MAAM,EAAE,yBAAyB;IAKvC,gBAAgB,IAAI,OAAO,CAAC,wBAAwB,CAAC;IAKrD,kBAAkB,CAAC,MAAM,EAAE;QAAE,cAAc,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAKrE,yBAAyB,CAC7B,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC;IAW/B,2BAA2B,CAC/B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,+BAA+B,CAAC;IAKrC,uBAAuB,CAAC,OAAO,EAAE,8BAA8B;IAQ/D,yBAAyB,CAAC,OAAO,EAAE,gCAAgC;IAyCnE,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;IAKtC,mBAAmB,IAAI,OAAO,CAAC,qBAAqB,CAAC;CAI5D"}
1
+ {"version":3,"file":"SubscriptionService.d.mts","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,GAAG,EACT,wBAAoB;AAErB,OAAO,KAAK,EACV,SAAS,EACT,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,YAAY,EACZ,8BAA8B,EAC9B,gCAAgC,EACjC,oBAAgB;AAEjB,MAAM,MAAM,yBAAyB,GAAG;IACtC,GAAG,EAAE,GAAG,CAAC;IACT,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAS,GAAG,QAAQ,MAAM,WACH,CAAC;AAErD,qBAAa,mBAAoB,YAAW,oBAAoB;;IAGvD,SAAS,EAAE,SAAS,CAAC;gBAEhB,MAAM,EAAE,yBAAyB;IAKvC,gBAAgB,IAAI,OAAO,CAAC,wBAAwB,CAAC;IAKrD,kBAAkB,CAAC,MAAM,EAAE;QAC/B,cAAc,EAAE,MAAM,CAAC;KACxB,GAAG,OAAO,CAAC,YAAY,CAAC;IAKnB,oBAAoB,CAAC,MAAM,EAAE;QACjC,cAAc,EAAE,MAAM,CAAC;KACxB,GAAG,OAAO,CAAC,YAAY,CAAC;IAKnB,yBAAyB,CAC7B,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC;IAW/B,2BAA2B,CAC/B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,+BAA+B,CAAC;IAKrC,uBAAuB,CAAC,OAAO,EAAE,8BAA8B;IAQ/D,yBAAyB,CAAC,OAAO,EAAE,gCAAgC;IAyCnE,UAAU,IAAI,OAAO,CAAC,eAAe,CAAC;IAKtC,mBAAmB,IAAI,OAAO,CAAC,qBAAqB,CAAC;CAI5D"}
@@ -26,8 +26,12 @@ export class SubscriptionService {
26
26
  return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
27
27
  }
28
28
  async cancelSubscription(params) {
29
- const path = `subscriptions/${params.subscriptionId}`;
30
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'DELETE');
29
+ const path = `subscriptions/${params.subscriptionId}/cancel`;
30
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', {});
31
+ }
32
+ async unCancelSubscription(params) {
33
+ const path = `subscriptions/${params.subscriptionId}/uncancel`;
34
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', {});
31
35
  }
32
36
  async startSubscriptionWithCard(request) {
33
37
  if (request.products.length === 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EACL,UAAU,EACV,kCAAkC,EAEnC,wBAAoB;AACrB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AAoBpD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AAErD,MAAM,OAAO,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KA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AAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n BillingPortalResponse,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCryptoRequest,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: { subscriptionId: string }): Promise<void> {\n const path = `subscriptions/${params.subscriptionId}`;\n return await this.#makeRequest(path, 'DELETE');\n }\n\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const path = 'billing-portal';\n return await this.#makeRequest<BillingPortalResponse>(path);\n }\n}\n"]}
1
+ {"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EACL,UAAU,EACV,kCAAkC,EAEnC,wBAAoB;AACrB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AAqBpD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAE,EAAE,CACzD,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AAErD,MAAM,OAAO,mBAAmB;IAK9B,Y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;aACX;YACD,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;KACjB;IAAC,OAAO,CAAC,EAAE;QACV,MAAM,YAAY,GAAG,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAExE,MAAM,IAAI,wBAAwB,CAChC,2BAA2B,YAAY,EAAE,CAC1C,CAAC;KACH;AACH,CAAC,gDAED,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n type Env,\n} from './constants';\nimport { SubscriptionServiceError } from './errors';\nimport type {\n AuthUtils,\n BillingPortalResponse,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n Subscription,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCryptoRequest,\n} from './types';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string) =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n return await this.#makeRequest(path, 'POST', {});\n }\n\n async unCancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/uncancel`;\n return await this.#makeRequest(path, 'POST', {});\n }\n\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n const path = 'subscriptions/card';\n\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\n }\n\n async updatePaymentMethodCard(request: UpdatePaymentMethodCardRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest) {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\n });\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const path = 'billing-portal';\n return await this.#makeRequest<BillingPortalResponse>(path);\n }\n}\n"]}
package/dist/index.cjs CHANGED
@@ -1,9 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SubscriptionService = exports.SubscriptionControllerErrorMessage = exports.Env = exports.SubscriptionServiceError = exports.getDefaultSubscriptionControllerState = exports.SubscriptionController = void 0;
3
+ exports.SubscriptionService = exports.SubscriptionControllerErrorMessage = exports.Env = exports.SubscriptionServiceError = exports.PAYMENT_TYPES = exports.RECURRING_INTERVALS = exports.PRODUCT_TYPES = exports.SUBSCRIPTION_STATUSES = exports.getDefaultSubscriptionControllerState = exports.SubscriptionController = void 0;
4
4
  var SubscriptionController_1 = require("./SubscriptionController.cjs");
5
5
  Object.defineProperty(exports, "SubscriptionController", { enumerable: true, get: function () { return SubscriptionController_1.SubscriptionController; } });
6
6
  Object.defineProperty(exports, "getDefaultSubscriptionControllerState", { enumerable: true, get: function () { return SubscriptionController_1.getDefaultSubscriptionControllerState; } });
7
+ var types_1 = require("./types.cjs");
8
+ Object.defineProperty(exports, "SUBSCRIPTION_STATUSES", { enumerable: true, get: function () { return types_1.SUBSCRIPTION_STATUSES; } });
9
+ Object.defineProperty(exports, "PRODUCT_TYPES", { enumerable: true, get: function () { return types_1.PRODUCT_TYPES; } });
10
+ Object.defineProperty(exports, "RECURRING_INTERVALS", { enumerable: true, get: function () { return types_1.RECURRING_INTERVALS; } });
11
+ Object.defineProperty(exports, "PAYMENT_TYPES", { enumerable: true, get: function () { return types_1.PAYMENT_TYPES; } });
7
12
  var errors_1 = require("./errors.cjs");
8
13
  Object.defineProperty(exports, "SubscriptionServiceError", { enumerable: true, get: function () { return errors_1.SubscriptionServiceError; } });
9
14
  var constants_1 = require("./constants.cjs");
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAeA,uEAGkC;AAFhC,gIAAA,sBAAsB,OAAA;AACtB,+IAAA,qCAAqC,OAAA;AA0BvC,uCAAoD;AAA3C,kHAAA,wBAAwB,OAAA;AACjC,6CAAsE;AAA7D,gGAAA,GAAG,OAAA;AAAE,+HAAA,kCAAkC,OAAA;AAEhD,iEAA4D;AAAnD,0HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAeA,uEAGkC;AAFhC,gIAAA,sBAAsB,OAAA;AACtB,+IAAA,qCAAqC,OAAA;AA8BvC,qCAKiB;AAJf,8GAAA,qBAAqB,OAAA;AACrB,sGAAA,aAAa,OAAA;AACb,4GAAA,mBAAmB,OAAA;AACnB,sGAAA,aAAa,OAAA;AAEf,uCAAoD;AAA3C,kHAAA,wBAAwB,OAAA;AACjC,6CAAsE;AAA7D,gGAAA,GAAG,OAAA;AAAE,+HAAA,kCAAkC,OAAA;AAEhD,iEAA4D;AAAnD,0HAAA,mBAAmB,OAAA","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n SubscriptionCardPaymentMethod,\n SubscriptionCryptoPaymentMethod,\n SubscriptionPaymentMethod,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n BillingPortalResponse,\n} from './types';\nexport {\n SUBSCRIPTION_STATUSES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n PAYMENT_TYPES,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type { SubscriptionControllerActions, SubscriptionControllerState, SubscriptionControllerEvents, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerCancelSubscriptionAction, SubscriptionControllerStartShieldSubscriptionWithCardAction, SubscriptionControllerGetPricingAction, SubscriptionControllerGetCryptoApproveTransactionParamsAction, SubscriptionControllerStartSubscriptionWithCryptoAction, SubscriptionControllerGetStateAction, SubscriptionControllerMessenger, SubscriptionControllerOptions, SubscriptionControllerStateChangeEvent, } from "./SubscriptionController.cjs";
2
2
  export { SubscriptionController, getDefaultSubscriptionControllerState, } from "./SubscriptionController.cjs";
3
- export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, } from "./types.cjs";
3
+ export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, SubscriptionCardPaymentMethod, SubscriptionCryptoPaymentMethod, SubscriptionPaymentMethod, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, BillingPortalResponse, } from "./types.cjs";
4
+ export { SUBSCRIPTION_STATUSES, PRODUCT_TYPES, RECURRING_INTERVALS, PAYMENT_TYPES, } from "./types.cjs";
4
5
  export { SubscriptionServiceError } from "./errors.cjs";
5
6
  export { Env, SubscriptionControllerErrorMessage } from "./constants.cjs";
6
7
  export type { SubscriptionServiceConfig } from "./SubscriptionService.cjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,EACf,uBAAuB,GACxB,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,6BAA6B,EAC7B,+BAA+B,EAC/B,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,EACf,uBAAuB,EACvB,qBAAqB,GACtB,oBAAgB;AACjB,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,aAAa,GACd,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type { SubscriptionControllerActions, SubscriptionControllerState, SubscriptionControllerEvents, SubscriptionControllerGetSubscriptionsAction, SubscriptionControllerCancelSubscriptionAction, SubscriptionControllerStartShieldSubscriptionWithCardAction, SubscriptionControllerGetPricingAction, SubscriptionControllerGetCryptoApproveTransactionParamsAction, SubscriptionControllerStartSubscriptionWithCryptoAction, SubscriptionControllerGetStateAction, SubscriptionControllerMessenger, SubscriptionControllerOptions, SubscriptionControllerStateChangeEvent, } from "./SubscriptionController.mjs";
2
2
  export { SubscriptionController, getDefaultSubscriptionControllerState, } from "./SubscriptionController.mjs";
3
- export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, } from "./types.mjs";
3
+ export type { Subscription, AuthUtils, ISubscriptionService, StartCryptoSubscriptionRequest, StartCryptoSubscriptionResponse, StartSubscriptionRequest, StartSubscriptionResponse, GetCryptoApproveTransactionRequest, GetCryptoApproveTransactionResponse, SubscriptionCardPaymentMethod, SubscriptionCryptoPaymentMethod, SubscriptionPaymentMethod, RecurringInterval, SubscriptionStatus, PaymentType, Product, ProductType, ProductPrice, ProductPricing, TokenPaymentInfo, ChainPaymentInfo, Currency, PricingPaymentMethod, PricingResponse, UpdatePaymentMethodOpts, BillingPortalResponse, } from "./types.mjs";
4
+ export { SUBSCRIPTION_STATUSES, PRODUCT_TYPES, RECURRING_INTERVALS, PAYMENT_TYPES, } from "./types.mjs";
4
5
  export { SubscriptionServiceError } from "./errors.mjs";
5
6
  export { Env, SubscriptionControllerErrorMessage } from "./constants.mjs";
6
7
  export type { SubscriptionServiceConfig } from "./SubscriptionService.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,EACf,uBAAuB,GACxB,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,4CAA4C,EAC5C,8CAA8C,EAC9C,2DAA2D,EAC3D,sCAAsC,EACtC,6DAA6D,EAC7D,uDAAuD,EACvD,oCAAoC,EACpC,+BAA+B,EAC/B,6BAA6B,EAC7B,sCAAsC,GACvC,qCAAiC;AAClC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,GACtC,qCAAiC;AAClC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,8BAA8B,EAC9B,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EACzB,kCAAkC,EAClC,mCAAmC,EACnC,6BAA6B,EAC7B,+BAA+B,EAC/B,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,WAAW,EACX,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,oBAAoB,EACpB,eAAe,EACf,uBAAuB,EACvB,qBAAqB,GACtB,oBAAgB;AACjB,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,aAAa,GACd,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AACtE,YAAY,EAAE,yBAAyB,EAAE,kCAA8B;AACvE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  export { SubscriptionController, getDefaultSubscriptionControllerState } from "./SubscriptionController.mjs";
2
+ export { SUBSCRIPTION_STATUSES, PRODUCT_TYPES, RECURRING_INTERVALS, PAYMENT_TYPES } from "./types.mjs";
2
3
  export { SubscriptionServiceError } from "./errors.mjs";
3
4
  export { Env, SubscriptionControllerErrorMessage } from "./constants.mjs";
4
5
  export { SubscriptionService } from "./SubscriptionService.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACtC,qCAAiC;AAyBlC,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AAEtE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACtC,qCAAiC;AA6BlC,OAAO,EACL,qBAAqB,EACrB,aAAa,EACb,mBAAmB,EACnB,aAAa,EACd,oBAAgB;AACjB,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AACpD,OAAO,EAAE,GAAG,EAAE,kCAAkC,EAAE,wBAAoB;AAEtE,OAAO,EAAE,mBAAmB,EAAE,kCAA8B","sourcesContent":["export type {\n SubscriptionControllerActions,\n SubscriptionControllerState,\n SubscriptionControllerEvents,\n SubscriptionControllerGetSubscriptionsAction,\n SubscriptionControllerCancelSubscriptionAction,\n SubscriptionControllerStartShieldSubscriptionWithCardAction,\n SubscriptionControllerGetPricingAction,\n SubscriptionControllerGetCryptoApproveTransactionParamsAction,\n SubscriptionControllerStartSubscriptionWithCryptoAction,\n SubscriptionControllerGetStateAction,\n SubscriptionControllerMessenger,\n SubscriptionControllerOptions,\n SubscriptionControllerStateChangeEvent,\n} from './SubscriptionController';\nexport {\n SubscriptionController,\n getDefaultSubscriptionControllerState,\n} from './SubscriptionController';\nexport type {\n Subscription,\n AuthUtils,\n ISubscriptionService,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n GetCryptoApproveTransactionRequest,\n GetCryptoApproveTransactionResponse,\n SubscriptionCardPaymentMethod,\n SubscriptionCryptoPaymentMethod,\n SubscriptionPaymentMethod,\n RecurringInterval,\n SubscriptionStatus,\n PaymentType,\n Product,\n ProductType,\n ProductPrice,\n ProductPricing,\n TokenPaymentInfo,\n ChainPaymentInfo,\n Currency,\n PricingPaymentMethod,\n PricingResponse,\n UpdatePaymentMethodOpts,\n BillingPortalResponse,\n} from './types';\nexport {\n SUBSCRIPTION_STATUSES,\n PRODUCT_TYPES,\n RECURRING_INTERVALS,\n PAYMENT_TYPES,\n} from './types';\nexport { SubscriptionServiceError } from './errors';\nexport { Env, SubscriptionControllerErrorMessage } from './constants';\nexport type { SubscriptionServiceConfig } from './SubscriptionService';\nexport { SubscriptionService } from './SubscriptionService';\n"]}
package/dist/types.cjs CHANGED
@@ -1,35 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SubscriptionStatus = exports.RecurringInterval = exports.PaymentType = exports.ProductType = void 0;
4
- var ProductType;
5
- (function (ProductType) {
6
- ProductType["SHIELD"] = "shield";
7
- })(ProductType || (exports.ProductType = ProductType = {}));
8
- var PaymentType;
9
- (function (PaymentType) {
10
- PaymentType["byCard"] = "card";
11
- PaymentType["byCrypto"] = "crypto";
12
- })(PaymentType || (exports.PaymentType = PaymentType = {}));
13
- var RecurringInterval;
14
- (function (RecurringInterval) {
15
- RecurringInterval["month"] = "month";
16
- RecurringInterval["year"] = "year";
17
- })(RecurringInterval || (exports.RecurringInterval = RecurringInterval = {}));
18
- var SubscriptionStatus;
19
- (function (SubscriptionStatus) {
3
+ exports.SUBSCRIPTION_STATUSES = exports.RECURRING_INTERVALS = exports.PAYMENT_TYPES = exports.PRODUCT_TYPES = void 0;
4
+ exports.PRODUCT_TYPES = {
5
+ SHIELD: 'shield',
6
+ };
7
+ exports.PAYMENT_TYPES = {
8
+ byCard: 'card',
9
+ byCrypto: 'crypto',
10
+ };
11
+ exports.RECURRING_INTERVALS = {
12
+ month: 'month',
13
+ year: 'year',
14
+ };
15
+ exports.SUBSCRIPTION_STATUSES = {
20
16
  // Initial states
21
- SubscriptionStatus["incomplete"] = "incomplete";
22
- SubscriptionStatus["incompleteExpired"] = "incomplete_expired";
17
+ incomplete: 'incomplete',
18
+ incompleteExpired: 'incomplete_expired',
23
19
  // Active states
24
- SubscriptionStatus["provisional"] = "provisional";
25
- SubscriptionStatus["trialing"] = "trialing";
26
- SubscriptionStatus["active"] = "active";
20
+ provisional: 'provisional',
21
+ trialing: 'trialing',
22
+ active: 'active',
27
23
  // Payment issues
28
- SubscriptionStatus["pastDue"] = "past_due";
29
- SubscriptionStatus["unpaid"] = "unpaid";
24
+ pastDue: 'past_due',
25
+ unpaid: 'unpaid',
30
26
  // Cancelled states
31
- SubscriptionStatus["canceled"] = "canceled";
27
+ canceled: 'canceled',
32
28
  // Paused states
33
- SubscriptionStatus["paused"] = "paused";
34
- })(SubscriptionStatus || (exports.SubscriptionStatus = SubscriptionStatus = {}));
29
+ paused: 'paused',
30
+ };
35
31
  //# sourceMappingURL=types.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAEA,IAAY,WAEX;AAFD,WAAY,WAAW;IACrB,gCAAiB,CAAA;AACnB,CAAC,EAFW,WAAW,2BAAX,WAAW,QAEtB;AAYD,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,8BAAe,CAAA;IACf,kCAAmB,CAAA;AACrB,CAAC,EAHW,WAAW,2BAAX,WAAW,QAGtB;AAED,IAAY,iBAGX;AAHD,WAAY,iBAAiB;IAC3B,oCAAe,CAAA;IACf,kCAAa,CAAA;AACf,CAAC,EAHW,iBAAiB,iCAAjB,iBAAiB,QAG5B;AAED,IAAY,kBAmBX;AAnBD,WAAY,kBAAkB;IAC5B,iBAAiB;IACjB,+CAAyB,CAAA;IACzB,8DAAwC,CAAA;IAExC,gBAAgB;IAChB,iDAA2B,CAAA;IAC3B,2CAAqB,CAAA;IACrB,uCAAiB,CAAA;IAEjB,iBAAiB;IACjB,0CAAoB,CAAA;IACpB,uCAAiB,CAAA;IAEjB,mBAAmB;IACnB,2CAAqB,CAAA;IAErB,gBAAgB;IAChB,uCAAiB,CAAA;AACnB,CAAC,EAnBW,kBAAkB,kCAAlB,kBAAkB,QAmB7B","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nexport enum ProductType {\n SHIELD = 'shield',\n}\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n id: string;\n currency: Currency;\n amount: number;\n};\n\nexport enum PaymentType {\n byCard = 'card',\n byCrypto = 'crypto',\n}\n\nexport enum RecurringInterval {\n month = 'month',\n year = 'year',\n}\n\nexport enum SubscriptionStatus {\n // Initial states\n incomplete = 'incomplete',\n incompleteExpired = 'incomplete_expired',\n\n // Active states\n provisional = 'provisional',\n trialing = 'trialing',\n active = 'active',\n\n // Payment issues\n pastDue = 'past_due',\n unpaid = 'unpaid',\n\n // Cancelled states\n canceled = 'canceled',\n\n // Paused states\n paused = 'paused',\n}\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart: string; // ISO 8601\n currentPeriodEnd: string; // ISO 8601\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n};\n\nexport type SubscriptionPaymentMethod = {\n type: PaymentType;\n crypto?: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n };\n};\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\nexport type StartCryptoSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n rawTransaction: Hex;\n};\n\nexport type StartCryptoSubscriptionResponse = {\n subscriptionId: string;\n status: SubscriptionStatus;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n minBillingCycles: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\nexport type TokenPaymentInfo = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate: {\n usd: string;\n };\n};\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n tokens: TokenPaymentInfo[];\n};\n\nexport type PricingPaymentMethod = {\n type: PaymentType;\n chains?: ChainPaymentInfo[];\n};\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n cancelSubscription(request: { subscriptionId: string }): Promise<void>;\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getBillingPortalUrl(): Promise<BillingPortalResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<void>;\n updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void>;\n};\n\nexport type UpdatePaymentMethodOpts =\n | ({\n paymentType: PaymentType.byCard;\n } & UpdatePaymentMethodCardRequest)\n | ({\n paymentType: PaymentType.byCrypto;\n } & UpdatePaymentMethodCryptoRequest);\n\nexport type UpdatePaymentMethodCardRequest = {\n /**\n * Subscription ID\n */\n subscriptionId: string;\n\n /**\n * Recurring interval\n */\n recurringInterval: RecurringInterval;\n};\n\nexport type UpdatePaymentMethodCryptoRequest = {\n subscriptionId: string;\n chainId: Hex;\n payerAddress: Hex;\n tokenSymbol: string;\n rawTransaction: Hex;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n\nexport type BillingPortalResponse = {\n url: string;\n};\n"]}
1
+ {"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAEa,QAAA,aAAa,GAAG;IAC3B,MAAM,EAAE,QAAQ;CACR,CAAC;AAIE,QAAA,aAAa,GAAG;IAC3B,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,QAAQ;CACV,CAAC;AAIE,QAAA,mBAAmB,GAAG;IACjC,KAAK,EAAE,OAAO;IACd,IAAI,EAAE,MAAM;CACJ,CAAC;AAKE,QAAA,qBAAqB,GAAG;IACnC,iBAAiB;IACjB,UAAU,EAAE,YAAY;IACxB,iBAAiB,EAAE,oBAAoB;IACvC,gBAAgB;IAChB,WAAW,EAAE,aAAa;IAC1B,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,iBAAiB;IACjB,OAAO,EAAE,UAAU;IACnB,MAAM,EAAE,QAAQ;IAChB,mBAAmB;IACnB,QAAQ,EAAE,UAAU;IACpB,gBAAgB;IAChB,MAAM,EAAE,QAAQ;CACR,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nexport const PRODUCT_TYPES = {\n SHIELD: 'shield',\n} as const;\n\nexport type ProductType = (typeof PRODUCT_TYPES)[keyof typeof PRODUCT_TYPES];\n\nexport const PAYMENT_TYPES = {\n byCard: 'card',\n byCrypto: 'crypto',\n} as const;\n\nexport type PaymentType = (typeof PAYMENT_TYPES)[keyof typeof PAYMENT_TYPES];\n\nexport const RECURRING_INTERVALS = {\n month: 'month',\n year: 'year',\n} as const;\n\nexport type RecurringInterval =\n (typeof RECURRING_INTERVALS)[keyof typeof RECURRING_INTERVALS];\n\nexport const SUBSCRIPTION_STATUSES = {\n // Initial states\n incomplete: 'incomplete',\n incompleteExpired: 'incomplete_expired',\n // Active states\n provisional: 'provisional',\n trialing: 'trialing',\n active: 'active',\n // Payment issues\n pastDue: 'past_due',\n unpaid: 'unpaid',\n // Cancelled states\n canceled: 'canceled',\n // Paused states\n paused: 'paused',\n} as const;\n\nexport type SubscriptionStatus =\n (typeof SUBSCRIPTION_STATUSES)[keyof typeof SUBSCRIPTION_STATUSES];\n\n/** only usd for now */\nexport type Currency = 'usd';\n\nexport type Product = {\n name: ProductType;\n currency: Currency;\n unitAmount: number;\n unitDecimals: number;\n};\n\n// state\nexport type Subscription = {\n id: string;\n products: Product[];\n currentPeriodStart: string; // ISO 8601\n currentPeriodEnd: string; // ISO 8601\n /** is subscription scheduled for cancellation */\n cancelAtPeriodEnd?: boolean;\n status: SubscriptionStatus;\n interval: RecurringInterval;\n paymentMethod: SubscriptionPaymentMethod;\n trialPeriodDays?: number;\n trialStart?: string; // ISO 8601\n trialEnd?: string; // ISO 8601\n /** is subscription ending soon */\n endDate?: string; // ISO 8601\n billingCycles?: number;\n};\n\nexport type SubscriptionCardPaymentMethod = {\n type: Extract<PaymentType, 'card'>;\n card: {\n brand: string;\n last4: string;\n };\n};\n\nexport type SubscriptionCryptoPaymentMethod = {\n type: Extract<PaymentType, 'crypto'>;\n crypto: {\n payerAddress: Hex;\n chainId: Hex;\n tokenSymbol: string;\n };\n};\n\nexport type SubscriptionPaymentMethod =\n | SubscriptionCardPaymentMethod\n | SubscriptionCryptoPaymentMethod;\n\nexport type GetSubscriptionsResponse = {\n customerId?: string;\n subscriptions: Subscription[];\n trialedProducts: ProductType[];\n};\n\nexport type StartSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n};\n\nexport type StartSubscriptionResponse = {\n checkoutSessionUrl: string;\n};\n\nexport type StartCryptoSubscriptionRequest = {\n products: ProductType[];\n isTrialRequested: boolean;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n chainId: Hex;\n payerAddress: Hex;\n /**\n * e.g. \"USDC\"\n */\n tokenSymbol: string;\n rawTransaction: Hex;\n};\n\nexport type StartCryptoSubscriptionResponse = {\n subscriptionId: string;\n status: SubscriptionStatus;\n};\n\nexport type AuthUtils = {\n getAccessToken: () => Promise<string>;\n};\n\nexport type ProductPrice = {\n interval: RecurringInterval;\n unitAmount: number; // amount in the smallest unit of the currency, e.g., cents\n unitDecimals: number; // number of decimals for the smallest unit of the currency\n /** only usd for now */\n currency: Currency;\n trialPeriodDays: number;\n minBillingCycles: number;\n};\n\nexport type ProductPricing = {\n name: ProductType;\n prices: ProductPrice[];\n};\n\nexport type TokenPaymentInfo = {\n symbol: string;\n address: Hex;\n decimals: number;\n /**\n * example: {\n usd: '1.0',\n },\n */\n conversionRate: {\n usd: string;\n };\n};\n\nexport type ChainPaymentInfo = {\n chainId: Hex;\n paymentAddress: Hex;\n tokens: TokenPaymentInfo[];\n};\n\nexport type PricingPaymentMethod = {\n type: PaymentType;\n chains?: ChainPaymentInfo[];\n};\n\nexport type PricingResponse = {\n products: ProductPricing[];\n paymentMethods: PricingPaymentMethod[];\n};\n\nexport type GetCryptoApproveTransactionRequest = {\n /**\n * payment chain ID\n */\n chainId: Hex;\n /**\n * Payment token address\n */\n paymentTokenAddress: Hex;\n productType: ProductType;\n interval: RecurringInterval;\n};\n\nexport type GetCryptoApproveTransactionResponse = {\n /**\n * The amount to approve\n * e.g: \"100000000\"\n */\n approveAmount: string;\n /**\n * The contract address (spender)\n */\n paymentAddress: Hex;\n /**\n * The payment token address\n */\n paymentTokenAddress: Hex;\n chainId: Hex;\n};\n\nexport type ISubscriptionService = {\n getSubscriptions(): Promise<GetSubscriptionsResponse>;\n cancelSubscription(request: {\n subscriptionId: string;\n }): Promise<Subscription>;\n unCancelSubscription(request: {\n subscriptionId: string;\n }): Promise<Subscription>;\n startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse>;\n getBillingPortalUrl(): Promise<BillingPortalResponse>;\n getPricing(): Promise<PricingResponse>;\n startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse>;\n updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<void>;\n updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void>;\n};\n\nexport type UpdatePaymentMethodOpts =\n | ({\n paymentType: Extract<PaymentType, 'card'>;\n } & UpdatePaymentMethodCardRequest)\n | ({\n paymentType: Extract<PaymentType, 'crypto'>;\n } & UpdatePaymentMethodCryptoRequest);\n\nexport type UpdatePaymentMethodCardRequest = {\n /**\n * Subscription ID\n */\n subscriptionId: string;\n\n /**\n * Recurring interval\n */\n recurringInterval: RecurringInterval;\n};\n\nexport type UpdatePaymentMethodCryptoRequest = {\n subscriptionId: string;\n chainId: Hex;\n payerAddress: Hex;\n tokenSymbol: string;\n rawTransaction: Hex;\n recurringInterval: RecurringInterval;\n billingCycles: number;\n};\n\nexport type BillingPortalResponse = {\n url: string;\n};\n"]}
package/dist/types.d.cts CHANGED
@@ -1,51 +1,71 @@
1
1
  import type { Hex } from "@metamask/utils";
2
- export declare enum ProductType {
3
- SHIELD = "shield"
4
- }
2
+ export declare const PRODUCT_TYPES: {
3
+ readonly SHIELD: "shield";
4
+ };
5
+ export type ProductType = (typeof PRODUCT_TYPES)[keyof typeof PRODUCT_TYPES];
6
+ export declare const PAYMENT_TYPES: {
7
+ readonly byCard: "card";
8
+ readonly byCrypto: "crypto";
9
+ };
10
+ export type PaymentType = (typeof PAYMENT_TYPES)[keyof typeof PAYMENT_TYPES];
11
+ export declare const RECURRING_INTERVALS: {
12
+ readonly month: "month";
13
+ readonly year: "year";
14
+ };
15
+ export type RecurringInterval = (typeof RECURRING_INTERVALS)[keyof typeof RECURRING_INTERVALS];
16
+ export declare const SUBSCRIPTION_STATUSES: {
17
+ readonly incomplete: "incomplete";
18
+ readonly incompleteExpired: "incomplete_expired";
19
+ readonly provisional: "provisional";
20
+ readonly trialing: "trialing";
21
+ readonly active: "active";
22
+ readonly pastDue: "past_due";
23
+ readonly unpaid: "unpaid";
24
+ readonly canceled: "canceled";
25
+ readonly paused: "paused";
26
+ };
27
+ export type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[keyof typeof SUBSCRIPTION_STATUSES];
5
28
  /** only usd for now */
6
29
  export type Currency = 'usd';
7
30
  export type Product = {
8
31
  name: ProductType;
9
- id: string;
10
32
  currency: Currency;
11
- amount: number;
12
- };
13
- export declare enum PaymentType {
14
- byCard = "card",
15
- byCrypto = "crypto"
16
- }
17
- export declare enum RecurringInterval {
18
- month = "month",
19
- year = "year"
20
- }
21
- export declare enum SubscriptionStatus {
22
- incomplete = "incomplete",
23
- incompleteExpired = "incomplete_expired",
24
- provisional = "provisional",
25
- trialing = "trialing",
26
- active = "active",
27
- pastDue = "past_due",
28
- unpaid = "unpaid",
29
- canceled = "canceled",
30
- paused = "paused"
31
- }
33
+ unitAmount: number;
34
+ unitDecimals: number;
35
+ };
32
36
  export type Subscription = {
33
37
  id: string;
34
38
  products: Product[];
35
39
  currentPeriodStart: string;
36
40
  currentPeriodEnd: string;
41
+ /** is subscription scheduled for cancellation */
42
+ cancelAtPeriodEnd?: boolean;
37
43
  status: SubscriptionStatus;
38
44
  interval: RecurringInterval;
39
45
  paymentMethod: SubscriptionPaymentMethod;
46
+ trialPeriodDays?: number;
47
+ trialStart?: string;
48
+ trialEnd?: string;
49
+ /** is subscription ending soon */
50
+ endDate?: string;
51
+ billingCycles?: number;
52
+ };
53
+ export type SubscriptionCardPaymentMethod = {
54
+ type: Extract<PaymentType, 'card'>;
55
+ card: {
56
+ brand: string;
57
+ last4: string;
58
+ };
40
59
  };
41
- export type SubscriptionPaymentMethod = {
42
- type: PaymentType;
43
- crypto?: {
60
+ export type SubscriptionCryptoPaymentMethod = {
61
+ type: Extract<PaymentType, 'crypto'>;
62
+ crypto: {
44
63
  payerAddress: Hex;
45
64
  chainId: Hex;
46
65
  tokenSymbol: string;
47
66
  };
48
67
  };
68
+ export type SubscriptionPaymentMethod = SubscriptionCardPaymentMethod | SubscriptionCryptoPaymentMethod;
49
69
  export type GetSubscriptionsResponse = {
50
70
  customerId?: string;
51
71
  subscriptions: Subscription[];
@@ -150,7 +170,10 @@ export type ISubscriptionService = {
150
170
  getSubscriptions(): Promise<GetSubscriptionsResponse>;
151
171
  cancelSubscription(request: {
152
172
  subscriptionId: string;
153
- }): Promise<void>;
173
+ }): Promise<Subscription>;
174
+ unCancelSubscription(request: {
175
+ subscriptionId: string;
176
+ }): Promise<Subscription>;
154
177
  startSubscriptionWithCard(request: StartSubscriptionRequest): Promise<StartSubscriptionResponse>;
155
178
  getBillingPortalUrl(): Promise<BillingPortalResponse>;
156
179
  getPricing(): Promise<PricingResponse>;
@@ -159,9 +182,9 @@ export type ISubscriptionService = {
159
182
  updatePaymentMethodCrypto(request: UpdatePaymentMethodCryptoRequest): Promise<void>;
160
183
  };
161
184
  export type UpdatePaymentMethodOpts = ({
162
- paymentType: PaymentType.byCard;
185
+ paymentType: Extract<PaymentType, 'card'>;
163
186
  } & UpdatePaymentMethodCardRequest) | ({
164
- paymentType: PaymentType.byCrypto;
187
+ paymentType: Extract<PaymentType, 'crypto'>;
165
188
  } & UpdatePaymentMethodCryptoRequest);
166
189
  export type UpdatePaymentMethodCardRequest = {
167
190
  /**