@ubnt/store.core 9.44.2 → 9.44.3-new-design

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 (524) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/lib/apis/smartcat.d.ts +4 -4
  3. package/lib/apis/smartcat.js +1 -1
  4. package/lib/apis/smartcat.js.map +1 -1
  5. package/lib/apis/smartcat.mjs +1 -1
  6. package/lib/apis/smartcat.mjs.map +1 -1
  7. package/lib/assets/cart-secondary.svg +5 -0
  8. package/lib/assets/close2.svg +3 -2
  9. package/lib/assets/close3.svg +2 -3
  10. package/lib/assets/icon-location-pin.svg +5 -0
  11. package/lib/assets/icons/cart-secondary.svg.js +27 -0
  12. package/lib/assets/icons/cart-secondary.svg.js.map +1 -0
  13. package/lib/assets/icons/cart-secondary.svg.mjs +3 -0
  14. package/lib/assets/icons/cart-secondary.svg.mjs.map +1 -0
  15. package/lib/assets/icons/menu/{icon-globe.svg.js → icon-location-pin.svg.js} +6 -6
  16. package/lib/assets/icons/menu/icon-location-pin.svg.js.map +1 -0
  17. package/lib/assets/icons/menu/icon-location-pin.svg.mjs +3 -0
  18. package/lib/assets/icons/menu/icon-location-pin.svg.mjs.map +1 -0
  19. package/lib/assets/logoUnifi.svg +10 -2
  20. package/lib/assets/pause.svg +3 -3
  21. package/lib/assets/pause2.svg +3 -3
  22. package/lib/assets/port.svg +4 -2
  23. package/lib/assets/port2.svg +2 -4
  24. package/lib/components/Accordion/Accordion.js +2 -2
  25. package/lib/components/Accordion/Accordion.js.map +1 -1
  26. package/lib/components/Accordion/Accordion.mjs +2 -2
  27. package/lib/components/Accordion/Accordion.mjs.map +1 -1
  28. package/lib/components/BackInStock/BackInStock.types.d.ts +1 -0
  29. package/lib/components/Button/Button.js +7 -0
  30. package/lib/components/Button/Button.js.map +1 -1
  31. package/lib/components/Button/Button.mjs +8 -1
  32. package/lib/components/Button/Button.mjs.map +1 -1
  33. package/lib/components/Button/CartButton.d.ts +3 -1
  34. package/lib/components/Button/CartButton.js +9 -4
  35. package/lib/components/Button/CartButton.js.map +1 -1
  36. package/lib/components/Button/CartButton.mjs +8 -4
  37. package/lib/components/Button/CartButton.mjs.map +1 -1
  38. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.d.ts +1 -1
  39. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.js +16 -4
  40. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.js.map +1 -1
  41. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.mjs +17 -5
  42. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.mjs.map +1 -1
  43. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.d.ts +5 -1
  44. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.js +82 -17
  45. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.js.map +1 -1
  46. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.mjs +82 -17
  47. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.styles.mjs.map +1 -1
  48. package/lib/components/ButtonGroupBasic/ButtonGroupBasic.types.d.ts +4 -0
  49. package/lib/components/CardSection/CardSection.styles.d.ts +1 -1
  50. package/lib/components/CategoryTabs/CategoryTabs.styles.d.ts +4 -2
  51. package/lib/components/CategoryTabs/CategoryTabs.styles.js +8 -5
  52. package/lib/components/CategoryTabs/CategoryTabs.styles.js.map +1 -1
  53. package/lib/components/CategoryTabs/CategoryTabs.styles.mjs +7 -6
  54. package/lib/components/CategoryTabs/CategoryTabs.styles.mjs.map +1 -1
  55. package/lib/components/Compare/Compare.styles.d.ts +5 -5
  56. package/lib/components/Container/Container.d.ts +1 -1
  57. package/lib/components/Container/Container.js +4 -3
  58. package/lib/components/Container/Container.js.map +1 -1
  59. package/lib/components/Container/Container.mjs +5 -4
  60. package/lib/components/Container/Container.mjs.map +1 -1
  61. package/lib/components/CustomImage/CustomImage.js +4 -4
  62. package/lib/components/CustomImage/CustomImage.js.map +1 -1
  63. package/lib/components/CustomImage/CustomImage.mjs +4 -4
  64. package/lib/components/CustomImage/CustomImage.mjs.map +1 -1
  65. package/lib/components/Explore/ExploreData.js +12 -12
  66. package/lib/components/Explore/ExploreData.js.map +1 -1
  67. package/lib/components/Explore/ExploreData.mjs +12 -12
  68. package/lib/components/Explore/ExploreData.mjs.map +1 -1
  69. package/lib/components/FeaturesSection_deprecated/FeaturesSection.js +2 -2
  70. package/lib/components/FeaturesSection_deprecated/FeaturesSection.js.map +1 -1
  71. package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs +2 -2
  72. package/lib/components/FeaturesSection_deprecated/FeaturesSection.mjs.map +1 -1
  73. package/lib/components/FeaturesSection_deprecated/assets/close.svg.js +1 -1
  74. package/lib/components/FeaturesSection_deprecated/assets/close.svg.mjs +2 -2
  75. package/lib/components/Gallery/Gallery.context.js.map +1 -1
  76. package/lib/components/Gallery/Gallery.context.mjs.map +1 -1
  77. package/lib/components/Gallery/GalleryItem/GalleryItem.js +3 -1
  78. package/lib/components/Gallery/GalleryItem/GalleryItem.js.map +1 -1
  79. package/lib/components/Gallery/GalleryItem/GalleryItem.mjs +3 -1
  80. package/lib/components/Gallery/GalleryItem/GalleryItem.mjs.map +1 -1
  81. package/lib/components/Header/AccountFrame/AccountFrame.js +3 -3
  82. package/lib/components/Header/AccountFrame/AccountFrame.js.map +1 -1
  83. package/lib/components/Header/AccountFrame/AccountFrame.mjs +3 -3
  84. package/lib/components/Header/AccountFrame/AccountFrame.mjs.map +1 -1
  85. package/lib/components/Header/AccountMenu/AccountMenu.js +11 -1
  86. package/lib/components/Header/AccountMenu/AccountMenu.js.map +1 -1
  87. package/lib/components/Header/AccountMenu/AccountMenu.mjs +13 -3
  88. package/lib/components/Header/AccountMenu/AccountMenu.mjs.map +1 -1
  89. package/lib/components/Header/CartModalV2/Item/Item.styles.d.ts +1 -1
  90. package/lib/components/Header/Header.js +12 -12
  91. package/lib/components/Header/Header.js.map +1 -1
  92. package/lib/components/Header/Header.mjs +12 -12
  93. package/lib/components/Header/Header.mjs.map +1 -1
  94. package/lib/components/Header/Header.styles.d.ts +7 -12
  95. package/lib/components/Header/Header.styles.js +10 -32
  96. package/lib/components/Header/Header.styles.js.map +1 -1
  97. package/lib/components/Header/Header.styles.mjs +10 -31
  98. package/lib/components/Header/Header.styles.mjs.map +1 -1
  99. package/lib/components/Header/Header.types.d.ts +30 -6
  100. package/lib/components/Header/Header.types.js +2 -1
  101. package/lib/components/Header/Header.types.js.map +1 -1
  102. package/lib/components/Header/Header.types.mjs +2 -1
  103. package/lib/components/Header/Header.types.mjs.map +1 -1
  104. package/lib/components/Header/IsolatedHeader.d.ts +1 -0
  105. package/lib/components/Header/IsolatedHeader.js +44 -44
  106. package/lib/components/Header/IsolatedHeader.js.map +1 -1
  107. package/lib/components/Header/IsolatedHeader.mjs +47 -46
  108. package/lib/components/Header/IsolatedHeader.mjs.map +1 -1
  109. package/lib/components/Header/LanguageFrame/LanguageFrame.js.map +1 -1
  110. package/lib/components/Header/LanguageFrame/LanguageFrame.mjs.map +1 -1
  111. package/lib/components/Header/LogoIcon/LogoIcon.d.ts +7 -0
  112. package/lib/components/Header/LogoIcon/LogoIcon.js +46 -0
  113. package/lib/components/Header/LogoIcon/LogoIcon.js.map +1 -0
  114. package/lib/components/Header/LogoIcon/LogoIcon.mjs +36 -0
  115. package/lib/components/Header/LogoIcon/LogoIcon.mjs.map +1 -0
  116. package/lib/components/Header/LogoIcon/index.d.ts +1 -0
  117. package/lib/components/Header/LogoIcon/index.js +6 -0
  118. package/lib/components/Header/LogoIcon/index.js.map +1 -0
  119. package/lib/components/Header/LogoIcon/index.mjs +3 -0
  120. package/lib/components/Header/LogoIcon/index.mjs.map +1 -0
  121. package/lib/components/Header/MenuItem/MenuItem.styles.d.ts +1 -1
  122. package/lib/components/Header/MenuItem/MenuItem.styles.js +3 -3
  123. package/lib/components/Header/MenuItem/MenuItem.styles.js.map +1 -1
  124. package/lib/components/Header/MenuItem/MenuItem.styles.mjs +3 -3
  125. package/lib/components/Header/MenuItem/MenuItem.styles.mjs.map +1 -1
  126. package/lib/components/Header/MenuItem/MenuItem.types.d.ts +1 -0
  127. package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.js +2 -2
  128. package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.js.map +1 -1
  129. package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.mjs +2 -2
  130. package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.mjs.map +1 -1
  131. package/lib/components/Header/Navigation/MicrositeMenu/MicrositeMenu.styles.d.ts +1 -1
  132. package/lib/components/Header/Navigation/MobileMenu/MobileMenu.styles.d.ts +1 -1
  133. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.d.ts +1 -1
  134. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js +110 -103
  135. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.js.map +1 -1
  136. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs +111 -104
  137. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.mjs.map +1 -1
  138. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.d.ts +9 -0
  139. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js +15 -1
  140. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.js.map +1 -1
  141. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs +13 -2
  142. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.styles.mjs.map +1 -1
  143. package/lib/components/Header/Navigation/ProMobileMenu/ProMobileMenu.types.d.ts +12 -6
  144. package/lib/components/Header/ProHeader/ProHeader.d.ts +9 -5
  145. package/lib/components/Header/ProHeader/ProHeader.js +260 -175
  146. package/lib/components/Header/ProHeader/ProHeader.js.map +1 -1
  147. package/lib/components/Header/ProHeader/ProHeader.mjs +261 -177
  148. package/lib/components/Header/ProHeader/ProHeader.mjs.map +1 -1
  149. package/lib/components/Header/ProHeader/ProHeader.styles.d.ts +30 -25
  150. package/lib/components/Header/ProHeader/ProHeader.styles.js +119 -66
  151. package/lib/components/Header/ProHeader/ProHeader.styles.js.map +1 -1
  152. package/lib/components/Header/ProHeader/ProHeader.styles.mjs +112 -65
  153. package/lib/components/Header/ProHeader/ProHeader.styles.mjs.map +1 -1
  154. package/lib/components/Header/translations/ar.json.js +4 -1
  155. package/lib/components/Header/translations/ar.json.js.map +1 -1
  156. package/lib/components/Header/translations/ar.json.mjs +4 -2
  157. package/lib/components/Header/translations/ar.json.mjs.map +1 -1
  158. package/lib/components/Header/translations/de.json.js +4 -1
  159. package/lib/components/Header/translations/de.json.js.map +1 -1
  160. package/lib/components/Header/translations/de.json.mjs +4 -2
  161. package/lib/components/Header/translations/de.json.mjs.map +1 -1
  162. package/lib/components/Header/translations/el.json.js +4 -1
  163. package/lib/components/Header/translations/el.json.js.map +1 -1
  164. package/lib/components/Header/translations/el.json.mjs +4 -2
  165. package/lib/components/Header/translations/el.json.mjs.map +1 -1
  166. package/lib/components/Header/translations/en.json.js +7 -1
  167. package/lib/components/Header/translations/en.json.js.map +1 -1
  168. package/lib/components/Header/translations/en.json.mjs +6 -2
  169. package/lib/components/Header/translations/en.json.mjs.map +1 -1
  170. package/lib/components/Header/translations/es.json.js +4 -1
  171. package/lib/components/Header/translations/es.json.js.map +1 -1
  172. package/lib/components/Header/translations/es.json.mjs +4 -2
  173. package/lib/components/Header/translations/es.json.mjs.map +1 -1
  174. package/lib/components/Header/translations/fr.json.js +4 -1
  175. package/lib/components/Header/translations/fr.json.js.map +1 -1
  176. package/lib/components/Header/translations/fr.json.mjs +4 -2
  177. package/lib/components/Header/translations/fr.json.mjs.map +1 -1
  178. package/lib/components/Header/translations/it.json.js +4 -1
  179. package/lib/components/Header/translations/it.json.js.map +1 -1
  180. package/lib/components/Header/translations/it.json.mjs +4 -2
  181. package/lib/components/Header/translations/it.json.mjs.map +1 -1
  182. package/lib/components/Header/translations/ja.json.js +4 -1
  183. package/lib/components/Header/translations/ja.json.js.map +1 -1
  184. package/lib/components/Header/translations/ja.json.mjs +4 -2
  185. package/lib/components/Header/translations/ja.json.mjs.map +1 -1
  186. package/lib/components/Header/translations/pt-BR.json.js +4 -1
  187. package/lib/components/Header/translations/pt-BR.json.js.map +1 -1
  188. package/lib/components/Header/translations/pt-BR.json.mjs +4 -2
  189. package/lib/components/Header/translations/pt-BR.json.mjs.map +1 -1
  190. package/lib/components/Header/translations/zh-Hans.json.js +4 -1
  191. package/lib/components/Header/translations/zh-Hans.json.js.map +1 -1
  192. package/lib/components/Header/translations/zh-Hans.json.mjs +4 -2
  193. package/lib/components/Header/translations/zh-Hans.json.mjs.map +1 -1
  194. package/lib/components/Header/translations/zh-Hant-TW.json.js +4 -1
  195. package/lib/components/Header/translations/zh-Hant-TW.json.js.map +1 -1
  196. package/lib/components/Header/translations/zh-Hant-TW.json.mjs +4 -2
  197. package/lib/components/Header/translations/zh-Hant-TW.json.mjs.map +1 -1
  198. package/lib/components/Hero/Hero.js +1 -1
  199. package/lib/components/Hero/Hero.js.map +1 -1
  200. package/lib/components/Hero/Hero.mjs +1 -1
  201. package/lib/components/Hero/Hero.mjs.map +1 -1
  202. package/lib/components/Hero/Hero.styles.d.ts +2 -2
  203. package/lib/components/HeroFadeGallery/HeroFadeGallery.styles.d.ts +1 -1
  204. package/lib/components/HeroVideo/HeroVideo.js +5 -5
  205. package/lib/components/HeroVideo/HeroVideo.js.map +1 -1
  206. package/lib/components/HeroVideo/HeroVideo.mjs +5 -5
  207. package/lib/components/HeroVideo/HeroVideo.mjs.map +1 -1
  208. package/lib/components/HowToUseSection/HowToUseSection.styles.d.ts +2 -2
  209. package/lib/components/ImageCarousel/ImageCarousel.js.map +1 -1
  210. package/lib/components/ImageCarousel/ImageCarousel.mjs.map +1 -1
  211. package/lib/components/LandingPagePro/LandingPagePro.js +4 -1
  212. package/lib/components/LandingPagePro/LandingPagePro.js.map +1 -1
  213. package/lib/components/LandingPagePro/LandingPagePro.mjs +4 -1
  214. package/lib/components/LandingPagePro/LandingPagePro.mjs.map +1 -1
  215. package/lib/components/LandingPagePro/LandingPagePro.styles.d.ts +1 -1
  216. package/lib/components/LandingPageSidebar/LandingPageSidebar.js +8 -8
  217. package/lib/components/LandingPageSidebar/LandingPageSidebar.js.map +1 -1
  218. package/lib/components/LandingPageSidebar/LandingPageSidebar.mjs +8 -8
  219. package/lib/components/LandingPageSidebar/LandingPageSidebar.mjs.map +1 -1
  220. package/lib/components/LayoutRenderer/LayoutRenderer.styles.d.ts +1 -1
  221. package/lib/components/LayoutRendererV1/LayoutRenderer.styles.d.ts +3 -3
  222. package/lib/components/LayoutRendererV2/LayoutRenderer.styles.d.ts +3 -3
  223. package/lib/components/LoaderDots/LoaderDots.d.ts +1 -1
  224. package/lib/components/LoaderDots/LoaderDots.js +3 -1
  225. package/lib/components/LoaderDots/LoaderDots.js.map +1 -1
  226. package/lib/components/LoaderDots/LoaderDots.mjs +3 -1
  227. package/lib/components/LoaderDots/LoaderDots.mjs.map +1 -1
  228. package/lib/components/LoaderDots/LoaderDots.styles.d.ts +2 -1
  229. package/lib/components/LoaderDots/LoaderDots.styles.js +11 -1
  230. package/lib/components/LoaderDots/LoaderDots.styles.js.map +1 -1
  231. package/lib/components/LoaderDots/LoaderDots.styles.mjs +11 -1
  232. package/lib/components/LoaderDots/LoaderDots.styles.mjs.map +1 -1
  233. package/lib/components/LoaderDots/LoaderDots.types.d.ts +2 -0
  234. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.js +4 -4
  235. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.js.map +1 -1
  236. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.mjs +4 -4
  237. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.mjs.map +1 -1
  238. package/lib/components/MeetUniFiVideoPlayer/MeetUniFiVideoPlayer.styles.d.ts +1 -1
  239. package/lib/components/MicrositeHero/MicrositeHero.js +2 -2
  240. package/lib/components/MicrositeHero/MicrositeHero.js.map +1 -1
  241. package/lib/components/MicrositeHero/MicrositeHero.mjs +2 -2
  242. package/lib/components/MicrositeHero/MicrositeHero.mjs.map +1 -1
  243. package/lib/components/MicrositeSectionWrap/MicrositeSectionWrap.styles.d.ts +1 -1
  244. package/lib/components/MicrositeVideoSlideshow/MicrositeVideoSlideshow.js +1 -1
  245. package/lib/components/MicrositeVideoSlideshow/MicrositeVideoSlideshow.mjs +1 -1
  246. package/lib/components/MicrositeVideoSlideshow/assets/pause.svg.js +1 -1
  247. package/lib/components/MicrositeVideoSlideshow/assets/pause.svg.mjs +2 -2
  248. package/lib/components/Microsites/Microsites.types.js.map +1 -1
  249. package/lib/components/Microsites/Microsites.types.mjs.map +1 -1
  250. package/lib/components/ModelCompareV3/ModelComparePropertyValueGridItem.js +37 -26
  251. package/lib/components/ModelCompareV3/ModelComparePropertyValueGridItem.js.map +1 -1
  252. package/lib/components/ModelCompareV3/ModelComparePropertyValueGridItem.mjs +37 -26
  253. package/lib/components/ModelCompareV3/ModelComparePropertyValueGridItem.mjs.map +1 -1
  254. package/lib/components/ModelCompareV3/ModelCompareV3.types.d.ts +1 -1
  255. package/lib/components/ModelCompareV3/StickyGrid/StickyGridItem.js +16 -8
  256. package/lib/components/ModelCompareV3/StickyGrid/StickyGridItem.js.map +1 -1
  257. package/lib/components/ModelCompareV3/StickyGrid/StickyGridItem.mjs +16 -8
  258. package/lib/components/ModelCompareV3/StickyGrid/StickyGridItem.mjs.map +1 -1
  259. package/lib/components/ModelCompareV3/StickyGrid/context.d.ts +3 -3
  260. package/lib/components/ModelCompareV3/StickyGrid/context.js.map +1 -1
  261. package/lib/components/ModelCompareV3/StickyGrid/context.mjs.map +1 -1
  262. package/lib/components/ModelCompareV3/assets/port.svg.js +1 -1
  263. package/lib/components/ModelCompareV3/assets/port.svg.mjs +2 -2
  264. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.js +4 -2
  265. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.js.map +1 -1
  266. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.mjs +4 -2
  267. package/lib/components/ModelCompareV3/data/products/cloudKeyEnterprise.mjs.map +1 -1
  268. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.js +2 -2
  269. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.js.map +1 -1
  270. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.mjs +2 -2
  271. package/lib/components/ModelCompareV3/data/products/cloudKeyG2Plus.mjs.map +1 -1
  272. package/lib/components/ModelCompareV3/data/products/express.js +3 -3
  273. package/lib/components/ModelCompareV3/data/products/express.js.map +1 -1
  274. package/lib/components/ModelCompareV3/data/products/express.mjs +3 -3
  275. package/lib/components/ModelCompareV3/data/products/express.mjs.map +1 -1
  276. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.js +4 -2
  277. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.js.map +1 -1
  278. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.mjs +4 -2
  279. package/lib/components/ModelCompareV3/data/products/gatewayEnterprise.mjs.map +1 -1
  280. package/lib/components/ModelCompareV3/data/products/gatewayLite.js +4 -2
  281. package/lib/components/ModelCompareV3/data/products/gatewayLite.js.map +1 -1
  282. package/lib/components/ModelCompareV3/data/products/gatewayLite.mjs +4 -2
  283. package/lib/components/ModelCompareV3/data/products/gatewayLite.mjs.map +1 -1
  284. package/lib/components/ModelCompareV3/data/products/gatewayMax.js +4 -2
  285. package/lib/components/ModelCompareV3/data/products/gatewayMax.js.map +1 -1
  286. package/lib/components/ModelCompareV3/data/products/gatewayMax.mjs +4 -2
  287. package/lib/components/ModelCompareV3/data/products/gatewayMax.mjs.map +1 -1
  288. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.js +4 -2
  289. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.js.map +1 -1
  290. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.mjs +4 -2
  291. package/lib/components/ModelCompareV3/data/products/gatewayProfessional.mjs.map +1 -1
  292. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.js +3 -1
  293. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.js.map +1 -1
  294. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.mjs +3 -1
  295. package/lib/components/ModelCompareV3/data/products/officialUniFiHosting.mjs.map +1 -1
  296. package/lib/components/ModelCompareV3/data/products/ucgMax.js +1 -1
  297. package/lib/components/ModelCompareV3/data/products/ucgMax.js.map +1 -1
  298. package/lib/components/ModelCompareV3/data/products/ucgMax.mjs +1 -1
  299. package/lib/components/ModelCompareV3/data/products/ucgMax.mjs.map +1 -1
  300. package/lib/components/ModelCompareV3/data/products/ucgUltra.js +3 -3
  301. package/lib/components/ModelCompareV3/data/products/ucgUltra.js.map +1 -1
  302. package/lib/components/ModelCompareV3/data/products/ucgUltra.mjs +3 -3
  303. package/lib/components/ModelCompareV3/data/products/ucgUltra.mjs.map +1 -1
  304. package/lib/components/ModelCompareV3/data/products/udmPro.js +3 -3
  305. package/lib/components/ModelCompareV3/data/products/udmPro.js.map +1 -1
  306. package/lib/components/ModelCompareV3/data/products/udmPro.mjs +3 -3
  307. package/lib/components/ModelCompareV3/data/products/udmPro.mjs.map +1 -1
  308. package/lib/components/ModelCompareV3/data/products/udmProMax.js +3 -3
  309. package/lib/components/ModelCompareV3/data/products/udmProMax.js.map +1 -1
  310. package/lib/components/ModelCompareV3/data/products/udmProMax.mjs +3 -3
  311. package/lib/components/ModelCompareV3/data/products/udmProMax.mjs.map +1 -1
  312. package/lib/components/ModelCompareV3/data/products/udmProSpecial.js +3 -3
  313. package/lib/components/ModelCompareV3/data/products/udmProSpecial.js.map +1 -1
  314. package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs +3 -3
  315. package/lib/components/ModelCompareV3/data/products/udmProSpecial.mjs.map +1 -1
  316. package/lib/components/ModelCompareV3/data/products/udr.js +5 -41
  317. package/lib/components/ModelCompareV3/data/products/udr.js.map +1 -1
  318. package/lib/components/ModelCompareV3/data/products/udr.mjs +5 -21
  319. package/lib/components/ModelCompareV3/data/products/udr.mjs.map +1 -1
  320. package/lib/components/ModelCompareV3/data/products/udw.js +3 -3
  321. package/lib/components/ModelCompareV3/data/products/udw.js.map +1 -1
  322. package/lib/components/ModelCompareV3/data/products/udw.mjs +3 -3
  323. package/lib/components/ModelCompareV3/data/products/udw.mjs.map +1 -1
  324. package/lib/components/ModelCompareV3/data/properties/redundantRj45Port.js +1 -1
  325. package/lib/components/ModelCompareV3/data/properties/redundantRj45Port.mjs +1 -1
  326. package/lib/components/PriceRangeSlider/PriceRangeSlider.types.d.ts +2 -2
  327. package/lib/components/PriceRangeSlider/PriceRangeSlider.types.js.map +1 -1
  328. package/lib/components/PriceRangeSlider/PriceRangeSlider.types.mjs.map +1 -1
  329. package/lib/components/ProductCard/ProductCard.js +1 -1
  330. package/lib/components/ProductCard/ProductCard.js.map +1 -1
  331. package/lib/components/ProductCard/ProductCard.mjs +2 -2
  332. package/lib/components/ProductCard/ProductCard.mjs.map +1 -1
  333. package/lib/components/ProductCardPopup/ProductCardPopup.js +2 -2
  334. package/lib/components/ProductCardPopup/ProductCardPopup.js.map +1 -1
  335. package/lib/components/ProductCardPopup/ProductCardPopup.mjs +2 -2
  336. package/lib/components/ProductCardPopup/ProductCardPopup.mjs.map +1 -1
  337. package/lib/components/ProductSectionNavigation/ProductSectionNavigation.styles.d.ts +1 -1
  338. package/lib/components/ProductSectionNavigationV2/ProductSectionNavigation.styles.d.ts +1 -1
  339. package/lib/components/ProductSectionTabs/ProductSectionTabs.js +6 -1
  340. package/lib/components/ProductSectionTabs/ProductSectionTabs.js.map +1 -1
  341. package/lib/components/ProductSectionTabs/ProductSectionTabs.mjs +6 -1
  342. package/lib/components/ProductSectionTabs/ProductSectionTabs.mjs.map +1 -1
  343. package/lib/components/ProductTechSpecs/ProductTechSpecs.styles.d.ts +2 -2
  344. package/lib/components/ProductWizard/ProductWizard.js +3 -3
  345. package/lib/components/ProductWizard/ProductWizard.js.map +1 -1
  346. package/lib/components/ProductWizard/ProductWizard.mjs +3 -3
  347. package/lib/components/ProductWizard/ProductWizard.mjs.map +1 -1
  348. package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.js +17 -4
  349. package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.js.map +1 -1
  350. package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.mjs +17 -4
  351. package/lib/components/ProductWizardFootnotes/ProductWizardFootnotes.mjs.map +1 -1
  352. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.js +4 -4
  353. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.js.map +1 -1
  354. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.mjs +4 -4
  355. package/lib/components/ResourceCalculatorV1/ComputeResourceCalculator/ComputeResourceCalculator.mjs.map +1 -1
  356. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/RecommendedPoeSwitches.js +1 -1
  357. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/RecommendedPoeSwitches.mjs +1 -1
  358. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/assets/port.svg.js +1 -1
  359. package/lib/components/ResourceCalculatorV1/PoeCalculator/components/RecommendedPoeSwitches/assets/port.svg.mjs +2 -2
  360. package/lib/components/ScrollWrapper/ScrollWrapper.d.ts +1 -1
  361. package/lib/components/ScrollWrapper/ScrollWrapper.js +16 -8
  362. package/lib/components/ScrollWrapper/ScrollWrapper.js.map +1 -1
  363. package/lib/components/ScrollWrapper/ScrollWrapper.mjs +16 -8
  364. package/lib/components/ScrollWrapper/ScrollWrapper.mjs.map +1 -1
  365. package/lib/components/ScrollWrapper/ScrollWrapper.styles.js +87 -64
  366. package/lib/components/ScrollWrapper/ScrollWrapper.styles.js.map +1 -1
  367. package/lib/components/ScrollWrapper/ScrollWrapper.styles.mjs +87 -64
  368. package/lib/components/ScrollWrapper/ScrollWrapper.styles.mjs.map +1 -1
  369. package/lib/components/ScrollWrapper/ScrollWrapper.types.d.ts +2 -0
  370. package/lib/components/Search/Input/Input.d.ts +1 -1
  371. package/lib/components/Search/Input/Input.js +4 -4
  372. package/lib/components/Search/Input/Input.js.map +1 -1
  373. package/lib/components/Search/Input/Input.mjs +4 -4
  374. package/lib/components/Search/Input/Input.mjs.map +1 -1
  375. package/lib/components/Search/Input/Input.styles.js +0 -1
  376. package/lib/components/Search/Input/Input.styles.js.map +1 -1
  377. package/lib/components/Search/Input/Input.styles.mjs +0 -1
  378. package/lib/components/Search/Input/Input.styles.mjs.map +1 -1
  379. package/lib/components/Search/Input/Input.types.d.ts +3 -2
  380. package/lib/components/StorageSliders/StorageSliders.context.js +17 -14
  381. package/lib/components/StorageSliders/StorageSliders.context.js.map +1 -1
  382. package/lib/components/StorageSliders/StorageSliders.context.mjs +17 -14
  383. package/lib/components/StorageSliders/StorageSliders.context.mjs.map +1 -1
  384. package/lib/components/StorybookUtils/StoryFaker.js.map +1 -1
  385. package/lib/components/StorybookUtils/StoryFaker.mjs.map +1 -1
  386. package/lib/components/VariantSelector/VariantSelector.js +4 -4
  387. package/lib/components/VariantSelector/VariantSelector.js.map +1 -1
  388. package/lib/components/VariantSelector/VariantSelector.mjs +4 -4
  389. package/lib/components/VariantSelector/VariantSelector.mjs.map +1 -1
  390. package/lib/components/VideoPlayerNew/VideoPlayer.js +14 -16
  391. package/lib/components/VideoPlayerNew/VideoPlayer.js.map +1 -1
  392. package/lib/components/VideoPlayerNew/VideoPlayer.mjs +14 -16
  393. package/lib/components/VideoPlayerNew/VideoPlayer.mjs.map +1 -1
  394. package/lib/components/VideoPlayerNew/assets/close.svg.js +1 -1
  395. package/lib/components/VideoPlayerNew/assets/close.svg.mjs +2 -2
  396. package/lib/components/VideoPlayerNew/assets/pause.svg.js +1 -1
  397. package/lib/components/VideoPlayerNew/assets/pause.svg.mjs +2 -2
  398. package/lib/constants/address.d.ts +1 -1
  399. package/lib/constants/address.js +34 -34
  400. package/lib/constants/address.js.map +1 -1
  401. package/lib/constants/address.mjs +34 -34
  402. package/lib/constants/address.mjs.map +1 -1
  403. package/lib/constants/postalCode.js +10 -10
  404. package/lib/constants/postalCode.js.map +1 -1
  405. package/lib/constants/postalCode.mjs +10 -10
  406. package/lib/constants/postalCode.mjs.map +1 -1
  407. package/lib/constants/proStoreCategories/mapping/filters.d.ts +16 -0
  408. package/lib/constants/proStoreCategories/mapping/filters.js +16 -0
  409. package/lib/constants/proStoreCategories/mapping/filters.js.map +1 -1
  410. package/lib/constants/proStoreCategories/mapping/filters.mjs +16 -0
  411. package/lib/constants/proStoreCategories/mapping/filters.mjs.map +1 -1
  412. package/lib/constants/proStoreCategories/mapping/index.d.ts +3 -2
  413. package/lib/constants/proStoreCategories/mapping/index.js +45 -51
  414. package/lib/constants/proStoreCategories/mapping/index.js.map +1 -1
  415. package/lib/constants/proStoreCategories/mapping/index.mjs +44 -49
  416. package/lib/constants/proStoreCategories/mapping/index.mjs.map +1 -1
  417. package/lib/constants/proStoreCategories/mapping/mapping.d.ts +5 -0
  418. package/lib/constants/proStoreCategories/mapping/redirects.js +18 -3
  419. package/lib/constants/proStoreCategories/mapping/redirects.js.map +1 -1
  420. package/lib/constants/proStoreCategories/mapping/redirects.mjs +18 -3
  421. package/lib/constants/proStoreCategories/mapping/redirects.mjs.map +1 -1
  422. package/lib/constants/proStoreCategories/mapping/unifi.d.ts +8 -9
  423. package/lib/constants/proStoreCategories/mapping/unifi.js +8 -9
  424. package/lib/constants/proStoreCategories/mapping/unifi.js.map +1 -1
  425. package/lib/constants/proStoreCategories/mapping/unifi.mjs +8 -9
  426. package/lib/constants/proStoreCategories/mapping/unifi.mjs.map +1 -1
  427. package/lib/constants/proStoreCategories/translations/ar.json.js +4 -3
  428. package/lib/constants/proStoreCategories/translations/ar.json.js.map +1 -1
  429. package/lib/constants/proStoreCategories/translations/ar.json.mjs +4 -3
  430. package/lib/constants/proStoreCategories/translations/ar.json.mjs.map +1 -1
  431. package/lib/constants/proStoreCategories/translations/de.json.js +4 -3
  432. package/lib/constants/proStoreCategories/translations/de.json.js.map +1 -1
  433. package/lib/constants/proStoreCategories/translations/de.json.mjs +4 -3
  434. package/lib/constants/proStoreCategories/translations/de.json.mjs.map +1 -1
  435. package/lib/constants/proStoreCategories/translations/el.json.js +4 -3
  436. package/lib/constants/proStoreCategories/translations/el.json.js.map +1 -1
  437. package/lib/constants/proStoreCategories/translations/el.json.mjs +4 -3
  438. package/lib/constants/proStoreCategories/translations/el.json.mjs.map +1 -1
  439. package/lib/constants/proStoreCategories/translations/en.json.js +3 -2
  440. package/lib/constants/proStoreCategories/translations/en.json.js.map +1 -1
  441. package/lib/constants/proStoreCategories/translations/en.json.mjs +3 -2
  442. package/lib/constants/proStoreCategories/translations/en.json.mjs.map +1 -1
  443. package/lib/constants/proStoreCategories/translations/es.json.js +4 -3
  444. package/lib/constants/proStoreCategories/translations/es.json.js.map +1 -1
  445. package/lib/constants/proStoreCategories/translations/es.json.mjs +4 -3
  446. package/lib/constants/proStoreCategories/translations/es.json.mjs.map +1 -1
  447. package/lib/constants/proStoreCategories/translations/fr.json.js +4 -3
  448. package/lib/constants/proStoreCategories/translations/fr.json.js.map +1 -1
  449. package/lib/constants/proStoreCategories/translations/fr.json.mjs +4 -3
  450. package/lib/constants/proStoreCategories/translations/fr.json.mjs.map +1 -1
  451. package/lib/constants/proStoreCategories/translations/it.json.js +4 -3
  452. package/lib/constants/proStoreCategories/translations/it.json.js.map +1 -1
  453. package/lib/constants/proStoreCategories/translations/it.json.mjs +4 -3
  454. package/lib/constants/proStoreCategories/translations/it.json.mjs.map +1 -1
  455. package/lib/constants/proStoreCategories/translations/ja.json.js +4 -3
  456. package/lib/constants/proStoreCategories/translations/ja.json.js.map +1 -1
  457. package/lib/constants/proStoreCategories/translations/ja.json.mjs +4 -3
  458. package/lib/constants/proStoreCategories/translations/ja.json.mjs.map +1 -1
  459. package/lib/constants/proStoreCategories/translations/pt-BR.json.js +4 -3
  460. package/lib/constants/proStoreCategories/translations/pt-BR.json.js.map +1 -1
  461. package/lib/constants/proStoreCategories/translations/pt-BR.json.mjs +4 -3
  462. package/lib/constants/proStoreCategories/translations/pt-BR.json.mjs.map +1 -1
  463. package/lib/constants/proStoreCategories/translations/zh-Hans.json.js +4 -3
  464. package/lib/constants/proStoreCategories/translations/zh-Hans.json.js.map +1 -1
  465. package/lib/constants/proStoreCategories/translations/zh-Hans.json.mjs +4 -3
  466. package/lib/constants/proStoreCategories/translations/zh-Hans.json.mjs.map +1 -1
  467. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.js +4 -3
  468. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.js.map +1 -1
  469. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.mjs +4 -3
  470. package/lib/constants/proStoreCategories/translations/zh-Hant-TW.json.mjs.map +1 -1
  471. package/lib/constants/proStoreFilters/mapping.d.ts +45 -3
  472. package/lib/constants/proStoreFilters/mapping.js +119 -9
  473. package/lib/constants/proStoreFilters/mapping.js.map +1 -1
  474. package/lib/constants/proStoreFilters/mapping.mjs +119 -9
  475. package/lib/constants/proStoreFilters/mapping.mjs.map +1 -1
  476. package/lib/constants/theme.js +4 -0
  477. package/lib/constants/theme.js.map +1 -1
  478. package/lib/constants/theme.mjs +4 -0
  479. package/lib/constants/theme.mjs.map +1 -1
  480. package/lib/contexts/MenuContext/context.js +28 -27
  481. package/lib/contexts/MenuContext/context.js.map +1 -1
  482. package/lib/contexts/MenuContext/context.mjs +28 -27
  483. package/lib/contexts/MenuContext/context.mjs.map +1 -1
  484. package/lib/contexts/MenuContext/mapping.js.map +1 -1
  485. package/lib/contexts/MenuContext/mapping.mjs.map +1 -1
  486. package/lib/helpers/ux.d.ts +8 -11
  487. package/lib/helpers/ux.js +15 -4
  488. package/lib/helpers/ux.js.map +1 -1
  489. package/lib/helpers/ux.mjs +15 -4
  490. package/lib/helpers/ux.mjs.map +1 -1
  491. package/lib/hooks/useScrollToY.js.map +1 -1
  492. package/lib/hooks/useScrollToY.mjs.map +1 -1
  493. package/lib/utils/collectionSlug.js +2 -2
  494. package/lib/utils/collectionSlug.js.map +1 -1
  495. package/lib/utils/collectionSlug.mjs +2 -2
  496. package/lib/utils/collectionSlug.mjs.map +1 -1
  497. package/lib/utils/errors.js.map +1 -1
  498. package/lib/utils/errors.mjs.map +1 -1
  499. package/lib/utils/measures.js +1 -0
  500. package/lib/utils/measures.js.map +1 -1
  501. package/lib/utils/measures.mjs +1 -0
  502. package/lib/utils/measures.mjs.map +1 -1
  503. package/lib/utils/money/format.js.map +1 -1
  504. package/lib/utils/money/format.mjs.map +1 -1
  505. package/lib/utils/money/misc.js +1 -1
  506. package/lib/utils/money/misc.js.map +1 -1
  507. package/lib/utils/money/misc.mjs +1 -1
  508. package/lib/utils/money/misc.mjs.map +1 -1
  509. package/lib/utils/nextjs/ssr/transform-css-module.js.map +1 -1
  510. package/lib/utils/nextjs/ssr/transform-css-module.mjs.map +1 -1
  511. package/lib/utils/number.js.map +1 -1
  512. package/lib/utils/number.mjs.map +1 -1
  513. package/lib/utils/product.js +4 -4
  514. package/lib/utils/product.js.map +1 -1
  515. package/lib/utils/product.mjs +4 -4
  516. package/lib/utils/product.mjs.map +1 -1
  517. package/lib/utils/tags.js +2 -2
  518. package/lib/utils/tags.js.map +1 -1
  519. package/lib/utils/tags.mjs +2 -2
  520. package/lib/utils/tags.mjs.map +1 -1
  521. package/package.json +1 -1
  522. package/lib/assets/icons/menu/icon-globe.svg.js.map +0 -1
  523. package/lib/assets/icons/menu/icon-globe.svg.mjs +0 -3
  524. package/lib/assets/icons/menu/icon-globe.svg.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"measures.mjs","sources":["../../src/utils/measures.ts"],"sourcesContent":["import { Big } from \"big.js\";\nimport type {\n LengthSystems,\n LengthUnits,\n MassSystems,\n MassUnits,\n} from \"convert-units\";\nimport configureMeasurements, { length, mass } from \"convert-units\";\nimport type { Calculator, ComparisonOperator, Transformer } from \"dinero.js\";\nimport { createDinero, toFormat } from \"dinero.js\";\n\nimport { UnitSystem } from \"../types\";\nimport { assert, assertUnreachable } from \"./errors\";\n\n// Measures: The names of the measures being used\ntype Measures = \"length\" | \"mass\";\n// Systems: The systems being used across all measures\ntype Systems = LengthSystems | MassSystems;\n// Units: All the units across all measures and their systems\ntype Units = LengthUnits | MassUnits;\n\nexport const convert = configureMeasurements<Measures, Systems, Units>({\n length,\n mass,\n});\n\nconst calculator: Calculator<Big> = {\n add: (a, b) => a.plus(b),\n compare: (a, b) => a.cmp(b) as unknown as ComparisonOperator,\n decrement: (v) => v.minus(new Big(1)),\n increment: (v) => v.plus(new Big(1)),\n integerDivide: (a, b) => a.div(b).round(0, Big.roundDown),\n modulo: (a, b) => a.mod(b),\n multiply: (a, b) => a.times(b),\n power: (a, b) => a.pow(Number(b)),\n subtract: (a, b) => a.minus(b),\n zero: () => new Big(0),\n toNumber: () => NaN,\n};\n\nconst dineroBigint = createDinero({ calculator });\n\n// type ConvertMassFromTo =\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.Kg; to: Unit. }\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.G; to: Unit.Kg }\n// export const convertMass = (value: number, {from, to}: ConvertMassFromTo) => {\n// return convert(value).from(from).to(to)\n// }\n\nconst DINERO_WEIGHT_G = {\n code: \"WEIGHT_G\",\n base: Big(10),\n exponent: Big(0),\n};\nconst DINERO_WEIGHT_OZ = {\n code: \"WEIGHT_OZ\",\n base: Big(10),\n exponent: Big(6),\n};\n\ntype TransformerOptions = Parameters<Transformer<Big>>[0];\nconst transformer = ({ currency, dineroObject }: TransformerOptions) => {\n const exponent = currency.exponent;\n const multiplier = Big(0.1).pow(exponent.toNumber());\n\n const jsonObject = dineroObject.toJSON();\n const formattedWeight = jsonObject.amount\n .mul(multiplier)\n .toFixed(exponent.toNumber());\n\n return formattedWeight.toString();\n};\n\n/**\n * In database we store weight in \"weird\" format.\n * For metric we store weight in grams as is.\n * For imperial we store weight in oz with \"virtual scale/exponent\" => 6.\n * e.g. 1_000_000 => '1'\n * e.g. 300_000 => '0.3'\n *\n * Database weight is stored either in g or oz\n */\nexport const transformDatabaseWeightToFormat = (\n databaseWeight: string,\n system: UnitSystem,\n): string => {\n switch (system) {\n case UnitSystem.Metric:\n return toFormat(\n dineroBigint({\n amount: Big(databaseWeight),\n currency: DINERO_WEIGHT_G,\n }),\n transformer,\n );\n case UnitSystem.Imperial: {\n return toFormat(\n dineroBigint({\n amount: Big(databaseWeight),\n currency: DINERO_WEIGHT_OZ,\n }),\n transformer,\n );\n }\n default:\n assertUnreachable(system);\n }\n};\n\n/**\n * Executes transformDatabaseWeightToFormat and returns it as number if safe integer\n *\n * Database weight is stored either in g or oz\n */\nexport const transformDatabaseWeightToNumber = (\n databaseWeight: string,\n system: UnitSystem,\n): number => {\n const formattedBig = Big(\n transformDatabaseWeightToFormat(databaseWeight, system),\n );\n\n assert(\n formattedBig.lte(Number.MAX_SAFE_INTEGER),\n \"Weight is not in safe integer range\",\n );\n return parseFloat(formattedBig.toString());\n};\n\n/**\n * Prepares floating number to be stored in database as normalized bigint\n *\n * Database weights are stored either in g or oz\n */\nexport const transformNumberToDatabaseWeight = (\n numberWeight: number,\n system: UnitSystem,\n): string => {\n switch (system) {\n case UnitSystem.Metric: {\n /**\n * convert(1).from(oz).to(g) is 28.34952g.\n * We are stripping sub-gram measures, because database is storing grams\n */\n const numberWeightInt = parseInt(numberWeight.toFixed(0));\n\n assert(\n !!Number.isSafeInteger(numberWeightInt),\n \"Number is not safe integer\",\n );\n\n return numberWeightInt.toString();\n }\n case UnitSystem.Imperial: {\n const weightBig = Big(numberWeight);\n const multiplier = Big(10).pow(DINERO_WEIGHT_OZ.exponent.toNumber());\n return weightBig.mul(multiplier).toFixed(0);\n }\n default:\n assertUnreachable(system);\n }\n};\n\n/**\n * Shorthand function to transform weight number to formatted string.\n *\n * ! Use only with base weights g/oz\n */\nexport const transformBaseWeightNumberToFormat = (\n databaseWeight: number,\n system: UnitSystem,\n): string =>\n transformDatabaseWeightToFormat(\n transformNumberToDatabaseWeight(databaseWeight, system),\n system,\n );\n"],"names":["convert","configureMeasurements","length","mass","calculator","add","a","b","plus","compare","cmp","decrement","v","minus","Big","increment","integerDivide","div","round","roundDown","modulo","mod","multiply","times","power","pow","Number","subtract","zero","toNumber","NaN","dineroBigint","createDinero","DINERO_WEIGHT_G","code","base","exponent","DINERO_WEIGHT_OZ","transformer","currency","dineroObject","multiplier","jsonObject","toJSON","formattedWeight","amount","mul","toFixed","toString","transformDatabaseWeightToFormat","databaseWeight","system","UnitSystem","Metric","toFormat","Imperial","assertUnreachable","transformDatabaseWeightToNumber","formattedBig","assert","lte","MAX_SAFE_INTEGER","parseFloat","transformNumberToDatabaseWeight","numberWeight","numberWeightInt","parseInt","isSafeInteger","weightBig","transformBaseWeightNumberToFormat"],"mappings":";;;;;;;AAqBO,MAAMA,UAAUC,qBAAgD,CAAA;EACrEC,MAAA;EACAC;AACF,CAAC,CAAA;AAED,MAAMC,UAA8B,GAAA;EAClCC,KAAKA,CAACC,CAAA,EAAGC,CAAM,KAAAD,CAAA,CAAEE,KAAKD,CAAC,CAAA;EACvBE,SAASA,CAACH,CAAA,EAAGC,CAAM,KAAAD,CAAA,CAAEI,IAAIH,CAAC,CAAA;EAC1BI,SAAA,EAAYC,CAAM,IAAAA,CAAA,CAAEC,MAAM,IAAIC,GAAA,CAAI,CAAC,CAAC,CAAA;EACpCC,SAAA,EAAYH,CAAM,IAAAA,CAAA,CAAEJ,KAAK,IAAIM,GAAA,CAAI,CAAC,CAAC,CAAA;EACnCE,aAAA,EAAeA,C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;IACA,KAAKI,WAAWG,QAAU;MAAA;QAClB,MAAAa,SAAA,GAAYtD,IAAIkD,YAAY,CAAA;QAC5B,MAAAvB,UAAA,GAAa3B,IAAI,EAAE,CAAA,CAAEW,IAAIY,gBAAiB,CAAAD,QAAA,CAASP,UAAU,CAAA;QACnE,OAAOuC,SAAU,CAAAtB,GAAA,CAAIL,UAAU,CAAA,CAAEM,QAAQ,CAAC,CAAA;MAC5C;IACA;MACES,iBAAA,CAAkBL,MAAM,CAAA;EAC5B;AACF,CAAA;AAOa,MAAAkB,iCAAA,GAAoCA,CAC/CnB,cAAA,EACAC,MAEA,KAAAF,+BAAA,CACEc,+BAAA,CAAgCb,gBAAgBC,MAAM,CAAA,EACtDA,MACF,CAAA;"}
