@zonos/elements 1.3.18-alpha.2 → 1.3.18-alpha.4

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 (341) hide show
  1. package/README.md +341 -96
  2. package/dist/cjs/{cart-941a31dd.js → cart-72b0bccc.js} +34 -85
  3. package/dist/cjs/index.cjs.js +628 -0
  4. package/dist/cjs/loader.cjs.js +1 -1
  5. package/dist/cjs/logError-4e2f2020.js +58 -0
  6. package/dist/cjs/{submitGtag-9210b4fe.js → submitGtag-b0c8de90.js} +3 -2
  7. package/dist/cjs/zonos-address_8.cjs.entry.js +13 -12
  8. package/dist/cjs/zonos-badge_2.cjs.entry.js +3 -3
  9. package/dist/cjs/zonos-button_3.cjs.entry.js +3 -3
  10. package/dist/cjs/zonos-card_2.cjs.entry.js +7 -6
  11. package/dist/cjs/zonos-cart-items_11.cjs.entry.js +11 -10
  12. package/dist/cjs/zonos-checkout.cjs.entry.js +20 -15
  13. package/dist/cjs/zonos-controller.cjs.entry.js +47 -20
  14. package/dist/cjs/zonos-country-flag.cjs.entry.js +2 -1
  15. package/dist/cjs/zonos-country-select_3.cjs.entry.js +6 -5
  16. package/dist/cjs/zonos-elements.cjs.js +1 -1
  17. package/dist/cjs/zonos-hello-dialog.cjs.entry.js +2 -1
  18. package/dist/cjs/zonos-hello.cjs.entry.js +10 -9
  19. package/dist/cjs/zonos-input.cjs.entry.js +4 -4
  20. package/dist/cjs/zonos-link.cjs.entry.js +1 -1
  21. package/dist/cjs/zonos-payment.cjs.entry.js +3 -2
  22. package/dist/collection/__mocks__/zonos-url/index.js +1 -0
  23. package/dist/collection/__tests__/build-utils/urlCheckOne.js +1 -1
  24. package/dist/collection/collection-manifest.json +1 -1
  25. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout-finish/zonos-checkout-finish.js +4 -9
  26. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout.js +8 -4
  27. package/dist/collection/components/checkout/zonos-checkout/zonos-customer-info/zonos-customer-info.js +3 -3
  28. package/dist/collection/components/common/zonos-badge/zonos-badge.js +3 -3
  29. package/dist/collection/components/common/zonos-button/zonos-button.js +3 -3
  30. package/dist/collection/components/common/zonos-card/zonos-card.js +3 -3
  31. package/dist/collection/components/common/zonos-checkbox/zonos-checkbox.js +3 -3
  32. package/dist/collection/components/common/zonos-checkout-progress-tabs/zonos-checkout-progress-tabs.js +3 -3
  33. package/dist/collection/components/common/zonos-collapse/zonos-collapse.js +2 -2
  34. package/dist/collection/components/common/zonos-confirm-dialog/zonos-confirm-dialog.js +3 -3
  35. package/dist/collection/components/common/zonos-country-select/zonos-country-select.js +2 -2
  36. package/dist/collection/components/common/zonos-custom-message/zonos-custom-message.js +2 -2
  37. package/dist/collection/components/common/zonos-dialog/zonos-dialog.js +3 -3
  38. package/dist/collection/components/common/zonos-input/zonos-input.js +4 -4
  39. package/dist/collection/components/common/zonos-language-select/zonos-language-select.js +2 -2
  40. package/dist/collection/components/common/{component-template/zonos-link → zonos-link}/zonos-link.js +1 -1
  41. package/dist/collection/components/main/zonos-controller.js +41 -6
  42. package/dist/collection/components/stripe/zonos-address/zonos-address.js +3 -3
  43. package/dist/collection/components/utils/hello/setZCountryUrlParam.js +5 -1
  44. package/dist/collection/environment.js +0 -2
  45. package/dist/collection/index.js +1 -0
  46. package/dist/collection/scripts/_extractZonosQaUrl.js +26 -0
  47. package/dist/collection/scripts/_getZonosQaUrl.js +44 -0
  48. package/dist/collection/scripts/{loadStripe.js → _loadStripe.js} +1 -1
  49. package/dist/collection/scripts/{zonosBase.js → _zonosBase.js} +29 -6
  50. package/dist/collection/scripts/index.js +2 -0
  51. package/dist/collection/types/generated/graphql.customer.types.js +1 -0
  52. package/dist/collection/types/generated/graphql.frontend.types.js +1 -0
  53. package/dist/esm/{cart-cc593c2b.js → cart-1a37e002.js} +7 -56
  54. package/dist/esm/index.js +625 -0
  55. package/dist/esm/loader.js +1 -1
  56. package/dist/esm/logError-c456c092.js +55 -0
  57. package/dist/esm/{submitGtag-e50f903f.js → submitGtag-754935b4.js} +2 -1
  58. package/dist/esm/zonos-address_8.entry.js +11 -10
  59. package/dist/esm/zonos-badge_2.entry.js +3 -3
  60. package/dist/esm/zonos-button_3.entry.js +3 -3
  61. package/dist/esm/zonos-card_2.entry.js +7 -6
  62. package/dist/esm/zonos-cart-items_11.entry.js +11 -10
  63. package/dist/esm/zonos-checkout.entry.js +8 -3
  64. package/dist/esm/zonos-controller.entry.js +30 -3
  65. package/dist/esm/zonos-country-flag.entry.js +2 -1
  66. package/dist/esm/zonos-country-select_3.entry.js +6 -5
  67. package/dist/esm/zonos-elements.js +1 -1
  68. package/dist/esm/zonos-hello-dialog.entry.js +2 -1
  69. package/dist/esm/zonos-hello.entry.js +2 -1
  70. package/dist/esm/zonos-input.entry.js +4 -4
  71. package/dist/esm/zonos-link.entry.js +1 -1
  72. package/dist/esm/zonos-payment.entry.js +2 -1
  73. package/dist/esm-es5/cart-1a37e002.js +1 -0
  74. package/dist/esm-es5/index.js +1 -0
  75. package/dist/esm-es5/loader.js +1 -1
  76. package/dist/esm-es5/logError-c456c092.js +1 -0
  77. package/dist/esm-es5/submitGtag-754935b4.js +1 -0
  78. package/dist/esm-es5/zonos-address_8.entry.js +1 -1
  79. package/dist/esm-es5/zonos-badge_2.entry.js +1 -1
  80. package/dist/esm-es5/zonos-button_3.entry.js +1 -1
  81. package/dist/esm-es5/zonos-card_2.entry.js +1 -1
  82. package/dist/esm-es5/zonos-cart-items_11.entry.js +1 -1
  83. package/dist/esm-es5/zonos-checkout.entry.js +1 -1
  84. package/dist/esm-es5/zonos-controller.entry.js +1 -1
  85. package/dist/esm-es5/zonos-country-flag.entry.js +1 -1
  86. package/dist/esm-es5/zonos-country-select_3.entry.js +1 -1
  87. package/dist/esm-es5/zonos-elements.js +1 -1
  88. package/dist/esm-es5/zonos-hello-dialog.entry.js +1 -1
  89. package/dist/esm-es5/zonos-hello.entry.js +1 -1
  90. package/dist/esm-es5/zonos-input.entry.js +1 -1
  91. package/dist/esm-es5/zonos-link.entry.js +1 -1
  92. package/dist/esm-es5/zonos-payment.entry.js +1 -1
  93. package/dist/scripts/index.d.ts +3908 -0
  94. package/dist/scripts/index.js +1 -0
  95. package/dist/scripts/loadZonos.d.ts +3954 -0
  96. package/dist/scripts/loadZonos.js +1 -1
  97. package/dist/scripts/zonos.js +1 -1
  98. package/dist/types/components/checkout/zonos-checkout/zonos-checkout-finish/zonos-checkout-finish.d.ts +5 -7
  99. package/dist/types/components/checkout/zonos-checkout/zonos-checkout.d.ts +2 -2
  100. package/dist/types/components/checkout/zonos-checkout/zonos-customer-info/zonos-customer-info.d.ts +2 -2
  101. package/dist/types/components/main/zonos-controller.d.ts +6 -1
  102. package/dist/types/components/store/checkout/stripe.d.ts +1 -1
  103. package/dist/types/components/store/zonosStore.d.ts +1 -1
  104. package/dist/types/components/stripe/zonos-address/zonos-address.d.ts +2 -2
  105. package/dist/types/components/utils/styles.d.ts +1 -0
  106. package/dist/types/components.d.ts +22 -14
  107. package/dist/types/index.d.ts +1 -0
  108. package/dist/types/scripts/_extractZonosQaUrl.d.ts +11 -0
  109. package/dist/types/scripts/_getZonosQaUrl.d.ts +4 -0
  110. package/dist/types/scripts/{loadStripe.d.ts → _loadStripe.d.ts} +1 -1
  111. package/dist/types/scripts/{zonosBase.d.ts → _zonosBase.d.ts} +36 -2
  112. package/dist/types/scripts/index.d.ts +2 -0
  113. package/dist/types/types/checkout/CheckoutConfig.d.ts +5 -0
  114. package/dist/types/types/checkout/api/CalculateLandedCostRequest.d.ts +9 -0
  115. package/dist/types/types/generated/graphql.customer.types.d.ts +1 -0
  116. package/dist/types/types/generated/graphql.customer.types.ts +3 -0
  117. package/dist/types/types/generated/graphql.frontend.types.d.ts +1 -0
  118. package/dist/types/types/generated/graphql.frontend.types.ts +1 -0
  119. package/dist/types/types/global.d.ts +1 -1
  120. package/dist/zonos-elements/index.esm.js +1 -0
  121. package/dist/zonos-elements/p-0878369a.entry.js +1 -0
  122. package/dist/zonos-elements/p-0d1c06d7.entry.js +1 -0
  123. package/dist/zonos-elements/{p-9aab3ad7.entry.js → p-0d5b5bcc.entry.js} +1 -1
  124. package/dist/zonos-elements/p-1491717a.entry.js +1 -0
  125. package/dist/zonos-elements/p-14ff42fe.system.entry.js +1 -0
  126. package/dist/zonos-elements/p-2800c274.system.entry.js +1 -0
  127. package/dist/zonos-elements/p-2e02a76f.system.entry.js +1 -0
  128. package/dist/zonos-elements/{p-020a9b86.entry.js → p-3ba8838a.entry.js} +1 -1
  129. package/dist/zonos-elements/p-4594a125.js +1 -0
  130. package/dist/zonos-elements/p-483e1724.entry.js +1 -0
  131. package/dist/zonos-elements/{p-d0bc8902.system.entry.js → p-4f72bfee.system.entry.js} +1 -1
  132. package/dist/zonos-elements/p-58be220f.system.js +1 -0
  133. package/dist/zonos-elements/{p-9e9c318b.entry.js → p-58fc8ec1.entry.js} +1 -1
  134. package/dist/zonos-elements/p-63db40b9.system.js +1 -0
  135. package/dist/zonos-elements/p-6449c92b.js +1 -0
  136. package/dist/zonos-elements/p-6746455b.system.entry.js +1 -0
  137. package/dist/zonos-elements/{p-c20e5430.entry.js → p-6cb9812b.entry.js} +1 -1
  138. package/dist/zonos-elements/p-7487ef47.entry.js +1 -0
  139. package/dist/zonos-elements/p-7b2d367b.entry.js +1 -0
  140. package/dist/zonos-elements/p-9389cc42.system.entry.js +1 -0
  141. package/dist/zonos-elements/p-9be6c62b.system.js +1 -0
  142. package/dist/zonos-elements/p-9c242e4b.system.entry.js +1 -0
  143. package/dist/zonos-elements/p-a37796e1.entry.js +1 -0
  144. package/dist/zonos-elements/p-afb89d65.entry.js +1 -0
  145. package/dist/zonos-elements/p-bbb84165.system.entry.js +1 -0
  146. package/dist/zonos-elements/{p-96b8c9ba.system.entry.js → p-bdfa3705.system.entry.js} +1 -1
  147. package/dist/zonos-elements/p-c195e980.system.entry.js +1 -0
  148. package/dist/zonos-elements/p-c87c76d4.entry.js +1 -0
  149. package/dist/zonos-elements/p-d9011df9.entry.js +1 -0
  150. package/dist/zonos-elements/{p-3e26d7b3.system.entry.js → p-dda78e8e.system.entry.js} +1 -1
  151. package/dist/zonos-elements/p-de9e610d.system.entry.js +1 -0
  152. package/dist/zonos-elements/p-e0bf9666.system.js +1 -1
  153. package/dist/zonos-elements/p-eaa335e1.js +1 -0
  154. package/dist/zonos-elements/{p-e13bfbda.system.entry.js → p-ed3524ae.system.entry.js} +1 -1
  155. package/dist/zonos-elements/p-f5b14bab.system.js +1 -0
  156. package/dist/zonos-elements/p-f9a42a3c.system.entry.js +1 -0
  157. package/dist/zonos-elements/zonos-elements.esm.js +1 -1
  158. package/package.json +4 -2
  159. package/dist/components/ILanguage.js +0 -24
  160. package/dist/components/classes.js +0 -12
  161. package/dist/components/containsNonLatinChars.js +0 -21
  162. package/dist/components/formatCurrency.js +0 -11
  163. package/dist/components/getBorderRadius.js +0 -18
  164. package/dist/components/index.d.ts +0 -33
  165. package/dist/components/index.js +0 -1
  166. package/dist/components/isCheckoutMobile.js +0 -6
  167. package/dist/components/isColorVariable.js +0 -14
  168. package/dist/components/isDarkColor.js +0 -1199
  169. package/dist/components/stripe.js +0 -1691
  170. package/dist/components/submitGtag.js +0 -19
  171. package/dist/components/trackConversionEvent.js +0 -37
  172. package/dist/components/translationStore.js +0 -5611
  173. package/dist/components/zonos-address-display.d.ts +0 -11
  174. package/dist/components/zonos-address-display.js +0 -6
  175. package/dist/components/zonos-address-display2.js +0 -64
  176. package/dist/components/zonos-address-form.d.ts +0 -11
  177. package/dist/components/zonos-address-form.js +0 -6
  178. package/dist/components/zonos-address-form2.js +0 -84
  179. package/dist/components/zonos-address-update-dialog.d.ts +0 -11
  180. package/dist/components/zonos-address-update-dialog.js +0 -6
  181. package/dist/components/zonos-address-update-dialog2.js +0 -264
  182. package/dist/components/zonos-address.d.ts +0 -11
  183. package/dist/components/zonos-address.js +0 -6
  184. package/dist/components/zonos-address2.js +0 -176
  185. package/dist/components/zonos-badge.d.ts +0 -11
  186. package/dist/components/zonos-badge.js +0 -6
  187. package/dist/components/zonos-badge2.js +0 -61
  188. package/dist/components/zonos-banner.d.ts +0 -11
  189. package/dist/components/zonos-banner.js +0 -6
  190. package/dist/components/zonos-banner2.js +0 -95
  191. package/dist/components/zonos-button.d.ts +0 -11
  192. package/dist/components/zonos-button.js +0 -6
  193. package/dist/components/zonos-button2.js +0 -186
  194. package/dist/components/zonos-card.d.ts +0 -11
  195. package/dist/components/zonos-card.js +0 -6
  196. package/dist/components/zonos-card2.js +0 -57
  197. package/dist/components/zonos-cart-items.d.ts +0 -11
  198. package/dist/components/zonos-cart-items.js +0 -6
  199. package/dist/components/zonos-cart-items2.js +0 -57
  200. package/dist/components/zonos-cart-restricted-items.d.ts +0 -11
  201. package/dist/components/zonos-cart-restricted-items.js +0 -6
  202. package/dist/components/zonos-cart-restricted-items2.js +0 -135
  203. package/dist/components/zonos-cart-subtotal.d.ts +0 -11
  204. package/dist/components/zonos-cart-subtotal.js +0 -6
  205. package/dist/components/zonos-cart-subtotal2.js +0 -91
  206. package/dist/components/zonos-checkbox.d.ts +0 -11
  207. package/dist/components/zonos-checkbox.js +0 -6
  208. package/dist/components/zonos-checkbox2.js +0 -96
  209. package/dist/components/zonos-checkout-finish.d.ts +0 -11
  210. package/dist/components/zonos-checkout-finish.js +0 -6
  211. package/dist/components/zonos-checkout-finish2.js +0 -246
  212. package/dist/components/zonos-checkout-footer.d.ts +0 -11
  213. package/dist/components/zonos-checkout-footer.js +0 -6
  214. package/dist/components/zonos-checkout-footer2.js +0 -125
  215. package/dist/components/zonos-checkout-payment.d.ts +0 -11
  216. package/dist/components/zonos-checkout-payment.js +0 -6
  217. package/dist/components/zonos-checkout-payment2.js +0 -104
  218. package/dist/components/zonos-checkout-progress-tabs.d.ts +0 -11
  219. package/dist/components/zonos-checkout-progress-tabs.js +0 -6
  220. package/dist/components/zonos-checkout-progress-tabs2.js +0 -138
  221. package/dist/components/zonos-checkout.d.ts +0 -11
  222. package/dist/components/zonos-checkout.js +0 -1051
  223. package/dist/components/zonos-collapse.d.ts +0 -11
  224. package/dist/components/zonos-collapse.js +0 -6
  225. package/dist/components/zonos-collapse2.js +0 -78
  226. package/dist/components/zonos-component.d.ts +0 -11
  227. package/dist/components/zonos-component.js +0 -48
  228. package/dist/components/zonos-confirm-dialog.d.ts +0 -11
  229. package/dist/components/zonos-confirm-dialog.js +0 -6
  230. package/dist/components/zonos-confirm-dialog2.js +0 -161
  231. package/dist/components/zonos-controller.d.ts +0 -11
  232. package/dist/components/zonos-controller.js +0 -309
  233. package/dist/components/zonos-country-flag.d.ts +0 -11
  234. package/dist/components/zonos-country-flag.js +0 -6
  235. package/dist/components/zonos-country-flag2.js +0 -54
  236. package/dist/components/zonos-country-select.d.ts +0 -11
  237. package/dist/components/zonos-country-select.js +0 -6
  238. package/dist/components/zonos-country-select2.js +0 -1891
  239. package/dist/components/zonos-custom-message.d.ts +0 -11
  240. package/dist/components/zonos-custom-message.js +0 -6
  241. package/dist/components/zonos-custom-message2.js +0 -72
  242. package/dist/components/zonos-customer-info.d.ts +0 -11
  243. package/dist/components/zonos-customer-info.js +0 -6
  244. package/dist/components/zonos-customer-info2.js +0 -316
  245. package/dist/components/zonos-dialog.d.ts +0 -11
  246. package/dist/components/zonos-dialog.js +0 -6
  247. package/dist/components/zonos-dialog2.js +0 -136
  248. package/dist/components/zonos-hello-dialog-footer.d.ts +0 -11
  249. package/dist/components/zonos-hello-dialog-footer.js +0 -6
  250. package/dist/components/zonos-hello-dialog-footer2.js +0 -83
  251. package/dist/components/zonos-hello-dialog.d.ts +0 -11
  252. package/dist/components/zonos-hello-dialog.js +0 -6
  253. package/dist/components/zonos-hello-dialog2.js +0 -305
  254. package/dist/components/zonos-hello.d.ts +0 -11
  255. package/dist/components/zonos-hello.js +0 -879
  256. package/dist/components/zonos-icon.d.ts +0 -11
  257. package/dist/components/zonos-icon.js +0 -6
  258. package/dist/components/zonos-icon2.js +0 -55
  259. package/dist/components/zonos-input.d.ts +0 -11
  260. package/dist/components/zonos-input.js +0 -6
  261. package/dist/components/zonos-input2.js +0 -78
  262. package/dist/components/zonos-language-select.d.ts +0 -11
  263. package/dist/components/zonos-language-select.js +0 -6
  264. package/dist/components/zonos-language-select2.js +0 -88
  265. package/dist/components/zonos-link-authentication.d.ts +0 -11
  266. package/dist/components/zonos-link-authentication.js +0 -6
  267. package/dist/components/zonos-link-authentication2.js +0 -80
  268. package/dist/components/zonos-link.d.ts +0 -11
  269. package/dist/components/zonos-link.js +0 -43
  270. package/dist/components/zonos-logo.d.ts +0 -11
  271. package/dist/components/zonos-logo.js +0 -49
  272. package/dist/components/zonos-notification.d.ts +0 -11
  273. package/dist/components/zonos-notification.js +0 -6
  274. package/dist/components/zonos-notification2.js +0 -92
  275. package/dist/components/zonos-payment.d.ts +0 -11
  276. package/dist/components/zonos-payment.js +0 -6
  277. package/dist/components/zonos-payment2.js +0 -77
  278. package/dist/components/zonos-review.d.ts +0 -11
  279. package/dist/components/zonos-review.js +0 -6
  280. package/dist/components/zonos-review2.js +0 -89
  281. package/dist/components/zonos-select-dialog-header.d.ts +0 -11
  282. package/dist/components/zonos-select-dialog-header.js +0 -6
  283. package/dist/components/zonos-select-dialog-header2.js +0 -71
  284. package/dist/components/zonos-shipping-rich-radio.d.ts +0 -11
  285. package/dist/components/zonos-shipping-rich-radio.js +0 -6
  286. package/dist/components/zonos-shipping-rich-radio2.js +0 -88
  287. package/dist/components/zonos-shipping.d.ts +0 -11
  288. package/dist/components/zonos-shipping.js +0 -6
  289. package/dist/components/zonos-shipping2.js +0 -159
  290. package/dist/components/zonos-spinner.d.ts +0 -11
  291. package/dist/components/zonos-spinner.js +0 -6
  292. package/dist/components/zonos-spinner2.js +0 -43
  293. package/dist/components/zonos-text.d.ts +0 -11
  294. package/dist/components/zonos-text.js +0 -6
  295. package/dist/components/zonos-text2.js +0 -182
  296. package/dist/components/zonos-tooltip.d.ts +0 -11
  297. package/dist/components/zonos-tooltip.js +0 -6
  298. package/dist/components/zonos-tooltip2.js +0 -48
  299. package/dist/components/zonos-v-stack.d.ts +0 -11
  300. package/dist/components/zonos-v-stack.js +0 -6
  301. package/dist/components/zonos-v-stack2.js +0 -38
  302. package/dist/components/zonosStore.js +0 -2881
  303. package/dist/esm-es5/cart-cc593c2b.js +0 -1
  304. package/dist/esm-es5/submitGtag-e50f903f.js +0 -1
  305. package/dist/scripts/checkIfLoadVersionDomain.js +0 -1
  306. package/dist/scripts/extractZonosQaUrl.js +0 -1
  307. package/dist/scripts/getTempCartById.js +0 -1
  308. package/dist/scripts/loadStripe.js +0 -1
  309. package/dist/scripts/stripe.js +0 -1
  310. package/dist/scripts/zonosBase.js +0 -1
  311. package/dist/zonos-elements/p-04030a48.entry.js +0 -1
  312. package/dist/zonos-elements/p-0e892292.entry.js +0 -1
  313. package/dist/zonos-elements/p-0fac99e7.entry.js +0 -1
  314. package/dist/zonos-elements/p-1795c760.system.entry.js +0 -1
  315. package/dist/zonos-elements/p-24ac1c6f.entry.js +0 -1
  316. package/dist/zonos-elements/p-26a60a6e.entry.js +0 -1
  317. package/dist/zonos-elements/p-32744531.entry.js +0 -1
  318. package/dist/zonos-elements/p-35ac375a.system.entry.js +0 -1
  319. package/dist/zonos-elements/p-3bc88c3c.system.entry.js +0 -1
  320. package/dist/zonos-elements/p-4caaaaeb.system.entry.js +0 -1
  321. package/dist/zonos-elements/p-50ea2036.system.js +0 -1
  322. package/dist/zonos-elements/p-5e783394.entry.js +0 -1
  323. package/dist/zonos-elements/p-6366e7e3.entry.js +0 -1
  324. package/dist/zonos-elements/p-7c8ee4b9.system.entry.js +0 -1
  325. package/dist/zonos-elements/p-80ea85b8.entry.js +0 -1
  326. package/dist/zonos-elements/p-8da16d53.system.js +0 -1
  327. package/dist/zonos-elements/p-98a0b694.system.entry.js +0 -1
  328. package/dist/zonos-elements/p-b98cdf39.system.entry.js +0 -1
  329. package/dist/zonos-elements/p-d7b8c1c1.system.entry.js +0 -1
  330. package/dist/zonos-elements/p-dd0fd351.entry.js +0 -1
  331. package/dist/zonos-elements/p-e015cb0e.js +0 -1
  332. package/dist/zonos-elements/p-e1fbd05d.system.entry.js +0 -1
  333. package/dist/zonos-elements/p-e553dd19.js +0 -1
  334. package/dist/zonos-elements/p-e6fa0ebc.system.js +0 -1
  335. package/dist/zonos-elements/p-f6546bf4.system.entry.js +0 -1
  336. /package/dist/collection/components/common/{component-template/zonos-link → zonos-link}/zonos-link.css +0 -0
  337. /package/dist/collection/scripts/{checkIfLoadVersionDomain.js → _checkIfLoadVersionDomain.js} +0 -0
  338. /package/dist/collection/scripts/{stripe.js → _stripe.js} +0 -0
  339. /package/dist/types/components/common/{component-template/zonos-link → zonos-link}/zonos-link.d.ts +0 -0
  340. /package/dist/types/scripts/{checkIfLoadVersionDomain.d.ts → _checkIfLoadVersionDomain.d.ts} +0 -0
  341. /package/dist/types/scripts/{stripe.d.ts → _stripe.d.ts} +0 -0
