@ubnt/store.core 9.16.0 → 9.17.0-alpha.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.
Files changed (330) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/lib/_virtual/_virtual_multi-entry.js +27 -12
  3. package/lib/_virtual/_virtual_multi-entry.js.map +1 -1
  4. package/lib/_virtual/_virtual_multi-entry.mjs +14 -10
  5. package/lib/_virtual/_virtual_multi-entry.mjs.map +1 -1
  6. package/lib/assets/attention.svg +5 -5
  7. package/lib/assets/attention2.svg +5 -5
  8. package/lib/assets/close2.svg +3 -2
  9. package/lib/assets/close3.svg +2 -3
  10. package/lib/assets/efg.png +0 -0
  11. package/lib/assets/icon-location-pin.svg +5 -0
  12. package/lib/assets/icons/menu/icon-location-pin.svg.js +27 -0
  13. package/lib/assets/icons/menu/icon-location-pin.svg.js.map +1 -0
  14. package/lib/assets/icons/menu/icon-location-pin.svg.mjs +3 -0
  15. package/lib/assets/icons/menu/icon-location-pin.svg.mjs.map +1 -0
  16. package/lib/assets/minus4.svg +8 -8
  17. package/lib/assets/minus5.svg +8 -8
  18. package/lib/assets/plus5.svg +9 -9
  19. package/lib/assets/plus6.svg +9 -9
  20. package/lib/assets/ucg-max.png +0 -0
  21. package/lib/components/CategoryTabs/CategoryTabs.types.d.ts +1 -1
  22. package/lib/components/CustomImage/CustomImage.js.map +1 -1
  23. package/lib/components/CustomImage/CustomImage.mjs.map +1 -1
  24. package/lib/components/FeaturesSection_deprecated/FeaturesSection.js +1 -1
  25. package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs +1 -1
  26. package/lib/components/FeaturesSection_deprecated/assets/close.svg.js +1 -1
  27. package/lib/components/FeaturesSection_deprecated/assets/close.svg.mjs +2 -2
  28. package/lib/components/Header/AccountMenu/megaphone.http.service.js +1 -1
  29. package/lib/components/Header/AccountMenu/megaphone.http.service.js.map +1 -1
  30. package/lib/components/Header/AccountMenu/megaphone.http.service.mjs +1 -1
  31. package/lib/components/Header/AccountMenu/megaphone.http.service.mjs.map +1 -1
  32. package/lib/components/Header/Header.types.d.ts +8 -4
  33. package/lib/components/Header/Header.types.js +2 -1
  34. package/lib/components/Header/Header.types.js.map +1 -1
  35. package/lib/components/Header/Header.types.mjs +2 -1
  36. package/lib/components/Header/Header.types.mjs.map +1 -1
  37. package/lib/components/Header/MenuItem/MenuItem.styles.d.ts +1 -1
  38. package/lib/components/Header/MenuItem/MenuItem.styles.js +1 -1
  39. package/lib/components/Header/MenuItem/MenuItem.styles.js.map +1 -1
  40. package/lib/components/Header/MenuItem/MenuItem.styles.mjs +1 -1
  41. package/lib/components/Header/MenuItem/MenuItem.styles.mjs.map +1 -1
  42. package/lib/components/Header/Navigation/ProMenu/ProMenu.d.ts +2 -0
  43. package/lib/components/Header/Navigation/ProMenu/ProMenu.js +109 -0
  44. package/lib/components/Header/Navigation/ProMenu/ProMenu.js.map +1 -0
  45. package/lib/components/Header/Navigation/ProMenu/ProMenu.mjs +87 -0
  46. package/lib/components/Header/Navigation/ProMenu/ProMenu.mjs.map +1 -0
  47. package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.d.ts +24 -0
  48. package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.js +154 -0
  49. package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.js.map +1 -0
  50. package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.mjs +138 -0
  51. package/lib/components/Header/Navigation/ProMenu/ProMenu.styles.mjs.map +1 -0
  52. package/lib/components/Header/Navigation/ProMenu/ProMenu.types.d.ts +13 -0
  53. package/lib/components/Header/Navigation/ProMenu/index.d.ts +1 -0
  54. package/lib/components/Header/Navigation/ProMenu/index.js +6 -0
  55. package/lib/components/{ResourceCalculatorV1/components → Header/Navigation/ProMenu}/index.js.map +1 -1
  56. package/lib/components/Header/Navigation/ProMenu/index.mjs +3 -0
  57. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.d.ts +1 -1
  58. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js +130 -63
  59. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js.map +1 -1
  60. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs +111 -64
  61. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs.map +1 -1
  62. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.d.ts +6 -0
  63. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js +11 -1
  64. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js.map +1 -1
  65. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs +10 -2
  66. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs.map +1 -1
  67. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.types.d.ts +5 -1
  68. package/lib/components/Header/ProHeader/ProHeader.d.ts +2 -4
  69. package/lib/components/Header/ProHeader/ProHeader.js +142 -36
  70. package/lib/components/Header/ProHeader/ProHeader.js.map +1 -1
  71. package/lib/components/Header/ProHeader/ProHeader.mjs +143 -39
  72. package/lib/components/Header/ProHeader/ProHeader.mjs.map +1 -1
  73. package/lib/components/Header/ProHeader/ProHeader.styles.d.ts +3 -1
  74. package/lib/components/Header/ProHeader/ProHeader.styles.js +18 -13
  75. package/lib/components/Header/ProHeader/ProHeader.styles.js.map +1 -1
  76. package/lib/components/Header/ProHeader/ProHeader.styles.mjs +17 -14
  77. package/lib/components/Header/ProHeader/ProHeader.styles.mjs.map +1 -1
  78. package/lib/components/Header/translations/en.json.js +4 -1
  79. package/lib/components/Header/translations/en.json.js.map +1 -1
  80. package/lib/components/Header/translations/en.json.mjs +4 -2
  81. package/lib/components/Header/translations/en.json.mjs.map +1 -1
  82. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.d.ts +1 -1
  83. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.js +3 -1
  84. package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.js.map +1 -0
  85. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.mjs +3 -1
  86. package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.mjs.map +1 -0
  87. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.styles.d.ts +1 -0
  88. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.styles.js +10 -7
  89. package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.js.map +1 -0
  90. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.styles.mjs +10 -7
  91. package/lib/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.mjs.map +1 -0
  92. package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/HorizontalOptionSelect.types.d.ts +1 -0
  93. package/lib/components/LandingPagePro/LandingPagePro.d.ts +3 -0
  94. package/lib/components/LandingPagePro/LandingPagePro.js +3 -3
  95. package/lib/components/LandingPagePro/LandingPagePro.js.map +1 -1
  96. package/lib/components/LandingPagePro/LandingPagePro.mjs +2 -2
  97. package/lib/components/LandingPagePro/LandingPagePro.mjs.map +1 -1
  98. package/lib/components/NormalisedImage/NormalisedImage.js.map +1 -1
  99. package/lib/components/NormalisedImage/NormalisedImage.mjs.map +1 -1
  100. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.js +313 -17
  101. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.js.map +1 -1
  102. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.mjs +311 -17
  103. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.constants.mjs.map +1 -1
  104. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.d.ts +3 -2
  105. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.js +2 -0
  106. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.js.map +1 -1
  107. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.mjs +2 -0
  108. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.types.mjs.map +1 -1
  109. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.js +120 -34
  110. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.js.map +1 -1
  111. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.mjs +120 -34
  112. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.mjs.map +1 -1
  113. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.d.ts +16 -2
  114. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.js +54 -12
  115. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.js.map +1 -1
  116. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.mjs +50 -11
  117. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/DeviceSelect.styles.mjs.map +1 -1
  118. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/assets/ArrowLeftPrimary.svg.js +5 -5
  119. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/DeviceSelect/assets/ArrowRightPrimary.svg.js +5 -5
  120. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.js +2 -2
  121. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.js.map +1 -1
  122. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.mjs +2 -2
  123. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.mjs.map +1 -1
  124. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.js +2 -0
  125. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.js.map +1 -1
  126. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.mjs +2 -0
  127. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputCard.styles.mjs.map +1 -1
  128. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/CounterSection.js +2 -2
  129. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/InputSections/CounterSection.mjs +2 -2
  130. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/attention.svg.js +1 -1
  131. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/attention.svg.mjs +2 -2
  132. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/minus.svg.js +1 -1
  133. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/minus.svg.mjs +2 -2
  134. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/plus.svg.js +1 -1
  135. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/InputCard/assets/plus.svg.mjs +2 -2
  136. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.js +1 -1
  137. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/ProgressBarChart.mjs +1 -1
  138. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/assets/attention.svg.js +1 -1
  139. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/components/ProgressBarChart/assets/attention.svg.mjs +2 -2
  140. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.js +1 -1
  141. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.js.map +1 -1
  142. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.mjs +1 -1
  143. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/useComputeResourceCalculator.mjs.map +1 -1
  144. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js +4 -4
  145. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.js.map +1 -1
  146. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs +4 -4
  147. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/PoeConsumerSelectModal/PoeConsumerSelectModal.mjs.map +1 -1
  148. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/minus.svg.js +1 -1
  149. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/minus.svg.mjs +2 -2
  150. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/plus.svg.js +1 -1
  151. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/PoeConsumerConfigurator/assets/plus.svg.mjs +2 -2
  152. package/lib/components/ResourceCalculatorV1/ResourceCalculator.js +1 -2
  153. package/lib/components/ResourceCalculatorV1/ResourceCalculator.js.map +1 -1
  154. package/lib/components/ResourceCalculatorV1/ResourceCalculator.mjs +1 -2
  155. package/lib/components/ResourceCalculatorV1/ResourceCalculator.mjs.map +1 -1
  156. package/lib/{assets/icons/menu/icon-globe.svg.js → components/ResourceCalculatorV1/assets/consoles/efg.png.js} +6 -6
  157. package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.js.map +1 -0
  158. package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.mjs +3 -0
  159. package/lib/components/ResourceCalculatorV1/assets/consoles/efg.png.mjs.map +1 -0
  160. package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.js +27 -0
  161. package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.js.map +1 -0
  162. package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.mjs +3 -0
  163. package/lib/components/ResourceCalculatorV1/assets/consoles/ucg-max.png.mjs.map +1 -0
  164. package/lib/components/ResourceCalculatorV1/translations/en.json.js +6 -4
  165. package/lib/components/ResourceCalculatorV1/translations/en.json.js.map +1 -1
  166. package/lib/components/ResourceCalculatorV1/translations/en.json.mjs +6 -4
  167. package/lib/components/ResourceCalculatorV1/translations/en.json.mjs.map +1 -1
  168. package/lib/components/ResourceCalculatorV1/translations/useResourceCalculatorTranslation.d.ts +2 -2
  169. package/lib/components/StyleableSvgImage/StyleableSvgImage.js.map +1 -1
  170. package/lib/components/StyleableSvgImage/StyleableSvgImage.mjs.map +1 -1
  171. package/lib/components/VideoPlayerNew/VideoPlayer.js +1 -1
  172. package/lib/components/VideoPlayerNew/VideoPlayer.mjs +1 -1
  173. package/lib/components/VideoPlayerNew/assets/close.svg.js +1 -1
  174. package/lib/components/VideoPlayerNew/assets/close.svg.mjs +2 -2
  175. package/lib/components/index.d.ts +1 -0
  176. package/lib/components/index.js +2 -0
  177. package/lib/components/index.js.map +1 -1
  178. package/lib/components/index.mjs +2 -0
  179. package/lib/components/index.mjs.map +1 -1
  180. package/lib/constants/icons/options/colors/black.svg.js +5 -5
  181. package/lib/constants/icons/options/colors/index.js +3 -3
  182. package/lib/constants/icons/options/styles/black.svg.js +5 -5
  183. package/lib/constants/icons/options/styles/index.js +3 -3
  184. package/lib/constants/optionIcons.js +6 -6
  185. package/lib/constants/optionIcons.mjs +4 -4
  186. package/lib/constants/proStoreCategories/mapping/index.d.ts +1 -0
  187. package/lib/constants/proStoreCategories/mapping/index.js +15 -10
  188. package/lib/constants/proStoreCategories/mapping/index.js.map +1 -1
  189. package/lib/constants/proStoreCategories/mapping/index.mjs +15 -10
  190. package/lib/constants/proStoreCategories/mapping/index.mjs.map +1 -1
  191. package/lib/constants/proStoreCategories/mapping/unifi.d.ts +2 -1
  192. package/lib/constants/proStoreCategories/mapping/unifi.js +1 -0
  193. package/lib/constants/proStoreCategories/mapping/unifi.js.map +1 -1
  194. package/lib/constants/proStoreCategories/mapping/unifi.mjs +1 -0
  195. package/lib/constants/proStoreCategories/mapping/unifi.mjs.map +1 -1
  196. package/lib/constants/proStoreCategories/translations/en.json.js +3 -0
  197. package/lib/constants/proStoreCategories/translations/en.json.js.map +1 -1
  198. package/lib/constants/proStoreCategories/translations/en.json.mjs +3 -1
  199. package/lib/constants/proStoreCategories/translations/en.json.mjs.map +1 -1
  200. package/lib/constants/proStoreCategories/translations/fr.json.js +1 -1
  201. package/lib/constants/proStoreCategories/translations/fr.json.mjs +1 -1
  202. package/lib/constants/proStoreCategories/translations/zh-Hans.json.js +1 -1
  203. package/lib/constants/proStoreCategories/translations/zh-Hans.json.mjs +1 -1
  204. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.js +1 -1
  205. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.mjs +1 -1
  206. package/lib/contexts/MenuContext/context.js +1 -1
  207. package/lib/contexts/MenuContext/context.js.map +1 -1
  208. package/lib/contexts/MenuContext/context.mjs +1 -1
  209. package/lib/contexts/MenuContext/context.mjs.map +1 -1
  210. package/lib/helpers/index.d.ts +1 -0
  211. package/lib/helpers/index.js +11 -0
  212. package/lib/helpers/index.js.map +1 -1
  213. package/lib/helpers/index.mjs +1 -0
  214. package/lib/helpers/index.mjs.map +1 -1
  215. package/lib/helpers/product.d.ts +87 -0
  216. package/lib/helpers/product.js +346 -0
  217. package/lib/helpers/product.js.map +1 -0
  218. package/lib/helpers/product.mjs +335 -0
  219. package/lib/helpers/product.mjs.map +1 -0
  220. package/lib/helpers/ux.d.ts +1 -1
  221. package/lib/helpers/ux.js.map +1 -1
  222. package/lib/helpers/ux.mjs.map +1 -1
  223. package/lib/types/index.d.ts +1 -0
  224. package/lib/types/index.js +2 -0
  225. package/lib/types/index.js.map +1 -1
  226. package/lib/types/index.mjs +1 -0
  227. package/lib/types/index.mjs.map +1 -1
  228. package/lib/types/product.d.ts +87 -0
  229. package/lib/types/product.js +14 -0
  230. package/lib/types/product.js.map +1 -0
  231. package/lib/types/product.mjs +13 -0
  232. package/lib/types/product.mjs.map +1 -0
  233. package/lib/utils/array.d.ts +4 -0
  234. package/lib/utils/array.js +10 -0
  235. package/lib/utils/array.js.map +1 -1
  236. package/lib/utils/array.mjs +10 -1
  237. package/lib/utils/array.mjs.map +1 -1
  238. package/lib/utils/money/allocators/fixedAmount.d.ts +26 -0
  239. package/lib/utils/money/allocators/fixedAmount.js +55 -0
  240. package/lib/utils/money/allocators/fixedAmount.js.map +1 -0
  241. package/lib/utils/money/allocators/fixedAmount.mjs +53 -0
  242. package/lib/utils/money/allocators/fixedAmount.mjs.map +1 -0
  243. package/lib/utils/money/allocators/index.d.ts +2 -0
  244. package/lib/utils/money/allocators/index.js +8 -0
  245. package/lib/utils/money/allocators/index.js.map +1 -0
  246. package/lib/utils/money/allocators/index.mjs +4 -0
  247. package/lib/utils/money/allocators/index.mjs.map +1 -0
  248. package/lib/utils/money/allocators/productAmount.d.ts +13 -0
  249. package/lib/utils/money/allocators/productAmount.js +110 -0
  250. package/lib/utils/money/allocators/productAmount.js.map +1 -0
  251. package/lib/utils/money/allocators/productAmount.mjs +108 -0
  252. package/lib/utils/money/allocators/productAmount.mjs.map +1 -0
  253. package/lib/utils/money/constants.d.ts +56 -25
  254. package/lib/utils/money/constants.js +72 -7
  255. package/lib/utils/money/constants.js.map +1 -1
  256. package/lib/utils/money/constants.mjs +70 -7
  257. package/lib/utils/money/constants.mjs.map +1 -1
  258. package/lib/utils/money/exchangeRate.d.ts +31 -0
  259. package/lib/utils/money/exchangeRate.js +27 -0
  260. package/lib/utils/money/exchangeRate.js.map +1 -0
  261. package/lib/utils/money/exchangeRate.mjs +23 -0
  262. package/lib/utils/money/exchangeRate.mjs.map +1 -0
  263. package/lib/utils/money/format.d.ts +10 -5
  264. package/lib/utils/money/format.js +22 -14
  265. package/lib/utils/money/format.js.map +1 -1
  266. package/lib/utils/money/format.mjs +23 -16
  267. package/lib/utils/money/format.mjs.map +1 -1
  268. package/lib/utils/money/index.d.ts +4 -1
  269. package/lib/utils/money/index.js +26 -8
  270. package/lib/utils/money/index.js.map +1 -1
  271. package/lib/utils/money/index.mjs +8 -4
  272. package/lib/utils/money/index.mjs.map +1 -1
  273. package/lib/utils/money/misc.d.ts +68 -28
  274. package/lib/utils/money/misc.js +35 -64
  275. package/lib/utils/money/misc.js.map +1 -1
  276. package/lib/utils/money/misc.mjs +32 -43
  277. package/lib/utils/money/misc.mjs.map +1 -1
  278. package/lib/utils/money/misc.private.d.ts +23 -0
  279. package/lib/utils/money/misc.private.js +46 -0
  280. package/lib/utils/money/misc.private.js.map +1 -0
  281. package/lib/utils/money/misc.private.mjs +21 -0
  282. package/lib/utils/money/misc.private.mjs.map +1 -0
  283. package/lib/utils/money/shipping.d.ts +5 -0
  284. package/lib/utils/money/shipping.js +8 -0
  285. package/lib/utils/money/shipping.js.map +1 -0
  286. package/lib/utils/money/shipping.mjs +6 -0
  287. package/lib/utils/money/shipping.mjs.map +1 -0
  288. package/lib/utils/money/tax.d.ts +38 -2
  289. package/lib/utils/money/tax.js +46 -10
  290. package/lib/utils/money/tax.js.map +1 -1
  291. package/lib/utils/money/tax.mjs +42 -11
  292. package/lib/utils/money/tax.mjs.map +1 -1
  293. package/lib/utils/money/tax.private.d.ts +17 -0
  294. package/lib/utils/money/tax.private.js +65 -0
  295. package/lib/utils/money/tax.private.js.map +1 -0
  296. package/lib/utils/money/tax.private.mjs +60 -0
  297. package/lib/utils/money/tax.private.mjs.map +1 -0
  298. package/lib/utils/money/types.d.ts +78 -3
  299. package/lib/utils/number.d.ts +1 -1
  300. package/lib/utils/number.js +1 -1
  301. package/lib/utils/number.js.map +1 -1
  302. package/lib/utils/number.mjs +1 -1
  303. package/lib/utils/number.mjs.map +1 -1
  304. package/lib/utils/productSort.d.ts +41 -0
  305. package/lib/utils/productSort.js +66 -0
  306. package/lib/utils/productSort.js.map +1 -0
  307. package/lib/utils/productSort.mjs +59 -0
  308. package/lib/utils/productSort.mjs.map +1 -0
  309. package/package.json +1 -1
  310. package/lib/assets/icons/menu/icon-globe.svg.js.map +0 -1
  311. package/lib/assets/icons/menu/icon-globe.svg.mjs +0 -3
  312. package/lib/assets/icons/menu/icon-globe.svg.mjs.map +0 -1
  313. package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.js.map +0 -1
  314. package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.mjs.map +0 -1
  315. package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.js.map +0 -1
  316. package/lib/components/ResourceCalculatorV1/components/HorizontalOptionSelect/HorizontalOptionSelect.styles.mjs.map +0 -1
  317. package/lib/components/ResourceCalculatorV1/components/index.d.ts +0 -1
  318. package/lib/components/ResourceCalculatorV1/components/index.js +0 -5
  319. package/lib/components/ResourceCalculatorV1/components/index.mjs +0 -3
  320. package/lib/utils/validations.d.ts +0 -15
  321. package/lib/utils/validations.js +0 -23
  322. package/lib/utils/validations.js.map +0 -1
  323. package/lib/utils/validations.mjs +0 -21
  324. package/lib/utils/validations.mjs.map +0 -1
  325. /package/lib/components/{ResourceCalculatorV1/components → Header/Navigation/ProMenu}/index.mjs.map +0 -0
  326. /package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/index.d.ts +0 -0
  327. /package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/index.js +0 -0
  328. /package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/index.js.map +0 -0
  329. /package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/index.mjs +0 -0
  330. /package/lib/components/{ResourceCalculatorV1/components/HorizontalOptionSelect → HorizontalOptionSelect}/index.mjs.map +0 -0