1
+ {"version":3,"file":"measures.mjs","sources":["../../src/utils/measures.ts"],"sourcesContent":["import { Big } from \"big.js\";\nimport type {\n LengthSystems,\n LengthUnits,\n MassSystems,\n MassUnits,\n} from \"convert-units\";\nimport configureMeasurements, { length, mass } from \"convert-units\";\nimport type { Calculator, ComparisonOperator, Transformer } from \"dinero.js\";\nimport { createDinero, toFormat } from \"dinero.js\";\n\nimport { UnitSystem } from \"../types\";\nimport { assert, assertUnreachable } from \"./errors\";\n\n// Measures: The names of the measures being used\ntype Measures = \"length\" | \"mass\";\n// Systems: The systems being used across all measures\ntype Systems = LengthSystems | MassSystems;\n// Units: All the units across all measures and their systems\ntype Units = LengthUnits | MassUnits;\n\nexport const convert = configureMeasurements<Measures, Systems, Units>({\n length,\n mass,\n});\n\nconst calculator: Calculator<Big> = {\n add: (a, b) => a.plus(b),\n compare: (a, b) => a.cmp(b) as unknown as ComparisonOperator,\n decrement: (v) => v.minus(new Big(1)),\n increment: (v) => v.plus(new Big(1)),\n integerDivide: (a, b) => a.div(b).round(0, Big.roundDown),\n modulo: (a, b) => a.mod(b),\n multiply: (a, b) => a.times(b),\n power: (a, b) => a.pow(Number(b)),\n subtract: (a, b) => a.minus(b),\n zero: () => new Big(0),\n toNumber: () => NaN,\n};\n\nconst dineroBigint = createDinero({ calculator });\n\n// type ConvertMassFromTo =\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.Kg; to: Unit. }\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.G; to: Unit.Kg }\n// | { from: Unit.G; to: Unit.Kg }\n// export const convertMass = (value: number, {from, to}: ConvertMassFromTo) => {\n// return convert(value).from(from).to(to)\n// }\n\nconst DINERO_WEIGHT_G = {\n code: \"WEIGHT_G\",\n // eslint-disable-next-line sonarjs/inconsistent-function-call\n base: Big(10),\n exponent: Big(0),\n};\nconst DINERO_WEIGHT_OZ = {\n code: \"WEIGHT_OZ\",\n base: Big(10),\n exponent: Big(6),\n};\n\ntype TransformerOptions = Parameters<Transformer<Big>>[0];\nconst transformer = ({ currency, dineroObject }: TransformerOptions) => {\n const exponent = currency.exponent;\n const multiplier = Big(0.1).pow(exponent.toNumber());\n\n const jsonObject = dineroObject.toJSON();\n const formattedWeight = jsonObject.amount\n .mul(multiplier)\n .toFixed(exponent.toNumber());\n\n return formattedWeight.toString();\n};\n\n/**\n * In database we store weight in \"weird\" format.\n * For metric we store weight in grams as is.\n * For imperial we store weight in oz with \"virtual scale/exponent\" => 6.\n * e.g. 1_000_000 => '1'\n * e.g. 300_000 => '0.3'\n *\n * Database weight is stored either in g or oz\n */\nexport const transformDatabaseWeightToFormat = (\n databaseWeight: string,\n system: UnitSystem,\n): string => {\n switch (system) {\n case UnitSystem.Metric:\n return toFormat(\n dineroBigint({\n amount: Big(databaseWeight),\n currency: DINERO_WEIGHT_G,\n }),\n transformer,\n );\n case UnitSystem.Imperial: {\n return toFormat(\n dineroBigint({\n amount: Big(databaseWeight),\n currency: DINERO_WEIGHT_OZ,\n }),\n transformer,\n );\n }\n default:\n assertUnreachable(system);\n }\n};\n\n/**\n * Executes transformDatabaseWeightToFormat and returns it as number if safe integer\n *\n * Database weight is stored either in g or oz\n */\nexport const transformDatabaseWeightToNumber = (\n databaseWeight: string,\n system: UnitSystem,\n): number => {\n const formattedBig = Big(\n transformDatabaseWeightToFormat(databaseWeight, system),\n );\n\n assert(\n formattedBig.lte(Number.MAX_SAFE_INTEGER),\n \"Weight is not in safe integer range\",\n );\n return parseFloat(formattedBig.toString());\n};\n\n/**\n * Prepares floating number to be stored in database as normalized bigint\n *\n * Database weights are stored either in g or oz\n */\nexport const transformNumberToDatabaseWeight = (\n numberWeight: number,\n system: UnitSystem,\n): string => {\n switch (system) {\n case UnitSystem.Metric: {\n /**\n * convert(1).from(oz).to(g) is 28.34952g.\n * We are stripping sub-gram measures, because database is storing grams\n */\n const numberWeightInt = parseInt(numberWeight.toFixed(0));\n\n assert(\n !!Number.isSafeInteger(numberWeightInt),\n \"Number is not safe integer\",\n );\n\n return numberWeightInt.toString();\n }\n case UnitSystem.Imperial: {\n const weightBig = Big(numberWeight);\n const multiplier = Big(10).pow(DINERO_WEIGHT_OZ.exponent.toNumber());\n return weightBig.mul(multiplier).toFixed(0);\n }\n default:\n assertUnreachable(system);\n }\n};\n\n/**\n * Shorthand function to transform weight number to formatted string.\n *\n * ! Use only with base weights g/oz\n */\nexport const transformBaseWeightNumberToFormat = (\n databaseWeight: number,\n system: UnitSystem,\n): string =>\n transformDatabaseWeightToFormat(\n transformNumberToDatabaseWeight(databaseWeight, system),\n system,\n );\n"],"names":["convert","configureMeasurements","length","mass","calculator","add","a","b","plus","compare","cmp","decrement","v","minus","Big","increment","integerDivide","div","round","roundDown","modulo","mod","multiply","times","power","pow","Number","subtract","zero","toNumber","NaN","dineroBigint","createDinero","DINERO_WEIGHT_G","code","base","exponent","DINERO_WEIGHT_OZ","transformer","currency","dineroObject","multiplier","jsonObject","toJSON","formattedWeight","amount","mul","toFixed","toString","transformDatabaseWeightToFormat","databaseWeight","system","UnitSystem","Metric","toFormat","Imperial","assertUnreachable","transformDatabaseWeightToNumber","formattedBig","assert","lte","MAX_SAFE_INTEGER","parseFloat","transformNumberToDatabaseWeight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AAA,CAAgCC,gBAAgBC,MAAM,CAAA,CACxD;EAEAQ,MAAA,CACED,YAAA,CAAaE,GAAI,CAAAlC,MAAA,CAAOmC,gBAAgB,CAAA,EACxC,qCAAA,CACF;EACO,OAAAC,UAAA,CAAWJ,YAAa,CAAAV,QAAA,CAAA,CAAU,CAAA;AAC3C,CAAA;AAOa,MAAAe,+BAAA,GAAkCA,CAC7CC,YAAA,EACAb,MACW,KAAA;EACX,QAAQA,MAAQ;IACd,KAAKC,WAAWC,MAAQ;MAAA;QAKtB,MAAMY,eAAkB,GAAAC,QAAA,CAASF,YAAa,CAAAjB,OAAA,CAAQ,CAAC,CAAC,CAAA;QAExDY,MAAA,CACE,CAAC,CAACjC,MAAO,CAAAyC,aAAA,CAAcF,eAAe,CAAA,EACtC,4BAAA,CACF;QAEA,OAAOA,gBAAgBjB,QAAS,EAAA;MAClC;IACA,KAAKI,WAAWG,QAAU;MAAA;QAClB,MAAAa,SAAA,GAAYtD,IAAIkD,YAAY,CAAA;QAC5B,MAAAvB,UAAA,GAAa3B,IAAI,EAAE,CAAA,CAAEW,IAAIY,gBAAiB,CAAAD,QAAA,CAASP,UAAU,CAAA;QACnE,OAAOuC,SAAU,CAAAtB,GAAA,CAAIL,UAAU,CAAA,CAAEM,QAAQ,CAAC,CAAA;MAC5C;IACA;MACES,iBAAA,CAAkBL,MAAM,CAAA;EAC5B;AACF,CAAA;AAOa,MAAAkB,iCAAA,GAAoCA,CAC/CnB,cAAA,EACAC,MAEA,KAAAF,+BAAA,CACEc,+BAAA,CAAgCb,gBAAgBC,MAAM,CAAA,EACtDA,MACF,CAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"format.js","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,SAAAA,CAAAA,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,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DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,SAAO,CAAAA,MAAA,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;;;;"}
1
+ {"version":3,"file":"format.js","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n // eslint-disable-next-line sonarjs/deprecation\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,SAAAA,CAAAA,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EACT;EAEYA,SAAA,GAAA,IAAIC,IAAK,CAAAC,YAAA,CAAaJ,MAAQ,EAAA;IACxCK,KAAO,EAAA,UAAA;IACPC,QAAU,EAAAZ,YAAA;IAAA;AAAA;AAAA;AAAA;AAAA;IAMVa,YAAc,EAAA,UAAA;IACdC,eAAiB,EAAA;EAAA,CAClB,CAAA;EACsBX,sBAAA,CAAAY,GAAA,CAAIR,UAAUC,SAAS,CAAA;EAEvC,OAAAA,SAAA;AACT,CAAA;AAoCgB,SAAAQ,cAAAA,CACdC,MACA,EAAAX,MAAA,EACAY,OACQ,EAAA;EACR,OAAOC,mBAASF,MAAQ,EAAA,CAAC;IAAEG,MAAA;IAAQR;GAAe,KAAA;IAChD,MAAMJ,SAAY,GAAAH,oBAAA,CAAqBC,MAAQ,EAAA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,MAAA,IAAWJ,eAAe,EAAI,EAAA;UACrB,OAAAE,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAME,qBAAqB,CAAA;QAAA,CACvD,MAAA,IAAWL,eAAe,EAAI,EAAA;UACrB,OAAAE,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;QAAA,CACnC,MAAA;UACE,OAAAJ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMI,eAAe,CAAA;QACjD;MACF;IACA;MAAS;QAEH,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QACT;QAEA,MAAMe,mCAAmCC,SAAAA,CAAAA,mBAAoB,CAAAjD,GAAA,CAC3DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,SAAO,CAAAA,MAAA,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,gBAAA,CAAYR,KAAO,EAAAS,SAAA,CAAAA,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAAA,CAAA;AACpE,CAAA;AAKA,MAAMG,sBAAA,GAAA,mBAA6BC,GAA+B,EAAA;AAOlE,MAAMC,oBAAA,GAAuBA,CAC3BC,MAAA,EACAN,YACsB,KAAA;EACtB,MAAMO,QAAW,GAAA,GAAGD,MAAM,IAAIN,YAAY,EAAA;EAEtC,IAAAQ,SAAA,GAAYL,sBAAuB,CAAAD,GAAA,CAAIK,QAAQ,CAAA;EACnD,IAAIC,SAAW,EAAA;IACN,OAAAA,SAAA;EACT;EAEYA,S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ACF;AACF,CAAA;AAMa,MAAAgB,aAAA,GAAiBC,KAAsB,IAAA;EAC5C,MAAAC,SAAA,GAAYD,MAAME,MAAO,EAAA;EAEvB,QAAAD,SAAA,CAAUxB,SAASS,IAAM;IAAA;IAE/B,KAAKiB,GAAI,CAAAjB,IAAA;IACT,KAAKkB,GAAI,CAAAlB,IAAA;IACT,KAAKmB,IAAInB,IAAM;MAAA;QACP,MAAAoB,YAAA,GAAeC,OAAOP,KAAK,CAAA;QAEjC,IAAIM,eAAe,EAAI,EAAA;UACd,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMC,oBAAoB,CAAA;QAAA,CACtD,MAAA,IAAWJ,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAME,qBAAqB,CAAA;QAAA,CACvD,MAAA,IAAWL,eAAe,EAAI,EAAA;UACrB,OAAAE,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;QAAA,CACnC,MAAA;UACE,OAAAJ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMI,eAAe,CAAA;QACjD;MACF;IACA;MAAS;QAEH,IAAA,CAACC,WAAY,CAAAd,KAAK,CAAG,EAAA;UAChB,OAAAA,KAAA;QACT;QAEA,MAAMe,mCAAmCC,mBAAoB,CAAAjD,GAAA,CAC3DkC,UAAUxB,QAAS,CAAAS,IAAA,CACrB;QAGA,IACE6B,gCAAoC,IAAA,IAAA,IACpCR,MAAO,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;"}
1
+ {"version":3,"file":"format.mjs","sources":["../../../src/utils/money/format.ts"],"sourcesContent":["import { CAD, EUR, GBP } from \"@dinero.js/currencies\";\nimport { hasSubUnits, toFormat, toUnit } from \"dinero.js\";\n\nimport type { Currency, Nullish } from \"../../types\";\nimport { assert } from \"../errors\";\nimport {\n localizedCurrencyLookup,\n prettifyPriceLookup,\n Round,\n} from \"./constants\";\nimport { getDinero, roundDinero } from \"./misc\";\nimport type { Dino, LocalizedCurrency, Money } from \"./types\";\n\nexport const getLocalizedCurrency = (\n currencyCode: Nullish<Currency>,\n): LocalizedCurrency | undefined => {\n return currencyCode ? localizedCurrencyLookup.get(currencyCode) : undefined;\n};\n\n// #############################################################################\n// Formatter\n// #############################################################################\nconst currencyFormatterCache = new Map<string, Intl.NumberFormat>();\n/**\n * Function to get a Int.NumberFormat instance that can be reused to format currency over using\n * `Number.toLocaleString(...)` function, which makes more sense to use as we usually just display 1 or 2 currencies\n * MAX, so reusing the formatted makes a lot of sense\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#performance\n */\nconst getCurrencyFormatter = (\n locale: string,\n currencyCode: string,\n): Intl.NumberFormat => {\n const cacheKey = `${locale}_${currencyCode}`;\n\n let formatter = currencyFormatterCache.get(cacheKey);\n if (formatter) {\n return formatter;\n }\n\n formatter = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: currencyCode,\n /**\n * Explicitly define default behavior - just in case some runtime overrides it\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay\n */\n currencySign: \"standard\",\n currencyDisplay: \"symbol\",\n });\n currencyFormatterCache.set(cacheKey, formatter);\n\n return formatter;\n};\n\nexport type FormatPriceOptions = {\n /**\n * Optionally remove trailing zeroes (only if all of them are 0)\n * @default false\n * @example\n * \"420,66 €\" => \"420,66 €\"\n * \"420,60 €\" => \"420,60 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeTrailingZeros?: boolean;\n /**\n * Optionally return currency rounded down to the nearest dollar-equivalent of a the given currency. Doesn't apply any\n * rounding just \"trims\" end decimal values\n *\n * ! Only use for display purposes where monetary precision is not required!\n *\n * @default false\n * @example\n * \"420,66 €\" => \"420 €\"\n * \"420,60 €\" => \"420 €\"\n * \"420,00 €\" => \"420 €\"\n */\n removeFractions?: boolean;\n};\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * Based on:\n * @see https://v2.dinerojs.com/docs/guides/formatting-in-a-multilingual-site#building-a-custom-internationalization-formatter\n * @protected\n * @deprecated Use `formatPrice` instead as this functions is for INTERNAL USE ONLY! (function not actual deprecated,\n * just marked so it discourages usage of it)\n */\nexport function formatPriceRaw(\n dinero: Dino,\n locale: string,\n options?: FormatPriceOptions,\n): string {\n return toFormat(dinero, ({ amount, currency }) => {\n const formatter = getCurrencyFormatter(locale, currency.code);\n const formatted = formatter.format(amount);\n\n return options?.removeFractions || options?.removeTrailingZeros\n ? /**\n * Regex to handle complex removing trailing zeros from currency\n * - Dynamically create regex based on currency as their exponent changes\n * - Also handles some currencies (e.g. EUR) having trailing currency symbol\n *\n * TODO: improve how we detect \"decimal separator\" for formatted currency, at least right now we have tests for it and doesn't seem like an issue\n */\n formatted.replace(\n // For some reason `\\.` need to be double-escaped `\\\\` when creating the regex from template string\n new RegExp(\n `(\\\\.|,)${\n // Depending options remove all trailing digits or just zeros, this way we don't need to do any rounding\n options?.removeFractions ? \"\\\\d\" : 0\n }{0,${currency.exponent}}(\\\\s\\\\D)?$`,\n ),\n // In the replaced using \"last capture group\" (if-exists) so we restore the trailing currency sign\n \"$2\",\n )\n : formatted;\n });\n}\n\n/**\n * Currency formatter based on dinero currency types and browser internationalizing functions\n *\n * In reality just a wrapper around `formatPriceRaw` that does the real formatting\n */\nexport const formatPrice = (\n money: Money,\n options?: FormatPriceOptions,\n): string => {\n const localizedCurrency = getLocalizedCurrency(money.currency);\n assert(!!localizedCurrency, `Currency ${money.currency} not supported`);\n\n // eslint-disable-next-line sonarjs/deprecation\n return formatPriceRaw(\n getDinero(money.amount, money.currency),\n localizedCurrency.locale,\n options,\n );\n};\n\n/**\n * Prettify numbers depending on the currency using rounding down.\n * ! Should only be used to prettify storefront product prices after currency conversion but nothing else !\n */\nexport const prettifyTotal = (total: Dino): Dino => {\n const totalJson = total.toJSON();\n\n switch (totalJson.currency.code) {\n // @see: https://ubiquiti.atlassian.net/browse/NEP-3846\n case EUR.code:\n case GBP.code:\n case CAD.code: {\n const totalAsFloat = toUnit(total);\n\n if (totalAsFloat < 10) {\n return roundDinero(total, Round.PrettifyDecimalCents);\n } else if (totalAsFloat < 20) {\n return roundDinero(total, Round.PrettifyHalfUnitCents);\n } else if (totalAsFloat < 50) {\n return roundDinero(total, Round.Prettify);\n } else {\n return roundDinero(total, Round.PrettifyFull059);\n }\n }\n default: {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const minValueInclusiveToRoundDownFrom = prettifyPriceLookup.get(\n totalJson.currency.code,\n );\n\n // Don't round if currency unsupported or value is below min threshold\n if (\n minValueInclusiveToRoundDownFrom == null ||\n toUnit(total) < minValueInclusiveToRoundDownFrom\n ) {\n return total;\n }\n\n return roundDinero(total, Round.Prettify);\n }\n }\n};\n"],"names":["getLocalizedCurrency","currencyCode","localizedCurrencyLookup","get","currencyFormatterCache","Map","getCurrencyFormatter","locale","cacheKey","formatter","Intl","NumberFormat","style","currency","currencySign","currencyDisplay","set","formatPriceRaw","dinero","options","toFormat","amount","code","formatted","format","removeFractions","removeTrailingZeros","replace","RegExp","exponent","formatPrice","money","localizedCurrency","assert","getDinero","prettifyTotal","total","totalJson","toJSON","EUR","GBP","CAD","totalAsFloat","toUnit","roundDinero","Round","PrettifyDecimalCents","PrettifyHalfUnitCents","Prettify","PrettifyFull059","hasSubUnits","minValueInclusiveToRoundDownFrom","prettifyPriceLookup"],"mappings":";;;;;;AAaa,MAAAA,oBAAA,GACXC,YACkC,IAAA;EAClC,OAAOA,YAAe,GAAAC,uBAAA,CAAwBC,GAAI,CAAAF,YAAY,CAAI,GAAA,KAA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A,IACpCR,MAAO,CAAAP,KAAK,IAAIe,gCAChB,EAAA;UACO,OAAAf,KAAA;QACT;QAEO,OAAAQ,WAAA,CAAYR,KAAO,EAAAS,KAAA,CAAMG,QAAQ,CAAA;MAC1C;EACF;AACF,CAAA;"}
@@ -88,7 +88,7 @@ const money = dinero2 => {
88
88
  currency: parseCurrencyCode(currency2.code)
89
89
  };
90
90
  };
91
- const addMany = (addends, defaultCurrency) => [...addends, getDinero(0, defaultCurrency)].reduce(dinero_js.add);
91
+ const addMany = (addends, defaultCurrency) => addends.reduce(dinero_js.add, getDinero(0, defaultCurrency));
92
92
  const subtractMany = (subtractions, defaultCurrency) => [...subtractions, getDinero(0, defaultCurrency)].reduce(dinero_js.subtract);
93
93
  const stringAmountToDinero = (price, currency2) =>
94
94
  // FIXME: parseFloat seems dangerous O_O
@@ -1 +1 @@
1
- {"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","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CAAEC,OAAOI,SAAAA,CAAAA,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAACC,KAAerD,EAAAA,SAAAA;AAAA;AAElDqB,kBAAmB,CAAAiC,UAAA,CAAWD,KAAK,CAAA,EAAGrD,SAAQ,CAAA;AAUnC,MAAAE,WAAA,GAAcA,CAACe,OAAAA,EAAcsC,UAAiC,KAAA;EACnE,MAAAC,gBAAA,GAAmBpC,iBAAOH,OAAQ,EAAA;IAAEwC,QAAQ,CAAG;IAAAC,KAAA,EAAOH;GAAY,CAAA;EAElE,MAAAI,QAAA,GAAWvB,qBAAWnB,OAAM,CAAA;EAElC,OAAOA,QAAO2C,MAAO,CAAA;IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;IAOnB1C,QAAQ2C,IAAK,CAAAH,KAAA,CACXF,gBAAmB,GAAAG,QAAA,CAAS3D,QAAS,CAAAiC,IAAA,IAAQ0B,SAAS3D,QAAS,CAAA6B,QACjE,CAAA;IACA7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"misc.js","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n addends.reduce(add, getDinero(0, defaultCurrency));\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n // eslint-disable-next-line sonarjs/reduce-initial-value\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,SAAAA,CAAAA,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,SAAA,CAAAA,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,MAAAM,iBAAA,GAAqBH,SAAqC,IAAA;EAC/D,MAAAI,cAAA,GAAiBC,YAAAA,CAAAA,sBAAuB,CAAAN,GAAA,CAAIC,SAAQ,CAAA;EAC1DM,MAAA,CAAAA,MAAA,CAAO,CAAC,CAACF,cAAgB,EAAA,0BAA0BJ,SAAQ,GAAG,CAAA;EACvD,OAAAI,cAAA;AACT,CAAA;AAWa,MAAAG,iBAAA,GAAqBN,IAA2B,IAAA;EAC3D,MAAMO,cAAiB,GAAAC,MAAA,CAAAA,UAAA,CAAWR,IAAK,CAAAS,WAAA,CAAa,CAAA,CAAA;EACpDJ,MAAA,CAAAA,MAAA,CACEK,YAAA,CAAAA,cAAA,CAAeC,IAAIJ,cAAc,CAAA,EACjC,0BAA0BA,cAAc,EAAA,CAC1C;EACA,OAAOK,SAAAA,CAAAA,SAASL,cAAuC,CAAA;A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AAU,CAAG,EAAAY,eAAe,CAAC,CAAA;AAK5C,MAAMG,YAAe,GAAAA,CAC1BC,YACA,EAAAJ,eAAA,KAEG,CAAC,GAAGI,YAAc,EAAAhB,SAAA,CAAU,CAAG,EAAAY,eAAe,CAAC,CAAA,CAAEC,OAAOI,SAAAA,CAAAA,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAACC,KAAerD,EAAAA,SAAAA;AAAA;AAElDqB,kBAAmB,CAAAiC,UAAA,CAAWD,KAAK,CAAA,EAAGrD,SAAQ,CAAA;AAUnC,MAAAE,WAAA,GAAcA,CAACe,OAAAA,EAAcsC,UAAiC,KAAA;EACnE,MAAAC,gBAAA,GAAmBpC,iBAAOH,OAAQ,EAAA;IAAEwC,QAAQ,CAAG;IAAAC,KAAA,EAAOH;GAAY,CAAA;EAElE,MAAAI,QAAA,GAAWvB,qBAAWnB,OAAM,CAAA;EAElC,OAAOA,QAAO2C,MAAO,CAAA;IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;IAOnB1C,QAAQ2C,IAAK,CAAAH,KAAA,CACXF,gBAAmB,GAAAG,QAAA,CAAS3D,QAAS,CAAAiC,IAAA,IAAQ0B,SAAS3D,QAAS,CAAA6B,QACjE,CAAA;IACA7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;;;;;;;;;;;;;;;;"}
@@ -86,7 +86,7 @@ const money = dinero2 => {
86
86
  currency: parseCurrencyCode(currency2.code)
87
87
  };
88
88
  };
89
- const addMany = (addends, defaultCurrency) => [...addends, getDinero(0, defaultCurrency)].reduce(add);
89
+ const addMany = (addends, defaultCurrency) => addends.reduce(add, getDinero(0, defaultCurrency));
90
90
  const subtractMany = (subtractions, defaultCurrency) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);