@@ -1,1691 +0,0 @@
1
- import { z as zonosStore, c as createStore } from './zonosStore.js';
2
- import { t as translationStoreUpdateLanguage, a as translate } from './translationStore.js';
3
- import { i as isDarkColor } from './isDarkColor.js';
4
- import { g as getBorderRadius } from './getBorderRadius.js';
5
-
6
- var __rest = (undefined && undefined.__rest) || function (s, e) {
7
- var t = {};
8
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
9
- t[p] = s[p];
10
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
11
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
12
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
13
- t[p[i]] = s[p[i]];
14
- }
15
- return t;
16
- };
17
- const getResponseBody = async ({ response, shouldLog = true, shouldThrow = false, }) => {
18
- try {
19
- const json = await response.json();
20
- return json;
21
- }
22
- catch (e) {
23
- if (shouldThrow) {
24
- throw e;
25
- }
26
- if (shouldLog) {
27
- // eslint-disable-next-line
28
- console.error(e);
29
- }
30
- return null;
31
- }
32
- };
33
- const handleRequest = async (url, options) => {
34
- let response;
35
- try {
36
- response = await fetch(url, options);
37
- }
38
- catch (e) {
39
- if (e instanceof Error) {
40
- return {
41
- errors: [{ message: e.message, type: 'unknown' }],
42
- json: null,
43
- response: null,
44
- };
45
- }
46
- const message = 'Fail to fetch';
47
- return {
48
- errors: [{ message, type: 'unknown' }],
49
- json: null,
50
- response: null,
51
- };
52
- }
53
- const zonosMode = response.headers.get('Zonos-Mode');
54
- const usingZonosPreview = window.Zonos.zonosQaUrl;
55
- // We only want to alert once if the user is in preview mode and it's also using production environment
56
- if (!window.Zonos.modeAlerted && zonosMode && usingZonosPreview) {
57
- if (zonosMode === 'production') {
58
- alert(`Please be aware that you are currently operating in the production environment. Any interactions with the customer store, including payments, will be processed as real transactions!`);
59
- }
60
- if (zonosMode === 'test') {
61
- alert(`For testing payments, you can utilize the test payment information provided at this link: https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=elements#web-test-the-integration`);
62
- }
63
- window.Zonos.modeAlerted = true;
64
- }
65
- if (response.ok) {
66
- const data = await getResponseBody({ response });
67
- return {
68
- errors: [],
69
- json: data,
70
- response,
71
- };
72
- }
73
- const status = response.status.toString();
74
- try {
75
- const data = await getResponseBody({
76
- response,
77
- shouldThrow: true,
78
- });
79
- const message = JSON.stringify(data);
80
- return {
81
- errors: [{ message: `${status}: ${message}`, type: status }],
82
- json: null,
83
- response,
84
- };
85
- }
86
- catch (e) {
87
- const message = 'Unknown error';
88
- return {
89
- errors: [{ message: `${status}: ${message}`, type: status }],
90
- json: null,
91
- response: null,
92
- };
93
- }
94
- };
95
- function encodeString(text) {
96
- try {
97
- // encode the string, remove the "=" at the end of the encoded string
98
- const encodedString = btoa(text).replace(/=/g, '');
99
- return encodedString;
100
- }
101
- catch (error) {
102
- // return the reverse string if the encoding failed
103
- return text
104
- .replace(/[^A-Za-z0-9]/g, '')
105
- .split('')
106
- .reverse()
107
- .join('');
108
- }
109
- }
110
- const handleFetch = async (url, _opts) => {
111
- const opts = __rest(_opts || {}, []);
112
- const body = opts.body ? JSON.stringify(opts.body) : undefined;
113
- const method = opts.method || 'GET';
114
- // adding random encoded token to the url so that the request will be cached differently for each store
115
- const modifiedUrl = new URL(url);
116
- modifiedUrl.searchParams.set('zToken', encodeString(window.location.hostname));
117
- // headers content type
118
- const headers = Object.assign({ 'Content-Type': 'application/json', 'Zonos-Is-BigCommerce': window.Zonos.isBigCommerce.toString(), 'Zonos-Referer': window.location.hostname, 'Zonos-Version': window.Zonos.version, credentialtoken: window.Zonos.zonosApiKey || 'Empty credential token from zonos-elements' }, opts.headers);
119
- const options = Object.assign(Object.assign({}, opts), { body: method === 'GET' ? undefined : body, headers,
120
- method });
121
- return handleRequest(modifiedUrl.toString(), options);
122
- };
123
-
124
- const getCountries = async () => {
125
- try {
126
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/get-countries`, {
127
- method: 'GET',
128
- });
129
- if (errors.length || !json) {
130
- return null;
131
- }
132
- return json;
133
- }
134
- catch (error) {
135
- return null;
136
- }
137
- };
138
-
139
- const log = (message, type, ...additionalInfo) => {
140
- var _a, _b;
141
- const isDebug = !!((_a = window.Zonos) === null || _a === void 0 ? void 0 : _a.debug) ||
142
- !!window.location.search.match(/\?.*(&*)zonosDebug=1/);
143
- // if debug is false, do not log
144
- if (!isDebug) {
145
- // log errors to the console if the type is error
146
- if (type === 'error') {
147
- // eslint-disable-next-line no-console
148
- console.error(message, ...additionalInfo);
149
- }
150
- return;
151
- }
152
- let loggingIframe = document.querySelector('iframe#zonos---debug-logging-iframe');
153
- if (!loggingIframe) {
154
- // add a hidden iframe
155
- loggingIframe = document.createElement('iframe');
156
- loggingIframe.id = 'zonos---debug-logging-iframe';
157
- loggingIframe.style.display = 'none';
158
- loggingIframe.style.opacity = '0';
159
- loggingIframe.style.position = 'absolute';
160
- loggingIframe.style.top = '-9999px';
161
- loggingIframe.style.left = '-9999px';
162
- loggingIframe.style.width = '1px';
163
- loggingIframe.style.height = '1px';
164
- loggingIframe.style.border = 'none';
165
- loggingIframe.style.overflow = 'hidden';
166
- loggingIframe.style.visibility = 'hidden';
167
- document.body.appendChild(loggingIframe);
168
- }
169
- // use the logging iframe's console to log just in case the console is disabled (overriden) by the site owner
170
- const zConsole = ((_b = loggingIframe.contentWindow) === null || _b === void 0 ? void 0 : _b.window.console) || window.console;
171
- switch (type) {
172
- case 'warn':
173
- zConsole.warn(message, ...additionalInfo);
174
- break;
175
- case 'info':
176
- zConsole.info(message, ...additionalInfo);
177
- break;
178
- case 'error':
179
- zConsole.error(message, ...additionalInfo);
180
- break;
181
- default:
182
- zConsole.groupCollapsed(message, ...additionalInfo);
183
- zConsole.trace();
184
- zConsole.groupEnd();
185
- break;
186
- }
187
- };
188
-
189
- const logError = (message, ...rest) => {
190
- log(message, 'error', ...rest);
191
- };
192
-
193
- const getCountryLandedCost = async (countryCode) => {
194
- var _a;
195
- if (!countryCode) {
196
- return null;
197
- }
198
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/country-landed-cost/${countryCode}`;
199
- const { errors, json } = await handleFetch(url);
200
- if (errors.length || !json) {
201
- logError(`Error fetching country landed cost: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
202
- return null;
203
- }
204
- return json || null;
205
- };
206
-
207
- const getExchangeRate = async ({ country, isGuaranteed, sourceCurrency, targetCurrency, }) => {
208
- var _a;
209
- // If source currency matches target currency (US -> US) and is not a guaranteed rate, return null
210
- if (sourceCurrency === targetCurrency && !isGuaranteed) {
211
- return { exchangeRate: null, maxAge: null };
212
- }
213
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/exchange-rates?sourceCurrency=${sourceCurrency}&targetCurrency=${targetCurrency}&isGuaranteed=${isGuaranteed}&country=${country}`;
214
- const { errors, json } = await handleFetch(url);
215
- if (errors.length || !json) {
216
- logError(`Error fetching country landed cost: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
217
- return { exchangeRate: null, maxAge: null };
218
- }
219
- const { maxAge, rate, targetFormat } = json.exchangeRateCreate;
220
- if (rate) {
221
- sessionStorage.setItem(country + '_rate', JSON.stringify(rate));
222
- const exchangeRate = { rate, targetFormat };
223
- return { exchangeRate, maxAge };
224
- }
225
- return { exchangeRate: null, maxAge: null };
226
- };
227
-
228
- const getLocaleMessages = async ({ countryCode, localeTo, storeId, }) => {
229
- var _a;
230
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/locale-messages?countryCode=${countryCode}&storeId=${storeId}&localeTo=${localeTo}`;
231
- const { errors, json } = await handleFetch(url);
232
- if (errors.length || !json) {
233
- logError('Error fetching exchange rate', (_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message);
234
- return [];
235
- }
236
- return json.locale_countryCodesPage;
237
- };
238
-
239
- const getZCountryUrlParam = (urlParams) => {
240
- const urlSearchParams = new URLSearchParams(urlParams || window.location.search);
241
- const zCountry = urlSearchParams.get('zCountry');
242
- return zCountry;
243
- };
244
-
245
- const getLocalization = async () => {
246
- try {
247
- const currentUrl = new URL(window.location.href);
248
- // load and use country from session storage when zCountry query param is not present
249
- const countryLoadedSession = window.sessionStorage.getItem('zonos--country');
250
- const zCountry = getZCountryUrlParam(currentUrl.searchParams) || countryLoadedSession;
251
- const localizationUrl = new URL(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/localization`);
252
- if (zCountry) {
253
- localizationUrl.searchParams.set('zCountry', zCountry);
254
- }
255
- const fetchUrl = localizationUrl.href;
256
- const { errors, json } = await handleFetch(fetchUrl, {
257
- method: 'GET',
258
- });
259
- if (errors.length || !json) {
260
- return { country: null, locale: null };
261
- }
262
- return {
263
- country: json.country,
264
- locale: json.locale,
265
- };
266
- }
267
- catch (error) {
268
- return { country: null, locale: null };
269
- }
270
- };
271
-
272
- const getShippingZones = async () => {
273
- var _a, _b;
274
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/shipping-zones`;
275
- const { errors, json } = await handleFetch(url);
276
- if (errors.length || !json) {
277
- logError(`Error fetching shipping zones: ${(_a = errors.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message}`);
278
- return null;
279
- }
280
- const shippingZones = (_b = json === null || json === void 0 ? void 0 : json.shippingZones) === null || _b === void 0 ? void 0 : _b.flatMap(zone => zone === null || zone === void 0 ? void 0 : zone.countryCodes).filter(Boolean);
281
- return shippingZones || null;
282
- };
283
-
284
- const currencyConvert = (value) => {
285
- // TODO(potentially): Bring over the code for vanity checks
286
- const { exchangeRate } = localizationStore;
287
- if (!exchangeRate || !value || isNaN(value)) {
288
- return value;
289
- }
290
- const minimumFractionDigits = (exchangeRate === null || exchangeRate === void 0 ? void 0 : exchangeRate.targetFormat.scale) || 2;
291
- const convertedValue = value * exchangeRate.rate;
292
- const fixedValue = convertedValue.toFixed(minimumFractionDigits);
293
- return Number(fixedValue);
294
- };
295
-
296
- const currencyFormat = (value) => {
297
- if (!value || isNaN(value)) {
298
- return '';
299
- }
300
- const { exchangeRate } = localizationStore;
301
- const { targetFormat } = exchangeRate || {};
302
- if (!targetFormat) {
303
- return value.toString();
304
- }
305
- const minimumFractionDigits = (exchangeRate === null || exchangeRate === void 0 ? void 0 : exchangeRate.targetFormat.scale) || 2;
306
- // browsers can autoformat the currency based on the users language setting
307
- // unless the browser is Internet Explorer, because Internet Explorer is stupid
308
- const isIE = window.navigator.userAgent.indexOf('MSIE ') !== -1;
309
- const numberFormatExists = typeof Intl === 'object' && Intl && typeof Intl.NumberFormat === 'function';
310
- if (!isIE && numberFormatExists) {
311
- return new Intl.NumberFormat(window.navigator.language, {
312
- currency: targetFormat.currencyCode,
313
- minimumFractionDigits: minimumFractionDigits,
314
- style: 'currency',
315
- }).format(value);
316
- }
317
- else {
318
- let formattedNumber = Number(value)
319
- .toFixed(minimumFractionDigits)
320
- .replace('.', '|dec|')
321
- .replace(',', targetFormat.thousandsDelimiter || '')
322
- .replace('|dec|', targetFormat.decimalDelimiter || '');
323
- const result = `${targetFormat.symbol}${formattedNumber}${targetFormat.currencyCode !== 'USD' ? ` ${targetFormat.currencyCode}` : ''}`;
324
- return result;
325
- }
326
- };
327
-
328
- const currencyConvertAndFormat = (value) => {
329
- const convertedValue = currencyConvert(value);
330
- const formattedValue = currencyFormat(convertedValue);
331
- return formattedValue;
332
- };
333
-
334
- /**
335
- * Check if selector user pass is valid
336
- * @example
337
- * isValidSelector('div') // true
338
- * isValidSelector('div + >>> span') // false
339
- */
340
- const isValidSelector = (selector) => {
341
- try {
342
- // this will error out if the selector is invalid in the DOM
343
- document.createDocumentFragment().querySelector(selector);
344
- }
345
- catch (e) {
346
- return false;
347
- }
348
- return true;
349
- };
350
-
351
- const getCurrencyElements = (selector) => {
352
- const currencySelector = selector || '.money';
353
- if (!isValidSelector(currencySelector)) {
354
- logError(`Currency element selector "${currencySelector}" is not valid.`);
355
- return null;
356
- }
357
- const currencyElements = document.querySelectorAll(currencySelector);
358
- if (!currencyElements.length) {
359
- log(`No currency elements found with selector "${currencySelector}"`, 'warn');
360
- return null;
361
- }
362
- // return array of currency elements instead of a NodeList
363
- return Array.from(currencyElements);
364
- };
365
-
366
- const getInitialElementAmount = (element) => {
367
- var _a;
368
- const domesticValue = element.getAttribute('data-domestic');
369
- const intlValue = element.getAttribute('data-zintl');
370
- // Only keep numbers, decimal, and hyphens
371
- const cleanedText = (_a = element.textContent) === null || _a === void 0 ? void 0 : _a.replace(/[^\d.-]/g, '');
372
- if (!cleanedText) {
373
- return null;
374
- }
375
- // If the element has no data-domestic attribute, or the text content is different from the data-zintl attribute, set the data-domestic attribute
376
- if (!domesticValue || (element.textContent !== intlValue && intlValue)) {
377
- // Store the original value on the element once, and international on every new conversion
378
- element.setAttribute('data-domestic', cleanedText);
379
- return parseFloat(cleanedText);
380
- }
381
- return parseFloat(domesticValue);
382
- };
383
-
384
- const convertCurrency = (element) => {
385
- var _a;
386
- const amount = getInitialElementAmount(element);
387
- if (!amount || isNaN(amount)) {
388
- return;
389
- }
390
- const currentIntlValue = element.getAttribute('data-zintl');
391
- const currentCountryValue = element.getAttribute('data-zcountry-code');
392
- // do nothing if the target currency is the same
393
- const isExchangeRateReady = localizationStore.targetCurrency ===
394
- ((_a = localizationStore.exchangeRate) === null || _a === void 0 ? void 0 : _a.targetFormat.currencyCode);
395
- // if the current value on the element is different from the current intl value, update the data-zintl attribute
396
- if (isExchangeRateReady &&
397
- (element.textContent !== currentIntlValue ||
398
- currentCountryValue !== localizationStore.selectedCountryCode)) {
399
- const observedFormattedValue = currencyConvertAndFormat(amount);
400
- element.textContent = observedFormattedValue;
401
- // save the new value to the data-zintl attribute
402
- element.setAttribute('data-zintl', observedFormattedValue);
403
- element.setAttribute('data-zcountry-code', localizationStore.selectedCountryCode || '');
404
- }
405
- };
406
- const defaultCurrencyConverter = () => {
407
- const { currencyElementSelector } = zonosStore.helloSettings;
408
- const currencyElements = getCurrencyElements(currencyElementSelector);
409
- // do nothing if none of the currency elements are found
410
- if (!(currencyElements === null || currencyElements === void 0 ? void 0 : currencyElements.length)) {
411
- return;
412
- }
413
- if (!localizationStore.exchangeRate) {
414
- logError('Could not display currency. Exchange rate and format data is not available.');
415
- return;
416
- }
417
- currencyElements.forEach((element) => {
418
- // convert the currency and save the formatted value to the data-zintl attribute
419
- convertCurrency(element);
420
- });
421
- };
422
-
423
- const currencyDisplay = () => {
424
- if (zonosStore.helloSettings.currencyBehavior === 'DISABLED') {
425
- return;
426
- }
427
- const { currencyElementSelector } = zonosStore.helloSettings;
428
- if (zonosStore.currencyConverter) {
429
- zonosStore.currencyConverter({
430
- convert: currencyConvert,
431
- convertAndFormat: currencyConvertAndFormat,
432
- format: currencyFormat,
433
- selector: currencyElementSelector,
434
- });
435
- }
436
- else {
437
- defaultCurrencyConverter();
438
- }
439
- };
440
-
441
- const getCurrencyCode = (code) => {
442
- var _a;
443
- const countryInShippingZone = (_a = localizationStore.shippingZoneCountries) === null || _a === void 0 ? void 0 : _a[code];
444
- if (countryInShippingZone) {
445
- return countryInShippingZone.currencyCode;
446
- }
447
- return null;
448
- };
449
-
450
- const setZCountryUrlParam = (selectedCountryCode) => {
451
- if (!selectedCountryCode) {
452
- return;
453
- }
454
- const urlSearchParams = new URLSearchParams(window.location.search);
455
- urlSearchParams.set('zCountry', selectedCountryCode);
456
- const newUrl = `${window.location.pathname}?${urlSearchParams.toString()}`;
457
- window.history.replaceState({}, '', newUrl);
458
- };
459
-
460
- const { onChange: localizationStoreOnUpdate, state: localizationStore } = createStore({
461
- countryLandedCost: null,
462
- customMessages: [],
463
- exchangeRate: null,
464
- isShippableCountry: false,
465
- localizationLoaded: false,
466
- selectedCountryCode: null,
467
- selectedLocale: 'en',
468
- shippingZoneCountries: null,
469
- targetCurrency: 'USD',
470
- });
471
- const triggerGetExchangeRate = async (isGuaranteed) => {
472
- const { exchangeRate, maxAge } = await getExchangeRate({
473
- country: localizationStore.selectedCountryCode,
474
- isGuaranteed,
475
- sourceCurrency: zonosStore.sourceCurrency,
476
- targetCurrency: localizationStore.targetCurrency,
477
- });
478
- if (exchangeRate) {
479
- localizationStore.exchangeRate = exchangeRate;
480
- currencyDisplay();
481
- }
482
- return { maxAge };
483
- };
484
- // This recursive function is for users who step away from their computer and come back needing a new exchange rate
485
- const startExchangeRateTimeout = ({ isGuaranteed, maxAge, }) => {
486
- if (localizationStore.exchangeRateTimeout) {
487
- clearTimeout(localizationStore.exchangeRateTimeout);
488
- }
489
- // maxAge comes in seconds, convert to milliseconds
490
- const defaultMaxAge = 5 * 60;
491
- const maxAgeToUse = maxAge || defaultMaxAge;
492
- // Recursively set timeouts to get new exchange rates when the current one expires
493
- localizationStore.exchangeRateTimeout = setTimeout(async () => {
494
- const { maxAge: newMaxAge } = await triggerGetExchangeRate(isGuaranteed);
495
- startExchangeRateTimeout({ isGuaranteed, maxAge: newMaxAge });
496
- }, maxAgeToUse * 1000);
497
- };
498
- const getNewLocalization = async () => {
499
- log('get new localization store');
500
- const { isShippableCountry, selectedCountryCode } = localizationStore;
501
- if (zonosStore.helloSettings.currencyBehavior === 'DISABLED' ||
502
- !isShippableCountry ||
503
- !selectedCountryCode) {
504
- return;
505
- }
506
- const isGuaranteed = zonosStore.checkoutSettings.visibilityStatus === 'ENABLED';
507
- const { maxAge } = await triggerGetExchangeRate(isGuaranteed);
508
- startExchangeRateTimeout({ isGuaranteed, maxAge });
509
- localizationStore.countryLandedCost = await getCountryLandedCost(localizationStore.selectedCountryCode);
510
- };
511
- const getCustomMessages = async () => {
512
- if (!localizationStore.selectedCountryCode || !zonosStore.storeId) {
513
- return;
514
- }
515
- const localeMessages = await getLocaleMessages({
516
- countryCode: localizationStore.selectedCountryCode,
517
- localeTo: localizationStore.selectedLocale,
518
- storeId: zonosStore.storeId,
519
- });
520
- const allMessages = localeMessages.flatMap(x => {
521
- var _a;
522
- return {
523
- countryCode: localizationStore.selectedCountryCode,
524
- message: (_a = x.countryCodesPageMessageLinks.find(Boolean)) === null || _a === void 0 ? void 0 : _a.message.textTo,
525
- pageName: x.pageName,
526
- };
527
- });
528
- localizationStore.customMessages = allMessages;
529
- };
530
- const getOverrideLocale = () => {
531
- const currentUrl = new URL(window.location.href);
532
- const zonosLocale = currentUrl.searchParams.get('zonosLocale');
533
- return zonosLocale;
534
- };
535
- const localizationStoreUpdateSelectedCountryCode = (newSelectedCountryCode) => {
536
- var _a, _b;
537
- log('update selected country code');
538
- localizationStore.selectedCountryCode = newSelectedCountryCode;
539
- const { selectedCountryCode, shippingZoneCountries } = localizationStore;
540
- const isShippableCountry = shippingZoneCountries &&
541
- selectedCountryCode &&
542
- !!shippingZoneCountries[selectedCountryCode];
543
- // update shippable country
544
- localizationStore.isShippableCountry = !!isShippableCountry;
545
- log(`Is shippable country: ${localizationStore.isShippableCountry}`);
546
- if (!selectedCountryCode) {
547
- return;
548
- }
549
- const currencyCode = getCurrencyCode(selectedCountryCode);
550
- if (!currencyCode) {
551
- return;
552
- }
553
- localizationStore.targetCurrency = currencyCode;
554
- void getNewLocalization();
555
- void getCustomMessages();
556
- // Save the country code to session storage for later use
557
- window.sessionStorage.setItem('zonos--country', selectedCountryCode);
558
- // Update the URL query param with the new country code
559
- setZCountryUrlParam(selectedCountryCode);
560
- (_a = document
561
- .querySelector('zonos-hello')) === null || _a === void 0 ? void 0 : _a.setAttribute('z-country', selectedCountryCode);
562
- // Trigger callback onCountryChange
563
- (_b = zonosStore.onCountryChange) === null || _b === void 0 ? void 0 : _b.call(zonosStore, {
564
- countryCode: selectedCountryCode,
565
- currencyCode,
566
- });
567
- };
568
- const initLocalizationStore = async () => {
569
- // all countries from countries.json, shipping zone and localization
570
- const [allCountries, shippingZoneCountries, localization] = await Promise.all([getCountries(), getShippingZones(), getLocalization()]);
571
- // Filter countries to only include countries in the shipping zone
572
- const filteredCountries = shippingZoneCountries === null || shippingZoneCountries === void 0 ? void 0 : shippingZoneCountries.reduce((acc, countryCode) => {
573
- const countryInfo = allCountries === null || allCountries === void 0 ? void 0 : allCountries[countryCode];
574
- return countryInfo && countryInfo.active
575
- ? Object.assign(Object.assign({}, acc), { [countryCode]: countryInfo }) : acc;
576
- }, {});
577
- localizationStore.shippingZoneCountries = filteredCountries || null;
578
- const { country, locale } = localization;
579
- // update selected country code in store
580
- void localizationStoreUpdateSelectedCountryCode(country);
581
- // use locale from params if it exists, otherwise use locale from localization
582
- const overrideLocale = getOverrideLocale();
583
- localizationStore.selectedLocale = overrideLocale || locale || 'en';
584
- translationStoreUpdateLanguage(localizationStore.selectedLocale);
585
- const devSites = [
586
- 'dev.storybook.elements',
587
- 'dev.elements',
588
- 'dev.demo.elements',
589
- 'dev.dashboard',
590
- ];
591
- // If the country code is not set, set it to the US for development (vercel can't get geo country in dev)
592
- if (!localizationStore.selectedCountryCode &&
593
- devSites.some(site => window.location.origin.includes(site))) {
594
- // update selected country code in store
595
- void localizationStoreUpdateSelectedCountryCode('US');
596
- }
597
- localizationStore.localizationLoaded = true;
598
- void getCustomMessages();
599
- };
600
- const updateCheckoutSessionLanguage = async () => {
601
- if (!cartStore.checkoutSessionId) {
602
- return null;
603
- }
604
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/update-checkout-session-metadata`, {
605
- body: {
606
- id: cartStore.checkoutSessionId,
607
- metadata: [
608
- {
609
- key: 'language',
610
- value: localizationStore.selectedLocale,
611
- },
612
- ],
613
- },
614
- method: 'POST',
615
- });
616
- if (errors.length || !json) {
617
- logError('Error occurs when updating checkout session', JSON.stringify(errors, null, 2));
618
- return { errors, json };
619
- }
620
- return { errors: [], json };
621
- };
622
- const localizationStoreUpdateSelectedLocale = (newSelectedLocale) => {
623
- localizationStore.selectedLocale = newSelectedLocale;
624
- translationStoreUpdateLanguage(newSelectedLocale);
625
- void updateCheckoutSessionLanguage();
626
- };
627
-
628
- const formatDate = ({ date,
629
- // eslint-disable-next-line sort-keys/sort-keys-fix
630
- formatOptions = {
631
- dateStyle: 'full',
632
- }, }) => {
633
- // format date to 'Wednesday, May 15, 2024'
634
- return new Intl.DateTimeFormat('en-US', formatOptions).format(date);
635
- };
636
-
637
- const getDaysDifference = (targetDate) => {
638
- const currentDate = new Date();
639
- const timeDifference = targetDate.getTime() - currentDate.getTime();
640
- const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); // Convert milliseconds to days
641
- return daysDifference;
642
- };
643
-
644
- const { onChange: onChange$1, reset: reset$1, state: cartStore, } = createStore(() => ({
645
- checkoutSessionId: sessionStorage.getItem('zonos--checkout-session-id') || null,
646
- currency: 'USD',
647
- doneSteps: [],
648
- dutiesTaxFees: 0,
649
- error: null,
650
- exchangeRate: null,
651
- isSelectedShippingAboveDeminimis: false,
652
- isSelectedShippingGuarantee: false,
653
- items: [],
654
- landedCostData: null,
655
- restrictedItems: [],
656
- selectedLandedCost: null,
657
- selectedShippingOption: null,
658
- selectedShippingOptionExpectedDate: '',
659
- selectedShippingOptionTransitTime: '',
660
- shipping: 0,
661
- shippingData: null,
662
- step: 'customer-info',
663
- subtotal: 0,
664
- tabItems: {
665
- 'customer-info': {
666
- index: 1,
667
- isDone: false,
668
- label: 'Customer',
669
- value: 'customer-info',
670
- },
671
- shipping: {
672
- index: 2,
673
- isDone: false,
674
- label: 'Delivery',
675
- value: 'shipping',
676
- },
677
- // eslint-disable-next-line sort-keys/sort-keys-fix
678
- payment: {
679
- index: 3,
680
- isDone: false,
681
- label: 'Payment',
682
- value: 'payment',
683
- },
684
- },
685
- total: 0,
686
- }));
687
- /**
688
- * Format shipping transit info to be displayed on UI
689
- * @returns
690
- * - expectedDate: Thursday, Aug 12
691
- * - maxTransit: 5
692
- * - minTransit: 3
693
- */
694
- const cartStoreGetShippingTransitInfo = (item) => {
695
- const minTransit = item.minTransitAt
696
- ? getDaysDifference(new Date(item.minTransitAt))
697
- : '';
698
- const maxTransit = item.maxTransitAt
699
- ? getDaysDifference(new Date(item.maxTransitAt))
700
- : '';
701
- const expectedDate = item.minTransitAt
702
- ? formatDate({
703
- date: new Date(item.minTransitAt),
704
- })
705
- : '';
706
- return {
707
- expectedDate,
708
- maxTransit,
709
- minTransit,
710
- };
711
- };
712
- const getMatchItem = ({ item1, item2, }) => {
713
- if (!item1 || !item2) {
714
- return false;
715
- }
716
- return ((item2.sku && item1.sku && item1.sku === item2.sku) ||
717
- (item2.description &&
718
- item1.description &&
719
- item1.description === item2.description) ||
720
- (item1.name && item2.name && item1.name === item2.name));
721
- };
722
- /**
723
- * Check and set restricted items in cart
724
- */
725
- const cartStoreCheckItemRestrictions = (itemsWorkflow) => {
726
- log('Checking item restrictions');
727
- const mappedRestrictedItems = itemsWorkflow
728
- .map(item => {
729
- if (!item.restriction) {
730
- return null;
731
- }
732
- const { restriction } = item;
733
- const matchedItem = cartStore.items.find(x => getMatchItem({ item1: x, item2: item }));
734
- return Object.assign(Object.assign({ matchedItem }, item), { restriction });
735
- })
736
- .filter(Boolean);
737
- cartStore.restrictedItems = mappedRestrictedItems;
738
- // remove items that are restricted from cart
739
- cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: !!mappedRestrictedItems.find(x => getMatchItem({ item1: x, item2: item })) })));
740
- return {
741
- cartItems: cartStore.items,
742
- restrictedItems: mappedRestrictedItems,
743
- };
744
- };
745
- const cartStoreReset = () => {
746
- sessionStorage.removeItem('zonos--checkout-session-id');
747
- // reset cart store
748
- reset$1();
749
- };
750
- const cartStoreUpdateToErrorState = ({ messages, title, }) => {
751
- cartStoreReset();
752
- stripeStoreReset();
753
- cartStore.step = 'error';
754
- cartStore.error = {
755
- messages,
756
- title,
757
- };
758
- };
759
- const cartStoreApplySubtotals = (subtotals) => {
760
- // update exchange rate so we can use it to display cart items
761
- cartStore.exchangeRate = subtotals.exchangeRate;
762
- cartStore.dutiesTaxFees = subtotals.landedCostTotal;
763
- cartStore.subtotal = subtotals.items;
764
- cartStore.total = subtotals.total;
765
- cartStore.currency = subtotals.presentmentCurrencyCode;
766
- };
767
- /**
768
- * Detect if there are any items in cart that are not restricted and have positive amount, exclude negative amount items
769
- */
770
- const cartStoreHasOneEligibleItem = () => {
771
- // filter all items with positive amount
772
- const checkItems = cartStore.items.filter(item => item.amount > 0);
773
- // only check restricted status for items with positive amount
774
- // if there is no item restricted found => all items are restricted
775
- return !!checkItems.find(item => !item.isRestricted);
776
- };
777
- const cartStoreReCalculateTotal = async ({ currency, itemsAmount, landedCostId, }) => {
778
- if (landedCostId && cartStore.selectedLandedCost) {
779
- // update cart total right away if we have landed cost id to avoid order total flickering
780
- const subtotals = cartStore.selectedLandedCost.subtotals;
781
- cartStoreApplySubtotals(subtotals);
782
- log('Exchange rate updated for cart items (landed cost subtotal)', 'info', cartStore.exchangeRate);
783
- }
784
- // update checkout session
785
- if (!cartStore.checkoutSessionId) {
786
- logError('Could not update cart total without checkout session id');
787
- return false;
788
- }
789
- const { errors, json } = await stripeStoreUpdateCheckoutSession({
790
- currency,
791
- id: cartStore.checkoutSessionId,
792
- itemsAmount,
793
- landedCostId,
794
- presentmentCountryCode: localizationStore.selectedCountryCode,
795
- });
796
- if (errors.length > 0 || !json) {
797
- // do nothing if we can't get checkout session
798
- logError('Error occurs when updating checkout session');
799
- cartStoreUpdateToErrorState({
800
- messages: [
801
- translate("There's been an error updating your checkout session. Please reload and try again or contact support if the error persists"),
802
- ],
803
- title: translate('Error updating Checkout'),
804
- });
805
- return false;
806
- }
807
- if (!landedCostId) {
808
- // This is when first open the checkout modal and we just want to get info from the old cart session.
809
- // use subtotals from checkout session to update cart total
810
- cartStoreApplySubtotals(json.checkoutSessionUpdate.subtotals);
811
- log('Exchange rate updated for cart items (checkout session update)', 'info', cartStore.exchangeRate);
812
- }
813
- return true;
814
- };
815
- const cartStoreUpdateSelectedShippingOption = async (selectedShippingOption) => {
816
- var _a, _b, _c, _d, _e;
817
- cartStore.selectedShippingOption = selectedShippingOption;
818
- // update shipping transit info
819
- const { expectedDate, maxTransit, minTransit } = cartStoreGetShippingTransitInfo(cartStore.selectedShippingOption);
820
- cartStore.selectedShippingOptionExpectedDate = expectedDate;
821
- cartStore.selectedShippingOptionTransitTime =
822
- minTransit && maxTransit
823
- ? `${minTransit}-${maxTransit}`
824
- : `${minTransit || maxTransit}`;
825
- const selectedLandedCost = (_a = cartStore.landedCostData) === null || _a === void 0 ? void 0 : _a.find(checkoutSessionPresentment => {
826
- var _a, _b, _c;
827
- return ((_b = (_a = checkoutSessionPresentment.landedCost) === null || _a === void 0 ? void 0 : _a.shipmentRating) === null || _b === void 0 ? void 0 : _b.id) ===
828
- ((_c = cartStore.selectedShippingOption) === null || _c === void 0 ? void 0 : _c.id);
829
- });
830
- // save selected landed cost for later use
831
- cartStore.selectedLandedCost = selectedLandedCost || null;
832
- if (!selectedLandedCost) {
833
- // do nothing if we can't find landed cost for selected shipping option
834
- return false;
835
- }
836
- // update shipping value and dutiesTaxFees on selectedShippingOption change
837
- cartStore.shipping = selectedLandedCost.subtotals.shipping;
838
- // update deminimis status
839
- const isGuarantee = ((_b = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _b === void 0 ? void 0 : _b.landedCostGuaranteeCode) === 'ZONOS';
840
- // one item in deminimis with type of duty and tax has threshold value is "ABOVE"
841
- const isAboveDeminimis = !!((_d = (_c = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _c === void 0 ? void 0 : _c.deMinimis) === null || _d === void 0 ? void 0 : _d.find(item => ['DUTY', 'TAX'].includes(item.type) && item.threshold === 'ABOVE'));
842
- cartStore.isSelectedShippingAboveDeminimis = isAboveDeminimis;
843
- cartStore.isSelectedShippingGuarantee = isGuarantee;
844
- // update session with selected landed cost
845
- const updateCalulateStatus = await cartStoreReCalculateTotal({
846
- landedCostId: (_e = selectedLandedCost.landedCost) === null || _e === void 0 ? void 0 : _e.id,
847
- });
848
- return updateCalulateStatus;
849
- };
850
- onChange$1('checkoutSessionId', () => {
851
- if (!cartStore.checkoutSessionId) {
852
- sessionStorage.removeItem('zonos--checkout-session-id');
853
- return;
854
- }
855
- sessionStorage.setItem('zonos--checkout-session-id', cartStore.checkoutSessionId);
856
- });
857
- const getCartItemToUse = (items) => items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
858
- const cartStoreResetCartItems = () => {
859
- // mark all items as not restricted
860
- cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
861
- cartStore.restrictedItems = [];
862
- };
863
- const cartStoreUpdateItems = async (cartItems) => {
864
- var _a;
865
- cartStore.items = getCartItemToUse(cartItems);
866
- const currency = (_a = cartItems.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode;
867
- const total = cartItems.reduce((amt, item) => {
868
- return amt + item.amount * item.quantity;
869
- }, 0);
870
- if (!currency || !total) {
871
- // do nothing if we can't get currency or total
872
- return;
873
- }
874
- cartStore.currency = currency;
875
- // set loading state here because this is first load checkout session when we already have checkout session id stored
876
- stripeStore.isFetchingSession = true;
877
- await cartStoreReCalculateTotal({
878
- currency: currency,
879
- itemsAmount: total,
880
- });
881
- stripeStore.isFetchingSession = false;
882
- };
883
- const cartStoreResetSelectedShippingOption = () => {
884
- cartStore.selectedShippingOption = null;
885
- cartStore.isSelectedShippingAboveDeminimis = false;
886
- cartStore.isSelectedShippingGuarantee = false;
887
- cartStore.selectedShippingOptionExpectedDate = '';
888
- cartStore.selectedShippingOptionTransitTime = '';
889
- cartStore.dutiesTaxFees = 0;
890
- cartStore.shipping = 0;
891
- // reset total to subtotal
892
- cartStore.total = cartStore.subtotal;
893
- };
894
- const cartStoreNextStep = () => {
895
- if (cartStore.step === 'customer-info') {
896
- cartStore.step = 'shipping';
897
- // set customer-info step to done
898
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems['customer-info']), { isDone: true }) });
899
- }
900
- else if (cartStore.step === 'shipping') {
901
- cartStore.step = 'payment';
902
- // set shipping step to done
903
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: true }) });
904
- }
905
- else if (cartStore.step === 'payment') {
906
- cartStore.step = 'finish';
907
- }
908
- };
909
- const cartStoreResetTabItems = () => {
910
- cartStore.step = 'customer-info';
911
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems['customer-info']), { isDone: false }), payment: Object.assign(Object.assign({}, cartStore.tabItems.payment), { isDone: false }), shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
912
- cartStoreResetSelectedShippingOption();
913
- };
914
-
915
- const prepCalculateLandedCost = () => {
916
- // maybe we don't need email now for prefetch the landed cost
917
- const stripeLinkData = stripeStore.stripeLinkEventData;
918
- const stripeAddressData = stripeStore.stripeAddressEventData;
919
- const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
920
- ? stripeStore.stripeAddressEventData
921
- : stripeStore.stripeBillingAddressEventData;
922
- if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
923
- throw new Error('Missing stripe address data');
924
- }
925
- return {
926
- billingAddress: {
927
- addressLine1: stripeBillingAddressData.value.address.line1,
928
- addressLine2: stripeBillingAddressData.value.address.line2 || '',
929
- city: stripeBillingAddressData.value.address.city,
930
- country: stripeBillingAddressData.value.address.country,
931
- postalCode: stripeBillingAddressData.value.address.postal_code,
932
- state: stripeBillingAddressData.value.address.state,
933
- },
934
- billingContact: {
935
- // firstName and lastName should be valid now since stripe only mark
936
- // the address as complete when both fields are filled.
937
- firstName: stripeBillingAddressData.value.firstName || '',
938
- lastName: stripeBillingAddressData.value.lastName || '',
939
- phone: stripeBillingAddressData.value.phone || '',
940
- },
941
- checkoutSessionId: cartStore.checkoutSessionId || '',
942
- contact: {
943
- email: (stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email) || '',
944
- // firstName and lastName should be valid now since stripe only mark
945
- // the address as complete when both fields are filled.
946
- firstName: stripeAddressData.value.firstName || '',
947
- lastName: stripeAddressData.value.lastName || '',
948
- phone: stripeAddressData.value.phone || '',
949
- },
950
- items: cartStore.items,
951
- shippingAddress: {
952
- addressLine1: stripeAddressData.value.address.line1,
953
- addressLine2: stripeAddressData.value.address.line2 || '',
954
- city: stripeAddressData.value.address.city,
955
- country: stripeAddressData.value.address.country,
956
- postalCode: stripeAddressData.value.address.postal_code,
957
- state: stripeAddressData.value.address.state,
958
- },
959
- };
960
- };
961
-
962
- const triggerBuildLandedCost = async (buildLandedCost) => {
963
- var _a, _b, _c, _d;
964
- const data = prepCalculateLandedCost();
965
- const landedCost = await buildLandedCost({
966
- billingAddress: data.billingAddress,
967
- billingContact: data.billingContact,
968
- checkoutSessionId: data.checkoutSessionId,
969
- contact: data.contact,
970
- shippingAddress: data.shippingAddress,
971
- zonosApiRoute: "https://v1.route.js.zonos.com",
972
- });
973
- if (!landedCost || ((_a = landedCost.errors) === null || _a === void 0 ? void 0 : _a.length)) {
974
- throw new Error(`Failed to build landed cost: ${((_c = (_b = landedCost === null || landedCost === void 0 ? void 0 : landedCost.errors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) || 'Unknown error'}`);
975
- }
976
- // Validate the landed cost object to make sure the returned value from buildLandedCost has a valid schema
977
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/validate-landed-cost`, {
978
- body: landedCost,
979
- headers: {
980
- 'Content-Type': 'application/json',
981
- },
982
- method: 'POST',
983
- });
984
- if (!json || errors.length) {
985
- throw new Error(`Invalid landed cost object: ${((_d = errors.find(Boolean)) === null || _d === void 0 ? void 0 : _d.message) || 'Unknown error'}`);
986
- }
987
- return landedCost;
988
- };
989
-
990
- const calculateLandedCost = async (abortController) => {
991
- var _a;
992
- // If buildLandedCost callback is supplied, use that instead of our regular request to '/calculate-landed-cost'
993
- const buildLandedCost = zonosStore.checkoutSettings.buildLandedCost;
994
- if (buildLandedCost) {
995
- const json = await triggerBuildLandedCost(buildLandedCost);
996
- return json;
997
- }
998
- // request to get landed cost info
999
- const url = `${"https://v1.route.js.zonos.com"}/api/zonos-elements/calculate-landed-cost`;
1000
- const { errors, json } = await handleFetch(url, {
1001
- body: prepCalculateLandedCost(),
1002
- method: 'POST',
1003
- signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
1004
- });
1005
- if (errors.length || !json) {
1006
- const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
1007
- const errorMessage = isAbortedRequest
1008
- ? 'The landed cost calculation request was aborted to initiate a new one.'
1009
- : 'Failed to calculate landed cost';
1010
- throw new Error(errorMessage);
1011
- }
1012
- return json;
1013
- };
1014
-
1015
- /**
1016
- * This function generates an object that contains the fields of an address that have invalid characters.
1017
- *
1018
- * @param {Object} params - The parameters for the function.
1019
- * @param {Address | null} params.address - The address to check for invalid characters.
1020
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.invalidAdddressList - The list of address fields that contain invalid characters.
1021
- *
1022
- * @returns {Partial<Address> | undefined} - An object that contains the fields of the address that have invalid characters. If no fields have invalid characters, the function returns undefined.
1023
- */
1024
- const getExcludeAddressFieldsObject = ({ address, invalidAdddressList, }) => {
1025
- if (!address) {
1026
- return;
1027
- }
1028
- // if there are no invalid characters, return an empty object
1029
- if (!invalidAdddressList) {
1030
- return;
1031
- }
1032
- const excludeFields = {};
1033
- if (invalidAdddressList.city) {
1034
- excludeFields.city = address.city;
1035
- }
1036
- if (invalidAdddressList.line1) {
1037
- excludeFields.line1 = address.line1;
1038
- }
1039
- if (invalidAdddressList.line2) {
1040
- excludeFields.line2 = address.line2;
1041
- }
1042
- if (invalidAdddressList.postal_code) {
1043
- excludeFields.postal_code = address.postal_code;
1044
- }
1045
- if (invalidAdddressList.state) {
1046
- excludeFields.state = address.state;
1047
- }
1048
- if (invalidAdddressList.name) {
1049
- excludeFields.name = address.name;
1050
- }
1051
- // return null if there are no fields to exclude
1052
- return Object.keys(excludeFields).length ? excludeFields : undefined;
1053
- };
1054
- /**
1055
- * This function builds the request body for validating an address. It checks if the address and billing address are ready and if they contain any invalid characters.
1056
- * If there are non-latin character to translate, returns an object with the address fields that have invalid characters, the destination country, and the first and last name.
1057
- * If the conditions are not met, it returns null.
1058
- *
1059
- * @param {Object} params - The parameters for the function.
1060
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
1061
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
1062
- * @param {StripeAddressEventData} params.stripeAddressEventData - The Stripe event data for the address.
1063
- * @param {StripeAddressEventData} params.stripeBillingAddressEventData - The Stripe event data for the billing address.
1064
- * @param {boolean} params.stripeShippingSameAsBilling - A flag indicating whether the shipping address is the same as the billing address.
1065
- *
1066
- * @returns {ValidateAddressRequestBody | null} - An object that contains the address fields that have invalid characters, the destination country, and the first and last name. If the conditions are not met, the function returns null.
1067
- */
1068
- const buildTranslateRequestBody = ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, stripeAddressEventData, stripeBillingAddressEventData, stripeShippingSameAsBilling, }) => {
1069
- var _a, _b, _c, _d;
1070
- const isStripeAddressReady = !!(stripeAddressEventData === null || stripeAddressEventData === void 0 ? void 0 : stripeAddressEventData.complete);
1071
- const isStripeBillingAddressReady = stripeShippingSameAsBilling
1072
- ? isStripeAddressReady
1073
- : !!(stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.complete);
1074
- // only translate if both address and billing address are ready
1075
- if (!isStripeAddressReady || !isStripeBillingAddressReady) {
1076
- return null;
1077
- }
1078
- // only translate if there are invalid characters
1079
- if (!addressInvalidCharactersList && !billingAddressInvalidCharactersList) {
1080
- return null;
1081
- }
1082
- const stripeAddressValue = stripeAddressEventData.value;
1083
- const stripeBillingAddressValue = (stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.value) || null;
1084
- // Returns undefined if the name is Latin so it won't be included in the request body
1085
- const firstName = stripeAddressValue.firstName || ((_a = stripeAddressValue.name) === null || _a === void 0 ? void 0 : _a.split(' ')[0]);
1086
- const lastName = stripeAddressValue.lastName || ((_b = stripeAddressValue.name) === null || _b === void 0 ? void 0 : _b.split(' ')[1]);
1087
- const name = `${firstName} ${lastName}`;
1088
- const billingFirstName = stripeAddressValue.firstName ||
1089
- ((_c = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _c === void 0 ? void 0 : _c.split(' ')[0]);
1090
- const billingLastName = stripeAddressValue.lastName ||
1091
- ((_d = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _d === void 0 ? void 0 : _d.split(' ')[1]);
1092
- const billingName = billingFirstName && billingLastName
1093
- ? `${billingFirstName} ${billingLastName}`
1094
- : '';
1095
- const address = stripeAddressValue.address;
1096
- const billingAddress = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.address;
1097
- return {
1098
- address: getExcludeAddressFieldsObject({
1099
- address: Object.assign(Object.assign({}, address), { name }),
1100
- invalidAdddressList: addressInvalidCharactersList,
1101
- }),
1102
- // only include billing address if it's different from the shipping address
1103
- billingAddress: !stripeShippingSameAsBilling
1104
- ? getExcludeAddressFieldsObject({
1105
- address: billingAddress
1106
- ? Object.assign(Object.assign({}, billingAddress), { name: billingName }) : null,
1107
- invalidAdddressList: billingAddressInvalidCharactersList,
1108
- })
1109
- : undefined,
1110
- destinationCountry: address.country,
1111
- };
1112
- };
1113
-
1114
- const jsonParse = (_data) => {
1115
- if (typeof _data === 'string') {
1116
- try {
1117
- // eslint-disable-next-line no-restricted-syntax
1118
- const json = JSON.parse(_data);
1119
- return json;
1120
- }
1121
- catch (_error) {
1122
- return null;
1123
- }
1124
- }
1125
- return null;
1126
- };
1127
-
1128
- const addressRuleStyle = ({ theme, }) => {
1129
- const defaultStyle = {
1130
- '.Action': {
1131
- color: 'var(--colorText)',
1132
- },
1133
- '.Input': {
1134
- boxShadow: 'none',
1135
- // need to reset everything and the paddingTop to default, otherwise the paddingTop will not be updated.
1136
- padding: '0',
1137
- paddingBottom: '8px',
1138
- paddingLeft: '16px',
1139
- paddingRight: '8px',
1140
- // any value here will be add up to the default paddingTop (20px).
1141
- paddingTop: '6px',
1142
- },
1143
- '.PickerItem--highlight': {
1144
- boxShadow: '0 0 0 2px var(--colorBackground)',
1145
- },
1146
- '.PickerItem--highlight:hover': {
1147
- backgroundColor: 'var(--colorBackground)',
1148
- boxShadow: 'none',
1149
- },
1150
- '.PickerItem--new': {
1151
- color: 'var(--colorText)',
1152
- },
1153
- };
1154
- switch (theme) {
1155
- case 'DARK': {
1156
- return Object.assign(Object.assign({}, defaultStyle), { '.Action': Object.assign(Object.assign({}, defaultStyle['.Action']), { color: 'white' }), '.PickerItem--new': Object.assign(Object.assign({}, defaultStyle['.PickerItem--new']), { color: 'white' }) });
1157
- }
1158
- default:
1159
- return defaultStyle;
1160
- }
1161
- };
1162
-
1163
- const defaultVariable = ({ borderStyle, theme, }) => {
1164
- switch (theme) {
1165
- case 'DARK':
1166
- return {
1167
- borderRadius: getBorderRadius({ overrideBorderStyle: borderStyle }),
1168
- colorBackground: '#101117',
1169
- colorBackgroundText: '#C5C6CA',
1170
- colorText: '#C5C6CA',
1171
- colorTextPlaceholder: '#C5C6CA',
1172
- };
1173
- default:
1174
- return {
1175
- borderRadius: getBorderRadius({ overrideBorderStyle: borderStyle }),
1176
- };
1177
- }
1178
- };
1179
-
1180
- const { onChange, reset, state: stripeStore, } = createStore(() => ({
1181
- clientSecret: sessionStorage.getItem('zonos--client-secret') || null,
1182
- fetchingLandedCostAbordController: null,
1183
- isFetchingLandedCost: false,
1184
- isFetchingSession: false,
1185
- stripe: null,
1186
- stripeAddressElement: null,
1187
- stripeAddressEventData: null,
1188
- stripeAddressUsedWhenFetchingLC: null,
1189
- stripeAddressUsedWhenValidatingAddress: null,
1190
- stripeBillingAddressElement: null,
1191
- stripeBillingAddressEventData: null,
1192
- stripeBillingAddressUsedWhenFetchingLC: null,
1193
- stripeBillingAddressUsedWhenValidatingAddress: null,
1194
- stripeElements: null,
1195
- stripeElementsForBillingAddress: null,
1196
- stripeElementsOptions: null,
1197
- stripeLinkElement: null,
1198
- stripeLinkEventData: null,
1199
- stripeLinkUsedWhenFetchingLC: null,
1200
- stripePaymentElement: null,
1201
- stripePaymentEventData: null,
1202
- stripeShippingSameAsBilling: true,
1203
- translatedAddress: {
1204
- address: {},
1205
- billingAddress: {},
1206
- firstName: {},
1207
- lastName: {},
1208
- name: {},
1209
- },
1210
- }));
1211
- const getStripeOptions = ({ clientSecret, overrideBorderRaidus, overridePrimaryColor, overrideSecondaryColor, overrideTheme, }) => {
1212
- const primaryColor = overridePrimaryColor || zonosStore.appearance.colorPrimary;
1213
- const secondaryColor = overrideSecondaryColor || zonosStore.appearance.colorSecondary;
1214
- const themeBasedColor = primaryColor && isDarkColor(primaryColor) ? 'night' : 'flat';
1215
- // if overrideTheme is provided, use it. Otherwise, use theme based on primary color
1216
- const theme = overrideTheme === 'DARK' ? 'night' : 'flat';
1217
- return {
1218
- appearance: {
1219
- labels: 'floating',
1220
- rules: Object.assign({}, addressRuleStyle({ theme: overrideTheme || 'LIGHT' })),
1221
- // get contrast theme color base on primary color
1222
- theme: overrideTheme ? theme : themeBasedColor,
1223
- variables: Object.assign(Object.assign({}, defaultVariable({
1224
- borderStyle: overrideBorderRaidus,
1225
- theme: 'LIGHT',
1226
- })), {
1227
- // use the button background color for input glow color
1228
- colorPrimary: secondaryColor }),
1229
- },
1230
- clientSecret,
1231
- locale: localizationStore.selectedLocale,
1232
- };
1233
- };
1234
- const stripeStoreCleanupDomesticShippingSession = () => {
1235
- window.sessionStorage.removeItem('zonos--bigcommerce-domestic-checkout-shipping');
1236
- };
1237
- // Save shipping address to session storage
1238
- const stripeStoreSaveDomesticShippingSession = (props) => {
1239
- window.sessionStorage.setItem('zonos--bigcommerce-domestic-checkout-shipping', JSON.stringify(props));
1240
- };
1241
- const stripeStoreGetDomesticShippingSession = () => {
1242
- const session = window.sessionStorage.getItem('zonos--bigcommerce-domestic-checkout-shipping');
1243
- return jsonParse(session);
1244
- };
1245
- const initStripeElements = async (props) => {
1246
- var _a, _b;
1247
- const clientSecret = stripeStore.clientSecret;
1248
- if (!stripeStore.stripe) {
1249
- log('Skip. Stripe is not initialized');
1250
- return;
1251
- }
1252
- if (clientSecret) {
1253
- const stripeOptions = getStripeOptions({
1254
- clientSecret,
1255
- overrideBorderRaidus: props === null || props === void 0 ? void 0 : props.overrideBorderRaidus,
1256
- overridePrimaryColor: props === null || props === void 0 ? void 0 : props.overridePrimaryColor,
1257
- overrideSecondaryColor: props === null || props === void 0 ? void 0 : props.overrideSecondaryColor,
1258
- overrideTheme: props === null || props === void 0 ? void 0 : props.overrideTheme,
1259
- });
1260
- // compare with the previous options to see if we need to update
1261
- const isSameOptions = JSON.stringify(stripeOptions) ===
1262
- JSON.stringify(stripeStore.stripeElementsOptions);
1263
- if (!stripeStore.stripeElements ||
1264
- !stripeStore.stripeElementsForBillingAddress) {
1265
- // init stripe elements if it doesn't exist
1266
- stripeStore.stripeElements = (_a = stripeStore.stripe) === null || _a === void 0 ? void 0 : _a.elements(stripeOptions);
1267
- // save stripe elements options for later comparison
1268
- stripeStore.stripeElementsOptions = stripeOptions;
1269
- log('Stripe elements initialized');
1270
- // init stripe elements for billing address
1271
- stripeStore.stripeElementsForBillingAddress =
1272
- (_b = stripeStore.stripe) === null || _b === void 0 ? void 0 : _b.elements(stripeOptions);
1273
- log('Stripe elements for billing address initialized');
1274
- return;
1275
- }
1276
- if (!isSameOptions) {
1277
- // update elements with new option if it already exists
1278
- stripeStore.stripeElements.update(stripeOptions);
1279
- // update elements for stripe billing address
1280
- stripeStore.stripeElementsForBillingAddress.update(stripeOptions);
1281
- // save stripe elements options for later comparison
1282
- stripeStore.stripeElementsOptions = stripeOptions;
1283
- }
1284
- log('Stripe elements initialized');
1285
- }
1286
- };
1287
- const stripeStoreReset = () => {
1288
- // clean clientSecret so that we can start the new one.
1289
- sessionStorage.removeItem('zonos--client-secret');
1290
- // cleanup stripe elements
1291
- reset();
1292
- // set stripe back to window.Zonos.stripe
1293
- stripeStore.stripe = window.Zonos.stripe;
1294
- };
1295
- const checkIsAddressOutdatedForValidation = () => {
1296
- var _a, _b, _c, _d;
1297
- const isAddressDataDirty = JSON.stringify((_a = stripeStore.stripeAddressUsedWhenValidatingAddress) === null || _a === void 0 ? void 0 : _a.value) !== JSON.stringify((_b = stripeStore.stripeAddressEventData) === null || _b === void 0 ? void 0 : _b.value);
1298
- const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
1299
- JSON.stringify((_c = stripeStore.stripeBillingAddressEventData) === null || _c === void 0 ? void 0 : _c.value) !==
1300
- JSON.stringify((_d = stripeStore.stripeBillingAddressUsedWhenValidatingAddress) === null || _d === void 0 ? void 0 : _d.value);
1301
- return isAddressDataDirty || isBillingAddressDataDirty;
1302
- };
1303
- const checkIsAddressOutdatedForLCPrefetch = () => {
1304
- var _a, _b, _c, _d, _e, _f;
1305
- const isLinkDataDirty = JSON.stringify((_a = stripeStore.stripeLinkUsedWhenFetchingLC) === null || _a === void 0 ? void 0 : _a.value) !==
1306
- JSON.stringify((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.value);
1307
- const isAddressDataDirty = JSON.stringify((_c = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _c === void 0 ? void 0 : _c.value) !==
1308
- JSON.stringify((_d = stripeStore.stripeAddressEventData) === null || _d === void 0 ? void 0 : _d.value);
1309
- const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
1310
- JSON.stringify((_e = stripeStore.stripeBillingAddressEventData) === null || _e === void 0 ? void 0 : _e.value) !==
1311
- JSON.stringify((_f = stripeStore.stripeBillingAddressUsedWhenFetchingLC) === null || _f === void 0 ? void 0 : _f.value);
1312
- return isLinkDataDirty || isAddressDataDirty || isBillingAddressDataDirty;
1313
- };
1314
- /**
1315
- * Check if the address and email info used when fetching landed cost with the current email and address info are different
1316
- * Purpose is to resend the request if the info used when fetching landed cost is different from the current info
1317
- */
1318
- const isPrefetchInfoOutdated = () => {
1319
- var _a;
1320
- // Mark the landed cost is outdated since the item total amount has changed (items total didn't match with the cart subtotal)
1321
- const isTotalAmountChanged = cartStore.landedCostData &&
1322
- ((_a = cartStore.landedCostData.find(Boolean)) === null || _a === void 0 ? void 0 : _a.subtotals.items) !==
1323
- cartStore.subtotal;
1324
- const isAddressOutdated = checkIsAddressOutdatedForLCPrefetch();
1325
- return (
1326
- // if landed cost data is not available, we need to fetch it
1327
- !cartStore.landedCostData || isAddressOutdated || isTotalAmountChanged);
1328
- };
1329
- const stripeStorePrefetchLandedCost = async () => {
1330
- var _a, _b, _c, _d, _e, _f;
1331
- const stripeAddressReady = !!((_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.complete);
1332
- const stripeLinkReady = !!((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.complete);
1333
- const stripeBillingAddressReady = stripeStore.stripeShippingSameAsBilling
1334
- ? !!((_c = stripeStore.stripeLinkEventData) === null || _c === void 0 ? void 0 : _c.complete)
1335
- : !!((_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.complete);
1336
- const shouldRefetch = isPrefetchInfoOutdated();
1337
- if (shouldRefetch) {
1338
- // if the info used when fetching landed cost is different from the current info, abort the previous request
1339
- (_e = stripeStore.fetchingLandedCostAbordController) === null || _e === void 0 ? void 0 : _e.abort();
1340
- stripeStore.fetchingLandedCostAbordController = null;
1341
- }
1342
- // only fetch if we are not fetching or we need to refetch
1343
- if (stripeAddressReady &&
1344
- stripeLinkReady &&
1345
- stripeBillingAddressReady &&
1346
- shouldRefetch) {
1347
- stripeStore.isFetchingLandedCost = true;
1348
- if (stripeStore.stripeAddressEventData) {
1349
- stripeStore.stripeAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeAddressEventData);
1350
- }
1351
- if (stripeStore.stripeBillingAddressEventData) {
1352
- stripeStore.stripeBillingAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeBillingAddressEventData);
1353
- }
1354
- if (stripeStore.stripeLinkEventData) {
1355
- stripeStore.stripeLinkUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeLinkEventData);
1356
- }
1357
- try {
1358
- const abortController = new AbortController();
1359
- stripeStore.fetchingLandedCostAbordController = abortController;
1360
- // Reset cart items to non-restricted state and restricted item list
1361
- cartStoreResetCartItems();
1362
- const { checkoutSessionWorkflow, itemCreateWorkflow, landedCostCalculateWorkflow, shipmentRatingCalculateWorkflow, } = await calculateLandedCost(abortController);
1363
- // reset abort controller after we are done
1364
- stripeStore.fetchingLandedCostAbordController = null;
1365
- // update cart store with landed cost info
1366
- cartStore.landedCostData =
1367
- (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.map(checkoutSession => {
1368
- const foundLandedCost = landedCostCalculateWorkflow === null || landedCostCalculateWorkflow === void 0 ? void 0 : landedCostCalculateWorkflow.find(item => { var _a; return (item === null || item === void 0 ? void 0 : item.id) === ((_a = checkoutSession.landedCost) === null || _a === void 0 ? void 0 : _a.id); });
1369
- if (!foundLandedCost) {
1370
- return null;
1371
- }
1372
- return Object.assign(Object.assign({}, checkoutSession), { landedCost: foundLandedCost });
1373
- }).filter(Boolean)) || [];
1374
- cartStore.shippingData =
1375
- (shipmentRatingCalculateWorkflow === null || shipmentRatingCalculateWorkflow === void 0 ? void 0 : shipmentRatingCalculateWorkflow.filter(Boolean)) || [];
1376
- // apply new subtotal and total, this is mainly to show items in the presentment currency
1377
- const firstLandedCostData = (_f = cartStore.landedCostData) === null || _f === void 0 ? void 0 : _f.find(Boolean);
1378
- const subtotals = !!firstLandedCostData
1379
- ? firstLandedCostData.subtotals
1380
- : null;
1381
- // check and update cart items with restrictions
1382
- cartStoreCheckItemRestrictions(itemCreateWorkflow);
1383
- if (subtotals) {
1384
- // prefetch landed cost will not update shipping and taxes since we haven't selected shipping method yet
1385
- cartStoreApplySubtotals({
1386
- exchangeRate: subtotals.exchangeRate,
1387
- items: subtotals.items,
1388
- landedCostTotal: 0,
1389
- presentmentCurrencyCode: subtotals.presentmentCurrencyCode,
1390
- shipping: 0,
1391
- total: subtotals.items,
1392
- });
1393
- }
1394
- }
1395
- catch (err) {
1396
- // default to empty array if we fail to fetch landed cost, so we can show the error message
1397
- cartStore.landedCostData = [];
1398
- cartStore.shippingData = [];
1399
- logError(err);
1400
- }
1401
- stripeStore.isFetchingLandedCost = false;
1402
- }
1403
- };
1404
- const getStripeMessageBasedOnStatus = (status) => {
1405
- let messages = [];
1406
- let isError = true;
1407
- // Inspect the PaymentIntent `status` to indicate the status of the payment
1408
- // to your customer.
1409
- //
1410
- // Some payment methods will [immediately succeed or fail][0] upon
1411
- // confirmation, while others will first enter a `processing` state.
1412
- //
1413
- // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
1414
- switch (status) {
1415
- case 'succeeded': {
1416
- messages = [
1417
- translate('Your payment went through successfully! Thank you for shopping with us! We hope you had an enjoyable experience and your support means the world to us.'),
1418
- '',
1419
- '',
1420
- translate("We've sent an email confirmation of the order details for your review. And our team is carefully preparing your order so it arrives on time."),
1421
- ];
1422
- isError = false;
1423
- break;
1424
- }
1425
- case 'requires_capture':
1426
- case 'processing': {
1427
- messages = [
1428
- translate("Payment processing. We'll update you when payment is received."),
1429
- ];
1430
- isError = false;
1431
- break;
1432
- }
1433
- case 'requires_payment_method': {
1434
- messages = [
1435
- translate('Payment failed. Please try another payment method.'),
1436
- ];
1437
- break;
1438
- }
1439
- default: {
1440
- messages = [translate('Something went wrong.')];
1441
- break;
1442
- }
1443
- }
1444
- return {
1445
- isError,
1446
- messages,
1447
- };
1448
- };
1449
- const stripeStoreRetrievePayment = async ({ clientSecret: _clientSecret, storybookForceStatus, }) => {
1450
- if (storybookForceStatus) {
1451
- // return status right away if we are in storybook mode
1452
- const { isError, messages } = getStripeMessageBasedOnStatus(storybookForceStatus);
1453
- return { error: isError, messages };
1454
- }
1455
- const clientSecret = _clientSecret || stripeStore.clientSecret;
1456
- if (!stripeStore.stripe || !clientSecret) {
1457
- logError('Failed to retrieve payment intent. Stripe is not initialized');
1458
- return { error: true, message: [translate('Something went wrong.')] };
1459
- }
1460
- const { paymentIntent } = await stripeStore.stripe.retrievePaymentIntent(clientSecret);
1461
- const status = paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status;
1462
- const { isError, messages } = getStripeMessageBasedOnStatus(status);
1463
- return {
1464
- error: isError,
1465
- messages,
1466
- paymentMethod: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.payment_method,
1467
- };
1468
- };
1469
- const stripeStoreConfirmPayment = async () => {
1470
- var _a, _b, _c, _d;
1471
- const stripePaymentReady = !!((_a = stripeStore.stripePaymentEventData) === null || _a === void 0 ? void 0 : _a.complete);
1472
- const stripeElements = stripeStore.stripeElements;
1473
- const stripe = stripeStore.stripe;
1474
- const stripeClientSecret = stripeStore.clientSecret;
1475
- if (!((_b = cartStore.selectedLandedCost) === null || _b === void 0 ? void 0 : _b.landedCost.id)) {
1476
- throw new Error('Attemped to confirm the payment when no landed cost is found in store');
1477
- }
1478
- if (stripe && stripeElements && stripePaymentReady && stripeClientSecret) {
1479
- const { error } = await stripe.confirmPayment({
1480
- confirmParams: {
1481
- receipt_email: (_d = (_c = stripeStore.stripeLinkEventData) === null || _c === void 0 ? void 0 : _c.value) === null || _d === void 0 ? void 0 : _d.email,
1482
- return_url: window.location.href,
1483
- },
1484
- elements: stripeElements,
1485
- redirect: 'if_required',
1486
- });
1487
- if (error) {
1488
- if (error.type === 'card_error' || error.type === 'validation_error') {
1489
- throw new Error(error.message);
1490
- }
1491
- if (error.type === 'invalid_request_error') {
1492
- if (error.code === 'payment_intent_unexpected_state') {
1493
- // PaymentIntent was canceled or expired, or status is `require_capture`.
1494
- // don't throw error here because we will reset the checkout session last step
1495
- return;
1496
- }
1497
- }
1498
- throw new Error('An unexpected error occurred.');
1499
- }
1500
- }
1501
- };
1502
- /**
1503
- * Init checkout session
1504
- * @returns {boolean} whether or not the checkout session is successfully created
1505
- */
1506
- const stripeStoreInitCheckoutSession = async () => {
1507
- var _a;
1508
- const total = cartStore.items.reduce((amount, item) => amount + item.amount * item.quantity, 0);
1509
- if (!total || !localizationStore.targetCurrency) {
1510
- logError('Fail to create checkout session - invalid total or currency');
1511
- return false;
1512
- }
1513
- stripeStore.isFetchingSession = true;
1514
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/create-checkout-session`, {
1515
- body: {
1516
- currency: ((_a = cartStore.items.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode) || '',
1517
- itemsAmount: total,
1518
- metadata: [
1519
- { key: 'language', value: localizationStore.selectedLocale },
1520
- ],
1521
- presentmentCountryCode: localizationStore.selectedCountryCode || null,
1522
- },
1523
- method: 'POST',
1524
- });
1525
- stripeStore.isFetchingSession = false;
1526
- if (errors.length || !json) {
1527
- logError('Error occurs when creating checkout session', JSON.stringify(errors, null, 2));
1528
- return false;
1529
- }
1530
- const result = json.checkoutSessionCreate;
1531
- stripeStore.clientSecret = result.clientSecret;
1532
- // update cart store with updated informations
1533
- cartStore.checkoutSessionId = result.id;
1534
- cartStoreApplySubtotals(Object.assign(Object.assign({}, result.subtotals), { landedCostTotal: 0, shipping: 0, total: result.subtotals.items }));
1535
- log('Exchange rate updated for cart items (checkout session create)', 'info', cartStore.exchangeRate);
1536
- log('done-init-checkout-session');
1537
- return true;
1538
- };
1539
- /**
1540
- * Update checkout session. Use for updating amount with landed cost id, or update session when cart items change
1541
- */
1542
- const stripeStoreUpdateCheckoutSession = async ({ currency, id, itemsAmount, landedCostId, presentmentCountryCode, }) => {
1543
- // No need to set loading state here because this function will be called under the hood to update
1544
- // landed cost id for the section.
1545
- const { errors, json } = await handleFetch(`${"https://v1.route.js.zonos.com"}/api/zonos-elements/update-checkout-session`, {
1546
- body: {
1547
- currency,
1548
- id,
1549
- itemsAmount,
1550
- landedCostId,
1551
- presentmentCountryCode,
1552
- },
1553
- method: 'POST',
1554
- });
1555
- if (errors.length || !json) {
1556
- logError('Error occurs when updating checkout session', JSON.stringify(errors, null, 2));
1557
- return { errors, json };
1558
- }
1559
- return { errors: [], json };
1560
- };
1561
- /**
1562
- * This function builds a translated address object from the current address and the translated address result.
1563
- * It checks each field in the current address and if it exists in the translated address result, it adds it to the translated address object.
1564
- * The key of each field in the translated address object is the current address's field value and the value is the corresponding translated address's field value.
1565
- *
1566
- * @param {Object} params - The parameters for the function.
1567
- * @param {Address} params.currentAddress - The current address information.
1568
- * @param {Address} params.translatedAddressResult - The translated address result.
1569
- *
1570
- * @returns {TranslatedAddress} - An object containing the translated address. Each field is an object with the current address's field value as the key and the translated address's field value as the value.
1571
- */
1572
- const buildTranslatedAddress = ({ currentAddress, translatedAddressResult, }) => {
1573
- const translatedAddress = {};
1574
- if (!translatedAddressResult) {
1575
- return translatedAddress;
1576
- }
1577
- const { city, line1, line2, name, postal_code, state } = translatedAddressResult;
1578
- // If we have translated address, add it to the translated address object
1579
- if (currentAddress.city && city) {
1580
- translatedAddress.city = {
1581
- [currentAddress.city]: city,
1582
- };
1583
- }
1584
- if (currentAddress.line1 && line1) {
1585
- translatedAddress.line1 = {
1586
- [currentAddress.line1]: line1,
1587
- };
1588
- }
1589
- if (currentAddress.line2 && line2) {
1590
- translatedAddress.line2 = {
1591
- [currentAddress.line2]: line2,
1592
- };
1593
- }
1594
- if (currentAddress.postal_code && postal_code) {
1595
- translatedAddress.postal_code = {
1596
- [currentAddress.postal_code]: postal_code,
1597
- };
1598
- }
1599
- if (currentAddress.state && state) {
1600
- translatedAddress.state = {
1601
- [currentAddress.state]: state,
1602
- };
1603
- }
1604
- if (currentAddress.name && name) {
1605
- translatedAddress.name = {
1606
- [currentAddress.name]: name,
1607
- };
1608
- }
1609
- return translatedAddress;
1610
- };
1611
- /**
1612
- * This function translates an address to Latin characters using the Zonos API.
1613
- * It first builds the request body for the API call. If there's no request body, it resets the translated address in the store and returns.
1614
- * If the address is not outdated, it returns without making the API call.
1615
- * It then makes a POST request to the Zonos API to validate and translate the address. If the API call fails, it resets the translated address in the store and returns.
1616
- * If the API call is successful, it sets the current address and billing address in the store and builds the translated address and billing address from the API response.
1617
- *
1618
- * @param {Object} params - The parameters for the function.
1619
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
1620
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
1621
- */
1622
- const stripeStoreTranslateAddressToLatin = async ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, }) => {
1623
- var _a, _b, _c, _d;
1624
- const requestBody = buildTranslateRequestBody({
1625
- addressInvalidCharactersList,
1626
- billingAddressInvalidCharactersList,
1627
- stripeAddressEventData: stripeStore.stripeAddressEventData,
1628
- stripeBillingAddressEventData: stripeStore.stripeBillingAddressEventData,
1629
- stripeShippingSameAsBilling: stripeStore.stripeShippingSameAsBilling,
1630
- });
1631
- if (!requestBody) {
1632
- // reset translated address if we don't have any address to translate
1633
- stripeStore.translatedAddress = {
1634
- address: {},
1635
- billingAddress: {},
1636
- };
1637
- return;
1638
- }
1639
- // only translate address if the address is out of date
1640
- const isAddressOutdated = checkIsAddressOutdatedForValidation();
1641
- if (!isAddressOutdated) {
1642
- return;
1643
- }
1644
- const routeUrl = "https://v1.route.js.zonos.com";
1645
- const { errors, json } = await handleFetch(`${routeUrl}/api/zonos-elements/validate-address`, {
1646
- body: requestBody,
1647
- method: 'POST',
1648
- });
1649
- if (errors.length || !json) {
1650
- logError('Error occurs when translating address to latin', JSON.stringify(errors, null, 2));
1651
- // reset translated address if we fail to translate and let user manually fix it
1652
- stripeStore.translatedAddress = {
1653
- address: {},
1654
- billingAddress: {},
1655
- };
1656
- return;
1657
- }
1658
- // Set current address to the store so we can compare it later to determine if we need to re-translate the address
1659
- stripeStore.stripeAddressUsedWhenValidatingAddress =
1660
- stripeStore.stripeAddressEventData;
1661
- stripeStore.stripeBillingAddressUsedWhenValidatingAddress =
1662
- stripeStore.stripeBillingAddressEventData;
1663
- const address = (_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.value.address;
1664
- const billingAddress = (_b = stripeStore.stripeBillingAddressEventData) === null || _b === void 0 ? void 0 : _b.value.address;
1665
- // Set the translated address to the store so we can populate it to the address element for user to update
1666
- stripeStore.translatedAddress = {
1667
- address: address
1668
- ? buildTranslatedAddress({
1669
- currentAddress: Object.assign(Object.assign({}, address), { name: (_c = stripeStore.stripeAddressEventData) === null || _c === void 0 ? void 0 : _c.value.name }),
1670
- translatedAddressResult: json.address || null,
1671
- })
1672
- : {},
1673
- billingAddress: !stripeStore.stripeShippingSameAsBilling
1674
- ? buildTranslatedAddress({
1675
- currentAddress: Object.assign(Object.assign({}, billingAddress), { name: (_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.value.name }) || {},
1676
- translatedAddressResult: json.billingAddress || null,
1677
- })
1678
- : {},
1679
- };
1680
- };
1681
- onChange('clientSecret', clientSecret => {
1682
- // update stripe elements when client secret changes
1683
- if (clientSecret && stripeStore.stripe) {
1684
- sessionStorage.setItem('zonos--client-secret', clientSecret);
1685
- }
1686
- if (!clientSecret) {
1687
- sessionStorage.removeItem('zonos--client-secret');
1688
- }
1689
- });
1690
-
1691
- export { cartStoreGetShippingTransitInfo as A, isValidSelector as B, initLocalizationStore as C, getZCountryUrlParam as D, setZCountryUrlParam as E, currencyDisplay as F, currencyConvertAndFormat as G, currencyConvert as H, currencyFormat as I, localizationStore as a, cartStoreHasOneEligibleItem as b, cartStore as c, log as d, stripeStoreGetDomesticShippingSession as e, localizationStoreUpdateSelectedCountryCode as f, stripeStoreCleanupDomesticShippingSession as g, stripeStoreSaveDomesticShippingSession as h, initStripeElements as i, cartStoreUpdateItems as j, cartStoreReset as k, logError as l, cartStoreResetTabItems as m, stripeStoreInitCheckoutSession as n, cartStoreUpdateToErrorState as o, stripeStorePrefetchLandedCost as p, cartStoreNextStep as q, stripeStoreConfirmPayment as r, stripeStore as s, stripeStoreReset as t, localizationStoreOnUpdate as u, handleFetch as v, stripeStoreRetrievePayment as w, stripeStoreTranslateAddressToLatin as x, localizationStoreUpdateSelectedLocale as y, cartStoreUpdateSelectedShippingOption as z };