@ubnt/store.core 9.18.0-alpha.8 → 9.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -193
- package/lib/_virtual/_virtual_multi-entry.js +12 -27
- package/lib/_virtual/_virtual_multi-entry.js.map +1 -1
- package/lib/_virtual/_virtual_multi-entry.mjs +10 -14
- package/lib/_virtual/_virtual_multi-entry.mjs.map +1 -1
- package/lib/assets/attention.svg +5 -5
- package/lib/assets/attention2.svg +5 -5
- package/lib/{components/ResourceCalculatorV1/assets/consoles/ucg-max.png.js → assets/icons/menu/icon-globe.svg.js} +6 -6
- package/lib/assets/icons/menu/icon-globe.svg.js.map +1 -0
- package/lib/assets/icons/menu/icon-globe.svg.mjs +3 -0
- package/lib/assets/icons/menu/icon-globe.svg.mjs.map +1 -0
- package/lib/assets/pause.svg +3 -3
- package/lib/assets/pause2.svg +3 -3
- package/lib/assets/udmProMax.jpg +0 -0
- package/lib/assets/udmProMax2.jpg +0 -0
- package/lib/assets/udmProSpecial.jpg +0 -0
- package/lib/assets/udmProSpecial2.jpg +0 -0
- package/lib/components/CategoryTabs/CategoryTabs.styles.d.ts +1 -1
- package/lib/components/Compare/Compare.styles.d.ts +5 -5
- package/lib/components/Container/Container.d.ts +1 -1
- package/lib/components/Container/Container.js +3 -4
- package/lib/components/Container/Container.js.map +1 -1
- package/lib/components/Container/Container.mjs +4 -5
- package/lib/components/Container/Container.mjs.map +1 -1
- package/lib/components/Header/AccountMenu/AccountMenu.js +1 -11
- package/lib/components/Header/AccountMenu/AccountMenu.js.map +1 -1
- package/lib/components/Header/AccountMenu/AccountMenu.mjs +3 -13
- package/lib/components/Header/AccountMenu/AccountMenu.mjs.map +1 -1
- package/lib/components/Header/Header.styles.d.ts +2 -2
- package/lib/components/Header/Header.types.d.ts +4 -12
- package/lib/components/Header/Header.types.js +1 -2
- package/lib/components/Header/Header.types.js.map +1 -1
- package/lib/components/Header/Header.types.mjs +1 -2
- package/lib/components/Header/Header.types.mjs.map +1 -1
- package/lib/components/Header/MenuItem/MenuItem.styles.d.ts +1 -1
- package/lib/components/Header/MenuItem/MenuItem.styles.js +3 -3
- package/lib/components/Header/MenuItem/MenuItem.styles.js.map +1 -1
- package/lib/components/Header/MenuItem/MenuItem.styles.mjs +3 -3
- package/lib/components/Header/MenuItem/MenuItem.styles.mjs.map +1 -1
- package/lib/components/Header/MenuItem/MenuItem.types.d.ts +0 -1
- package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.styles.d.ts +1 -1
- package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.d.ts +1 -1
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.d.ts +1 -1
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js +95 -92
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js.map +1 -1
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs +95 -92
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs.map +1 -1
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.d.ts +0 -9
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js +1 -15
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js.map +1 -1
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs +2 -13
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs.map +1 -1
- package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.types.d.ts +4 -10
- package/lib/components/Header/ProHeader/ProHeader.d.ts +4 -3
- package/lib/components/Header/ProHeader/ProHeader.js +119 -245
- package/lib/components/Header/ProHeader/ProHeader.js.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.mjs +123 -247
- package/lib/components/Header/ProHeader/ProHeader.mjs.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.styles.d.ts +1 -7
- package/lib/components/Header/ProHeader/ProHeader.styles.js +17 -25
- package/lib/components/Header/ProHeader/ProHeader.styles.js.map +1 -1
- package/lib/components/Header/ProHeader/ProHeader.styles.mjs +18 -23
- package/lib/components/Header/ProHeader/ProHeader.styles.mjs.map +1 -1
- package/lib/components/Header/translations/ar.json.js +1 -4
- package/lib/components/Header/translations/ar.json.js.map +1 -1
- package/lib/components/Header/translations/ar.json.mjs +2 -4
- package/lib/components/Header/translations/ar.json.mjs.map +1 -1
- package/lib/components/Header/translations/de.json.js +1 -4
- package/lib/components/Header/translations/de.json.js.map +1 -1
- package/lib/components/Header/translations/de.json.mjs +2 -4
- package/lib/components/Header/translations/de.json.mjs.map +1 -1
- package/lib/components/Header/translations/el.json.js +1 -4
- package/lib/components/Header/translations/el.json.js.map +1 -1
- package/lib/components/Header/translations/el.json.mjs +2 -4
- package/lib/components/Header/translations/el.json.mjs.map +1 -1
- package/lib/components/Header/translations/en.json.js +1 -4
- package/lib/components/Header/translations/en.json.js.map +1 -1
- package/lib/components/Header/translations/en.json.mjs +2 -4
- package/lib/components/Header/translations/en.json.mjs.map +1 -1
- package/lib/components/Header/translations/es.json.js +1 -4
- package/lib/components/Header/translations/es.json.js.map +1 -1
- package/lib/components/Header/translations/es.json.mjs +2 -4
- package/lib/components/Header/translations/es.json.mjs.map +1 -1
- package/lib/components/Header/translations/fr.json.js +1 -4
- package/lib/components/Header/translations/fr.json.js.map +1 -1
- package/lib/components/Header/translations/fr.json.mjs +2 -4
- package/lib/components/Header/translations/fr.json.mjs.map +1 -1
- package/lib/components/Header/translations/it.json.js +1 -4
- package/lib/components/Header/translations/it.json.js.map +1 -1
- package/lib/components/Header/translations/it.json.mjs +2 -4
- package/lib/components/Header/translations/it.json.mjs.map +1 -1
- package/lib/components/Header/translations/ja.json.js +1 -4
- package/lib/components/Header/translations/ja.json.js.map +1 -1
- package/lib/components/Header/translations/ja.json.mjs +2 -4
- package/lib/components/Header/translations/ja.json.mjs.map +1 -1
- package/lib/components/Header/translations/pt-BR.json.js +1 -4
- package/lib/components/Header/translations/pt-BR.json.js.map +1 -1
- package/lib/components/Header/translations/pt-BR.json.mjs +2 -4
- package/lib/components/Header/translations/pt-BR.json.mjs.map +1 -1
- package/lib/components/Header/translations/zh-Hans.json.js +1 -4
- package/lib/components/Header/translations/zh-Hans.json.js.map +1 -1
- package/lib/components/Header/translations/zh-Hans.json.mjs +2 -4
- package/lib/components/Header/translations/zh-Hans.json.mjs.map +1 -1
- package/lib/components/Header/translations/zh-Hant-TW.json.js +1 -4
- package/lib/components/Header/translations/zh-Hant-TW.json.js.map +1 -1
- package/lib/components/Header/translations/zh-Hant-TW.json.mjs +2 -4
- package/lib/components/Header/translations/zh-Hant-TW.json.mjs.map +1 -1
- package/lib/components/Hero/Hero.styles.d.ts +2 -2
- package/lib/components/HeroFadeGallery/HeroFadeGallery.styles.d.ts +1 -1
- package/lib/components/HowToUseSection/HowToUseSection.styles.d.ts +2 -2
- package/lib/components/LandingPagePro/LandingPagePro.d.ts +0 -3
- package/lib/components/LandingPagePro/LandingPagePro.js +3 -3
- package/lib/components/LandingPagePro/LandingPagePro.js.map +1 -1
- package/lib/components/LandingPagePro/LandingPagePro.mjs +2 -2
- package/lib/components/LandingPagePro/LandingPagePro.mjs.map +1 -1
- package/lib/components/LandingPagePro/LandingPagePro.styles.d.ts +1 -1
- package/lib/components/LayoutRenderer/LayoutRenderer.styles.d.ts +1 -1
- package/lib/components/LayoutRendererV1/LayoutRenderer.styles.d.ts +3 -3
- package/lib/components/LayoutRendererV2/LayoutRenderer.styles.d.ts +3 -3
- package/lib/components/MicrositeSectionWrap/MicrositeSectionWrap.styles.d.ts +1 -1
- package/lib/components/MicrositeVideoSlideshow/MicrositeVideoSlideshow.js +1 -1
- package/lib/components/MicrositeVideoSlideshow/MicrositeVideoSlideshow.mjs +1 -1
- package/lib/components/MicrositeVideoSlideshow/assets/pause.svg.js +1 -1
- package/lib/components/MicrositeVideoSlideshow/assets/pause.svg.mjs +2 -2
- package/lib/components/ModelCompareV3/ModelCompareV3.types.d.ts +0 -1
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProMax.jpg.js +5 -5
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProMax.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProSpecial.jpg.js +5 -5
- package/lib/components/ModelCompareV3/assets/Consoles/bigCompare/udmProSpecial.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/udmProMax.jpg.js +1 -1
- package/lib/components/ModelCompareV3/assets/Consoles/udmProMax.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/assets/Consoles/udmProSpecial.jpg.js +1 -1
- package/lib/components/ModelCompareV3/assets/Consoles/udmProSpecial.jpg.mjs +2 -2
- package/lib/components/ModelCompareV3/data/CloudGateways.js +6 -6
- package/lib/components/ModelCompareV3/data/CloudGateways.mjs +4 -4
- package/lib/components/ModelCompareV3/data/VideoRecorders.js +2 -3
- package/lib/components/ModelCompareV3/data/VideoRecorders.js.map +1 -1
- package/lib/components/ModelCompareV3/data/VideoRecorders.mjs +2 -3
- package/lib/components/ModelCompareV3/data/VideoRecorders.mjs.map +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProMax.js +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProMax.mjs +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProSpecial.js +1 -1
- package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs +1 -1
- package/lib/components/ModelCompareV3/translations/ar.json.js +106 -742
- package/lib/components/ModelCompareV3/translations/ar.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/ar.json.mjs +106 -742
- package/lib/components/ModelCompareV3/translations/ar.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/de.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/de.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/de.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/de.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/el.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/el.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/el.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/el.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/en.json.js +0 -6
- package/lib/components/ModelCompareV3/translations/en.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/en.json.mjs +0 -6
- package/lib/components/ModelCompareV3/translations/en.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/es.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/es.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/es.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/es.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/fr.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/fr.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/fr.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/fr.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/it.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/it.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/it.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/it.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/ja.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/ja.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/ja.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/ja.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/pt-BR.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/pt-BR.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/pt-BR.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/pt-BR.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/useModelCompareTranslation.d.ts +2 -2
- package/lib/components/ModelCompareV3/translations/zh-Hans.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/zh-Hans.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/zh-Hans.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/zh-Hans.json.mjs.map +1 -1
- package/lib/components/ModelCompareV3/translations/zh-Hant-TW.json.js +105 -741
- package/lib/components/ModelCompareV3/translations/zh-Hant-TW.json.js.map +1 -1
- package/lib/components/ModelCompareV3/translations/zh-Hant-TW.json.mjs +105 -741
- package/lib/components/ModelCompareV3/translations/zh-Hant-TW.json.mjs.map +1 -1
- package/lib/components/ProductSectionNavigation/ProductSectionNavigation.styles.d.ts +1 -1
- package/lib/components/ProductSectionNavigationV2/ProductSectionNavigation.styles.d.ts +1 -1
- package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.d.ts +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.js +17 -313
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.mjs +17 -311
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.d.ts +2 -3
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.js +0 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.mjs +0 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.js +34 -120
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.mjs +34 -120
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.d.ts +2 -16
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.js +12 -54
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.mjs +11 -50
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/assets/ArrowLeftPrimary.svg.js +5 -5
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/assets/ArrowRightPrimary.svg.js +5 -5
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.js +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.js +0 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.mjs +0 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/attention.svg.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/attention.svg.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.mjs +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/assets/attention.svg.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/assets/attention.svg.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.js +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.mjs +1 -1
- package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js +2 -2
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs +2 -2
- package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/ResourceCalculator.js +2 -1
- package/lib/components/ResourceCalculatorV1/ResourceCalculator.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/ResourceCalculator.mjs +2 -1
- package/lib/components/ResourceCalculatorV1/ResourceCalculator.mjs.map +1 -1
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.d.ts +1 -1
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.js +1 -3
- package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.js.map +1 -0
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.mjs +1 -3
- package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.mjs.map +1 -0
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.styles.d.ts +0 -1
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.styles.js +7 -10
- package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.js.map +1 -0
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.styles.mjs +7 -10
- package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.mjs.map +1 -0
- package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/HorizontalOptionSelect.types.d.ts +0 -1
- package/lib/components/ResourceCalculatorV1/components/index.d.ts +1 -0
- package/lib/components/ResourceCalculatorV1/components/index.js +5 -0
- package/lib/components/{Header/Navigation/ProMenu → ResourceCalculatorV1/components}/index.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/components/index.mjs +3 -0
- package/lib/components/ResourceCalculatorV1/translations/en.json.js +4 -6
- package/lib/components/ResourceCalculatorV1/translations/en.json.js.map +1 -1
- package/lib/components/ResourceCalculatorV1/translations/en.json.mjs +4 -6
- package/lib/components/ResourceCalculatorV1/translations/en.json.mjs.map +1 -1
- package/lib/components/ResourceCalculatorV1/translations/useResourceCalculatorTranslation.d.ts +2 -2
- package/lib/components/VideoPlayerNew/VideoPlayer.js +1 -1
- package/lib/components/VideoPlayerNew/VideoPlayer.mjs +1 -1
- package/lib/components/VideoPlayerNew/assets/pause.svg.js +1 -1
- package/lib/components/VideoPlayerNew/assets/pause.svg.mjs +2 -2
- package/lib/components/index.d.ts +0 -1
- package/lib/components/index.js +0 -2
- package/lib/components/index.js.map +1 -1
- package/lib/components/index.mjs +0 -2
- package/lib/components/index.mjs.map +1 -1
- package/lib/constants/icons/options/colors/black.svg.js +5 -5
- package/lib/constants/icons/options/colors/index.js +3 -3
- package/lib/constants/icons/options/styles/black.svg.js +5 -5
- package/lib/constants/icons/options/styles/index.js +3 -3
- package/lib/constants/optionIcons.js +6 -6
- package/lib/constants/optionIcons.mjs +4 -4
- package/lib/constants/proStoreCategories/mapping/index.d.ts +0 -1
- package/lib/constants/proStoreCategories/mapping/index.js +10 -15
- package/lib/constants/proStoreCategories/mapping/index.js.map +1 -1
- package/lib/constants/proStoreCategories/mapping/index.mjs +10 -15
- package/lib/constants/proStoreCategories/mapping/index.mjs.map +1 -1
- package/lib/constants/proStoreCategories/mapping/unifi.d.ts +1 -2
- package/lib/constants/proStoreCategories/mapping/unifi.js +0 -1
- package/lib/constants/proStoreCategories/mapping/unifi.js.map +1 -1
- package/lib/constants/proStoreCategories/mapping/unifi.mjs +0 -1
- package/lib/constants/proStoreCategories/mapping/unifi.mjs.map +1 -1
- package/lib/constants/proStoreCategories/translations/en.json.js +0 -3
- package/lib/constants/proStoreCategories/translations/en.json.js.map +1 -1
- package/lib/constants/proStoreCategories/translations/en.json.mjs +1 -3
- package/lib/constants/proStoreCategories/translations/en.json.mjs.map +1 -1
- package/lib/constants/proStoreCategories/translations/fr.json.js +1 -1
- package/lib/constants/proStoreCategories/translations/fr.json.mjs +1 -1
- package/lib/constants/proStoreCategories/translations/zh-Hans.json.js +1 -1
- package/lib/constants/proStoreCategories/translations/zh-Hans.json.mjs +1 -1
- package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.js +1 -1
- package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.mjs +1 -1
- package/lib/constants/theme.js +0 -4
- package/lib/constants/theme.js.map +1 -1
- package/lib/constants/theme.mjs +0 -4
- package/lib/constants/theme.mjs.map +1 -1
- package/lib/contexts/MenuContext/context.js +1 -1
- package/lib/contexts/MenuContext/context.js.map +1 -1
- package/lib/contexts/MenuContext/context.mjs +1 -1
- package/lib/contexts/MenuContext/context.mjs.map +1 -1
- package/lib/helpers/index.d.ts +0 -1
- package/lib/helpers/index.js +0 -11
- package/lib/helpers/index.js.map +1 -1
- package/lib/helpers/index.mjs +0 -1
- package/lib/helpers/index.mjs.map +1 -1
- package/lib/helpers/ux.d.ts +1 -9
- package/lib/helpers/ux.js +0 -15
- package/lib/helpers/ux.js.map +1 -1
- package/lib/helpers/ux.mjs +1 -15
- package/lib/helpers/ux.mjs.map +1 -1
- package/lib/types/index.d.ts +0 -1
- package/lib/types/index.js +0 -2
- package/lib/types/index.js.map +1 -1
- package/lib/types/index.mjs +0 -1
- package/lib/types/index.mjs.map +1 -1
- package/lib/utils/array.d.ts +0 -4
- package/lib/utils/array.js +0 -10
- package/lib/utils/array.js.map +1 -1
- package/lib/utils/array.mjs +1 -10
- package/lib/utils/array.mjs.map +1 -1
- package/lib/utils/money/constants.d.ts +25 -56
- package/lib/utils/money/constants.js +7 -72
- package/lib/utils/money/constants.js.map +1 -1
- package/lib/utils/money/constants.mjs +7 -70
- package/lib/utils/money/constants.mjs.map +1 -1
- package/lib/utils/money/format.d.ts +5 -10
- package/lib/utils/money/format.js +14 -22
- package/lib/utils/money/format.js.map +1 -1
- package/lib/utils/money/format.mjs +16 -23
- package/lib/utils/money/format.mjs.map +1 -1
- package/lib/utils/money/index.d.ts +1 -4
- package/lib/utils/money/index.js +8 -26
- package/lib/utils/money/index.js.map +1 -1
- package/lib/utils/money/index.mjs +4 -8
- package/lib/utils/money/index.mjs.map +1 -1
- package/lib/utils/money/misc.d.ts +28 -68
- package/lib/utils/money/misc.js +64 -35
- package/lib/utils/money/misc.js.map +1 -1
- package/lib/utils/money/misc.mjs +43 -32
- package/lib/utils/money/misc.mjs.map +1 -1
- package/lib/utils/money/tax.d.ts +2 -38
- package/lib/utils/money/tax.js +10 -46
- package/lib/utils/money/tax.js.map +1 -1
- package/lib/utils/money/tax.mjs +11 -42
- package/lib/utils/money/tax.mjs.map +1 -1
- package/lib/utils/money/types.d.ts +3 -78
- package/lib/utils/number.d.ts +1 -1
- package/lib/utils/number.js +1 -1
- package/lib/utils/number.js.map +1 -1
- package/lib/utils/number.mjs +1 -1
- package/lib/utils/number.mjs.map +1 -1
- package/lib/utils/validations.d.ts +15 -0
- package/lib/utils/validations.js +23 -0
- package/lib/utils/validations.js.map +1 -0
- package/lib/utils/validations.mjs +21 -0
- package/lib/utils/validations.mjs.map +1 -0
- package/package.json +1 -1
- package/lib/assets/efg.png +0 -0
- package/lib/assets/envr.png +0 -0
- package/lib/assets/icon-location-pin.svg +0 -5
- package/lib/assets/icons/menu/icon-location-pin.svg.js +0 -27
- package/lib/assets/icons/menu/icon-location-pin.svg.js.map +0 -1
- package/lib/assets/icons/menu/icon-location-pin.svg.mjs +0 -3
- package/lib/assets/icons/menu/icon-location-pin.svg.mjs.map +0 -1
- package/lib/assets/ucg-max.png +0 -0
- package/lib/components/Header/Navigation/ProMenu/ProMenu.d.ts +0 -2
- package/lib/components/Header/Navigation/ProMenu/ProMenu.js +0 -103
- package/lib/components/Header/Navigation/ProMenu/ProMenu.js.map +0 -1
- package/lib/components/Header/Navigation/ProMenu/ProMenu.mjs +0 -81
- package/lib/components/Header/Navigation/ProMenu/ProMenu.mjs.map +0 -1
- package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.d.ts +0 -23
- package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.js +0 -121
- package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.js.map +0 -1
- package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.mjs +0 -106
- package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.mjs.map +0 -1
- package/lib/components/Header/Navigation/ProMenu/ProMenu.types.d.ts +0 -12
- package/lib/components/Header/Navigation/ProMenu/index.d.ts +0 -1
- package/lib/components/Header/Navigation/ProMenu/index.js +0 -6
- package/lib/components/Header/Navigation/ProMenu/index.mjs +0 -3
- package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.js.map +0 -1
- package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.mjs.map +0 -1
- package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.js.map +0 -1
- package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.mjs.map +0 -1
- package/lib/components/ModelCompareV3/assets/envr.png.js +0 -27
- package/lib/components/ModelCompareV3/assets/envr.png.js.map +0 -1
- package/lib/components/ModelCompareV3/assets/envr.png.mjs +0 -3
- package/lib/components/ModelCompareV3/assets/envr.png.mjs.map +0 -1
- package/lib/components/ModelCompareV3/data/products/envr.d.ts +0 -2
- package/lib/components/ModelCompareV3/data/products/envr.js +0 -97
- package/lib/components/ModelCompareV3/data/products/envr.js.map +0 -1
- package/lib/components/ModelCompareV3/data/products/envr.mjs +0 -89
- package/lib/components/ModelCompareV3/data/products/envr.mjs.map +0 -1
- package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.js +0 -27
- package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.js.map +0 -1
- package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.mjs +0 -3
- package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.mjs.map +0 -1
- package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.js.map +0 -1
- package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.mjs +0 -3
- package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.mjs.map +0 -1
- package/lib/helpers/product.d.ts +0 -87
- package/lib/helpers/product.js +0 -346
- package/lib/helpers/product.js.map +0 -1
- package/lib/helpers/product.mjs +0 -335
- package/lib/helpers/product.mjs.map +0 -1
- package/lib/types/product.d.ts +0 -87
- package/lib/types/product.js +0 -14
- package/lib/types/product.js.map +0 -1
- package/lib/types/product.mjs +0 -13
- package/lib/types/product.mjs.map +0 -1
- package/lib/utils/money/allocators/fixedAmount.d.ts +0 -26
- package/lib/utils/money/allocators/fixedAmount.js +0 -52
- package/lib/utils/money/allocators/fixedAmount.js.map +0 -1
- package/lib/utils/money/allocators/fixedAmount.mjs +0 -50
- package/lib/utils/money/allocators/fixedAmount.mjs.map +0 -1
- package/lib/utils/money/allocators/index.d.ts +0 -2
- package/lib/utils/money/allocators/index.js +0 -8
- package/lib/utils/money/allocators/index.js.map +0 -1
- package/lib/utils/money/allocators/index.mjs +0 -4
- package/lib/utils/money/allocators/index.mjs.map +0 -1
- package/lib/utils/money/allocators/productAmount.d.ts +0 -13
- package/lib/utils/money/allocators/productAmount.js +0 -98
- package/lib/utils/money/allocators/productAmount.js.map +0 -1
- package/lib/utils/money/allocators/productAmount.mjs +0 -96
- package/lib/utils/money/allocators/productAmount.mjs.map +0 -1
- package/lib/utils/money/exchangeRate.d.ts +0 -31
- package/lib/utils/money/exchangeRate.js +0 -27
- package/lib/utils/money/exchangeRate.js.map +0 -1
- package/lib/utils/money/exchangeRate.mjs +0 -23
- package/lib/utils/money/exchangeRate.mjs.map +0 -1
- package/lib/utils/money/misc.private.d.ts +0 -23
- package/lib/utils/money/misc.private.js +0 -46
- package/lib/utils/money/misc.private.js.map +0 -1
- package/lib/utils/money/misc.private.mjs +0 -21
- package/lib/utils/money/misc.private.mjs.map +0 -1
- package/lib/utils/money/shipping.d.ts +0 -5
- package/lib/utils/money/shipping.js +0 -8
- package/lib/utils/money/shipping.js.map +0 -1
- package/lib/utils/money/shipping.mjs +0 -6
- package/lib/utils/money/shipping.mjs.map +0 -1
- package/lib/utils/money/tax.private.d.ts +0 -17
- package/lib/utils/money/tax.private.js +0 -65
- package/lib/utils/money/tax.private.js.map +0 -1
- package/lib/utils/money/tax.private.mjs +0 -60
- package/lib/utils/money/tax.private.mjs.map +0 -1
- package/lib/utils/productSort.d.ts +0 -41
- package/lib/utils/productSort.js +0 -67
- package/lib/utils/productSort.js.map +0 -1
- package/lib/utils/productSort.mjs +0 -60
- package/lib/utils/productSort.mjs.map +0 -1
- /package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/index.d.ts +0 -0
- /package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/index.js +0 -0
- /package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/index.js.map +0 -0
- /package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/index.mjs +0 -0
- /package/lib/components/{HorizontalOptionSelect → ResourceCalculatorV1/components/HorizontalOptionSelect}/index.mjs.map +0 -0
- /package/lib/components/{Header/Navigation/ProMenu → ResourceCalculatorV1/components}/index.mjs.map +0 -0
package/lib/utils/money/misc.js
CHANGED
|
@@ -1,14 +1,56 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var currencies = require('@dinero.js/currencies');
|
|
3
4
|
var dinero_js = require('dinero.js');
|
|
4
5
|
require('../../types/index.js');
|
|
5
6
|
var errors = require('../errors.js');
|
|
6
7
|
var number = require('../number.js');
|
|
7
8
|
var string = require('../string.js');
|
|
9
|
+
var validations = require('../validations.js');
|
|
8
10
|
var constants = require('./constants.js');
|
|
9
|
-
var misc_private = require('./misc.private.js');
|
|
10
11
|
var generated = require('../../types/generated.js');
|
|
12
|
+
function _interopNamespace(e) {
|
|
13
|
+
if (e && e.__esModule) return e;
|
|
14
|
+
var n = Object.create(null);
|
|
15
|
+
if (e) {
|
|
16
|
+
Object.keys(e).forEach(function (k) {
|
|
17
|
+
if (k !== 'default') {
|
|
18
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
19
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
20
|
+
enumerable: true,
|
|
21
|
+
get: function () {
|
|
22
|
+
return e[k];
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
n["default"] = e;
|
|
29
|
+
return Object.freeze(n);
|
|
30
|
+
}
|
|
31
|
+
var currencies__namespace = /*#__PURE__*/_interopNamespace(currencies);
|
|
11
32
|
"use strict";
|
|
33
|
+
const currencyLookup = new Set(Object.keys(generated.Currency).map(el => el.toString()));
|
|
34
|
+
const currenciesMap = new Map(Object.values(currencies__namespace).map(currency2 => [currency2.code, currency2]));
|
|
35
|
+
const floatToInt = (floatAmount, base, exponent) => constants.financialRound(floatAmount * Math.pow(base, exponent));
|
|
36
|
+
const prettifyTotal = total => {
|
|
37
|
+
if (!dinero_js.hasSubUnits(total)) {
|
|
38
|
+
return total;
|
|
39
|
+
}
|
|
40
|
+
const totalJson = total.toJSON();
|
|
41
|
+
const minValueInclusiveToRoundDownFrom = constants.prettifyPriceLookup.get(totalJson.currency.code);
|
|
42
|
+
if (minValueInclusiveToRoundDownFrom == null || dinero_js.toUnit(total) < minValueInclusiveToRoundDownFrom) {
|
|
43
|
+
return total;
|
|
44
|
+
}
|
|
45
|
+
const roundedUnitPrice = dinero_js.toUnit(total, {
|
|
46
|
+
digits: 0,
|
|
47
|
+
round: dinero_js.down
|
|
48
|
+
});
|
|
49
|
+
return dinero_js.dinero({
|
|
50
|
+
amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
|
|
51
|
+
currency: totalJson.currency
|
|
52
|
+
});
|
|
53
|
+
};
|
|
12
54
|
const toSmallestSubunit = total => {
|
|
13
55
|
if (!dinero_js.hasSubUnits(total)) {
|
|
14
56
|
return total;
|
|
@@ -18,47 +60,49 @@ const toSmallestSubunit = total => {
|
|
|
18
60
|
if (roundToDigits == null || roundingMode == null) {
|
|
19
61
|
return total;
|
|
20
62
|
}
|
|
21
|
-
|
|
63
|
+
const roundedUnitPrice = dinero_js.toUnit(total, {
|
|
64
|
+
digits: roundToDigits,
|
|
65
|
+
round: roundingMode
|
|
66
|
+
});
|
|
67
|
+
return dinero_js.dinero({
|
|
68
|
+
amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
|
|
69
|
+
currency: totalJson.currency
|
|
70
|
+
});
|
|
22
71
|
};
|
|
23
72
|
const getDineroCurrency = currency2 => {
|
|
24
|
-
const dineroCurrency =
|
|
73
|
+
const dineroCurrency = currenciesMap.get(currency2);
|
|
25
74
|
errors.assert(!!dineroCurrency, `Unsupported currency: "${currency2}"`);
|
|
26
75
|
return dineroCurrency;
|
|
27
76
|
};
|
|
28
77
|
const parseCurrencyCode = code => {
|
|
29
78
|
const normalizedCode = string.capitalize(code.toLowerCase());
|
|
30
|
-
errors.assert(
|
|
79
|
+
errors.assert(currencyLookup.has(normalizedCode), `Invalid currency code: ${normalizedCode}`);
|
|
31
80
|
return generated.Currency[normalizedCode];
|
|
32
81
|
};
|
|
33
|
-
const
|
|
82
|
+
const centsToMajorUnits = (amount2, currency2) => {
|
|
34
83
|
const dineroCurrency = getDineroCurrency(currency2);
|
|
35
|
-
const
|
|
36
|
-
amount:
|
|
84
|
+
const price = dinero_js.dinero({
|
|
85
|
+
amount: amount2,
|
|
37
86
|
currency: dineroCurrency
|
|
38
87
|
});
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const dineroToCurrencyUnit = dineroObj => {
|
|
42
|
-
return dinero_js.toUnit(dineroObj);
|
|
88
|
+
const divider = Math.pow(10, dineroCurrency.exponent);
|
|
89
|
+
return dinero_js.toSnapshot(price).amount / divider;
|
|
43
90
|
};
|
|
44
91
|
const parseFloatToDinero = (floatAmount, currency2) => {
|
|
45
|
-
const dineroCurrency = getDineroCurrency(currency2);
|
|
46
|
-
return parseFloatToDineroRaw(floatAmount, dineroCurrency);
|
|
47
|
-
};
|
|
48
|
-
const parseFloatToDineroRaw = (floatAmount, dineroCurrency) => {
|
|
49
92
|
number.isFloat(floatAmount, "Amount");
|
|
93
|
+
const dineroCurrency = getDineroCurrency(currency2);
|
|
50
94
|
const scaleOfGivenAmount = String(floatAmount).split(".")[1]?.length ?? dineroCurrency.exponent;
|
|
51
95
|
if (scaleOfGivenAmount == null || scaleOfGivenAmount > dineroCurrency.exponent) {
|
|
52
96
|
throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);
|
|
53
97
|
}
|
|
54
|
-
const rateInt =
|
|
98
|
+
const rateInt = floatToInt(floatAmount, dineroCurrency.base, dineroCurrency.exponent);
|
|
55
99
|
return dinero_js.dinero({
|
|
56
100
|
amount: rateInt,
|
|
57
101
|
currency: dineroCurrency
|
|
58
102
|
});
|
|
59
103
|
};
|
|
60
104
|
const getDinero = (amount2, currency2) => {
|
|
61
|
-
|
|
105
|
+
validations.isInt(amount2, "Amount");
|
|
62
106
|
return dinero_js.dinero({
|
|
63
107
|
amount: amount2,
|
|
64
108
|
currency: getDineroCurrency(currency2)
|
|
@@ -90,33 +134,18 @@ const money = dinero2 => {
|
|
|
90
134
|
};
|
|
91
135
|
const addMany = (addends, defaultCurrency) => [...addends, getDinero(0, defaultCurrency)].reduce(dinero_js.add);
|
|
92
136
|
const subtractMany = (subtractions, defaultCurrency) => [...subtractions, getDinero(0, defaultCurrency)].reduce(dinero_js.subtract);
|
|
93
|
-
const stringAmountToDinero = (price, currency2) =>
|
|
94
|
-
// FIXME: parseFloat seems dangerous O_O
|
|
95
|
-
parseFloatToDinero(parseFloat(price), currency2);
|
|
96
|
-
const roundDinero = (dinero2, roundingFn) => {
|
|
97
|
-
const roundedUnitPrice = dinero_js.toUnit(dinero2, {
|
|
98
|
-
digits: 0,
|
|
99
|
-
round: roundingFn
|
|
100
|
-
});
|
|
101
|
-
const snapshot = dinero_js.toSnapshot(dinero2);
|
|
102
|
-
return dinero2.create({
|
|
103
|
-
amount: roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,
|
|
104
|
-
currency: snapshot.currency
|
|
105
|
-
});
|
|
106
|
-
};
|
|
137
|
+
const stringAmountToDinero = (price, currency2) => parseFloatToDinero(parseFloat(price), currency2);
|
|
107
138
|
exports.addMany = addMany;
|
|
108
139
|
exports.amount = amount;
|
|
109
|
-
exports.
|
|
140
|
+
exports.centsToMajorUnits = centsToMajorUnits;
|
|
110
141
|
exports.currency = currency;
|
|
111
|
-
exports.dineroToCurrencyUnit = dineroToCurrencyUnit;
|
|
112
142
|
exports.getDinero = getDinero;
|
|
113
143
|
exports.getDineroCurrency = getDineroCurrency;
|
|
114
144
|
exports.money = money;
|
|
115
145
|
exports.multiplyByFullPercent = multiplyByFullPercent;
|
|
116
146
|
exports.parseCurrencyCode = parseCurrencyCode;
|
|
117
147
|
exports.parseFloatToDinero = parseFloatToDinero;
|
|
118
|
-
exports.
|
|
119
|
-
exports.roundDinero = roundDinero;
|
|
148
|
+
exports.prettifyTotal = prettifyTotal;
|
|
120
149
|
exports.stringAmountToDinero = stringAmountToDinero;
|
|
121
150
|
exports.subtractMany = subtractMany;
|
|
122
151
|
exports.toSmallestSubunit = toSmallestSubunit;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n amount:\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,MAAAM,iBAAA,GAAqBH,SAAqC,IAAA;EAC/D,MAAAI,cAAA,GAAiBC,YAAAA,CAAAA,sBAAuB,CAAAN,GAAA,CAAIC,SAAQ,CAAA;EAC1DM,MAAA,CAAAA,MAAA,CAAO,CAAC,CAACF,cAAgB,EAAA,0BAA0BJ,SAAW,GAAA,CAAA;EACvD,OAAAI,cAAA;AACT,CAAA;AAWa,MAAAG,iBAAA,GAAqBN,IAA2B,IAAA;EAC3D,MAAMO,cAAiB,GAAAC,MAAA,CAAAA,UAAA,CAAWR,IAAK,CAAAS,WAAA,CAAa,CAAA,CAAA;EACpDJ,MAAA,CAAAA,MAAA,CACEK,YAAA,CAAAA,cAAA,CAAeC,IAAIJ,cAAc,CAAA,4BACPA,cAAc,EAAA,CAC1C;EACA,OAAOK,SAAAA,CAAAA,SAASL,cAAuC,CAAA;AACzD,CAAA;AAYa,MAAAM,mBAAA,GAAsBA,CACjCC,WAAA,EACAf,SACW,KAAA;EACL,MAAAI,cAAA,GAA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ACA,EAAAJ,eAAA,KACG,CAAC,GAAGI,YAAc,EAAAhB,SAAA,CAAU,CAAG,EAAAY,eAAe,CAAC,CAAA,CAAEC,OAAOI,SAAAA,CAAAA,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAACC,KAAerD,EAAAA,SAAAA;AAAA;AAElDqB,kBAAmB,CAAAiC,UAAA,CAAWD,KAAK,CAAA,EAAGrD,SAAQ,CAAA;AAUnC,MAAAE,WAAA,GAAcA,CAACe,OAAAA,EAAcsC,UAAiC,KAAA;EACnE,MAAAC,gBAAA,GAAmBpC,iBAAOH,OAAQ,EAAA;IAAEwC,QAAQ,CAAG;IAAAC,KAAA,EAAOH;GAAY,CAAA;EAElE,MAAAI,QAAA,GAAWvB,qBAAWnB,OAAM,CAAA;EAElC,OAAOA,QAAO2C,MAAO,CAAA;IACnB1C,QACEsC,gBAAmB,GAAAG,QAAA,CAAS3D,QAAS,CAAAiC,IAAA,IAAQ0B,SAAS3D,QAAS,CAAA6B,QAAA;IACjE7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import * as currencies from \"@dinero.js/currencies\";\nimport type { Dinero, Currency as DineroCurrency } from \"dinero.js\";\nimport {\n add,\n dinero,\n down,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { isInt } from \"../validations\";\nimport {\n financialRound,\n prettifyPriceLookup,\n smallestSubunitLookup,\n} from \"./constants\";\n\nexport interface Money {\n amount: number;\n currency: Currency;\n}\n\n// #############################################################################\n// Private helpers\n// #############################################################################\nconst currencyLookup = new Set(\n Object.keys(Currency).map((el) => el.toString()),\n);\n\n/**\n * Creating a map of currencies for way faster lookup then doing a array.find()\n * @see https://stackoverflow.com/a/65604244/1378261\n */\nconst currenciesMap = new Map(\n Object.values(currencies).map((currency) => [currency.code, currency]),\n);\n\n/**\n * Private util to convert a float value into a int. Also applies financial rounding to the value if needed.\n * Inspired by https://v2.dinerojs.com/docs/faq/how-can-i-create-dinero-objects-from-floats\n * @private Just for using within this file, please consider using other methods to solve your issue\n * @example\n * floatToInt(69.10, 10, 2); // 6910\n * floatToInt(42, 10, 2); // 4200\n * floatToInt(0.22, 10, 6); // 220000\n */\nconst floatToInt = (\n floatAmount: number,\n base: number,\n exponent: number,\n): number => financialRound(floatAmount * Math.pow(base, exponent));\n\n// #############################################################################\n// Public functions\n// #############################################################################\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dinero<number>): Dinero<number> => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n const roundedUnitPrice = toUnit(total, { digits: 0, round: down });\n // Multiplying by 100 to get the cents\n return dinero({\n amount:\n roundedUnitPrice *\n Math.pow(totalJson.currency.base, totalJson.currency.exponent),\n currency: totalJson.currency,\n });\n};\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dinero<number>): Dinero<number> => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n const roundedUnitPrice = toUnit(total, {\n digits: roundToDigits,\n round: roundingMode,\n });\n return dinero({\n amount:\n roundedUnitPrice *\n Math.pow(totalJson.currency.base, totalJson.currency.exponent),\n currency: totalJson.currency,\n });\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (\n currency: Currency,\n): DineroCurrency<number> => {\n const dineroCurrency = currenciesMap.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency to local currency type\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Get major units amount for cents amount and currency\n *\n * Can look into the approach of dinero core toUnits if we need a more robust approach\n * https://github.com/dinerojs/dinero.js/blob/main/packages/core/src/api/toUnits.ts\n * Though, based on experimentation, it's a basic division in the end regardless\n */\nexport const centsToMajorUnits = (\n amount: number,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const price = dinero({ amount, currency: dineroCurrency });\n const divider = Math.pow(10, dineroCurrency.exponent);\n\n return toSnapshot(price).amount / divider;\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n isFloat(floatAmount, \"Amount\");\n\n const dineroCurrency = getDineroCurrency(currency);\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n */\nexport const getDinero = (\n amount: number,\n currency: Currency,\n): Dinero<number> => {\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n */\nexport const amount = (dinero: Dinero<number>): number => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dinero<number>,\n percentIncrease: number,\n): Dinero<number> => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n */\nexport const currency = (dinero: Dinero<number>): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n */\nexport const money = (dinero: Dinero<number>): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n */\nexport const addMany = (\n addends: Array<Dinero<number>>,\n defaultCurrency: Currency,\n) => [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dinero<number>>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n parseFloatToDinero(parseFloat(price), currency);\n"],"names":["currencyLookup","Set","Object","keys","Currency","map","el","toString","currenciesMap","Map","values","currencies","currency","code","floatToInt","floatAmount","base","exponent","financialRound","Math","pow","prettifyTotal","total","hasSubUnits","totalJson","toJSON","minValueInclusiveToRoundDownFrom","prettifyPriceLookup","get","toUnit","roundedUnitPrice","digits","round","down","dinero","amount","toSmallestSubunit","roundToDigits","roundingMode","smallestSubunitLookup","getDineroCurrency","dineroCurrency","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","has","centsToMajorUnits","price","divider","toSnapshot","parseFloatToDinero","isFloat","scaleOfGivenAmount","String","split","length","Error","rateInt","getDinero","isInt","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","parseFloat"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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,eAAA,KACG,CAAC,GAAGI,YAAc,EAAAf,SAAA,CAAU,CAAG,EAAAW,eAAe,CAAC,CAAA,CAAEC,OAAOI,SAAAA,CAAAA,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAAC5B,KAAerC,EAAAA,SAAAA,KAClDwC,mBAAmB0B,UAAW,CAAA7B,KAAK,GAAGrC,SAAQ,CAAA;;;;;;;;;;;;;;"}
|
package/lib/utils/money/misc.mjs
CHANGED
|
@@ -1,12 +1,34 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as currencies from '@dinero.js/currencies';
|
|
2
|
+
import { hasSubUnits, toUnit, down, dinero, toSnapshot, multiply, transformScale, add, subtract } from 'dinero.js';
|
|
2
3
|
import '../../types/index.mjs';
|
|
3
4
|
import { assert } from '../errors.mjs';
|
|
4
|
-
import { isFloat
|
|
5
|
+
import { isFloat } from '../number.mjs';
|
|
5
6
|
import { capitalize } from '../string.mjs';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
7
|
+
import { isInt } from '../validations.mjs';
|
|
8
|
+
import { financialRound, prettifyPriceLookup, smallestSubunitLookup } from './constants.mjs';
|
|
8
9
|
import { Currency } from '../../types/generated.mjs';
|
|
9
10
|
"use strict";
|
|
11
|
+
const currencyLookup = new Set(Object.keys(Currency).map(el => el.toString()));
|
|
12
|
+
const currenciesMap = new Map(Object.values(currencies).map(currency2 => [currency2.code, currency2]));
|
|
13
|
+
const floatToInt = (floatAmount, base, exponent) => financialRound(floatAmount * Math.pow(base, exponent));
|
|
14
|
+
const prettifyTotal = total => {
|
|
15
|
+
if (!hasSubUnits(total)) {
|
|
16
|
+
return total;
|
|
17
|
+
}
|
|
18
|
+
const totalJson = total.toJSON();
|
|
19
|
+
const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(totalJson.currency.code);
|
|
20
|
+
if (minValueInclusiveToRoundDownFrom == null || toUnit(total) < minValueInclusiveToRoundDownFrom) {
|
|
21
|
+
return total;
|
|
22
|
+
}
|
|
23
|
+
const roundedUnitPrice = toUnit(total, {
|
|
24
|
+
digits: 0,
|
|
25
|
+
round: down
|
|
26
|
+
});
|
|
27
|
+
return dinero({
|
|
28
|
+
amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
|
|
29
|
+
currency: totalJson.currency
|
|
30
|
+
});
|
|
31
|
+
};
|
|
10
32
|
const toSmallestSubunit = total => {
|
|
11
33
|
if (!hasSubUnits(total)) {
|
|
12
34
|
return total;
|
|
@@ -16,10 +38,17 @@ const toSmallestSubunit = total => {
|
|
|
16
38
|
if (roundToDigits == null || roundingMode == null) {
|
|
17
39
|
return total;
|
|
18
40
|
}
|
|
19
|
-
|
|
41
|
+
const roundedUnitPrice = toUnit(total, {
|
|
42
|
+
digits: roundToDigits,
|
|
43
|
+
round: roundingMode
|
|
44
|
+
});
|
|
45
|
+
return dinero({
|
|
46
|
+
amount: roundedUnitPrice * Math.pow(totalJson.currency.base, totalJson.currency.exponent),
|
|
47
|
+
currency: totalJson.currency
|
|
48
|
+
});
|
|
20
49
|
};
|
|
21
50
|
const getDineroCurrency = currency2 => {
|
|
22
|
-
const dineroCurrency =
|
|
51
|
+
const dineroCurrency = currenciesMap.get(currency2);
|
|
23
52
|
assert(!!dineroCurrency, `Unsupported currency: "${currency2}"`);
|
|
24
53
|
return dineroCurrency;
|
|
25
54
|
};
|
|
@@ -28,23 +57,18 @@ const parseCurrencyCode = code => {
|
|
|
28
57
|
assert(currencyLookup.has(normalizedCode), `Invalid currency code: ${normalizedCode}`);
|
|
29
58
|
return Currency[normalizedCode];
|
|
30
59
|
};
|
|
31
|
-
const
|
|
60
|
+
const centsToMajorUnits = (amount2, currency2) => {
|
|
32
61
|
const dineroCurrency = getDineroCurrency(currency2);
|
|
33
|
-
const
|
|
34
|
-
amount:
|
|
62
|
+
const price = dinero({
|
|
63
|
+
amount: amount2,
|
|
35
64
|
currency: dineroCurrency
|
|
36
65
|
});
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const dineroToCurrencyUnit = dineroObj => {
|
|
40
|
-
return toUnit(dineroObj);
|
|
66
|
+
const divider = Math.pow(10, dineroCurrency.exponent);
|
|
67
|
+
return toSnapshot(price).amount / divider;
|
|
41
68
|
};
|
|
42
69
|
const parseFloatToDinero = (floatAmount, currency2) => {
|
|
43
|
-
const dineroCurrency = getDineroCurrency(currency2);
|
|
44
|
-
return parseFloatToDineroRaw(floatAmount, dineroCurrency);
|
|
45
|
-
};
|
|
46
|
-
const parseFloatToDineroRaw = (floatAmount, dineroCurrency) => {
|
|
47
70
|
isFloat(floatAmount, "Amount");
|
|
71
|
+
const dineroCurrency = getDineroCurrency(currency2);
|
|
48
72
|
const scaleOfGivenAmount = String(floatAmount).split(".")[1]?.length ?? dineroCurrency.exponent;
|
|
49
73
|
if (scaleOfGivenAmount == null || scaleOfGivenAmount > dineroCurrency.exponent) {
|
|
50
74
|
throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);
|
|
@@ -88,19 +112,6 @@ const money = dinero2 => {
|
|
|
88
112
|
};
|
|
89
113
|
const addMany = (addends, defaultCurrency) => [...addends, getDinero(0, defaultCurrency)].reduce(add);
|
|
90
114
|
const subtractMany = (subtractions, defaultCurrency) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);
|
|
91
|
-
const stringAmountToDinero = (price, currency2) =>
|
|
92
|
-
|
|
93
|
-
parseFloatToDinero(parseFloat(price), currency2);
|
|
94
|
-
const roundDinero = (dinero2, roundingFn) => {
|
|
95
|
-
const roundedUnitPrice = toUnit(dinero2, {
|
|
96
|
-
digits: 0,
|
|
97
|
-
round: roundingFn
|
|
98
|
-
});
|
|
99
|
-
const snapshot = toSnapshot(dinero2);
|
|
100
|
-
return dinero2.create({
|
|
101
|
-
amount: roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,
|
|
102
|
-
currency: snapshot.currency
|
|
103
|
-
});
|
|
104
|
-
};
|
|
105
|
-
export { addMany, amount, centsToCurrencyUnit, currency, dineroToCurrencyUnit, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, parseFloatToDineroRaw, roundDinero, stringAmountToDinero, subtractMany, toSmallestSubunit };
|
|
115
|
+
const stringAmountToDinero = (price, currency2) => parseFloatToDinero(parseFloat(price), currency2);
|
|
116
|
+
export { addMany, amount, centsToMajorUnits, currency, getDinero, getDineroCurrency, money, multiplyByFullPercent, parseCurrencyCode, parseFloatToDinero, prettifyTotal, stringAmountToDinero, subtractMany, toSmallestSubunit };
|
|
106
117
|
//# sourceMappingURL=misc.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"misc.mjs","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n amount:\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create"],"mappings":";;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,C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,CAAA6B,QAAA;IACjE7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;"}
|
|
1
|
+
{"version":3,"file":"misc.mjs","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import * as currencies from \"@dinero.js/currencies\";\nimport type { Dinero, Currency as DineroCurrency } from \"dinero.js\";\nimport {\n add,\n dinero,\n down,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { isInt } from \"../validations\";\nimport {\n financialRound,\n prettifyPriceLookup,\n smallestSubunitLookup,\n} from \"./constants\";\n\nexport interface Money {\n amount: number;\n currency: Currency;\n}\n\n// #############################################################################\n// Private helpers\n// #############################################################################\nconst currencyLookup = new Set(\n Object.keys(Currency).map((el) => el.toString()),\n);\n\n/**\n * Creating a map of currencies for way faster lookup then doing a array.find()\n * @see https://stackoverflow.com/a/65604244/1378261\n */\nconst currenciesMap = new Map(\n Object.values(currencies).map((currency) => [currency.code, currency]),\n);\n\n/**\n * Private util to convert a float value into a int. Also applies financial rounding to the value if needed.\n * Inspired by https://v2.dinerojs.com/docs/faq/how-can-i-create-dinero-objects-from-floats\n * @private Just for using within this file, please consider using other methods to solve your issue\n * @example\n * floatToInt(69.10, 10, 2); // 6910\n * floatToInt(42, 10, 2); // 4200\n * floatToInt(0.22, 10, 6); // 220000\n */\nconst floatToInt = (\n floatAmount: number,\n base: number,\n exponent: number,\n): number => financialRound(floatAmount * Math.pow(base, exponent));\n\n// #############################################################################\n// Public functions\n// #############################################################################\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dinero<number>): Dinero<number> => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n const roundedUnitPrice = toUnit(total, { digits: 0, round: down });\n // Multiplying by 100 to get the cents\n return dinero({\n amount:\n roundedUnitPrice *\n Math.pow(totalJson.currency.base, totalJson.currency.exponent),\n currency: totalJson.currency,\n });\n};\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dinero<number>): Dinero<number> => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n const roundedUnitPrice = toUnit(total, {\n digits: roundToDigits,\n round: roundingMode,\n });\n return dinero({\n amount:\n roundedUnitPrice *\n Math.pow(totalJson.currency.base, totalJson.currency.exponent),\n currency: totalJson.currency,\n });\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (\n currency: Currency,\n): DineroCurrency<number> => {\n const dineroCurrency = currenciesMap.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency to local currency type\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Get major units amount for cents amount and currency\n *\n * Can look into the approach of dinero core toUnits if we need a more robust approach\n * https://github.com/dinerojs/dinero.js/blob/main/packages/core/src/api/toUnits.ts\n * Though, based on experimentation, it's a basic division in the end regardless\n */\nexport const centsToMajorUnits = (\n amount: number,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const price = dinero({ amount, currency: dineroCurrency });\n const divider = Math.pow(10, dineroCurrency.exponent);\n\n return toSnapshot(price).amount / divider;\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n isFloat(floatAmount, \"Amount\");\n\n const dineroCurrency = getDineroCurrency(currency);\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n */\nexport const getDinero = (\n amount: number,\n currency: Currency,\n): Dinero<number> => {\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n */\nexport const amount = (dinero: Dinero<number>): number => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dinero<number>,\n percentIncrease: number,\n): Dinero<number> => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n */\nexport const currency = (dinero: Dinero<number>): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n */\nexport const money = (dinero: Dinero<number>): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n */\nexport const addMany = (\n addends: Array<Dinero<number>>,\n defaultCurrency: Currency,\n) => [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dinero<number>>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n parseFloatToDinero(parseFloat(price), currency);\n"],"names":["currencyLookup","Set","Object","keys","Currency","map","el","toString","currenciesMap","Map","values","currencies","currency","code","floatToInt","floatAmount","base","exponent","financialRound","Math","pow","prettifyTotal","total","hasSubUnits","totalJson","toJSON","minValueInclusiveToRoundDownFrom","prettifyPriceLookup","get","toUnit","roundedUnitPrice","digits","round","down","dinero","amount","toSmallestSubunit","roundToDigits","roundingMode","smallestSubunitLookup","getDineroCurrency","dineroCurrency","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","has","centsToMajorUnits","price","divider","toSnapshot","parseFloatToDinero","isFloat","scaleOfGivenAmount","String","split","length","Error","rateInt","getDinero","isInt","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","parseFloat"],"mappings":";;;;;;;;;;AAiCA,MAAMA,iBAAiB,IAAIC,GAAA,CACzBC,MAAA,CAAOC,KAAKC,QAAQ,CAAA,CAAEC,IAAKC,EAAA,IAAOA,EAAG,CAAAC,QAAA,EAAU,CACjD,CAAA;AAMA,MAAMC,gBAAgB,IAAIC,GAAA,CACxBP,MAAA,CAAOQ,MAAO,CAAAC,UAAU,CAAE,CAAAN,GAAA,CAAKO,SAAAA,IAAa,CAACA,SAAAA,CAASC,IAAMD,EAAAA,SAAQ,CAAC,CACvE,CAAA;AAWA,MAAME,UAAA,GAAaA,CACjBC,WAAA,EACAC,IACA,EAAAC,QAAA,KACWC,cAAe,CAAAH,WAAA,GAAcI,IAAK,CAAAC,GAAA,CAAIJ,IAAM,EAAAC,QAAQ,CAAC,CAAA;AAUrD,MAAAI,aAAA,GAAiBC,KAA0C,IAAA;EAElE,IAAA,CAACC,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAE/B,MAAMC,mCAAmCC,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AAAA,EAAAA,OAAAA;IACAvB,QAAA,EAAU+B,iBAAkB/B,CAAAA,SAAAA,CAASC,IAAI;EAAA,CAC3C;AACF,CAAA;AAKO,MAAMwD,OAAU,GAAAA,CACrBC,OACA,EAAAC,eAAA,KACG,CAAC,GAAGD,OAAS,EAAAV,SAAA,CAAU,CAAG,EAAAW,eAAe,CAAC,CAAA,CAAEC,OAAOC,GAAG,CAAA;AAKpD,MAAMC,YAAe,GAAAA,CAC1BC,YACA,EAAAJ,eAAA,KACG,CAAC,GAAGI,YAAc,EAAAf,SAAA,CAAU,CAAG,EAAAW,eAAe,CAAC,CAAA,CAAEC,OAAOI,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAAC5B,KAAerC,EAAAA,SAAAA,KAClDwC,mBAAmB0B,UAAW,CAAA7B,KAAK,GAAGrC,SAAQ,CAAA;"}
|
package/lib/utils/money/tax.d.ts
CHANGED
|
@@ -1,39 +1,3 @@
|
|
|
1
1
|
import { type Dinero } from "dinero.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Function to calculate the tax amount for a given line item depending on the store's tax rate calculation strategy
|
|
6
|
-
*/
|
|
7
|
-
export declare const calculateLineItemTax: ({ itemSummary, taxRate, storeId, }: {
|
|
8
|
-
itemSummary: LineItemSummary;
|
|
9
|
-
taxRate: TaxRate;
|
|
10
|
-
storeId: StoreId;
|
|
11
|
-
}) => Dinero<number>;
|
|
12
|
-
export declare const removeTaxAmount: (baseAmountWithTaxObj: Dinero<Cents>, taxRate: TaxRate) => Dinero<number>;
|
|
13
|
-
/**
|
|
14
|
-
* Will return a percentage tax rate from a decimal tax rate (usually returned by DB)
|
|
15
|
-
*
|
|
16
|
-
* Use for math-related calculations ONLY! Use `formatDecimalTaxRate` for display purposes e.g. invoices.
|
|
17
|
-
*
|
|
18
|
-
* @example convertDecimalTaxRateToPercentage("0.01") // 1
|
|
19
|
-
* @example convertDecimalTaxRateToPercentage("0.1023") // 10.23
|
|
20
|
-
* @example convertDecimalTaxRateToPercentage("0.12345678") // 12.345678
|
|
21
|
-
*/
|
|
22
|
-
export declare const convertDecimalTaxRateToPercentage: (taxRate: string | number) => number;
|
|
23
|
-
export declare const decimalTaxRateToDinero: (taxRate: string | number) => Dino;
|
|
24
|
-
/**
|
|
25
|
-
* Will return a percentage string from a decimal tax rate (usually returned by DB).
|
|
26
|
-
*
|
|
27
|
-
* Use for display purposes e.g. invoices.
|
|
28
|
-
*
|
|
29
|
-
* @example formatDecimalTaxRate("0.01") // "1%"
|
|
30
|
-
* @example formatDecimalTaxRate("0.1023") // "10.23%"
|
|
31
|
-
* @example formatDecimalTaxRate("0.12345678") // "12.345678%"
|
|
32
|
-
*/
|
|
33
|
-
export declare const formatDecimalTaxRate: <TaxRateFloat extends string | number>(taxRate: TaxRateFloat) => `${number}%`;
|
|
34
|
-
export declare const stringTaxRateToFloat: (rate: string) => number;
|
|
35
|
-
/**
|
|
36
|
-
* Calculate total Tax(LV: "PVN") for country, which consists of multiple tax entries
|
|
37
|
-
* Returning fixed to ${TAX_RATE_DINERO_CURRENCY.exponent} 4 decimal places, to for example 0.2100 represent 21.00%
|
|
38
|
-
*/
|
|
39
|
-
export declare const calculateTotalTaxRate: (rates: number[]) => number;
|
|
2
|
+
export declare const allocateTaxAmount: (baseAmountObj: Dinero<number>, floatRate: number) => Dinero<number>;
|
|
3
|
+
export declare const removeTaxAmount: (baseAmountWithTaxObj: Dinero<number>, floatRate: number) => Dinero<number>;
|
package/lib/utils/money/tax.js
CHANGED
|
@@ -1,58 +1,22 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var dinero_js = require('dinero.js');
|
|
4
|
-
var errors = require('../errors.js');
|
|
5
|
-
var number = require('../number.js');
|
|
6
|
-
var constants = require('./constants.js');
|
|
7
|
-
var tax_private = require('./tax.private.js');
|
|
8
4
|
"use strict";
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
5
|
+
const allocateTaxAmount = (baseAmountObj, floatRate) => {
|
|
6
|
+
const rateScale = String(floatRate).split(".")[1]?.length;
|
|
7
|
+
if (rateScale === void 0) {
|
|
8
|
+
throw new Error(`rateScale is unsupported ${floatRate}`);
|
|
9
|
+
}
|
|
10
|
+
const rateInt = Math.round(floatRate * Math.pow(10, rateScale));
|
|
11
|
+
return dinero_js.allocate(baseAmountObj, [rateInt, Math.pow(10, rateScale) - rateInt])[0];
|
|
15
12
|
};
|
|
16
|
-
const removeTaxAmount = (baseAmountWithTaxObj,
|
|
13
|
+
const removeTaxAmount = (baseAmountWithTaxObj, floatRate) => {
|
|
17
14
|
const snapshot = dinero_js.toSnapshot(baseAmountWithTaxObj);
|
|
18
15
|
return dinero_js.dinero({
|
|
19
16
|
...snapshot,
|
|
20
|
-
amount: dinero_js.down(snapshot.amount / (1 +
|
|
17
|
+
amount: dinero_js.down(snapshot.amount / (1 + floatRate))
|
|
21
18
|
});
|
|
22
19
|
};
|
|
23
|
-
|
|
24
|
-
const dineroObj = decimalTaxRateToDinero(taxRate);
|
|
25
|
-
const t = dinero_js.multiply(dineroObj, 100);
|
|
26
|
-
return dinero_js.toUnit(t, {
|
|
27
|
-
digits: constants.TAX_RATE_DINERO_CURRENCY.exponent,
|
|
28
|
-
round: dinero_js.halfEven
|
|
29
|
-
});
|
|
30
|
-
};
|
|
31
|
-
const decimalTaxRateToDinero = taxRate => {
|
|
32
|
-
const parsedNumber = typeof taxRate === "number" ? taxRate : Number.parseFloat(taxRate);
|
|
33
|
-
number.isFloat(parsedNumber);
|
|
34
|
-
const parsedNumberInt = Number.parseInt((parsedNumber * Math.pow(constants.TAX_RATE_DINERO_CURRENCY.base, constants.TAX_RATE_DINERO_CURRENCY.exponent)).toFixed(0));
|
|
35
|
-
return dinero_js.dinero({
|
|
36
|
-
amount: parsedNumberInt,
|
|
37
|
-
currency: constants.TAX_RATE_DINERO_CURRENCY
|
|
38
|
-
});
|
|
39
|
-
};
|
|
40
|
-
const formatDecimalTaxRate = taxRate => {
|
|
41
|
-
return `${convertDecimalTaxRateToPercentage(taxRate)}%`;
|
|
42
|
-
};
|
|
43
|
-
const stringTaxRateToFloat = rate => number.toFixedRate(+rate, constants.TAX_RATE_DINERO_CURRENCY.exponent, true);
|
|
44
|
-
const calculateTotalTaxRate = rates => {
|
|
45
|
-
const rateSum = rates.reduce((sum, rate) => sum + rate, 0);
|
|
46
|
-
const result = number.toFixedRate(rateSum, constants.TAX_RATE_DINERO_CURRENCY.exponent, true);
|
|
47
|
-
errors.assert(result >= 0, "Tax rate must be positive");
|
|
48
|
-
errors.assert(result < 1, "Tax rate must be less than 1");
|
|
49
|
-
return result;
|
|
50
|
-
};
|
|
51
|
-
exports.calculateLineItemTax = calculateLineItemTax;
|
|
52
|
-
exports.calculateTotalTaxRate = calculateTotalTaxRate;
|
|
53
|
-
exports.convertDecimalTaxRateToPercentage = convertDecimalTaxRateToPercentage;
|
|
54
|
-
exports.decimalTaxRateToDinero = decimalTaxRateToDinero;
|
|
55
|
-
exports.formatDecimalTaxRate = formatDecimalTaxRate;
|
|
20
|
+
exports.allocateTaxAmount = allocateTaxAmount;
|
|
56
21
|
exports.removeTaxAmount = removeTaxAmount;
|
|
57
|
-
exports.stringTaxRateToFloat = stringTaxRateToFloat;
|
|
58
22
|
//# sourceMappingURL=tax.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tax.js","sources":["../../../src/utils/money/tax.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"tax.js","sources":["../../../src/utils/money/tax.ts"],"sourcesContent":["import { allocate, type Dinero, dinero, down, toSnapshot } from \"dinero.js\";\n\nexport const allocateTaxAmount = (\n baseAmountObj: Dinero<number>,\n floatRate: number,\n) => {\n // FIXME: currently the API returns rate as a floating number, but the dinero lib expects be a integer number with some\n // scale so for now we attempt calculate the scale from the float rate\n // @see https://v2.dinerojs.com/docs/api/mutations/allocate\n const rateScale = String(floatRate).split(\".\")[1]?.length;\n if (rateScale === undefined) {\n throw new Error(`rateScale is unsupported ${floatRate}`);\n }\n const rateInt = Math.round(floatRate * Math.pow(10, rateScale));\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return allocate(baseAmountObj, [\n rateInt,\n Math.pow(10, rateScale) - rateInt,\n ])[0]!;\n};\n\nexport const removeTaxAmount = (\n baseAmountWithTaxObj: Dinero<number>,\n floatRate: number,\n) => {\n const snapshot = toSnapshot(baseAmountWithTaxObj);\n return dinero({\n ...snapshot,\n amount: down(snapshot.amount / (1 + floatRate)),\n });\n};\n"],"names":["allocateTaxAmount","baseAmountObj","floatRate","rateScale","String","split","length","Error","rateInt","Math","round","pow","allocate","removeTaxAmount","baseAmountWithTaxObj","snapshot","toSnapshot","dinero","amount","down"],"mappings":";;;;AAEa,MAAAA,iBAAA,GAAoBA,CAC/BC,aAAA,EACAC,SACG,KAAA;EAIG,MAAAC,SAAA,GAAYC,OAAOF,SAAS,CAAA,CAAEG,MAAM,GAAG,CAAA,CAAE,CAAC,CAAG,EAAAC,MAAA;EACnD,IAAIH,cAAc,KAAW,CAAA,EAAA;IAC3B,MAAM,IAAII,KAAA,CAAkC,4BAAAL,SAAW,EAAA,CAAA;EACzD;EACM,MAAAM,OAAA,GAAUC,KAAKC,KAAM,CAAAR,SAAA,GAAYO,KAAKE,GAAI,CAAA,EAAA,EAAIR,SAAS,CAAC,CAAA;EAE9D,OAAOS,SAAAA,CAAAA,SAASX,aAAe,EAAA,CAC7BO,OAAA,EACAC,IAAK,CAAAE,GAAA,CAAI,EAAI,EAAAR,SAAS,CAAI,GAAAK,OAAA,CAC3B,EAAE,CAAC,CAAA;AACN,CAAA;AAEa,MAAAK,eAAA,GAAkBA,CAC7BC,oBAAA,EACAZ,SACG,KAAA;EACG,MAAAa,QAAA,GAAWC,qBAAWF,oBAAoB,CAAA;EAChD,OAAOG,gBAAO,CAAA;IACZ,GAAGF,QAAA;IACHG,MAAQ,EAAAC,SAAA,CAAAA,IAAA,CAAKJ,QAAS,CAAAG,MAAA,IAAU,IAAIhB,SAAU,CAAA;EAAA,CAC/C,CAAA;AACH,CAAA;;"}
|
package/lib/utils/money/tax.mjs
CHANGED
|
@@ -1,50 +1,19 @@
|
|
|
1
|
-
import { toSnapshot, dinero, down
|
|
2
|
-
import { assert } from '../errors.mjs';
|
|
3
|
-
import { isFloat, toFixedRate } from '../number.mjs';
|
|
4
|
-
import { storesWithPerItemTaxRate, TAX_RATE_DINERO_CURRENCY } from './constants.mjs';
|
|
5
|
-
import { calculatePerQtyLineItemTax, calculateWholeQtyLineItemTax } from './tax.private.mjs';
|
|
1
|
+
import { allocate, toSnapshot, dinero, down } from 'dinero.js';
|
|
6
2
|
"use strict";
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
3
|
+
const allocateTaxAmount = (baseAmountObj, floatRate) => {
|
|
4
|
+
const rateScale = String(floatRate).split(".")[1]?.length;
|
|
5
|
+
if (rateScale === void 0) {
|
|
6
|
+
throw new Error(`rateScale is unsupported ${floatRate}`);
|
|
7
|
+
}
|
|
8
|
+
const rateInt = Math.round(floatRate * Math.pow(10, rateScale));
|
|
9
|
+
return allocate(baseAmountObj, [rateInt, Math.pow(10, rateScale) - rateInt])[0];
|
|
13
10
|
};
|
|
14
|
-
const removeTaxAmount = (baseAmountWithTaxObj,
|
|
11
|
+
const removeTaxAmount = (baseAmountWithTaxObj, floatRate) => {
|
|
15
12
|
const snapshot = toSnapshot(baseAmountWithTaxObj);
|
|
16
13
|
return dinero({
|
|
17
14
|
...snapshot,
|
|
18
|
-
amount: down(snapshot.amount / (1 +
|
|
15
|
+
amount: down(snapshot.amount / (1 + floatRate))
|
|
19
16
|
});
|
|
20
17
|
};
|
|
21
|
-
|
|
22
|
-
const dineroObj = decimalTaxRateToDinero(taxRate);
|
|
23
|
-
const t = multiply(dineroObj, 100);
|
|
24
|
-
return toUnit(t, {
|
|
25
|
-
digits: TAX_RATE_DINERO_CURRENCY.exponent,
|
|
26
|
-
round: halfEven
|
|
27
|
-
});
|
|
28
|
-
};
|
|
29
|
-
const decimalTaxRateToDinero = taxRate => {
|
|
30
|
-
const parsedNumber = typeof taxRate === "number" ? taxRate : Number.parseFloat(taxRate);
|
|
31
|
-
isFloat(parsedNumber);
|
|
32
|
-
const parsedNumberInt = Number.parseInt((parsedNumber * Math.pow(TAX_RATE_DINERO_CURRENCY.base, TAX_RATE_DINERO_CURRENCY.exponent)).toFixed(0));
|
|
33
|
-
return dinero({
|
|
34
|
-
amount: parsedNumberInt,
|
|
35
|
-
currency: TAX_RATE_DINERO_CURRENCY
|
|
36
|
-
});
|
|
37
|
-
};
|
|
38
|
-
const formatDecimalTaxRate = taxRate => {
|
|
39
|
-
return `${convertDecimalTaxRateToPercentage(taxRate)}%`;
|
|
40
|
-
};
|
|
41
|
-
const stringTaxRateToFloat = rate => toFixedRate(+rate, TAX_RATE_DINERO_CURRENCY.exponent, true);
|
|
42
|
-
const calculateTotalTaxRate = rates => {
|
|
43
|
-
const rateSum = rates.reduce((sum, rate) => sum + rate, 0);
|
|
44
|
-
const result = toFixedRate(rateSum, TAX_RATE_DINERO_CURRENCY.exponent, true);
|
|
45
|
-
assert(result >= 0, "Tax rate must be positive");
|
|
46
|
-
assert(result < 1, "Tax rate must be less than 1");
|
|
47
|
-
return result;
|
|
48
|
-
};
|
|
49
|
-
export { calculateLineItemTax, calculateTotalTaxRate, convertDecimalTaxRateToPercentage, decimalTaxRateToDinero, formatDecimalTaxRate, removeTaxAmount, stringTaxRateToFloat };
|
|
18
|
+
export { allocateTaxAmount, removeTaxAmount };
|
|
50
19
|
//# sourceMappingURL=tax.mjs.map
|