file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
src/networking/responses/checkout-start-response.ts
TypeScript
import type { GatewayParams } from "./stripe-elements"; export interface CheckoutStartResponse { operation_session_id: string; gateway_params: GatewayParams; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/networking/responses/checkout-status-response.ts
TypeScript
export enum CheckoutSessionStatus { Started = "started", InProgress = "in_progress", Succeeded = "succeeded", Failed = "failed", } export enum CheckoutStatusErrorCodes { SetupIntentCreationFailed = 1, PaymentMethodCreationFailed = 2, PaymentChargeFailed = 3, SetupIntentCompletionFailed = 4, AlreadyPurchased = 5, } export interface CheckoutStatusError { readonly code: CheckoutStatusErrorCodes | number; readonly message: string; } export interface CheckoutStatusRedemptionInfo { readonly redeem_url?: string | null; } export interface CheckoutStatusInnerResponse { readonly status: CheckoutSessionStatus; readonly is_expired: boolean; readonly error?: CheckoutStatusError | null; readonly redemption_info?: CheckoutStatusRedemptionInfo | null; } export interface CheckoutStatusResponse { readonly operation: CheckoutStatusInnerResponse; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/networking/responses/offerings-response.ts
TypeScript
export interface PackageResponse { identifier: string; platform_product_identifier: string; } export interface OfferingResponse { identifier: string; description: string; packages: PackageResponse[]; metadata: { [key: string]: unknown } | null; paywall_components: { [key: string]: unknown } | null; } export interface TargetingResponse { readonly rule_id: string; readonly revision: number; } export interface PlacementsResponse { readonly fallback_offering_id: string; readonly offering_ids_by_placement?: { [key: string]: string | null }; } export interface OfferingsResponse { current_offering_id: string | null; offerings: OfferingResponse[]; targeting?: TargetingResponse; placements?: PlacementsResponse; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/networking/responses/products-response.ts
TypeScript
export interface PriceResponse { amount_micros: number; currency: string; } export interface PricingPhaseResponse { period_duration: string | null; price: PriceResponse | null; cycle_count: number; } export interface PurchaseOptionResponse { id: string; price_id: string; } export interface SubscriptionOptionResponse extends PurchaseOptionResponse { base: PricingPhaseResponse | null; trial: PricingPhaseResponse | null; } export interface NonSubscriptionOptionResponse extends PurchaseOptionResponse { base_price: PriceResponse; } export interface ProductResponse { identifier: string; product_type: string; title: string; description: string | null; default_purchase_option_id: string | null; purchase_options: { [key: string]: NonSubscriptionOptionResponse | SubscriptionOptionResponse; }; } export interface ProductsResponse { product_details: ProductResponse[]; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/networking/responses/stripe-elements.ts
TypeScript
export enum StripeElementsMode { Payment = "payment", Setup = "setup", } export enum StripeElementsSetupFutureUsage { OffSession = "off_session", OnSession = "on_session", } export interface StripeElementsConfiguration { mode: StripeElementsMode; payment_method_types: string[]; setup_future_usage: StripeElementsSetupFutureUsage; amount?: number; currency?: string; } export interface GatewayParams { stripe_account_id?: string; publishable_api_key?: string; elements_configuration?: StripeElementsConfiguration; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/networking/responses/subscriber-response.ts
TypeScript
import { type PeriodType, type Store } from "../../entities/customer-info"; export interface SubscriberEntitlementResponse { expires_date: string | null; grace_period_expires_date?: string | null; product_identifier: string; product_plan_identifier?: string | null; purchase_date: string; } export interface SubscriberSubscriptionResponse { auto_resume_date?: string | null; billing_issues_detected_at: string | null; expires_date: string | null; grace_period_expires_date?: string | null; is_sandbox: boolean; original_purchase_date: string; period_type: PeriodType; product_plan_identifier?: string | null; purchase_date: string; refunded_at?: string | null; store: Store; store_transaction_id?: string | null; unsubscribe_detected_at: string | null; } export interface NonSubscriptionResponse { id: string; is_sandbox: boolean; original_purchase_date: string; purchase_date?: string | null; store: Store; store_transaction_id?: string | null; } export interface SubscriberInnerResponse { entitlements: { [entitlementId: string]: SubscriberEntitlementResponse }; first_seen: string; last_seen?: string | null; management_url: string | null; non_subscriptions: { [key: string]: NonSubscriptionResponse[] }; original_app_user_id: string; original_application_version: string | null; original_purchase_date: string | null; other_purchases?: { [key: string]: unknown } | null; // TODO: Add proper types subscriptions: { [productId: string]: SubscriberSubscriptionResponse }; } export interface SubscriberResponse { request_date: string; request_date_ms: number; subscriber: SubscriberInnerResponse; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/atoms/app-logo.stories.svelte
Svelte
<script module> import { default as AppLogo } from "../../ui/atoms/app-logo.svelte"; import { type Args, defineMeta, setTemplate, type StoryContext, } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; import { brandingInfos } from "../fixtures"; import { buildAssetURL } from "../../networking/assets"; let { Story } = defineMeta({ component: AppLogo, title: "Atoms/AppLogo", // @ts-expect-error ignore typing of decorator decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <script lang="ts"> setTemplate(template); </script> {#snippet template( _args: Args<typeof Story>, context: StoryContext<typeof Story>, )} {@const isLoading = context.story === "Loading"} {@const brandingInfo = brandingInfos[context.globals.brandingName]} {@const src = brandingInfo?.app_icon && !isLoading ? buildAssetURL(brandingInfo?.app_icon) : null} {@const srcWebp = brandingInfo?.app_icon_webp && !isLoading ? buildAssetURL(brandingInfo?.app_icon_webp) : null} <AppLogo {src} {srcWebp} /> {/snippet} <Story name="Default" /> <Story name="Loading" />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/atoms/button.stories.svelte
Svelte
<script module> import { default as Button } from "../../ui/atoms/button.svelte"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; let { Story } = defineMeta<typeof Button>({ component: Button, title: "Atoms/Button", // @ts-expect-error ignore typing of decorator decorators: [withLayout], argTypes: { intent: { control: "radio", options: ["primary", undefined], }, }, parameters: { chromatic: { modes: brandingModes, }, }, }); const args = { intent: "primary" as const, disabled: false, loading: false, }; </script> <script lang="ts"> setTemplate(template); </script> {#snippet template({ ...args }: Args<typeof Story>)} <Button {...args}> {#snippet children()} Click Me {/snippet} </Button> {/snippet} <Story name="Default" {args} /> <Story name="Disabled" args={{ ...args, disabled: true }} /> <Story name="Loading" args={{ ...args, loading: true }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/atoms/icon.stories.svelte
Svelte
<script module> import { default as Icon } from "../../ui/atoms/icon.svelte"; import { brandingModes } from "../../../.storybook/modes"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; const { Story } = defineMeta({ component: Icon, title: "Atoms/Icon", // @ts-expect-error ignore typing of decorator decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <script lang="ts"> setTemplate(template); </script> {#snippet template({ name }: Args<typeof Story>)} <Icon name={name ?? "cart"} /> {/snippet} <Story name="Cart" args={{ name: "cart" }} /> <Story name="Error" args={{ name: "error" }} /> <Story name="Lock" args={{ name: "lock" }} /> <Story name="Success" args={{ name: "success" }} /> <Story name="Chevron Up" args={{ name: "chevron-up" }} /> <Story name="Chevron Down" args={{ name: "chevron-down" }} /> <Story name="Chevron Left" args={{ name: "chevron-left" }} /> <Story name="Chevron Right" args={{ name: "chevron-right" }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/atoms/processing-animation.stories.svelte
Svelte
<script module> import { default as ProcessingAnimation } from "../../ui/atoms/processing-animation.svelte"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; let { Story } = defineMeta({ component: ProcessingAnimation, title: "Atoms/ProcessingAnimation", // @ts-expect-error ignore typing of decorator decorators: [withLayout], argTypes: { size: { control: "radio", options: ["small", "medium", "large"], }, }, parameters: { chromatic: { modes: brandingModes, }, }, }); const args = { size: "medium" as const, }; </script> <script lang="ts"> setTemplate(template); </script> {#snippet template({ ...args }: Args<typeof Story>)} <ProcessingAnimation {...args} /> {/snippet} <Story name="Small" args={{ ...args, size: "small" }} /> <Story name="Medium" args={{ ...args, size: "medium" }} /> <Story name="Large" args={{ ...args, size: "large" }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/atoms/skeleton.stories.svelte
Svelte
<script module> import { brandingModes } from "../../../.storybook/modes"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import Skeleton from "../../ui/atoms/skeleton.svelte"; const { Story } = defineMeta({ component: Skeleton, title: "Atoms/Skeleton", // @ts-expect-error ignore typing of decorator decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <script lang="ts"> setTemplate(template); </script> {#snippet template(args: Args<typeof Story>)} <div style="display: flex; align-items: flex-start;"> <Skeleton> {@render args.children?.()} </Skeleton> </div> {/snippet} {#snippet loading()} Loading {/snippet} {#snippet priceUsd()} $12.34 {/snippet} {#snippet priceSek()} 12.34 SEK {/snippet} <Story name="Loading" args={{ children: loading }} /> <Story name="Price USD" args={{ children: priceUsd }} /> <Story name="Price SEK" args={{ children: priceSek }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/atoms/spinner.stories.svelte
Svelte
<script module> import { default as Spinner } from "../../ui/atoms/spinner.svelte"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; let { Story } = defineMeta({ component: Spinner, title: "Atoms/Spinner", decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); const args = {}; </script> <script lang="ts"> setTemplate(template); </script> {#snippet template({ ...args }: Args<typeof Story>)} <Spinner {...args} /> {/snippet} <Story name="Default" {args} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/decorators/global-decorator.svelte
Svelte
<script module> import { Translator } from "../../ui/localization/translator"; import { translatorContextKey } from "../../ui/localization/constants"; import { eventsTrackerContextKey } from "../../ui/constants"; import { setContext, type Snippet } from "svelte"; import { writable, type Writable } from "svelte/store"; </script> <script lang="ts"> interface Props { children?: Snippet; globals: { locale: string; viewport: string; }; } let { children, globals }: Props = $props(); const isEmbeddedViewport = globals.viewport === "embedded"; const initiaLocale = globals.locale || "en"; const translator = new Translator({}, initiaLocale, initiaLocale); const translatorStore: Writable<Translator> = writable(translator); setContext(translatorContextKey, translatorStore); setContext(eventsTrackerContextKey, { trackSDKEvent: () => {} }); $effect(() => { const newLocale = globals.locale; const newTranslator = new Translator({}, newLocale, newLocale); translatorStore.set(newTranslator); }); </script> {#if isEmbeddedViewport} {@render embedded(children)} {:else} {@render children?.()} {/if} {#snippet embedded(children?: Snippet)} <div style="width: 100vw; height:100vh; background-color: red;"> <div style="display: flex"> <div id="embedding-container" style="width: 500px; height: 600px; position: relative; overflow: hidden; background-color: lightgray;" > {@render children?.()} </div> <div style="padding: 20px;"> <h1>Homer's Web page</h1> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quos. </p> </div> </div> </div> {/snippet}
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/decorators/with-context.svelte
Svelte
<script lang="ts"> import { setContext, type Snippet } from "svelte"; interface Props { children?: Snippet; context?: Record<string, any>; } let { children, context }: Props = $props(); Object.entries(context || {}).forEach(([key, value]) => { setContext(key, value); }); </script> {@render children?.()}
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/decorators/with-layout.svelte
Svelte
<script module> import { brandingInfos } from "../fixtures"; import { toProductInfoStyleVar } from "../../ui/theme/utils"; import Container from "../../ui/layout/container.svelte"; import Layout from "../../ui/layout/layout.svelte"; import Main from "../../ui/layout/main-block.svelte"; import type { Snippet } from "svelte"; </script> <script lang="ts"> export interface Props { children: Snippet<[]>; globals: { brandingName: string; }; } const { children, globals }: Props = $props(); const brandingInfo = $derived(brandingInfos[globals.brandingName]); const colorVariables = $derived( toProductInfoStyleVar(brandingInfo.appearance), ); </script> <Container brandingAppearance={brandingInfo.appearance}> <Layout style={colorVariables}> <Main brandingAppearance={brandingInfo.appearance}> {#snippet body()} {@render children()} {/snippet} </Main> </Layout> </Container>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/decorators/with-layout.ts
TypeScript
import WithLayout from "./with-layout.svelte"; export function withLayout(Story: unknown, context: unknown) { return { Component: WithLayout, props: { // @ts-expect-error too hard to get the type right globals: context.globals, children: () => ({ Component: Story, // @ts-expect-error too hard to get the type right props: context.args, }), }, }; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/decorators/with-navbar.svelte
Svelte
<script module> import { brandingInfos } from "../fixtures"; import { toProductInfoStyleVar } from "../../ui/theme/utils"; import Container from "../../ui/layout/container.svelte"; import Layout from "../../ui/layout/layout.svelte"; import Main from "../../ui/layout/main-block.svelte"; import NavBar from "../../ui/layout/navbar.svelte"; import { type Snippet } from "svelte"; </script> <script lang="ts"> export interface Props { children?: Snippet<[]>; globals: { brandingName: string; viewport: string; }; } const { children, globals }: Props = $props(); const brandingInfo = $derived(brandingInfos[globals.brandingName]); const colorVariables = $derived( toProductInfoStyleVar(brandingInfo.appearance), ); const isInElement = $derived(globals.viewport === "embedded"); </script> <Container brandingAppearance={brandingInfo.appearance} {isInElement}> <Layout style={colorVariables}> <NavBar brandingAppearance={brandingInfo.appearance} showCloseButton={false} > {#snippet headerContent()}{/snippet} {#snippet bodyContent()} {@render children?.()} {/snippet} </NavBar> <Main brandingAppearance={brandingInfo.appearance}> {#snippet body()}{/snippet} </Main> </Layout> </Container>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/decorators/with-navbar.ts
TypeScript
import WithNavbar from "./with-navbar.svelte"; export function withNavbar(Story: unknown, context: unknown) { return { Component: WithNavbar, props: { // @ts-expect-error too hard to get the type right globals: context.globals, children: () => ({ Component: Story, // @ts-expect-error too hard to get the type right props: context.args, }), }, }; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/fixtures.ts
TypeScript
import type { BrandingInfoResponse } from "../networking/responses/branding-response"; import { eventsTrackerContextKey } from "../ui/constants"; import { type NonSubscriptionOption, type Package, PackageType, type Product, ProductType, type SubscriptionOption, } from "../entities/offerings"; import { PeriodUnit } from "../helpers/duration-helper"; import { PurchaseFlowError } from "../helpers/purchase-operation-helper"; import { type CheckoutStartResponse } from "../networking/responses/checkout-start-response"; import type { BrandingAppearance } from "../entities/branding"; import type { CheckoutCalculateTaxResponse } from "../networking/responses/checkout-calculate-tax-response"; import { StripeElementsSetupFutureUsage } from "../networking/responses/stripe-elements"; import { StripeElementsMode } from "../networking/responses/stripe-elements"; import type { PriceBreakdown } from "src/ui/ui-types"; const subscriptionOptionBasePrice = { periodDuration: "P1M", period: { unit: PeriodUnit.Month, number: 1, }, price: { amount: 990, amountMicros: 9900000, currency: "USD", formattedPrice: "9.90$", }, cycleCount: 0, }; export const subscriptionOption: SubscriptionOption = { id: "option_id_1", priceId: "price_1", base: subscriptionOptionBasePrice, trial: null, }; export const subscriptionOptionWithTrial: SubscriptionOption = { id: "option_id_1", priceId: "price_1", base: subscriptionOption.base, trial: { periodDuration: "P1W", period: { number: 1, unit: PeriodUnit.Week, }, cycleCount: 1, price: null, }, }; export const nonSubscriptionOption: NonSubscriptionOption = { id: "option_id_1", priceId: "price_1", basePrice: { amount: 1995, amountMicros: 19950000, currency: "USD", formattedPrice: "19.95$", }, }; export const product: Product = { identifier: "some_product_123", displayName: "Fantastic Cat", description: "This is a long description of the product which is long. " + "It is long indeed so that it spans multiple lines.", title: "Fantastic Cat Pro", productType: ProductType.Subscription, currentPrice: { amount: 990, amountMicros: 9900000, currency: "USD", formattedPrice: "9.90$", }, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "some_offering_identifier", presentedOfferingContext: { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: subscriptionOption, defaultNonSubscriptionOption: null, defaultSubscriptionOption: subscriptionOption, subscriptionOptions: { option_id_1: subscriptionOption, }, }; export const consumableProduct: Product = { ...structuredClone(product), productType: ProductType.Consumable, defaultPurchaseOption: nonSubscriptionOption, }; export const nonConsumableProduct: Product = { ...structuredClone(product), productType: ProductType.NonConsumable, defaultPurchaseOption: nonSubscriptionOption, }; export const rcPackage: Package = { identifier: "testPackage", packageType: PackageType.Monthly, rcBillingProduct: product, webBillingProduct: product, }; export const colorfulBrandingAppearance: BrandingAppearance = { shapes: "rounded", color_form_bg: "#313131", // dark grey color_error: "#E79462", // orange color_product_info_bg: "#ffffff", // white color_buttons_primary: "#AC7DE3", // purple color_accent: "#99BB37", // green color_page_bg: "#ffffff", // white font: "sans-serif", show_product_description: true, }; export const brandingInfo: BrandingInfoResponse = { id: "branding_info_id", support_email: "support@somefantasticcat.com", app_name: "Some Fantastic Cat, Inc.", app_icon: "1005820_1715624566.png", app_icon_webp: "1005820_1715624566.webp", appearance: null, gateway_tax_collection_enabled: false, }; export const purchaseFlowError = new PurchaseFlowError(1); export const purchaseResponse = { next_action: "collect_payment_info", data: { client_secret: "test_client_secret", publishable_api_key: "test_publishable_api_key", stripe_account_id: "test_stripe_account_id", }, }; export const stripeElementsConfiguration = { mode: StripeElementsMode.Payment, payment_method_types: ["card"], setup_future_usage: StripeElementsSetupFutureUsage.OffSession, amount: 999, currency: "usd", }; const publishableApiKey = import.meta.env.VITE_STORYBOOK_PUBLISHABLE_API_KEY; const accountId = import.meta.env.VITE_STORYBOOK_ACCOUNT_ID; export const checkoutStartResponse: CheckoutStartResponse = { operation_session_id: "rcbopsess_test_test_test", gateway_params: { publishable_api_key: publishableApiKey, stripe_account_id: accountId, elements_configuration: stripeElementsConfiguration, }, }; export const checkoutCalculateTaxResponse: CheckoutCalculateTaxResponse = { operation_session_id: "operation-session-id", currency: "USD", tax_inclusive: false, total_amount_in_micros: 9900000 + 2450000, total_excluding_tax_in_micros: 9900000, tax_amount_in_micros: 2450000, pricing_phases: { base: { tax_breakdown: [], }, }, gateway_params: { elements_configuration: stripeElementsConfiguration, }, }; export const defaultContext = { [eventsTrackerContextKey]: { trackExternalEvent: () => {}, trackSDKEvent: () => {}, updateUser: () => Promise.resolve(), dispose: () => {}, }, }; export const brandingInfos: Record<string, BrandingInfoResponse> = { None: brandingInfo, Fantastic: { id: "branding_info_id", support_email: "support@somefantasticcat.com", app_name: "Some Fantastic Cat, Inc.", app_icon: "1005820_1715624566.png", app_icon_webp: "1005820_1715624566.webp", appearance: { shapes: "rectangle", color_form_bg: "#313131", color_error: "#E79462", color_product_info_bg: "#ffffff", color_buttons_primary: "#AC7DE3", color_accent: "#99BB37", color_page_bg: "#ffffff", font: "sans-serif", show_product_description: true, }, gateway_tax_collection_enabled: false, }, Igify: { id: "app7e12a2a4b3", support_email: "devservices@revenuecat.com", app_icon: "1005820_1739283698.png", app_icon_webp: "1005820_1739283698.webp", app_name: "Igify", appearance: { color_accent: "#969696", color_buttons_primary: "#000000", color_error: "#e61054", color_form_bg: "#FFFFFF", color_page_bg: "#114ab8", color_product_info_bg: "#114ab8", font: "default", shapes: "default", show_product_description: true, }, gateway_tax_collection_enabled: false, }, Dipsea: { id: "appd458f1e3a2", support_email: "devservices@revenuecat.com", app_icon: "1005820_1730470500.png", app_icon_webp: "1005820_1730470500.webp", app_name: "Dipsea", appearance: { color_accent: "#DF5539", color_buttons_primary: "#DF5539", color_error: "#F2545B", color_form_bg: "#372CBC", color_page_bg: "#26122F", color_product_info_bg: "#26122F", font: "default", shapes: "pill", show_product_description: false, }, gateway_tax_collection_enabled: false, }, }; export const priceBreakdownTaxDisabled: PriceBreakdown = { currency: "USD", totalAmountInMicros: 9900000, totalExcludingTaxInMicros: 9900000, taxCollectionEnabled: false, taxCalculationStatus: "calculated", taxAmountInMicros: 0, pendingReason: null, taxBreakdown: null, }; export const priceBreakdownTaxInclusive: PriceBreakdown = { ...priceBreakdownTaxDisabled, totalAmountInMicros: 1718000 + 8180000, totalExcludingTaxInMicros: 8180000, taxAmountInMicros: 1718000, taxCollectionEnabled: true, taxCalculationStatus: "calculated", taxBreakdown: [ { tax_type: "VAT", tax_amount_in_micros: 1718000, tax_rate_in_micros: 210000, country: "ES", state: null, taxable_amount_in_micros: 8180000, display_name: "VAT - Spain (21%)", }, ], }; export const priceBreakdownTaxExclusive: PriceBreakdown = { ...priceBreakdownTaxDisabled, totalAmountInMicros: 693000 + 9900000, totalExcludingTaxInMicros: 9900000, taxAmountInMicros: 693000, taxCollectionEnabled: true, taxCalculationStatus: "calculated", taxBreakdown: [ { tax_type: "tax_rate", tax_amount_in_micros: 693000, tax_rate_in_micros: 70000, country: "USA", state: "NY", taxable_amount_in_micros: 9900000, display_name: "Tax Rate - NY (7%)", }, ], }; export const priceBreakdownTaxLoading: PriceBreakdown = { ...priceBreakdownTaxExclusive, totalAmountInMicros: 9900000, taxCalculationStatus: "loading", }; export const priceBreakdownTaxPending: PriceBreakdown = { ...priceBreakdownTaxExclusive, totalAmountInMicros: 9900000, taxCalculationStatus: "pending", pendingReason: null, }; export const priceBreakdownTaxExclusiveWithMultipleTaxItems: PriceBreakdown = { ...priceBreakdownTaxDisabled, totalAmountInMicros: 9900000 + 495000 + 987525, totalExcludingTaxInMicros: 9900000, taxAmountInMicros: 495000 + 987525, taxCollectionEnabled: true, taxCalculationStatus: "calculated", taxBreakdown: [ { tax_type: "GST", tax_amount_in_micros: 495000, tax_rate_in_micros: 50000, country: "CA", state: null, taxable_amount_in_micros: 9900000, display_name: "GST - Canada (5%)", }, { tax_type: "QST", tax_amount_in_micros: 987525, tax_rate_in_micros: 99750, country: "CA", state: "ON", taxable_amount_in_micros: 9900000, display_name: "QST - Ontario (9.975%)", }, ], };
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/back-button.stories.svelte
Svelte
<script module> import BackButton from "../../ui/molecules/back-button.svelte"; import { defineMeta } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; let { Story } = defineMeta({ component: BackButton, title: "Molecules/BackButton", // @ts-expect-error ignore typing of decorator decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="Default" /> <Story name="Disabled" args={{ disabled: true }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/close-button.stories.svelte
Svelte
<script module> import CloseButton from "../../ui/molecules/close-button.svelte"; import { defineMeta } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; let { Story } = defineMeta({ component: CloseButton, title: "Molecules/CloseButton", // @ts-expect-error ignore typing of decorator decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="Default" />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/payment-button.stories.svelte
Svelte
<script module> import PaymentButton from "../../ui/molecules/payment-button.svelte"; import { defineMeta } from "@storybook/addon-svelte-csf"; import { withLayout } from "../decorators/with-layout"; import { brandingModes } from "../../../.storybook/modes"; import { subscriptionOption, subscriptionOptionWithTrial } from "../fixtures"; let { Story } = defineMeta({ component: PaymentButton, title: "Molecules/PaymentButton", // @ts-expect-error ignore typing of decorator decorators: [withLayout], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="With Subscription" args={{ disabled: false, subscriptionOption: subscriptionOption, }} /> <Story name="With Subscription Disabled" args={{ disabled: true, subscriptionOption: subscriptionOption, }} /> <Story name="With Trial" args={{ disabled: false, subscriptionOption: subscriptionOptionWithTrial, }} /> <Story name="With Trial Disabled" args={{ disabled: true, subscriptionOption: subscriptionOptionWithTrial, }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/pricing-dropdown.stories.svelte
Svelte
<script module> import { default as Dropdown } from "../../ui/molecules/pricing-dropdown.svelte"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withNavbar } from "../decorators/with-navbar"; import { mobileAndDesktopBrandingModes } from "../../../.storybook/modes"; let { Story } = defineMeta({ component: Dropdown, title: "Molecules/PricingDropdown", // @ts-expect-error ignore typing of decorator decorators: [withNavbar], parameters: { chromatic: { modes: mobileAndDesktopBrandingModes, }, }, }); </script> <script lang="ts"> setTemplate(template); </script> {#snippet template({ ...props }: Args<typeof Story>)} <Dropdown isExpanded={props.isExpanded ?? true}> {#snippet children()} <p> This is the dropdown content.<br /> You can put any content here. </p> {/snippet} </Dropdown> {/snippet} <Story name="Default" /> <Story name="Collapsed" args={{ isExpanded: false }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/pricing-summary.stories.svelte
Svelte
<script module> import { brandingModes } from "../../../.storybook/modes"; import { defineMeta, setTemplate } from "@storybook/addon-svelte-csf"; import { withNavbar } from "../decorators/with-navbar"; import PricingSummary from "../../ui/molecules/pricing-summary.svelte"; import { product, subscriptionOption, subscriptionOptionWithTrial, nonSubscriptionOption, consumableProduct, priceBreakdownTaxDisabled, } from "../fixtures"; const { Story } = defineMeta({ component: PricingSummary, title: "Molecules/PricingSummary", // @ts-expect-error ignore typing of decorator decorators: [withNavbar], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="Subscription" args={{ priceBreakdown: priceBreakdownTaxDisabled, basePhase: subscriptionOption.base, }} /> <Story name="Trial" args={{ priceBreakdown: priceBreakdownTaxDisabled, basePhase: subscriptionOption.base, trialPhase: subscriptionOptionWithTrial.trial, }} /> <Story name="Non Subscription" args={{ priceBreakdown: priceBreakdownTaxDisabled, }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/pricing-table.stories.svelte
Svelte
<script module> import PricingTable from "../../ui/molecules/pricing-table.svelte"; import { type Args, defineMeta, setTemplate, } from "@storybook/addon-svelte-csf"; import { withNavbar } from "../decorators/with-navbar"; import { brandingModes } from "../../../.storybook/modes"; import { priceBreakdownTaxDisabled, priceBreakdownTaxExclusive, priceBreakdownTaxExclusiveWithMultipleTaxItems, priceBreakdownTaxInclusive, priceBreakdownTaxLoading, priceBreakdownTaxPending, subscriptionOptionWithTrial, } from "../fixtures"; let { Story } = defineMeta({ component: PricingTable, title: "Molecules/PricingTable", // @ts-expect-error ignore typing of decorator decorators: [withNavbar], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <script lang="ts"> setTemplate(template); </script> {#snippet template(args: Args<typeof Story>)} <PricingTable priceBreakdown={args.priceBreakdown ?? priceBreakdownTaxDisabled} trialPhase={args.trialPhase ?? null} /> {/snippet} <Story name="Disabled Tax" /> <Story name="Disabled Tax Trial" args={{ trialPhase: subscriptionOptionWithTrial.trial, }} /> <Story name="Pending Tax Generic" args={{ priceBreakdown: priceBreakdownTaxPending, }} /> <Story name="Pending Tax US" args={{ priceBreakdown: { ...priceBreakdownTaxPending, pendingReason: "needs_postal_code", }, }} /> <Story name="Pending Tax CA" args={{ priceBreakdown: { ...priceBreakdownTaxPending, pendingReason: "needs_state_or_postal_code", }, }} /> <Story name="Loading Tax" args={{ priceBreakdown: priceBreakdownTaxLoading, }} /> <Story name="Tax Inclusive" args={{ priceBreakdown: priceBreakdownTaxInclusive, }} /> <Story name="Tax Inclusive Trial" args={{ priceBreakdown: priceBreakdownTaxInclusive, trialPhase: subscriptionOptionWithTrial.trial, }} /> <Story name="Tax Exclusive" args={{ priceBreakdown: priceBreakdownTaxExclusive, }} /> <Story name="Tax Exclusive Trial" args={{ priceBreakdown: priceBreakdownTaxExclusive, trialPhase: subscriptionOptionWithTrial.trial, }} /> <Story name="Multiple Tax Items (Exclusive)" args={{ priceBreakdown: priceBreakdownTaxExclusiveWithMultipleTaxItems, }} /> <Story name="Multiple Tax Items Trial (Exclusive)" args={{ priceBreakdown: priceBreakdownTaxExclusiveWithMultipleTaxItems, trialPhase: subscriptionOptionWithTrial.trial, }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/product-header.stories.svelte
Svelte
<script module> import { brandingModes } from "../../../.storybook/modes"; import { defineMeta, setTemplate } from "@storybook/addon-svelte-csf"; import { withNavbar } from "../decorators/with-navbar"; import ProductInfoHeader from "../../ui/molecules/product-header.svelte"; import { product, colorfulBrandingAppearance } from "../fixtures"; const { Story } = defineMeta({ component: ProductInfoHeader, title: "Molecules/ProductHeader", // @ts-expect-error ignore typing of decorator decorators: [withNavbar], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="Without description"> <ProductInfoHeader productDetails={product} showProductDescription={false} /> </Story> <Story name="With description"> <ProductInfoHeader productDetails={product} showProductDescription={true} /> </Story>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/molecules/secure-checkout-rc.stories.svelte
Svelte
<script module> import { brandingModes } from "../../../.storybook/modes"; import { defineMeta, setTemplate } from "@storybook/addon-svelte-csf"; import { withNavbar } from "../decorators/with-navbar"; import SecureCheckoutRC from "../../ui/molecules/secure-checkout-rc.svelte"; import { brandingInfo } from "../fixtures"; import { subscriptionOptionWithTrial } from "../fixtures"; const { Story } = defineMeta({ component: SecureCheckoutRC, title: "Molecules/SecureCheckoutRC", // @ts-expect-error ignore typing of decorator decorators: [withNavbar], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="Without Extra Info"> <SecureCheckoutRC brandingInfo={null} subscriptionOption={null} /> </Story> <Story name="With Terms Info"> <SecureCheckoutRC {brandingInfo} /> </Story> <Story name="With Terms and Trial Info"> <SecureCheckoutRC {brandingInfo} subscriptionOption={subscriptionOptionWithTrial} /> </Story>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/organisms/product-info.stories.svelte
Svelte
<script module> import { brandingModes } from "../../../.storybook/modes"; import { defineMeta, setTemplate } from "@storybook/addon-svelte-csf"; import { withNavbar } from "../decorators/with-navbar"; import ProductInfo from "../../ui/organisms/product-info.svelte"; import { product, subscriptionOption, subscriptionOptionWithTrial, nonSubscriptionOption, consumableProduct, priceBreakdownTaxDisabled, priceBreakdownTaxInclusive, priceBreakdownTaxExclusive, } from "../fixtures"; const { Story } = defineMeta({ component: ProductInfo, title: "Organisms/ProductInfo", // @ts-expect-error ignore typing of decorator decorators: [withNavbar], parameters: { chromatic: { modes: brandingModes, }, }, }); </script> <Story name="Default" args={{ productDetails: product, purchaseOption: subscriptionOption, showProductDescription: true, priceBreakdown: priceBreakdownTaxDisabled, }} /> <Story name="Trial" args={{ productDetails: product, purchaseOption: subscriptionOptionWithTrial, showProductDescription: true, priceBreakdown: priceBreakdownTaxDisabled, }} /> <Story name="Non-subscription" args={{ productDetails: consumableProduct, purchaseOption: nonSubscriptionOption, showProductDescription: true, priceBreakdown: priceBreakdownTaxDisabled, }} /> <Story name="Tax Inclusive" args={{ productDetails: product, purchaseOption: subscriptionOption, showProductDescription: true, priceBreakdown: priceBreakdownTaxInclusive, }} /> <Story name="Tax Exclusive" args={{ productDetails: product, purchaseOption: subscriptionOption, showProductDescription: true, priceBreakdown: priceBreakdownTaxExclusive, }} /> <Story name="Tax Exclusive with trial" args={{ productDetails: product, purchaseOption: subscriptionOptionWithTrial, showProductDescription: true, priceBreakdown: priceBreakdownTaxExclusive, }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stories/pages/purchase.stories.svelte
Svelte
<script module> import { defineMeta, setTemplate, type StoryContext, type Args, } from "@storybook/addon-svelte-csf"; import PurchasesInner from "../../ui/purchases-ui-inner.svelte"; import { brandingLanguageViewportModes } from "../../../.storybook/modes"; import { brandingInfos, product, purchaseFlowError, subscriptionOption, subscriptionOptionWithTrial, checkoutStartResponse, priceBreakdownTaxDisabled, priceBreakdownTaxInclusive, } from "../fixtures"; import { PurchaseOperationHelper } from "../../helpers/purchase-operation-helper"; const defaultArgs = { productDetails: product, purchaseOptionToUse: subscriptionOption, purchaseOption: subscriptionOption, lastError: purchaseFlowError, onContinue: () => {}, }; let { Story } = defineMeta({ title: "Pages/Purchase", args: defaultArgs, argTypes: { withTaxes: { control: "boolean", }, }, parameters: { viewport: { defaultViewport: "mobile", }, chromatic: { modes: brandingLanguageViewportModes, diffThreshold: 0.49, }, }, }); </script> <script lang="ts"> setTemplate(template); </script> {#snippet template( args: Args<typeof Story>, context: StoryContext<typeof Story>, )} {@const brandingInfo = brandingInfos[context.globals.brandingName]} <PurchasesInner isSandbox={args.isSandbox} currentPage={args.currentPage} productDetails={args.productDetails} purchaseOptionToUse={args.purchaseOptionToUse} {brandingInfo} handleContinue={() => {}} closeWithError={() => {}} lastError={null} gatewayParams={checkoutStartResponse.gateway_params} priceBreakdown={args.withTaxes ? priceBreakdownTaxInclusive : priceBreakdownTaxDisabled} purchaseOperationHelper={null as unknown as PurchaseOperationHelper} isInElement={context.globals.viewport === "embedded"} onTaxCustomerDetailsUpdated={() => {}} /> {/snippet} <Story name="Email Input" args={{ currentPage: "email-entry" }} /> <Story name="Email Input (with Sandbox Banner)" args={{ currentPage: "email-entry", isSandbox: true }} /> <Story name="Email Input (with Trial Product)" args={{ currentPage: "email-entry", isSandbox: true, productDetails: { ...product, normalPeriodDuration: "P1Y", }, purchaseOptionToUse: subscriptionOptionWithTrial, }} /> <Story name="Checkout" args={{ ...defaultArgs, currentPage: "payment-entry" }} /> <Story name="Checkout (with Tax)" args={{ ...defaultArgs, currentPage: "payment-entry", withTaxes: true, }} /> <Story name="Checkout (with Trial Product)" args={{ ...defaultArgs, currentPage: "payment-entry", productDetails: { ...product, subscriptionOptions: { ...product.subscriptionOptions, [subscriptionOptionWithTrial.id]: subscriptionOptionWithTrial, }, }, purchaseOptionToUse: subscriptionOptionWithTrial, defaultPurchaseOption: subscriptionOptionWithTrial, }} /> <Story name="Loading" args={{ currentPage: "payment-entry-loading" }} /> <Story name="Payment complete" args={{ currentPage: "success" }} /> <Story name="Payment failed" args={{ currentPage: "error" }} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/stripe/stripe-service.ts
TypeScript
import type { Appearance, PaymentIntentResult, SetupIntentResult, Stripe, StripeElementLocale, StripeElements, StripeError, } from "@stripe/stripe-js"; import { loadStripe } from "@stripe/stripe-js"; import type { BrandingInfoResponse } from "../networking/responses/branding-response"; import { Theme } from "../ui/theme/theme"; import { DEFAULT_TEXT_STYLES } from "../ui/theme/text"; import type { GatewayParams, StripeElementsConfiguration, } from "../networking/responses/stripe-elements"; export class StripeService { private static FORM_VALIDATED_CARD_ERROR_CODES = [ "card_declined", "expired_card", "incorrect_cvc", "incorrect_number", ]; static async initializeStripe( gatewayParams: GatewayParams, brandingInfo: BrandingInfoResponse | null, localeToUse: StripeElementLocale, stripeVariables: Appearance["variables"], viewport: "mobile" | "desktop", ) { const stripePk = gatewayParams.publishable_api_key; const stripeAcctId = gatewayParams.stripe_account_id; const elementsConfiguration = gatewayParams.elements_configuration; if (!stripePk || !stripeAcctId || !elementsConfiguration) { throw new Error("Stripe configuration is missing"); } const stripe = await loadStripe(stripePk, { stripeAccount: stripeAcctId, }); if (!stripe) { throw new Error("Stripe client not found"); } const theme = new Theme(brandingInfo?.appearance); const customShape = theme.shape; const customColors = theme.formColors; const textStyles = theme.textStyles; const baseFontSize = DEFAULT_TEXT_STYLES.body1[viewport].fontSize || DEFAULT_TEXT_STYLES.body1["mobile"].fontSize; const elements = stripe.elements({ loader: "always", locale: localeToUse, appearance: { theme: "stripe", labels: "floating", variables: { borderRadius: customShape["input-border-radius"], fontLineHeight: "10px", focusBoxShadow: "none", colorDanger: customColors["error"], colorTextPlaceholder: customColors["grey-text-light"], colorText: customColors["grey-text-dark"], colorTextSecondary: customColors["grey-text-light"], fontSizeBase: baseFontSize, ...stripeVariables, }, rules: { ".Input": { boxShadow: "none", paddingTop: "6px", paddingBottom: "6px", fontSize: baseFontSize, border: `1px solid ${customColors["grey-ui-dark"]}`, backgroundColor: customColors["input-background"], color: customColors["grey-text-dark"], }, ".Input:focus": { border: `1px solid ${customColors["focus"]}`, outline: "none", }, ".Label": { fontWeight: textStyles.body1[viewport].fontWeight, lineHeight: "22px", color: customColors["grey-text-dark"], }, ".Label--floating": { opacity: "1", }, ".Input--invalid": { boxShadow: "none", }, ".TermsText": { fontSize: textStyles.caption[viewport].fontSize, lineHeight: textStyles.caption[viewport].lineHeight, }, ".Tab": { boxShadow: "none", backgroundColor: "transparent", color: customColors["grey-text-light"], border: `1px solid ${customColors["grey-ui-dark"]}`, }, ".Tab:hover, .Tab:focus, .Tab--selected, .Tab--selected:hover, .Tab--selected:focus": { boxShadow: "none", color: customColors["grey-text-dark"], }, ".Tab:focus, .Tab--selected, .Tab--selected:hover, .Tab--selected:focus": { border: `1px solid ${customColors["focus"]}`, }, ".TabIcon": { fill: customColors["grey-text-light"], }, ".TabIcon--selected": { fill: customColors["grey-text-dark"], }, ".Block": { boxShadow: "none", backgroundColor: "transparent", border: `1px solid ${customColors["grey-ui-dark"]}`, }, }, }, }); await this.updateElementsConfiguration(elements, elementsConfiguration); return { stripe, elements }; } static async updateElementsConfiguration( elements: StripeElements, elementsConfiguration: StripeElementsConfiguration, ) { await elements.update({ mode: elementsConfiguration.mode, paymentMethodTypes: elementsConfiguration.payment_method_types, setupFutureUsage: elementsConfiguration.setup_future_usage, amount: elementsConfiguration.amount, currency: elementsConfiguration.currency, }); } static isStripeHandledCardError(error: StripeError) { if ( error.type === "card_error" && error.code && this.FORM_VALIDATED_CARD_ERROR_CODES.includes(error.code) ) { return true; } return false; } static createPaymentElement( elements: StripeElements, appName?: string | null, ) { return elements.create("payment", { business: appName ? { name: appName } : undefined, layout: { type: "tabs", }, terms: { applePay: "never", auBecsDebit: "never", bancontact: "never", card: "never", cashapp: "never", googlePay: "never", ideal: "never", paypal: "never", sepaDebit: "never", sofort: "never", usBankAccount: "never", }, }); } static async confirmIntent( stripe: Stripe, elements: StripeElements, clientSecret: string, confirmationTokenId?: string, ): Promise<StripeError | undefined> { const baseOptions = { clientSecret, redirect: "if_required" as const, }; const confirmOptions = confirmationTokenId ? { ...baseOptions, confirmParams: { confirmation_token: confirmationTokenId }, } : { ...baseOptions, elements: elements, }; const isSetupIntent = clientSecret.startsWith("seti_"); let result: SetupIntentResult | PaymentIntentResult | undefined; if (isSetupIntent) { result = await stripe.confirmSetup(confirmOptions); } else { result = await stripe.confirmPayment(confirmOptions); } return result?.error; } }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/base.purchases_test.ts
TypeScript
import { Purchases } from "../main"; import { setupServer } from "msw/node"; import { APIGetRequest, APIPostRequest, getRequestHandlers, } from "./test-responses"; import { afterAll, beforeAll, beforeEach } from "vitest"; export const testApiKey = "rcb_test_api_key"; export const testUserId = "someAppUserId"; export const server = setupServer(...getRequestHandlers()); beforeAll(() => { server.listen(); }); beforeEach(() => { APIGetRequest.mockReset(); APIPostRequest.mockReset(); if (Purchases.isConfigured()) { Purchases.getSharedInstance().close(); } }); afterAll(() => server.close()); export function configurePurchases(appUserId: string = testUserId): Purchases { return Purchases.configure(testApiKey, appUserId); }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/behavioral-events/events-tracker.test.ts
TypeScript
import { afterEach, beforeEach, describe, expect, vi } from "vitest"; import { server, testApiKey } from "../base.purchases_test"; import { APIPostRequest, eventsURL } from "../test-responses"; import { http, HttpResponse } from "msw"; import "../utils/to-have-been-called-exactly-once-with"; import { Logger } from "../../helpers/logger"; import EventsTracker from "../../behavioural-events/events-tracker"; interface EventsTrackerFixtures { eventsTracker: EventsTracker; } vi.mock("../../behavioural-events/sdk-event-context", () => ({ buildEventContext: vi.fn().mockReturnValue({ library_name: "purchases-js", library_version: "1.0.0", }), })); const MAX_JITTER_MULTIPLIER = 1 + 0.1; describe("EventsTracker", (test) => { const date = new Date(1988, 10, 18, 13, 37, 0); vi.mock("uuid", () => ({ v4: () => "c1365463-ce59-4b83-b61b-ef0d883e9047", })); const loggerMock = vi .spyOn(Logger, "debugLog") .mockImplementation(() => undefined); beforeEach<EventsTrackerFixtures>((context) => { context.eventsTracker = new EventsTracker({ apiKey: testApiKey, appUserId: "someAppUserId", }); vi.useFakeTimers(); vi.setSystemTime(date); }); afterEach<EventsTrackerFixtures>((context) => { loggerMock.mockReset(); vi.useRealTimers(); context.eventsTracker.dispose(); }); test("does not track event if silent", async () => { const eventsTracker = new EventsTracker({ apiKey: testApiKey, appUserId: "someAppUserId", silent: true, }); eventsTracker.trackExternalEvent({ eventName: "external", source: "sdk", properties: { a: "b", b: 1, c: false, d: null, }, }); await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).not.toBeCalled(); }); test<EventsTrackerFixtures>("sends the serialized event", async ({ eventsTracker, }) => { eventsTracker.trackExternalEvent({ eventName: "external", source: "sdk", properties: { a: "b", b: 1, c: false, d: null, }, }); await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenCalledWith({ url: eventsURL, json: { events: [ { id: "c1365463-ce59-4b83-b61b-ef0d883e9047", type: "web_billing", timestamp_ms: date.getTime(), event_name: "external", app_user_id: "someAppUserId", context: { library_name: "purchases-js", library_version: "1.0.0", }, properties: { trace_id: "c1365463-ce59-4b83-b61b-ef0d883e9047", a: "b", b: 1, c: false, d: null, }, }, ], }, }); }); test<EventsTrackerFixtures>("passes the user props to the event", async ({ eventsTracker, }) => { eventsTracker.updateUser("newAppUserId"); eventsTracker.trackExternalEvent({ eventName: "external", source: "sdk", properties: { a: "b" }, }); await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenCalledWith( expect.objectContaining({ json: expect.objectContaining({ events: expect.arrayContaining([ expect.objectContaining({ app_user_id: "newAppUserId", }), ]), }), }), ); }); test<EventsTrackerFixtures>("passes the checkout trace id to the event", async ({ eventsTracker, }) => { eventsTracker.trackExternalEvent({ eventName: "external", source: "sdk", }); await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenCalledWith( expect.objectContaining({ json: expect.objectContaining({ events: expect.arrayContaining([ expect.objectContaining({ properties: expect.objectContaining({ trace_id: expect.any(String), }), }), ]), }), }), ); }); test<EventsTrackerFixtures>("retries tracking events exponentially", async ({ eventsTracker, }) => { let attempts = 0; const successFlushMock = vi.fn(); server.use( http.post(eventsURL, async ({ request }) => { ++attempts; switch (attempts) { case 1: return new HttpResponse(null, { status: 500 }); case 2: await new Promise((resolve) => setTimeout(resolve, 1_000)); throw new Error("Unexpected error"); case 3: await new Promise((resolve) => setTimeout(resolve, 20_000)); throw new Error("Unexpected error"); case 4: successFlushMock(); return HttpResponse.json(await request.json(), { status: 201 }); default: throw new Error("Unexpected call"); } }), ); eventsTracker.trackExternalEvent({ eventName: "external", source: "sdk", }); // Attempt 1: First direct attempt to flush without timeout await vi.advanceTimersByTimeAsync(100); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 2: Wait for next flush await vi.advanceTimersByTimeAsync(2_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 2: Wait for request to complete await vi.advanceTimersByTimeAsync(1_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 3: Wait for next flush await vi.advanceTimersByTimeAsync(4_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 3: Wait for request to complete await vi.advanceTimersByTimeAsync(20_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 4: Wait for next flush await vi.advanceTimersByTimeAsync(8_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).toHaveBeenCalled(); }); test<EventsTrackerFixtures>("retries tracking events accumulating them if there are errors", async ({ eventsTracker, }) => { let attempts = 0; const successFlushMock = vi.fn(); server.use( http.post(eventsURL, async ({ request }) => { ++attempts; if (attempts < 4) { return new HttpResponse(null, { status: 500 }); } const json = (await request.json()) as Record<string, Array<unknown>>; if (json.events?.length === 4) { successFlushMock(); return HttpResponse.json(json, { status: 201 }); } return new HttpResponse(null, { status: 500 }); }), ); for (let i = 0; i < 4; i++) { eventsTracker.trackExternalEvent({ eventName: "external", source: "wpl", }); } await vi.advanceTimersByTimeAsync( 1000 * MAX_JITTER_MULTIPLIER + 2000 * MAX_JITTER_MULTIPLIER + 4000 * MAX_JITTER_MULTIPLIER + 8000 * MAX_JITTER_MULTIPLIER, ); expect(successFlushMock).toHaveBeenCalled(); }); test<EventsTrackerFixtures>("retries tracking events exponentially", async ({ eventsTracker, }) => { let attempts = 0; const successFlushMock = vi.fn(); server.use( http.post(eventsURL, async ({ request }) => { ++attempts; switch (attempts) { case 1: return new HttpResponse(null, { status: 500 }); case 2: await new Promise((resolve) => setTimeout(resolve, 1_000)); throw new Error("Unexpected error"); case 3: await new Promise((resolve) => setTimeout(resolve, 20_000)); throw new Error("Unexpected error"); case 4: successFlushMock(); return HttpResponse.json(await request.json(), { status: 201 }); default: throw new Error("Unexpected call"); } }), ); eventsTracker.trackExternalEvent({ eventName: "external", source: "wpl", }); // Attempt 1: First direct attempt to flush without timeout await vi.advanceTimersByTimeAsync(100 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 2: Wait for next flush await vi.advanceTimersByTimeAsync(2_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 2: Wait for request to complete await vi.advanceTimersByTimeAsync(1_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 3: Wait for next flush await vi.advanceTimersByTimeAsync(4_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 3: Wait for request to complete await vi.advanceTimersByTimeAsync(20_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).not.toHaveBeenCalled(); loggerMock.mockClear(); // Attempt 4: Wait for next flush await vi.advanceTimersByTimeAsync(8_000 * MAX_JITTER_MULTIPLIER); expect(successFlushMock).toHaveBeenCalled(); }); test<EventsTrackerFixtures>("does not lose events due to race conditions on the request", async ({ eventsTracker, }) => { const eventPayloadSpy = vi.fn(); let attempts = 0; server.use( http.post(eventsURL, async ({ request }) => { ++attempts; const json = await request.json(); eventPayloadSpy(json); if (attempts === 1) { setTimeout( () => eventsTracker.trackExternalEvent({ eventName: "external2", properties: { a: "b" }, source: "other", }), 1_000, ); await new Promise((resolve) => setTimeout(resolve, 10_000)); return new HttpResponse(null, { status: 201 }); } return HttpResponse.json(null, { status: 201 }); }), ); eventsTracker.trackExternalEvent({ eventName: "external1", source: "wpl", }); await vi.runAllTimersAsync(); expect(eventPayloadSpy).toHaveBeenNthCalledWith(1, { events: expect.arrayContaining([ expect.objectContaining({ event_name: "external1", timestamp_ms: date.getTime(), }), ]), }); expect(eventPayloadSpy).toHaveBeenNthCalledWith(2, { events: expect.arrayContaining([ expect.objectContaining({ event_name: "external2", timestamp_ms: date.getTime() + 1_000, }), ]), }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/behavioral-events/flush-manager.test.ts
TypeScript
import { afterEach, beforeEach, expect, test, vi } from "vitest"; import { describe, type MockedFunction } from "vitest"; import { FlushManager } from "../../behavioural-events/flush-manager"; describe("FlushManager", () => { let callbackSpy: MockedFunction<() => Promise<void>>; let flushManager: FlushManager; beforeEach(() => { vi.useFakeTimers(); callbackSpy = vi.fn().mockReturnValue(Promise.resolve()); flushManager = new FlushManager(1_000, 10_000, 0, callbackSpy); }); afterEach(() => { flushManager.stop(); vi.useRealTimers(); }); test("expedites the callback when not backing off", async () => { flushManager.tryFlush(); await vi.advanceTimersToNextTimerAsync(); flushManager.tryFlush(); await vi.advanceTimersToNextTimerAsync(); flushManager.tryFlush(); await vi.advanceTimersToNextTimerAsync(); expect(callbackSpy).toHaveBeenCalledTimes(3); }); test("does not expedite the callback when it is backing off", async () => { callbackSpy.mockReturnValue(Promise.reject(new Error("Mocked error"))); flushManager.tryFlush(); expect(callbackSpy).toHaveBeenCalledTimes(1); callbackSpy.mockClear(); flushManager.tryFlush(); await vi.advanceTimersByTimeAsync(500); expect(callbackSpy).not.toHaveBeenCalled(); }); test("reschedules the callback when it is already running adding jitter", async () => { callbackSpy.mockReturnValueOnce( new Promise((resolve) => setTimeout(() => resolve(), 10_000)), ); callbackSpy.mockReturnValueOnce(Promise.resolve()); // Immediate flush flushManager.tryFlush(); expect(callbackSpy).toHaveBeenCalledTimes(1); callbackSpy.mockClear(); // Scheduled flush flushManager.tryFlush(); await vi.advanceTimersByTimeAsync(1_000); expect(callbackSpy).not.toHaveBeenCalled(); callbackSpy.mockClear(); await vi.advanceTimersByTimeAsync(9_000); expect(callbackSpy).toHaveBeenCalledTimes(1); }); test("should increase delay exponentially when erroring repeatedly", async () => { callbackSpy.mockImplementation(() => { throw new Error("Mocked error"); }); flushManager.tryFlush(); await vi.advanceTimersByTimeAsync(1_000 + 2_000 + 4_000 + 8_000 + 16_000); expect(callbackSpy).toHaveBeenCalledTimes(6); }); test("should respect maxDelay when backoff is called", async () => { callbackSpy.mockImplementation(() => { throw new Error("Mocked error"); }); flushManager.tryFlush(); await vi.advanceTimersByTimeAsync( 1_000 + 2_000 + 4_000 + 8_000 + 10_000 + 10_000 + 10_000 + 10_000, ); expect(callbackSpy).toHaveBeenCalledTimes(9); }); test("should reset to initial delay when callback succeeds", async () => { callbackSpy.mockImplementationOnce(() => { throw new Error("Mocked error"); }); callbackSpy.mockImplementationOnce(() => { throw new Error("Mocked Error"); }); callbackSpy.mockImplementationOnce(() => { throw new Error("Mocked Error"); }); flushManager.tryFlush(); await vi.advanceTimersByTimeAsync(1000 + 2_000 + 4_000); expect(callbackSpy).toHaveBeenCalledTimes(4); }); test("adds jitter to the delay", async () => { const mathRandomSpy = vi.spyOn(Math, "random").mockReturnValue(1); flushManager = new FlushManager(1_000, 10_000, 0.1, callbackSpy); // Immediate flush flushManager.tryFlush(); expect(callbackSpy).toHaveBeenCalledTimes(1); callbackSpy.mockClear(); // Scheduled flush flushManager.tryFlush(); await vi.advanceTimersByTimeAsync(1_000); expect(callbackSpy).not.toHaveBeenCalled(); // Scheduled flush adding jitter flushManager.tryFlush(); await vi.advanceTimersByTimeAsync(101); expect(callbackSpy).toHaveBeenCalledTimes(1); mathRandomSpy.mockRestore(); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/behavioral-events/sdk-event-context.test.ts
TypeScript
import { buildEventContext } from "../../behavioural-events/sdk-event-context"; import { VERSION } from "../../helpers/constants"; import { beforeAll, describe, expect, it } from "vitest"; describe("buildEventContext", () => { beforeAll(() => { // Mocking global objects Object.defineProperty(window, "location", { value: { search: "?utm_source=google&utm_medium=cpc&utm_campaign=spring_sale", pathname: "/home", origin: "https://example.com", }, writable: true, }); Object.defineProperty(document, "referrer", { value: "https://referrer.com", writable: true, }); Object.defineProperty(document, "title", { value: "Example Page", writable: true, }); Object.defineProperty(navigator, "language", { value: "en-US", writable: true, }); Object.defineProperty(navigator, "userAgent", { value: "Mozilla/5.0", writable: true, }); Object.defineProperty(Intl.DateTimeFormat.prototype, "resolvedOptions", { value: () => ({ timeZone: "America/New_York" }), writable: true, }); Object.defineProperty(screen, "width", { value: 1920, writable: true, }); Object.defineProperty(screen, "height", { value: 1080, writable: true, }); }); it("should build the correct event context", () => { const context = buildEventContext("sdk"); expect(context).toEqual({ libraryName: "purchases-js", libraryVersion: VERSION, locale: "en-US", userAgent: "Mozilla/5.0", timeZone: "America/New_York", screenWidth: 1920, screenHeight: 1080, utmSource: "google", utmMedium: "cpc", utmCampaign: "spring_sale", utmContent: null, utmTerm: null, pageReferrer: "https://referrer.com", pageUrl: "https://example.com/home", pageTitle: "Example Page", source: "sdk", }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/entities/customer-info.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { type SubscriberResponse } from "../../networking/responses/subscriber-response"; import { type CustomerInfo, toCustomerInfo, } from "../../entities/customer-info"; describe("customer info parsing", () => { test("subscriber info with no purchases is parsed correctly", () => { const subscriberResponse: SubscriberResponse = { request_date: "2024-01-31T15:08:05Z", request_date_ms: 1706713685064, subscriber: { entitlements: {}, first_seen: "2024-01-23T13:22:12Z", last_seen: "2024-01-24T16:12:11Z", management_url: null, non_subscriptions: {}, original_app_user_id: "someUserTestToni6", original_application_version: null, original_purchase_date: null, other_purchases: {}, subscriptions: {}, }, }; const expectedCustomerInfo: CustomerInfo = { activeSubscriptions: new Set(), allExpirationDatesByProduct: {}, allPurchaseDatesByProduct: {}, entitlements: { active: {}, all: {}, }, firstSeenDate: new Date("2024-01-23T13:22:12.000Z"), managementURL: null, originalAppUserId: "someUserTestToni6", originalPurchaseDate: null, requestDate: new Date("2024-01-31T15:08:05.000Z"), }; const customerInfo = toCustomerInfo(subscriberResponse); expect(customerInfo).toEqual(expectedCustomerInfo); }); test("subscriber info with rc-billing subscription purchase is parsed correctly", () => { const subscriberResponse: SubscriberResponse = { request_date: "2024-01-31T15:10:21Z", request_date_ms: 1706713821860, subscriber: { entitlements: { catServices: { expires_date: "2124-02-07T13:46:23Z", grace_period_expires_date: null, product_identifier: "weekly_test", purchase_date: "2024-01-31T13:46:23Z", }, }, first_seen: "2024-01-23T13:22:12Z", last_seen: "2024-01-29T15:40:09Z", management_url: null, non_subscriptions: {}, original_app_user_id: "someUserTestToni6", original_application_version: null, original_purchase_date: null, other_purchases: {}, subscriptions: { weekly_test: { auto_resume_date: null, billing_issues_detected_at: null, expires_date: "2124-02-07T13:46:23Z", grace_period_expires_date: null, is_sandbox: true, original_purchase_date: "2024-01-24T13:46:23Z", period_type: "normal", purchase_date: "2024-01-31T13:46:23Z", refunded_at: null, store: "rc_billing", store_transaction_id: "txRcb1486347e9afce2143eec187a781f82e8..1706708783", unsubscribe_detected_at: null, }, }, }, }; const expectedCustomerInfo: CustomerInfo = { activeSubscriptions: new Set(["weekly_test"]), allExpirationDatesByProduct: { weekly_test: new Date("2124-02-07T13:46:23.000Z"), }, allPurchaseDatesByProduct: { weekly_test: new Date("2024-01-31T13:46:23.000Z"), }, entitlements: { active: { catServices: { billingIssueDetectedAt: null, expirationDate: new Date("2124-02-07T13:46:23.000Z"), identifier: "catServices", isActive: true, isSandbox: true, latestPurchaseDate: new Date("2024-01-31T13:46:23Z"), originalPurchaseDate: new Date("2024-01-31T13:46:23.000Z"), periodType: "normal", productIdentifier: "weekly_test", store: "rc_billing", unsubscribeDetectedAt: null, willRenew: true, }, }, all: { catServices: { billingIssueDetectedAt: null, expirationDate: new Date("2124-02-07T13:46:23.000Z"), identifier: "catServices", isActive: true, isSandbox: true, latestPurchaseDate: new Date("2024-01-31T13:46:23Z"), originalPurchaseDate: new Date("2024-01-31T13:46:23.000Z"), periodType: "normal", productIdentifier: "weekly_test", store: "rc_billing", unsubscribeDetectedAt: null, willRenew: true, }, }, }, firstSeenDate: new Date("2024-01-23T13:22:12.000Z"), managementURL: null, originalAppUserId: "someUserTestToni6", originalPurchaseDate: null, requestDate: new Date("2024-01-31T15:10:21.000Z"), }; const customerInfo = toCustomerInfo(subscriberResponse); expect(customerInfo).toEqual(expectedCustomerInfo); }); test("subscriber info with other store subscription purchase is parsed correctly", () => { const subscriberResponse: SubscriberResponse = { request_date: "2019-08-16T10:30:42Z", request_date_ms: 1565951442879, subscriber: { original_app_user_id: "app_user_id", original_application_version: "2083", first_seen: "2019-06-17T16:05:33Z", original_purchase_date: "2019-07-26T23:30:41Z", non_subscriptions: { "100_coins_pack": [ { id: "72c26cc69c", is_sandbox: true, original_purchase_date: "1990-08-30T02:40:36Z", purchase_date: "1990-08-30T02:40:36Z", store: "app_store", }, { id: "6229b0bef1", is_sandbox: true, original_purchase_date: "2019-11-06T03:26:15Z", purchase_date: "2019-11-06T03:26:15Z", store: "play_store", }, ], "7_extra_lives": [ { id: "d6c007ba74", is_sandbox: true, original_purchase_date: "2019-07-11T18:36:20Z", purchase_date: "2019-07-11T18:36:20Z", store: "play_store", }, { id: "5b9ba226bc", is_sandbox: true, original_purchase_date: "2019-07-26T22:10:27Z", purchase_date: "2019-07-26T22:10:27Z", store: "app_store", }, ], lifetime_access: [ { id: "b6c007ba74", is_sandbox: true, original_purchase_date: "2019-09-11T18:36:20Z", purchase_date: "2019-09-11T18:36:20Z", store: "play_store", }, ], }, subscriptions: { pro: { billing_issues_detected_at: null, is_sandbox: true, original_purchase_date: "2019-07-26T23:30:41Z", purchase_date: "2019-07-26T23:45:40Z", product_plan_identifier: "monthly", store: "app_store", unsubscribe_detected_at: null, expires_date: "2100-04-06T20:54:45.975000Z", period_type: "normal", }, basic: { billing_issues_detected_at: null, is_sandbox: true, original_purchase_date: "2019-07-26T23:30:41Z", purchase_date: "2019-07-26T23:45:40Z", product_plan_identifier: "monthly", store: "app_store", unsubscribe_detected_at: null, period_type: "normal", expires_date: "1990-08-30T02:40:36Z", }, }, entitlements: { pro: { expires_date: "2100-04-06T20:54:45.975000Z", product_identifier: "pro", product_plan_identifier: "monthly", purchase_date: "2018-10-26T23:17:53Z", }, basic: { expires_date: "1990-08-30T02:40:36Z", product_identifier: "basic", product_plan_identifier: "monthly", purchase_date: "1990-06-30T02:40:36Z", }, forever_pro: { expires_date: null, product_identifier: "lifetime_access", purchase_date: "2019-09-11T18:36:20Z", }, }, management_url: "https://play.google.com/store/account/subscriptions", }, }; const expectedCustomerInfo: CustomerInfo = { activeSubscriptions: new Set(["pro"]), allExpirationDatesByProduct: { pro: new Date("2100-04-06T20:54:45.975000Z"), basic: new Date("1990-08-30T02:40:36Z"), }, allPurchaseDatesByProduct: { "100_coins_pack": new Date("2019-11-06T03:26:15.000Z"), "7_extra_lives": new Date("2019-07-26T22:10:27.000Z"), lifetime_access: new Date("2019-09-11T18:36:20.000Z"), pro: new Date("2019-07-26T23:45:40.000Z"), basic: new Date("2019-07-26T23:45:40.000Z"), }, entitlements: { active: { forever_pro: { billingIssueDetectedAt: null, expirationDate: null, identifier: "forever_pro", isActive: true, isSandbox: true, latestPurchaseDate: new Date("2019-09-11T18:36:20.000Z"), originalPurchaseDate: new Date("2019-09-11T18:36:20.000Z"), periodType: "normal", productIdentifier: "lifetime_access", store: "play_store", unsubscribeDetectedAt: null, willRenew: false, }, pro: { billingIssueDetectedAt: null, expirationDate: new Date("2100-04-06T20:54:45.975Z"), identifier: "pro", isActive: true, isSandbox: true, latestPurchaseDate: new Date("2018-10-26T23:17:53.000Z"), originalPurchaseDate: new Date("2018-10-26T23:17:53.000Z"), periodType: "normal", productIdentifier: "pro", store: "app_store", unsubscribeDetectedAt: null, willRenew: true, }, }, all: { basic: { billingIssueDetectedAt: null, expirationDate: new Date("1990-08-30T02:40:36.000Z"), identifier: "basic", isActive: false, isSandbox: true, latestPurchaseDate: new Date("1990-06-30T02:40:36.000Z"), originalPurchaseDate: new Date("1990-06-30T02:40:36.000Z"), periodType: "normal", productIdentifier: "basic", store: "app_store", unsubscribeDetectedAt: null, willRenew: true, }, forever_pro: { billingIssueDetectedAt: null, expirationDate: null, identifier: "forever_pro", isActive: true, isSandbox: true, latestPurchaseDate: new Date("2019-09-11T18:36:20.000Z"), originalPurchaseDate: new Date("2019-09-11T18:36:20.000Z"), periodType: "normal", productIdentifier: "lifetime_access", store: "play_store", unsubscribeDetectedAt: null, willRenew: false, }, pro: { billingIssueDetectedAt: null, expirationDate: new Date("2100-04-06T20:54:45.975Z"), identifier: "pro", isActive: true, isSandbox: true, latestPurchaseDate: new Date("2018-10-26T23:17:53.000Z"), originalPurchaseDate: new Date("2018-10-26T23:17:53.000Z"), periodType: "normal", productIdentifier: "pro", store: "app_store", unsubscribeDetectedAt: null, willRenew: true, }, }, }, firstSeenDate: new Date("2019-06-17T16:05:33.000Z"), managementURL: "https://play.google.com/store/account/subscriptions", originalAppUserId: "app_user_id", originalPurchaseDate: new Date("2019-07-26T23:30:41.000Z"), requestDate: new Date("2019-08-16T10:30:42.000Z"), }; const customerInfo = toCustomerInfo(subscriberResponse); expect(customerInfo).toEqual(expectedCustomerInfo); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/duration-helper.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { getNextRenewalDate, parseISODuration, type Period, PeriodUnit, } from "../../helpers/duration-helper"; describe("parseISODuration", () => { test("should parse a valid ISO 8601 yearly duration", () => { const duration = "P1Y"; const period = parseISODuration(duration); expect(period).toEqual({ number: 1, unit: PeriodUnit.Year }); }); test("should parse a valid ISO 8601 monthly duration", () => { const duration = "P3M"; const period = parseISODuration(duration); expect(period).toEqual({ number: 3, unit: PeriodUnit.Month }); }); test("should parse a valid ISO 8601 weekly duration", () => { const duration = "P1W"; const period = parseISODuration(duration); expect(period).toEqual({ number: 1, unit: PeriodUnit.Week }); }); test("should parse a valid ISO 8601 daily duration", () => { const duration = "P14D"; const period = parseISODuration(duration); expect(period).toEqual({ number: 14, unit: PeriodUnit.Day }); }); test("should fail with multiple durations but valid ISO 8601 duration", () => { const duration = "P1Y3M"; const period = parseISODuration(duration); expect(period).toBeNull(); }); test("should fail with invalid ISO 8601 duration", () => { const duration = "P3MM"; const period = parseISODuration(duration); expect(period).toBeNull(); }); }); describe("getNextRenewalDate", () => { test("should return null if willRenew is false", () => { const startDate = new Date(2025, 1, 24); const period: Period = { unit: PeriodUnit.Month, number: 1 }; expect(getNextRenewalDate(startDate, period, false)).toBeNull(); }); test("should correctly add years to the date", () => { const startDate = new Date(2025, 1, 24); const period: Period = { unit: PeriodUnit.Year, number: 2 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2027, 1, 24), ); }); test("should correctly add months to the date", () => { const startDate = new Date(2025, 0, 31); const period: Period = { unit: PeriodUnit.Month, number: 1 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2025, 1, 28), ); // Handle month-end cases }); test("should correctly add weeks to the date", () => { const startDate = new Date(2025, 1, 24); const period: Period = { unit: PeriodUnit.Week, number: 2 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2025, 2, 10), ); }); test("should correctly add days to the date", () => { const startDate = new Date(2025, 1, 24); const period: Period = { unit: PeriodUnit.Day, number: 10 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2025, 2, 6), ); }); test("should handle leap years correctly", () => { const startDate = new Date(2024, 1, 29); // Leap year date const period: Period = { unit: PeriodUnit.Year, number: 1 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2025, 1, 28), ); }); test("should handle repeated leap years correctly", () => { const startDate = new Date(2024, 1, 29); // Leap year date const period: Period = { unit: PeriodUnit.Year, number: 4 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2028, 1, 29), ); }); test("should handle edge cases for month increments", () => { const startDate = new Date(2025, 0, 31); const period: Period = { unit: PeriodUnit.Month, number: 1 }; expect(getNextRenewalDate(startDate, period, true)).toEqual( new Date(2025, 1, 28), ); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/paywall-variables-helper.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { parseOfferingIntoVariables } from "../../helpers/paywall-variables-helpers"; import type { Offering, SubscriptionOption } from "../../entities/offerings"; import { type VariableDictionary } from "@revenuecat/purchases-ui-js"; import { Translator } from "../../ui/localization/translator"; import { englishLocale } from "../../ui/localization/constants"; const monthlyProduct = { identifier: "test_multicurrency_all_currencies", displayName: "Mario", title: "Mario", description: "Just the best for Italian supercalifragilisticexpialidocious plumbers, groom them on a monthly basis", productType: "subscription", currentPrice: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "MultiCurrencyTest", presentedOfferingContext: { offeringIdentifier: "MultiCurrencyTest", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: { id: "base_option", priceId: "prcb358d16d7b7744bb8ab0", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, defaultSubscriptionOption: { id: "base_option", priceId: "prcb358d16d7b7744bb8ab0", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, subscriptionOptions: { base_option: { id: "base_option", priceId: "prcb358d16d7b7744bb8ab0", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, }, defaultNonSubscriptionOption: null, }; const weeklyProduct = { identifier: "luigis_weekly", displayName: "Luigi Special", title: "Luigi Special", description: "A fresh alternative to the Mario's, clean them up every week", productType: "subscription", currentPrice: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, normalPeriodDuration: "P1W", presentedOfferingIdentifier: "MultiCurrencyTest", presentedOfferingContext: { offeringIdentifier: "MultiCurrencyTest", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: { id: "base_option", priceId: "prca9ad8d30922442b58e05", base: { periodDuration: "P1W", period: { number: 1, unit: "week", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, defaultSubscriptionOption: { id: "base_option", priceId: "prca9ad8d30922442b58e05", base: { periodDuration: "P1W", period: { number: 1, unit: "week", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, subscriptionOptions: { base_option: { id: "base_option", priceId: "prca9ad8d30922442b58e05", base: { periodDuration: "P1W", period: { number: 1, unit: "week", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, }, defaultNonSubscriptionOption: null, }; const trialProduct = { identifier: "mario_with_trial", displayName: "Trial Mario", title: "Trial Mario", description: "Mario with a trial", productType: "subscription", currentPrice: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "MultiCurrencyTest", presentedOfferingContext: { offeringIdentifier: "MultiCurrencyTest", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: { id: "offerbd69715c768244238f6b6acc84c85c4c", priceId: "prc028090d2f0cd45b08559", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, }, trial: { periodDuration: "P2W", period: { number: 2, unit: "week", }, cycleCount: 1, price: null, }, } as SubscriptionOption, defaultSubscriptionOption: { id: "offerbd69715c768244238f6b6acc84c85c4c", priceId: "prc028090d2f0cd45b08559", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, }, trial: { periodDuration: "P2W", period: { number: 2, unit: "week", }, cycleCount: 1, price: null, }, } as SubscriptionOption, subscriptionOptions: { offerbd69715c768244238f6b6acc84c85c4c: { id: "offerbd69715c768244238f6b6acc84c85c4c", priceId: "prc028090d2f0cd45b08559", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, }, trial: { periodDuration: "P2W", period: { number: 2, unit: "week", }, cycleCount: 1, price: null, }, }, }, defaultNonSubscriptionOption: null, }; const trialProduct900 = { identifier: "mario_with_trial", displayName: "Trial Mario", title: "Trial Mario", description: "Mario with a trial", productType: "subscription", currentPrice: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "MultiCurrencyTest", presentedOfferingContext: { offeringIdentifier: "MultiCurrencyTest", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: { id: "offerbd69715c768244238f6b6acc84c85c4c", priceId: "prc028090d2f0cd45b08559", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, }, trial: { periodDuration: "P2W", period: { number: 2, unit: "week", }, cycleCount: 1, price: null, }, } as SubscriptionOption, defaultSubscriptionOption: { id: "offerbd69715c768244238f6b6acc84c85c4c", priceId: "prc028090d2f0cd45b08559", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, }, trial: { periodDuration: "P2W", period: { number: 2, unit: "week", }, cycleCount: 1, price: null, }, } as SubscriptionOption, subscriptionOptions: { offerbd69715c768244238f6b6acc84c85c4c: { id: "offerbd69715c768244238f6b6acc84c85c4c", priceId: "prc028090d2f0cd45b08559", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 3000, amountMicros: 30000000, currency: "EUR", formattedPrice: "€30.00", }, }, trial: { periodDuration: "P2W", period: { number: 2, unit: "week", }, cycleCount: 1, price: null, }, }, }, defaultNonSubscriptionOption: null, }; const monthlyProduct300 = { identifier: "test_multicurrency_all_currencies", displayName: "Mario", title: "Mario", description: "Just the best for Italian supercalifragilisticexpialidocious plumbers, groom them on a monthly basis", productType: "subscription", currentPrice: { amount: 300, amountMicros: 3000000, currency: "EUR", formattedPrice: "€3.00", }, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "MultiCurrencyTest", presentedOfferingContext: { offeringIdentifier: "MultiCurrencyTest", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: { id: "base_option", priceId: "prcb358d16d7b7744bb8ab0", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, defaultSubscriptionOption: { id: "base_option", priceId: "prcb358d16d7b7744bb8ab0", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, subscriptionOptions: { base_option: { id: "base_option", priceId: "prcb358d16d7b7744bb8ab0", base: { periodDuration: "P1M", period: { number: 1, unit: "month", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, }, defaultNonSubscriptionOption: null, }; const weeklyProduct600 = { identifier: "luigis_weekly", displayName: "Luigi Special", title: "Luigi Special", description: "A fresh alternative to the Mario's, clean them up every week", productType: "subscription", currentPrice: { amount: 600, amountMicros: 6000000, currency: "EUR", formattedPrice: "€6.00", }, normalPeriodDuration: "P1W", presentedOfferingIdentifier: "MultiCurrencyTest", presentedOfferingContext: { offeringIdentifier: "MultiCurrencyTest", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: { id: "base_option", priceId: "prca9ad8d30922442b58e05", base: { periodDuration: "P1W", period: { number: 1, unit: "week", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, defaultSubscriptionOption: { id: "base_option", priceId: "prca9ad8d30922442b58e05", base: { periodDuration: "P1W", period: { number: 1, unit: "week", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, subscriptionOptions: { base_option: { id: "base_option", priceId: "prca9ad8d30922442b58e05", base: { periodDuration: "P1W", period: { number: 1, unit: "week", }, cycleCount: 1, price: { amount: 900, amountMicros: 9000000, currency: "EUR", formattedPrice: "€9.00", }, }, trial: null, }, }, defaultNonSubscriptionOption: null, }; const offering = { identifier: "MultiCurrencyTest", serverDescription: "Multi currency test Nicola", metadata: null, packagesById: { $rc_monthly: { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, $rc_weekly: { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, trial: { identifier: "trial", rcBillingProduct: trialProduct, webBillingProduct: trialProduct, packageType: "custom", }, }, availablePackages: [ { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, { identifier: "trial", rcBillingProduct: trialProduct, webBillingProduct: trialProduct, packageType: "custom", }, ], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, weekly: { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, paywall_components: null, } as Offering; const samePricePackages = { identifier: "MultiCurrencyTest", serverDescription: "Multi currency test Nicola", metadata: null, packagesById: { $rc_monthly: { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, $rc_weekly: { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, trial: { identifier: "trial", rcBillingProduct: trialProduct, webBillingProduct: trialProduct, packageType: "custom", }, }, availablePackages: [ { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, { identifier: "trial", rcBillingProduct: trialProduct900, webBillingProduct: trialProduct900, packageType: "custom", }, ], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, weekly: { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, paywall_components: null, } as Offering; const differentPricedPackages = { identifier: "MultiCurrencyTest", serverDescription: "Multi currency test Nicola", metadata: null, packagesById: { $rc_monthly: { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, $rc_weekly: { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, trial: { identifier: "trial", rcBillingProduct: trialProduct, webBillingProduct: trialProduct, packageType: "custom", }, }, availablePackages: [ { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct300, webBillingProduct: monthlyProduct300, packageType: "$rc_monthly", }, { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct600, webBillingProduct: weeklyProduct600, packageType: "$rc_weekly", }, { identifier: "trial", rcBillingProduct: trialProduct900, webBillingProduct: trialProduct900, packageType: "custom", }, ], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: { identifier: "$rc_monthly", rcBillingProduct: monthlyProduct, webBillingProduct: monthlyProduct, packageType: "$rc_monthly", }, weekly: { identifier: "$rc_weekly", rcBillingProduct: weeklyProduct, webBillingProduct: weeklyProduct, packageType: "$rc_weekly", }, paywall_components: null, } as Offering; const expectedVariables: Record<string, VariableDictionary> = { $rc_monthly: { price: "€9.00", price_per_period: "€9.00/1mo", price_per_period_full: "€9.00/1month", product_name: "Mario", sub_duration: "1 month", sub_duration_in_months: "1 month", sub_offer_duration: undefined, sub_offer_duration_2: undefined, sub_offer_price: undefined, sub_offer_price_2: undefined, sub_period: "monthly", sub_period_abbreviated: "mo", sub_period_length: "month", sub_price_per_month: "€9.00", sub_price_per_week: "€9.00", sub_relative_discount: "70% off", total_price_and_per_month: "€9.00", total_price_and_per_month_full: "€9.00", }, $rc_weekly: { price: "€9.00", price_per_period: "€9.00/1wk", price_per_period_full: "€9.00/1week", product_name: "Luigi Special", sub_duration: "1 week", sub_duration_in_months: "1 week", sub_offer_duration: undefined, sub_offer_duration_2: undefined, sub_offer_price: undefined, sub_offer_price_2: undefined, sub_period: "weekly", sub_period_abbreviated: "wk", sub_period_length: "week", sub_price_per_month: "€36.00", sub_price_per_week: "€9.00", sub_relative_discount: "70% off", total_price_and_per_month: "€9.00/1wk(€36.00/mo)", total_price_and_per_month_full: "€9.00/1week(€36.00/month)", }, trial: { price: "€30.00", price_per_period: "€30.00/1mo", price_per_period_full: "€30.00/1month", product_name: "Trial Mario", sub_duration: "1 month", sub_duration_in_months: "1 month", sub_offer_duration: undefined, sub_offer_duration_2: undefined, sub_offer_price: undefined, sub_offer_price_2: undefined, sub_period: "monthly", sub_period_abbreviated: "mo", sub_period_length: "month", sub_price_per_month: "€30.00", sub_price_per_week: "€30.00", sub_relative_discount: "", total_price_and_per_month: "€30.00", total_price_and_per_month_full: "€30.00", }, }; const enTranslator = new Translator({}, englishLocale); describe("getPaywallVariables", () => { test("should return expected paywall variables", () => { expect(parseOfferingIntoVariables(offering, enTranslator)).toEqual( expectedVariables, ); }); test("sub_relative_discount is calculated correctly for same-priced packages", () => { const variables = parseOfferingIntoVariables( samePricePackages, enTranslator, ); Object.values(variables).forEach((variable) => expect(variable.sub_relative_discount).toBe(""), ); }); test("sub_relative_discount is calculated correctly for two packages with the same price", () => { const expectedValues = ["67% off", "33% off", ""]; const variables = parseOfferingIntoVariables( differentPricedPackages, enTranslator, ); Object.values(variables).forEach((variable, idx) => expect(variable.sub_relative_discount).toBe(expectedValues[idx]), ); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/price-labels.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { formatPrice, getTranslatedPeriodFrequency, } from "../../helpers/price-labels"; import { Translator } from "../../ui/localization/translator"; describe("getRenewsLabel", () => { const translator: Translator = new Translator(); test("should return correct text for single period durations", () => { expect(getTranslatedPeriodFrequency("P1Y", translator)).toEqual("yearly"); expect(getTranslatedPeriodFrequency("P1M", translator)).toEqual("monthly"); expect(getTranslatedPeriodFrequency("P1W", translator)).toEqual("weekly"); expect(getTranslatedPeriodFrequency("P1D", translator)).toEqual("daily"); }); test("should return correct text for multiple period durations", () => { expect(getTranslatedPeriodFrequency("P2Y", translator)).toEqual( "every 2 years", ); expect(getTranslatedPeriodFrequency("P3M", translator)).toEqual( "every 3 months", ); expect(getTranslatedPeriodFrequency("P2W", translator)).toEqual( "every 2 weeks", ); expect(getTranslatedPeriodFrequency("P14D", translator)).toEqual( "every 14 days", ); }); }); describe("formatPrice", () => { test("should return expected formatted price", () => { expect(formatPrice(9990000, "USD", "en-US")).toEqual("$9.99"); expect(formatPrice(10000000, "USD", "en-US")).toEqual("$10.00"); expect(formatPrice(990000, "USD", "en-US")).toEqual("$0.99"); expect(formatPrice(9900000, "USD", "es-MX")).toEqual("USD 9.90"); expect(formatPrice(9900000, "MXN", "es-MX")).toEqual("$9.90"); expect(formatPrice(9990000, "EUR", "en-US")).toEqual("€9.99"); expect(formatPrice(9990000, "USD", "es-ES")).toEqual("9,99 $"); expect(formatPrice(9990000, "USD", "en-GB")).toEqual("$9.99"); expect(formatPrice(9990000, "CNY", "en-US")).toEqual("CN¥9.99"); expect(formatPrice(9990000, "CNY", "zh-CN")).toEqual("¥9.99"); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/purchase-operation-helper.test.ts
TypeScript
import { afterEach, assert, beforeEach, describe, expect, test, vi, } from "vitest"; import { PurchaseFlowError, PurchaseFlowErrorCode, PurchaseOperationHelper, } from "../../helpers/purchase-operation-helper"; import { Backend } from "../../networking/backend"; import { setupServer, type SetupServer } from "msw/node"; import { http, HttpResponse } from "msw"; import { StatusCodes } from "http-status-codes"; import { CheckoutSessionStatus, CheckoutStatusErrorCodes, type CheckoutStatusResponse, } from "../../networking/responses/checkout-status-response"; import { type IEventsTracker } from "../../behavioural-events/events-tracker"; import { checkoutStartResponse } from "../test-responses"; describe("PurchaseOperationHelper", () => { let server: SetupServer; let backend: Backend; let purchaseOperationHelper: PurchaseOperationHelper; const testTraceId = "test-trace-id"; const operationSessionId = checkoutStartResponse.operation_session_id; beforeEach(() => { server = setupServer(); server.listen(); backend = new Backend("test_api_key"); const eventsTrackerMock: IEventsTracker = { getTraceId: () => testTraceId, updateUser: () => Promise.resolve(), trackSDKEvent: () => {}, trackExternalEvent: () => {}, dispose: () => {}, }; purchaseOperationHelper = new PurchaseOperationHelper( backend, eventsTrackerMock, ); }); afterEach(() => { server.close(); }); function setCheckoutStartResponse( httpResponse: HttpResponse, traceId?: string | undefined, ) { server.use( http.post( "http://localhost:8000/rcbilling/v1/checkout/start", async (req) => { const json = (await req.request.json()) as Record<string, unknown>; if (traceId) { expect(json["trace_id"]).toBe(traceId); } return httpResponse; }, ), ); } function setCheckoutCompleteResponse(httpResponse: HttpResponse) { server.use( http.post( `http://localhost:8000/rcbilling/v1/checkout/${operationSessionId}/complete`, () => { return httpResponse; }, ), ); } function setGetCheckoutStatusResponse(httpResponse: HttpResponse) { setGetCheckoutStatusResponseResolver(() => { return httpResponse; }); } function setGetCheckoutStatusResponseResolver( httpResponseResolver: () => HttpResponse, ) { server.use( http.get( `http://localhost:8000/rcbilling/v1/checkout/${operationSessionId}`, httpResponseResolver, ), ); } test("checkoutStart fails if /checkout/start fails", async () => { setCheckoutStartResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), testTraceId, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorSettingUpPurchase, "Unknown backend error.", "Request: postCheckoutStart. Status code: 500. Body: null.", ), ); }); test("checkoutStart fails if user already subscribed to product", async () => { setCheckoutStartResponse( HttpResponse.json( { code: 7772, message: "This subscriber is already subscribed to the requested product.", }, { status: StatusCodes.CONFLICT }, ), ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, "test-email@test.com", ), new PurchaseFlowError( PurchaseFlowErrorCode.AlreadyPurchasedError, "This product is already active for the user.", "This subscriber is already subscribed to the requested product.", ), ); }); test("checkoutComplete fails if checkoutStart not called before", async () => { await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutComplete(), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorSettingUpPurchase, "No purchase started", ), ); }); test("checkoutComplete fails if /checkout/{operation_session_id}/complete fails", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); setCheckoutCompleteResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, "test-email@test.com", ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutComplete(), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorSettingUpPurchase, "Unknown backend error.", "Request: postCheckoutComplete. Status code: 500. Body: null.", ), ); }); test("checkoutComplete fails if operation session is invalid", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); setCheckoutCompleteResponse( HttpResponse.json( { code: 7877, message: "The operation session is invalid.", }, { status: StatusCodes.BAD_REQUEST }, ), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutComplete(), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorSettingUpPurchase, "One or more of the arguments provided are invalid.", "The operation session is invalid.", ), ); }); test("checkoutComplete fails if purchase could not be completed", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); setCheckoutCompleteResponse( HttpResponse.json( { code: 7878, message: "The purchase could not be completed.", }, { status: StatusCodes.UNPROCESSABLE_ENTITY }, ), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutComplete(), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorSettingUpPurchase, "One or more of the arguments provided are invalid.", "The purchase could not be completed.", ), ); }); test("checkoutComplete fails if email is required", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); setCheckoutCompleteResponse( HttpResponse.json( { code: 7879, message: "Email is required to complete the purchase.", }, { status: StatusCodes.BAD_REQUEST }, ), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.checkoutComplete(), new PurchaseFlowError( PurchaseFlowErrorCode.MissingEmailError, "Email is not valid. Please provide a valid email address.", "Email is required to complete the purchase.", ), ); }); test("pollCurrentPurchaseForCompletion fails if checkoutStart not called before", async () => { await expectPromiseToPurchaseFlowError( purchaseOperationHelper.pollCurrentPurchaseForCompletion(), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorSettingUpPurchase, "No purchase in progress", ), ); }); test("pollCurrentPurchaseForCompletion fails if poll request fails", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); setGetCheckoutStatusResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.pollCurrentPurchaseForCompletion(), new PurchaseFlowError( PurchaseFlowErrorCode.NetworkError, "Unknown backend error.", "Request: getCheckoutStatus. Status code: 500. Body: null.", ), ); }); test("pollCurrentPurchaseForCompletion success if poll returns success", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); const getCheckoutStatusResponse: CheckoutStatusResponse = { operation: { status: CheckoutSessionStatus.Succeeded, is_expired: false, error: null, }, }; setGetCheckoutStatusResponse( HttpResponse.json(getCheckoutStatusResponse, { status: StatusCodes.OK }), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, "test-email", ); await purchaseOperationHelper.pollCurrentPurchaseForCompletion(); }); test("pollCurrentPurchaseForCompletion success with redemption info and operation session id if poll returns success", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); const getCheckoutStatusResponse: CheckoutStatusResponse = { operation: { status: CheckoutSessionStatus.Succeeded, is_expired: false, error: null, redemption_info: { redeem_url: "test-url://redeem_my_rcb?token=1234", }, }, }; setGetCheckoutStatusResponse( HttpResponse.json(getCheckoutStatusResponse, { status: StatusCodes.OK }), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); const pollResult = await purchaseOperationHelper.pollCurrentPurchaseForCompletion(); expect(pollResult.redemptionInfo?.redeemUrl).toEqual( "test-url://redeem_my_rcb?token=1234", ); expect(pollResult.operationSessionId).toEqual(operationSessionId); }); test("pollCurrentPurchaseForCompletion fails if poll returns in progress more times than retries", async () => { vi.useFakeTimers(); setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); const getCheckoutStatusResponse: CheckoutStatusResponse = { operation: { status: CheckoutSessionStatus.InProgress, is_expired: false, error: null, }, }; let callCount = 0; let lastCallTime = 0; setGetCheckoutStatusResponseResolver(() => { callCount++; const currentTime = Date.now(); if (lastCallTime > 0) { expect(currentTime - lastCallTime).toBeGreaterThanOrEqual(1000); } lastCallTime = currentTime; return HttpResponse.json(getCheckoutStatusResponse, { status: StatusCodes.OK, }); }); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); const pollPromise = expectPromiseToPurchaseFlowError( purchaseOperationHelper.pollCurrentPurchaseForCompletion(), new PurchaseFlowError( PurchaseFlowErrorCode.UnknownError, "Max attempts reached trying to get successful purchase status", ), ); await vi.runAllTimersAsync(); expect(callCount).toEqual(10); await pollPromise; vi.useRealTimers(); }); test("pollCurrentPurchaseForCompletion error if poll returns error", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); const getCheckoutStatusResponse: CheckoutStatusResponse = { operation: { status: CheckoutSessionStatus.Failed, is_expired: false, error: { code: CheckoutStatusErrorCodes.PaymentChargeFailed, message: "test-error-message", }, }, }; setGetCheckoutStatusResponse( HttpResponse.json(getCheckoutStatusResponse, { status: StatusCodes.OK }), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.pollCurrentPurchaseForCompletion(), new PurchaseFlowError( PurchaseFlowErrorCode.ErrorChargingPayment, "Payment charge failed", ), ); }); test("pollCurrentPurchaseForCompletion error if poll returns unknown error code", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: StatusCodes.OK, }), ); const getCheckoutStatusResponse: CheckoutStatusResponse = { operation: { status: CheckoutSessionStatus.Failed, is_expired: false, error: { code: 12345, message: "test-error-message", }, }, }; setGetCheckoutStatusResponse( HttpResponse.json(getCheckoutStatusResponse, { status: StatusCodes.OK }), ); await purchaseOperationHelper.checkoutStart( "test-app-user-id", "test-product-id", { id: "test-option-id", priceId: "test-price-id" }, { offeringIdentifier: "test-offering-id", targetingContext: null, placementIdentifier: null, }, ); await expectPromiseToPurchaseFlowError( purchaseOperationHelper.pollCurrentPurchaseForCompletion(), new PurchaseFlowError( PurchaseFlowErrorCode.UnknownError, "Unknown error code received", ), ); }); }); function verifyExpectedError(e: unknown, expectedError: PurchaseFlowError) { expect(e).toBeInstanceOf(PurchaseFlowError); const purchasesError = e as PurchaseFlowError; expect(purchasesError.errorCode).toEqual(expectedError.errorCode); expect(purchasesError.message).toEqual(expectedError.message); expect(purchasesError.underlyingErrorMessage).toEqual( expectedError.underlyingErrorMessage, ); } function expectPromiseToPurchaseFlowError( f: Promise<unknown>, expectedError: PurchaseFlowError, ) { return f.then( () => assert.fail("Promise was expected to raise an error"), (e) => verifyExpectedError(e, expectedError), ); }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/string-helpers.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { capitalize } from "../../helpers/string-helpers"; describe("capitalize", () => { test("capitalizes the first letter of a lowercase word", () => { expect(capitalize("hello")).toBe("Hello"); }); test("keeps the first letter capitalized if already uppercase", () => { expect(capitalize("Hello")).toBe("Hello"); }); test("handles empty strings", () => { expect(capitalize("")).toBe(""); }); test("handles a string with only one character", () => { expect(capitalize("a")).toBe("A"); expect(capitalize("A")).toBe("A"); }); test("handles strings with special characters", () => { expect(capitalize("!hello")).toBe("!hello"); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/utm-params.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { spyOn } from "@vitest/spy"; import { autoParseUTMParams } from "../../helpers/utm-params"; describe("autoParseUTMParams", () => { test("Returns an empty object if no utm param is set", () => { spyOn(URLSearchParams.prototype, "get").mockImplementation(() => null); const utmParams = autoParseUTMParams(); expect(utmParams).toEqual({}); }); test("Returns all utm params if set", () => { const mockUTMParams: { [key: string]: string } = { utm_source: "source", utm_medium: "medium", utm_campaign: "campaign", utm_term: "term", utm_content: "content", }; spyOn(URLSearchParams.prototype, "get").mockImplementation( (key: string) => { if (mockUTMParams[key] === undefined) { return null; } return mockUTMParams[key]; }, ); const utmParams = autoParseUTMParams(); expect(utmParams).toEqual(mockUTMParams); }); test("Returns only the utm params that are set set", () => { const mockUTMParams: { [key: string]: string | null } = { utm_source: "source", utm_campaign: null, utm_term: "term", utm_content: "content", }; spyOn(URLSearchParams.prototype, "get").mockImplementation( (key: string) => { if (mockUTMParams[key] === undefined) { return null; } return mockUTMParams[key]; }, ); const utmParams = autoParseUTMParams(); expect(utmParams).toEqual({ utm_source: "source", utm_term: "term", utm_content: "content", }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/helpers/validators.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { validateEmail } from "../../helpers/validators"; describe("validateEmail", () => { test("validates empty email correctly", () => { expect(validateEmail("")).toEqual( "You need to provide your email address to continue.", ); }); test("validates invalid email correctly", () => { expect(validateEmail("ajajdfljf@lkajd")).toEqual( "Email is not valid. Please provide a valid email address.", ); }); test("validates valid email correctly", () => { expect(validateEmail("test123@revenuecat.com")).toEqual(null); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/locale/locale.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { LocalizationKeys, supportedLanguages, } from "../../ui/localization/supportedLanguages"; import * as fs from "node:fs"; import type { Price } from "../../entities/offerings"; import { Translator } from "../../ui/localization/translator"; import { type Period, PeriodUnit } from "../../helpers/duration-helper"; const eqSet = (xs: Set<unknown>, ys: Set<unknown>) => xs.size === ys.size && [...xs].every((x) => ys.has(x)); describe("The Translator class", () => { test("should have the expected keys in all supported languages", () => { const expectedKeysSet = new Set(Object.values(LocalizationKeys)); Object.entries(supportedLanguages).forEach(([lang, translations]) => { const otherLabelKeys = new Set(Object.keys(translations)); expect( eqSet(expectedKeysSet, otherLabelKeys), `Language ${lang} doesn't have all the expected keys`, ).toBe(true); }); }); test("should not fail for any language/fallbackLanguage when formatting prices", () => { const price: Price = { amountMicros: 10000000, currency: "USD", formattedPrice: "$10.00", amount: 10, }; Object.entries(supportedLanguages).forEach(([lang]) => { Object.entries(supportedLanguages).forEach(([fallbackLang]) => { const translator = new Translator({}, lang, fallbackLang); expect( () => translator.formatPrice(price.amountMicros, price.currency), `Formatting price failed for language ${lang}/${fallbackLang}`, ).not.toThrow(); }); }); }); test("should not fail for any language/fallbackLanguage when translating labels", () => { Object.entries(supportedLanguages).forEach(([lang]) => { Object.entries(supportedLanguages).forEach(([fallbackLang]) => { const translator = new Translator({}, lang, fallbackLang); expect( () => translator.translate(LocalizationKeys.EmailEntryPageEmailStepTitle), `Translating failed for language ${lang}/${fallbackLang}`, ).not.toThrow(); }); }); }); test("should not fail for wrong languages when translating labels", () => { const translator = new Translator({}, "clearly_not_a_locale", "me_neither"); expect( () => translator.translate(LocalizationKeys.EmailEntryPageEmailStepTitle), `Translating failed for language`, ).not.toThrow(); }); test("should not fail for any language/fallbackLanguage when translating periods", () => { const period: Period = { number: 10, unit: PeriodUnit.Month, }; Object.entries(supportedLanguages).forEach(([lang]) => { Object.entries(supportedLanguages).forEach(([fallbackLang]) => { const translator = new Translator({}, lang, fallbackLang); expect( () => translator.translatePeriod(period.number, period.unit), `Translating failed for language ${lang}/${fallbackLang}`, ).not.toThrow(); }); }); }); test("should not fail for wrong languages when translating periods", () => { const period: Period = { number: 10, unit: PeriodUnit.Month, }; const translator = new Translator({}, "clearly_not_a_locale", "me_neither"); expect( () => translator.translatePeriod(period.number, period.unit), `Translating failed for language`, ).not.toThrow(); }); test("should correctly translate 'per {labels}' for day", () => { const translator = new Translator({}, "en", "en"); expect( translator.translatePeriodFrequency(1, PeriodUnit.Day, { useMultipleWords: true, }), ).toBe("per day"); expect( translator.translatePeriodFrequency(1, PeriodUnit.Week, { useMultipleWords: true, }), ).toBe("per week"); expect( translator.translatePeriodFrequency(1, PeriodUnit.Month, { useMultipleWords: true, }), ).toBe("per month"); expect( translator.translatePeriodFrequency(1, PeriodUnit.Year, { useMultipleWords: true, }), ).toBe("per year"); expect( translator.translatePeriodFrequency(2, PeriodUnit.Day, { useMultipleWords: true, }), ).toBe("every 2 days"); expect( translator.translatePeriodFrequency(2, PeriodUnit.Week, { useMultipleWords: true, }), ).toBe("every 2 weeks"); expect( translator.translatePeriodFrequency(2, PeriodUnit.Month, { useMultipleWords: true, }), ).toBe("every 2 months"); expect( translator.translatePeriodFrequency(2, PeriodUnit.Year, { useMultipleWords: true, }), ).toBe("every 2 years"); }); }); describe("The supportedLanguages", () => { test("should include all the files present in /locales", () => { const files: string[] = []; fs.readdirSync("src/ui/localization/locale").forEach((file) => { if (file.endsWith(".json")) { files.push(file.replace(".json", "")); } }); expect( eqSet(new Set(Object.keys(supportedLanguages)), new Set(files)), "Not all files in /locales are imported as supportedLanguages", ).toBe(true); }); test("should have the same variables in all translations as in English", () => { // Function to extract variables from a string (e.g., "{{amount}} week" -> ["amount"]) const extractVariables = (str: string): string[] => { const matches = str.match(/\{\{([^}]+)\}\}/g) || []; return matches.map((match) => match.slice(2, -2)); // Remove {{ and }} }; // English is our reference language const englishTranslations = supportedLanguages["en"]; // For each key in the English translations Object.entries(englishTranslations).forEach(([key, englishValue]) => { // Get variables in the English version const englishVariables = new Set(extractVariables(englishValue)); // Check each other language Object.entries(supportedLanguages).forEach(([lang, translations]) => { // Skip English as it's our reference if (lang === "en") return; const translation = translations[key as LocalizationKeys]; if (!translation) { throw new Error( `Missing translation for key ${key} in language ${lang}`, ); } // Get variables in this language's translation const translationVariables = new Set(extractVariables(translation)); // Check if the variables match expect( eqSet(englishVariables, translationVariables), `Variables don't match for key "${key}" in language "${lang}". ` + `English has ${[...englishVariables].join(", ")} but ${lang} has ${[...translationVariables].join(", ")}`, ).toBe(true); }); }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/main.test.d.ts
TypeScript
export {};
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/main.test.ts
TypeScript
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import * as svelte from "svelte"; // import the module as a namespace import { type CustomerInfo, type EntitlementInfo, Purchases, PurchasesError, } from "../main"; import { ErrorCode, UninitializedPurchasesError } from "../entities/errors"; import { configurePurchases, testApiKey, testUserId, } from "./base.purchases_test"; import { createMonthlyPackageMock } from "./mocks/offering-mock-provider"; import { waitFor } from "@testing-library/svelte"; describe("Purchases.configure()", () => { test("throws error if given invalid api key", () => { expect(() => Purchases.configure("goog_api_key", "appUserId")).toThrowError( PurchasesError, ); expect(() => Purchases.configure("rcb_test invalidchar", "appUserId"), ).toThrowError(PurchasesError); }); test("throws error if given invalid user id", () => { expect(() => Purchases.configure(testApiKey, "")).toThrowError( PurchasesError, ); expect(() => Purchases.configure(testApiKey, "some/AppUserId"), ).toThrowError(PurchasesError); }); test("throws error if given invalid proxy url", () => { expect(() => Purchases.configure(testApiKey, testUserId, { proxyURL: "https://test.revenuecat.com/", }), ).toThrowError(PurchasesError); }); test("throws error if given reserved additional header", () => { expect(() => Purchases.configure(testApiKey, testUserId, { additionalHeaders: { "X-Version": "123" }, }), ).toThrowError(PurchasesError); }); test("configures successfully", () => { const purchases = Purchases.configure(testApiKey, testUserId); expect(purchases).toBeDefined(); }); test("configure multiple times returns different instances", () => { const purchases = Purchases.configure(testApiKey, testUserId); const purchases2 = Purchases.configure( "rcb_another_api_key", "another_user_id", ); expect(purchases).not.toEqual(purchases2); }); }); describe("Purchases.isConfigured()", () => { test("returns false if not configured", () => { expect(Purchases.isConfigured()).toBeFalsy(); }); test("returns true if configured", () => { Purchases.configure(testApiKey, testUserId); expect(Purchases.isConfigured()).toBeTruthy(); }); }); describe("Purchases.getSharedInstance()", () => { test("throws error if not configured", () => { expect(() => Purchases.getSharedInstance()).toThrowError( UninitializedPurchasesError, ); }); test("returns same instance than one returned after initialization", () => { const purchases = configurePurchases(); expect(purchases).toEqual(Purchases.getSharedInstance()); }); }); describe("Purchases.isEntitledTo", () => { test("returns true if a user is entitled", async () => { const purchases = configurePurchases(); const isEntitled = await purchases.isEntitledTo("activeCatServices"); expect(isEntitled).toBeTruthy(); }); test("returns false if a user is not entitled", async () => { const purchases = configurePurchases(); const isEntitled = await purchases.isEntitledTo("expiredEntitlement"); expect(isEntitled).not.toBeTruthy(); }); }); describe("Purchases.changeUser", () => { test("throws error if given invalid user id", async () => { const purchases = configurePurchases(); await expect(purchases.changeUser("")).rejects.toThrow(PurchasesError); }); test("can change user", async () => { const newAppUserId = "newAppUserId"; const purchases = configurePurchases(); expect(purchases.getAppUserId()).toEqual(testUserId); await purchases.changeUser(newAppUserId); expect(purchases.getAppUserId()).toEqual(newAppUserId); }); }); describe("Purchases.getAppUserId()", () => { test("returns app user id", () => { const purchases = configurePurchases(); expect(purchases.getAppUserId()).toEqual(testUserId); }); }); test("can get customer info", async () => { const purchases = configurePurchases(); const customerInfo = await purchases.getCustomerInfo(); const activeCatServicesEntitlementInfo: EntitlementInfo = { identifier: "activeCatServices", billingIssueDetectedAt: null, isActive: true, isSandbox: true, periodType: "normal", latestPurchaseDate: new Date("2023-12-19T16:48:42Z"), originalPurchaseDate: new Date("2023-12-19T16:48:42Z"), expirationDate: new Date("2053-12-20T16:48:42Z"), productIdentifier: "black_f_friday_worten", store: "rc_billing", unsubscribeDetectedAt: null, willRenew: true, }; const expectedCustomerInfo: CustomerInfo = { entitlements: { all: { expiredCatServices: { identifier: "expiredCatServices", billingIssueDetectedAt: null, isActive: false, isSandbox: true, periodType: "normal", latestPurchaseDate: new Date("2023-12-19T16:48:42Z"), originalPurchaseDate: new Date("2023-12-19T16:48:42Z"), expirationDate: new Date("2023-12-20T16:48:42Z"), productIdentifier: "black_f_friday_worten_2", store: "rc_billing", unsubscribeDetectedAt: null, willRenew: true, }, activeCatServices: activeCatServicesEntitlementInfo, }, active: { activeCatServices: activeCatServicesEntitlementInfo, }, }, activeSubscriptions: new Set(["black_f_friday_worten"]), allExpirationDatesByProduct: { black_f_friday_worten: new Date("2054-01-22T16:48:42.000Z"), black_f_friday_worten_2: new Date("2024-01-22T16:48:42.000Z"), }, allPurchaseDatesByProduct: { black_f_friday_worten: new Date("2024-01-21T16:48:42.000Z"), black_f_friday_worten_2: new Date("2024-01-21T16:48:42.000Z"), }, managementURL: "https://test-management-url.revenuecat.com", originalAppUserId: "someAppUserId", requestDate: new Date("2024-01-22T13:23:07Z"), firstSeenDate: new Date("2023-11-20T16:48:29Z"), originalPurchaseDate: null, }; expect(customerInfo).toEqual(expectedCustomerInfo); }); describe("Purchases.close()", () => { test("can close purchases", () => { const purchases = configurePurchases(); expect(Purchases.isConfigured()).toBeTruthy(); purchases.close(); expect(Purchases.isConfigured()).toBeFalsy(); }); test("disposes of events tracker and calls through", () => { const purchases = configurePurchases(); // Create spy that calls through to the original implementation const disposeSpy = vi.spyOn(purchases["eventsTracker"], "dispose"); purchases.close(); expect(disposeSpy).toHaveBeenCalled(); }); }); describe("Purchases.preload()", () => { test("can initialize without failing", async () => { const purchases = configurePurchases(); await purchases.preload(); }); }); const uuidImplementations = [ { name: "crypto.randomUUID", setup: () => { return vi.spyOn(crypto, "randomUUID"); }, }, { name: "crypto.getRandomValues fallback", setup: () => { crypto.randomUUID = undefined as unknown as typeof crypto.randomUUID; return vi.spyOn(crypto, "getRandomValues"); }, }, { name: "Math.random fallback", setup: () => { crypto.randomUUID = undefined as unknown as typeof crypto.randomUUID; crypto.getRandomValues = undefined as unknown as typeof crypto.getRandomValues; return vi.spyOn(Math, "random"); }, }, ]; uuidImplementations.forEach((implementation) => { describe(`Purchases.generateRevenueCatAnonymousAppUserId() with ${implementation.name}`, () => { let setupResult: ReturnType<typeof implementation.setup>; beforeEach(() => { setupResult = implementation.setup(); }); afterEach(() => { vi.restoreAllMocks(); }); test("generates ID with correct format", () => { const anonymousId = Purchases.generateRevenueCatAnonymousAppUserId(); expect(anonymousId).toMatch(/^\$RCAnonymousID:[0-9a-f]{32}$/); }); test("generates unique IDs", () => { const id1 = Purchases.generateRevenueCatAnonymousAppUserId(); const id2 = Purchases.generateRevenueCatAnonymousAppUserId(); expect(id1).not.toEqual(id2); }); test("generated ID passes appUserId validation", () => { const anonymousId = Purchases.generateRevenueCatAnonymousAppUserId(); expect(() => Purchases.configure(testApiKey, anonymousId)).not.toThrow(); }); test("calls the expected uuid implementation", () => { const anonymousId = Purchases.generateRevenueCatAnonymousAppUserId(); expect(anonymousId).toMatch(/^\$RCAnonymousID:[0-9a-f]{32}$/); expect(setupResult).toHaveBeenCalled(); }); }); }); describe("Purchases._trackEvent", () => { test("allows tracking events", () => { const purchases = configurePurchases(); const trackEventSpy = vi.spyOn( purchases["eventsTracker"], "trackExternalEvent", ); purchases._trackEvent({ source: "wpl", eventName: "test_event", properties: { test_property: "test_value", }, }); expect(trackEventSpy).toHaveBeenCalledWith({ eventName: "test_event", source: "wpl", properties: { test_property: "test_value", }, }); }); }); describe("Purchases.purchase()", () => { test("pressing back button onmounts the component", async () => { const unmountSpy = vi.spyOn(svelte, "unmount").mockImplementation(() => { return Promise.resolve(); }); const purchases = configurePurchases(); const purchasePromise = purchases.purchase({ rcPackage: createMonthlyPackageMock(), }); await waitFor(() => { const container = document.querySelector(".rcb-ui-root"); expect(container).not.toBeNull(); if (container) { expect(container.innerHTML).not.toBe(""); } }); window.dispatchEvent(new PopStateEvent("popstate")); await waitFor(() => { expect(unmountSpy).toHaveBeenCalled(); }); await expect(purchasePromise).rejects.toHaveProperty( "errorCode", ErrorCode.UserCancelledError, ); unmountSpy.mockRestore(); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/mocks/events-tracker-mock-provider.ts
TypeScript
import type { IEventsTracker } from "../../behavioural-events/events-tracker"; import { vi } from "vitest"; export function createEventsTrackerMock() { return { updateUser: vi.fn(), trackSDKEvent: vi.fn(), trackExternalEvent: vi.fn(), dispose: vi.fn(), } as unknown as IEventsTracker; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/mocks/offering-mock-provider.ts
TypeScript
import { type NonSubscriptionOption, type Package, PackageType, ProductType, type SubscriptionOption, type TargetingContext, } from "../../entities/offerings"; import { PeriodUnit } from "../../helpers/duration-helper"; export function createMonthlyPackageMock( targetingContext: TargetingContext | null = { ruleId: "test_rule_id", revision: 123, }, ): Package { const subscriptionOption: SubscriptionOption = { id: "base_option", priceId: "test_price_id", base: { cycleCount: 1, periodDuration: "P1M", period: { number: 1, unit: PeriodUnit.Month, }, price: { amount: 300, amountMicros: 3000000, currency: "USD", formattedPrice: "$3.00", }, }, trial: null, }; const webBillingProduct = { currentPrice: { currency: "USD", amount: 300, amountMicros: 3000000, formattedPrice: "$3.00", }, displayName: "Monthly test", title: "Monthly test", description: null, identifier: "monthly", productType: ProductType.Subscription, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "offering_1", presentedOfferingContext: { offeringIdentifier: "offering_1", targetingContext: targetingContext, placementIdentifier: null, }, defaultPurchaseOption: subscriptionOption, defaultSubscriptionOption: subscriptionOption, defaultNonSubscriptionOption: null, subscriptionOptions: { base_option: subscriptionOption, }, }; return { identifier: "$rc_monthly", packageType: PackageType.Monthly, rcBillingProduct: webBillingProduct, webBillingProduct: webBillingProduct, }; } export function createConsumablePackageMock(): Package { const webBillingProduct = { currentPrice: { currency: "USD", amount: 100, amountMicros: 1000000, formattedPrice: "$1.00", }, displayName: "Consumable test", title: "Consumable test", description: "Consumable description", identifier: "test-consumable-product", productType: ProductType.Consumable, normalPeriodDuration: null, presentedOfferingIdentifier: "offering_consumables", presentedOfferingContext: { offeringIdentifier: "offering_consumables", placementIdentifier: null, targetingContext: null, }, defaultPurchaseOption: { id: "base_option", priceId: "test_price_id", basePrice: { amount: 100, amountMicros: 1000000, currency: "USD", formattedPrice: "$1.00", }, } as NonSubscriptionOption, defaultSubscriptionOption: null, defaultNonSubscriptionOption: { id: "base_option", priceId: "test_price_id", basePrice: { amount: 100, amountMicros: 1000000, currency: "USD", formattedPrice: "$1.00", }, }, subscriptionOptions: {}, }; return { identifier: "test-consumable-package", packageType: PackageType.Custom, rcBillingProduct: webBillingProduct, webBillingProduct: webBillingProduct, }; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/networking/backend.test.ts
TypeScript
import { type SetupServer, setupServer } from "msw/node"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { http, HttpResponse } from "msw"; import { checkoutStartResponse, checkoutCompleteResponse, customerInfoResponse, offeringsArray, productsResponse, } from "../test-responses"; import { Backend } from "../../networking/backend"; import { StatusCodes } from "http-status-codes"; import { BackendErrorCode, ErrorCode, PurchasesError, } from "../../entities/errors"; import { expectPromiseToError } from "../test-helpers"; let server: SetupServer; let backend: Backend; beforeEach(() => { server = setupServer(); server.listen(); backend = new Backend("test_api_key"); }); afterEach(() => { server.close(); }); describe("httpConfig is setup correctly", () => { function setCustomerInfoResponse(httpResponse: HttpResponse) { server.use( http.get("http://localhost:8000/v1/subscribers/someAppUserId", () => { return httpResponse; }), ); } test("additionalHeaders are included correctly", async () => { setCustomerInfoResponse( HttpResponse.json(customerInfoResponse, { status: 200 }), ); let requestPerformed: Request | undefined; server.events.on("request:start", (req) => { requestPerformed = req.request; }); backend = new Backend("test_api_key", { additionalHeaders: { "X-Custom-Header": "customValue", "X-Another-Header": "anotherValue", }, }); await backend.getCustomerInfo("someAppUserId"); expect(requestPerformed).not.toBeNull(); expect(requestPerformed?.headers.get("X-Custom-Header")).toEqual( "customValue", ); expect(requestPerformed?.headers.get("X-Another-Header")).toEqual( "anotherValue", ); }); test("additionalHeaders don't override existing headers", async () => { setCustomerInfoResponse( HttpResponse.json(customerInfoResponse, { status: 200 }), ); let requestPerformed: Request | undefined; server.events.on("request:start", (req) => { requestPerformed = req.request; }); backend = new Backend("test_api_key", { additionalHeaders: { "X-Platform": "overridenValue", }, }); await backend.getCustomerInfo("someAppUserId"); expect(requestPerformed).not.toBeNull(); expect(requestPerformed?.headers.get("X-Platform")).toEqual("web"); }); }); describe("getCustomerInfo request", () => { function setCustomerInfoResponse(httpResponse: HttpResponse) { server.use( http.get("http://localhost:8000/v1/subscribers/someAppUserId", () => { return httpResponse; }), ); } test("can get customer info successfully", async () => { setCustomerInfoResponse( HttpResponse.json(customerInfoResponse, { status: 200 }), ); const backendResponse = await backend.getCustomerInfo("someAppUserId"); expect(backendResponse).toEqual(customerInfoResponse); }); test("throws an error if the backend returns a server error", async () => { setCustomerInfoResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await expectPromiseToError( backend.getCustomerInfo("someAppUserId"), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", "Request: getCustomerInfo. Status code: 500. Body: null.", ), ); }); test("throws a known error if the backend returns a request error with correct body", async () => { setCustomerInfoResponse( HttpResponse.json( { code: BackendErrorCode.BackendInvalidAPIKey, message: "API key was wrong", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.getCustomerInfo("someAppUserId"), new PurchasesError( ErrorCode.InvalidCredentialsError, "There was a credentials issue. Check the underlying error for more details.", "API key was wrong", ), ); }); test("throws unknown error if the backend returns a request error with unknown error code in body", async () => { setCustomerInfoResponse( HttpResponse.json( { code: 1234567890, message: "Invalid error message", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.getCustomerInfo("someAppUserId"), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", 'Request: getCustomerInfo. Status code: 400. Body: {"code":1234567890,"message":"Invalid error message"}.', ), ); }); test("throws unknown error if the backend returns a request error without error code in body", async () => { setCustomerInfoResponse( HttpResponse.json(null, { status: StatusCodes.BAD_REQUEST }), ); await expectPromiseToError( backend.getCustomerInfo("someAppUserId"), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", "Request: getCustomerInfo. Status code: 400. Body: null.", ), ); }); test("throws network error if cannot reach server", async () => { setCustomerInfoResponse(HttpResponse.error()); await expectPromiseToError( backend.getCustomerInfo("someAppUserId"), new PurchasesError( ErrorCode.NetworkError, "Error performing request. Please check your network connection and try again.", "Failed to fetch", ), ); }); }); describe("getOfferings request", () => { function setOfferingsResponse(httpResponse: HttpResponse) { server.use( http.get( "http://localhost:8000/v1/subscribers/someAppUserId/offerings", () => { return httpResponse; }, ), ); } test("can get offerings successfully", async () => { const expectedResponse = { current_offering_id: "offering_1", offerings: offeringsArray, }; setOfferingsResponse(HttpResponse.json(expectedResponse, { status: 200 })); expect(await backend.getOfferings("someAppUserId")).toEqual( expectedResponse, ); }); test("throws an error if the backend returns a server error", async () => { setOfferingsResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await expectPromiseToError( backend.getOfferings("someAppUserId"), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", "Request: getOfferings. Status code: 500. Body: null.", ), ); }); test("throws a known error if the backend returns a request error with correct body", async () => { setOfferingsResponse( HttpResponse.json( { code: BackendErrorCode.BackendInvalidAPIKey, message: "API key was wrong", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.getOfferings("someAppUserId"), new PurchasesError( ErrorCode.InvalidCredentialsError, "There was a credentials issue. Check the underlying error for more details.", "API key was wrong", ), ); }); test("throws network error if cannot reach server", async () => { setOfferingsResponse(HttpResponse.error()); await expectPromiseToError( backend.getOfferings("someAppUserId"), new PurchasesError( ErrorCode.NetworkError, "Error performing request. Please check your network connection and try again.", "Failed to fetch", ), ); }); }); describe("getProducts request", () => { function setProductsResponse(httpResponse: HttpResponse, currency?: string) { const baseUrl = "http://localhost:8000/rcbilling/v1/subscribers/someAppUserId/products"; server.use( http.get(baseUrl, ({ request }) => { const url = new URL(request.url); const productIds = url.searchParams.getAll("id"); const urlCurrency = url.searchParams.get("currency"); if ( productIds.includes("monthly") && productIds.includes("monthly_2") && productIds.length === 2 && (urlCurrency === null || urlCurrency === currency) ) { return httpResponse; } throw new Error("Invalid request"); }), ); } test("can get products successfully", async () => { setProductsResponse(HttpResponse.json(productsResponse, { status: 200 })); expect( await backend.getProducts("someAppUserId", ["monthly", "monthly_2"]), ).toEqual(productsResponse); }); test("passes request with currency successfully", async () => { setProductsResponse( HttpResponse.json(productsResponse, { status: 200 }), "USD", ); expect( await backend.getProducts( "someAppUserId", ["monthly", "monthly_2"], "USD", ), ).toEqual(productsResponse); }); test("throws an error if the backend returns a server error", async () => { setProductsResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await expectPromiseToError( backend.getProducts("someAppUserId", ["monthly", "monthly_2"]), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", "Request: getProducts. Status code: 500. Body: null.", ), ); }); test("throws a known error if the backend returns a request error with correct body", async () => { setProductsResponse( HttpResponse.json( { code: BackendErrorCode.BackendInvalidAPIKey, message: "API key was wrong", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.getProducts("someAppUserId", ["monthly", "monthly_2"]), new PurchasesError( ErrorCode.InvalidCredentialsError, "There was a credentials issue. Check the underlying error for more details.", "API key was wrong", ), ); }); test("throws network error if cannot reach server", async () => { setProductsResponse(HttpResponse.error()); await expectPromiseToError( backend.getProducts("someAppUserId", ["monthly", "monthly_2"]), new PurchasesError( ErrorCode.NetworkError, "Error performing request. Please check your network connection and try again.", "Failed to fetch", ), ); }); }); describe("postCheckoutStart request", () => { const purchaseMethodAPIMock = vi.fn(); function setCheckoutStartResponse(httpResponse: HttpResponse) { server.use( http.post("http://localhost:8000/rcbilling/v1/checkout/start", (req) => { purchaseMethodAPIMock(req); return httpResponse; }), ); } afterEach(() => { purchaseMethodAPIMock.mockReset(); }); test("can post checkout start successfully", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: 200 }), ); const result = await backend.postCheckoutStart( "someAppUserId", "monthly", { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, { id: "base_option", priceId: "test_price_id" }, "test-trace-id", ); expect(purchaseMethodAPIMock).toHaveBeenCalledTimes(1); const request = purchaseMethodAPIMock.mock.calls[0][0].request; expect(request.headers.get("Content-Type")).toBe("application/json"); expect(request.headers.get("Authorization")).toBe("Bearer test_api_key"); const requestBody = await request.json(); expect(requestBody).toEqual({ app_user_id: "someAppUserId", product_id: "monthly", price_id: "test_price_id", presented_offering_identifier: "offering_1", trace_id: "test-trace-id", }); expect(result).toEqual(checkoutStartResponse); }); test("accepts an email if provided", async () => { setCheckoutStartResponse( HttpResponse.json(checkoutStartResponse, { status: 200 }), ); const result = await backend.postCheckoutStart( "someAppUserId", "monthly", { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, { id: "base_option", priceId: "test_price_id" }, "test-trace-id", "testemail@revenuecat.com", { utm_campaign: "test-campaign" }, ); expect(purchaseMethodAPIMock).toHaveBeenCalledTimes(1); const request = purchaseMethodAPIMock.mock.calls[0][0].request; expect(request.headers.get("Content-Type")).toBe("application/json"); expect(request.headers.get("Authorization")).toBe("Bearer test_api_key"); const requestBody = await request.json(); expect(requestBody).toEqual({ app_user_id: "someAppUserId", product_id: "monthly", email: "testemail@revenuecat.com", price_id: "test_price_id", presented_offering_identifier: "offering_1", metadata: { utm_campaign: "test-campaign" }, trace_id: "test-trace-id", }); expect(result).toEqual(checkoutStartResponse); }); test("throws an error if the backend returns a server error", async () => { setCheckoutStartResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await expectPromiseToError( backend.postCheckoutStart( "someAppUserId", "monthly", { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, { id: "base_option", priceId: "test_price_id" }, "test-trace-id", undefined, { utm_campaign: "test-campaign" }, ), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", "Request: postCheckoutStart. Status code: 500. Body: null.", ), ); }); test("throws a known error if the backend returns a request error with correct body", async () => { setCheckoutStartResponse( HttpResponse.json( { code: BackendErrorCode.BackendInvalidAPIKey, message: "API key was wrong", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.postCheckoutStart( "someAppUserId", "monthly", { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, { id: "base_option", priceId: "test_price_id" }, "test-trace-id", "testemail@revenuecat.com", { utm_campaign: "test-campaign" }, ), new PurchasesError( ErrorCode.InvalidCredentialsError, "There was a credentials issue. Check the underlying error for more details.", "API key was wrong", ), ); }); test("throws a PurchaseInvalidError if the backend returns with a offer not found error", async () => { setCheckoutStartResponse( HttpResponse.json( { code: BackendErrorCode.BackendOfferNotFound, message: "Offer not available", }, { status: StatusCodes.NOT_FOUND }, ), ); await expectPromiseToError( backend.postCheckoutStart( "someAppUserId", "monthly", { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, { id: "base_option", priceId: "test_price_id" }, "test-trace-id", "testemail@revenuecat.com", { utm_campaign: "test-campaign" }, ), new PurchasesError( ErrorCode.PurchaseInvalidError, "One or more of the arguments provided are invalid.", "Offer not available", ), ); }); test("throws network error if cannot reach server", async () => { setCheckoutStartResponse(HttpResponse.error()); await expectPromiseToError( backend.postCheckoutStart( "someAppUserId", "monthly", { offeringIdentifier: "offering_1", targetingContext: null, placementIdentifier: null, }, { id: "base_option", priceId: "test_price_id" }, "test-trace-id", undefined, { utm_campaign: "test-campaign" }, ), new PurchasesError( ErrorCode.NetworkError, "Error performing request. Please check your network connection and try again.", "Failed to fetch", ), ); }); }); describe("postCheckoutComplete request", () => { const purchaseMethodAPIMock = vi.fn(); function setCheckoutCompleteResponse(httpResponse: HttpResponse) { server.use( http.post( "http://localhost:8000/rcbilling/v1/checkout/someOperationSessionId/complete", (req) => { purchaseMethodAPIMock(req); return httpResponse; }, ), ); } afterEach(() => { purchaseMethodAPIMock.mockReset(); }); test("can post checkout complete successfully", async () => { setCheckoutCompleteResponse( HttpResponse.json(checkoutCompleteResponse, { status: 200 }), ); const result = await backend.postCheckoutComplete("someOperationSessionId"); expect(purchaseMethodAPIMock).toHaveBeenCalledTimes(1); const request = purchaseMethodAPIMock.mock.calls[0][0].request; expect(request.headers.get("Content-Type")).toBe("application/json"); expect(request.headers.get("Authorization")).toBe("Bearer test_api_key"); const requestBody = await request.json(); expect(requestBody).toEqual({}); expect(result).toEqual(checkoutCompleteResponse); }); test("accepts an email if provided", async () => { setCheckoutCompleteResponse( HttpResponse.json(checkoutCompleteResponse, { status: 200 }), ); const result = await backend.postCheckoutComplete( "someOperationSessionId", "testemail@revenuecat.com", ); expect(purchaseMethodAPIMock).toHaveBeenCalledTimes(1); const request = purchaseMethodAPIMock.mock.calls[0][0].request; expect(request.headers.get("Content-Type")).toBe("application/json"); expect(request.headers.get("Authorization")).toBe("Bearer test_api_key"); const requestBody = await request.json(); expect(requestBody).toEqual({ email: "testemail@revenuecat.com", }); expect(result).toEqual(checkoutCompleteResponse); }); test("throws an error if the backend returns a server error", async () => { setCheckoutCompleteResponse( HttpResponse.json(null, { status: StatusCodes.INTERNAL_SERVER_ERROR }), ); await expectPromiseToError( backend.postCheckoutComplete("someOperationSessionId"), new PurchasesError( ErrorCode.UnknownBackendError, "Unknown backend error.", "Request: postCheckoutComplete. Status code: 500. Body: null.", ), ); }); test("throws a known error if the backend returns a request error with correct body", async () => { setCheckoutCompleteResponse( HttpResponse.json( { code: BackendErrorCode.BackendInvalidAPIKey, message: "API key was wrong", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.postCheckoutComplete("someOperationSessionId"), new PurchasesError( ErrorCode.InvalidCredentialsError, "There was a credentials issue. Check the underlying error for more details.", "API key was wrong", ), ); }); test("throws a PurchaseInvalidError if the backend returns with a invalid operation session error", async () => { setCheckoutCompleteResponse( HttpResponse.json( { code: BackendErrorCode.BackendInvalidOperationSession, message: "The operation session is invalid.", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.postCheckoutComplete("someOperationSessionId"), new PurchasesError( ErrorCode.PurchaseInvalidError, "One or more of the arguments provided are invalid.", "The operation session is invalid.", ), ); }); test("throws a PurchaseInvalidError if the backend returns with a purchase cannot be completed error", async () => { setCheckoutCompleteResponse( HttpResponse.json( { code: BackendErrorCode.BackendPurchaseCannotBeCompleted, message: "The purchase cannot be completed.", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.postCheckoutComplete("someOperationSessionId"), new PurchasesError( ErrorCode.PurchaseInvalidError, "One or more of the arguments provided are invalid.", "The purchase cannot be completed.", ), ); }); test("throws a InvalidEmailError if the backend returns with a email is required error", async () => { setCheckoutCompleteResponse( HttpResponse.json( { code: BackendErrorCode.BackendEmailIsRequired, message: "Email is required to complete the purchase.", }, { status: StatusCodes.BAD_REQUEST }, ), ); await expectPromiseToError( backend.postCheckoutComplete("someOperationSessionId"), new PurchasesError( ErrorCode.InvalidEmailError, "Email is not valid. Please provide a valid email address.", "Email is required to complete the purchase.", ), ); }); test("throws network error if cannot reach server", async () => { setCheckoutCompleteResponse(HttpResponse.error()); await expectPromiseToError( backend.postCheckoutComplete("someOperationSessionId"), new PurchasesError( ErrorCode.NetworkError, "Error performing request. Please check your network connection and try again.", "Failed to fetch", ), ); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/networking/endpoints.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { GetBrandingInfoEndpoint, GetCheckoutStatusEndpoint, GetCustomerInfoEndpoint, GetOfferingsEndpoint, GetProductsEndpoint, PurchaseEndpoint, } from "../../networking/endpoints"; describe("getOfferings endpoint", () => { const endpoint = new GetOfferingsEndpoint("someAppUserId"); test("uses correct method", () => { expect(endpoint.method).toBe("GET"); }); test("has correct urlPath for common app user id", () => { expect(endpoint.urlPath()).toBe("/v1/subscribers/someAppUserId/offerings"); }); test("correctly encodes app user id", () => { expect( new GetOfferingsEndpoint("some+User/id#That$Requires&Encoding").urlPath(), ).toBe( "/v1/subscribers/some%2BUser%2Fid%23That%24Requires%26Encoding/offerings", ); }); }); describe("purchase endpoint", () => { const endpoint = new PurchaseEndpoint(); test("uses correct method", () => { expect(endpoint.method).toBe("POST"); }); test("has correct urlPath", () => { expect(endpoint.urlPath()).toBe("/rcbilling/v1/purchase"); }); }); describe("getProducts endpoint", () => { const endpoint = new GetProductsEndpoint("someAppUserId", [ "monthly", "annual", ]); test("uses correct method", () => { expect(endpoint.method).toBe("GET"); }); test("has correct urlPath for common app user id", () => { expect(endpoint.urlPath()).toBe( "/rcbilling/v1/subscribers/someAppUserId/products?id=monthly&id=annual", ); }); test("correctly encodes app user id and product ids", () => { expect( new GetProductsEndpoint("some+User/id#That$Requires&Encoding", [ "product+id/That$requires!Encoding", "productIdWithoutEncoding", ]).urlPath(), ).toBe( "/rcbilling/v1/subscribers/some%2BUser%2Fid%23That%24Requires%26Encoding/products?id=product%2Bid%2FThat%24requires!Encoding&id=productIdWithoutEncoding", ); }); }); describe("getCustomerInfo endpoint", () => { const endpoint = new GetCustomerInfoEndpoint("someAppUserId"); test("uses correct method", () => { expect(endpoint.method).toBe("GET"); }); test("has correct urlPath for common app user id", () => { expect(endpoint.urlPath()).toBe("/v1/subscribers/someAppUserId"); }); test("correctly encodes app user id", () => { expect( new GetCustomerInfoEndpoint( "some+User/id#That$Requires&Encoding", ).urlPath(), ).toBe("/v1/subscribers/some%2BUser%2Fid%23That%24Requires%26Encoding"); }); }); describe("getBrandingInfo endpoint", () => { const endpoint = new GetBrandingInfoEndpoint(); test("uses correct method", () => { expect(endpoint.method).toBe("GET"); }); test("has correct urlPath", () => { expect(endpoint.urlPath()).toBe("/rcbilling/v1/branding"); }); }); describe("getCheckoutStatus endpoint", () => { const endpoint = new GetCheckoutStatusEndpoint("someOperationSessionId"); test("uses correct method", () => { expect(endpoint.method).toBe("GET"); }); test("has correct urlPath", () => { expect(endpoint.urlPath()).toBe( "/rcbilling/v1/checkout/someOperationSessionId", ); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/purchase.events.test.ts
TypeScript
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { configurePurchases } from "./base.purchases_test"; import { APIPostRequest } from "./test-responses"; import "./utils/to-have-been-called-exactly-once-with"; import { Logger } from "../helpers/logger"; import { ErrorCode, Purchases, PurchasesError } from "../main"; import { mount } from "svelte"; vi.mock("svelte", () => ({ mount: vi.fn(), })); vi.mock("uuid", () => ({ v4: () => "c1365463-ce59-4b83-b61b-ef0d883e9047", })); describe("Purchases.configure()", () => { const date = new Date(1988, 10, 18, 13, 37, 0); beforeEach(async () => { vi.spyOn(Logger, "debugLog").mockImplementation(() => undefined); vi.mock("../behavioural-events/sdk-event-context", () => ({ buildEventContext: vi.fn().mockReturnValue({}), })); vi.useFakeTimers(); vi.setSystemTime(date); configurePurchases(); await vi.advanceTimersToNextTimerAsync(); }); afterEach(() => { vi.clearAllMocks(); vi.resetAllMocks(); vi.useRealTimers(); }); test("tracks the SDKInitialized event upon configuration of the SDK", async () => { expect(APIPostRequest).toHaveBeenCalledWith({ url: "http://localhost:8000/v1/events", json: { events: [ { id: "c1365463-ce59-4b83-b61b-ef0d883e9047", type: "web_billing", event_name: "sdk_initialized", timestamp_ms: date.getTime(), app_user_id: "someAppUserId", context: {}, properties: { trace_id: "c1365463-ce59-4b83-b61b-ef0d883e9047", }, }, ], }, }); }); test("tracks the CheckoutSessionStarted event upon starting a purchase", async () => { const purchases = Purchases.getSharedInstance(); const offerings = await purchases.getOfferings(); const packageToBuy = offerings.current?.availablePackages[0]; purchases.purchase({ rcPackage: packageToBuy!, }); await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenCalledWith({ url: "http://localhost:8000/v1/events", json: { events: [ { id: "c1365463-ce59-4b83-b61b-ef0d883e9047", type: "web_billing", event_name: "checkout_session_start", timestamp_ms: date.getTime(), app_user_id: "someAppUserId", context: {}, properties: { trace_id: "c1365463-ce59-4b83-b61b-ef0d883e9047", customer_email_provided_by_developer: false, customization_color_buttons_primary: null, customization_color_accent: null, customization_color_error: null, customization_color_product_info_bg: null, customization_color_form_bg: null, customization_color_page_bg: null, customization_font: null, customization_shapes: null, customization_show_product_description: null, product_currency: "USD", product_interval: "P1M", product_price: 3000000, selected_package_id: "$rc_monthly", selected_product_id: "monthly", selected_purchase_option: "base_option", }, }, ], }, }); }); test("tracks the CheckoutSessionEnded event upon finishing a purchase", async () => { vi.mocked(mount).mockImplementation((_component, options) => { options.props?.onFinished("test-operation-session-id", null); return vi.fn(); }); const purchases = Purchases.getSharedInstance(); const offerings = await purchases.getOfferings(); const packageToBuy = offerings.current?.availablePackages[0]; await purchases.purchase({ rcPackage: packageToBuy!, }); await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenLastCalledWith({ url: "http://localhost:8000/v1/events", json: { events: [ { id: "c1365463-ce59-4b83-b61b-ef0d883e9047", type: "web_billing", event_name: "checkout_session_end", timestamp_ms: date.getTime(), app_user_id: "someAppUserId", context: {}, properties: { trace_id: "c1365463-ce59-4b83-b61b-ef0d883e9047", outcome: "finished", with_redemption_info: false, }, }, ], }, }); }); test("tracks the CheckoutSessionEnded event upon closing a purchase", async () => { vi.mocked(mount).mockImplementation((_component, options) => { options.props?.onClose(); return vi.fn(); }); const purchases = Purchases.getSharedInstance(); const offerings = await purchases.getOfferings(); const packageToBuy = offerings.current?.availablePackages[0]; try { await purchases.purchase({ rcPackage: packageToBuy!, }); } catch (error) { if (!(error instanceof PurchasesError)) { throw error; } } await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenLastCalledWith({ url: "http://localhost:8000/v1/events", json: { events: [ { id: "c1365463-ce59-4b83-b61b-ef0d883e9047", type: "web_billing", event_name: "checkout_session_end", timestamp_ms: date.getTime(), app_user_id: "someAppUserId", context: {}, properties: { trace_id: "c1365463-ce59-4b83-b61b-ef0d883e9047", outcome: "closed", }, }, ], }, }); }); test("tracks the CheckoutSessionEnded event upon erroring a purchase", async () => { vi.mocked(mount).mockImplementation((_component, options) => { options.props?.onError( new PurchasesError(ErrorCode.UnknownError, "Unexpected error"), ); return vi.fn(); }); const purchases = Purchases.getSharedInstance(); const offerings = await purchases.getOfferings(); const packageToBuy = offerings.current?.availablePackages[0]; try { await purchases.purchase({ rcPackage: packageToBuy!, }); } catch (error) { if (!(error instanceof PurchasesError)) { throw error; } } await vi.advanceTimersToNextTimerAsync(); expect(APIPostRequest).toHaveBeenLastCalledWith({ url: "http://localhost:8000/v1/events", json: { events: [ { id: "c1365463-ce59-4b83-b61b-ef0d883e9047", type: "web_billing", event_name: "checkout_session_end", timestamp_ms: date.getTime(), app_user_id: "someAppUserId", context: {}, properties: { trace_id: "c1365463-ce59-4b83-b61b-ef0d883e9047", outcome: "errored", error_code: "0", error_message: "Unexpected error", }, }, ], }, }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/purchase.offerings.test.ts
TypeScript
import { assert, describe, expect, test } from "vitest"; import { createConsumablePackageMock, createMonthlyPackageMock, } from "./mocks/offering-mock-provider"; import { configurePurchases } from "./base.purchases_test"; import { type Offering, type Offerings, type Package, PackageType, ProductType, } from "../entities/offerings"; import { PeriodUnit } from "../helpers/duration-helper"; import { ErrorCode, PurchasesError } from "../entities/errors"; import { OfferingKeyword } from "../entities/get-offerings-params"; describe("getOfferings", () => { const expectedMonthlyPackage = createMonthlyPackageMock(); const subscriptionOption = { id: "offer_12345", priceId: "test_price_id", base: { cycleCount: 1, periodDuration: "P1M", period: { number: 1, unit: PeriodUnit.Month, }, price: { amount: 500, amountMicros: 5000000, currency: "USD", formattedPrice: "$5.00", }, }, trial: { cycleCount: 1, periodDuration: "P1W", period: { number: 1, unit: PeriodUnit.Week, }, price: null, }, }; test("can get offerings", async () => { const purchases = configurePurchases(); const offerings = await purchases.getOfferings(); const currentOffering: Offering = { paywall_components: null, serverDescription: "Offering 1", identifier: "offering_1", metadata: null, packagesById: { $rc_monthly: expectedMonthlyPackage, }, availablePackages: [expectedMonthlyPackage], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: expectedMonthlyPackage, weekly: null, }; const webBillingProduct = { currentPrice: { currency: "USD", amount: 500, amountMicros: 5000000, formattedPrice: "$5.00", }, displayName: "Monthly test 2", title: "Monthly test 2", description: "monthly description", identifier: "monthly_2", productType: ProductType.Subscription, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "offering_2", presentedOfferingContext: { offeringIdentifier: "offering_2", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: subscriptionOption, defaultSubscriptionOption: subscriptionOption, defaultNonSubscriptionOption: null, subscriptionOptions: { offer_12345: subscriptionOption, }, }; const package2: Package = { identifier: "package_2", packageType: PackageType.Custom, rcBillingProduct: webBillingProduct, webBillingProduct: webBillingProduct, }; const expectedOfferings: Offerings = { all: { offering_1: currentOffering, offering_2: { paywall_components: null, serverDescription: "Offering 2", identifier: "offering_2", metadata: null, packagesById: { package_2: package2, }, availablePackages: [package2], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: null, weekly: null, }, }, current: currentOffering, }; expect(offerings).toEqual(expectedOfferings); }); test("can get offerings without current offering id", async () => { const purchases = configurePurchases("appUserIdWithoutCurrentOfferingId"); const offerings = await purchases.getOfferings(); const webBillingProduct = { currentPrice: { currency: "USD", amount: 500, amountMicros: 5000000, formattedPrice: "$5.00", }, displayName: "Monthly test 2", title: "Monthly test 2", description: "monthly description", identifier: "monthly_2", productType: ProductType.Subscription, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "offering_2", presentedOfferingContext: { offeringIdentifier: "offering_2", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: subscriptionOption, defaultSubscriptionOption: subscriptionOption, defaultNonSubscriptionOption: null, subscriptionOptions: { offer_12345: subscriptionOption, }, }; const package2: Package = { identifier: "package_2", packageType: PackageType.Custom, rcBillingProduct: webBillingProduct, webBillingProduct: webBillingProduct, }; const packageWithoutTargeting = createMonthlyPackageMock(null); const expectedOfferings: Offerings = { all: { offering_1: { paywall_components: null, serverDescription: "Offering 1", identifier: "offering_1", metadata: null, packagesById: { $rc_monthly: packageWithoutTargeting, }, availablePackages: [packageWithoutTargeting], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: packageWithoutTargeting, weekly: null, }, offering_2: { paywall_components: null, serverDescription: "Offering 2", identifier: "offering_2", metadata: null, packagesById: { package_2: package2, }, availablePackages: [package2], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: null, weekly: null, }, }, current: null, } as Offerings; expect(offerings).toEqual(expectedOfferings); }); test("can get offerings with missing products", async () => { const purchases = configurePurchases("appUserIdWithMissingProducts"); const offerings = await purchases.getOfferings(); const packageWithoutTargeting = createMonthlyPackageMock(null); const offering_1: Offering = { paywall_components: null, serverDescription: "Offering 1", identifier: "offering_1", metadata: null, packagesById: { $rc_monthly: packageWithoutTargeting, }, availablePackages: [packageWithoutTargeting], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: packageWithoutTargeting, weekly: null, }; expect(offerings).toEqual({ all: { offering_1: offering_1, }, current: null, }); }); test("can get offering with consumable product", async () => { const purchases = configurePurchases( "appUserIdWithNonSubscriptionProducts", ); const offerings = await purchases.getOfferings(); const expectedConsumablePackage = createConsumablePackageMock(); const expectedOffering: Offering = { paywall_components: null, serverDescription: "Offering consumable", identifier: "offering_consumables", metadata: null, packagesById: { "test-consumable-package": expectedConsumablePackage, }, availablePackages: [expectedConsumablePackage], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: null, weekly: null, }; expect(offerings).toEqual({ all: { offering_consumables: expectedOffering, }, current: expectedOffering, }); }); test("gets offerings with valid currency", async () => { const purchases = configurePurchases(); await purchases.getOfferings({ currency: "EUR" }).then( (offerings) => { expect(offerings.current).not.toBeNull(); }, () => assert.fail("Getting offerings with valid currency failed"), ); }); test("fails to get offerings with invalid currency", async () => { const purchases = configurePurchases(); await purchases.getOfferings({ currency: "invalid" }).then( () => assert.fail("Promise was expected to raise an error"), (e) => { expect(e).toBeInstanceOf(PurchasesError); expect(e.errorCode).toEqual(ErrorCode.ConfigurationError); }, ); }); test("can get offerings with a specific offering identifier", async () => { const purchases = configurePurchases(); const offerings = await purchases.getOfferings({ offeringIdentifier: "offering_2", }); const webBillingProduct = { currentPrice: { currency: "USD", amount: 500, amountMicros: 5000000, formattedPrice: "$5.00", }, displayName: "Monthly test 2", title: "Monthly test 2", description: "monthly description", identifier: "monthly_2", productType: ProductType.Subscription, normalPeriodDuration: "P1M", presentedOfferingIdentifier: "offering_2", presentedOfferingContext: { offeringIdentifier: "offering_2", targetingContext: null, placementIdentifier: null, }, defaultPurchaseOption: subscriptionOption, defaultSubscriptionOption: subscriptionOption, defaultNonSubscriptionOption: null, subscriptionOptions: { offer_12345: subscriptionOption, }, }; const package2: Package = { identifier: "package_2", packageType: PackageType.Custom, rcBillingProduct: webBillingProduct, webBillingProduct: webBillingProduct, }; const expectedOfferings: Offerings = { all: { offering_2: { serverDescription: "Offering 2", identifier: "offering_2", metadata: null, packagesById: { package_2: package2, }, availablePackages: [package2], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: null, weekly: null, paywall_components: null, }, }, current: null, }; expect(offerings).toEqual(expectedOfferings); }); test("can get just current offering", async () => { const purchases = configurePurchases(); const offerings = await purchases.getOfferings({ offeringIdentifier: OfferingKeyword.Current, }); const currentOffering: Offering = { serverDescription: "Offering 1", identifier: "offering_1", metadata: null, packagesById: { $rc_monthly: expectedMonthlyPackage, }, availablePackages: [expectedMonthlyPackage], lifetime: null, annual: null, sixMonth: null, threeMonth: null, twoMonth: null, monthly: expectedMonthlyPackage, weekly: null, paywall_components: null, }; const expectedOfferings: Offerings = { all: { offering_1: currentOffering, }, current: currentOffering, }; expect(offerings).toEqual(expectedOfferings); }); test("returns no offerings when offering identifier is invalid", async () => { const purchases = configurePurchases(); const offerings = await purchases.getOfferings({ offeringIdentifier: "invalid_offering", }); expect(Object.keys(offerings.all).length).toBe(0); expect(offerings.current).toBeNull(); }); }); describe("getOfferings placements", () => { test("gets fallback offering if placement id is missing", async () => { const purchases = configurePurchases(); const offeringWithPlacement = await purchases.getCurrentOfferingForPlacement("missing_placement_id"); expect(offeringWithPlacement).not.toBeNull(); expect(offeringWithPlacement?.identifier).toEqual("offering_1"); expect( offeringWithPlacement!.availablePackages[0].webBillingProduct .presentedOfferingContext.placementIdentifier, ).toEqual("missing_placement_id"); }); test("gets null offering if placement id has null offering id", async () => { const purchases = configurePurchases(); const offeringWithPlacement = await purchases.getCurrentOfferingForPlacement("test_null_placement_id"); expect(offeringWithPlacement).toBeNull(); }); test("gets correct offering if placement id is valid", async () => { const purchases = configurePurchases(); const offeringWithPlacement = await purchases.getCurrentOfferingForPlacement("test_placement_id"); expect(offeringWithPlacement).not.toBeNull(); expect(offeringWithPlacement?.identifier).toEqual("offering_2"); expect( offeringWithPlacement!.availablePackages[0].webBillingProduct .presentedOfferingContext.placementIdentifier, ).toEqual("test_placement_id"); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/purchase.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { configurePurchases } from "./base.purchases_test"; import { APIGetRequest, type GetRequest } from "./test-responses"; describe("purchase", () => { test("purchase loads branding if not preloaded", async () => { const purchases = configurePurchases(); const expectedRequest: GetRequest = { url: "http://localhost:8000/rcbilling/v1/branding", }; const offerings = await purchases.getOfferings(); const packageToBuy = offerings.current?.availablePackages[0]; expect(packageToBuy).not.toBeNull(); expect(APIGetRequest).not.toHaveBeenCalledWith(expectedRequest); // Currently we hold on the purchase UI, so we add a timeout to not hold the test forever. // We're just checking that the request happened as expected. await Promise.race([ purchases.purchase({ rcPackage: packageToBuy!, }), new Promise((resolve) => setTimeout(resolve, 100)), ]); expect(APIGetRequest).toHaveBeenCalledWith(expectedRequest); }); }); describe("preload", () => { test("loads branding info", async () => { const purchases = configurePurchases(); const expectedRequest: GetRequest = { url: "http://localhost:8000/rcbilling/v1/branding", }; expect(APIGetRequest).not.toHaveBeenCalledWith(expectedRequest); await purchases.preload(); expect(APIGetRequest).toHaveBeenCalledWith(expectedRequest); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/test-helpers.ts
TypeScript
import { expect, assert } from "vitest"; import { PurchasesError } from "../entities/errors"; export function verifyExpectedError(e: unknown, expectedError: PurchasesError) { expect(e).toBeInstanceOf(PurchasesError); const purchasesError = e as PurchasesError; expect(purchasesError.errorCode).toEqual(expectedError.errorCode); expect(purchasesError.message).toEqual(expectedError.message); expect(purchasesError.underlyingErrorMessage).toEqual( expectedError.underlyingErrorMessage, ); } export function expectPromiseToError( f: Promise<unknown>, expectedError: PurchasesError, ) { return f.then( () => assert.fail("Promise was expected to raise an error"), (e) => verifyExpectedError(e, expectedError), ); }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/test-responses.ts
TypeScript
import { http, HttpResponse, type RequestHandler } from "msw"; import type { OfferingsResponse } from "../networking/responses/offerings-response"; import { vi } from "vitest"; import type { ProductResponse, ProductsResponse, } from "../networking/responses/products-response"; import { type CheckoutStartResponse } from "../networking/responses/checkout-start-response"; import type { CheckoutCompleteResponse } from "../networking/responses/checkout-complete-response"; import { StripeElementsSetupFutureUsage } from "../networking/responses/stripe-elements"; import { StripeElementsMode } from "../networking/responses/stripe-elements"; const monthlyProductResponse: ProductResponse = { identifier: "monthly", product_type: "subscription", title: "Monthly test", description: null, default_purchase_option_id: "base_option", purchase_options: { base_option: { id: "base_option", price_id: "test_price_id", base: { period_duration: "P1M", cycle_count: 1, price: { amount_micros: 3000000, currency: "USD", }, }, trial: null, }, }, }; const monthly2ProductResponse: ProductResponse = { identifier: "monthly_2", product_type: "subscription", title: "Monthly test 2", description: "monthly description", default_purchase_option_id: "offer_12345", purchase_options: { offer_12345: { id: "offer_12345", price_id: "test_price_id", base: { period_duration: "P1M", cycle_count: 1, price: { amount_micros: 5000000, currency: "USD", }, }, trial: { period_duration: "P1W", cycle_count: 1, price: null, }, }, }, }; const consumableProductResponse: ProductResponse = { identifier: "test-consumable-product", product_type: "consumable", title: "Consumable test", description: "Consumable description", default_purchase_option_id: "offer_12345", purchase_options: { offer_12345: { id: "base_option", price_id: "test_price_id", base_price: { amount_micros: 1000000, currency: "USD", }, }, }, }; export const productsResponse: ProductsResponse = { product_details: [monthlyProductResponse, monthly2ProductResponse], }; export const offeringsArray = [ { identifier: "offering_1", description: "Offering 1", metadata: null, packages: [ { identifier: "$rc_monthly", platform_product_identifier: "monthly", }, ], paywall_components: null, }, { identifier: "offering_2", description: "Offering 2", metadata: null, packages: [ { identifier: "package_2", platform_product_identifier: "monthly_2", }, ], paywall_components: null, }, ]; export const customerInfoResponse = { request_date: "2024-01-22T13:23:07Z", request_date_ms: 1705929787636, subscriber: { entitlements: { expiredCatServices: { expires_date: "2023-12-20T16:48:42Z", grace_period_expires_date: null, product_identifier: "black_f_friday_worten_2", purchase_date: "2023-12-19T16:48:42Z", }, activeCatServices: { expires_date: "2053-12-20T16:48:42Z", grace_period_expires_date: null, product_identifier: "black_f_friday_worten", purchase_date: "2023-12-19T16:48:42Z", }, }, first_seen: "2023-11-20T16:48:29Z", last_seen: "2023-11-20T16:48:29Z", management_url: "https://test-management-url.revenuecat.com", non_subscriptions: {}, original_app_user_id: "someAppUserId", original_application_version: null, original_purchase_date: null, other_purchases: {}, subscriptions: { black_f_friday_worten_2: { auto_resume_date: null, billing_issues_detected_at: null, expires_date: "2024-01-22T16:48:42Z", grace_period_expires_date: null, is_sandbox: true, original_purchase_date: "2023-11-20T16:48:42Z", period_type: "normal", purchase_date: "2024-01-21T16:48:42Z", refunded_at: null, store: "rc_billing", store_transaction_id: "one_transaction_id", unsubscribe_detected_at: null, }, black_f_friday_worten: { auto_resume_date: null, billing_issues_detected_at: null, expires_date: "2054-01-22T16:48:42Z", grace_period_expires_date: null, is_sandbox: true, original_purchase_date: "2023-11-20T16:48:42Z", period_type: "normal", purchase_date: "2024-01-21T16:48:42Z", refunded_at: null, store: "rc_billing", store_transaction_id: "another_transaction_id", unsubscribe_detected_at: null, }, }, }, }; export const newAppUserIdCustomerInfoResponse = { request_date: "2024-01-22T13:23:07Z", request_date_ms: 1705929787636, subscriber: { entitlements: {}, first_seen: "2023-11-20T16:48:29Z", last_seen: "2023-11-20T16:48:29Z", management_url: "https://test-management-url.revenuecat.com", non_subscriptions: {}, original_app_user_id: "newAppUserId", original_application_version: null, original_purchase_date: null, other_purchases: {}, subscriptions: {}, }, }; const offeringsResponsesPerUserId: { [userId: string]: OfferingsResponse } = { someAppUserId: { current_offering_id: "offering_1", offerings: offeringsArray, placements: { fallback_offering_id: "offering_1", offering_ids_by_placement: { test_placement_id: "offering_2", test_null_placement_id: null, }, }, targeting: { rule_id: "test_rule_id", revision: 123, }, }, appUserIdWithoutCurrentOfferingId: { current_offering_id: null, offerings: offeringsArray, }, appUserIdWithMissingProducts: { current_offering_id: "offering_2", offerings: offeringsArray, }, appUserIdWithNonSubscriptionProducts: { current_offering_id: "offering_consumables", offerings: [ { identifier: "offering_consumables", description: "Offering consumable", metadata: null, packages: [ { identifier: "test-consumable-package", platform_product_identifier: "test-consumable-product", }, ], paywall_components: null, }, ], }, }; const productsResponsesPerUserId: { [userId: string]: object } = { someAppUserId: productsResponse, appUserIdWithoutCurrentOfferingId: productsResponse, appUserIdWithMissingProducts: { product_details: [monthlyProductResponse] }, appUserIdWithNonSubscriptionProducts: { product_details: [consumableProductResponse], }, }; const customerInfoResponsePerUserId: { [userId: string]: object } = { someAppUserId: customerInfoResponse, newAppUserId: newAppUserIdCustomerInfoResponse, }; const brandingInfoResponse = { app_icon: null, app_icon_webp: null, id: "test-app-id", app_name: "Test Company name", support_email: "test-rcbilling-support@revenuecat.com", }; export const checkoutStartResponse: CheckoutStartResponse = { operation_session_id: "test-operation-session-id", gateway_params: { stripe_account_id: "test-stripe-account-id", publishable_api_key: "test-publishable-api-key", elements_configuration: { mode: StripeElementsMode.Setup, payment_method_types: ["card"], setup_future_usage: StripeElementsSetupFutureUsage.OffSession, }, }, }; export const checkoutCompleteResponse: CheckoutCompleteResponse = { operation_session_id: "test-operation-session-id", gateway_params: { client_secret: "test-client-secret", }, }; export interface GetRequest { url: string; } export const APIGetRequest = vi.fn(); export const APIPostRequest = vi.fn(); export const eventsURL = "http://localhost:8000/v1/events"; export function getRequestHandlers(): RequestHandler[] { const requestHandlers: RequestHandler[] = []; Object.keys(offeringsResponsesPerUserId).forEach((userId: string) => { const body = offeringsResponsesPerUserId[userId]!; const url = `http://localhost:8000/v1/subscribers/${userId}/offerings`; requestHandlers.push( http.get(url, ({ request }) => { APIGetRequest({ url: request.url }); return HttpResponse.json(body, { status: 200 }); }), ); }); Object.keys(productsResponsesPerUserId).forEach((userId: string) => { const body = productsResponsesPerUserId[userId]!; const url = `http://localhost:8000/rcbilling/v1/subscribers/${userId}/products`; requestHandlers.push( http.get(url, ({ request }) => { APIGetRequest({ url: request.url }); return HttpResponse.json(body, { status: 200 }); }), ); }); Object.keys(customerInfoResponsePerUserId).forEach((userId: string) => { const body = customerInfoResponsePerUserId[userId]!; const url = `http://localhost:8000/v1/subscribers/${userId}`; requestHandlers.push( http.get(url, ({ request }) => { APIGetRequest({ url: request.url }); return HttpResponse.json(body, { status: 200 }); }), ); }); const brandingUrl = "http://localhost:8000/rcbilling/v1/branding"; requestHandlers.push( http.get(brandingUrl, ({ request }) => { APIGetRequest({ url: request.url }); return HttpResponse.json(brandingInfoResponse, { status: 200 }); }), ); requestHandlers.push( http.post(eventsURL, async ({ request }) => { const json = await request.json(); APIPostRequest({ url: eventsURL, json }); return HttpResponse.json({}, { status: 200 }); }), ); return requestHandlers; }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/theme/utils.test.ts
TypeScript
import { describe, expect, test } from "vitest"; import { applyAlpha } from "../../ui/theme/utils"; describe("overlayColor", () => { test("applies black overlay for a light color", () => { expect(applyAlpha("#FFFFFF", 0.1)).toBe("#E6E6E6"); // 10% black overlay on white }); test("applies white overlay for a dark color", () => { expect(applyAlpha("#000000", 0.1)).toBe("#1A1A1A"); // 10% white overlay on black }); test("applies correct overlay for a mid-tone color", () => { expect(applyAlpha("#888888", 0.15)).toBe("#9A9A9A"); // 15% lighter grey }); test("returns same color if alpha is 0", () => { expect(applyAlpha("#123456", 0)).toBe("#123456"); }); test("returns full overlay color if alpha is 1", () => { expect(applyAlpha("#123456", 1)).toBe("#FFFFFF"); // White overlay completely replaces dark color }); test("handles incorrect hex input gracefully", () => { expect(applyAlpha("invalid", 0.5)).toBe("#808080"); // Should fall back to neutral gray }); test("handles incorrect alpha input gracefully", () => { expect(applyAlpha("#FFFFFF", -4)).toBe("#FFFFFF"); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/ui/pages/email-entry-page.test.ts
TypeScript
import "@testing-library/jest-dom"; import { fireEvent, render, screen } from "@testing-library/svelte"; import { describe, test, expect, vi } from "vitest"; import EmailEntryPage from "../../../ui/pages/email-entry-page.svelte"; import { SDKEventName } from "../../../behavioural-events/sdk-events"; import { createEventsTrackerMock } from "../../mocks/events-tracker-mock-provider"; import { eventsTrackerContextKey } from "../../../ui/constants"; import { writable } from "svelte/store"; import { Translator } from "../../../ui/localization/translator"; import { translatorContextKey } from "../../../ui/localization/constants"; const eventsTrackerMock = createEventsTrackerMock(); const defaultContext = new Map( Object.entries({ [eventsTrackerContextKey]: eventsTrackerMock, [translatorContextKey]: writable(new Translator()), }), ); const basicProps = { lastError: null, processing: false, onClose: vi.fn(), onContinue: vi.fn(), }; describe("PurchasesUI", () => { test("displays error when an invalid email format is submitted", async () => { render(EmailEntryPage, { props: { ...basicProps, customerEmail: undefined }, context: defaultContext, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "testest.com" } }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(screen.getByText(/Email is not valid/)).toBeInTheDocument(); }); test("clears email format error after it is fixed", async () => { render(EmailEntryPage, { props: { ...basicProps, customerEmail: undefined }, context: defaultContext, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "testest.com" }, }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(screen.getByText(/Email is not valid/)).toBeInTheDocument(); await fireEvent.input(emailInput, { target: { value: "test@test.com" }, }); await fireEvent.click(continueButton); expect(screen.queryByText(/Email is not valid/)).not.toBeInTheDocument(); }); test("tracks the CheckoutBillingFormImpression on mount", async () => { render(EmailEntryPage, { props: { ...basicProps, customerEmail: undefined }, context: defaultContext, }); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutBillingFormImpression, }); }); test("tracks the CheckoutBillingFormSubmit event email is submitted", async () => { render(EmailEntryPage, { props: { ...basicProps, customerEmail: undefined }, context: defaultContext, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "test@test.com" } }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutBillingFormSubmit, }); }); test("tracks the CheckoutBillingFormError event when input has an email format error", async () => { render(EmailEntryPage, { props: { ...basicProps, customerEmail: undefined }, context: defaultContext, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "testest.com" } }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutBillingFormError, properties: { errorCode: null, errorMessage: "Email is not valid. Please provide a valid email address.", }, }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/ui/pages/payment-entry-page.test.ts
TypeScript
import { fireEvent, render, screen } from "@testing-library/svelte"; import { describe, test, expect, vi, beforeEach } from "vitest"; import PaymentEntryPage from "../../../ui/pages/payment-entry-page.svelte"; import { brandingInfo, rcPackage, checkoutStartResponse, priceBreakdownTaxDisabled, } from "../../../stories/fixtures"; import { SDKEventName } from "../../../behavioural-events/sdk-events"; import { createEventsTrackerMock } from "../../mocks/events-tracker-mock-provider"; import { eventsTrackerContextKey } from "../../../ui/constants"; import type { PurchaseOperationHelper } from "../../../helpers/purchase-operation-helper"; import type { CheckoutStartResponse } from "../../../networking/responses/checkout-start-response"; import { writable } from "svelte/store"; import { Translator } from "../../../ui/localization/translator"; import { translatorContextKey } from "../../../ui/localization/constants"; import { StripeService } from "../../../stripe/stripe-service"; import type { StripeError, StripePaymentElementChangeEvent, } from "@stripe/stripe-js"; import type { ComponentProps } from "svelte"; const eventsTrackerMock = createEventsTrackerMock(); const purchaseOperationHelperMock: PurchaseOperationHelper = { checkoutStart: async () => Promise.resolve(checkoutStartResponse as CheckoutStartResponse), checkoutComplete: async () => Promise.resolve(null), } as unknown as PurchaseOperationHelper; const basicProps: ComponentProps<PaymentEntryPage> = { brandingInfo: brandingInfo, priceBreakdown: priceBreakdownTaxDisabled, purchaseOption: rcPackage.webBillingProduct.defaultPurchaseOption, productDetails: rcPackage.webBillingProduct, processing: false, purchaseOperationHelper: purchaseOperationHelperMock, checkoutStartResponse: checkoutStartResponse, initialTaxCalculation: null, onClose: vi.fn(), onContinue: vi.fn(), }; const defaultContext = new Map( Object.entries({ [eventsTrackerContextKey]: eventsTrackerMock, [translatorContextKey]: writable(new Translator()), }), ); vi.mock("../../../stripe/stripe-service", () => ({ StripeService: { initializeStripe: vi.fn(), createPaymentElement: vi.fn(), isStripeHandledCardError: vi.fn(), }, })); describe("PurchasesUI", () => { beforeEach(() => { vi.useFakeTimers(); vi.mocked(StripeService.initializeStripe).mockResolvedValue({ // @ts-expect-error - This is a mock stripe: { exists: true }, elements: { // @ts-expect-error - This is a mock _elements: [1], submit: vi.fn().mockResolvedValue({ error: null }), }, }); vi.mocked(StripeService.isStripeHandledCardError).mockReturnValue(false); }); test("tracks the PaymentEntryImpression event when the payment entry is displayed", async () => { render(PaymentEntryPage, { props: { ...basicProps, }, context: defaultContext, }); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPaymentFormImpression, }); }); test("tracks the PaymentEntrySubmit event when the payment entry is submitted", async () => { const paymentElement = { on: ( eventType: string, callback: (event?: StripePaymentElementChangeEvent) => void, ) => { if (eventType === "ready") { setTimeout(() => callback(), 0); } if (eventType === "change") { setTimeout(() => { callback({ complete: true, value: { type: "card", }, elementType: "payment", empty: false, collapsed: false, }); }, 100); } }, mount: vi.fn(), destroy: vi.fn(), }; vi.mocked(StripeService.createPaymentElement).mockReturnValue( // @ts-expect-error - This is a mock paymentElement, ); render(PaymentEntryPage, { props: { ...basicProps }, context: defaultContext, }); await vi.advanceTimersToNextTimerAsync(); await vi.advanceTimersToNextTimerAsync(); const paymentForm = screen.getByTestId("payment-form"); await fireEvent.submit(paymentForm); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPaymentFormSubmit, properties: { selectedPaymentMethod: "card", }, }); }); test("tracks the CheckoutPaymentFormGatewayError event when the payment form fails to initialize", async () => { vi.mocked(StripeService.initializeStripe).mockRejectedValue( new Error("Failed to initialize payment form"), ); render(PaymentEntryPage, { props: { ...basicProps }, context: defaultContext, }); await vi.advanceTimersToNextTimerAsync(); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPaymentFormGatewayError, properties: { errorCode: "", errorMessage: "Failed to initialize payment form", }, }); }); test("tracks the CheckoutPaymentFormGatewayError event when stripe onload error occurs", async () => { const paymentElement = { on: ( eventType: string, callback: (event?: { elementType: "payment"; error: StripeError; }) => void, ) => { if (eventType === "loaderror") { setTimeout( () => callback({ elementType: "payment", error: { code: "0", message: "Failed to initialize payment form", } as StripeError, }), 0, ); } }, mount: vi.fn(), destroy: vi.fn(), }; vi.mocked(StripeService.createPaymentElement).mockReturnValue( // @ts-expect-error - This is a mock paymentElement, ); render(PaymentEntryPage, { props: { ...basicProps }, context: defaultContext, }); await vi.advanceTimersToNextTimerAsync(); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPaymentFormGatewayError, properties: { errorCode: "0", errorMessage: "Failed to initialize payment form", }, }); }); test("tracks the CheckoutPaymentFormGatewayError event when stripe ", async () => { const stripeInitializationMock = { stripe: { exists: true }, elements: { _elements: [1], submit: vi.fn().mockResolvedValue({ error: { type: "api_error", code: "0", message: "Submission error", }, }), }, }; vi.mocked(StripeService.initializeStripe).mockReturnValue( // @ts-expect-error - This is a mock stripeInitializationMock, ); render(PaymentEntryPage, { props: { ...basicProps }, context: defaultContext, }); await vi.advanceTimersToNextTimerAsync(); await vi.advanceTimersToNextTimerAsync(); const paymentForm = screen.getByTestId("payment-form"); await fireEvent.submit(paymentForm); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPaymentFormGatewayError, properties: { errorCode: "0", errorMessage: "Submission error", }, }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/ui/pages/success-page.test.ts
TypeScript
import "@testing-library/jest-dom"; import { fireEvent, render, screen } from "@testing-library/svelte"; import { describe, test, expect, vi } from "vitest"; import SuccessPage from "../../../ui/pages/success-page.svelte"; import { brandingInfo, rcPackage } from "../../../stories/fixtures"; import { SDKEventName } from "../../../behavioural-events/sdk-events"; import { createEventsTrackerMock } from "../../mocks/events-tracker-mock-provider"; import { eventsTrackerContextKey } from "../../../ui/constants"; import { Translator } from "../../../ui/localization/translator"; import { writable } from "svelte/store"; import { translatorContextKey } from "../../../ui/localization/constants"; const eventsTrackerMock = createEventsTrackerMock(); const basicProps = { productDetails: rcPackage.rcBillingProduct, brandingInfo: brandingInfo, onContinue: vi.fn(), }; const defaultContext = new Map( Object.entries({ [eventsTrackerContextKey]: eventsTrackerMock, [translatorContextKey]: writable(new Translator()), }), ); describe("PurchasesUI", () => { function renderComponent() { render(SuccessPage, { props: basicProps, context: defaultContext, }); } test("tracks the PurchaseSuccessfulImpression event when the purchase is successful", async () => { renderComponent(); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPurchaseSuccessfulImpression, }); }); test("tracks the PurchaseSuccessfulDismiss event when the purchase successful dialog button is pressed", async () => { renderComponent(); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith({ eventName: SDKEventName.CheckoutPurchaseSuccessfulDismiss, properties: { ui_element: "go_back_to_app", }, }); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/ui/purchases-ui.test.ts
TypeScript
import "@testing-library/jest-dom"; import { fireEvent, render, screen } from "@testing-library/svelte"; import { afterEach, describe, expect, test, vi } from "vitest"; import PurchasesUI from "../../ui/purchases-ui.svelte"; import { brandingInfo, checkoutCalculateTaxResponse, checkoutStartResponse, rcPackage, subscriptionOption, } from "../../stories/fixtures"; import type { Purchases } from "../../main"; import { PurchaseFlowError, PurchaseFlowErrorCode, type PurchaseOperationHelper, } from "../../helpers/purchase-operation-helper"; import { SDKEventName } from "../../behavioural-events/sdk-events"; import { createEventsTrackerMock } from "../mocks/events-tracker-mock-provider"; import type { CheckoutStartResponse } from "../../networking/responses/checkout-start-response"; import type { CheckoutCalculateTaxResponse } from "../../networking/responses/checkout-calculate-tax-response"; import * as constants from "../../helpers/constants"; const eventsTrackerMock = createEventsTrackerMock(); const purchaseOperationHelperMock: PurchaseOperationHelper = { checkoutStart: async () => Promise.resolve(checkoutStartResponse as CheckoutStartResponse), checkoutCalculateTax: async () => Promise.resolve( checkoutCalculateTaxResponse as CheckoutCalculateTaxResponse, ), } as unknown as PurchaseOperationHelper; const purchasesMock: Purchases = { isSandbox: () => true, close: vi.fn(), } as unknown as Purchases; const basicProps = { appUserId: "app-user-id", metadata: { utm_term: "something" }, onFinished: vi.fn(), onError: vi.fn(), purchases: purchasesMock, eventsTracker: eventsTrackerMock, purchaseOperationHelper: purchaseOperationHelperMock, rcPackage: rcPackage, purchaseOption: subscriptionOption, brandingInfo: null, isSandbox: true, branding: brandingInfo, customerEmail: "test@test.com", onClose: vi.fn(), }; describe("PurchasesUI", () => { afterEach(() => { vi.clearAllMocks(); }); test("displays error when an unreachable email is submitted", async () => { vi.spyOn(purchaseOperationHelperMock, "checkoutStart").mockRejectedValue( new PurchaseFlowError( PurchaseFlowErrorCode.MissingEmailError, "Email domain is not valid. Please check the email address or try a different one.", ), ); vi.spyOn( purchaseOperationHelperMock, "checkoutCalculateTax", ).mockResolvedValue(checkoutCalculateTaxResponse); render(PurchasesUI, { props: { ...basicProps, customerEmail: undefined }, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "test@unrechable.com" }, }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); await new Promise(process.nextTick); expect(screen.getByText(/Email domain is not valid/)).toBeInTheDocument(); }); test("clears domain email errors after they are fixed", async () => { vi.spyOn(purchaseOperationHelperMock, "checkoutStart").mockRejectedValue( new PurchaseFlowError( PurchaseFlowErrorCode.MissingEmailError, "Email domain is not valid. Please check the email address or try a different one.", ), ); render(PurchasesUI, { props: { ...basicProps, customerEmail: undefined }, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "testest.com" }, }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(screen.getByText(/Email is not valid/)).toBeInTheDocument(); await fireEvent.input(emailInput, { target: { value: "test@test.com" }, }); await fireEvent.click(continueButton); expect(screen.queryByText(/Email is not valid/)).not.toBeInTheDocument(); }); test("performs tax calculation when gateway_tax_collection_enabled is true and VITE_ALLOW_TAX_CALCULATION_FF is enabled", async () => { vi.spyOn(constants, "ALLOW_TAX_CALCULATION_FF", "get").mockReturnValue( true, ); vi.spyOn(purchaseOperationHelperMock, "checkoutStart").mockResolvedValue( checkoutStartResponse, ); const calculateTaxSpy = vi .spyOn(purchaseOperationHelperMock, "checkoutCalculateTax") .mockResolvedValue(checkoutCalculateTaxResponse); render(PurchasesUI, { props: { ...basicProps, brandingInfo: { ...brandingInfo, gateway_tax_collection_enabled: true, }, }, }); await new Promise(process.nextTick); expect(calculateTaxSpy).toHaveBeenCalled(); }); test("does not perform tax calculation when VITE_ALLOW_TAX_CALCULATION_FF is disabled, even if gateway_tax_collection_enabled is true", async () => { vi.spyOn(constants, "ALLOW_TAX_CALCULATION_FF", "get").mockReturnValue( false, ); vi.spyOn(purchaseOperationHelperMock, "checkoutStart").mockResolvedValue( checkoutStartResponse, ); const calculateTaxSpy = vi .spyOn(purchaseOperationHelperMock, "checkoutCalculateTax") .mockResolvedValue(checkoutCalculateTaxResponse); render(PurchasesUI, { props: { ...basicProps, brandingInfo: { ...brandingInfo, gateway_tax_collection_enabled: true, }, }, }); await new Promise(process.nextTick); expect(calculateTaxSpy).not.toHaveBeenCalled(); }); test("does not perform tax calculation when gateway_tax_collection_enabled is false", async () => { vi.spyOn(purchaseOperationHelperMock, "checkoutStart").mockResolvedValue( checkoutStartResponse, ); const calculateTaxSpy = vi .spyOn(purchaseOperationHelperMock, "checkoutCalculateTax") .mockResolvedValue(checkoutCalculateTaxResponse); render(PurchasesUI, { props: { ...basicProps, brandingInfo: { ...brandingInfo, gateway_tax_collection_enabled: false, }, }, }); await new Promise(process.nextTick); expect(calculateTaxSpy).not.toHaveBeenCalled(); }); test("NOTs render CheckoutBillingFormImpression when email has been provided", async () => { render(PurchasesUI, { props: { ...basicProps, customerEmail: "test@test.com" }, }); expect(screen.queryByText(/Billing email address/)); }); test("tracks the CheckoutFlowError event when an email is handled at the root component", async () => { vi.spyOn( purchaseOperationHelperMock, "checkoutStart", ).mockRejectedValueOnce( new PurchaseFlowError( PurchaseFlowErrorCode.MissingEmailError, "Email domain is not valid. Please check the email address or try a different one.", ), ); render(PurchasesUI, { props: { ...basicProps, customerEmail: undefined }, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "test@unrechable.com" }, }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(eventsTrackerMock.trackSDKEvent).toHaveBeenCalledWith( expect.objectContaining({ eventName: SDKEventName.CheckoutFlowError, }), ); }); test("does NOT track the CheckoutBillingFormError event when a different error occurs", async () => { vi.spyOn( purchaseOperationHelperMock, "checkoutStart", ).mockRejectedValueOnce( new PurchaseFlowError( PurchaseFlowErrorCode.UnknownError, "Unknown error without state set.", ), ); render(PurchasesUI, { props: { ...basicProps, customerEmail: undefined }, }); const emailInput = screen.getByTestId("email"); await fireEvent.input(emailInput, { target: { value: "test@test.com" } }); const continueButton = screen.getByText("Continue"); await fireEvent.click(continueButton); expect(eventsTrackerMock.trackSDKEvent).not.toHaveBeenCalledWith( expect.objectContaining({ eventName: SDKEventName.CheckoutBillingFormError, }), ); }); });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/utils/to-have-been-called-exactly-once-with.ts
TypeScript
import { expect, type MockInstance } from "vitest"; expect.extend({ // This expectation was added to vitest 3.0 toHaveBeenCalledExactlyOnceWith: // In the meantime adding it as a custom one here function toHaveBeenCalledExactlyOnceWith( received: MockInstance, ...expectedArgs: unknown[] ) { const spyName = received.getMockName(); const callsWithExactArgs = received.mock.calls.filter((callArgs) => { if (callArgs.length !== expectedArgs.length) return false; for (let i = 0; i < callArgs.length; i++) { if (callArgs[i] !== expectedArgs[i]) return false; } return true; }); const pass = callsWithExactArgs.length === 1; if (pass) { return { message: () => `expected "${spyName}" not to be called exactly once with arguments: ${this.utils.printExpected(expectedArgs)}`, pass: true, }; } else { return { message: () => `expected "${spyName}" to be called exactly once with arguments: ${this.utils.printExpected(expectedArgs)} but was called ${callsWithExactArgs.length} times`, pass: false, }; } }, });
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/tests/vitest.d.ts
TypeScript
import "vitest"; interface CustomMatchers<R = unknown> { toHaveBeenCalledExactlyOnceWith(...expectedArgs: unknown[]): R; } declare module "vitest" { // eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-explicit-any interface Assertion<T = any> extends CustomMatchers<T> {} // eslint-disable-next-line @typescript-eslint/no-empty-object-type interface AsymmetricMatchersContaining extends CustomMatchers {} }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/app-logo.svelte
Svelte
<script lang="ts"> export let src: string | null = null; export let srcWebp: string | null = null; </script> {#if src !== null} <picture class="rcb-app-icon-picture-container"> <source type="image/webp" srcset={srcWebp} /> <img class="rcb-app-icon" {src} alt="App icon" /> </picture> {:else} <div class="rcb-app-icon loading"></div> {/if} <style> .rcb-app-icon { width: 40px; height: 40px; border-radius: 12px; box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 0.1); margin-right: 16px; } .rcb-app-icon-picture-container { height: 40px; } .rcb-app-icon.loading { background-color: gray; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/button.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; import ProcessingAnimation from "./processing-animation.svelte"; export let intent: "primary" = "primary"; export let disabled = false; export let testId: string | undefined = undefined; export let type: "reset" | "submit" | "button" | null | undefined = undefined; export let loading: boolean = false; export let children: Snippet | undefined; </script> <button on:click class={`intent-${intent}`} {disabled} data-testid={testId} {type} > {#if loading} <ProcessingAnimation size="small" /> {:else} {@render children?.()} {/if} </button> <style> button { border: none; border-radius: var(--rc-shape-input-button-border-radius); font-size: 16px; cursor: pointer; height: var(--rc-spacing-inputHeight-mobile); color: var(--rc-color-grey-text-dark); background-color: var(--rc-color-grey-ui-dark); display: flex; align-items: center; justify-content: center; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -webkit-tap-highlight-color: transparent; transition: background-color 0.15s ease-in-out; user-select: none; } @container layout-query-container (width >= 768px) { button { height: var(--rc-spacing-inputHeight-desktop); } } /* focus-visible is triggered only when focused with keyboard/reader */ button:focus-visible { outline: 2px solid var(--rc-color-focus); } button.intent-primary { background-color: var(--rc-color-primary); color: var(--rc-color-primary-text); font-size: 16px; } button:disabled { color: var(--rc-color-grey-text-light); background-color: var(--rc-color-grey-ui-dark); outline: none; } button.intent-primary:not(:disabled):hover { background-color: var(--rc-color-primary-hover); } button.intent-primary:not(:disabled):active, button:active { background-color: var(--rc-color-primary-pressed); outline: none; } button.intent-primary:disabled { color: var(--rc-color-grey-text-light); background-color: var(--rc-color-grey-ui-dark); } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/icon.svelte
Svelte
<script module> import { type Component } from "svelte"; import { type Direction, default as IconChevron, } from "./icons/icon-chevron.svelte"; import { default as IconCart } from "../atoms/icons/icon-cart.svelte"; import { default as IconError } from "../atoms/icons/icon-error.svelte"; import { default as IconLock } from "../atoms/icons/icon-lock.svelte"; import { default as IconSuccess } from "../atoms/icons/icon-success.svelte"; export type IconName = | "cart" | "error" | "lock" | "success" | "chevron-left" | "chevron-right" | "chevron-up" | "chevron-down"; const iconMap: Record<IconName, Component<{ direction?: Direction }>> = { cart: IconCart, error: IconError, lock: IconLock, success: IconSuccess, "chevron-left": IconChevron as Component<{ direction?: Direction }>, "chevron-right": IconChevron as Component<{ direction?: Direction }>, "chevron-up": IconChevron as Component<{ direction?: Direction }>, "chevron-down": IconChevron as Component<{ direction?: Direction }>, }; </script> <script lang="ts"> const { name }: { name: IconName } = $props(); const MappedIcon = iconMap[name]; let args = $state({}); if (name.startsWith("chevron")) { const direction = name.split("-")[1]; args = { direction: direction }; } </script> <MappedIcon {...args} />
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/icons/icon-cart.svelte
Svelte
<script> import Icon from "../../../assets/cart.svg?raw"; // Load SVG as a raw string </script> <div style="color:var(--rc-color-gray-text-dark);"> {@html Icon} </div>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/icons/icon-chevron.svelte
Svelte
<script module> export type Direction = "up" | "down" | "left" | "right"; </script> <script lang="ts"> export let direction: Direction; </script> <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" class="arrow {direction}" > <path d="M4.94 5.72656L8 8.7799L11.06 5.72656L12 6.66656L8 10.6666L4 6.66656L4.94 5.72656Z" class="arrow-fill" fill-opacity="0.7" /> </svg> <style> .arrow { transition: transform 0.3s ease; } .arrow-fill { fill: var(--rc-color-grey-text-dark); } .arrow.left { transform: rotate(90deg); } .arrow.up { transform: rotate(180deg); } .arrow.right { transform: rotate(-90deg); } .arrow.down { transform: rotate(0deg); } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/icons/icon-error.svelte
Svelte
<script> import Icon from "../../../assets/error.svg?raw"; // Load SVG as a raw string </script> <div style="color:var(--rc-color-primary);" class="rcb-ui-asset-icon"> {@html Icon} </div> <style> .rcb-ui-asset-icon { width: 40px; height: 40px; margin: 0 auto; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/icons/icon-lock.svelte
Svelte
<script> import Icon from "../../../assets/lock.svg?raw"; // Load SVG as a raw string </script> <div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon"> {@html Icon} </div> <style> div { height: 24px; width: 24px; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/icons/icon-success.svelte
Svelte
<script> import Icon from "../../../assets/success.svg?raw"; // Load SVG as a raw string </script> <div style="color:var(--rc-color-primary);" class="rcb-ui-asset-icon"> {@html Icon} </div> <style> .rcb-ui-asset-icon { width: 40px; height: 40px; margin: 0 auto; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/processing-animation.svelte
Svelte
<script lang="ts"> export let size: "small" | "medium" | "large" = "medium"; const sizeMap = { small: { width: "8px", offset: "10px" }, medium: { width: "12px", offset: "20px" }, large: { width: "16px", offset: "30px" }, }; </script> <div class="rcb-processing" style="--shadow-offset: {sizeMap[size].offset}; --width: {sizeMap[size] .width};" ></div> <style> .rcb-processing { width: var(--width, 12px); aspect-ratio: 1; border-radius: 50%; animation: l5 1.5s infinite linear; } @keyframes l5 { 0% { box-shadow: var(--shadow-offset) 0 #fff2, calc(-1 * var(--shadow-offset)) 0 #fff2; background: #fff2; } 25% { box-shadow: var(--shadow-offset) 0 #fff2, calc(-1 * var(--shadow-offset)) 0 #ffff; background: #fff2; } 50% { box-shadow: var(--shadow-offset) 0 #fff2, calc(-1 * var(--shadow-offset)) 0 #fff2; background: #ffff; } 75% { box-shadow: var(--shadow-offset) 0 #ffff, calc(-1 * var(--shadow-offset)) 0 #fff2; background: #fff2; } 100% { box-shadow: var(--shadow-offset) 0 #fff2, calc(-1 * var(--shadow-offset)) 0 #fff2; background: #fff2; } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/skeleton.svelte
Svelte
<script module> import { type Snippet } from "svelte"; </script> <script lang="ts"> export let children: Snippet; </script> <div class="rcb-pricing-table-value-loading">{@render children?.()}</div> <style> .rcb-pricing-table-value-loading { color: transparent; animation: rcb-pricing-table-value-loading 1.5s ease-in-out 0s infinite normal none running; cursor: progress; background-color: var(--rc-color-grey-text-dark); user-select: none; border-radius: var(--rc-shape-input-border-radius); } @keyframes rcb-pricing-table-value-loading { 0%, 100% { opacity: 0.5; } 50% { opacity: 0.3; } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/spinner.svelte
Svelte
<script> import Icon from "../../assets/spinner.svg?raw"; </script> <div style="color:var(--rc-color-accent);" class="rcb-ui-asset-icon"> {@html Icon} </div> <style> @-webkit-keyframes rotating /* Safari and Chrome */ { from { -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes rotating { from { -ms-transform: rotate(0deg); -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg); } to { -ms-transform: rotate(360deg); -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); -o-transform: rotate(360deg); transform: rotate(360deg); } } div { width: 80px; height: 80px; -webkit-animation: rotating 2s ease-in-out infinite; -moz-animation: rotating 2s ease-in-out infinite; -ms-animation: rotating 2s ease-in-out infinite; -o-animation: rotating 2s ease-in-out infinite; animation: rotating 2s ease-in-out infinite; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/atoms/text-separator.svelte
Svelte
<script> export let text; </script> <div class="text-separator"> <hr class="line" /> <span class="text">{text}</span> <hr class="line" /> </div> <style> .text-separator { display: flex; align-items: center; justify-content: center; gap: var(--rc-spacing-gapSmall-mobile); } @container layout-query-container (width >= 768px) { .text-separator { gap: var(--rc-spacing-gapSmall-desktop); } } .line { flex: 1; height: 1px; background-color: var(--rc-color-grey-ui-dark); border: none; } .text { font: var(--rc-text-caption-mobile); color: var(--rc-color-grey-text-light); text-transform: uppercase; white-space: nowrap; } @container layout-query-container (width >= 768px) { .text { font: var(--rc-text-caption-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/constants.ts
TypeScript
export const eventsTrackerContextKey = "rcb-ui-events-tracker";
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/container.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; import { Theme } from "../theme/theme"; import type { BrandingAppearance } from "../../entities/branding"; export let brandingAppearance: BrandingAppearance | null | undefined = undefined; export let isInElement: boolean = false; // Make styles reactive to changes in brandingAppearance $: textStyle = new Theme(brandingAppearance).textStyleVars; $: spacingStyle = new Theme(brandingAppearance).spacingStyleVars; $: style = [textStyle, spacingStyle].join("; "); export let children: Snippet; </script> <div class="rcb-ui-container" class:fullscreen={!isInElement} class:inside={isInElement} {style} > {@render children?.()} </div> <style> .rcb-ui-container { display: flex; flex-direction: column; inset: 0; color-scheme: none; font-size: 16px; line-height: 1.5em; font-weight: 400; font-family: -apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif; overflow-x: hidden; overflow-y: auto; } .rcb-ui-container.fullscreen { position: fixed; top: 0; left: 0; right: 0; bottom: 0; overscroll-behavior: none; z-index: 1000001; } .rcb-ui-container.inside { position: relative; width: 100%; z-index: unset; height: 100%; top: 0; left: 0; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/layout.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; export let style = ""; export let children: Snippet; </script> <div id="layout-query-container"> <div class="rcb-ui-layout" {style}> {@render children?.()} </div> </div> <style> #layout-query-container { width: 100%; height: 100%; container-type: size; container-name: layout-query-container; overflow-y: auto; overscroll-behavior: none; } .rcb-ui-layout { width: 100%; min-height: 100%; display: flex; box-sizing: border-box; flex-direction: column; overflow-y: auto; overscroll-behavior: none; } @container layout-query-container (width < 768px) { .rcb-ui-layout { flex-grow: 1; } } @container layout-query-container (width >= 768px) { .rcb-ui-layout { flex-direction: row; } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/main-block.svelte
Svelte
<script lang="ts"> import { Theme } from "../theme/theme"; import { onMount } from "svelte"; import SectionLayout from "./section-layout.svelte"; import type { BrandingAppearance } from "../../entities/branding"; export let brandingAppearance: BrandingAppearance | null | undefined = undefined; // Make style reactive to changes in brandingAppearance $: style = new Theme(brandingAppearance).formStyleVars; export let body; export let header: (() => any) | null = null; let showContent = true; // This makes the tests fail onMount(() => { setTimeout(() => (showContent = true), 10); }); </script> <div class="rcb-ui-main" {style}> <SectionLayout show={showContent} layoutStyle="" {header} {body} /> </div> <style> .rcb-ui-main { flex: 1; display: flex; background-color: var(--rc-color-background); } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/message-layout.svelte
Svelte
<script lang="ts"> import Button from "../atoms/button.svelte"; import ModalFooter from "./modal-footer.svelte"; import ModalSection from "./modal-section.svelte"; import RowLayout from "./row-layout.svelte"; import { type ContinueHandlerParams } from "../ui-types"; export let onContinue: (params?: ContinueHandlerParams) => void; export let title: string | null = null; export let type: string; export let closeButtonTitle: string = "Go back to app"; export let icon: (() => any) | null = null; export let message; function handleContinue() { onContinue(); } </script> <div class="message-layout"> <div class="message-layout-content"> <RowLayout gap="large"> <ModalSection> <div class="rcb-modal-message" data-type={type} data-has-title={!!title} > <RowLayout gap="large" align="center"> <RowLayout gap="large" align="center"> {#if icon} {@render icon()} {/if} {#if title} <span class="rcb-title">{title}</span> {/if} {#if message} <span class="rcb-subtitle"> {@render message()} </span> {/if} </RowLayout> </RowLayout> </div> </ModalSection> </RowLayout> </div> <div class="message-layout-footer"> <ModalFooter> <Button on:click={handleContinue} type="submit">{closeButtonTitle}</Button > </ModalFooter> </div> </div> <style> .message-layout { display: flex; flex-direction: column; } .message-layout-content { flex-grow: 1; display: flex; flex-direction: column; justify-content: center; } .rcb-modal-message { width: 100%; min-height: 160px; display: flex; justify-content: center; align-items: center; flex-direction: column; text-align: center; } .rcb-modal-message[data-has-title="false"] { margin-top: var(--rc-spacing-gapXXLarge-mobile); } .rcb-title { font: var(--rc-text-titleLarge-mobile); } .rcb-subtitle { font: var(--rc-text-body1-mobile); } @container layout-query-container (width < 768px) { .message-layout { flex-grow: 1; } } @container layout-query-container (width >= 768px) { .message-layout { min-height: 440px; } .message-layout-content { justify-content: flex-start; flex-grow: 1; } .message-layout-footer { margin-top: var(--rc-spacing-gapXXLarge-desktop); } .rcb-modal-message[data-has-title="false"] { margin-top: var(--rc-spacing-gapXXLarge-desktop); } .rcb-title { font: var(--rc-text-titleLarge-desktop); } .rcb-subtitle { font: var(--rc-text-body1-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/modal-footer.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; export let children: Snippet; </script> <footer class="rcb-modal-footer"> {@render children?.()} </footer> <style> footer { display: flex; flex-direction: column; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/modal-section.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; export let as = "section"; export let children: Snippet; </script> <svelte:element this={as} class={`rcb-modal-section`}> {@render children?.()} </svelte:element> <style> .rcb-modal-section { padding: 8px 0px; display: flex; } section.rcb-modal-section { flex-grow: 1; } .rcb-modal-section:last-of-type { padding: 0; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/navbar-header.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; import ModalSection from "./modal-section.svelte"; import CloseButton from "../molecules/close-button.svelte"; import BackButton from "../molecules/back-button.svelte"; export let children: Snippet; export let showCloseButton: boolean; export let onClose: (() => void) | undefined = undefined; </script> <ModalSection as="header"> <div class="rcb-header-multiline-layout"> {#if showCloseButton} <div class="rcb-back"> <BackButton on:click={() => { onClose && onClose(); }} /> </div> {/if} <div class="rcb-header-layout"> {@render children?.()} {#if showCloseButton} <div class="rcb-close"> <CloseButton on:click={() => { onClose && onClose(); }} /> </div> {/if} </div> </div> </ModalSection> <style> .rcb-header-multiline-layout { all: unset; display: flex; flex-direction: column; width: 100%; } .rcb-header-layout { display: flex; justify-content: space-between; align-items: center; width: 100%; font: var(--rc-text-titleXLarge-mobile); margin: 0; } .rcb-back { display: none; } .rcb-close { display: inline-block; } @container layout-query-container (width >= 768px) { .rcb-header-layout { width: auto; } .rcb-back { display: block; } .rcb-close { display: none; } .rcb-header-multiline-layout { gap: var(--rc-spacing-gapXLarge-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/navbar.svelte
Svelte
<script lang="ts"> import { Theme } from "../theme/theme"; import NavBarHeader from "./navbar-header.svelte"; import SectionLayout from "./section-layout.svelte"; import type { BrandingAppearance } from "../../entities/branding"; export let brandingAppearance: BrandingAppearance | null | undefined = undefined; $: style = new Theme(brandingAppearance).productInfoStyleVars; export let headerContent; export let bodyContent: () => any; export let showCloseButton: boolean; export let onClose: (() => void) | undefined = undefined; </script> <div class="rcb-ui-navbar" {style}> <SectionLayout layoutStyle="justify-content: flex-end;"> {#snippet header()} <NavBarHeader {showCloseButton} {onClose}> {@render headerContent?.()} </NavBarHeader> {/snippet} {#snippet body()} {@render bodyContent?.()} {/snippet} </SectionLayout> </div> <style> .rcb-ui-navbar { width: 100%; max-width: none; flex-shrink: 0; background-color: var(--rc-color-background); } @container layout-query-container (width >= 768px) { .rcb-ui-navbar { width: 50vw; display: flex; justify-content: flex-end; } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/row-layout.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; type Gap = "large" | "medium" | "small"; export let gap: Gap = "small"; export let align: "start" | "center" | "end" = "start"; export let children: Snippet; </script> <div class="rcb-column gap-{gap} align-{align}"> {@render children?.()} </div> <style> .rcb-column { display: flex; flex-direction: column; justify-content: flex-start; flex-grow: 1; } .rcb-column.align-center { justify-content: center; } .rcb-column.align-end { justify-content: flex-end; } .rcb-column.gap-small { gap: var(--rc-spacing-gapSmall-mobile); } .rcb-column.gap-medium { gap: var(--rc-spacing-gapMedium-mobile); } .rcb-column.gap-large { gap: var(--rc-spacing-gapXXLarge-mobile); } @container layout-query-container (width >= 768px) { .rcb-column.gap-small { gap: var(--rc-spacing-gapSmall-desktop); } .rcb-column.gap-medium { gap: var(--rc-spacing-gapMedium-desktop); } .rcb-column.gap-large { gap: var(--rc-spacing-gapXXLarge-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/section-layout.svelte
Svelte
<script lang="ts"> import { fade } from "svelte/transition"; export let show: boolean = true; export let layoutStyle: string | undefined = undefined; export let header: (() => any) | null = null; export let body: (() => any) | null = null; </script> <div class="layout-wrapper-outer" style={layoutStyle}> {#if show} <div class="layout-wrapper"> <div class="layout-content" transition:fade={{ duration: 500, delay: 50 }} > {#if header} {@render header()} {/if} {#if body} {@render body()} {/if} </div> </div> {/if} </div> <style> .layout-wrapper-outer { flex: 1; display: flex; background-color: var(--rc-color-background); } .layout-wrapper { width: 100%; } .layout-content { box-sizing: border-box; background-color: var(--rc-color-background); color: var(--rc-color-grey-text-dark); display: flex; flex-direction: column; padding: var(--rc-spacing-outerPadding-mobile); } @container layout-query-container (width >= 768px) { .layout-wrapper { min-height: 100vh; flex-basis: 600px; } } @container layout-query-container (width >= 768px) and (width <= 1024px) { .layout-content { padding: var(--rc-spacing-outerPadding-tablet); } } @container layout-query-container (width > 1024px) { .layout-content { padding: var(--rc-spacing-outerPadding-desktop); } } @container layout-query-container (width < 768px) { .layout-wrapper { width: 100%; min-width: 300px; display: flex; flex-grow: 1; } .layout-content { flex-grow: 1; height: 100%; } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/layout/template.svelte
Svelte
<script lang="ts"> import Container from "./container.svelte"; import Layout from "./layout.svelte"; import NavBar from "./navbar.svelte"; import SandboxBanner from "../molecules/sandbox-banner.svelte"; import Main from "./main-block.svelte"; import { type BrandingInfoResponse } from "../../networking/responses/branding-response"; import BrandingInfoUI from "../molecules/branding-info.svelte"; import { type Snippet } from "svelte"; import { toProductInfoStyleVar } from "../theme/utils"; export interface Props { brandingInfo: BrandingInfoResponse | null; isInElement: boolean; isSandbox: boolean; onClose: (() => void) | undefined; navbarContent: Snippet<[]>; mainContent: Snippet<[]>; } const { brandingInfo, isInElement, isSandbox, onClose, navbarContent, mainContent, }: Props = $props(); const colorVariables = $derived( toProductInfoStyleVar(brandingInfo?.appearance) ?? "", ); </script> <Container brandingAppearance={brandingInfo?.appearance} {isInElement}> {#if isSandbox} <SandboxBanner style={colorVariables} {isInElement} /> {/if} <Layout style={colorVariables}> <NavBar brandingAppearance={brandingInfo?.appearance} {onClose} showCloseButton={!isInElement} > {#snippet headerContent()} <BrandingInfoUI {brandingInfo} /> {/snippet} {#snippet bodyContent()} {@render navbarContent?.()} {/snippet} </NavBar> <Main brandingAppearance={brandingInfo?.appearance}> {#snippet body()} {@render mainContent?.()} {/snippet} </Main> </Layout> </Container>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/localization/constants.ts
TypeScript
export const translatorContextKey = "rcb-ui-translator"; export const englishLocale = "en";
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/localization/localized.svelte
Svelte
<script lang="ts"> import { type EmptyString, type TranslationVariables, Translator, } from "./translator"; import { getContext } from "svelte"; import { translatorContextKey } from "./constants"; import { LocalizationKeys } from "./supportedLanguages"; import { type Writable } from "svelte/store"; interface LocalizedProps { key?: LocalizationKeys | EmptyString | undefined; variables?: TranslationVariables; children?: any; } const { key = "", variables, children }: LocalizedProps = $props(); const translator = getContext<Writable<Translator>>(translatorContextKey); const translatedLabel = $derived( key ? $translator.translate( (key as LocalizationKeys) || ("" as EmptyString), variables, ) : undefined, ); </script> {#if translatedLabel} {translatedLabel} {:else} {@render children?.()} {/if}
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/localization/supportedLanguages.ts
TypeScript
import en from "./locale/en.json"; import es from "./locale/es.json"; import it from "./locale/it.json"; import ar from "./locale/ar.json"; import ca from "./locale/ca.json"; import zh_Hans from "./locale/zh_Hans.json"; import zh_Hant from "./locale/zh_Hant.json"; import hr from "./locale/hr.json"; import cs from "./locale/cs.json"; import da from "./locale/da.json"; import nl from "./locale/nl.json"; import fi from "./locale/fi.json"; import fr from "./locale/fr.json"; import de from "./locale/de.json"; import el from "./locale/el.json"; import he from "./locale/he.json"; import hi from "./locale/hi.json"; import hu from "./locale/hu.json"; import id from "./locale/id.json"; import ja from "./locale/ja.json"; import ko from "./locale/ko.json"; import ms from "./locale/ms.json"; import no from "./locale/no.json"; import pl from "./locale/pl.json"; import pt from "./locale/pt.json"; import ro from "./locale/ro.json"; import ru from "./locale/ru.json"; import sk from "./locale/sk.json"; import sv from "./locale/sv.json"; import th from "./locale/th.json"; import tr from "./locale/tr.json"; import uk from "./locale/uk.json"; import vi from "./locale/vi.json"; export enum LocalizationKeys { PeriodsWeek = "periods.week", PeriodsMonth = "periods.month", PeriodsYear = "periods.year", PeriodsDay = "periods.day", PeriodsWeekShort = "periods.weekShort", PeriodsMonthShort = "periods.monthShort", PeriodsYearShort = "periods.yearShort", PeriodsDayShort = "periods.dayShort", PeriodsLifetime = "periods.lifetime", PeriodsWeekPlural = "periods.weekPlural", PeriodsMonthPlural = "periods.monthPlural", PeriodsYearPlural = "periods.yearPlural", PeriodsDayPlural = "periods.dayPlural", PeriodsWeekFrequency = "periods.weekFrequency", PeriodsMonthFrequency = "periods.monthFrequency", PeriodsYearFrequency = "periods.yearFrequency", PeriodsDayFrequency = "periods.dayFrequency", PeriodsPerWeekFrequency = "periods.perWeekFrequency", PeriodsPerMonthFrequency = "periods.perMonthFrequency", PeriodsPerYearFrequency = "periods.perYearFrequency", PeriodsPerDayFrequency = "periods.perDayFrequency", PeriodsUnknownFrequency = "periods.unknownFrequency", PeriodsWeekFrequencyPlural = "periods.weekFrequencyPlural", PeriodsMonthFrequencyPlural = "periods.monthFrequencyPlural", PeriodsYearFrequencyPlural = "periods.yearFrequencyPlural", PeriodsDayFrequencyPlural = "periods.dayFrequencyPlural", ProductInfoProductTitle = "product_info.product_title", ProductInfoProductDescription = "product_info.product_description", ProductInfoProductPrice = "product_info.product_price", ProductInfoFreeTrialDuration = "product_info.free_trial_duration", ProductInfoPriceAfterFreeTrial = "product_info.price_after_free_trial", ProductInfoPriceTotalDueToday = "product_info.total_due_today", ProductInfoSubscribeTo = "product_info.subscribe_to", ProductInfoRenewalFrequency = "product_info.renewal_frequency", ProductInfoContinuesUntilCancelled = "product_info.continues_until_cancelled", ProductInfoCancelAnytime = "product_info.cancel_anytime", EmailEntryPageEmailStepTitle = "email_entry_page.email_step_title", EmailEntryPageEmailInputLabel = "email_entry_page.email_input_label", EmailEntryPageEmailInputPlaceholder = "email_entry_page.email_input_placeholder", EmailEntryPageButtonContinue = "email_entry_page.button_continue", PaymentEntryPagePaymentStepTitle = "payment_entry_page.payment_step_title", PaymentEntryPageTermsInfo = "payment_entry_page.terms_info", PaymentEntryPageTrialInfo = "payment_entry_page.trial_info", PaymentEntryPageButtonPay = "payment_entry_page.button_pay", PaymentEntryPageButtonStartTrial = "payment_entry_page.button_start_trial", SuccessPagePurchaseSuccessful = "success_page.purchase_successful", SuccessPageSubscriptionNowActive = "success_page.subscription_now_active", SuccessPageButtonClose = "success_page.button_close", ErrorPageIfErrorPersists = "error_page.if_error_persists", ErrorPageErrorTitleAlreadySubscribed = "error_page.error_title_already_subscribed", ErrorPageErrorTitleAlreadyPurchased = "error_page.error_title_already_purchased", ErrorPageErrorTitleOtherErrors = "error_page.error_title_other_errors", ErrorPageErrorMessageAlreadySubscribed = "error_page.error_message_already_subscribed", ErrorPageErrorMessageAlreadyPurchased = "error_page.error_message_already_purchased", ErrorPageErrorMessageMissingEmailError = "error_page.error_message_missing_email_error", ErrorPageErrorMessageNetworkError = "error_page.error_message_network_error", ErrorPageErrorMessageErrorChargingPayment = "error_page.error_message_error_charging_payment", ErrorPageErrorMessageErrorSettingUpPurchase = "error_page.error_message_error_setting_up_purchase", ErrorPageErrorMessageUnknownError = "error_page.error_message_unknown_error", ErrorButtonTryAgain = "error_page.button_try_again", PaywallVariablesPricePerPeriod = "paywall_variables.price_per_period", PaywallVariablesSubRelativeDiscount = "paywall_variables.sub_relative_discount", PaywallVariablesTotalPriceAndPerMonth = "paywall_variables.total_price_and_per_month", PricingDropdownShowDetails = "pricing_dropdown.show_details", PricingDropdownHideDetails = "pricing_dropdown.hide_details", PricingTotalExcludingTax = "pricing_table.total_excluding_tax", PricingTableTrialEnds = "pricing_table.trial_ends", PricingTableTotalDueToday = "pricing_table.total_due_today", PricingTableTax = "pricing_table.tax", PricingTableEnterBillingAddressToCalculate = "pricing_table.enter_billing_address_to_calculate", PricingTableEnterStateOrPostalCodeToCalculate = "pricing_table.enter_state_or_postal_code_to_calculate", PricingTableEnterPostalCodeToCalculate = "pricing_table.enter_postal_code_to_calculate", NavbarHeaderDetails = "navbar_header.details", NavbarBackButton = "navbar_header.back_button", } export const supportedLanguages: Record< string, Record<LocalizationKeys, string> > = { en, es, it, ar, ca, zh_Hans, zh_Hant, hr, cs, da, nl, fi, fr, de, el, he, hi, hu, id, ja, ko, ms, no, pl, pt, ro, ru, sk, sv, th, tr, uk, vi, };
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/localization/translator.ts
TypeScript
import { Logger } from "../../helpers/logger"; import type { PeriodUnit } from "../../helpers/duration-helper"; import { englishLocale } from "./constants"; import type { LocalizationKeys } from "./supportedLanguages"; import { supportedLanguages } from "./supportedLanguages"; import { formatPrice } from "../../helpers/price-labels"; import { capitalize } from "../../helpers/string-helpers"; export type EmptyString = ""; /** * Custom translations to be used in the purchase flow. * This class allows you to override the default translations used in the purchase flow. * The main level keys are the locale codes and the values are objects with the same keys as the default translations. * @public * @example * This example will override the default translation for the email step title in the English locale. * ```typescript * const customTranslations = { * en: { * "email_entry_page.email_step_title": "Billing email", * } * } * ``` */ export type CustomTranslations = { [langKey: string]: { [translationKey in LocalizationKeys]?: string }; }; /** * Translation variables to be used in the translation. * This class allows you to pass variables to the translate method. * @public * @example Given a label with id `periods.monthPlural` and value `{{amount}} months`. This example will replace the variable `{{amount}}` with the value `10`. * ```typescript * translator.translate('periods.monthPlural', { amount: 10 }); * // Output: 10 months * ``` */ export type TranslationVariables = Record< string, string | number | undefined | null >; export interface TranslatePeriodOptions { noWhitespace?: boolean; short?: boolean; } export interface TranslateFrequencyOptions { useMultipleWords?: boolean; } const defaultTranslatePeriodOptions: TranslatePeriodOptions = { noWhitespace: false, short: false, }; const defaultTranslateFrequencyOptions: TranslateFrequencyOptions = { useMultipleWords: false, }; export class Translator { public readonly locales: Record<string, LocaleTranslations> = {}; public static fallback() { return new Translator(); } public constructor( customTranslations: CustomTranslations = {}, public readonly selectedLocale: string = englishLocale, public readonly defaultLocale: string = englishLocale, ) { const locales: Record<string, LocaleTranslations> = {}; Object.entries(supportedLanguages).forEach(([locale, translations]) => { locales[locale] = new LocaleTranslations(translations, locale); }); this.locales = locales; if (customTranslations) { this.override(customTranslations); } } public override(customTranslations: CustomTranslations) { Object.entries(customTranslations).forEach(([locale, translations]) => { this.locales[locale] = new LocaleTranslations( { ...(this.locales[locale].labels || {}), ...translations, }, this.getLanguageCodeString(locale), ); }); } public formatPrice(priceInMicros: number, currency: string): string { const additionalFormattingOptions: { maximumFractionDigits?: number; currencyDisplay?: "narrowSymbol"; } = { currencyDisplay: "narrowSymbol" }; if (priceInMicros === 0) { additionalFormattingOptions.maximumFractionDigits = 0; } try { return formatPrice( priceInMicros, currency, this.locale, additionalFormattingOptions, ); } catch { Logger.errorLog( `Failed to create a price formatter for locale: ${this.locale}`, ); } try { return formatPrice( priceInMicros, currency, this.fallbackLocale, additionalFormattingOptions, ); } catch { Logger.errorLog( `Failed to create a price formatter for locale: ${this.fallbackLocale}`, ); } return formatPrice( priceInMicros, currency, englishLocale, additionalFormattingOptions, ); } get locale(): string { return ( this.getLocaleInstance(this.selectedLocale)?.localeKey || this.getLanguageCodeString(this.selectedLocale) ); } get fallbackLocale(): string { return ( this.getLocaleInstance(this.defaultLocale)?.localeKey || this.getLanguageCodeString(this.defaultLocale) ); } private getLanguageCodeString(locale: string): string { return locale.split("_")[0].split("-")[0]; } private getLocaleInstance(locale: string): LocaleTranslations | undefined { const potentialLocaleCode = this.getLanguageCodeString(locale); return this.locales[locale] || this.locales[potentialLocaleCode]; } public translate( key: LocalizationKeys | EmptyString, variables?: TranslationVariables, ): string { const localeInstance = this.getLocaleInstance(this.selectedLocale); const fallbackInstance = this.getLocaleInstance(this.defaultLocale); return ( localeInstance?.translate(key, variables) || fallbackInstance?.translate(key, variables) || "" ); } public formatCountry(countryCode: string): string { return ( new Intl.DisplayNames([this.locale], { type: "region" }).of( countryCode, ) || countryCode ); } public translatePeriod( amount: number, period: PeriodUnit, options: TranslatePeriodOptions = defaultTranslatePeriodOptions, ): string | undefined { const localeInstance = this.getLocaleInstance(this.selectedLocale); const fallbackInstance = this.getLocaleInstance(this.defaultLocale); return ( localeInstance?.translatePeriod(amount, period, options) || fallbackInstance?.translatePeriod(amount, period, options) ); } public translatePeriodUnit( period: PeriodUnit, options: TranslatePeriodOptions = defaultTranslatePeriodOptions, ): string | undefined { const localeInstance = this.getLocaleInstance(this.selectedLocale); const fallbackInstance = this.getLocaleInstance(this.defaultLocale); return ( localeInstance?.translatePeriodUnit(period, options) || fallbackInstance?.translatePeriodUnit(period, options) ); } public translatePeriodFrequency( amount: number, period: PeriodUnit, options: TranslateFrequencyOptions = defaultTranslateFrequencyOptions, ): string | undefined { const localeInstance = this.getLocaleInstance(this.selectedLocale); const fallbackInstance = this.getLocaleInstance(this.defaultLocale); return ( localeInstance?.translatePeriodFrequency(amount, period, options) || fallbackInstance?.translatePeriodFrequency(amount, period, options) ); } public translateDate( date: Date, options: Intl.DateTimeFormatOptions = {}, ): string | undefined { const localeInstance = this.getLocaleInstance(this.selectedLocale); const fallbackInstance = this.getLocaleInstance(this.defaultLocale); return ( localeInstance?.translateDate(date, options) || fallbackInstance?.translateDate(date, options) ); } } export class LocaleTranslations { public constructor( public readonly labels: Record<string, string> = {}, public readonly localeKey: string, ) {} private replaceVariables( label: string, variables: TranslationVariables, ): string { return Object.entries(variables).reduce( (acc, [key, value]) => acc.replace( `{{${key}}}`, `${value === undefined || value === null ? "" : value}`, ), label, ); } public translate( labelId: LocalizationKeys | EmptyString, variables?: TranslationVariables, ): string | undefined { const label = this.labels[labelId]; if (!label) return undefined; return this.replaceVariables(label, variables || {}); } public translatePeriod( amount: number, period: PeriodUnit, options: TranslatePeriodOptions = defaultTranslatePeriodOptions, ): string | undefined { const { noWhitespace, short } = { ...defaultTranslatePeriodOptions, ...options, }; const key = short ? `periods.${period}Short` : Math.abs(amount) === 1 ? `periods.${period}` : `periods.${period}Plural`; return this.translate(key as LocalizationKeys, { amount: amount.toString(), })?.replace(" ", noWhitespace ? "" : " "); } public translatePeriodUnit( period: PeriodUnit, options: TranslatePeriodOptions = defaultTranslatePeriodOptions, ): string | undefined { const { noWhitespace, short } = { ...defaultTranslatePeriodOptions, ...options, }; const key = `periods.${period}${short ? "Short" : ""}`; return this.translate(key as LocalizationKeys, { amount: "" })?.replace( " ", noWhitespace ? "" : " ", ); } public translatePeriodFrequency( amount: number, period: PeriodUnit, options: TranslateFrequencyOptions = defaultTranslateFrequencyOptions, ): string | undefined { const useMultipleWords = options?.useMultipleWords; const key = Math.abs(amount) === 1 ? `periods.${useMultipleWords === true ? "per" : ""}${useMultipleWords ? capitalize(period.toString()) : period}Frequency` : `periods.${period}FrequencyPlural`; return this.translate(key as LocalizationKeys, { amount: amount.toString(), }); } public translateDate( date: Date, options: Intl.DateTimeFormatOptions = {}, ): string | undefined { return date.toLocaleDateString(this.localeKey, options); } }
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/back-button.svelte
Svelte
<script lang="ts"> import Icon from "../atoms/icon.svelte"; import Localized from "../localization/localized.svelte"; import { LocalizationKeys } from "../localization/supportedLanguages"; </script> <button on:click class="rcb-back-button" data-testid="close-button"> <Icon name="chevron-left" /> <Localized key={LocalizationKeys.NavbarBackButton} /> </button> <style> .rcb-back-button { border: none; cursor: pointer; background-color: transparent; padding: 0; border-radius: 50%; color: var(--rc-color-grey-text-dark); /* This button is only shown in desktop layout*/ font: var(--rc-text-body1-desktop); display: flex; align-items: center; justify-content: center; } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/branding-info.svelte
Svelte
<script lang="ts"> import AppLogo from "../atoms/app-logo.svelte"; import { type BrandingInfoResponse } from "../../networking/responses/branding-response"; import { buildAssetURL } from "../../networking/assets"; export let brandingInfo: BrandingInfoResponse | null = null; const valueOrNull = (value: string | null | undefined) => { if (value == null) return null; if (value == undefined) return null; if (value == "") return null; return value; }; const appIcon = valueOrNull(brandingInfo?.app_icon); const webpIcon = valueOrNull(brandingInfo?.app_icon_webp); </script> <div class="rcb-header-layout__business-info"> {#if appIcon !== null && webpIcon !== null} <AppLogo src={buildAssetURL(appIcon)} srcWebp={buildAssetURL(webpIcon)} /> {/if} <div class="rcb-app-name"> {brandingInfo?.app_name} </div> </div> <style> .rcb-header-layout__business-info { display: flex; align-items: center; } .rcb-app-name { font: var(--rc-text-titleMedium-mobile); } @container layout-query-container (width >= 768px) { .rcb-app-name { font: var(--rc-text-titleLarge-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/close-button.svelte
Svelte
<script lang="ts"> import Icon from "../../assets/close.svg?raw"; </script> <button on:click class="rcb-close-button" data-testid="close-button"> {@html Icon} </button> <style> .rcb-close-button { border: none; cursor: pointer; background-color: transparent; padding: 0; height: 24px; width: 24px; padding: 4px; border-radius: 50%; color: inherit; display: flex; align-items: center; justify-content: center; } .rcb-close-button:active { transition: outline 0.1s ease-in-out; outline: 2px solid var(--rc-color-focus); } .rcb-close-button:hover { color: var(--rc-color-grey-text-dark); } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/loading.svelte
Svelte
<script> import Spinner from "../atoms/spinner.svelte"; let style = ""; </script> <div class="rcb-modal-loader"> <Spinner /> </div> <style> .rcb-modal-loader { width: 100%; flex-grow: 1; display: flex; justify-content: center; align-items: center; } @container layout-query-container (width >= 768px) { .rcb-modal-loader { align-items: flex-start; margin-top: calc(var(--rc-spacing-gapXXLarge-desktop) * 6); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/payment-button.svelte
Svelte
<script lang="ts"> import { type SubscriptionOption } from "../../entities/offerings"; import Button from "../atoms/button.svelte"; import Localized from "../localization/localized.svelte"; import { LocalizationKeys } from "../localization/supportedLanguages"; export let disabled: boolean; export let subscriptionOption: SubscriptionOption | null; </script> <Button {disabled} testId="PayButton"> {#if subscriptionOption?.trial} <Localized key={LocalizationKeys.PaymentEntryPageButtonStartTrial} /> {:else} <Localized key={LocalizationKeys.PaymentEntryPageButtonPay} /> {/if} </Button>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/pricing-dropdown.svelte
Svelte
<script lang="ts"> import { type Snippet } from "svelte"; import Icon from "../atoms/icon.svelte"; import { LocalizationKeys } from "../localization/supportedLanguages"; import { translatorContextKey } from "../localization/constants"; import { getContext } from "svelte"; import { type Writable } from "svelte/store"; import { Translator } from "../localization/translator"; export let isExpanded: boolean = true; export let children: Snippet; const translator: Writable<Translator> = getContext(translatorContextKey); function toggleExpanded() { isExpanded = !isExpanded; } </script> <div class="rcb-pricing-dropdown"> <div class="rcb-pricing-dropdown-header" on:click={toggleExpanded} on:keydown={(e) => e.key === "Enter" || e.key === " " ? toggleExpanded() : null} tabindex="0" role="button" aria-expanded={isExpanded} > {#if isExpanded} {$translator.translate(LocalizationKeys.PricingDropdownHideDetails)} {:else} {$translator.translate(LocalizationKeys.PricingDropdownShowDetails)} {/if} <span class="rcb-pricing-dropdown-toggle"> {#if isExpanded} <Icon name="chevron-up" /> {:else} <Icon name="chevron-down" /> {/if} </span> </div> <div class="rcb-pricing-dropdown-content" class:collapsed={!isExpanded}> {@render children?.()} </div> </div> <style> .rcb-pricing-dropdown { width: 100%; overflow: hidden; display: flex; flex-direction: column; gap: var(--rc-spacing-gapMedium-mobile); } .rcb-pricing-dropdown-header { padding-top: var(--rc-spacing-gapSmall-mobile); padding-bottom: var(--rc-spacing-gapSmall-mobile); padding-left: var(--rc-spacing-gapLarge-mobile); padding-right: var(--rc-spacing-gapMedium-mobile); font: var(--rc-text-largeCaption-mobile); color: var(--rc-color-grey-text-light); border-radius: var(--rc-shape-input-button-border-radius); cursor: pointer; display: inline-flex; align-items: center; background-color: var(--rc-color-grey-ui-light); width: fit-content; user-select: none; } .rcb-pricing-dropdown-toggle { display: flex; align-items: center; margin-left: var(--rc-spacing-gapSmall-mobile); font: var(--rc-text-caption-mobile); } .rcb-pricing-dropdown-content { display: flex; flex-direction: column; overflow: hidden; } @container layout-query-container (width < 768px) { .rcb-pricing-dropdown-content { max-height: 1000px; /* Set a large max-height for animation */ transition: max-height 0.2s ease-in-out; } .rcb-pricing-dropdown-content.collapsed { max-height: 0; } } @container layout-query-container (width >= 768px) { .rcb-pricing-dropdown-header { display: none; } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/pricing-summary.svelte
Svelte
<script lang="ts"> import { type Writable } from "svelte/store"; import Localized from "../localization/localized.svelte"; import { LocalizationKeys } from "../localization/supportedLanguages"; import { Translator } from "../localization/translator"; import { getContext } from "svelte"; import { translatorContextKey } from "../localization/constants"; import { getTranslatedPeriodLength } from "../../helpers/price-labels"; import { type PriceBreakdown } from "../ui-types"; import { type PricingPhase } from "../../entities/offerings"; export type Props = { priceBreakdown: PriceBreakdown; basePhase: PricingPhase | null; trialPhase: PricingPhase | null; }; let { priceBreakdown, basePhase, trialPhase }: Props = $props(); const translator: Writable<Translator> = getContext(translatorContextKey); const formattedPrice = $derived( $translator.formatPrice( priceBreakdown.totalAmountInMicros, priceBreakdown.currency, ), ); </script> <div class="rcb-product-price-container"> {#if trialPhase?.periodDuration} <div class="rcb-product-trial"> <Localized key={LocalizationKeys.ProductInfoFreeTrialDuration} variables={{ trialDuration: getTranslatedPeriodLength( trialPhase.periodDuration, $translator, ), }} /> </div> {/if} <div> <span class="rcb-product-price"> <Localized key={LocalizationKeys.ProductInfoProductPrice} variables={{ productPrice: formattedPrice, }} /> </span> {#if basePhase?.period} <span class="rcb-product-price-frequency"> <span class="rcb-product-price-frequency-text"> {$translator.translatePeriodFrequency( basePhase.period.number, basePhase.period.unit, { useMultipleWords: true }, )}</span > </span> {/if} </div> </div> <style> .rcb-product-price { color: var(--rc-color-grey-text-dark); font: var(--rc-text-titleMedium-mobile); } @container layout-query-container (width >= 768px) { .rcb-product-price { font: var(--rc-text-titleMedium-desktop); } } .rcb-product-price-container { display: flex; flex-direction: column; justify-content: space-between; gap: var(--rc-spacing-gapMedium-mobile); } .rcb-product-trial { color: var(--rc-color-grey-text-dark); font: var(--rc-text-titleLarge-mobile); } .rcb-product-price-frequency { color: var(--rc-color-grey-text-dark); font: var(--rc-text-body1-mobile); } .rcb-product-price-frequency-text { white-space: nowrap; } @container layout-query-container (width >= 768px) { .rcb-product-price-frequency { font: var(--rc-text-body1-desktop); } .rcb-product-trial { font: var(--rc-text-titleLarge-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/pricing-table.svelte
Svelte
<script lang="ts"> import { type Writable } from "svelte/store"; import { type Translator } from "../localization/translator"; import { getContext } from "svelte"; import { translatorContextKey } from "../localization/constants"; import { LocalizationKeys } from "../localization/supportedLanguages"; import { type PriceBreakdown } from "../ui-types"; import { getNextRenewalDate } from "../../helpers/duration-helper"; import { type PricingPhase } from "../../entities/offerings"; import PricingDropdown from "./pricing-dropdown.svelte"; import Skeleton from "../atoms/skeleton.svelte"; interface Props { priceBreakdown: PriceBreakdown; trialPhase: PricingPhase | null; } let { priceBreakdown, trialPhase }: Props = $props(); let trialEndDate = $state<Date | null>(null); if (trialPhase?.period) { trialEndDate = getNextRenewalDate(new Date(), trialPhase.period, true); } const translator: Writable<Translator> = getContext(translatorContextKey); </script> {#snippet pricingTable()} <div class="rcb-pricing-table"> {#if priceBreakdown.taxCollectionEnabled} <div class="rcb-pricing-table-row"> <div class="rcb-pricing-table-header"> {$translator.translate(LocalizationKeys.PricingTotalExcludingTax)} </div> <div class="rcb-pricing-table-value"> {$translator.formatPrice( priceBreakdown.totalExcludingTaxInMicros, priceBreakdown.currency, )} </div> </div> {#if priceBreakdown.taxCalculationStatus === "loading"} <div class="rcb-pricing-table-row"> <div class="rcb-pricing-table-header"> {$translator.translate(LocalizationKeys.PricingTableTax)} </div> <div class="rcb-pricing-table-value"> <Skeleton> {$translator.formatPrice(12340000, priceBreakdown.currency)} </Skeleton> </div> </div> {:else if priceBreakdown.taxCalculationStatus === "pending"} <div class="rcb-pricing-table-row"> <div class="rcb-pricing-table-header"> {$translator.translate(LocalizationKeys.PricingTableTax)} </div> <div class="rcb-pricing-table-value"> {#if priceBreakdown.pendingReason === "needs_postal_code"} {$translator.translate( LocalizationKeys.PricingTableEnterPostalCodeToCalculate, )} {:else if priceBreakdown.pendingReason === "needs_state_or_postal_code"} {$translator.translate( LocalizationKeys.PricingTableEnterStateOrPostalCodeToCalculate, )} {:else} {$translator.translate( LocalizationKeys.PricingTableEnterBillingAddressToCalculate, )} {/if} </div> </div> {:else if priceBreakdown.taxBreakdown !== null} {#each priceBreakdown.taxBreakdown as taxItem} <div class="rcb-pricing-table-row"> <div class="rcb-pricing-table-header"> {taxItem.display_name} </div> <div class="rcb-pricing-table-value"> {$translator.formatPrice( taxItem.tax_amount_in_micros, priceBreakdown.currency, )} </div> </div> {/each} {/if} <div class="rcb-pricing-table-separator"></div> {/if} {#if trialEndDate} <div class="rcb-pricing-table-row"> <div class="rcb-pricing-table-header"> {$translator.translate(LocalizationKeys.PricingTableTrialEnds, { formattedTrialEndDate: $translator.translateDate(trialEndDate, { dateStyle: "medium", }), })} </div> <div class="rcb-pricing-table-value"> {$translator.formatPrice( priceBreakdown.totalAmountInMicros, priceBreakdown.currency, )} </div> </div> {/if} <div class="rcb-pricing-table-row rcb-header"> <div class="rcb-pricing-table-header"> {$translator.translate(LocalizationKeys.PricingTableTotalDueToday)} </div> <div class="rcb-pricing-table-value"> {#if trialEndDate} {$translator.formatPrice(0, priceBreakdown.currency)} {:else} {$translator.formatPrice( priceBreakdown.totalAmountInMicros, priceBreakdown.currency, )} {/if} </div> </div> </div> {/snippet} {#if priceBreakdown.taxCollectionEnabled} <PricingDropdown> {@render pricingTable()} </PricingDropdown> {:else} {@render pricingTable()} {/if} <style> .rcb-pricing-table { display: flex; flex-direction: column; gap: var(--rc-spacing-gapMedium-mobile); font: var(--rc-text-caption-mobile); } .rcb-pricing-table-row { display: flex; flex-direction: row; align-items: center; justify-content: space-between; } .rcb-pricing-table-separator { height: 1px; background-color: var(--rc-color-grey-ui-dark); } .rcb-pricing-table-row > .rcb-pricing-table-header { color: var(--rc-color-grey-text-light); } .rcb-pricing-table-row > .rcb-pricing-table-value { color: var(--rc-color-grey-text-dark); } .rcb-pricing-table-row:last-child > .rcb-pricing-table-header, .rcb-pricing-table-row:last-child > .rcb-pricing-table-value { color: var(--rc-color-grey-text-dark); } @container layout-query-container (width >= 768px) { .rcb-pricing-table-separator { display: none; } .rcb-pricing-table { gap: var(--rc-spacing-gapSmall-desktop); } .rcb-pricing-table-row > .rcb-pricing-table-header, .rcb-pricing-table-row > .rcb-pricing-table-value { font: var(--rc-text-caption-desktop); color: var(--rc-color-grey-text-light); } .rcb-pricing-table-row:last-child { padding-top: var(--rc-spacing-gapSmall-desktop); } .rcb-pricing-table-row:last-child > .rcb-pricing-table-header, .rcb-pricing-table-row:last-child > .rcb-pricing-table-value { font: var(--rc-text-body1-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/product-header.svelte
Svelte
<script lang="ts"> import Localized from "../localization/localized.svelte"; import { LocalizationKeys } from "../localization/supportedLanguages"; import { ProductType, type Product } from "../../entities/offerings"; export let productDetails: Product; export let showProductDescription: boolean; const isSubscription = productDetails.productType === ProductType.Subscription; </script> <div class="rcb-pricing-info-header"> {#if isSubscription} <div class="rcb-subscribe-to only-desktop"> <Localized key={LocalizationKeys.ProductInfoSubscribeTo} variables={{ productTitle: productDetails.title }} /> </div> {/if} <div class="rcb-product-title"> <Localized key={LocalizationKeys.ProductInfoProductTitle} variables={{ productTitle: productDetails.title }} /> </div> {#if showProductDescription && productDetails.description} <span class="rcb-product-description"> <Localized key={LocalizationKeys.ProductInfoProductDescription} variables={{ productDescription: productDetails.description, }} /> </span> {/if} </div> <style> .rcb-pricing-info-header { display: flex; flex-direction: column; gap: var(--rc-spacing-gapSmall-desktop); } .rcb-product-title { color: var(--rc-color-grey-text-dark); font: var(--rc-text-titleXLarge-mobile); } .rcb-product-description { font: var(--rc-text-body1-mobile); color: var(--rc-color-grey-text-light); } .rcb-subscribe-to { font: var(--rc-text-body1-desktop); } .only-desktop { display: none; } @container layout-query-container (width >= 768px) { .only-desktop { display: block; } .rcb-pricing-info-header { display: flex; flex-direction: column; gap: var(--rc-spacing-gapXLarge-desktop); } .rcb-product-title { font: var(--rc-text-titleXLarge-desktop); } .rcb-product-description { font: var(--rc-text-body1-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/product-pricing/non-subscription-pricing.svelte
Svelte
<script lang="ts"> import Localized from "../../localization/localized.svelte"; import { LocalizationKeys } from "../../localization/supportedLanguages"; import { type NonSubscriptionOption } from "../../../entities/offerings"; import type { Translator } from "../../localization/translator"; import { translatorContextKey } from "../../localization/constants"; import { type Writable } from "svelte/store"; import { getContext } from "svelte"; export let purchaseOption: NonSubscriptionOption; const basePrice = purchaseOption?.basePrice; const translator: Writable<Translator> = getContext(translatorContextKey); const formattedNonSubscriptionBasePrice = basePrice && $translator.formatPrice(basePrice.amountMicros, basePrice.currency); </script> <span class="rcb-product-price"> <Localized key={LocalizationKeys.ProductInfoProductPrice} variables={{ productPrice: formattedNonSubscriptionBasePrice }} /> </span> <style> .rcb-product-price { color: var(--rc-color-grey-text-dark); font: var(--rc-text-titleMedium-mobile); } @container layout-query-container (width >= 768px) { .rcb-product-price { font: var(--rc-text-titleMedium-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui
src/ui/molecules/product-pricing/subscription-pricing.svelte
Svelte
<script lang="ts"> import Localized from "../../localization/localized.svelte"; import { LocalizationKeys } from "../../localization/supportedLanguages"; import type { Translator } from "../../localization/translator"; import { type SubscriptionOption } from "../../../entities/offerings"; import { getTranslatedPeriodLength } from "../../../helpers/price-labels"; import { translatorContextKey } from "../../localization/constants"; import { type Writable } from "svelte/store"; import { getContext } from "svelte"; import { getNextRenewalDate } from "../../../helpers/duration-helper"; export let purchaseOption: SubscriptionOption; const subscriptionBasePrice = purchaseOption?.base?.price; const translator: Writable<Translator> = getContext(translatorContextKey); let renewalDate = null; const expectedPeriod = purchaseOption?.trial?.period || purchaseOption?.base?.period; if (expectedPeriod) { renewalDate = getNextRenewalDate(new Date(), expectedPeriod, true); } const formattedSubscriptionBasePrice = subscriptionBasePrice && $translator.formatPrice( subscriptionBasePrice.amountMicros, subscriptionBasePrice.currency, ); const formattedZeroPrice = subscriptionBasePrice && $translator.formatPrice(0, subscriptionBasePrice.currency); </script> <div class="rcb-product-price-container"> {#if purchaseOption?.trial?.periodDuration} <div class="rcb-product-trial"> <Localized key={LocalizationKeys.ProductInfoFreeTrialDuration} variables={{ trialDuration: getTranslatedPeriodLength( purchaseOption.trial.periodDuration || "", $translator, ), }} /> </div> {/if} <div> {#if subscriptionBasePrice} <span class="rcb-product-price"> <Localized key={LocalizationKeys.ProductInfoProductPrice} variables={{ productPrice: formattedSubscriptionBasePrice, }} /> </span> {/if} {#if purchaseOption?.base?.period} <span class="rcb-product-price-frequency"> <span class="rcb-product-price-frequency-text"> {$translator.translatePeriodFrequency( purchaseOption.base.period.number, purchaseOption.base.period.unit, { useMultipleWords: true }, )}</span > </span> {/if} </div> </div> <div class="rcb-product-details expanded"> <div class="rcb-product-details-padding"> {#if purchaseOption?.trial?.periodDuration} <div class="rcb-product-trial-explanation"> <div class="rcb-after-trial-ends rcb-text-dark"> <Localized key={LocalizationKeys.ProductInfoPriceAfterFreeTrial} variables={{ renewalDate: renewalDate && $translator.translateDate(renewalDate, { dateStyle: "medium", }), }} /> </div> <div class="rcb-after-trial-ends rcb-text-dark"> {formattedSubscriptionBasePrice} </div> </div> <div class="rcb-product-trial-explanation"> <div class="rcb-text-dark rcb-total-due-today"> <Localized key={LocalizationKeys.ProductInfoPriceTotalDueToday} /> </div> <div class="rcb-text-dark rcb-total-due-today"> {formattedZeroPrice} </div> </div> {/if} </div> </div> <style> .rcb-product-price { color: var(--rc-color-grey-text-dark); font: var(--rc-text-titleMedium-mobile); } .rcb-product-trial { color: var(--rc-color-grey-text-dark); font: var(--rc-text-titleLarge-mobile); } .rcb-product-price-frequency { color: var(--rc-color-grey-text-dark); font: var(--rc-text-body1-mobile); } .rcb-product-price-frequency-text { white-space: nowrap; } .rcb-product-details { color: var(--rc-color-grey-text-light); margin: 0; overflow: hidden; transition: max-height 0.2s ease-in-out; } .rcb-product-details-padding { display: flex; flex-direction: column; gap: var(--rc-spacing-gapSmall-mobile); } .rcb-product-trial-explanation { display: flex; flex-direction: row; align-items: center; justify-content: space-between; } .rcb-text-dark { color: var(--rc-color-grey-text-dark); } @container layout-query-container (width >= 768px) { .rcb-product-price { font: var(--rc-text-titleMedium-desktop); } .rcb-product-price-frequency { font: var(--rc-text-body1-desktop); } .rcb-product-details { max-height: 500px; gap: var(--rc-spacing-gapXLarge-desktop); } .rcb-product-details-padding { gap: var(--rc-spacing-gapMedium-desktop); } .rcb-total-due-today { font: var(--rc-text-titleMedium-desktop); } .rcb-after-trial-ends { font: var(--rc-text-body1-desktop); } .rcb-product-trial { font: var(--rc-text-titleLarge-desktop); } } </style>
yannbf/purchases-js-repro
0
TypeScript
yannbf
Yann Braga
chromaui