@@ -1,19 +1,50 @@
1
- import { allocate, toSnapshot, dinero, down } from 'dinero.js';
1
+ import { toSnapshot, dinero, down, multiply, toUnit, halfEven } from 'dinero.js';
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';
2
6
  "use strict";
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];
7
+ const calculateLineItemTax = ({
8
+ itemSummary,
9
+ taxRate,
10
+ storeId
11
+ }) => {
12
+ return storesWithPerItemTaxRate.has(storeId) ? calculatePerQtyLineItemTax(itemSummary, taxRate) : calculateWholeQtyLineItemTax(itemSummary, taxRate);
10
13
  };
11
- const removeTaxAmount = (baseAmountWithTaxObj, floatRate) => {
14
+ const removeTaxAmount = (baseAmountWithTaxObj, taxRate) => {
12
15
  const snapshot = toSnapshot(baseAmountWithTaxObj);
13
16
  return dinero({
14
17
  ...snapshot,
15
- amount: down(snapshot.amount / (1 + floatRate))
18
+ amount: down(snapshot.amount / (1 + taxRate))
16
19
  });
17
20
  };
18
- export { allocateTaxAmount, removeTaxAmount };
21
+ const convertDecimalTaxRateToPercentage = taxRate => {
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 };
19
50
  //# sourceMappingURL=tax.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tax.mjs","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,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,WAAWF,oBAAoB,CAAA;EAChD,OAAOG,MAAO,CAAA;IACZ,GAAGF,QAAA;IACHG,MAAQ,EAAAC,IAAA,CAAKJ,QAAS,CAAAG,MAAA,IAAU,IAAIhB,SAAU,CAAA;EAAA,CAC/C,CAAA;AACH,CAAA;"}
1
+ {"version":3,"file":"tax.mjs","sources":["../../../src/utils/money/tax.ts"],"sourcesContent":["import {\n type Dinero,\n dinero,\n // FIXME: move usage to rounding\n down,\n // FIXME: move usage to rounding\n halfEven,\n multiply,\n toSnapshot,\n toUnit,\n} from \"dinero.js\";\n\nimport type { StoreId } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, toFixedRate } from \"../number\";\nimport {\n storesWithPerItemTaxRate,\n TAX_RATE_DINERO_CURRENCY,\n} from \"./constants\";\nimport {\n calculatePerQtyLineItemTax,\n calculateWholeQtyLineItemTax,\n} from \"./tax.private\";\nimport type { Cents, Dino, LineItemSummary, TaxRate } from \"./types\";\n\n/**\n * Function to calculate the tax amount for a given line item depending on the store's tax rate calculation strategy\n */\nexport const calculateLineItemTax = ({\n itemSummary,\n taxRate,\n storeId,\n}: {\n itemSummary: LineItemSummary;\n taxRate: TaxRate;\n storeId: StoreId;\n}) => {\n return storesWithPerItemTaxRate.has(storeId)\n ? calculatePerQtyLineItemTax(itemSummary, taxRate)\n : calculateWholeQtyLineItemTax(itemSummary, taxRate);\n};\n\nexport const removeTaxAmount = (\n baseAmountWithTaxObj: Dinero<Cents>,\n taxRate: TaxRate,\n) => {\n const snapshot = toSnapshot(baseAmountWithTaxObj);\n return dinero({\n ...snapshot,\n amount: down(snapshot.amount / (1 + taxRate)),\n });\n};\n\n/**\n * Will return a percentage tax rate from a decimal tax rate (usually returned by DB)\n *\n * Use for math-related calculations ONLY! Use `formatDecimalTaxRate` for display purposes e.g. invoices.\n *\n * @example convertDecimalTaxRateToPercentage(\"0.01\") // 1\n * @example convertDecimalTaxRateToPercentage(\"0.1023\") // 10.23\n * @example convertDecimalTaxRateToPercentage(\"0.12345678\") // 12.345678\n */\nexport const convertDecimalTaxRateToPercentage = (\n taxRate: string | number,\n): number => {\n const dineroObj = decimalTaxRateToDinero(taxRate);\n const t = multiply(dineroObj, 100);\n return toUnit(t, {\n digits: TAX_RATE_DINERO_CURRENCY.exponent,\n round: halfEven,\n });\n};\n\nexport const decimalTaxRateToDinero = (taxRate: string | number): Dino => {\n const parsedNumber =\n typeof taxRate === \"number\" ? taxRate : Number.parseFloat(taxRate);\n isFloat(parsedNumber);\n\n const parsedNumberInt = Number.parseInt(\n (\n parsedNumber *\n Math.pow(TAX_RATE_DINERO_CURRENCY.base, TAX_RATE_DINERO_CURRENCY.exponent)\n ).toFixed(0),\n );\n return dinero({\n amount: parsedNumberInt,\n currency: TAX_RATE_DINERO_CURRENCY,\n });\n};\n\n/**\n * Will return a percentage string from a decimal tax rate (usually returned by DB).\n *\n * Use for display purposes e.g. invoices.\n *\n * @example formatDecimalTaxRate(\"0.01\") // \"1%\"\n * @example formatDecimalTaxRate(\"0.1023\") // \"10.23%\"\n * @example formatDecimalTaxRate(\"0.12345678\") // \"12.345678%\"\n */\nexport const formatDecimalTaxRate = <TaxRateFloat extends string | number>(\n taxRate: TaxRateFloat,\n): `${number}%` => {\n return `${convertDecimalTaxRateToPercentage(taxRate)}%`;\n};\n\nexport const stringTaxRateToFloat = (rate: string): number =>\n toFixedRate(+rate, TAX_RATE_DINERO_CURRENCY.exponent, true);\n\n/**\n * Calculate total Tax(LV: \"PVN\") for country, which consists of multiple tax entries\n * Returning fixed to ${TAX_RATE_DINERO_CURRENCY.exponent} 4 decimal places, to for example 0.2100 represent 21.00%\n */\nexport const calculateTotalTaxRate = (rates: number[]): number => {\n const rateSum = rates.reduce((sum, rate) => sum + rate, 0);\n const result = toFixedRate(rateSum, TAX_RATE_DINERO_CURRENCY.exponent, true);\n assert(result >= 0, \"Tax rate must be positive\");\n assert(result < 1, \"Tax rate must be less than 1\");\n return result;\n};\n"],"names":["calculateLineItemTax","itemSummary","taxRate","storeId","storesWithPerItemTaxRate","has","calculatePerQtyLineItemTax","calculateWholeQtyLineItemTax","removeTaxAmount","baseAmountWithTaxObj","snapshot","toSnapshot","dinero","amount","down","convertDecimalTaxRateToPercentage","dineroObj","decimalTaxRateToDinero","t","multiply","toUnit","digits","TAX_RATE_DINERO_CURRENCY","exponent","round","halfEven","parsedNumber","Number","parseFloat","isFloat","parsedNumberInt","parseInt","Math","pow","base","toFixed","currency","formatDecimalTaxRate","stringTaxRateToFloat","rate","toFixedRate","calculateTotalTaxRate","rates","rateSum","reduce","sum","result","assert"],"mappings":";;;;;;AA4BO,MAAMA,uBAAuBA,CAAC;EACnCC,WAAA;EACAC,OAAA;EACAC;AACF,CAIM,KAAA;EACG,OAAAC,wBAAA,CAAyBC,GAAI,CAAAF,OAAO,CACvC,GAAAG,0BAAA,CAA2BL,aAAaC,OAAO,CAAA,GAC/CK,4BAA6B,CAAAN,WAAA,EAAaC,OAAO,CAAA;AACvD,CAAA;AAEa,MAAAM,eAAA,GAAkBA,CAC7BC,oBAAA,EACAP,OACG,KAAA;EACG,MAAAQ,QAAA,GAAWC,WAAWF,oBAAoB,CAAA;EAChD,OAAOG,MAAO,CAAA;IACZ,GAAGF,QAAA;IACHG,MAAQ,EAAAC,IAAA,CAAKJ,QAAS,CAAAG,MAAA,IAAU,IAAIX,OAAQ,CAAA;EAAA,CAC7C,CAAA;AACH,CAAA;AAWa,MAAAa,iCAAA,GACXb,OACW,IAAA;EACL,MAAAc,SAAA,GAAYC,uBAAuBf,OAAO,CAAA;EAC1C,MAAAgB,CAAA,GAAIC,QAAS,CAAAH,SAAA,EAAW,GAAG,CAAA;EACjC,OAAOI,OAAOF,CAAG,EAAA;IACfG,QAAQC,wBAAyB,CAAAC,QAAA;IACjCC,KAAO,EAAAC;EAAA,CACR,CAAA;AACH,CAAA;AAEa,MAAAR,sBAAA,GAA0Bf,OAAmC,IAAA;EACxE,MAAMwB,eACJ,OAAOxB,OAAA,KAAY,WAAWA,OAAU,GAAAyB,MAAA,CAAOC,WAAW1B,OAAO,CAAA;EACnE2B,OAAA,CAAQH,YAAY,CAAA;EAEpB,MAAMI,kBAAkBH,MAAO,CAAAI,QAAA,CAE3B,CAAAL,YAAA,GACAM,KAAKC,GAAI,CAAAX,wBAAA,CAAyBY,MAAMZ,wBAAyB,CAAAC,QAAQ,CACzE,EAAAY,OAAA,CAAQ,CAAC,CAAA,CACb;EACA,OAAOvB,MAAO,CAAA;IACZC,MAAQ,EAAAiB,eAAA;IACRM,QAAU,EAAAd;EAAA,CACX,CAAA;AACH,CAAA;AAWa,MAAAe,oBAAA,GACXnC,OACiB,IAAA;EACV,OAAA,GAAGa,iCAAkC,CAAAb,OAAO,CAAC,GAAA;AACtD,CAAA;AAEa,MAAAoC,oBAAA,GAAwBC,IACnC,IAAAC,WAAA,CAAY,CAACD,IAAM,EAAAjB,wBAAA,CAAyBC,UAAU,IAAI,CAAA;AAM/C,MAAAkB,qBAAA,GAAyBC,KAA4B,IAAA;EAC1D,MAAAC,OAAA,GAAUD,MAAME,MAAO,CAAA,CAACC,KAAKN,IAAS,KAAAM,GAAA,GAAMN,MAAM,CAAC,CAAA;EACzD,MAAMO,MAAS,GAAAN,WAAA,CAAYG,OAAS,EAAArB,wBAAA,CAAyBC,UAAU,IAAI,CAAA;EACpEwB,MAAA,CAAAD,MAAA,IAAU,GAAG,2BAA2B,CAAA;EACxCC,MAAA,CAAAD,MAAA,GAAS,GAAG,8BAA8B,CAAA;EAC1C,OAAAA,MAAA;AACT,CAAA;"}
@@ -0,0 +1,17 @@
1
+ import type { Dinero } from "dinero.js";
2
+ import type { Cents, LineItemSummary, SingleLineItemSummary, TaxRate } from "./types";
3
+ /**
4
+ * Private helper to convert a floating number to a dinero friendly allocation integer pair
5
+ * @see https://v2.dinerojs.com/docs/api/mutations/allocate
6
+ * @example
7
+ * taxRateToDineroAllocation(0.1) // [1, 9]
8
+ * taxRateToDineroAllocation(0.5) // [5, 5]
9
+ */
10
+ export declare const taxRateToDineroAllocation: (taxRate: TaxRate) => [number, number];
11
+ /**
12
+ * Reverse engineer the taxable amount from "whole item" taxable amount into "per item" taxable amount for custom tax
13
+ * rate calculations
14
+ */
15
+ export declare const allocatePerItemTaxableAmount: (itemSummary: LineItemSummary) => SingleLineItemSummary[];
16
+ export declare const calculateWholeQtyLineItemTax: (itemSummary: LineItemSummary, taxRate: TaxRate) => Dinero<Cents>;
17
+ export declare const calculatePerQtyLineItemTax: (itemSummary: LineItemSummary, taxRate: TaxRate) => Dinero<Cents>;
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ var dinero_js = require('dinero.js');
4
+ var errors = require('../errors.js');
5
+ var fixedAmount = require('./allocators/fixedAmount.js');
6
+ var misc = require('./misc.js');
7
+ "use strict";
8
+ const taxRateToDineroAllocation = taxRate => {
9
+ if (taxRate <= 0 || taxRate >= 1) {
10
+ throw new RangeError("Unsupported rate, expected in range of 0>rate<1");
11
+ }
12
+ const rateScale = String(taxRate).split(".")[1]?.length;
13
+ errors.assert(rateScale !== void 0, "rateScale is undefined");
14
+ const rateInt = Math.round(taxRate * Math.pow(10, rateScale));
15
+ return [rateInt, Math.pow(10, rateScale) - rateInt];
16
+ };
17
+ const allocatePerItemTaxableAmount = itemSummary => {
18
+ if (itemSummary.quantity === 1) {
19
+ return [itemSummary];
20
+ }
21
+ const preDiscountAmount = dinero_js.add(misc.getDinero(itemSummary.taxableAmount, itemSummary.currency), misc.getDinero(itemSummary.discountAmount, itemSummary.currency));
22
+ const allocator = new fixedAmount.FixedAmountAllocator({
23
+ initialAllocateAmount: itemSummary.discountAmount,
24
+ initialTotalAmount: misc.amount(preDiscountAmount),
25
+ currency: itemSummary.currency
26
+ });
27
+ return Array.from({
28
+ length: itemSummary.quantity
29
+ }, () => {
30
+ const discountAllocatedAmount = allocator.allocate(itemSummary.itemPrice, itemSummary.currency);
31
+ const taxableAmount = dinero_js.subtract(misc.getDinero(itemSummary.itemPrice, itemSummary.currency), discountAllocatedAmount);
32
+ return {
33
+ itemPrice: itemSummary.itemPrice,
34
+ taxableAmount: misc.amount(taxableAmount),
35
+ discountAmount: misc.amount(discountAllocatedAmount),
36
+ currency: itemSummary.currency,
37
+ quantity: 1
38
+ };
39
+ });
40
+ };
41
+ const calculateWholeQtyLineItemTax = (itemSummary, taxRate) => {
42
+ if (taxRate === 0) {
43
+ return misc.getDinero(0, itemSummary.currency);
44
+ }
45
+ const [taxAmount] = dinero_js.allocate(misc.getDinero(itemSummary.taxableAmount, itemSummary.currency), taxRateToDineroAllocation(taxRate));
46
+ errors.assert(taxAmount !== void 0, "taxAmount is undefined");
47
+ return taxAmount;
48
+ };
49
+ const calculatePerQtyLineItemTax = (itemSummary, taxRate) => {
50
+ if (taxRate === 0) {
51
+ return misc.getDinero(0, itemSummary.currency);
52
+ }
53
+ const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);
54
+ let totalTaxAmount = misc.getDinero(0, itemSummary.currency);
55
+ singleItemSummaries.forEach(itemSummary2 => {
56
+ const taxAmount = calculateWholeQtyLineItemTax(itemSummary2, taxRate);
57
+ totalTaxAmount = dinero_js.add(totalTaxAmount, taxAmount);
58
+ });
59
+ return totalTaxAmount;
60
+ };
61
+ exports.allocatePerItemTaxableAmount = allocatePerItemTaxableAmount;
62
+ exports.calculatePerQtyLineItemTax = calculatePerQtyLineItemTax;
63
+ exports.calculateWholeQtyLineItemTax = calculateWholeQtyLineItemTax;
64
+ exports.taxRateToDineroAllocation = taxRateToDineroAllocation;
65
+ //# sourceMappingURL=tax.private.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tax.private.js","sources":["../../../src/utils/money/tax.private.ts"],"sourcesContent":["// #############################################################################\n// Internal helper functions not for consumption outside of store.core!\n// Wrote as separate files so that they can be easily unit tested without exposing them\n// #############################################################################\nimport type { Dinero } from \"dinero.js\";\nimport { add, allocate, subtract } from \"dinero.js\";\n\nimport { assert } from \"../errors\";\nimport { FixedAmountAllocator } from \"./allocators/fixedAmount\";\nimport { amount, getDinero } from \"./misc\";\nimport type {\n Cents,\n LineItemSummary,\n SingleLineItemSummary,\n TaxRate,\n} from \"./types\";\n\n/**\n * Private helper to convert a floating number to a dinero friendly allocation integer pair\n * @see https://v2.dinerojs.com/docs/api/mutations/allocate\n * @example\n * taxRateToDineroAllocation(0.1) // [1, 9]\n * taxRateToDineroAllocation(0.5) // [5, 5]\n */\nexport const taxRateToDineroAllocation = (\n taxRate: TaxRate,\n): [number, number] => {\n if (taxRate <= 0 || taxRate >= 1) {\n throw new RangeError(\"Unsupported rate, expected in range of 0>rate<1\");\n }\n\n // Get the scale of the rate\n const rateScale = String(taxRate).split(\".\")[1]?.length;\n assert(rateScale !== undefined, \"rateScale is undefined\");\n\n // Convert to integers\n const rateInt = Math.round(taxRate * Math.pow(10, rateScale));\n return [rateInt, Math.pow(10, rateScale) - rateInt];\n};\n\n/**\n * Reverse engineer the taxable amount from \"whole item\" taxable amount into \"per item\" taxable amount for custom tax\n * rate calculations\n */\nexport const allocatePerItemTaxableAmount = (\n itemSummary: LineItemSummary,\n): SingleLineItemSummary[] => {\n /**\n * If the item quantity is 1, we can just return the item summary as is\n */\n if (itemSummary.quantity === 1) {\n return [itemSummary as SingleLineItemSummary];\n }\n\n // Reverse engineer price before discount\n const preDiscountAmount = add(\n getDinero(itemSummary.taxableAmount, itemSummary.currency),\n getDinero(itemSummary.discountAmount, itemSummary.currency),\n );\n\n const allocator = new FixedAmountAllocator({\n initialAllocateAmount: itemSummary.discountAmount,\n initialTotalAmount: amount(preDiscountAmount),\n currency: itemSummary.currency,\n });\n\n // Iterate over the amount of qty to reverse engineer the discount price\n return Array.from({ length: itemSummary.quantity }, () => {\n const discountAllocatedAmount = allocator.allocate(\n itemSummary.itemPrice,\n itemSummary.currency,\n );\n\n const taxableAmount = subtract(\n getDinero(itemSummary.itemPrice, itemSummary.currency),\n discountAllocatedAmount,\n );\n\n return {\n itemPrice: itemSummary.itemPrice,\n taxableAmount: amount(taxableAmount),\n discountAmount: amount(discountAllocatedAmount),\n currency: itemSummary.currency,\n quantity: 1,\n } as SingleLineItemSummary;\n });\n};\n\nexport const calculateWholeQtyLineItemTax = (\n itemSummary: LineItemSummary,\n taxRate: TaxRate,\n): Dinero<Cents> => {\n // Nothing to calculate\n if (taxRate === 0) {\n return getDinero(0, itemSummary.currency);\n }\n\n /**\n * FIXME: look into approach with multiply and different scale for control over rounding, currently we just inherit\n * what dinero gives us which cause unexpected rounding issue\n */\n const [taxAmount] = allocate(\n getDinero(itemSummary.taxableAmount, itemSummary.currency),\n taxRateToDineroAllocation(taxRate),\n );\n\n assert(taxAmount !== undefined, \"taxAmount is undefined\");\n return taxAmount;\n};\n\nexport const calculatePerQtyLineItemTax = (\n itemSummary: LineItemSummary,\n taxRate: TaxRate,\n): Dinero<Cents> => {\n // Nothing to calculate\n if (taxRate === 0) {\n return getDinero(0, itemSummary.currency);\n }\n\n // Split the item summary into per individual item qty summaries\n const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);\n\n // Calculate individual item qty tax and sum them up\n let totalTaxAmount = getDinero(0, itemSummary.currency);\n\n singleItemSummaries.forEach((itemSummary) => {\n // Probably a bit confusing at first, but calling the whole qty tax calculation function here as we can safely use\n // it as item summary is always a single item summary here\n const taxAmount = calculateWholeQtyLineItemTax(itemSummary, taxRate);\n totalTaxAmount = add(totalTaxAmount, taxAmount);\n });\n\n return totalTaxAmount;\n};\n"],"names":["taxRateToDineroAllocation","taxRate","RangeError","rateScale","String","split","length","assert","rateInt","Math","round","pow","allocatePerItemTaxableAmount","itemSummary","quantity","preDiscountAmount","add","getDinero","taxableAmount","currency","discountAmount","allocator","FixedAmountAllocator","initialAllocateAmount","initialTotalAmount","amount","Array","from","discountAllocatedAmount","allocate","itemPrice","subtract","calculateWholeQtyLineItemTax","taxAmount","calculatePerQtyLineItemTax","singleItemSummaries","totalTaxAmount","forEach"],"mappings":";;;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MAAAoB,SAAA,GAAYD,4BAA6BnB,CAAAA,YAAAA,EAAaZ,OAAO,CAAA;IAClDmC,cAAA,GAAApB,SAAA,CAAAA,GAAA,CAAIoB,gBAAgBH,SAAS,CAAA;EAAA,CAC/C,CAAA;EAEM,OAAAG,cAAA;AACT,CAAA;;;;"}
@@ -0,0 +1,60 @@
1
+ import { add, subtract, allocate } from 'dinero.js';
2
+ import { assert } from '../errors.mjs';
3
+ import { FixedAmountAllocator } from './allocators/fixedAmount.mjs';
4
+ import { getDinero, amount } from './misc.mjs';
5
+ "use strict";
6
+ const taxRateToDineroAllocation = taxRate => {
7
+ if (taxRate <= 0 || taxRate >= 1) {
8
+ throw new RangeError("Unsupported rate, expected in range of 0>rate<1");
9
+ }
10
+ const rateScale = String(taxRate).split(".")[1]?.length;
11
+ assert(rateScale !== void 0, "rateScale is undefined");
12
+ const rateInt = Math.round(taxRate * Math.pow(10, rateScale));
13
+ return [rateInt, Math.pow(10, rateScale) - rateInt];
14
+ };
15
+ const allocatePerItemTaxableAmount = itemSummary => {
16
+ if (itemSummary.quantity === 1) {
17
+ return [itemSummary];
18
+ }
19
+ const preDiscountAmount = add(getDinero(itemSummary.taxableAmount, itemSummary.currency), getDinero(itemSummary.discountAmount, itemSummary.currency));
20
+ const allocator = new FixedAmountAllocator({
21
+ initialAllocateAmount: itemSummary.discountAmount,
22
+ initialTotalAmount: amount(preDiscountAmount),
23
+ currency: itemSummary.currency
24
+ });
25
+ return Array.from({
26
+ length: itemSummary.quantity
27
+ }, () => {
28
+ const discountAllocatedAmount = allocator.allocate(itemSummary.itemPrice, itemSummary.currency);
29
+ const taxableAmount = subtract(getDinero(itemSummary.itemPrice, itemSummary.currency), discountAllocatedAmount);
30
+ return {
31
+ itemPrice: itemSummary.itemPrice,
32
+ taxableAmount: amount(taxableAmount),
33
+ discountAmount: amount(discountAllocatedAmount),
34
+ currency: itemSummary.currency,
35
+ quantity: 1
36
+ };
37
+ });
38
+ };
39
+ const calculateWholeQtyLineItemTax = (itemSummary, taxRate) => {
40
+ if (taxRate === 0) {
41
+ return getDinero(0, itemSummary.currency);
42
+ }
43
+ const [taxAmount] = allocate(getDinero(itemSummary.taxableAmount, itemSummary.currency), taxRateToDineroAllocation(taxRate));
44
+ assert(taxAmount !== void 0, "taxAmount is undefined");
45
+ return taxAmount;
46
+ };
47
+ const calculatePerQtyLineItemTax = (itemSummary, taxRate) => {
48
+ if (taxRate === 0) {
49
+ return getDinero(0, itemSummary.currency);
50
+ }
51
+ const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);
52
+ let totalTaxAmount = getDinero(0, itemSummary.currency);
53
+ singleItemSummaries.forEach(itemSummary2 => {
54
+ const taxAmount = calculateWholeQtyLineItemTax(itemSummary2, taxRate);
55
+ totalTaxAmount = add(totalTaxAmount, taxAmount);
56
+ });
57
+ return totalTaxAmount;
58
+ };
59
+ export { allocatePerItemTaxableAmount, calculatePerQtyLineItemTax, calculateWholeQtyLineItemTax, taxRateToDineroAllocation };
60
+ //# sourceMappingURL=tax.private.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tax.private.mjs","sources":["../../../src/utils/money/tax.private.ts"],"sourcesContent":["// #############################################################################\n// Internal helper functions not for consumption outside of store.core!\n// Wrote as separate files so that they can be easily unit tested without exposing them\n// #############################################################################\nimport type { Dinero } from \"dinero.js\";\nimport { add, allocate, subtract } from \"dinero.js\";\n\nimport { assert } from \"../errors\";\nimport { FixedAmountAllocator } from \"./allocators/fixedAmount\";\nimport { amount, getDinero } from \"./misc\";\nimport type {\n Cents,\n LineItemSummary,\n SingleLineItemSummary,\n TaxRate,\n} from \"./types\";\n\n/**\n * Private helper to convert a floating number to a dinero friendly allocation integer pair\n * @see https://v2.dinerojs.com/docs/api/mutations/allocate\n * @example\n * taxRateToDineroAllocation(0.1) // [1, 9]\n * taxRateToDineroAllocation(0.5) // [5, 5]\n */\nexport const taxRateToDineroAllocation = (\n taxRate: TaxRate,\n): [number, number] => {\n if (taxRate <= 0 || taxRate >= 1) {\n throw new RangeError(\"Unsupported rate, expected in range of 0>rate<1\");\n }\n\n // Get the scale of the rate\n const rateScale = String(taxRate).split(\".\")[1]?.length;\n assert(rateScale !== undefined, \"rateScale is undefined\");\n\n // Convert to integers\n const rateInt = Math.round(taxRate * Math.pow(10, rateScale));\n return [rateInt, Math.pow(10, rateScale) - rateInt];\n};\n\n/**\n * Reverse engineer the taxable amount from \"whole item\" taxable amount into \"per item\" taxable amount for custom tax\n * rate calculations\n */\nexport const allocatePerItemTaxableAmount = (\n itemSummary: LineItemSummary,\n): SingleLineItemSummary[] => {\n /**\n * If the item quantity is 1, we can just return the item summary as is\n */\n if (itemSummary.quantity === 1) {\n return [itemSummary as SingleLineItemSummary];\n }\n\n // Reverse engineer price before discount\n const preDiscountAmount = add(\n getDinero(itemSummary.taxableAmount, itemSummary.currency),\n getDinero(itemSummary.discountAmount, itemSummary.currency),\n );\n\n const allocator = new FixedAmountAllocator({\n initialAllocateAmount: itemSummary.discountAmount,\n initialTotalAmount: amount(preDiscountAmount),\n currency: itemSummary.currency,\n });\n\n // Iterate over the amount of qty to reverse engineer the discount price\n return Array.from({ length: itemSummary.quantity }, () => {\n const discountAllocatedAmount = allocator.allocate(\n itemSummary.itemPrice,\n itemSummary.currency,\n );\n\n const taxableAmount = subtract(\n getDinero(itemSummary.itemPrice, itemSummary.currency),\n discountAllocatedAmount,\n );\n\n return {\n itemPrice: itemSummary.itemPrice,\n taxableAmount: amount(taxableAmount),\n discountAmount: amount(discountAllocatedAmount),\n currency: itemSummary.currency,\n quantity: 1,\n } as SingleLineItemSummary;\n });\n};\n\nexport const calculateWholeQtyLineItemTax = (\n itemSummary: LineItemSummary,\n taxRate: TaxRate,\n): Dinero<Cents> => {\n // Nothing to calculate\n if (taxRate === 0) {\n return getDinero(0, itemSummary.currency);\n }\n\n /**\n * FIXME: look into approach with multiply and different scale for control over rounding, currently we just inherit\n * what dinero gives us which cause unexpected rounding issue\n */\n const [taxAmount] = allocate(\n getDinero(itemSummary.taxableAmount, itemSummary.currency),\n taxRateToDineroAllocation(taxRate),\n );\n\n assert(taxAmount !== undefined, \"taxAmount is undefined\");\n return taxAmount;\n};\n\nexport const calculatePerQtyLineItemTax = (\n itemSummary: LineItemSummary,\n taxRate: TaxRate,\n): Dinero<Cents> => {\n // Nothing to calculate\n if (taxRate === 0) {\n return getDinero(0, itemSummary.currency);\n }\n\n // Split the item summary into per individual item qty summaries\n const singleItemSummaries = allocatePerItemTaxableAmount(itemSummary);\n\n // Calculate individual item qty tax and sum them up\n let totalTaxAmount = getDinero(0, itemSummary.currency);\n\n singleItemSummaries.forEach((itemSummary) => {\n // Probably a bit confusing at first, but calling the whole qty tax calculation function here as we can safely use\n // it as item summary is always a single item summary here\n const taxAmount = calculateWholeQtyLineItemTax(itemSummary, taxRate);\n totalTaxAmount = add(totalTaxAmount, taxAmount);\n });\n\n return totalTaxAmount;\n};\n"],"names":["taxRateToDineroAllocation","taxRate","RangeError","rateScale","String","split","length","assert","rateInt","Math","round","pow","allocatePerItemTaxableAmount","itemSummary","quantity","preDiscountAmount","add","getDinero","taxableAmount","currency","discountAmount","allocator","FixedAmountAllocator","initialAllocateAmount","initialTotalAmount","amount","Array","from","discountAllocatedAmount","allocate","itemPrice","subtract","calculateWholeQtyLineItemTax","taxAmount","calculatePerQtyLineItemTax","singleItemSummaries","totalTaxAmount","forEach"],"mappings":";;;;;AAwBa,MAAAA,yBAAA,GACXC,OACqB,IAAA;EACjB,IAAAA,OAAA,IAAW,CAAK,IAAAA,OAAA,IAAW,CAAG,EAAA;IAC1B,MAAA,IAAIC,WAAW,iDAAiD,CAAA;EACxE;EAGM,MAAAC,SAAA,GAAYC,OAAOH,OAAO,CAAA,CAAEI,MAAM,GAAG,CAAA,CAAE,CAAC,CAAG,EAAAC,MAAA;EAC1CC,MAAA,CAAAJ,SAAA,KAAc,QAAW,wBAAwB,CAAA;EAGlD,MAAAK,OAAA,GAAUC,KAAKC,KAAM,CAAAT,OAAA,GAAUQ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,OACkB,KAAA;EAElB,IAAIA,YAAY,CAAG,EAAA;IACV,OAAAgB,SAAA,CAAU,CAAG,EAAAJ,WAAA,CAAYM,QAAQ,CAAA;EAC1C;EAMM,MAAA,CAACc,SAAS,CAAI,GAAAJ,QAAA,CAClBZ,SAAU,CAAAJ,WAAA,CAAYK,aAAe,EAAAL,WAAA,CAAYM,QAAQ,CAAA,EACzDnB,0BAA0BC,OAAO,CAAA,CACnC;EAEOM,MAAA,CAAA0B,SAAA,KAAc,QAAW,wBAAwB,CAAA;EACjD,OAAAA,SAAA;AACT,CAAA;AAEa,MAAAC,0BAAA,GAA6BA,CACxCrB,WAAA,EACAZ,OACkB,KAAA;EAElB,IAAIA,YAAY,CAAG,EAAA;IACV,OAAAgB,SAAA,CAAU,CAAG,EAAAJ,WAAA,CAAYM,QAAQ,CAAA;EAC1C;EAGM,MAAAgB,mBAAA,GAAsBvB,6BAA6BC,WAAW,CAAA;EAGpE,IAAIuB,cAAiB,GAAAnB,SAAA,CAAU,CAAG,EAAAJ,WAAA,CAAYM,QAAQ,CAAA;EAElCgB,mBAAA,CAAAE,OAAA,CAASxB,YAAgB,IAAA;IAGrC,MAAAoB,SAAA,GAAYD,4BAA6BnB,CAAAA,YAAAA,EAAaZ,OAAO,CAAA;IAClDmC,cAAA,GAAApB,GAAA,CAAIoB,gBAAgBH,SAAS,CAAA;EAAA,CAC/C,CAAA;EAEM,OAAAG,cAAA;AACT,CAAA;"}
@@ -1,10 +1,85 @@
1
- import type { Currency as DineroCurrency } from "dinero.js";
1
+ import type { Dinero, Currency as DineroCurrency } from "dinero.js";
2
+ import type { Currency } from "../../types";
3
+ /**
4
+ * Floating point number of item tax rate
5
+ * Number in range of 0>rate<1 (non-inclusive boundaries)
6
+ * @example
7
+ * 0.09 // 9%
8
+ */
9
+ export type TaxRate = number;
10
+ /**
11
+ * Shorthand for Dinero.js instance with number as the amount
12
+ */
13
+ export type Dino = Dinero<number>;
14
+ /**
15
+ * Shorthand for Dinero.js currency instance representing either a currency or custom currency such as tax-rate or shipping
16
+ */
17
+ export type DinoCurrency = DineroCurrency<number>;
18
+ /**
19
+ * Cents representation of specific currency
20
+ * As a helper to easily understand the code, we use `Cents` as a type alias for `number` as historically we have had
21
+ * mistakes by the team where we have used as dollar instead of `Cents` and vice versa.
22
+ * @example
23
+ * 100 // in USD this is $1.00
24
+ * 100 // in YEN this is ¥100
25
+ */
26
+ export type Cents = number;
27
+ /**
28
+ * Type definition for a rounding function that can be used to round fractions
29
+ */
30
+ export type RoundingFn = (float: number) => Cents;
31
+ /**
32
+ * Convenient way to represent a money on the API level
33
+ * When working with dinero you typically will convert this to a Dinero instance
34
+ */
35
+ export interface Money {
36
+ amount: Cents;
37
+ currency: Currency;
38
+ }
2
39
  /**
3
40
  * Attempt to type out some locales `language-TERRITORY` which "we" as store care about
4
41
  * @see https://unicode-org.github.io/cldr-staging/charts/38/supplemental/territory_language_information.html
5
42
  */