91
91
  const stringAmountToDinero = (price, currency2) =>
92
92
  // FIXME: parseFloat seems dangerous O_O
@@ -1 +1 @@
1
- {"version":3,"file":"misc.mjs","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n [...addends, getDinero(0, defaultCurrency)].reduce(add);\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,MAAAM,iBAAA,GAAqBH,SAAqC,IAAA;EAC/D,MAAAI,cAAA,GAAiBC,sBAAuB,CAAAN,GAA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CAAA;EAEvC,OAAA;IACLC,MAAAA,EAAAA,OAAAA;IACAlB,QAAA,EAAUO,iBAAkBP,CAAAA,SAAAA,CAASC,IAAI;EAAA,CAC3C;AACF,CAAA;AAQO,MAAM2C,OAAU,GAAAA,CAACC,OAAsB,EAAAC,eAAA,KAC5C,CAAC,GAAGD,OAAS,EAAAX,SAAA,CAAU,CAAG,EAAAY,eAAe,CAAC,CAAA,CAAEC,OAAOC,GAAG,CAAA;AAKjD,MAAMC,YAAe,GAAAA,CAC1BC,YACA,EAAAJ,eAAA,KACG,CAAC,GAAGI,YAAc,EAAAhB,SAAA,CAAU,CAAG,EAAAY,eAAe,CAAC,CAAA,CAAEC,OAAOI,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAACC,KAAerD,EAAAA,SAAAA;AAAA;AAElDqB,kBAAmB,CAAAiC,UAAA,CAAWD,KAAK,CAAA,EAAGrD,SAAQ,CAAA;AAUnC,MAAAE,WAAA,GAAcA,CAACe,OAAAA,EAAcsC,UAAiC,KAAA;EACnE,MAAAC,gBAAA,GAAmBpC,OAAOH,OAAQ,EAAA;IAAEwC,QAAQ,CAAG;IAAAC,KAAA,EAAOH;GAAY,CAAA;EAElE,MAAAI,QAAA,GAAWvB,WAAWnB,OAAM,CAAA;EAElC,OAAOA,QAAO2C,MAAO,CAAA;IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;IAOnB1C,QAAQ2C,IAAK,CAAAH,KAAA,CACXF,gBAAmB,GAAAG,QAAA,CAAS3D,QAAS,CAAAiC,IAAA,IAAQ0B,SAAS3D,QAAS,CAAA6B,QACjE,CAAA;IACA7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;"}
1
+ {"version":3,"file":"misc.mjs","sources":["../../../src/utils/money/misc.ts"],"sourcesContent":["import {\n add,\n dinero,\n hasSubUnits,\n multiply,\n subtract,\n toSnapshot,\n toUnit,\n transformScale,\n} from \"dinero.js\";\n\nimport { Currency } from \"../../types\";\nimport { assert } from \"../errors\";\nimport { isFloat, isInt } from \"../number\";\nimport { capitalize } from \"../string\";\nimport { smallestSubunitLookup } from \"./constants\";\nimport {\n currencyLookup,\n dineroCurrenciesLookup,\n floatToInt,\n} from \"./misc.private\";\nimport type { Cents, Dino, DinoCurrency, Money, RoundingFn } from \"./types\";\n\n/**\n * Some currencies have subunits in their currency spec that are not used in reality. This causes Dinero to return incorrect subunit values for those currencies.\n * This util rounds down any unused subunits to closest subunit resolution.\n *\n * ! Not to be confused with prettifyTotal\n */\nexport const toSmallestSubunit = (total: Dino): Dino => {\n // Nothing to round\n if (!hasSubUnits(total)) {\n return total;\n }\n\n const totalJson = total.toJSON();\n\n const [roundToDigits, roundingMode] =\n smallestSubunitLookup.get(totalJson.currency.code) ?? [];\n\n if (roundToDigits == null || roundingMode == null) {\n return total;\n }\n\n return roundDinero(total, roundingMode);\n};\n\n/**\n * Find Dinero.js currency instance from our Currency enum.\n * @throws Throws an error if currency is not found!\n *\n * @example\n * getDineroCurrency(Currency.Usd); // => Dinero.js currency instance\n * getDineroCurrency(\"invalid\"); // => throws AssertionError\n */\nexport const getDineroCurrency = (currency: Currency): DinoCurrency => {\n const dineroCurrency = dineroCurrenciesLookup.get(currency);\n assert(!!dineroCurrency, `Unsupported currency: \"${currency}\"`);\n return dineroCurrency;\n};\n\n/**\n * Convert Dinero currency (case-insensitive) to local currency type\n * @throws Throws an error if currency is not found!\n *\n * @example\n * parseCurrencyCode('usd') // Currency.Usd\n * parseCurrencyCode('JPY') // Currency.Jpy\n * parseCurrencyCode('invalid') // throws AssertionError\n */\nexport const parseCurrencyCode = (code: string): Currency => {\n const normalizedCode = capitalize(code.toLowerCase());\n assert(\n currencyLookup.has(normalizedCode),\n `Invalid currency code: ${normalizedCode}`,\n );\n return Currency[normalizedCode as keyof typeof Currency];\n};\n\n/**\n * Utility to quickly convert cents to a to currency float amount number\n *\n * @example\n * centsToCurrencyUnit(100, \"USD\") // 1\n * centsToCurrencyUnit(1, \"USD\") // 0.01\n * centsToCurrencyUnit(420, \"USD\") // 4.2\n * centsToCurrencyUnit(420, \"JPY\") // 420\n * FIXME: worth moving to a combined method of centsToCurrencyUnit & dineroToCurrencyUnit that accepts Money|Dino as input\n */\nexport const centsToCurrencyUnit = (\n centsAmount: Cents,\n currency: Currency,\n): number => {\n const dineroCurrency = getDineroCurrency(currency);\n const dineroObj = dinero({ amount: centsAmount, currency: dineroCurrency });\n return dineroToCurrencyUnit(dineroObj);\n};\n\n/**\n * Utility to quickly convert dinero instance to a to currency amount number\n *\n * @example\n * dineroToCurrencyUnit(getDinero(100, Currency.Usd)) // 1\n * dineroToCurrencyUnit(getDinero(1, Currency.Usd)) // 0.01\n * dineroToCurrencyUnit(getDinero(420, Currency.Usd)) // 4.2\n */\nexport const dineroToCurrencyUnit = (dineroObj: Dino): number => {\n return toUnit(dineroObj);\n};\n\n/**\n * Parse arbitrary float amount in a given currency to a dinero object.\n * Wrapper around `parseFloatToDineroRaw` for easier usage.\n *\n * Doesn't work on string float amounts!\n * @example\n * parseFloatToDinero(420, Currency.Usd); // => Dinero.js instance\n */\nexport const parseFloatToDinero = (floatAmount: number, currency: Currency) => {\n const dineroCurrency = getDineroCurrency(currency);\n return parseFloatToDineroRaw(floatAmount, dineroCurrency);\n};\n\n/**\n * Parse arbitrary float amount in a given dinero like currency object to a dinero object.\n * ! Typically use `parseFloatToDinero` instead of this method ! But this one is useful for custom currencies (e.g. custom exchange rates)\n */\nexport const parseFloatToDineroRaw = (\n floatAmount: number,\n dineroCurrency: DinoCurrency,\n) => {\n isFloat(floatAmount, \"Amount\");\n\n /**\n * Try to determine given input scale after comma, if not found, use currency default as that would indicate that\n * given input was an integer instead of a float\n *\n * FIXME: Won't work correctly if some currencies use dot/comma separation for decimal digits:\n * At least MacOS shows 4 different kind of formats to numbers.\n * 1. \"1234567,89\"\n * 2. \"1,234,567,89\"\n * 3. \"1.234.567,89\"\n * 4. \"1 234 567,89\"\n * Have to research if there are any more standards we should try to parse support\n */\n const scaleOfGivenAmount =\n String(floatAmount).split(\".\")[1]?.length ?? dineroCurrency.exponent;\n\n if (\n scaleOfGivenAmount == null ||\n scaleOfGivenAmount > dineroCurrency.exponent\n ) {\n throw new Error(`scaleOfGivenAmount is unsupported ${scaleOfGivenAmount}`);\n }\n const rateInt = floatToInt(\n floatAmount,\n dineroCurrency.base,\n dineroCurrency.exponent,\n );\n return dinero({\n amount: rateInt,\n currency: dineroCurrency,\n });\n};\n\n/**\n * Shorthand for dinero constructor\n *\n * @example\n * getDinero(100, Currency.Usd); // => Dinero.js instance (representing $1)\n */\nexport const getDinero = (amount: Cents, currency: Currency): Dino => {\n // TODO: verify if this is even needed, as dinero might already handle this\n isInt(amount, \"Amount\");\n return dinero({ amount, currency: getDineroCurrency(currency) });\n};\n\n/**\n * Shorthand to get amount from dinero instance\n *\n * FIXME: There is potential issue because we are not trimming scale:\n * multiply(getDinero(100, Currency.Usd), { amount: 100 + percentIncrease, scale: 2 })\n * will result in amount:10600, scale:4 (2*2), because dinero is rounding to safest scale.\n * @see https://v2.dinerojs.com/docs/core-concepts/scale#trimming-scale\n *\n * We should call something like: transformScale(d, currency.exponent)\n * @see https://v2.dinerojs.com/docs/api/conversions/transform-scale\n *\n * @example\n * amount(getDinero(100, Currency.Usd)); // 100\n */\nexport const amount = (dinero: Dino): Cents => {\n return toSnapshot(dinero).amount;\n};\n\n/**\n * Method to multiply dinero amount by full percent.\n * It also transforms scale back to currency exponent.\n * Where in case 20.34*1.06=21,5604, it will round to 21.56\n *\n * Will convert 0.01 - 12% to 0, but thats edge case we can tolerate, because\n * of dinero version we do not control rounding\n */\nexport const multiplyByFullPercent = (\n dinero: Dino,\n percentIncrease: number,\n): Dino => {\n assert(\n percentIncrease >= -100 && percentIncrease <= 100,\n \"Range should be in [-100, 100]\",\n );\n // (106 / 10^2 = 1.06)\n const multiplyResult = multiply(dinero, {\n amount: 100 + percentIncrease,\n scale: 2,\n });\n return transformScale(\n multiplyResult,\n multiplyResult.toJSON().currency.exponent,\n );\n};\n\n/**\n * Shorthand to get currency from dinero instance\n *\n * @example\n * currency(getDinero(100, Currency.Usd)); // Currency.Usd\n */\nexport const currency = (dinero: Dino): Currency => {\n return parseCurrencyCode(toSnapshot(dinero).currency.code);\n};\n\n/**\n * Shorthand to get our GraphQL Money type from dinero instance\n *\n * @example\n * money(getDinero(100, Currency.Usd)); // { amount: 100, currency: Currency.Usd }\n */\nexport const money = (dinero: Dino): Money => {\n const { amount, currency } = toSnapshot(dinero);\n\n return {\n amount,\n currency: parseCurrencyCode(currency.code),\n };\n};\n\n/**\n * Helper to quickly add multiple dinero instances with same currency\n *\n * @example\n * addMany([getDinero(100, Currency.Usd), getDinero(200, Currency.Usd)], Currency.Usd); // => Dinero.js instance (representing $3)\n */\nexport const addMany = (addends: Array<Dino>, defaultCurrency: Currency) =>\n addends.reduce(add, getDinero(0, defaultCurrency));\n\n/**\n * Helper to quickly subtract multiple dinero instances with same currency\n */\nexport const subtractMany = (\n subtractions: Array<Dino>,\n defaultCurrency: Currency,\n // eslint-disable-next-line sonarjs/reduce-initial-value\n) => [...subtractions, getDinero(0, defaultCurrency)].reduce(subtract);\n\n/**\n * Helper to quickly get dinero object from string\n */\nexport const stringAmountToDinero = (price: string, currency: Currency) =>\n // FIXME: parseFloat seems dangerous O_O\n parseFloatToDinero(parseFloat(price), currency);\n\n/**\n * Helper to quickly round dinero object to closest integer by a given rounding function\n * FIXME: add tests\n *\n * @example\n * roundDinero(getDinero(120, Currency.Usd), Math.floor); // => Dinero.js instance (representing $1)\n * roundDinero(getDinero(120, Currency.Usd), Math.ceil); // => Dinero.js instance (representing $2)\n */\nexport const roundDinero = (dinero: Dino, roundingFn: RoundingFn): Dino => {\n const roundedUnitPrice = toUnit(dinero, { digits: 0, round: roundingFn });\n\n const snapshot = toSnapshot(dinero);\n\n return dinero.create({\n /**\n * Rounding to mitigate floating precision errors:\n *\n * 8.2 * 10 ** 2 = 819.9999999999999\n * 2.2 * 10 ** 2 = 220.00000000000003\n */\n amount: Math.round(\n roundedUnitPrice * snapshot.currency.base ** snapshot.currency.exponent,\n ),\n currency: snapshot.currency,\n });\n};\n"],"names":["toSmallestSubunit","total","hasSubUnits","totalJson","toJSON","roundToDigits","roundingMode","smallestSubunitLookup","get","currency","code","roundDinero","getDineroCurrency","dineroCurrency","dineroCurrenciesLookup","assert","parseCurrencyCode","normalizedCode","capitalize","toLowerCase","currencyLookup","has","Currency","centsToCurrencyUnit","centsAmount","dineroObj","dinero","amount","dineroToCurrencyUnit","toUnit","parseFloatToDinero","floatAmount","parseFloatToDineroRaw","isFloat","scaleOfGivenAmount","String","split","length","exponent","Error","rateInt","floatToInt","base","getDinero","isInt","toSnapshot","multiplyByFullPercent","percentIncrease","multiplyResult","multiply","scale","transformScale","money","addMany","addends","defaultCurrency","reduce","add","subtractMany","subtractions","subtract","stringAmountToDinero","price","parseFloat","roundingFn","roundedUnitPrice","digits","round","snapshot","create","Math"],"mappings":";;;;;;;;;AA6Ba,MAAAA,iBAAA,GAAqBC,KAAsB,IAAA;EAElD,IAAA,CAACC,WAAY,CAAAD,KAAK,CAAG,EAAA;IAChB,OAAAA,KAAA;EACT;EAEM,MAAAE,SAAA,GAAYF,MAAMG,MAAO,EAAA;EAEzB,MAAA,CAACC,aAAe,EAAAC,YAAY,CAChC,GAAAC,qBAAA,CAAsBC,IAAIL,SAAU,CAAAM,QAAA,CAASC,IAAI,CAAA,IAAK,EAAC;EAErD,IAAAL,aAAA,IAAiB,IAAQ,IAAAC,YAAA,IAAgB,IAAM,EAAA;IAC1C,OAAAL,KAAA;EACT;EAEO,OAAAU,WAAA,CAAYV,OAAOK,YAAY,CAAA;AACxC,CAAA;AAUa,MAAAM,iBAAA,GAAqBH,SAAqC,IAAA;EAC/D,MAAAI,cAAA,GAAiBC,sBAAuB,CAAAN,GAAA,CAAIC,SAAQ,CAAA;EAC1DM,MAAA,CAAO,CAAC,CAACF,cAAgB,EAAA,0BAA0BJ,SAAQ,GAAG,CAAA;E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AI;EAAA,CAC3C;AACF,CAAA;AAQa,MAAA2C,OAAA,GAAUA,CAACC,OAAA,EAAsBC,eAC5C,KAAAD,OAAA,CAAQE,OAAOC,GAAK,EAAAd,SAAA,CAAU,CAAG,EAAAY,eAAe,CAAC,CAAA;AAK5C,MAAMG,YAAe,GAAAA,CAC1BC,YACA,EAAAJ,eAAA,KAEG,CAAC,GAAGI,YAAc,EAAAhB,SAAA,CAAU,CAAG,EAAAY,eAAe,CAAC,CAAA,CAAEC,OAAOI,QAAQ,CAAA;AAKxD,MAAAC,oBAAA,GAAuBA,CAACC,KAAerD,EAAAA,SAAAA;AAAA;AAElDqB,kBAAmB,CAAAiC,UAAA,CAAWD,KAAK,CAAA,EAAGrD,SAAQ,CAAA;AAUnC,MAAAE,WAAA,GAAcA,CAACe,OAAAA,EAAcsC,UAAiC,KAAA;EACnE,MAAAC,gBAAA,GAAmBpC,OAAOH,OAAQ,EAAA;IAAEwC,QAAQ,CAAG;IAAAC,KAAA,EAAOH;GAAY,CAAA;EAElE,MAAAI,QAAA,GAAWvB,WAAWnB,OAAM,CAAA;EAElC,OAAOA,QAAO2C,MAAO,CAAA;IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;IAOnB1C,QAAQ2C,IAAK,CAAAH,KAAA,CACXF,gBAAmB,GAAAG,QAAA,CAAS3D,QAAS,CAAAiC,IAAA,IAAQ0B,SAAS3D,QAAS,CAAA6B,QACjE,CAAA;IACA7B,UAAU2D,QAAS,CAAA3D;EAAA,CACpB,CAAA;AACH,CAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"transform-css-module.js","sources":["../../../../src/utils/nextjs/ssr/transform-css-module.ts"],"sourcesContent":["import type { PluginObj } from \"@babel/core\";\nimport * as t from \"@babel/types\";\nimport crypto from \"node:crypto\";\n\nfunction generateMd5(input: string): string {\n return crypto.createHash(\"md5\").update(input).digest(\"hex\");\n}\n\ntype Plugin = PluginObj<{\n // Store the name of the default import identifier for \"style-inject.es.js\"\n defaultImportName: null | string;\n}>;\n\n/**\n * FIXME: Currently this plugin won't:\n * - Handle existing source maps correctly and would strip from the output: \"//#\n * sourceMappingURL=BubbleContainer.module.css.js.map\"\n */\nexport const transformCssModule = (): Plugin => {\n return {\n visitor: {\n // Step 0: Setup state\n Program(_path, state) {\n state[\"defaultImportName\"] = null;\n },\n // Step 1: Find the default import from \"style-inject.es.js\"\n ImportDeclaration(path, state) {\n // Skip, if the default import name is already found (assuming there is only one per-file)\n if (state[\"defaultImportName\"]) {\n return;\n }\n\n // Look for imports for \"style-inject.es.js\" file\n const importSource = path.node.source.value;\n if (!importSource.endsWith(\"style-inject.es.js\")) {\n return;\n }\n\n // Check for default import specifier\n const defaultSpecifier = path.node.specifiers.find((specifier) =>\n t.isImportDefaultSpecifier(specifier),\n ) as t.ImportDefaultSpecifier | undefined;\n\n // Store the default import name\n if (defaultSpecifier) {\n // Fail if two instances of file is found\n state[\"defaultImportName\"] = defaultSpecifier.local.name;\n } else {\n throw new Error(\n \"Import for `style-inject.es.js` file not found in file\",\n );\n }\n },\n\n // Step 2: Find all calls to the imported identifier\n CallExpression(path, state) {\n // Ignore if the default import name is not found\n if (!state[\"defaultImportName\"]) {\n return;\n }\n\n // Check if the callee is the default import identifier\n const callee = path.node.callee;\n if (\n t.isIdentifier(callee) &&\n callee.name === state[\"defaultImportName\"]\n ) {\n const args = path.node.arguments;\n\n // If arguments are not between 1 and 2, fail\n if (!(args.length >= 1 && args.length <= 2)) {\n throw new Error(\"Unexpected number of arguments\");\n }\n\n /**\n * Validates that the function arguments are:\n * 1. needs to be a string literal or variable holding string\n * 2. (optional) string literal\n */\n if (\n !(\n (t.isStringLiteral(args[0]) || t.isIdentifier(args[0])) &&\n (!args[1] || t.isStringLiteral(args[1]))\n )\n ) {\n throw new Error(\"Unexpected argument types\");\n }\n\n // CSS string\n let cssString: string = \"\";\n\n // Try to remove duplicate string literal as first argument and instead re-use the a already generated variable\n if (t.isStringLiteral(args[0])) {\n cssString = args[0].value;\n\n let reusedVariable = null;\n path.scope.path.traverse({\n VariableDeclarator(variablePath) {\n const { id, init } = variablePath.node;\n\n // Match variables initialized with the same string value.\n if (t.isStringLiteral(init, { value: cssString })) {\n reusedVariable = id;\n variablePath.stop(); // Stop traversing once a match is found.\n }\n },\n });\n\n // Replace the string literal with the existing variable reference.\n if (reusedVariable) {\n path.node.arguments[0] = reusedVariable;\n }\n } else if (t.isIdentifier(args[0])) {\n // Extract value from variable\n const binding = path.scope.getBinding(args[0].name);\n if (\n binding &&\n t.isVariableDeclarator(binding.path.node) &&\n t.isStringLiteral(binding.path.node.init)\n ) {\n cssString = binding.path.node.init.value;\n }\n }\n\n if (!cssString) {\n throw new Error(\"Invalid first argument value\");\n }\n\n // Generate MD5 hash of the first argument's value\n // TODO: Looked into that styled-components use murmurhash. Also it's possible to use sha1 for longer key\n // (less % of collision)\n const hash = generateMd5(cssString);\n\n // Add the hash as the second argument\n const hashArg = t.stringLiteral(hash);\n if (args.length > 1) {\n // If a second argument exists, replace it\n args[1] = hashArg;\n } else {\n // Otherwise, add it as a new second argument\n args.push(hashArg);\n }\n }\n },\n },\n } satisfies Plugin;\n};\n"],"names":["generateMd5","input","crypto","createHash","update","digest","transformCssModule","visitor","Program","_path","state","ImportDeclaration","path","importSource","node","source","value","endsWith","defaultSpecifier","specifiers","find","specifier","t","isImportDefaultSpecifier","local","name","Error","CallExpression","callee","isIdentifier","args","arguments","length","isStringLiteral","cssString","reusedVariable","scope","traverse","VariableDeclarator","variablePath","id","init","stop","binding","getBinding","isVariableDeclarator","hash","hashArg","stringLiteral","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,YAAYC,KAAuB,EAAA;EACnC,OAAAC,eAAA,CAAA,SAAA,CAAA,CAAOC,WAAW,KAAK,CAAA,CAAEC,OAAOH,KAAK,CAAA,CAAEI,OAAO,KAAK,CAAA;AAC5D;AAYO,MAAMC,qBAAqBA,CAAA,KAAc;EACvC,OAAA;IACLC,OAAS,EAA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xC,EAAA;cACYP,SAAA,GAAAS,OAAA,CAAQ/B,IAAK,CAAAE,IAAA,CAAK2B,IAAK,CAAAzB,KAAA;YACrC;UACF;UAEA,IAAI,CAACkB,SAAW,EAAA;YACR,MAAA,IAAIR,MAAM,8BAA8B,CAAA;UAChD;UAKM,MAAAoB,IAAA,GAAO9C,YAAYkC,SAAS,CAAA;UAG5B,MAAAa,OAAA,GAAUzB,YAAE,CAAA0B,aAAA,CAAcF,IAAI,CAAA;UAChC,IAAAhB,IAAA,CAAKE,SAAS,CAAG,EAAA;YAEnBF,IAAA,CAAK,CAAC,CAAI,GAAAiB,OAAA;UAAA,CACL,MAAA;YAELjB,IAAA,CAAKmB,KAAKF,OAAO,CAAA;UACnB;QACF;MACF;IACF;EAAA,CACF;AACF,CAAA;"}
1
+ {"version":3,"file":"transform-css-module.js","sources":["../../../../src/utils/nextjs/ssr/transform-css-module.ts"],"sourcesContent":["import type { PluginObj } from \"@babel/core\";\nimport * as t from \"@babel/types\";\nimport crypto from \"node:crypto\";\n\nfunction generateMd5(input: string): string {\n // eslint-disable-next-line sonarjs/hashing\n return crypto.createHash(\"md5\").update(input).digest(\"hex\");\n}\n\ntype Plugin = PluginObj<{\n // Store the name of the default import identifier for \"style-inject.es.js\"\n defaultImportName: null | string;\n}>;\n\n/**\n * FIXME: Currently this plugin won't:\n * - Handle existing source maps correctly and would strip from the output: \"//#\n * sourceMappingURL=BubbleContainer.module.css.js.map\"\n */\nexport const transformCssModule = (): Plugin => {\n return {\n visitor: {\n // Step 0: Setup state\n Program(_path, state) {\n state[\"defaultImportName\"] = null;\n },\n // Step 1: Find the default import from \"style-inject.es.js\"\n ImportDeclaration(path, state) {\n // Skip, if the default import name is already found (assuming there is only one per-file)\n if (state[\"defaultImportName\"]) {\n return;\n }\n\n // Look for imports for \"style-inject.es.js\" file\n const importSource = path.node.source.value;\n if (!importSource.endsWith(\"style-inject.es.js\")) {\n return;\n }\n\n // Check for default import specifier\n const defaultSpecifier = path.node.specifiers.find((specifier) =>\n t.isImportDefaultSpecifier(specifier),\n ) as t.ImportDefaultSpecifier | undefined;\n\n // Store the default import name\n if (defaultSpecifier) {\n // Fail if two instances of file is found\n state[\"defaultImportName\"] = defaultSpecifier.local.name;\n } else {\n throw new Error(\n \"Import for `style-inject.es.js` file not found in file\",\n );\n }\n },\n\n // Step 2: Find all calls to the imported identifier\n CallExpression(path, state) {\n // Ignore if the default import name is not found\n if (!state[\"defaultImportName\"]) {\n return;\n }\n\n // Check if the callee is the default import identifier\n const callee = path.node.callee;\n if (\n t.isIdentifier(callee) &&\n callee.name === state[\"defaultImportName\"]\n ) {\n const args = path.node.arguments;\n\n // If arguments are not between 1 and 2, fail\n if (!(args.length >= 1 && args.length <= 2)) {\n throw new Error(\"Unexpected number of arguments\");\n }\n\n /**\n * Validates that the function arguments are:\n * 1. needs to be a string literal or variable holding string\n * 2. (optional) string literal\n */\n if (\n !(\n (t.isStringLiteral(args[0]) || t.isIdentifier(args[0])) &&\n (!args[1] || t.isStringLiteral(args[1]))\n )\n ) {\n throw new Error(\"Unexpected argument types\");\n }\n\n // CSS string\n let cssString: string = \"\";\n\n // Try to remove duplicate string literal as first argument and instead re-use the a already generated variable\n if (t.isStringLiteral(args[0])) {\n cssString = args[0].value;\n\n let reusedVariable = null;\n path.scope.path.traverse({\n VariableDeclarator(variablePath) {\n const { id, init } = variablePath.node;\n\n // Match variables initialized with the same string value.\n if (t.isStringLiteral(init, { value: cssString })) {\n reusedVariable = id;\n variablePath.stop(); // Stop traversing once a match is found.\n }\n },\n });\n\n // Replace the string literal with the existing variable reference.\n if (reusedVariable) {\n path.node.arguments[0] = reusedVariable;\n }\n } else if (t.isIdentifier(args[0])) {\n // Extract value from variable\n const binding = path.scope.getBinding(args[0].name);\n if (\n binding &&\n t.isVariableDeclarator(binding.path.node) &&\n t.isStringLiteral(binding.path.node.init)\n ) {\n cssString = binding.path.node.init.value;\n }\n }\n\n if (!cssString) {\n throw new Error(\"Invalid first argument value\");\n }\n\n // Generate MD5 hash of the first argument's value\n // TODO: Looked into that styled-components use murmurhash. Also it's possible to use sha1 for longer key\n // (less % of collision)\n const hash = generateMd5(cssString);\n\n // Add the hash as the second argument\n const hashArg = t.stringLiteral(hash);\n if (args.length > 1) {\n // If a second argument exists, replace it\n args[1] = hashArg;\n } else {\n // Otherwise, add it as a new second argument\n args.push(hashArg);\n }\n }\n },\n },\n } satisfies Plugin;\n};\n"],"names":["generateMd5","input","crypto","createHash","update","digest","transformCssModule","visitor","Program","_path","state","ImportDeclaration","path","importSource","node","source","value","endsWith","defaultSpecifier","specifiers","find","specifier","t","isImportDefaultSpecifier","local","name","Error","CallExpression","callee","isIdentifier","args","arguments","length","isStringLiteral","cssString","reusedVariable","scope","traverse","VariableDeclarator","variablePath","id","init","stop","binding","getBinding","isVariableDeclarator","hash","hashArg","stringLiteral","push"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,YAAYC,KAAuB,EAAA;EAEnC,OAAAC,eAAA,CAAA,SAAA,CAAA,CAAOC,WAAW,KAAK,CAAA,CAAEC,OAAOH,KAAK,CAAA,CAAEI,OAAO,KAAK,CAAA;AAC5D;AAYO,MAAMC,qBAAqBA,CAAA,KAAc;EACvC,OAAA;IACLC,OAAS,EAAA;MAAA;MAEPC,OAAAA,CAAQC,OAAOC,KAAO,EAAA;QACpBA,KAAA,CAAM,mBAAmB,CAAI,GAAA,IAAA;MAC/B,CAAA;MAAA;MAEAC,iBAAAA,CAAkBC,MAAMF,KAAO,EAAA;QAEzB,IAAAA,KAAA,CAAM,mBAAmB,CAAG,EAAA;UAC9B;QACF;QAGM,MAAAG,YAAA,GAAeD,IAAK,CAAAE,IAAA,CAAKC,MAAO,CAAAC,KAAA;QACtC,IAAI,CAACH,YAAA,CAAaI,QAAS,CAAA,oBAAoB,CAAG,EAAA;UAChD;QACF;QAGM,MAAAC,gBAAA,GAAmBN,IAAK,CAAAE,IAAA,CAAKK,UAAW,CAAAC,IAAA,CAAM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AAA;UACnB;QACF;MACF;IACF;EAAA,CACF;AACF,CAAA;"}
@@ -1 +1 @@
1
- {"version":3,"file":"transform-css-module.mjs","sources":["../../../../src/utils/nextjs/ssr/transform-css-module.ts"],"sourcesContent":["import type { PluginObj } from \"@babel/core\";\nimport * as t from \"@babel/types\";\nimport crypto from \"node:crypto\";\n\nfunction generateMd5(input: string): string {\n return crypto.createHash(\"md5\").update(input).digest(\"hex\");\n}\n\ntype Plugin = PluginObj<{\n // Store the name of the default import identifier for \"style-inject.es.js\"\n defaultImportName: null | string;\n}>;\n\n/**\n * FIXME: Currently this plugin won't:\n * - Handle existing source maps correctly and would strip from the output: \"//#\n * sourceMappingURL=BubbleContainer.module.css.js.map\"\n */\nexport const transformCssModule = (): Plugin => {\n return {\n visitor: {\n // Step 0: Setup state\n Program(_path, state) {\n state[\"defaultImportName\"] = null;\n },\n // Step 1: Find the default import from \"style-inject.es.js\"\n ImportDeclaration(path, state) {\n // Skip, if the default import name is already found (assuming there is only one per-file)\n if (state[\"defaultImportName\"]) {\n return;\n }\n\n // Look for imports for \"style-inject.es.js\" file\n const importSource = path.node.source.value;\n if (!importSource.endsWith(\"style-inject.es.js\")) {\n return;\n }\n\n // Check for default import specifier\n const defaultSpecifier = path.node.specifiers.find((specifier) =>\n t.isImportDefaultSpecifier(specifier),\n ) as t.ImportDefaultSpecifier | undefined;\n\n // Store the default import name\n if (defaultSpecifier) {\n // Fail if two instances of file is found\n state[\"defaultImportName\"] = defaultSpecifier.local.name;\n } else {\n throw new Error(\n \"Import for `style-inject.es.js` file not found in file\",\n );\n }\n },\n\n // Step 2: Find all calls to the imported identifier\n CallExpression(path, state) {\n // Ignore if the default import name is not found\n if (!state[\"defaultImportName\"]) {\n return;\n }\n\n // Check if the callee is the default import identifier\n const callee = path.node.callee;\n if (\n t.isIdentifier(callee) &&\n callee.name === state[\"defaultImportName\"]\n ) {\n const args = path.node.arguments;\n\n // If arguments are not between 1 and 2, fail\n if (!(args.length >= 1 && args.length <= 2)) {\n throw new Error(\"Unexpected number of arguments\");\n }\n\n /**\n * Validates that the function arguments are:\n * 1. needs to be a string literal or variable holding string\n * 2. (optional) string literal\n */\n if (\n !(\n (t.isStringLiteral(args[0]) || t.isIdentifier(args[0])) &&\n (!args[1] || t.isStringLiteral(args[1]))\n )\n ) {\n throw new Error(\"Unexpected argument types\");\n }\n\n // CSS string\n let cssString: string = \"\";\n\n // Try to remove duplicate string literal as first argument and instead re-use the a already generated variable\n if (t.isStringLiteral(args[0])) {\n cssString = args[0].value;\n\n let reusedVariable = null;\n path.scope.path.traverse({\n VariableDeclarator(variablePath) {\n const { id, init } = variablePath.node;\n\n // Match variables initialized with the same string value.\n if (t.isStringLiteral(init, { value: cssString })) {\n reusedVariable = id;\n variablePath.stop(); // Stop traversing once a match is found.\n }\n },\n });\n\n // Replace the string literal with the existing variable reference.\n if (reusedVariable) {\n path.node.arguments[0] = reusedVariable;\n }\n } else if (t.isIdentifier(args[0])) {\n // Extract value from variable\n const binding = path.scope.getBinding(args[0].name);\n if (\n binding &&\n t.isVariableDeclarator(binding.path.node) &&\n t.isStringLiteral(binding.path.node.init)\n ) {\n cssString = binding.path.node.init.value;\n }\n }\n\n if (!cssString) {\n throw new Error(\"Invalid first argument value\");\n }\n\n // Generate MD5 hash of the first argument's value\n // TODO: Looked into that styled-components use murmurhash. Also it's possible to use sha1 for longer key\n // (less % of collision)\n const hash = generateMd5(cssString);\n\n // Add the hash as the second argument\n const hashArg = t.stringLiteral(hash);\n if (args.length > 1) {\n // If a second argument exists, replace it\n args[1] = hashArg;\n } else {\n // Otherwise, add it as a new second argument\n args.push(hashArg);\n }\n }\n },\n },\n } satisfies Plugin;\n};\n"],"names":["generateMd5","input","crypto","createHash","update","digest","transformCssModule","visitor","Program","_path","state","ImportDeclaration","path","importSource","node","source","value","endsWith","defaultSpecifier","specifiers","find","specifier","t","isImportDefaultSpecifier","local","name","Error","CallExpression","callee","isIdentifier","args","arguments","length","isStringLiteral","cssString","reusedVariable","scope","traverse","VariableDeclarator","variablePath","id","init","stop","binding","getBinding","isVariableDeclarator","hash","hashArg","stringLiteral","push"],"mappings":";;;AAIA,SAASA,YAAYC,KAAuB,EAAA;EACnC,OAAAC,MAAA,CAAOC,WAAW,KAAK,CAAA,CAAEC,OAAOH,KAAK,CAAA,CAAEI,OAAO,KAAK,CAAA;AAC5D;AAYO,MAAMC,qBAAqBA,CAAA,KAAc;EACvC,OAAA;IACLC,OAAS,EAAA;MAAA;MAEPC,OAAAA,CAAQC,OAAOC,KAAO,EAAA;QACpBA,KAAA,CAAM,mBAAmB,CAAI,GAAA,IAAA;MAC/B,CAAA;MAAA;MAEAC,iBAAAA,CAAkBC,MAAMF,KAAO,EAAA;QAEzB,IAAAA,KAAA,CAAM,mBAAmB,CAAG,EAAA;UAC9B;QACF;QAGM,MAAAG,YAAA,GAAeD,IAAK,CAAAE,IAAA,CAAKC,MAAO,CAAAC,KAAA;QACtC,IAAI,CAACH,YAAA,CAAaI,QAAS,CAAA,oBAAoB,CAAG,EAAA;UAChD;QACF;QAGM,MAAAC,gBAAA,GAAmBN,IAAK,CAAAE,IAAA,CAAKK,UAAW,CAAAC,IAAA,CAAMC,SAAA,IAClDC,CAAE,CAAAC,wBAAA,CAAyBF,SAAS,CAAA,CACtC;QAGA,IAAIH,gBAAkB,EAAA;UAEdR,KAAA,CAAA,mBAAmB,CAAI,GAAAQ,gBAAA,CAAiBM,KAAM,CAAAC,IAAA;QAAA,CAC/C,MAAA;UACL,MAAM,IAAIC,KAAA,CACR,wDAAA,CACF;QACF;MACF,CAAA;MAAA;MAGAC,cAAAA,CAAef,MAAMF,KAAO,EAAA;QAEtB,IAAA,CAACA,KAAM,CAAA,mBAAmB,CAAG,EAAA;UAC/B;QACF;QAGM,MAAAkB,MAAA,GAAShB,KAAKE,IAAK,CAAAc,MAAA;QAEvB,IAAAN,CAAA,CAAEO,aAAaD,MAAM,CAAA,IACrBA,OAAOH,IAAS,KAAAf,KAAA,CAAM,mBAAmB,CACzC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AA;YAElC,MAAMa,UAAU/B,IAAK,CAAAwB,KAAA,CAAMQ,WAAWd,IAAK,CAAA,CAAC,EAAEL,IAAI,CAAA;YAClD,IACEkB,OACA,IAAArB,CAAA,CAAEuB,oBAAqB,CAAAF,OAAA,CAAQ/B,IAAK,CAAAE,IAAI,CACxC,IAAAQ,CAAA,CAAEW,eAAgB,CAAAU,OAAA,CAAQ/B,IAAK,CAAAE,IAAA,CAAK2B,IAAI,CACxC,EAAA;cACYP,SAAA,GAAAS,OAAA,CAAQ/B,IAAK,CAAAE,IAAA,CAAK2B,IAAK,CAAAzB,KAAA;YACrC;UACF;UAEA,IAAI,CAACkB,SAAW,EAAA;YACR,MAAA,IAAIR,MAAM,8BAA8B,CAAA;UAChD;UAKM,MAAAoB,IAAA,GAAO9C,YAAYkC,SAAS,CAAA;UAG5B,MAAAa,OAAA,GAAUzB,CAAE,CAAA0B,aAAA,CAAcF,IAAI,CAAA;UAChC,IAAAhB,IAAA,CAAKE,SAAS,CAAG,EAAA;YAEnBF,IAAA,CAAK,CAAC,CAAI,GAAAiB,OAAA;UAAA,CACL,MAAA;YAELjB,IAAA,CAAKmB,KAAKF,OAAO,CAAA;UACnB;QACF;MACF;IACF;EAAA,CACF;AACF,CAAA;"}
1
+ {"version":3,"file":"transform-css-module.mjs","sources":["../../../../src/utils/nextjs/ssr/transform-css-module.ts"],"sourcesContent":["import type { PluginObj } from \"@babel/core\";\nimport * as t from \"@babel/types\";\nimport crypto from \"node:crypto\";\n\nfunction generateMd5(input: string): string {\n // eslint-disable-next-line sonarjs/hashing\n return crypto.createHash(\"md5\").update(input).digest(\"hex\");\n}\n\ntype Plugin = PluginObj<{\n // Store the name of the default import identifier for \"style-inject.es.js\"\n defaultImportName: null | string;\n}>;\n\n/**\n * FIXME: Currently this plugin won't:\n * - Handle existing source maps correctly and would strip from the output: \"//#\n * sourceMappingURL=BubbleContainer.module.css.js.map\"\n */\nexport const transformCssModule = (): Plugin => {\n return {\n visitor: {\n // Step 0: Setup state\n Program(_path, state) {\n state[\"defaultImportName\"] = null;\n },\n // Step 1: Find the default import from \"style-inject.es.js\"\n ImportDeclaration(path, state) {\n // Skip, if the default import name is already found (assuming there is only one per-file)\n if (state[\"defaultImportName\"]) {\n return;\n }\n\n // Look for imports for \"style-inject.es.js\" file\n const importSource = path.node.source.value;\n if (!importSource.endsWith(\"style-inject.es.js\")) {\n return;\n }\n\n // Check for default import specifier\n const defaultSpecifier = path.node.specifiers.find((specifier) =>\n t.isImportDefaultSpecifier(specifier),\n ) as t.ImportDefaultSpecifier | undefined;\n\n // Store the default import name\n if (defaultSpecifier) {\n // Fail if two instances of file is found\n state[\"defaultImportName\"] = defaultSpecifier.local.name;\n } else {\n throw new Error(\n \"Import for `style-inject.es.js` file not found in file\",\n );\n }\n },\n\n // Step 2: Find all calls to the imported identifier\n CallExpression(path, state) {\n // Ignore if the default import name is not found\n if (!state[\"defaultImportName\"]) {\n return;\n }\n\n // Check if the callee is the default import identifier\n const callee = path.node.callee;\n if (\n t.isIdentifier(callee) &&\n callee.name === state[\"defaultImportName\"]\n ) {\n const args = path.node.arguments;\n\n // If arguments are not between 1 and 2, fail\n if (!(args.length >= 1 && args.length <= 2)) {\n throw new Error(\"Unexpected number of arguments\");\n }\n\n /**\n * Validates that the function arguments are:\n * 1. needs to be a string literal or variable holding string\n * 2. (optional) string literal\n */\n if (\n !(\n (t.isStringLiteral(args[0]) || t.isIdentifier(args[0])) &&\n (!args[1] || t.isStringLiteral(args[1]))\n )\n ) {\n throw new Error(\"Unexpected argument types\");\n }\n\n // CSS string\n let cssString: string = \"\";\n\n // Try to remove duplicate string literal as first argument and instead re-use the a already generated variable\n if (t.isStringLiteral(args[0])) {\n cssString = args[0].value;\n\n let reusedVariable = null;\n path.scope.path.traverse({\n VariableDeclarator(variablePath) {\n const { id, init } = variablePath.node;\n\n // Match variables initialized with the same string value.\n if (t.isStringLiteral(init, { value: cssString })) {\n reusedVariable = id;\n variablePath.stop(); // Stop traversing once a match is found.\n }\n },\n });\n\n // Replace the string literal with the existing variable reference.\n if (reusedVariable) {\n path.node.arguments[0] = reusedVariable;\n }\n } else if (t.isIdentifier(args[0])) {\n // Extract value from variable\n const binding = path.scope.getBinding(args[0].name);\n if (\n binding &&\n t.isVariableDeclarator(binding.path.node) &&\n t.isStringLiteral(binding.path.node.init)\n ) {\n cssString = binding.path.node.init.value;\n }\n }\n\n if (!cssString) {\n throw new Error(\"Invalid first argument value\");\n }\n\n // Generate MD5 hash of the first argument's value\n // TODO: Looked into that styled-components use murmurhash. Also it's possible to use sha1 for longer key\n // (less % of collision)\n const hash = generateMd5(cssString);\n\n // Add the hash as the second argument\n const hashArg = t.stringLiteral(hash);\n if (args.length > 1) {\n // If a second argument exists, replace it\n args[1] = hashArg;\n } else {\n // Otherwise, add it as a new second argument\n args.push(hashArg);\n }\n }\n },\n },\n } satisfies Plugin;\n};\n"],"names":["generateMd5","input","crypto","createHash","update","digest","transformCssModule","visitor","Program","_path","state","ImportDeclaration","path","importSource","node","source","value","endsWith","defaultSpecifier","specifiers","find","specifier","t","isImportDefaultSpecifier","local","name","Error","CallExpression","callee","isIdentifier","args","arguments","length","isStringLiteral","cssString","reusedVariable","scope","traverse","VariableDeclarator","variablePath","id","init","stop","binding","getBinding","isVariableDeclarator","hash","hashArg","stringLiteral","push"],"mappings":";;;AAIA,SAASA,YAAYC,KAAuB,EAAA;EAEnC,OAAAC,MAAA,CAAOC,WAAW,KAAK,CAAA,CAAEC,OAAOH,KAAK,CAAA,CAAEI,OAAO,KAAK,CAAA;AAC5D;AAYO,MAAMC,qBAAqBA,CAAA,KAAc;EACvC,OAAA;IACLC,OAAS,EAAA;MAAA;MAEPC,OAAAA,CAAQC,OAAOC,KAAO,EAAA;QACpBA,KAAA,CAAM,mBAAmB,CAAI,GAAA,IAAA;MAC/B,CAAA;MAAA;MAEAC,iBAAAA,CAAkBC,MAAMF,KAAO,EAAA;QAEzB,IAAAA,KAAA,CAAM,mBAAmB,CAAG,EAAA;UAC9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AAYkC,SAAS,CAAA;UAG5B,MAAAa,OAAA,GAAUzB,CAAE,CAAA0B,aAAA,CAAcF,IAAI,CAAA;UAChC,IAAAhB,IAAA,CAAKE,SAAS,CAAG,EAAA;YAEnBF,IAAA,CAAK,CAAC,CAAI,GAAAiB,OAAA;UAAA,CACL,MAAA;YAELjB,IAAA,CAAKmB,KAAKF,OAAO,CAAA;UACnB;QACF;MACF;IACF;EAAA,CACF;AACF,CAAA;"}
@@ -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 throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\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 throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\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;IACpD,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,qBAAqBD,KAAK,EAAE,CAAA;EAC5D;EAEA,IAAI,CAACI,MAAA,CAAOE,QAAS,CAAAN,KAAK,CAAG,EAAA;IAC3B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,4BAA4BD,KAAK,EAAE,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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E,CAAA;EACxD,MAAMK,YAAYlC,KAAQ,GAAA6B,EAAA;EAE1B,IAAIK,YAAY,CAAG,EAAA;IACjBJ,MAAA,CAAOK,KAAKD,SAAS,CAAA;EACvB;EAEO,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 throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\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 throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\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 // eslint-disable-next-line sonarjs/reduce-initial-value\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;IACpD,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,qBAAqBD,KAAK,EAAE,CAAA;EAC5D;EAEA,IAAI,CAACI,MAAA,CAAOE,QAAS,CAAAN,KAAK,CAAG,EAAA;IAC3B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,4BAA4BD,KAAK,EAAE,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;IAC5B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,uBAAuBD,KAAK,EAAE,CAAA;EAC9D;EAEA,IAAI,CAACI,MAAA,CAAOK,aAAc,CAAAT,KAAK,CAAG,EAAA;IAChC,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,2BAA2BD,KAAK,EAAE,CAAA;EAClE;AACF;AAWO,SAASU,OACdA,CAAAV,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC,QAAQC,UAA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G,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 +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 throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\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 throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\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,QA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AS,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 throw new ErrorClass(`${entity} is not a number: ${value}`);\n }\n\n if (!Number.isFinite(value)) {\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 throw new ErrorClass(`${entity} is not an integer: ${value}`);\n }\n\n if (!Number.isSafeInteger(value)) {\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 // eslint-disable-next-line sonarjs/reduce-initial-value\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;IACpD,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,qBAAqBD,KAAK,EAAE,CAAA;EAC5D;EAEA,IAAI,CAACI,MAAA,CAAOE,QAAS,CAAAN,KAAK,CAAG,EAAA;IAC3B,MAAM,IAAIE,UAAW,CAAA,GAAGD,MAAM,4BAA4BD,KAAK,EAAE,CAAA;EACnE;AACF;AAWO,SAASO,KACdA,CAAAP,KAAA,EACAC,MAAS,GAAA,OAAA,EACTC,aAA4CC,SACnB,EAAA;EACVJ,cAAA,CAAAC,KAAA,EAAOC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ecs */:
16
16
  {
17
- return /techspecs-sort-weight:(-?[0-9]+)/;
17
+ return /techspecs-sort-weight:(-?\d+)/;
18
18
  }
19
19
  case "store" /* Store */:
20
20
  {
21
21
  switch (store) {
22
22
  case generated.StoreId.Us:
23
- return /pro-sort-weight:(-?[0-9]+)/;
23
+ return /pro-sort-weight:(-?\d+)/;
24
24
  case generated.StoreId.Ca:
25
25
  case generated.StoreId.Eu:
26
26
  case generated.StoreId.Me:
@@ -33,7 +33,7 @@ const getSortWeightTagRegex = (site, store) => {
33
33
  case generated.StoreId.Tw:
34
34
  case generated.StoreId.Mx:
35
35
  case generated.StoreId.Ph:
36
- return /pro-sort-weight:(-?[0-9]+):other/;
36
+ return /pro-sort-weight:(-?\d+):other/;
37
37
  case null:
38
38
  case void 0:
39
39
  {
@@ -64,7 +64,7 @@ const getTagsSortWeight = (tags, site, store) => {
64
64
  if (!tag || !regExp) {
65
65
  return void 0;
66
66
  }
67
- const match = tag?.name.match(regExp)?.[1];
67
+ const match = regExp.exec(tag.name)?.[1];
68
68
  return match ? parseInt(match) : void 0;
69
69
  };
70
70
  const sortByTagWeight = (site, store) => (current, next) => {
@@ -1 +1 @@
1
- {"version":3,"file":"product.js","sources":["../../src/utils/product.ts"],"sourcesContent":["import type { Nullish } from \"../types\";\nimport { StoreId } from \"../types\";\nimport { normalizeSortResult } from \"./array\";\nimport { checkUnreachable } from \"./errors\";\n\nexport enum SortSiteId {\n /**\n * Store.ui.com\n */\n Store = \"store\",\n /**\n * Techspecs.ui.com\n */\n Techspecs = \"techspecs\",\n}\n\n/**\n * Get correct sort weight tag regex based on site in which\n * the product is being displayed and the store\n */\nconst getSortWeightTagRegex = (\n site: SortSiteId,\n store: Nullish<StoreId>,\n): RegExp | null => {\n switch (site) {\n case SortSiteId.Techspecs: {\n return /techspecs-sort-weight:(-?[0-9]+)/;\n }\n case SortSiteId.Store: {\n // eslint-disable-next-line sonarjs/no-nested-switch\n switch (store) {\n case StoreId.Us:\n return /pro-sort-weight:(-?[0-9]+)/;\n case StoreId.Ca:\n case StoreId.Eu:\n case StoreId.Me:\n case StoreId.Uk:\n case StoreId.Za:\n case StoreId.In:\n case StoreId.Sg:\n case StoreId.Jp:\n case StoreId.Br:\n case StoreId.Tw:\n case StoreId.Mx:\n case StoreId.Ph:\n return /pro-sort-weight:(-?[0-9]+):other/;\n case null:\n case undefined: {\n return null;\n }\n default:\n checkUnreachable(store);\n return null;\n }\n }\n\n default: {\n checkUnreachable(site);\n return null;\n }\n }\n};\n\n/**\n * Get sort weight from product tags\n */\nexport const getTagsSortWeight = <\n T extends {\n name: string;\n },\n>(\n tags: T[],\n site: SortSiteId,\n store: Nullish<StoreId>,\n): number | undefined => {\n let regExp = getSortWeightTagRegex(site, store);\n\n // Attempt to find a tag matching the regular expression\n let tag = regExp ? tags.find((tag) => regExp?.test(tag.name)) : undefined;\n\n // If no tag is found and store is not US, retry with StoreId.Us\n if (!tag && store !== StoreId.Us) {\n regExp = getSortWeightTagRegex(site, StoreId.Us);\n\n // If no regular expression is returned, exit early\n if (!regExp) {\n return undefined;\n }\n\n tag = tags.find((tag) => regExp?.test(tag.name));\n }\n\n if (!tag || !regExp) {\n return undefined;\n }\n\n const match = tag?.name.match(regExp)?.[1];\n\n return match ? parseInt(match) : undefined;\n};\n\n/**\n * Sort by tag weight which can be used in `Array.sort(sortByTagWeight(site, store))`\n */\nexport const sortByTagWeight =\n (site: SortSiteId, store?: Nullish<StoreId>) =>\n <T extends { tags: { name: string }[] }>(current: T, next: T): number => {\n // Fallback to \"-1\" to group them in to the back\n const currentSortWeight =\n getTagsSortWeight(current.tags, site, store) ?? -1;\n const nextSortWeight = getTagsSortWeight(next.tags, site, store) ?? -1;\n return normalizeSortResult(nextSortWeight - currentSortWeight);\n };\n"],"names":["SortSiteId","getSortWeightTagRegex","site","store","StoreId","Us","Ca","Eu","Me","Uk","Za","In","Sg","Jp","Br","Tw","Mx","Ph","checkUnreachable","getTagsSortWeight","tags","regExp","tag","find","test","name","match","parse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CAAAW,IAAA,CAAKV,IAAM,EAAAlB,IAAA,EAAMC,KAAK,CAAK,IAAA,CAAA,CAAA;EAC7D,OAAA8B,KAAA,CAAAA,mBAAA,CAAoBD,iBAAiBD,iBAAiB,CAAA;AAC/D,CAAA;;;"}
1
+ {"version":3,"file":"product.js","sources":["../../src/utils/product.ts"],"sourcesContent":["import type { Nullish } from \"../types\";\nimport { StoreId } from \"../types\";\nimport { normalizeSortResult } from \"./array\";\nimport { checkUnreachable } from \"./errors\";\n\nexport enum SortSiteId {\n /**\n * Store.ui.com\n */\n Store = \"store\",\n /**\n * Techspecs.ui.com\n */\n Techspecs = \"techspecs\",\n}\n\n/**\n * Get correct sort weight tag regex based on site in which\n * the product is being displayed and the store\n */\nconst getSortWeightTagRegex = (\n site: SortSiteId,\n store: Nullish<StoreId>,\n): RegExp | null => {\n switch (site) {\n case SortSiteId.Techspecs: {\n return /techspecs-sort-weight:(-?\\d+)/;\n }\n case SortSiteId.Store: {\n // eslint-disable-next-line sonarjs/no-nested-switch\n switch (store) {\n case StoreId.Us:\n return /pro-sort-weight:(-?\\d+)/;\n case StoreId.Ca:\n case StoreId.Eu:\n case StoreId.Me:\n case StoreId.Uk:\n case StoreId.Za:\n case StoreId.In:\n case StoreId.Sg:\n case StoreId.Jp:\n case StoreId.Br:\n case StoreId.Tw:\n case StoreId.Mx:\n case StoreId.Ph:\n return /pro-sort-weight:(-?\\d+):other/;\n case null:\n case undefined: {\n return null;\n }\n default:\n checkUnreachable(store);\n return null;\n }\n }\n\n default: {\n checkUnreachable(site);\n return null;\n }\n }\n};\n\n/**\n * Get sort weight from product tags\n */\nexport const getTagsSortWeight = <\n T extends {\n name: string;\n },\n>(\n tags: T[],\n site: SortSiteId,\n store: Nullish<StoreId>,\n): number | undefined => {\n let regExp = getSortWeightTagRegex(site, store);\n\n // Attempt to find a tag matching the regular expression\n let tag = regExp ? tags.find((tag) => regExp?.test(tag.name)) : undefined;\n\n // If no tag is found and store is not US, retry with StoreId.Us\n if (!tag && store !== StoreId.Us) {\n regExp = getSortWeightTagRegex(site, StoreId.Us);\n\n // If no regular expression is returned, exit early\n if (!regExp) {\n return undefined;\n }\n\n tag = tags.find((tag) => regExp?.test(tag.name));\n }\n\n if (!tag || !regExp) {\n return undefined;\n }\n\n const match = regExp.exec(tag.name)?.[1];\n\n return match ? parseInt(match) : undefined;\n};\n\n/**\n * Sort by tag weight which can be used in `Array.sort(sortByTagWeight(site, store))`\n */\nexport const sortByTagWeight =\n (site: SortSiteId, store?: Nullish<StoreId>) =>\n <T extends { tags: { name: string }[] }>(current: T, next: T): number => {\n // Fallback to \"-1\" to group them in to the back\n const currentSortWeight =\n getTagsSortWeight(current.tags, site, store) ?? -1;\n const nextSortWeight = getTagsSortWeight(next.tags, site, store) ?? -1;\n return normalizeSortResult(nextSortWeight - currentSortWeight);\n };\n"],"names":["SortSiteId","getSortWeightTagRegex","site","store","StoreId","Us","Ca","Eu","Me","Uk","Za","In","Sg","Jp","Br","Tw","Mx","Ph","checkUnreachable","getTagsSortWeight","tags","regExp","tag","find","test","name","match","exec","parseInt","sortByTagWeight","current","next","currentSortWeight","nextSortWeight","normalizeSortResult"],"mappings":";;;;;;;AAKY,IAAAA,UAAA,GAAA,gBAAAA,WAAL,IAAA;EAILA,YAAA,OAAQ,CAAA,GAAA,OAAA;EAIRA,YAAA,WAAY,CAAA,GAAA,WAAA;EARFA,OAAAA,WAAAA;AAAA,CAAA,EAAAA,UAAA,IAAA,CAAA,CAAA,CAAA;AAeZ,MAAMC,qBAAA,GAAwBA,CAC5BC,IAAA,EACAC,KACkB,KAAA;EAClB,QAAQD,IAAM;IACZ,KAAK,WAAsB,CAAA;MAAA;QAClB,OAAA,+BAAA;MACT;IACA,KAAK,OAAkB,CAAA;MAAA;QAErB,QAAQC,KAAO;UACb,KAAKC,SAAQ,CAAAA,OAAA,CAAAC,EAAA;YACJ,OAAA,yBAAA;UACT,KAAKD,SAAAA,CAAAA,OAAQ,CAAAE,EAAA;UACb,KAAK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