@rechargeapps/storefront-client 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"bundleData.js","sources":["../../../src/utils/bundleData.ts"],"sourcesContent":["import { PublicBundleData, PriceRule } from '../types/bundleData';\nimport { BaseProduct, BaseProductVariant, BundleData as StorefrontBundleData } from '../types/bundle';\n\nconst mapBundleSettings = (bundleSettings: StorefrontBundleData['bundle_settings']) => {\n const addons = bundleSettings.layout_settings.addons;\n const crossSells = bundleSettings.layout_settings.crossSells;\n const customizationWindow = bundleSettings.customization_window;\n const defaultVariantId = bundleSettings.layout_settings?.defaultVariantId ?? bundleSettings.default_bundle_variant_id;\n const defaultFrequency = bundleSettings.layout_settings.defaultFrequency;\n const addToCartBehavior = bundleSettings.layout_settings.addToCartCallback;\n\n return {\n default_variant_id: defaultVariantId ? String(defaultVariantId) : null,\n is_customizable: bundleSettings.is_customizable,\n price_rule: String(bundleSettings.price_rule).toUpperCase(),\n customization_window: customizationWindow\n ? {\n active_days: customizationWindow,\n disabled_message: bundleSettings.customization_window_disabled_message || '',\n }\n : null,\n addons: addons.collectionId\n ? { collection_id: addons.collectionId, collection_handle: addons.collectionHandle }\n : null,\n cross_sells: crossSells.collectionId\n ? { collection_id: addons.collectionId, collection_handle: addons.collectionHandle }\n : null,\n default_selling_plan_id: defaultFrequency || null,\n collapsible_collections: bundleSettings.layout_settings.collapsibleSections,\n max_quantity_per_variant: bundleSettings.max_quantity_per_variant,\n show_product_variants: bundleSettings.layout_settings.showVariants,\n product_details_modal_enabled: bundleSettings.layout_settings.learnMoreModal,\n addToCartBehavior: {\n type: addToCartBehavior.type === 'none' ? ('cart_page' as const) : addToCartBehavior.type,\n value: addToCartBehavior.value,\n },\n };\n};\n\nconst mapIncentives = (incentives: StorefrontBundleData['incentives']): PublicBundleData['incentives'] => {\n if (incentives.tiered_discounts.length === 0) return null;\n\n return {\n tiered_discounts: incentives.tiered_discounts,\n };\n};\n\nconst mapSellingPlan = (\n sellingPlan: StorefrontBundleData['selling_plan_groups'][number]['selling_plans'][number]\n): PublicBundleData['selling_plan_groups'][number]['selling_plans'][number] => ({\n id: sellingPlan.id,\n name: sellingPlan.name,\n options: sellingPlan.options.map(option => ({ name: option.name, value: option.value })),\n recurring_deliveries: sellingPlan.recurring_deliveries,\n price_adjustments: sellingPlan.price_adjustments.map(({ value, value_type }) => ({\n value,\n value_type,\n })),\n});\n\nconst mapSellingPlanGroups = (\n sellingPlanGroup: StorefrontBundleData['selling_plan_groups'][number]\n): PublicBundleData['selling_plan_groups'][number] => ({\n name: sellingPlanGroup.name,\n options: sellingPlanGroup.options.map(option => ({ name: option.name, values: option.values })),\n selling_plans: sellingPlanGroup.selling_plans.map(mapSellingPlan),\n});\n\nconst mapBasicVariant = (variant: BaseProductVariant) => ({\n id: String(variant.id),\n title: variant.title,\n price: variant.price,\n compare_at_price: variant.compare_at_price,\n options: variant.options,\n available_for_sale: variant.available,\n});\n\nconst formatFeaturedImage = (featuredImage: BaseProduct['featured_image']): string | null => {\n if (featuredImage == null || typeof featuredImage === 'string') return featuredImage;\n\n if ('src' in featuredImage) return featuredImage['src'];\n\n return null;\n};\n\nconst mapBasicProduct = (product: BaseProduct) => {\n return {\n id: String(product.id),\n title: product.title,\n description: product.description,\n available_for_sale: product.available,\n featured_image: formatFeaturedImage(product.featured_image),\n images: product.images,\n requires_selling_plan: product.requires_selling_plan,\n selling_plan_groups: product.selling_plan_groups.map(mapSellingPlanGroups),\n };\n};\n\nconst mapProduct = (product: StorefrontBundleData['collections'][number]['products'][number]) => {\n const productPlansLookup = productSellingPlansGroupLookup(product.selling_plan_groups);\n\n return {\n ...mapBasicProduct(product),\n handle: product.handle,\n tags: product.tags,\n price_range: { min: product.price_min, max: product.price_max },\n compare_at_price_range: { min: product.compare_at_price_min, max: product.compare_at_price_max },\n options: product.options,\n variants: product.variants.map(variant => ({\n ...mapBasicVariant(variant),\n selling_plan_allocations: variant.selling_plan_allocations.map(sellingPlan => ({\n price: sellingPlan.price,\n compare_at_price: sellingPlan.compare_at_price,\n selling_plan: mapSellingPlan(\n productPlansLookup[`${sellingPlan.selling_plan_group_id}-${sellingPlan.selling_plan_id}`]\n ),\n })),\n option1: variant.option1,\n option2: variant.option2,\n option3: variant.option3,\n sku: variant.sku || '',\n requires_shipping: variant.requires_shipping,\n taxable: variant.taxable,\n featured_image: formatFeaturedImage(variant.featured_image),\n public_title: variant.public_title,\n requires_selling_plan: variant.requires_selling_plan,\n })),\n };\n};\n\nconst mapBundleVariantRanges = ({\n items_count,\n ranges,\n}: Pick<StorefrontBundleData['bundle_settings']['variants'][number], 'items_count' | 'ranges'>) => {\n if (ranges.length > 0) {\n return ranges.map(({ quantity_max, quantity_min }) => ({ min: quantity_min, max: quantity_max }));\n }\n\n return [{ min: items_count, max: items_count }];\n};\n\nconst productSellingPlansGroupLookup = (sellingPlanGroups: BaseProduct['selling_plan_groups']) =>\n sellingPlanGroups.reduce<\n Record<string, StorefrontBundleData['selling_plan_groups'][number]['selling_plans'][number]>\n >((acc, current) => {\n current.selling_plans.forEach(sellingPlan => {\n const key = `${current.id}-${sellingPlan.id}`;\n acc[key] = sellingPlan;\n });\n\n return acc;\n }, {});\n\nconst mapFilters = (filters: StorefrontBundleData['filters']): PublicBundleData['filters'] => {\n if (!Array.isArray(filters)) return [];\n return filters;\n};\n\nexport function mapOnlineStoreToPublicBundleData(bundleData: StorefrontBundleData): PublicBundleData {\n const bundleSettings = mapBundleSettings(bundleData.bundle_settings);\n const variantsLookup = bundleData.variants.reduce<Record<string, StorefrontBundleData['variants'][number]>>(\n (acc, variant) => {\n acc[variant.id] = variant;\n return acc;\n },\n {}\n );\n\n return {\n id: String(bundleData.id),\n title: bundleData.title,\n description: bundleData.description || null,\n handle: bundleData.handle,\n options: bundleData.options.map(option => ({\n name: option.name,\n position: option.position,\n values: option.values,\n })),\n default_variant_id: bundleSettings.default_variant_id,\n default_selling_plan_id: bundleSettings.default_selling_plan_id\n ? Number(bundleSettings.default_selling_plan_id)\n : null,\n available_for_sale: bundleData.available,\n requires_selling_plan: bundleData.requires_selling_plan,\n bundle_settings: {\n is_customizable: bundleSettings.is_customizable,\n price_rule: bundleSettings.price_rule as PriceRule,\n customization_window: bundleSettings.customization_window,\n max_quantity_per_variant: bundleSettings.max_quantity_per_variant,\n collapsible_collections: bundleSettings.collapsible_collections,\n show_product_variants: bundleSettings.show_product_variants,\n product_details_modal_enabled: bundleSettings.product_details_modal_enabled,\n show_variants_as_individual_products:\n bundleData.bundle_settings.settings.display_variants_as_separate_products_in_list,\n post_add_to_cart_behavior: bundleSettings.addToCartBehavior,\n },\n variants: bundleData.bundle_settings.variants\n .filter(({ enabled }) => enabled)\n .map((item, index) => {\n const variant = variantsLookup[String(item.external_variant_id)];\n\n return {\n id: String(item.external_variant_id),\n title: variant.title,\n price: variant.price,\n compare_at_price: variant.compare_at_price,\n image: variant.image || '',\n available_for_sale: variant.available,\n options: variant.options,\n requires_selling_plan: variant.requires_selling_plan,\n selling_plan_allocations: variant.selling_plan_allocations.map(sellingPlan => ({\n price: sellingPlan.price,\n compare_at_price: sellingPlan.compare_at_price,\n selling_plan: mapSellingPlan(sellingPlan.selling_plan),\n })),\n ranges: mapBundleVariantRanges(item),\n collections: item.option_sources.map(source => ({\n id: source.option_source_id,\n source_platform: 'shopify',\n min: source.quantity_min || 0,\n max: source.quantity_max,\n position: source.position,\n })),\n default_selections: item.selection_defaults.map(selectionDefault => ({\n quantity: selectionDefault.quantity,\n product: {\n id: String(selectionDefault.product.id),\n handle: selectionDefault.handle,\n title: selectionDefault.product.title,\n description: selectionDefault.product.description,\n images: selectionDefault.product.images,\n },\n variant: {\n id: selectionDefault.external_variant_id,\n title: selectionDefault.variant.title,\n featured_image: formatFeaturedImage(selectionDefault.variant.featured_image),\n sku: selectionDefault.sku || '',\n },\n })),\n position: index,\n };\n }),\n selling_plan_groups: bundleData.selling_plan_groups.map(mapSellingPlanGroups),\n collections: Object.values(bundleData.collections).reduce<PublicBundleData['collections']>((acc, current) => {\n if (!Array.isArray(current.products)) {\n /* If a collection is not published in Online store, it is included \n as _1:{ handle: \"<collection-handle\"} in the collections object.\n We need to skip these collections.\n */\n return acc;\n }\n\n acc[String(current.id)] = {\n id: String(current.id),\n title: current.title,\n handle: current.handle,\n products: current.products.map(mapProduct),\n };\n\n return acc;\n }, {}),\n addons: bundleData.addons.products.length\n ? {\n collection_id: bundleSettings.addons?.collection_id || '',\n collection_handle: bundleSettings.addons?.collection_handle || '',\n products: bundleData.addons.products.map(product => ({\n ...mapBasicProduct(product),\n price_range: { min: product.price, max: product.price },\n compare_at_price_range: { min: product.compare_at_price || 0, max: product.compare_at_price },\n variants: product.variants.map(variant => ({\n ...mapBasicVariant(variant),\n image: variant.image,\n selling_plan_allocations: variant.selling_plan_allocations.map(sellingPlan => ({\n price: sellingPlan.price,\n compare_at_price: sellingPlan.compare_at_price,\n selling_plan: mapSellingPlan(sellingPlan.selling_plan),\n })),\n })),\n })),\n }\n : null,\n cross_sells: bundleData.cross_sells.products.length\n ? {\n collection_id: bundleSettings.cross_sells?.collection_id || '',\n collection_handle: bundleSettings.cross_sells?.collection_handle || '',\n products: bundleData.cross_sells.products.map(mapProduct),\n }\n : null,\n incentives: mapIncentives(bundleData.incentives),\n filters: mapFilters(bundleData.filters),\n templates: bundleData.bundle_settings.layout_settings.templates || null,\n globalStyles: bundleData.bundle_settings.layout_settings.globalStyles || null,\n };\n}\n"],"names":[],"mappings":"AAGA,MAAM,iBAAA,GAAoB,CAAC,cAAA,KAA4D;AACrF,EAAA,MAAM,MAAA,GAAS,eAAe,eAAA,CAAgB,MAAA;AAC9C,EAAA,MAAM,UAAA,GAAa,eAAe,eAAA,CAAgB,UAAA;AAClD,EAAA,MAAM,sBAAsB,cAAA,CAAe,oBAAA;AAC3C,EAAA,MAAM,gBAAA,GAAmB,cAAA,CAAe,eAAA,EAAiB,gBAAA,IAAoB,cAAA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bundleData';\nimport { BaseProduct, BaseProductVariant, BundleData as StorefrontBundleData } from '../types/bundle';\n\nconst mapBundleSettings = (bundleSettings: StorefrontBundleData['bundle_settings']) => {\n const addons = bundleSettings.layout_settings.addons;\n const crossSells = bundleSettings.layout_settings.crossSells;\n const customizationWindow = bundleSettings.customization_window;\n const defaultVariantId = bundleSettings.layout_settings?.defaultVariantId ?? bundleSettings.default_bundle_variant_id;\n const defaultFrequency = bundleSettings.layout_settings.defaultFrequency;\n const addToCartBehavior = bundleSettings.layout_settings.addToCartCallback;\n\n return {\n default_variant_id: defaultVariantId ? String(defaultVariantId) : null,\n is_customizable: bundleSettings.is_customizable,\n price_rule: String(bundleSettings.price_rule).toUpperCase(),\n customization_window: customizationWindow\n ? {\n active_days: customizationWindow,\n disabled_message: bundleSettings.customization_window_disabled_message || '',\n }\n : null,\n addons: addons.collectionId\n ? { collection_id: addons.collectionId, collection_handle: addons.collectionHandle }\n : null,\n cross_sells: crossSells.collectionId\n ? { collection_id: addons.collectionId, collection_handle: addons.collectionHandle }\n : null,\n default_selling_plan_id: defaultFrequency || null,\n collapsible_collections: bundleSettings.layout_settings.collapsibleSections,\n max_quantity_per_variant: bundleSettings.max_quantity_per_variant,\n show_product_variants: bundleSettings.layout_settings.showVariants,\n product_details_modal_enabled: bundleSettings.layout_settings.learnMoreModal,\n addToCartBehavior: {\n type: addToCartBehavior.type === 'none' ? ('cart_page' as const) : addToCartBehavior.type,\n value: addToCartBehavior.value,\n },\n };\n};\n\nconst mapIncentives = (incentives: StorefrontBundleData['incentives']): PublicBundleData['incentives'] => {\n if (incentives.tiered_discounts.length === 0) return null;\n\n return {\n tiered_discounts: incentives.tiered_discounts,\n };\n};\n\nconst mapSellingPlan = (\n sellingPlan: StorefrontBundleData['selling_plan_groups'][number]['selling_plans'][number]\n): PublicBundleData['selling_plan_groups'][number]['selling_plans'][number] => ({\n id: sellingPlan.id,\n name: sellingPlan.name,\n options: sellingPlan.options.map(option => ({ name: option.name, value: option.value })),\n recurring_deliveries: sellingPlan.recurring_deliveries,\n price_adjustments: sellingPlan.price_adjustments.map(({ value, value_type }) => ({\n value,\n value_type,\n })),\n});\n\nconst mapSellingPlanGroups = (\n sellingPlanGroup: StorefrontBundleData['selling_plan_groups'][number]\n): PublicBundleData['selling_plan_groups'][number] => ({\n name: sellingPlanGroup.name,\n options: sellingPlanGroup.options.map(option => ({ name: option.name, values: option.values })),\n selling_plans: sellingPlanGroup.selling_plans.map(mapSellingPlan),\n});\n\nconst mapBasicVariant = (variant: BaseProductVariant) => ({\n id: String(variant.id),\n title: variant.title,\n price: variant.price,\n compare_at_price: variant.compare_at_price,\n options: variant.options,\n available_for_sale: variant.available,\n});\n\nconst formatFeaturedImage = (featuredImage: BaseProduct['featured_image']): string | null => {\n if (featuredImage == null || typeof featuredImage === 'string') return featuredImage;\n\n if ('src' in featuredImage) return featuredImage['src'];\n\n return null;\n};\n\nconst mapBasicProduct = (product: BaseProduct) => {\n return {\n id: String(product.id),\n title: product.title,\n description: product.description,\n available_for_sale: product.available,\n featured_image: formatFeaturedImage(product.featured_image),\n images: product.images,\n requires_selling_plan: product.requires_selling_plan,\n selling_plan_groups: product.selling_plan_groups.map(mapSellingPlanGroups),\n };\n};\n\nconst mapProduct = (product: StorefrontBundleData['collections'][number]['products'][number]) => {\n const productPlansLookup = productSellingPlansGroupLookup(product.selling_plan_groups);\n\n return {\n ...mapBasicProduct(product),\n handle: product.handle,\n tags: product.tags,\n price_range: { min: product.price_min, max: product.price_max },\n compare_at_price_range: { min: product.compare_at_price_min, max: product.compare_at_price_max },\n options: product.options,\n variants: product.variants.map(variant => ({\n ...mapBasicVariant(variant),\n selling_plan_allocations: variant.selling_plan_allocations.map(sellingPlan => ({\n price: sellingPlan.price,\n compare_at_price: sellingPlan.compare_at_price,\n selling_plan: mapSellingPlan(\n productPlansLookup[`${sellingPlan.selling_plan_group_id}-${sellingPlan.selling_plan_id}`]\n ),\n })),\n option1: variant.option1,\n option2: variant.option2,\n option3: variant.option3,\n sku: variant.sku || '',\n requires_shipping: variant.requires_shipping,\n taxable: variant.taxable,\n featured_image: formatFeaturedImage(variant.featured_image),\n public_title: variant.public_title,\n requires_selling_plan: variant.requires_selling_plan,\n })),\n };\n};\n\nconst mapBundleVariantRanges = ({\n items_count,\n ranges,\n}: Pick<StorefrontBundleData['bundle_settings']['variants'][number], 'items_count' | 'ranges'>) => {\n if (ranges.length > 0) {\n return ranges.map(({ quantity_max, quantity_min }) => ({ min: quantity_min, max: quantity_max }));\n }\n\n return [{ min: items_count, max: items_count }];\n};\n\nconst productSellingPlansGroupLookup = (sellingPlanGroups: BaseProduct['selling_plan_groups']) =>\n sellingPlanGroups.reduce<\n Record<string, StorefrontBundleData['selling_plan_groups'][number]['selling_plans'][number]>\n >((acc, current) => {\n current.selling_plans.forEach(sellingPlan => {\n const key = `${current.id}-${sellingPlan.id}`;\n acc[key] = sellingPlan;\n });\n\n return acc;\n }, {});\n\nconst mapFilters = (filters: StorefrontBundleData['filters']): PublicBundleData['filters'] => {\n if (!Array.isArray(filters)) return [];\n return filters;\n};\n\nexport function mapOnlineStoreToPublicBundleData(bundleData: StorefrontBundleData): PublicBundleData {\n const bundleSettings = mapBundleSettings(bundleData.bundle_settings);\n const variantsLookup = bundleData.variants.reduce<Record<string, StorefrontBundleData['variants'][number]>>(\n (acc, variant) => {\n acc[variant.id] = variant;\n return acc;\n },\n {}\n );\n\n return {\n id: String(bundleData.id),\n title: bundleData.title,\n description: bundleData.description || null,\n handle: bundleData.handle,\n options: bundleData.options.map(option => ({\n name: option.name,\n position: option.position,\n values: option.values,\n })),\n default_variant_id: bundleSettings.default_variant_id,\n default_selling_plan_id: bundleSettings.default_selling_plan_id\n ? Number(bundleSettings.default_selling_plan_id)\n : null,\n available_for_sale: bundleData.available,\n requires_selling_plan: bundleData.requires_selling_plan,\n bundle_settings: {\n is_customizable: bundleSettings.is_customizable,\n price_rule: bundleSettings.price_rule as PriceRule,\n customization_window: bundleSettings.customization_window,\n max_quantity_per_variant: bundleSettings.max_quantity_per_variant,\n collapsible_collections: bundleSettings.collapsible_collections,\n show_product_variants: bundleSettings.show_product_variants,\n product_details_modal_enabled: bundleSettings.product_details_modal_enabled,\n show_variants_as_individual_products:\n bundleData.bundle_settings.settings.display_variants_as_separate_products_in_list,\n post_add_to_cart_behavior: bundleSettings.addToCartBehavior,\n cross_sells_default_purchase_type:\n bundleData.bundle_settings.layout_settings.crossSells.defaultPurchaseType ?? null,\n },\n variants: bundleData.bundle_settings.variants\n .filter(({ enabled }) => enabled)\n .map((item, index) => {\n const variant = variantsLookup[String(item.external_variant_id)];\n\n return {\n id: String(item.external_variant_id),\n title: variant.title,\n price: variant.price,\n compare_at_price: variant.compare_at_price,\n image: variant.image || '',\n available_for_sale: variant.available,\n options: variant.options,\n requires_selling_plan: variant.requires_selling_plan,\n selling_plan_allocations: variant.selling_plan_allocations.map(sellingPlan => ({\n price: sellingPlan.price,\n compare_at_price: sellingPlan.compare_at_price,\n selling_plan: mapSellingPlan(sellingPlan.selling_plan),\n })),\n ranges: mapBundleVariantRanges(item),\n collections: item.option_sources.map(source => ({\n id: source.option_source_id,\n source_platform: 'shopify',\n min: source.quantity_min || 0,\n max: source.quantity_max,\n position: source.position,\n })),\n default_selections: item.selection_defaults.map(selectionDefault => ({\n quantity: selectionDefault.quantity,\n product: {\n id: String(selectionDefault.product.id),\n handle: selectionDefault.handle,\n title: selectionDefault.product.title,\n description: selectionDefault.product.description,\n images: selectionDefault.product.images,\n },\n variant: {\n id: selectionDefault.external_variant_id,\n title: selectionDefault.variant.title,\n featured_image: formatFeaturedImage(selectionDefault.variant.featured_image),\n sku: selectionDefault.sku || '',\n },\n })),\n position: index,\n };\n }),\n selling_plan_groups: bundleData.selling_plan_groups.map(mapSellingPlanGroups),\n collections: Object.values(bundleData.collections).reduce<PublicBundleData['collections']>((acc, current) => {\n if (!Array.isArray(current.products)) {\n /* If a collection is not published in Online store, it is included \n as _1:{ handle: \"<collection-handle\"} in the collections object.\n We need to skip these collections.\n */\n return acc;\n }\n\n acc[String(current.id)] = {\n id: String(current.id),\n title: current.title,\n handle: current.handle,\n products: current.products.map(mapProduct),\n };\n\n return acc;\n }, {}),\n addons: bundleData.addons.products.length\n ? {\n collection_id: bundleSettings.addons?.collection_id || '',\n collection_handle: bundleSettings.addons?.collection_handle || '',\n products: bundleData.addons.products.map(product => ({\n ...mapBasicProduct(product),\n price_range: { min: product.price, max: product.price },\n compare_at_price_range: { min: product.compare_at_price || 0, max: product.compare_at_price },\n variants: product.variants.map(variant => ({\n ...mapBasicVariant(variant),\n image: variant.image,\n selling_plan_allocations: variant.selling_plan_allocations.map(sellingPlan => ({\n price: sellingPlan.price,\n compare_at_price: sellingPlan.compare_at_price,\n selling_plan: mapSellingPlan(sellingPlan.selling_plan),\n })),\n })),\n })),\n }\n : null,\n cross_sells: bundleData.cross_sells.products.length\n ? {\n collection_id: bundleSettings.cross_sells?.collection_id || '',\n collection_handle: bundleSettings.cross_sells?.collection_handle || '',\n products: bundleData.cross_sells.products.map(mapProduct),\n }\n : null,\n incentives: mapIncentives(bundleData.incentives),\n filters: mapFilters(bundleData.filters),\n templates: bundleData.bundle_settings.layout_settings.templates || null,\n globalStyles: bundleData.bundle_settings.layout_settings.globalStyles || null,\n };\n}\n"],"names":[],"mappings":"AAGA,MAAM,iBAAA,GAAoB,CAAC,cAAA,KAA4D;AACrF,EAAA,MAAM,MAAA,GAAS,eAAe,eAAA,CAAgB,MAAA;AAC9C,EAAA,MAAM,UAAA,GAAa,eAAe,eAAA,CAAgB,UAAA;AAClD,EAAA,MAAM,sBAAsB,cAAA,CAAe,oBAAA;AAC3C,EAAA,MAAM,gBAAA,GAAmB,cAAA,CAAe,eAAA,EAAiB,gBAAA,IAAoB,cAAA,CAAe,yBAAA;AAC5F,EAAA,MAAM,gBAAA,GAAmB,eAAe,eAAA,CAAgB,gBAAA;AACxD,EAAA,MAAM,iBAAA,GAAoB,eAAe,eAAA,CAAgB,iBAAA;AAEzD,EAAA,OAA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AAK,QAAQ,gBAAA,EAAiB;AAAA,QAC5F,QAAA,EAAU,OAAA,CAAQ,QAAA,CAAS,GAAA,CAAI,CAAA,OAAA,MAAY;AAAA,UACzC,GAAG,gBAAgB,OAAO,CAAA;AAAA,UAC1B,OAAO,OAAA,CAAQ,KAAA;AAAA,UACf,wBAAA,EAA0B,OAAA,CAAQ,wBAAA,CAAyB,GAAA,CAAI,CAAA,WAAA,MAAgB;AAAA,YAC7E,OAAO,WAAA,CAAY,KAAA;AAAA,YACnB,kBAAkB,WAAA,CAAY,gBAAA;AAAA,YAC9B,YAAA,EAAc,cAAA,CAAe,WAAA,CAAY,YAAY;AAAA,WACvD,CAAE;AAAA,SACJ,CAAE;AAAA,OACJ,CAAE;AAAA,KACJ,GACA,IAAA;AAAA,IACJ,WAAA,EAAa,UAAA,CAAW,WAAA,CAAY,QAAA,CAAS,MAAA,GACzC;AAAA,MACE,aAAA,EAAe,cAAA,CAAe,WAAA,EAAa,aAAA,IAAiB,EAAA;AAAA,MAC5D,iBAAA,EAAmB,cAAA,CAAe,WAAA,EAAa,iBAAA,IAAqB,EAAA;AAAA,MACpE,QAAA,EAAU,UAAA,CAAW,WAAA,CAAY,QAAA,CAAS,IAAI,UAAU;AAAA,KAC1D,GACA,IAAA;AAAA,IACJ,UAAA,EAAY,aAAA,CAAc,UAAA,CAAW,UAAU,CAAA;AAAA,IAC/C,OAAA,EAAS,UAAA,CAAW,UAAA,CAAW,OAAO,CAAA;AAAA,IACtC,SAAA,EAAW,UAAA,CAAW,eAAA,CAAgB,eAAA,CAAgB,SAAA,IAAa,IAAA;AAAA,IACnE,YAAA,EAAc,UAAA,CAAW,eAAA,CAAgB,eAAA,CAAgB,YAAA,IAAgB;AAAA,GAC3E;AACF;;"}
@@ -9,6 +9,31 @@ function stringifyQuery(obj) {
9
9
  return Object.entries(obj).filter(([, value]) => value !== void 0 && !(Array.isArray(value) && value.length === 0)).map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(",") : encode(value)}`).join("&");
10
10
  }
11
11
  const RESERVED_QUERY_KEYS = /* @__PURE__ */ new Set(["shop_url"]);
12
+ const sessionRetryStates = /* @__PURE__ */ new WeakMap();
13
+ let sessionRetryGeneration = 0;
14
+ function getSessionRetryState(retryFn) {
15
+ let state = sessionRetryStates.get(retryFn);
16
+ if (!state) {
17
+ state = {};
18
+ sessionRetryStates.set(retryFn, state);
19
+ }
20
+ return state;
21
+ }
22
+ function getRetrySession(retryFn, failedToken, sentAtGeneration) {
23
+ const state = getSessionRetryState(retryFn);
24
+ if (state.inFlight) return state.inFlight;
25
+ if (state.latest && state.latest.generation > sentAtGeneration) return Promise.resolve(state.latest.session);
26
+ state.inFlight = retryFn().then((session) => {
27
+ if (session && session.apiToken !== failedToken) {
28
+ sessionRetryGeneration += 1;
29
+ state.latest = { session, generation: sessionRetryGeneration };
30
+ }
31
+ return session;
32
+ }).finally(() => {
33
+ state.inFlight = void 0;
34
+ });
35
+ return state.inFlight;
36
+ }
12
37
  function getInternalSession(session, fnName) {
13
38
  return {
14
39
  ...session,
@@ -37,6 +62,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
37
62
  if (!token) {
38
63
  throw new Error("No API token defined on session.");
39
64
  }
65
+ const sentAtGeneration = sessionRetryGeneration;
40
66
  const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);
41
67
  const reqHeaders = {
42
68
  "X-Recharge-Access-Token": token,
@@ -44,7 +70,7 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
44
70
  "X-Recharge-Sdk-Fn": session.internalFnCall,
45
71
  ...appName ? { "X-Recharge-Sdk-App-Name": appName } : {},
46
72
  ...appVersion ? { "X-Recharge-Sdk-App-Version": appVersion } : {},
47
- "X-Recharge-Sdk-Version": "2.7.0",
73
+ "X-Recharge-Sdk-Version": "2.8.0",
48
74
  "X-Request-Id": session.internalRequestId,
49
75
  ...session.tmp_fn_identifier ? { "X-Recharge-Sdk-Fn-Identifier": session.tmp_fn_identifier } : {},
50
76
  ...headers ? headers : {}
@@ -58,38 +84,23 @@ async function rechargeApiRequest(method, url, { id, query, data, headers } = {}
58
84
  try {
59
85
  return await request(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });
60
86
  } catch (error) {
61
- if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {
62
- return loginRetryFn().then((session2) => {
63
- if (session2) {
64
- return request(method, `${rechargeBaseUrl}${url}`, {
65
- id,
66
- query: localQuery,
67
- data,
68
- headers: {
69
- ...reqHeaders,
70
- "X-Recharge-Access-Token": session2.apiToken
71
- }
72
- });
73
- }
74
- throw error;
75
- });
76
- } else if (__unstable_twoFactorRetryFn && error instanceof RechargeRequestError && error.status === 423) {
77
- return __unstable_twoFactorRetryFn().then((session2) => {
78
- if (session2) {
79
- return request(method, `${rechargeBaseUrl}${url}`, {
80
- id,
81
- query: localQuery,
82
- data,
83
- headers: {
84
- ...reqHeaders,
85
- "X-Recharge-Access-Token": session2.apiToken
86
- }
87
- });
88
- }
89
- throw error;
90
- });
91
- }
92
- throw error;
87
+ const retryFnsByStatus = {
88
+ 401: loginRetryFn,
89
+ 423: __unstable_twoFactorRetryFn
90
+ };
91
+ const retryFn = error instanceof RechargeRequestError && error.status ? retryFnsByStatus[error.status] : void 0;
92
+ if (!retryFn) throw error;
93
+ const retrySession = await getRetrySession(retryFn, token, sentAtGeneration);
94
+ if (!retrySession) throw error;
95
+ return request(method, `${rechargeBaseUrl}${url}`, {
96
+ id,
97
+ query: localQuery,
98
+ data,
99
+ headers: {
100
+ ...reqHeaders,
101
+ "X-Recharge-Access-Token": retrySession.apiToken
102
+ }
103
+ });
93
104
  }
94
105
  }
95
106
  async function shopifyAppProxyRequest(method, url, requestOptions = {}) {
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import { nanoid } from './id';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\nimport { encodePathSegment } from './url';\n\n/**\n * Converts a query object into a URL-encoded query string using the following rules:\n * - Arrays are serialized as comma-separated values: `a=1,2` (not `a[0]=1&a[1]=2`)\n * - Only the values are URL-encoded; keys are not encoded\n * - Properties with `undefined` values or empty arrays are omitted from the result\n *\n * Reference: qs\n */\nfunction stringifyQuery(obj: Record<string, unknown>): string {\n const encode = (value: unknown) => encodeURIComponent(value === null ? '' : String(value));\n return Object.entries(obj)\n .filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0))\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(',') : encode(value)}`)\n .join('&');\n}\n\nconst RESERVED_QUERY_KEYS = new Set(['shop_url']);\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const {\n environment,\n environmentUri,\n storeIdentifier,\n loginRetryFn,\n __unstable_twoFactorRetryFn,\n appName,\n appVersion,\n } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const token = session.apiToken;\n if (!token) {\n throw new Error('No API token defined on session.');\n }\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(session.tmp_fn_identifier ? { 'X-Recharge-Sdk-Fn-Identifier': session.tmp_fn_identifier } : {}),\n ...(headers ? headers : {}),\n };\n\n const callerQuery = query as Record<string, unknown> | undefined;\n const sanitizedCallerQuery = callerQuery\n ? Object.fromEntries(Object.entries(callerQuery).filter(([k]) => !RESERVED_QUERY_KEYS.has(k)))\n : undefined;\n\n const localQuery = {\n ...sanitizedCallerQuery,\n shop_url: storeIdentifier,\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n if (loginRetryFn && error instanceof RechargeRequestError && error.status === 401) {\n // call loginRetryFn and retry request on 401\n return loginRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n } else if (__unstable_twoFactorRetryFn && error instanceof RechargeRequestError && error.status === 423) {\n // trigger two-factor authentication flow and retry request on 423\n return __unstable_twoFactorRetryFn().then(session => {\n if (session) {\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': session.apiToken,\n },\n });\n }\n throw error;\n });\n }\n throw error;\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n // Encode the id as a single opaque path segment. Without this, an id\n // containing `../` or `?` could traverse to a different API route or\n // smuggle query params (H1-3884884 / SEC-4002).\n reqUrl = [reqUrl, encodePathSegment(id)].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query as Record<string, unknown>)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (response.status === 502 || response.status === 504) {\n throw new RechargeRequestError('A gateway error occurred while making the request', response.status);\n } else if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":["session"],"mappings":";;;;;;AAgBA,SAAS,eAAe,GAAA,EAAsC;AAC5D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAAmB,kBAAA,CAAmB,UAAU,IAAA,GAAO,EAAA,GAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AACzF,EAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA,CACtB,OAAO,CAAC,GAAG,KAAK,CAAA,KAAM,UAAU,MAAA,IAAa,EAAE,MAAM,OAAA,CAAQ,KAAK,KAAK,KAAA,CAAM,MAAA,KAAW,CAAA,CAAE,CAAA,CAC1F,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,KAAK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,EAAK;AAAA,EAC/B,SAAS,CAAA,EAAG;AAAA,EAEZ;AAEA,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,IAAI,QAAA,CAAS,MAAA,KAAW,GAAA,IAAO,QAAA,CAAS,WAAW,GAAA,EAAK;AACtD,MAAA,MAAM,IAAI,oBAAA,CAAqB,mDAAA,EAAqD,QAAA,CAAS,MAAM,CAAA;AAAA,IACrG,CAAA,MAAA,IAAW,MAAA,IAAU,MAAA,CAAO,KAAA,EAAO;AACjC,MAAA,MAAM,IAAI,oBAAA,CAAqB,MAAA,CAAO,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,IAC9D,CAAA,MAAA,IAAW,MAAA,IAAU,MAAA,CAAO,MAAA,EAAQ;AAClC,MAAA,MAAM,IAAI,qBAAqB,IAAA,CAAK,SAAA,CAAU,OAAO,MAAM,CAAA,EAAG,SAAS,MAAM,CAAA;AAAA,IAC/E,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,qBAAqB,sDAAsD,CAAA;AAAA,IACvF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;"}
1
+ {"version":3,"file":"request.js","sources":["../../../src/utils/request.ts"],"sourcesContent":["import { nanoid } from './id';\n\nimport { Method, RequestHeaders, RequestOptions, InternalSession, Session } from '../types';\nimport { getOptions } from './options';\nimport { RECHARGE_API_URL, RECHARGE_CDN_URL, SHOPIFY_APP_PROXY_URL } from '../constants/api';\nimport { RechargeRequestError } from './error';\nimport { encodePathSegment } from './url';\n\n/**\n * Converts a query object into a URL-encoded query string using the following rules:\n * - Arrays are serialized as comma-separated values: `a=1,2` (not `a[0]=1&a[1]=2`)\n * - Only the values are URL-encoded; keys are not encoded\n * - Properties with `undefined` values or empty arrays are omitted from the result\n *\n * Reference: qs\n */\nfunction stringifyQuery(obj: Record<string, unknown>): string {\n const encode = (value: unknown) => encodeURIComponent(value === null ? '' : String(value));\n return Object.entries(obj)\n .filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0))\n .map(([key, value]) => `${key}=${Array.isArray(value) ? value.map(encode).join(',') : encode(value)}`)\n .join('&');\n}\n\nconst RESERVED_QUERY_KEYS = new Set(['shop_url']);\n\ntype SessionRetryFn = () => Promise<Session | undefined>;\n\ninterface SessionRetryState {\n inFlight?: Promise<Session | undefined>;\n latest?: { session: Session; generation: number };\n}\n\nconst sessionRetryStates = new WeakMap<SessionRetryFn, SessionRetryState>();\nlet sessionRetryGeneration = 0;\n\nfunction getSessionRetryState(retryFn: SessionRetryFn): SessionRetryState {\n let state = sessionRetryStates.get(retryFn);\n if (!state) {\n state = {};\n sessionRetryStates.set(retryFn, state);\n }\n return state;\n}\n\n/**\n * Gets a fresh session for a failed request. Concurrent failures share one `retryFn` call. A request sent before an\n * earlier call returned a new session retries with that session instead of calling `retryFn` again; a request sent\n * after it always calls `retryFn`, so the app still decides (for example, after the customer logs out).\n */\nfunction getRetrySession(\n retryFn: SessionRetryFn,\n failedToken: string,\n sentAtGeneration: number\n): Promise<Session | undefined> {\n const state = getSessionRetryState(retryFn);\n if (state.inFlight) return state.inFlight;\n if (state.latest && state.latest.generation > sentAtGeneration) return Promise.resolve(state.latest.session);\n\n state.inFlight = retryFn()\n .then(session => {\n if (session && session.apiToken !== failedToken) {\n sessionRetryGeneration += 1;\n state.latest = { session, generation: sessionRetryGeneration };\n }\n return session;\n })\n .finally(() => {\n state.inFlight = undefined;\n });\n return state.inFlight;\n}\n\n/** @internal */\nexport function getInternalSession(session: Session | InternalSession, fnName: string): InternalSession {\n return {\n ...session,\n internalFnCall: (session as InternalSession).internalFnCall ?? fnName,\n internalRequestId: (session as InternalSession).internalRequestId ?? nanoid(),\n };\n}\n\nexport async function cdnRequest<T>(method: Method, url: string, requestOptions: RequestOptions = {}): Promise<T> {\n const opts = getOptions();\n return request(method, `${RECHARGE_CDN_URL(opts.environment)}/store/${opts.storeIdentifier}${url}`, requestOptions);\n}\n\nexport async function rechargeApiRequest<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {},\n session: InternalSession\n): Promise<T> {\n const {\n environment,\n environmentUri,\n storeIdentifier,\n loginRetryFn,\n __unstable_twoFactorRetryFn,\n appName,\n appVersion,\n } = getOptions();\n if (!storeIdentifier) {\n throw new Error('InitRecharge has not been called and/or no store identifier has been defined.');\n }\n const token = session.apiToken;\n if (!token) {\n throw new Error('No API token defined on session.');\n }\n const sentAtGeneration = sessionRetryGeneration;\n const rechargeBaseUrl = RECHARGE_API_URL(environment, environmentUri);\n const reqHeaders: RequestHeaders = {\n 'X-Recharge-Access-Token': token,\n 'X-Recharge-Version': '2021-11',\n 'X-Recharge-Sdk-Fn': session.internalFnCall,\n ...(appName ? { 'X-Recharge-Sdk-App-Name': appName } : {}),\n ...(appVersion ? { 'X-Recharge-Sdk-App-Version': appVersion } : {}),\n 'X-Recharge-Sdk-Version': '__SDK_VERSION__',\n 'X-Request-Id': session.internalRequestId,\n ...(session.tmp_fn_identifier ? { 'X-Recharge-Sdk-Fn-Identifier': session.tmp_fn_identifier } : {}),\n ...(headers ? headers : {}),\n };\n\n const callerQuery = query as Record<string, unknown> | undefined;\n const sanitizedCallerQuery = callerQuery\n ? Object.fromEntries(Object.entries(callerQuery).filter(([k]) => !RESERVED_QUERY_KEYS.has(k)))\n : undefined;\n\n const localQuery = {\n ...sanitizedCallerQuery,\n shop_url: storeIdentifier,\n };\n\n try {\n // await to catch any errors\n return await request<T>(method, `${rechargeBaseUrl}${url}`, { id, query: localQuery, data, headers: reqHeaders });\n } catch (error: unknown) {\n const retryFnsByStatus: Partial<Record<number, SessionRetryFn>> = {\n 401: loginRetryFn,\n 423: __unstable_twoFactorRetryFn,\n };\n const retryFn = error instanceof RechargeRequestError && error.status ? retryFnsByStatus[error.status] : undefined;\n if (!retryFn) throw error;\n\n const retrySession = await getRetrySession(retryFn, token, sentAtGeneration);\n if (!retrySession) throw error;\n return request(method, `${rechargeBaseUrl}${url}`, {\n id,\n query: localQuery,\n data,\n headers: {\n ...reqHeaders,\n 'X-Recharge-Access-Token': retrySession.apiToken,\n },\n });\n }\n}\n\nexport async function shopifyAppProxyRequest<T>(\n method: Method,\n url: string,\n requestOptions: RequestOptions = {}\n): Promise<T> {\n return request(method, `${SHOPIFY_APP_PROXY_URL}${url}`, requestOptions);\n}\n\nexport async function request<T>(\n method: Method,\n url: string,\n { id, query, data, headers }: RequestOptions = {}\n): Promise<T> {\n let reqUrl = url.trim();\n\n if (id) {\n // Encode the id as a single opaque path segment. Without this, an id\n // containing `../` or `?` could traverse to a different API route or\n // smuggle query params (H1-3884884 / SEC-4002).\n reqUrl = [reqUrl, encodePathSegment(id)].join('/');\n }\n\n if (query) {\n let exQuery;\n [reqUrl, exQuery] = reqUrl.split('?');\n const fullQuery = [exQuery, stringifyQuery(query as Record<string, unknown>)].join('&').replace(/^&/, '');\n reqUrl = `${reqUrl}${fullQuery ? `?${fullQuery}` : ''}`;\n }\n\n let reqBody;\n if (data && method !== 'get') {\n reqBody = JSON.stringify(data);\n }\n\n const reqHeaders: RequestHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'X-Recharge-App': 'storefront-client',\n ...(headers ? headers : {}),\n };\n\n const response = await fetch(reqUrl, {\n method,\n headers: reqHeaders,\n body: reqBody,\n });\n\n let result;\n try {\n result = await response.json();\n } catch (e) {\n // If we get here, it means we were a no content response.\n }\n\n if (!response.ok) {\n if (response.status === 502 || response.status === 504) {\n throw new RechargeRequestError('A gateway error occurred while making the request', response.status);\n } else if (result && result.error) {\n throw new RechargeRequestError(result.error, response.status);\n } else if (result && result.errors) {\n throw new RechargeRequestError(JSON.stringify(result.errors), response.status);\n } else {\n throw new RechargeRequestError('A connection error occurred while making the request');\n }\n }\n\n return result as T;\n}\n"],"names":[],"mappings":";;;;;;AAgBA,SAAS,eAAe,GAAA,EAAsC;AAC5D,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAAmB,kBAAA,CAAmB,UAAU,IAAA,GAAO,EAAA,GAAK,MAAA,CAAO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AA,CAAqB,mDAAA,EAAqD,QAAA,CAAS,MAAM,CAAA;AAAA,IACrG,CAAA,MAAA,IAAW,MAAA,IAAU,MAAA,CAAO,KAAA,EAAO;AACjC,MAAA,MAAM,IAAI,oBAAA,CAAqB,MAAA,CAAO,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,IAC9D,CAAA,MAAA,IAAW,MAAA,IAAU,MAAA,CAAO,MAAA,EAAQ;AAClC,MAAA,MAAM,IAAI,qBAAqB,IAAA,CAAK,SAAA,CAAU,OAAO,MAAM,CAAA,EAAG,SAAS,MAAM,CAAA;AAAA,IAC/E,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,qBAAqB,sDAAsD,CAAA;AAAA,IACvF;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;;"}
package/dist/index.d.ts CHANGED
@@ -1028,6 +1028,7 @@ interface CrossSellsSettings {
1028
1028
  collectionId: string;
1029
1029
  collectionHandle: string;
1030
1030
  enabled: boolean;
1031
+ defaultPurchaseType?: 'subscription' | 'onetime';
1031
1032
  }
1032
1033
  interface StepSettingsCommon {
1033
1034
  description?: string;
@@ -2470,6 +2471,7 @@ interface BundleSettings {
2470
2471
  type: 'cart_page' | 'callback' | 'redirect';
2471
2472
  value: string;
2472
2473
  };
2474
+ cross_sells_default_purchase_type: 'subscription' | 'onetime' | null;
2473
2475
  }
2474
2476
  /**
2475
2477
  * A specific variant of a bundle product
@@ -3790,7 +3792,8 @@ interface StorefrontOptions {
3790
3792
  /**
3791
3793
  * Middleware function that should return a Session, called when API functions return a 401.
3792
3794
  * This function allows your app to refetch a session, store it by whatever means your app uses for future calls,
3793
- * then return it so the call that failed can be retried.
3795
+ * then return it so the call that failed can be retried. Calls that fail while this function is pending share its
3796
+ * result, and calls sent before it returned a new session retry with that session instead of calling it again.
3794
3797
  *
3795
3798
  * @returns Session
3796
3799
  */
@@ -3799,7 +3802,8 @@ interface StorefrontOptions {
3799
3802
  * Beta feature - (may change in the future)
3800
3803
  * Middleware function that should return a Session, called when API functions return a 423.
3801
3804
  * This function allows your app to refetch a session, store it by whatever means your app uses for future calls,
3802
- * then return it so the call that failed can be retried.
3805
+ * then return it so the call that failed can be retried. Calls that fail while this function is pending share its
3806
+ * result, and calls sent before it returned a new session retry with that session instead of calling it again.
3803
3807
  *
3804
3808
  * @returns Session
3805
3809
  */
@@ -3823,7 +3827,8 @@ interface InitOptions {
3823
3827
  /**
3824
3828
  * Middleware function that should return a Session, called when API functions return a 401.
3825
3829
  * This function allows your app to refetch a session, store it by whatever means your app uses for future calls,
3826
- * then return it so the call that failed can be retried.
3830
+ * then return it so the call that failed can be retried. Calls that fail while this function is pending share its
3831
+ * result, and calls sent before it returned a new session retry with that session instead of calling it again.
3827
3832
  *
3828
3833
  * @returns Session
3829
3834
  */
@@ -3832,7 +3837,8 @@ interface InitOptions {
3832
3837
  * Beta feature - (may change in the future)
3833
3838
  * Middleware function that should return a Session, called when API functions return a 423.
3834
3839
  * This function allows your app to refetch a session, store it by whatever means your app uses for future calls,
3835
- * then return it so the call that failed can be retried.
3840
+ * then return it so the call that failed can be retried. Calls that fail while this function is pending share its
3841
+ * result, and calls sent before it returned a new session retry with that session instead of calling it again.
3836
3842
  *
3837
3843
  * @returns Session
3838
3844
  */