6
43
  export type Locale = "ar-AE" | "ar-SA" | "bg-BG" | "bn-BD" | "bn-IN" | "cs-CZ" | "da-DK" | "de-AT" | "de-CH" | "de-DE" | "el-GR" | "en-AU" | "en-BR" | "en-CA" | "en-GB" | "en-IE" | "en-IN" | "en-JP" | "en-NZ" | "en-SG" | "en-US" | "en-ZA" | "es-AR" | "es-CL" | "es-CO" | "es-ES" | "es-MX" | "es-US" | "fi-FI" | "fr-BE" | "fr-CA" | "fr-CH" | "fr-FR" | "he-IL" | "hi-IN" | "hr-HR" | "hu-HU" | "id-ID" | "it-CH" | "it-IT" | "ja-JP" | "ko-KR" | "nl-BE" | "nl-NL" | "no-NO" | "pl-PL" | "pt-BR" | "pt-PT" | "ro-RO" | "ru-RU" | "sk-SK" | "sv-SE" | "ta-IN" | "ta-LK" | "th-TH" | "tr-TR" | "zh-CN" | "zh-HK" | "zh-TW" | string;
7
- export type CurrencyObj = {
8
- currency: DineroCurrency<number>;
44
+ export type LocalizedCurrency = {
45
+ currency: DinoCurrency;
9
46
  locale: Locale;
10
47
  };
48
+ export interface LineItemSummary {
49
+ itemPrice: Cents;
50
+ /**
51
+ * Item quantity that is always bigger than zero!
52
+ */
53
+ quantity: number;
54
+ currency: Currency;
55
+ /**
56
+ * Total discount amount (only) applied for the given item quantity.
57
+ * No taxes are included. Calculated by `total_raw_price * <discount-allocation-percentage>`
58
+ */
59
+ discountAmount: Cents;
60
+ /**
61
+ * subtotal - discountAmount
62
+ */
63
+ taxableAmount: Cents;
64
+ }
65
+ /**
66
+ * Pretty much the same as PreTaxItemSummary but with quantity always set to 1 (for clearer type hinting and reasoning
67
+ * around the topic)
68
+ */
69
+ export interface SingleLineItemSummary extends LineItemSummary {
70
+ quantity: 1;
71
+ }
72
+ export interface FullLineItemSummary extends LineItemSummary {
73
+ /**
74
+ * Total price for the given item quantity. Calculated by `(itemPrice * quantity)`
75
+ */
76
+ subtotal: Cents;
77
+ /**
78
+ * Total tax amount for the given item quantity.
79
+ */
80
+ tax: Cents;
81
+ /**
82
+ * Total price for the given item quantity. Calculated by `subtotal - discountAmount + tax`
83
+ */
84
+ total: Cents;
85
+ }
@@ -31,7 +31,7 @@ export declare function isFloat(value: unknown, entity?: string, ErrorClass?: ne
31
31
  * toFixed(1.2345, 0) // => "1"
32
32
  * toFixed(1.23, 4) // => "1.2300"
33
33
  */
34
- export declare function toFixedRate(rate: number, scale: number): string;
34
+ export declare function toFixedRate(rate: number, scale: number, asNumber?: boolean): string;
35
35
  export declare function toFixedRate(rate: number, scale: number, asNumber: true): number;
36
36
  /**
37
37
  * Util to convert a float number to a string. Using this rather than simple template string to have a consistent way of
@@ -21,7 +21,7 @@ function isInt(value, entity = "Value", ErrorClass = TypeError) {
21
21
  function isFloat(value, entity = "Value", ErrorClass = TypeError) {
22
22
  isFiniteNumber(value, entity, ErrorClass);
23
23
  }
24
- function toFixedRate(rate, scale = 0, asNumber = false) {
24
+ function toFixedRate(rate, scale, asNumber) {
25
25
  isFloat(rate, "Rate");
26
26
  const fixedRate = rate.toFixed(scale);
27
27
  return asNumber ? +fixedRate : fixedRate;
@@ -1 +1 @@
1
- {"version":3,"file":"number.js","sources":["../../src/utils/number.ts"],"sourcesContent":["/**\n * Util to easily parse that any given input is a finite number (not NaN, Infinity, -Infinity, etc.)\n * @throws If given input is not a finite number\n */\nexport function isFiniteNumber(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a finite number: ${value}`);\n }\n}\n\n/**\n * Custom isInt validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.isSafeInteger would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L20-L32\n * @throws If given input is not a valid integer\n */\nexport function isInt(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n\n if (!Number.isInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a safe integer: ${value}`);\n }\n}\n\n/**\n * Custom isFloat validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.parseFloat would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L34-L38\n * @throws If given input is not a valid float\n */\nexport function isFloat(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n}\n\n/**\n * Returns a string representing a number in fixed-point notation.\n * Overload: Returns the rate parsed as a number\n * @example\n * toFixed(1.2345, 2) // => \"1.23\"\n * toFixed(1.2345, 0) // => \"1\"\n * toFixed(1.23, 4) // => \"1.2300\"\n */\nexport function toFixedRate(rate: number, scale: number): string;\nexport function toFixedRate(\n rate: number,\n scale: number,\n asNumber: true,\n): number;\nexport function toFixedRate(rate: number, scale = 0, asNumber = false) {\n // Verify rate\n isFloat(rate, \"Rate\");\n\n const fixedRate = rate.toFixed(scale);\n\n return asNumber ? +fixedRate : fixedRate;\n}\n\n/**\n * Util to convert a float number to a string. Using this rather than simple template string to have a consistent way of\n * doing it. Removes any redundant trailing zeros.\n * @example\n * numberToString(1.23) // => \"1.23\"\n * numberToString(10.00) // => \"10\"\n * @throws If given input is not a valid number\n */\nexport const numberToString = (num: number): string => {\n isFloat(num);\n return num.toString(10);\n};\n\n/**\n * @see https://stackoverflow.com/a/35000557\n */\nexport const findClosestNumber = <T extends number>(\n haystack: T[],\n needle: number,\n): T => {\n return haystack.reduce((prev, curr) =>\n Math.abs(curr - needle) < Math.abs(prev - needle) ? curr : prev,\n );\n};\n\n/**\n * Splits number into array by max value provided.\n * E.g. splitNumberBy(100, 30) => [30, 30, 30, 10]\n */\nexport const splitNumberBy = (value: number, by: number) => {\n const chunks = new Array(Math.floor(value / by)).fill(by);\n const remainder = value % by;\n\n if (remainder > 0) {\n chunks.push(remainder);\n }\n\n return chunks;\n};\n\n/**\n * Clamp value to a given range\n */\nexport const clamp = (val: number, min: number, max: number) => {\n const trueMin = Math.min(min, max);\n const trueMax = Math.max(min, max);\n\n return Math.min(trueMax, Math.max(trueMin, val));\n};\n\n/**\n * Interpolate a number to a new range\n *\n * @example\n * linearInterpolate(5, [0, 10], [0, 100]); // 50\n */\nexport const linearInterpolate = (\n inputY: number,\n [fromMin, fromMax]: [number, number],\n [toMin, toMax]: [number, number],\n clampResult = true,\n) => {\n const percent = (inputY - fromMin) / (fromMax - fromMin);\n const outputX = percent * (toMax - toMin) + toMin;\n\n return clampResult ? clamp(outputX, toMin, toMax) : outputX;\n};\n\n/**\n * Increase value and start over once the range is overflown\n */\nexport const incrementLoopValue = (\n value: number,\n [min, max]: [number, number],\n) => {\n if (value === max) {\n return min;\n }\n return value + 1;\n};\n"],"names":["isFiniteNumber","value","entity","ErrorClass","TypeError","Number","isNaN","isFinite","isInt","isInteger","isSafeInteger","isFloat","toFixedRate","rate","scale","asNumber","fixedRate","toFixed","numberToString","num","toString","findClosestNumber","haystack","needle","reduce","prev","curr","Math","abs","splitNumberBy","by","chunks","Array","floor","fill","remainder","push","clamp","val","min","max","trueMin","trueMax","linearInterpolate","inputY","fromMin","fromMax","toMin","toMax","clampResult","percent","outputX","incrementLoopValue"],"mappings":";;;AAIO,SAASA,cACdA,CAAAC,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACzB,IAAI,OAAOH,KAAU,KAAA,QAAA,IAAYI,MAAO,CAAAC,KAAA,CAAML,KAAK,CAAG,EAAA;IAEpD,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,qBAAqBD,KAAO,EAAA,CAAA;EAC5D;EAEA,IAAI,CAACI,MAAA,CAAOE,QAAS,CAAAN,KAAK,CAAG,EAAA;IAE3B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,4BAA4BD,KAAO,EAAA,CAAA;EACnE;AACF;AAWO,SAASO,KACdA,CAAAP,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC,QAAQC,UAAU,CAAA;EAExC,IAAI,CAACE,MAAA,CAAOI,SAAU,CAAAR,KAAK,CAAG,EAAA;IAE5B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,uBAAuBD,KAAO,EAAA,CAAA;EAC9D;EAEA,IAAI,CAACI,MAAA,CAAOK,aAA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AEO,OAAAJ,MAAA;AACT,CAAA;AAKO,MAAMM,KAAQ,GAAAA,CAACC,GAAa,EAAAC,GAAA,EAAaC,GAAgB,KAAA;EAC9D,MAAMC,OAAU,GAAAd,IAAA,CAAKY,GAAI,CAAAA,GAAA,EAAKC,GAAG,CAAA;EACjC,MAAME,OAAU,GAAAf,IAAA,CAAKa,GAAI,CAAAD,GAAA,EAAKC,GAAG,CAAA;EAEjC,OAAOb,KAAKY,GAAI,CAAAG,OAAA,EAASf,KAAKa,GAAI,CAAAC,OAAA,EAASH,GAAG,CAAC,CAAA;AACjD,CAAA;AAQO,MAAMK,iBAAoB,GAAAA,CAC/BC,MACA,EAAA,CAACC,OAAS,EAAAC,OAAO,CACjB,EAAA,CAACC,KAAO,EAAAC,KAAK,CACb,EAAAC,WAAA,GAAc,IACX,KAAA;EACG,MAAAC,OAAA,GAAA,CAAWN,MAAS,GAAAC,OAAA,KAAYC,OAAU,GAAAD,OAAA,CAAA;EAC1C,MAAAM,OAAA,GAAUD,OAAW,IAAAF,KAAA,GAAQD,KAAS,CAAA,GAAAA,KAAA;EAE5C,OAAOE,WAAc,GAAAZ,KAAA,CAAMc,OAAS,EAAAJ,KAAA,EAAOC,KAAK,CAAI,GAAAG,OAAA;AACtD,CAAA;AAKO,MAAMC,qBAAqBA,CAChCnD,KAAA,EACA,CAACsC,GAAA,EAAKC,GAAG,CACN,KAAA;EACH,IAAIvC,UAAUuC,GAAK,EAAA;IACV,OAAAD,GAAA;EACT;EACA,OAAOtC,KAAQ,GAAA,CAAA;AACjB,CAAA;;;;;;;;;;"}
1
+ {"version":3,"file":"number.js","sources":["../../src/utils/number.ts"],"sourcesContent":["/**\n * Util to easily parse that any given input is a finite number (not NaN, Infinity, -Infinity, etc.)\n * @throws If given input is not a finite number\n */\nexport function isFiniteNumber(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a finite number: ${value}`);\n }\n}\n\n/**\n * Custom isInt validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.isSafeInteger would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L20-L32\n * @throws If given input is not a valid integer\n */\nexport function isInt(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n\n if (!Number.isInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a safe integer: ${value}`);\n }\n}\n\n/**\n * Custom isFloat validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.parseFloat would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L34-L38\n * @throws If given input is not a valid float\n */\nexport function isFloat(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n}\n\n/**\n * Returns a string representing a number in fixed-point notation.\n * Overload: Returns the rate parsed as a number\n * @example\n * toFixed(1.2345, 2) // => \"1.23\"\n * toFixed(1.2345, 0) // => \"1\"\n * toFixed(1.23, 4) // => \"1.2300\"\n */\nexport function toFixedRate(\n rate: number,\n scale: number,\n asNumber?: boolean,\n): string;\nexport function toFixedRate(\n rate: number,\n scale: number,\n asNumber: true,\n): number;\nexport function toFixedRate(rate: number, scale: number, asNumber?: boolean) {\n // Verify rate\n isFloat(rate, \"Rate\");\n\n const fixedRate = rate.toFixed(scale);\n\n return asNumber ? +fixedRate : fixedRate;\n}\n\n/**\n * Util to convert a float number to a string. Using this rather than simple template string to have a consistent way of\n * doing it. Removes any redundant trailing zeros.\n * @example\n * numberToString(1.23) // => \"1.23\"\n * numberToString(10.00) // => \"10\"\n * @throws If given input is not a valid number\n */\nexport const numberToString = (num: number): string => {\n isFloat(num);\n return num.toString(10);\n};\n\n/**\n * @see https://stackoverflow.com/a/35000557\n */\nexport const findClosestNumber = <T extends number>(\n haystack: T[],\n needle: number,\n): T => {\n return haystack.reduce((prev, curr) =>\n Math.abs(curr - needle) < Math.abs(prev - needle) ? curr : prev,\n );\n};\n\n/**\n * Splits number into array by max value provided.\n * E.g. splitNumberBy(100, 30) => [30, 30, 30, 10]\n */\nexport const splitNumberBy = (value: number, by: number) => {\n const chunks = new Array(Math.floor(value / by)).fill(by);\n const remainder = value % by;\n\n if (remainder > 0) {\n chunks.push(remainder);\n }\n\n return chunks;\n};\n\n/**\n * Clamp value to a given range\n */\nexport const clamp = (val: number, min: number, max: number) => {\n const trueMin = Math.min(min, max);\n const trueMax = Math.max(min, max);\n\n return Math.min(trueMax, Math.max(trueMin, val));\n};\n\n/**\n * Interpolate a number to a new range\n *\n * @example\n * linearInterpolate(5, [0, 10], [0, 100]); // 50\n */\nexport const linearInterpolate = (\n inputY: number,\n [fromMin, fromMax]: [number, number],\n [toMin, toMax]: [number, number],\n clampResult = true,\n) => {\n const percent = (inputY - fromMin) / (fromMax - fromMin);\n const outputX = percent * (toMax - toMin) + toMin;\n\n return clampResult ? clamp(outputX, toMin, toMax) : outputX;\n};\n\n/**\n * Increase value and start over once the range is overflown\n */\nexport const incrementLoopValue = (\n value: number,\n [min, max]: [number, number],\n) => {\n if (value === max) {\n return min;\n }\n return value + 1;\n};\n"],"names":["isFiniteNumber","value","entity","ErrorClass","TypeError","Number","isNaN","isFinite","isInt","isInteger","isSafeInteger","isFloat","toFixedRate","rate","scale","asNumber","fixedRate","toFixed","numberToString","num","toString","findClosestNumber","haystack","needle","reduce","prev","curr","Math","abs","splitNumberBy","by","chunks","Array","floor","fill","remainder","push","clamp","val","min","max","trueMin","trueMax","linearInterpolate","inputY","fromMin","fromMax","toMin","toMax","clampResult","percent","outputX","incrementLoopValue"],"mappings":";;;AAIO,SAASA,cACdA,CAAAC,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACzB,IAAI,OAAOH,KAAU,KAAA,QAAA,IAAYI,MAAO,CAAAC,KAAA,CAAML,KAAK,CAAG,EAAA;IAEpD,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,qBAAqBD,KAAO,EAAA,CAAA;EAC5D;EAEA,IAAI,CAACI,MAAA,CAAOE,QAAS,CAAAN,KAAK,CAAG,EAAA;IAE3B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,4BAA4BD,KAAO,EAAA,CAAA;EACnE;AACF;AAWO,SAASO,KACdA,CAAAP,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC,QAAQC,UAAU,CAAA;EAExC,IAAI,CAACE,MAAA,CAAOI,SAAU,CAAAR,KAAK,CAAG,EAAA;IAE5B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,uBAAuBD,KAAO,EAAA,CAAA;EAC9D;EAEA,IAAI,CAACI,MAAA,CAAOK,aAAc,CAAAT,KAAK,CAAG,EAAA;IAEhC,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,2BAA2BD,KAAO,EAAA,CAAA;EAClE;AACF;AAWO,SAASU,OACdA,CAAAV,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC,QAAQC,UAAU,CAAA;AAC1C;AAoBgB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AAKY,GAAI,CAAAG,OAAA,EAASf,KAAKa,GAAI,CAAAC,OAAA,EAASH,GAAG,CAAC,CAAA;AACjD,CAAA;AAQO,MAAMK,iBAAoB,GAAAA,CAC/BC,MACA,EAAA,CAACC,OAAS,EAAAC,OAAO,CACjB,EAAA,CAACC,KAAO,EAAAC,KAAK,CACb,EAAAC,WAAA,GAAc,IACX,KAAA;EACG,MAAAC,OAAA,GAAA,CAAWN,MAAS,GAAAC,OAAA,KAAYC,OAAU,GAAAD,OAAA,CAAA;EAC1C,MAAAM,OAAA,GAAUD,OAAW,IAAAF,KAAA,GAAQD,KAAS,CAAA,GAAAA,KAAA;EAE5C,OAAOE,WAAc,GAAAZ,KAAA,CAAMc,OAAS,EAAAJ,KAAA,EAAOC,KAAK,CAAI,GAAAG,OAAA;AACtD,CAAA;AAKO,MAAMC,qBAAqBA,CAChCnD,KAAA,EACA,CAACsC,GAAA,EAAKC,GAAG,CACN,KAAA;EACH,IAAIvC,UAAUuC,GAAK,EAAA;IACV,OAAAD,GAAA;EACT;EACA,OAAOtC,KAAQ,GAAA,CAAA;AACjB,CAAA;;;;;;;;;;"}
@@ -20,7 +20,7 @@ function isInt(value, entity = "Value", ErrorClass = TypeError) {
20
20
  function isFloat(value, entity = "Value", ErrorClass = TypeError) {
21
21
  isFiniteNumber(value, entity, ErrorClass);
22
22
  }
23
- function toFixedRate(rate, scale = 0, asNumber = false) {
23
+ function toFixedRate(rate, scale, asNumber) {
24
24
  isFloat(rate, "Rate");
25
25
  const fixedRate = rate.toFixed(scale);
26
26
  return asNumber ? +fixedRate : fixedRate;
@@ -1 +1 @@
1
- {"version":3,"file":"number.mjs","sources":["../../src/utils/number.ts"],"sourcesContent":["/**\n * Util to easily parse that any given input is a finite number (not NaN, Infinity, -Infinity, etc.)\n * @throws If given input is not a finite number\n */\nexport function isFiniteNumber(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a finite number: ${value}`);\n }\n}\n\n/**\n * Custom isInt validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.isSafeInteger would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L20-L32\n * @throws If given input is not a valid integer\n */\nexport function isInt(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n\n if (!Number.isInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a safe integer: ${value}`);\n }\n}\n\n/**\n * Custom isFloat validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.parseFloat would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L34-L38\n * @throws If given input is not a valid float\n */\nexport function isFloat(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n}\n\n/**\n * Returns a string representing a number in fixed-point notation.\n * Overload: Returns the rate parsed as a number\n * @example\n * toFixed(1.2345, 2) // => \"1.23\"\n * toFixed(1.2345, 0) // => \"1\"\n * toFixed(1.23, 4) // => \"1.2300\"\n */\nexport function toFixedRate(rate: number, scale: number): string;\nexport function toFixedRate(\n rate: number,\n scale: number,\n asNumber: true,\n): number;\nexport function toFixedRate(rate: number, scale = 0, asNumber = false) {\n // Verify rate\n isFloat(rate, \"Rate\");\n\n const fixedRate = rate.toFixed(scale);\n\n return asNumber ? +fixedRate : fixedRate;\n}\n\n/**\n * Util to convert a float number to a string. Using this rather than simple template string to have a consistent way of\n * doing it. Removes any redundant trailing zeros.\n * @example\n * numberToString(1.23) // => \"1.23\"\n * numberToString(10.00) // => \"10\"\n * @throws If given input is not a valid number\n */\nexport const numberToString = (num: number): string => {\n isFloat(num);\n return num.toString(10);\n};\n\n/**\n * @see https://stackoverflow.com/a/35000557\n */\nexport const findClosestNumber = <T extends number>(\n haystack: T[],\n needle: number,\n): T => {\n return haystack.reduce((prev, curr) =>\n Math.abs(curr - needle) < Math.abs(prev - needle) ? curr : prev,\n );\n};\n\n/**\n * Splits number into array by max value provided.\n * E.g. splitNumberBy(100, 30) => [30, 30, 30, 10]\n */\nexport const splitNumberBy = (value: number, by: number) => {\n const chunks = new Array(Math.floor(value / by)).fill(by);\n const remainder = value % by;\n\n if (remainder > 0) {\n chunks.push(remainder);\n }\n\n return chunks;\n};\n\n/**\n * Clamp value to a given range\n */\nexport const clamp = (val: number, min: number, max: number) => {\n const trueMin = Math.min(min, max);\n const trueMax = Math.max(min, max);\n\n return Math.min(trueMax, Math.max(trueMin, val));\n};\n\n/**\n * Interpolate a number to a new range\n *\n * @example\n * linearInterpolate(5, [0, 10], [0, 100]); // 50\n */\nexport const linearInterpolate = (\n inputY: number,\n [fromMin, fromMax]: [number, number],\n [toMin, toMax]: [number, number],\n clampResult = true,\n) => {\n const percent = (inputY - fromMin) / (fromMax - fromMin);\n const outputX = percent * (toMax - toMin) + toMin;\n\n return clampResult ? clamp(outputX, toMin, toMax) : outputX;\n};\n\n/**\n * Increase value and start over once the range is overflown\n */\nexport const incrementLoopValue = (\n value: number,\n [min, max]: [number, number],\n) => {\n if (value === max) {\n return min;\n }\n return value + 1;\n};\n"],"names":["isFiniteNumber","value","entity","ErrorClass","TypeError","Number","isNaN","isFinite","isInt","isInteger","isSafeInteger","isFloat","toFixedRate","rate","scale","asNumber","fixedRate","toFixed","numberToString","num","toString","findClosestNumber","haystack","needle","reduce","prev","curr","Math","abs","splitNumberBy","by","chunks","Array","floor","fill","remainder","push","clamp","val","min","max","trueMin","trueMax","linearInterpolate","inputY","fromMin","fromMax","toMin","toMax","clampResult","percent","outputX","incrementLoopValue"],"mappings":";;AAIO,SAASA,cACdA,CAAAC,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACzB,IAAI,OAAOH,KAAU,KAAA,QAAA,IAAYI,MAAO,CAAAC,KAAA,CAAML,KAAK,CAAG,EAAA;IAEpD,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,qBAAqBD,KAAO,EAAA,CAAA;EAC5D;EAEA,IAAI,CAACI,MAAA,CAAOE,QAAS,CAAAN,KAAK,CAAG,EAAA;IAE3B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,4BAA4BD,KAAO,EAAA,CAAA;EACnE;AACF;AAWO,SAASO,KACdA,CAAAP,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC,QAAQC,UAAU,CAAA;EAExC,IAAI,CAACE,MAAA,CAAOI,SAAU,CAAAR,KAAK,CAAG,EAAA;IAE5B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,uBAAuBD,KAAO,EAAA,CAAA;EAC9D;EAEA,IAAI,CAACI,MAAA,CAAOK,aAAc,CAAAT,KAAK,CAAG,EAAA;IAEhC,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,2BAA2BD,KAAO,EAAA,CAAA;EAClE;AACF;AAWO,SAASU,OACdA,CAAAV,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC,QAAQC,UAAU,CAAA;AAC1C;AAgBO,SAAS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C,OAAOb,KAAKY,GAAI,CAAAG,OAAA,EAASf,KAAKa,GAAI,CAAAC,OAAA,EAASH,GAAG,CAAC,CAAA;AACjD,CAAA;AAQO,MAAMK,iBAAoB,GAAAA,CAC/BC,MACA,EAAA,CAACC,OAAS,EAAAC,OAAO,CACjB,EAAA,CAACC,KAAO,EAAAC,KAAK,CACb,EAAAC,WAAA,GAAc,IACX,KAAA;EACG,MAAAC,OAAA,GAAA,CAAWN,MAAS,GAAAC,OAAA,KAAYC,OAAU,GAAAD,OAAA,CAAA;EAC1C,MAAAM,OAAA,GAAUD,OAAW,IAAAF,KAAA,GAAQD,KAAS,CAAA,GAAAA,KAAA;EAE5C,OAAOE,WAAc,GAAAZ,KAAA,CAAMc,OAAS,EAAAJ,KAAA,EAAOC,KAAK,CAAI,GAAAG,OAAA;AACtD,CAAA;AAKO,MAAMC,qBAAqBA,CAChCnD,KAAA,EACA,CAACsC,GAAA,EAAKC,GAAG,CACN,KAAA;EACH,IAAIvC,UAAUuC,GAAK,EAAA;IACV,OAAAD,GAAA;EACT;EACA,OAAOtC,KAAQ,GAAA,CAAA;AACjB,CAAA;"}
1
+ {"version":3,"file":"number.mjs","sources":["../../src/utils/number.ts"],"sourcesContent":["/**\n * Util to easily parse that any given input is a finite number (not NaN, Infinity, -Infinity, etc.)\n * @throws If given input is not a finite number\n */\nexport function isFiniteNumber(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a finite number: ${value}`);\n }\n}\n\n/**\n * Custom isInt validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.isSafeInteger would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L20-L32\n * @throws If given input is not a valid integer\n */\nexport function isInt(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n\n if (!Number.isInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw new ErrorClass(`${entity} is not a safe integer: ${value}`);\n }\n}\n\n/**\n * Custom isFloat validation function that returns a more fine-grained error message otherwise for type safety alone a\n * Number.parseFloat would be sufficient.\n *\n * Code inspired from graphql-scalars library.\n * @see\n * https://github.com/Urigo/graphql-scalars/blob/c4fa3d27b965e39ceda6c33fc18041f112ecce49/src/scalars/utilities.ts#L34-L38\n * @throws If given input is not a valid float\n */\nexport function isFloat(\n value: unknown,\n entity = \"Value\",\n ErrorClass: new (message: string) => void = TypeError,\n): asserts value is number {\n isFiniteNumber(value, entity, ErrorClass);\n}\n\n/**\n * Returns a string representing a number in fixed-point notation.\n * Overload: Returns the rate parsed as a number\n * @example\n * toFixed(1.2345, 2) // => \"1.23\"\n * toFixed(1.2345, 0) // => \"1\"\n * toFixed(1.23, 4) // => \"1.2300\"\n */\nexport function toFixedRate(\n rate: number,\n scale: number,\n asNumber?: boolean,\n): string;\nexport function toFixedRate(\n rate: number,\n scale: number,\n asNumber: true,\n): number;\nexport function toFixedRate(rate: number, scale: number, asNumber?: boolean) {\n // Verify rate\n isFloat(rate, \"Rate\");\n\n const fixedRate = rate.toFixed(scale);\n\n return asNumber ? +fixedRate : fixedRate;\n}\n\n/**\n * Util to convert a float number to a string. Using this rather than simple template string to have a consistent way of\n * doing it. Removes any redundant trailing zeros.\n * @example\n * numberToString(1.23) // => \"1.23\"\n * numberToString(10.00) // => \"10\"\n * @throws If given input is not a valid number\n */\nexport const numberToString = (num: number): string => {\n isFloat(num);\n return num.toString(10);\n};\n\n/**\n * @see https://stackoverflow.com/a/35000557\n */\nexport const findClosestNumber = <T extends number>(\n haystack: T[],\n needle: number,\n): T => {\n return haystack.reduce((prev, curr) =>\n Math.abs(curr - needle) < Math.abs(prev - needle) ? curr : prev,\n );\n};\n\n/**\n * Splits number into array by max value provided.\n * E.g. splitNumberBy(100, 30) => [30, 30, 30, 10]\n */\nexport const splitNumberBy = (value: number, by: number) => {\n const chunks = new Array(Math.floor(value / by)).fill(by);\n const remainder = value % by;\n\n if (remainder > 0) {\n chunks.push(remainder);\n }\n\n return chunks;\n};\n\n/**\n * Clamp value to a given range\n */\nexport const clamp = (val: number, min: number, max: number) => {\n const trueMin = Math.min(min, max);\n const trueMax = Math.max(min, max);\n\n return Math.min(trueMax, Math.max(trueMin, val));\n};\n\n/**\n * Interpolate a number to a new range\n *\n * @example\n * linearInterpolate(5, [0, 10], [0, 100]); // 50\n */\nexport const linearInterpolate = (\n inputY: number,\n [fromMin, fromMax]: [number, number],\n [toMin, toMax]: [number, number],\n clampResult = true,\n) => {\n const percent = (inputY - fromMin) / (fromMax - fromMin);\n const outputX = percent * (toMax - toMin) + toMin;\n\n return clampResult ? clamp(outputX, toMin, toMax) : outputX;\n};\n\n/**\n * Increase value and start over once the range is overflown\n */\nexport const incrementLoopValue = (\n value: number,\n [min, max]: [number, number],\n) => {\n if (value === max) {\n return min;\n }\n return value + 1;\n};\n"],"names":["isFiniteNumber","value","entity","ErrorClass","TypeError","Number","isNaN","isFinite","isInt","isInteger","isSafeInteger","isFloat","toFixedRate","rate","scale","asNumber","fixedRate","toFixed","numberToString","num","toString","findClosestNumber","haystack","needle","reduce","prev","curr","Math","abs","splitNumberBy","by","chunks","Array","floor","fill","remainder","push","clamp","val","min","max","trueMin","trueMax","linearInterpolate","inputY","fromMin","fromMax","toMin","toMax","clampResult","percent","outputX","incrementLoopValue"],"mappings":";;AAIO,SAASA,c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S,GAAAC,OAAA,KAAYC,OAAU,GAAAD,OAAA,CAAA;EAC1C,MAAAM,OAAA,GAAUD,OAAW,IAAAF,KAAA,GAAQD,KAAS,CAAA,GAAAA,KAAA;EAE5C,OAAOE,WAAc,GAAAZ,KAAA,CAAMc,OAAS,EAAAJ,KAAA,EAAOC,KAAK,CAAI,GAAAG,OAAA;AACtD,CAAA;AAKO,MAAMC,qBAAqBA,CAChCnD,KAAA,EACA,CAACsC,GAAA,EAAKC,GAAG,CACN,KAAA;EACH,IAAIvC,UAAUuC,GAAK,EAAA;IACV,OAAAD,GAAA;EACT;EACA,OAAOtC,KAAQ,GAAA,CAAA;AACjB,CAAA;"}
@@ -0,0 +1,41 @@
1
+ import type { Nullish, StorefrontProduct, StoreId, UnionToAllPossibleTuples } from "../types";
2
+ import { DisplayProductStatus } from "../types";
3
+ /**
4
+ * Narrow MinimalProProductFragment type even more to the union of fields that are needed to sort product
5
+ */
6
+ type ProductMinFieldsForSorting = Pick<StorefrontProduct, "status" | "tags" | "minDisplayPrice"> & {
7
+ variants: {
8
+ availableInOtherStores: Array<{
9
+ __typename: string;
10
+ }>;
11
+ }[];
12
+ linkedProducts?: {
13
+ status: StorefrontProduct["status"];
14
+ }[];
15
+ };
16
+ export declare enum Sort {
17
+ HighestPrice = "highest-price",
18
+ LowestPrice = "lowest-price",
19
+ Availability = "availability"
20
+ }
21
+ export declare enum SortOrder {
22
+ Asc = "Asc",
23
+ Desc = "Desc"
24
+ }
25
+ /**
26
+ * Variants statuses sorted in ascending order from least preferable to most, so if some new status comes in, then the
27
+ * lookup for `.indexOf()` would return `-1`, thus being "worse" then DisplayProductStatus.SoldOut and moved to the very
28
+ * back of list
29
+ */
30
+ export declare const sortedStatusesByPriorityAsc: UnionToAllPossibleTuples<DisplayProductStatus>;
31
+ export declare const sortByAvailabilityDesc: (current: ProductMinFieldsForSorting, next: ProductMinFieldsForSorting) => number;
32
+ export declare const sortByPrice: (order: SortOrder) => (current: ProductMinFieldsForSorting, next: ProductMinFieldsForSorting) => number;
33
+ /**
34
+ * Sorts products based on the given sort type.
35
+ * @param currentSort - sort type
36
+ * @param sortByWeightTag - if false, then sort by weight tag is
37
+ * ignored (e.g. for `Related Add-ons` where
38
+ * we don't want to sort by weight tag)
39
+ */
40
+ export declare const sortProducts: (currentSort: Nullish<string | Sort>, storeId?: StoreId, sortByWeightTag?: boolean) => (current: ProductMinFieldsForSorting, next: ProductMinFieldsForSorting) => number;
41
+ export {};
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ require('../types/index.js');
4
+ var array = require('./array.js');
5
+ var product$1 = require('./product.js');
6
+ var product = require('../types/product.js');
7
+ "use strict";
8
+ var Sort = /* @__PURE__ */(Sort2 => {
9
+ Sort2["HighestPrice"] = "highest-price";
10
+ Sort2["LowestPrice"] = "lowest-price";
11
+ Sort2["Availability"] = "availability";
12
+ return Sort2;
13
+ })(Sort || {});
14
+ var SortOrder = /* @__PURE__ */(SortOrder2 => {
15
+ SortOrder2["Asc"] = "Asc";
16
+ SortOrder2["Desc"] = "Desc";
17
+ return SortOrder2;
18
+ })(SortOrder || {});
19
+ const sortedStatusesByPriorityAsc = [product.DisplayProductStatus.Unavailable, product.DisplayProductStatus.ComingSoon, product.DisplayProductStatus.SoldOut, product.DisplayProductStatus.RegionNotAvailable, product.DisplayProductStatus.Backorder, product.DisplayProductStatus.Available];
20
+ const getProductStatusPriority = product$1 => {
21
+ let sortStatus = product$1.status;
22
+ if (product$1.variants.some(variant => variant.availableInOtherStores.length) || product$1.linkedProducts && product$1.linkedProducts.some(linkedProduct => linkedProduct.status === product.DisplayProductStatus.Available)) {
23
+ sortStatus = product.DisplayProductStatus.Available;
24
+ }
25
+ return sortedStatusesByPriorityAsc.indexOf(sortStatus);
26
+ };
27
+ const sortByAvailabilityDesc = (current, next) => {
28
+ return array.normalizeSortResult(getProductStatusPriority(next) - getProductStatusPriority(current));
29
+ };
30
+ const sortByPrice = order => (current, next) => {
31
+ const currentProductPrice = current.minDisplayPrice.amount;
32
+ const nextProductPrice = next.minDisplayPrice.amount;
33
+ if (order === "Desc" /* Desc */) {
34
+ return nextProductPrice - currentProductPrice;
35
+ } else {
36
+ return currentProductPrice - nextProductPrice;
37
+ }
38
+ };
39
+ const sortProducts = (currentSort, storeId, sortByWeightTag = true) => (current, next) => {
40
+ switch (currentSort) {
41
+ case "highest-price" /* HighestPrice */:
42
+ case "lowest-price" /* LowestPrice */:
43
+ {
44
+ return sortByPrice(currentSort === "highest-price" /* HighestPrice */ ? "Desc" /* Desc */ : "Asc" /* Asc */)(current, next);
45
+ }
46
+ case "availability" /* Availability */:
47
+ {
48
+ return sortByAvailabilityDesc(current, next);
49
+ }
50
+ default:
51
+ {
52
+ const sorts = [sortByAvailabilityDesc];
53
+ if (sortByWeightTag) {
54
+ sorts.push(product$1.sortByTagWeight(product$1.SortSiteId.Store, storeId));
55
+ }
56
+ return array.combineSorts(sorts)(current, next);
57
+ }
58
+ }
59
+ };
60
+ exports.Sort = Sort;
61
+ exports.SortOrder = SortOrder;
62
+ exports.sortByAvailabilityDesc = sortByAvailabilityDesc;
63
+ exports.sortByPrice = sortByPrice;
64
+ exports.sortProducts = sortProducts;
65
+ exports.sortedStatusesByPriorityAsc = sortedStatusesByPriorityAsc;
66
+ //# sourceMappingURL=productSort.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"productSort.js","sources":["../../src/utils/productSort.ts"],"sourcesContent":["import type { Nullish, StorefrontProduct, StoreId, UnionToAllPossibleTuples } from \"../types\";\nimport { DisplayProductStatus } from \"../types\";\nimport { combineSorts, normalizeSortResult } from \"./array\";\nimport { sortByTagWeight, SortSiteId } from \"./product\";\n\n/**\n * Narrow MinimalProProductFragment type even more to the union of fields that are needed to sort product\n */\ntype ProductMinFieldsForSorting = Pick<\n StorefrontProduct,\n \"status\" | \"tags\" | \"minDisplayPrice\"\n> & {\n variants: {\n // We only need bare minimum from array to compare array length\n // FIXME: move it to backend as a boolean field so we don't need to fetch entire array to reduce it to a boolean ourselves\n availableInOtherStores: Array<{ __typename: string }>;\n }[];\n linkedProducts?: {\n status: StorefrontProduct[\"status\"];\n }[];\n};\n\nexport enum Sort {\n HighestPrice = \"highest-price\",\n LowestPrice = \"lowest-price\",\n Availability = \"availability\",\n}\n\nexport enum SortOrder {\n Asc = \"Asc\",\n Desc = \"Desc\",\n}\n\n/**\n * Variants statuses sorted in ascending order from least preferable to most, so if some new status comes in, then the\n * lookup for `.indexOf()` would return `-1`, thus being \"worse\" then DisplayProductStatus.SoldOut and moved to the very\n * back of list\n */\nexport const sortedStatusesByPriorityAsc: UnionToAllPossibleTuples<DisplayProductStatus> =\n [\n DisplayProductStatus.Unavailable,\n DisplayProductStatus.ComingSoon,\n DisplayProductStatus.SoldOut,\n DisplayProductStatus.RegionNotAvailable,\n DisplayProductStatus.Backorder,\n DisplayProductStatus.Available,\n ];\n/**\n * Due to currently variant status being nullable for historical reasons we need to have a fallback state\n * TODO: remove once display status is StorefrontProductVariant.status is non-nullable\n */\nconst getProductStatusPriority = (\n product: ProductMinFieldsForSorting,\n): number => {\n let sortStatus = product.status;\n\n // Virtually set sort status as available if it has alternative stores\n if (\n product.variants.some((variant) => variant.availableInOtherStores.length) ||\n (product.linkedProducts &&\n product.linkedProducts.some(\n (linkedProduct) =>\n linkedProduct.status === DisplayProductStatus.Available,\n ))\n ) {\n sortStatus = DisplayProductStatus.Available;\n }\n\n return sortedStatusesByPriorityAsc.indexOf(sortStatus);\n};\n\nexport const sortByAvailabilityDesc = (\n current: ProductMinFieldsForSorting,\n next: ProductMinFieldsForSorting,\n): number => {\n return normalizeSortResult(\n getProductStatusPriority(next) - getProductStatusPriority(current),\n );\n};\n\nexport const sortByPrice =\n (order: SortOrder) => (\n current: ProductMinFieldsForSorting,\n next: ProductMinFieldsForSorting,\n ): number => {\n const currentProductPrice = current.minDisplayPrice.amount;\n\n const nextProductPrice = next.minDisplayPrice.amount;\n\n if (order === SortOrder.Desc) {\n return nextProductPrice - currentProductPrice;\n } else {\n return currentProductPrice - nextProductPrice;\n }\n };\n\n\n/**\n * Sorts products based on the given sort type.\n * @param currentSort - sort type\n * @param sortByWeightTag - if false, then sort by weight tag is\n * ignored (e.g. for `Related Add-ons` where\n * we don't want to sort by weight tag)\n */\nexport const sortProducts = (\n currentSort: Nullish<string | Sort>,\n storeId?: StoreId,\n sortByWeightTag = true,\n ) =>\n (current: ProductMinFieldsForSorting, next: ProductMinFieldsForSorting) => {\n switch (currentSort) {\n // Sort by price\n case Sort.HighestPrice:\n case Sort.LowestPrice: {\n return sortByPrice(\n currentSort === Sort.HighestPrice ? SortOrder.Desc : SortOrder.Asc,\n )(current, next);\n }\n\n case Sort.Availability: {\n return sortByAvailabilityDesc(current, next);\n }\n\n default: {\n const sorts = [sortByAvailabilityDesc];\n\n // Add sorting by tag weight\n if (sortByWeightTag) {\n sorts.push(sortByTagWeight(SortSiteId.Store, storeId));\n }\n\n // Do additional sorting by tag weight only after initial sorting resulting in \"same group\"\n return combineSorts(sorts)(current, next);\n }\n }\n };"],"names":["Sort","SortOrder","sortedStatusesByPriorityAsc","DisplayProductStatus","Unavailable","ComingSoon","SoldOut","RegionNotAvailable","Backorder","Available","getProductStatusPriority","product","sortStatus","status","variants","some","variant","availableInOtherStores","length","linkedProducts","linkedProduct","indexOf","sortByAvailabilityDesc","current","next","normalizeSortResult","sortByPrice","order","currentProductPrice","minDisplayPrice","amount","nextProductPrice","sortProducts","currentSort","storeId","sortByWeightTag","sorts","push","sortByTagWeight","SortSiteId","Store","combineSorts"],"mappings":";;;;;;;AAsBY,IAAAA,IAAA,GAAA,gBAAAA,KAAL,IAAA;EACLA,MAAA,cAAe,CAAA,GAAA,eAAA;EACfA,MAAA,aAAc,CAAA,GAAA,cAAA;EACdA,MAAA,cAAe,CAAA,GAAA,cAAA;EAHLA,OAAAA,KAAAA;AAAA,CAAA,EAAAA,IAAA,IAAA,CAAA,CAAA,CAAA;AAMA,IAAAC,SAAA,GAAA,gBAAAA,UAAL,IAAA;EACLA,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