@zonos/elements 1.3.200 → 1.3.202

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 (308) hide show
  1. package/dist/cjs/VarianceTest-0cb1e118.js +12 -0
  2. package/dist/cjs/cart-637ba3d0.js +1943 -0
  3. package/dist/cjs/{debounce-d393fafe.js → debounce-94e1b7ff.js} +1 -1
  4. package/dist/cjs/{getBorderRadius-3d0a563e.js → getBorderRadius-8d3b1049.js} +1 -1
  5. package/dist/cjs/index.cjs.js +10 -8
  6. package/dist/cjs/{isDarkColor-92a10a85.js → isDarkColor-bcf49625.js} +1 -1
  7. package/dist/cjs/loader.cjs.js +1 -1
  8. package/dist/cjs/{cart-add8fe50.js → localization-2f17c95f.js} +74 -1926
  9. package/dist/cjs/{paypal-afc19dec.js → paypal-0eceff03.js} +10 -9
  10. package/dist/cjs/zonos-address_11.cjs.entry.js +98 -72
  11. package/dist/cjs/zonos-badge.cjs.entry.js +2 -1
  12. package/dist/cjs/zonos-banner.cjs.entry.js +2 -1
  13. package/dist/cjs/zonos-button_3.cjs.entry.js +4 -3
  14. package/dist/cjs/zonos-card.cjs.entry.js +3 -2
  15. package/dist/cjs/{zonos-cart-items_13.cjs.entry.js → zonos-cart-items_14.cjs.entry.js} +99 -80
  16. package/dist/cjs/zonos-checkout.cjs.entry.js +395 -50
  17. package/dist/cjs/zonos-collapse.cjs.entry.js +2 -1
  18. package/dist/cjs/zonos-component.cjs.entry.js +1 -1
  19. package/dist/cjs/zonos-controller.cjs.entry.js +13 -11
  20. package/dist/cjs/zonos-country-flag.cjs.entry.js +4 -5
  21. package/dist/cjs/zonos-country-select_4.cjs.entry.js +13 -13
  22. package/dist/cjs/zonos-elements.cjs.js +1 -1
  23. package/dist/cjs/zonos-empty-state-payment_4.cjs.entry.js +10 -8
  24. package/dist/cjs/zonos-hello-dialog.cjs.entry.js +41 -42
  25. package/dist/cjs/zonos-hello.cjs.entry.js +30 -31
  26. package/dist/cjs/zonos-input.cjs.entry.js +3 -2
  27. package/dist/cjs/zonos-language-select_2.cjs.entry.js +8 -9
  28. package/dist/cjs/zonos-logo.cjs.entry.js +4 -3
  29. package/dist/cjs/zonos-shipping-rich-radio.cjs.entry.js +3 -2
  30. package/dist/cjs/zonos-stripe-input.cjs.entry.js +8 -7
  31. package/dist/cjs/zonos-text.cjs.entry.js +2 -1
  32. package/dist/cjs/zonos-toggle.cjs.entry.js +4 -3
  33. package/dist/cjs/zonos-tooltip.cjs.entry.js +2 -2
  34. package/dist/cjs/zonos-v-stack.cjs.entry.js +4 -3
  35. package/dist/cjs/{zonosStore-c466b127.js → zonosStore-9264749e.js} +15 -5
  36. package/dist/collection/collection-manifest.json +1 -0
  37. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout-finish/zonos-checkout-finish.js +18 -17
  38. package/dist/collection/components/checkout/zonos-checkout/zonos-checkout.js +235 -15
  39. package/dist/collection/components/checkout/zonos-checkout/zonos-customer-info/zonos-customer-info.js +3 -3
  40. package/dist/collection/components/checkout/zonos-checkout/zonos-shipping/zonos-shipping.js +2 -1
  41. package/dist/collection/components/common/zonos-loading-overlay/zonos-loading-overlay.css +62 -0
  42. package/dist/collection/components/common/zonos-loading-overlay/zonos-loading-overlay.js +90 -0
  43. package/dist/collection/components/common/zonos-logo/zonos-logo.js +2 -2
  44. package/dist/collection/components/common/zonos-rest-state/zonos-rest-state.js +3 -3
  45. package/dist/collection/components/common/zonos-select-dialog-header/zonos-select-dialog-header.js +2 -2
  46. package/dist/collection/components/common/zonos-stripe-input/zonos-stripe-input.js +4 -4
  47. package/dist/collection/components/common/zonos-stripe-phone-input/zonos-stripe-phone-input.js +5 -5
  48. package/dist/collection/components/common/zonos-stripe-select/zonos-stripe-select.js +5 -5
  49. package/dist/collection/components/common/zonos-toggle/zonos-toggle.js +2 -2
  50. package/dist/collection/components/common/zonos-tooltip/zonos-tooltip.js +2 -2
  51. package/dist/collection/components/common/zonos-v-stack/zonos-v-stack.js +2 -2
  52. package/dist/collection/components/common/zonos-virtual-scroll/zonos-virtual-scroll.js +2 -2
  53. package/dist/collection/components/component-template/zonos-component/zonos-component.js +1 -1
  54. package/dist/collection/components/hello/zonos-hello-dialog/zonos-hello-dialog-footer/zonos-hello-dialog-footer.js +2 -2
  55. package/dist/collection/components/hello/zonos-hello-dialog/zonos-hello-dialog.js +4 -4
  56. package/dist/collection/components/main/zonos-controller.js +3 -3
  57. package/dist/collection/components/paypal/zonos-paypal-payment.js +1 -1
  58. package/dist/collection/components/store/checkout/cart.js +15 -16
  59. package/dist/collection/components/store/checkout/paypal.js +2 -1
  60. package/dist/collection/components/store/checkout/stripe.js +33 -13
  61. package/dist/collection/components/store/hello/localization.js +5 -5
  62. package/dist/collection/components/store/storageStore.js +32 -0
  63. package/dist/collection/components/store/zonosStore.js +12 -6
  64. package/dist/collection/components/stripe/zonos-address/zonos-address.js +18 -6
  65. package/dist/collection/components/stripe/zonos-custom-address/zonos-address-suggestions/zonos-address-suggestions.js +2 -2
  66. package/dist/collection/components/stripe/zonos-custom-address/zonos-custom-address.js +19 -7
  67. package/dist/collection/components/stripe/zonos-payment/zonos-payment.js +3 -3
  68. package/dist/collection/components/utils/api/getCheckoutSession.js +3 -3
  69. package/dist/collection/components/utils/api/placeTestOrder.js +2 -1
  70. package/dist/collection/components/utils/api/prepCalculateLandedCost.js +3 -2
  71. package/dist/collection/components/utils/api/selectVarianceTest.js +20 -0
  72. package/dist/collection/components/utils/buildCartUrl.js +44 -0
  73. package/dist/collection/components/utils/getLegacyQueryParams.js +42 -0
  74. package/dist/collection/components/utils/varianceTest/filterExpiredTests.js +6 -0
  75. package/dist/collection/components/utils/varianceTest/filterValidTests.js +23 -0
  76. package/dist/collection/components/utils/varianceTest/getSelectedTestVariant.js +6 -0
  77. package/dist/collection/components/utils/varianceTest/hasAtLeastOneAvailableTestKey.js +14 -0
  78. package/dist/collection/components/utils/varianceTest/isInAvailableTestKey.js +4 -0
  79. package/dist/collection/components/utils/varianceTest/isTestEnabled.js +4 -0
  80. package/dist/collection/components/utils/varianceTest/isTestKeysAllVariantSelected.js +6 -0
  81. package/dist/collection/components/utils/varianceTest/mergeTest.js +13 -0
  82. package/dist/collection/scripts/_getZonosQaUrl.js +2 -2
  83. package/dist/collection/types/checkout/api/VarianceTest.js +8 -0
  84. package/dist/collection/types/generated/graphql.internal.types.js +12 -0
  85. package/dist/collection/types/index.js +1 -0
  86. package/dist/esm/VarianceTest-fef2d958.js +10 -0
  87. package/dist/esm/cart-b7c15b61.js +1907 -0
  88. package/dist/esm/{debounce-a2121722.js → debounce-3a9f27a0.js} +1 -1
  89. package/dist/esm/{getBorderRadius-413e97eb.js → getBorderRadius-78b28b4d.js} +1 -1
  90. package/dist/esm/index.js +9 -8
  91. package/dist/esm/{isDarkColor-4c7b2ffc.js → isDarkColor-31dd7dff.js} +1 -1
  92. package/dist/esm/loader.js +1 -1
  93. package/dist/esm/{cart-e03d615e.js → localization-bf7224aa.js} +70 -1892
  94. package/dist/esm/{paypal-23dd5023.js → paypal-932fd3dd.js} +5 -4
  95. package/dist/esm/zonos-address_11.entry.js +54 -28
  96. package/dist/esm/zonos-badge.entry.js +2 -1
  97. package/dist/esm/zonos-banner.entry.js +2 -1
  98. package/dist/esm/zonos-button_3.entry.js +4 -3
  99. package/dist/esm/zonos-card.entry.js +3 -2
  100. package/dist/esm/{zonos-cart-items_13.entry.js → zonos-cart-items_14.entry.js} +48 -30
  101. package/dist/esm/zonos-checkout.entry.js +363 -18
  102. package/dist/esm/zonos-collapse.entry.js +2 -1
  103. package/dist/esm/zonos-component.entry.js +1 -1
  104. package/dist/esm/zonos-controller.entry.js +8 -6
  105. package/dist/esm/zonos-country-flag.entry.js +3 -4
  106. package/dist/esm/zonos-country-select_4.entry.js +8 -8
  107. package/dist/esm/zonos-elements.js +1 -1
  108. package/dist/esm/zonos-empty-state-payment_4.entry.js +10 -8
  109. package/dist/esm/zonos-hello-dialog.entry.js +7 -8
  110. package/dist/esm/zonos-hello.entry.js +4 -5
  111. package/dist/esm/zonos-input.entry.js +3 -2
  112. package/dist/esm/zonos-language-select_2.entry.js +5 -6
  113. package/dist/esm/zonos-logo.entry.js +4 -3
  114. package/dist/esm/zonos-shipping-rich-radio.entry.js +3 -2
  115. package/dist/esm/zonos-stripe-input.entry.js +8 -7
  116. package/dist/esm/zonos-text.entry.js +2 -1
  117. package/dist/esm/zonos-toggle.entry.js +4 -3
  118. package/dist/esm/zonos-tooltip.entry.js +2 -2
  119. package/dist/esm/zonos-v-stack.entry.js +4 -3
  120. package/dist/esm/{zonosStore-cdabc848.js → zonosStore-d10a829f.js} +15 -5
  121. package/dist/esm-es5/VarianceTest-fef2d958.js +1 -0
  122. package/dist/esm-es5/cart-b7c15b61.js +1 -0
  123. package/dist/esm-es5/{debounce-a2121722.js → debounce-3a9f27a0.js} +1 -1
  124. package/dist/esm-es5/{getBorderRadius-413e97eb.js → getBorderRadius-78b28b4d.js} +1 -1
  125. package/dist/esm-es5/index.js +1 -1
  126. package/dist/esm-es5/{isDarkColor-4c7b2ffc.js → isDarkColor-31dd7dff.js} +1 -1
  127. package/dist/esm-es5/loader.js +1 -1
  128. package/dist/esm-es5/localization-bf7224aa.js +1 -0
  129. package/dist/esm-es5/{paypal-23dd5023.js → paypal-932fd3dd.js} +2 -2
  130. package/dist/esm-es5/zonos-address_11.entry.js +1 -1
  131. package/dist/esm-es5/zonos-badge.entry.js +1 -1
  132. package/dist/esm-es5/zonos-banner.entry.js +1 -1
  133. package/dist/esm-es5/zonos-button_3.entry.js +1 -1
  134. package/dist/esm-es5/zonos-card.entry.js +1 -1
  135. package/dist/esm-es5/zonos-cart-items_14.entry.js +1 -0
  136. package/dist/esm-es5/zonos-checkout.entry.js +1 -1
  137. package/dist/esm-es5/zonos-collapse.entry.js +1 -1
  138. package/dist/esm-es5/zonos-component.entry.js +1 -1
  139. package/dist/esm-es5/zonos-controller.entry.js +1 -1
  140. package/dist/esm-es5/zonos-country-flag.entry.js +1 -1
  141. package/dist/esm-es5/zonos-country-select_4.entry.js +1 -1
  142. package/dist/esm-es5/zonos-elements.js +1 -1
  143. package/dist/esm-es5/zonos-empty-state-payment_4.entry.js +1 -1
  144. package/dist/esm-es5/zonos-hello-dialog.entry.js +1 -1
  145. package/dist/esm-es5/zonos-hello.entry.js +1 -1
  146. package/dist/esm-es5/zonos-input.entry.js +1 -1
  147. package/dist/esm-es5/zonos-language-select_2.entry.js +1 -1
  148. package/dist/esm-es5/zonos-logo.entry.js +1 -1
  149. package/dist/esm-es5/zonos-shipping-rich-radio.entry.js +1 -1
  150. package/dist/esm-es5/zonos-stripe-input.entry.js +1 -1
  151. package/dist/esm-es5/zonos-text.entry.js +1 -1
  152. package/dist/esm-es5/zonos-toggle.entry.js +1 -1
  153. package/dist/esm-es5/zonos-tooltip.entry.js +1 -1
  154. package/dist/esm-es5/zonos-v-stack.entry.js +1 -1
  155. package/dist/esm-es5/zonosStore-d10a829f.js +1 -0
  156. package/dist/scripts/index.d.ts +839 -765
  157. package/dist/scripts/index.js +1 -1
  158. package/dist/scripts/loadZonos.js +1 -1
  159. package/dist/scripts/zonos.js +1 -1
  160. package/dist/types/components/checkout/zonos-checkout/zonos-checkout.d.ts +16 -0
  161. package/dist/types/components/common/zonos-loading-overlay/zonos-loading-overlay.d.ts +16 -0
  162. package/dist/types/components/store/checkout/cart.d.ts +0 -1
  163. package/dist/types/components/store/checkout/stripe.d.ts +2 -2
  164. package/dist/types/components/store/hello/localization.d.ts +2 -2
  165. package/dist/types/components/store/storageStore.d.ts +13 -0
  166. package/dist/types/components/store/zonosStore.d.ts +7 -2
  167. package/dist/types/components/stripe/zonos-address/zonos-address.d.ts +2 -0
  168. package/dist/types/components/stripe/zonos-custom-address/zonos-custom-address.d.ts +2 -0
  169. package/dist/types/components/utils/api/selectVarianceTest.d.ts +6 -0
  170. package/dist/types/components/utils/buildCartUrl.d.ts +10 -0
  171. package/dist/types/components/utils/getLegacyQueryParams.d.ts +2 -0
  172. package/dist/types/components/utils/varianceTest/filterExpiredTests.d.ts +2 -0
  173. package/dist/types/components/utils/varianceTest/filterValidTests.d.ts +9 -0
  174. package/dist/types/components/utils/varianceTest/getSelectedTestVariant.d.ts +2 -0
  175. package/dist/types/components/utils/varianceTest/hasAtLeastOneAvailableTestKey.d.ts +8 -0
  176. package/dist/types/components/utils/varianceTest/isInAvailableTestKey.d.ts +2 -0
  177. package/dist/types/components/utils/varianceTest/isTestEnabled.d.ts +2 -0
  178. package/dist/types/components/utils/varianceTest/isTestKeysAllVariantSelected.d.ts +9 -0
  179. package/dist/types/components/utils/varianceTest/mergeTest.d.ts +5 -0
  180. package/dist/types/components.d.ts +51 -0
  181. package/dist/types/scripts/cart/_setupCartDataWithSettings.d.ts +7 -0
  182. package/dist/types/types/checkout/CheckoutConfig.d.ts +13 -1
  183. package/dist/types/types/checkout/api/CheckoutSession.d.ts +7 -0
  184. package/dist/types/types/checkout/api/VarianceTest.d.ts +30 -0
  185. package/dist/types/types/generated/graphql.internal.types.d.ts +163 -0
  186. package/dist/types/types/generated/graphql.internal.types.ts +199 -0
  187. package/dist/types/types/index.d.ts +1 -0
  188. package/dist/types/types/utils/ZonosSettings.d.ts +7 -6
  189. package/dist/zonos-elements/index.esm.js +1 -1
  190. package/dist/zonos-elements/{p-609c32a3.system.entry.js → p-01987cb2.system.entry.js} +1 -1
  191. package/dist/zonos-elements/p-04a01cb1.js +1 -0
  192. package/dist/zonos-elements/p-04b43dd5.entry.js +1 -0
  193. package/dist/zonos-elements/p-0f77d087.system.entry.js +1 -0
  194. package/dist/zonos-elements/{p-329efa8c.system.entry.js → p-1dcdb65f.system.entry.js} +1 -1
  195. package/dist/zonos-elements/p-26a634a5.system.entry.js +1 -0
  196. package/dist/zonos-elements/p-27987298.system.entry.js +1 -0
  197. package/dist/zonos-elements/p-2af2eb6f.system.entry.js +1 -0
  198. package/dist/zonos-elements/p-2b8f787a.entry.js +1 -0
  199. package/dist/zonos-elements/p-30cfa524.entry.js +1 -0
  200. package/dist/zonos-elements/p-32320d9a.system.js +1 -0
  201. package/dist/zonos-elements/p-3284f459.system.entry.js +1 -0
  202. package/dist/zonos-elements/{p-13796f98.js → p-3d82a352.js} +1 -1
  203. package/dist/zonos-elements/p-452070af.system.entry.js +1 -0
  204. package/dist/zonos-elements/p-45ebc788.entry.js +1 -0
  205. package/dist/zonos-elements/p-4c81112f.entry.js +1 -0
  206. package/dist/zonos-elements/p-4efa8187.js +1 -0
  207. package/dist/zonos-elements/p-5170bc41.entry.js +1 -0
  208. package/dist/zonos-elements/p-5a2dd041.system.js +1 -0
  209. package/dist/zonos-elements/p-5c74e5c9.system.entry.js +1 -0
  210. package/dist/zonos-elements/p-5d0f7364.system.js +1 -0
  211. package/dist/zonos-elements/p-6a52a2bc.system.entry.js +1 -0
  212. package/dist/zonos-elements/p-715d0f59.system.entry.js +1 -0
  213. package/dist/zonos-elements/{p-b8d87932.js → p-72f37935.js} +1 -1
  214. package/dist/zonos-elements/p-7ae5cd60.entry.js +1 -0
  215. package/dist/zonos-elements/p-80bbd9c0.system.entry.js +1 -0
  216. package/dist/zonos-elements/p-851c642e.system.entry.js +1 -0
  217. package/dist/zonos-elements/{p-623a30aa.entry.js → p-8d870d4c.entry.js} +1 -1
  218. package/dist/zonos-elements/p-98b65387.entry.js +1 -0
  219. package/dist/zonos-elements/p-9af5e93a.entry.js +1 -0
  220. package/dist/zonos-elements/p-aa1193bc.entry.js +1 -0
  221. package/dist/zonos-elements/{p-8fc08673.js → p-aae60057.js} +2 -2
  222. package/dist/zonos-elements/p-ab176281.system.entry.js +1 -0
  223. package/dist/zonos-elements/p-b52aba52.entry.js +1 -0
  224. package/dist/zonos-elements/p-bc220d35.system.js +1 -0
  225. package/dist/zonos-elements/p-bc8bda92.entry.js +1 -0
  226. package/dist/zonos-elements/p-be5afc91.system.entry.js +1 -0
  227. package/dist/zonos-elements/p-bec2a3ce.entry.js +1 -0
  228. package/dist/zonos-elements/p-c291bac1.entry.js +1 -0
  229. package/dist/zonos-elements/p-c3d2422e.entry.js +1 -0
  230. package/dist/zonos-elements/{p-f28eb1dd.system.js → p-c50b3100.system.js} +1 -1
  231. package/dist/zonos-elements/p-c58acd4c.system.entry.js +1 -0
  232. package/dist/zonos-elements/p-c5fcbc92.system.entry.js +1 -0
  233. package/dist/zonos-elements/p-c767242b.entry.js +1 -0
  234. package/dist/zonos-elements/p-c9aa902e.system.entry.js +1 -0
  235. package/dist/zonos-elements/p-cb823c4d.system.js +1 -0
  236. package/dist/zonos-elements/{p-24554580.system.js → p-d2466fbd.system.js} +2 -2
  237. package/dist/zonos-elements/{p-d422ad1d.system.js → p-d42dfd32.system.js} +1 -1
  238. package/dist/zonos-elements/p-d46349d3.system.entry.js +1 -0
  239. package/dist/zonos-elements/p-d60ca44b.system.entry.js +1 -0
  240. package/dist/zonos-elements/{p-b2241919.entry.js → p-d6a10007.entry.js} +1 -1
  241. package/dist/zonos-elements/p-db025dfc.system.entry.js +1 -0
  242. package/dist/zonos-elements/p-db3968a2.js +1 -0
  243. package/dist/zonos-elements/p-dcd6acd4.system.entry.js +1 -0
  244. package/dist/zonos-elements/p-dd1cfa74.entry.js +1 -0
  245. package/dist/zonos-elements/p-df4c46a6.entry.js +1 -0
  246. package/dist/zonos-elements/{p-4593324c.js → p-e26c9e83.js} +1 -1
  247. package/dist/zonos-elements/p-e68d5219.entry.js +1 -0
  248. package/dist/zonos-elements/p-ea6d87a1.system.js +1 -1
  249. package/dist/zonos-elements/p-ef3e05e5.system.js +1 -0
  250. package/dist/zonos-elements/p-f255e822.js +1 -0
  251. package/dist/zonos-elements/p-f655ec36.entry.js +1 -0
  252. package/dist/zonos-elements/{p-e91b244c.entry.js → p-f891d470.entry.js} +1 -1
  253. package/dist/zonos-elements/p-f8d0d488.system.entry.js +1 -0
  254. package/dist/zonos-elements/{p-240ee490.system.entry.js → p-fbe36bc8.system.entry.js} +1 -1
  255. package/dist/zonos-elements/p-fcc2e712.entry.js +1 -0
  256. package/dist/zonos-elements/zonos-elements.esm.js +1 -1
  257. package/package.json +1 -1
  258. package/dist/esm-es5/cart-e03d615e.js +0 -1
  259. package/dist/esm-es5/zonos-cart-items_13.entry.js +0 -1
  260. package/dist/esm-es5/zonosStore-cdabc848.js +0 -1
  261. package/dist/zonos-elements/p-06ed3582.system.js +0 -1
  262. package/dist/zonos-elements/p-0a2101d4.system.js +0 -1
  263. package/dist/zonos-elements/p-0aa20875.system.entry.js +0 -1
  264. package/dist/zonos-elements/p-0bfd23da.entry.js +0 -1
  265. package/dist/zonos-elements/p-0f3568a7.entry.js +0 -1
  266. package/dist/zonos-elements/p-147ca395.entry.js +0 -1
  267. package/dist/zonos-elements/p-190398dd.entry.js +0 -1
  268. package/dist/zonos-elements/p-1eddec23.entry.js +0 -1
  269. package/dist/zonos-elements/p-1f2c3f5c.system.entry.js +0 -1
  270. package/dist/zonos-elements/p-24a2e899.system.entry.js +0 -1
  271. package/dist/zonos-elements/p-2882b9f4.entry.js +0 -1
  272. package/dist/zonos-elements/p-28ba5a6b.system.entry.js +0 -1
  273. package/dist/zonos-elements/p-33488109.system.entry.js +0 -1
  274. package/dist/zonos-elements/p-337fab4e.js +0 -1
  275. package/dist/zonos-elements/p-35573f66.entry.js +0 -1
  276. package/dist/zonos-elements/p-394d468f.system.js +0 -1
  277. package/dist/zonos-elements/p-3ddecaa4.system.entry.js +0 -1
  278. package/dist/zonos-elements/p-48f70043.system.entry.js +0 -1
  279. package/dist/zonos-elements/p-55711b80.system.entry.js +0 -1
  280. package/dist/zonos-elements/p-578bf5d7.entry.js +0 -1
  281. package/dist/zonos-elements/p-5b8e5d1a.entry.js +0 -1
  282. package/dist/zonos-elements/p-5c061a35.entry.js +0 -1
  283. package/dist/zonos-elements/p-6096c1c5.entry.js +0 -1
  284. package/dist/zonos-elements/p-6adc6e27.entry.js +0 -1
  285. package/dist/zonos-elements/p-7bb9c330.entry.js +0 -1
  286. package/dist/zonos-elements/p-7c6b8d3f.entry.js +0 -1
  287. package/dist/zonos-elements/p-85270076.system.entry.js +0 -1
  288. package/dist/zonos-elements/p-8a9d4605.system.entry.js +0 -1
  289. package/dist/zonos-elements/p-94e3e50d.system.entry.js +0 -1
  290. package/dist/zonos-elements/p-9f272e8e.system.entry.js +0 -1
  291. package/dist/zonos-elements/p-9f6dd86a.entry.js +0 -1
  292. package/dist/zonos-elements/p-a64ab131.system.entry.js +0 -1
  293. package/dist/zonos-elements/p-aac95779.system.entry.js +0 -1
  294. package/dist/zonos-elements/p-ad3c5358.entry.js +0 -1
  295. package/dist/zonos-elements/p-ad8a0584.entry.js +0 -1
  296. package/dist/zonos-elements/p-aeaba33e.system.entry.js +0 -1
  297. package/dist/zonos-elements/p-af6af82e.system.js +0 -1
  298. package/dist/zonos-elements/p-b2e76636.system.entry.js +0 -1
  299. package/dist/zonos-elements/p-b6afcf3f.system.entry.js +0 -1
  300. package/dist/zonos-elements/p-b8d91f99.entry.js +0 -1
  301. package/dist/zonos-elements/p-be8fa9a5.system.entry.js +0 -1
  302. package/dist/zonos-elements/p-c770044a.system.entry.js +0 -1
  303. package/dist/zonos-elements/p-d4842d10.system.entry.js +0 -1
  304. package/dist/zonos-elements/p-e390725f.js +0 -1
  305. package/dist/zonos-elements/p-eb85f0b6.system.entry.js +0 -1
  306. package/dist/zonos-elements/p-ef3d0394.entry.js +0 -1
  307. package/dist/zonos-elements/p-f6e587bb.entry.js +0 -1
  308. package/dist/zonos-elements/p-ff23980c.entry.js +0 -1
@@ -1,9 +1,71 @@
1
1
  'use strict';
2
2
 
3
- const zonosStore = require('./zonosStore-c466b127.js');
3
+ const zonosStore = require('./zonosStore-9264749e.js');
4
4
  const handleFetch = require('./handleFetch-969d05d8.js');
5
- const isDarkColor = require('./isDarkColor-92a10a85.js');
6
- const getBorderRadius = require('./getBorderRadius-3d0a563e.js');
5
+ const VarianceTest = require('./VarianceTest-0cb1e118.js');
6
+
7
+ /**
8
+ * Check if the response contains at least one available test key that we support
9
+ */
10
+ const hasAtLeastOneAvailableTestKey = (rawResponse) => {
11
+ const hasAvailableTestKey = !!rawResponse.find(item => item.testKey in VarianceTest.availableTestKeys);
12
+ if (!hasAvailableTestKey) {
13
+ handleFetch.log('No available test key found in response', 'info', {
14
+ response: rawResponse,
15
+ });
16
+ }
17
+ return !!rawResponse.find(item => item.testKey in VarianceTest.availableTestKeys);
18
+ };
19
+
20
+ /**
21
+ * Filter the response to only include test keys and variants key that we support
22
+ */
23
+ const filterValidTests = (testKeys) => {
24
+ // Type guard the response to ensure it matches the expected structure
25
+ if (!hasAtLeastOneAvailableTestKey(testKeys)) {
26
+ return [];
27
+ }
28
+ // Filter the response to only include test keys that we support
29
+ return testKeys
30
+ .filter(item => {
31
+ var _a;
32
+ const isTestKeyValidButNoSelectedVariantKey = VarianceTest.availableTestKeys[item.testKey] && !item.selectedVariantKey;
33
+ const validTestKeyWithSelectedVariantKey = item.selectedVariantKey &&
34
+ !!((_a = VarianceTest.availableTestKeys[item.testKey]) === null || _a === void 0 ? void 0 : _a['availableVariants'].includes(item.selectedVariantKey));
35
+ return (isTestKeyValidButNoSelectedVariantKey ||
36
+ validTestKeyWithSelectedVariantKey);
37
+ })
38
+ .map(item => (Object.assign(Object.assign({}, item), { expiresAt: item.expiresAt || Date.now() + VARIANT_TEST_KEY_EXPIRATION, selectedVariantKey: item.selectedVariantKey || null })));
39
+ };
40
+
41
+ /**
42
+ * Expiration time for variant test keys in milliseconds
43
+ * @default 1 day
44
+ */
45
+ const VARIANT_TEST_KEY_EXPIRATION = 60 * 60 * 24 * 1000;
46
+ const { onChange: storageStoreOnChange, state: storageStore } = zonosStore.createStore({
47
+ checkoutSessionId: sessionStorage.getItem('zonos--checkout-session-id'),
48
+ enabledVariantTestKeys: handleFetch.jsonParse(localStorage.getItem('zonos--enabled-variant-test-keys')),
49
+ });
50
+ storageStoreOnChange('enabledVariantTestKeys', () => {
51
+ var _a;
52
+ // This should be set in localStorage so we don't have multiple tests for the same user in short period of time
53
+ if (!((_a = storageStore.enabledVariantTestKeys) === null || _a === void 0 ? void 0 : _a.length)) {
54
+ localStorage.removeItem('zonos--enabled-variant-test-keys');
55
+ return;
56
+ }
57
+ localStorage.setItem('zonos--enabled-variant-test-keys', JSON.stringify(storageStore.enabledVariantTestKeys));
58
+ });
59
+ storageStoreOnChange('checkoutSessionId', () => {
60
+ if (!storageStore.checkoutSessionId) {
61
+ sessionStorage.removeItem('zonos--checkout-session-id');
62
+ return;
63
+ }
64
+ sessionStorage.setItem('zonos--checkout-session-id', storageStore.checkoutSessionId);
65
+ });
66
+ const storageStoreSetEnabledVariantTestKeys = (testKeys) => {
67
+ storageStore.enabledVariantTestKeys = filterValidTests(testKeys);
68
+ };
7
69
 
8
70
  const stringsArabic = {
9
71
  ' (Duties due at door)': {
@@ -13520,7 +13582,7 @@ const setZCountryUrlParam = (selectedCountryCode) => {
13520
13582
  }
13521
13583
  };
13522
13584
 
13523
- const { dispose: localizationDispose, onChange: localizationStoreOnUpdate, state: localizationStore, } = zonosStore.createStore({
13585
+ const { dispose: localizationDispose, onChange: localizationStoreOnChange, state: localizationStore, } = zonosStore.createStore({
13524
13586
  countryLandedCost: null,
13525
13587
  customMessages: [],
13526
13588
  exchangeRate: null,
@@ -13701,12 +13763,12 @@ const initHelloCountryList = (allCountries) => {
13701
13763
  }, {});
13702
13764
  };
13703
13765
  const updateCheckoutSessionLanguage = async () => {
13704
- if (!cartStore.checkoutSessionId) {
13766
+ if (!storageStore.checkoutSessionId) {
13705
13767
  return null;
13706
13768
  }
13707
13769
  const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/update-checkout-session-metadata', {
13708
13770
  body: {
13709
- id: cartStore.checkoutSessionId,
13771
+ id: storageStore.checkoutSessionId,
13710
13772
  metadata: [
13711
13773
  {
13712
13774
  key: 'language',
@@ -13763,1936 +13825,22 @@ const initLocalizationStore = async () => {
13763
13825
  localizationStore.localizationLoaded = true;
13764
13826
  };
13765
13827
 
13766
- /**
13767
- * Extract value from translated object
13768
- */
13769
- const getTranslatedAddress = ({ currentAddress, translatedAddress, }) => {
13770
- var _a, _b, _c, _d, _e, _f;
13771
- const { city, country, line1, line2, postal_code, state } = currentAddress.value.address;
13772
- const name = currentAddress.value.name ||
13773
- [currentAddress.value.firstName, currentAddress.value.lastName].join(' ');
13774
- return {
13775
- city: ((_a = translatedAddress.city) === null || _a === void 0 ? void 0 : _a[city]) || city,
13776
- country: country,
13777
- line1: ((_b = translatedAddress.line1) === null || _b === void 0 ? void 0 : _b[line1]) || line1,
13778
- line2: ((_c = translatedAddress.line2) === null || _c === void 0 ? void 0 : _c[line2 || '']) || line2 || '',
13779
- name: ((_d = translatedAddress.name) === null || _d === void 0 ? void 0 : _d[name]) || name,
13780
- phone: currentAddress.value.phone || '',
13781
- postal_code: ((_e = translatedAddress.postal_code) === null || _e === void 0 ? void 0 : _e[postal_code]) || postal_code,
13782
- state: ((_f = translatedAddress.state) === null || _f === void 0 ? void 0 : _f[state]) || state,
13783
- };
13784
- };
13785
- /**
13786
- * Similar to prepCalculateLandedCost except it only uses cart ID
13787
- */
13788
- const prepCartCalculateLandedCost = (cartId) => {
13789
- var _a;
13790
- const isE2ETest = new URLSearchParams(window.location.search).get('zonosE2ETest') === '1';
13791
- // maybe we don't need email now for prefetch the landed cost
13792
- const stripeLinkData = stripeStore.stripeLinkEventData;
13793
- const stripeAddressData = stripeStore.stripeAddressEventData;
13794
- const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
13795
- ? stripeStore.stripeAddressEventData
13796
- : stripeStore.stripeBillingAddressEventData;
13797
- if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
13798
- throw new Error('Missing stripe address data');
13799
- }
13800
- // Attempt to get translated address if available
13801
- const translatedShippingAddress = getTranslatedAddress({
13802
- currentAddress: stripeAddressData,
13803
- translatedAddress: stripeStore.translatedAddress.address,
13804
- });
13805
- const shippingFirstName = translatedShippingAddress.name.split(' ')[0] || '';
13806
- const shippingLastName = translatedShippingAddress.name.split(' ').splice(1).join(' ') || '';
13807
- const translatedBillingAddress = getTranslatedAddress({
13808
- currentAddress: stripeBillingAddressData,
13809
- translatedAddress: stripeStore.translatedAddress.address,
13810
- });
13811
- const billingFirstName = translatedBillingAddress.name.split(' ')[0] || '';
13812
- const billingLastName = translatedBillingAddress.name.split(' ').splice(1).join(' ') || '';
13813
- return {
13814
- billingAddress: {
13815
- addressLine1: translatedBillingAddress.line1,
13816
- addressLine2: translatedBillingAddress.line2 || '',
13817
- city: translatedBillingAddress.city,
13818
- country: translatedBillingAddress.country,
13819
- postalCode: translatedBillingAddress.postal_code,
13820
- state: translatedBillingAddress.state,
13821
- },
13822
- billingContact: {
13823
- // firstName and lastName should be valid now since stripe only mark
13824
- // the address as complete when both fields are filled.
13825
- firstName: billingFirstName,
13826
- lastName: billingLastName,
13827
- phone: translatedBillingAddress.phone,
13828
- },
13829
- // Use the first item's currency code
13830
- cartCurrencyCode: (_a = cartStore.items[0]) === null || _a === void 0 ? void 0 : _a.currencyCode,
13831
- cartId,
13832
- checkoutSessionId: cartStore.checkoutSessionId || '',
13833
- contact: {
13834
- companyName: stripeStore.companyName,
13835
- email: stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email,
13836
- // firstName and lastName should be valid now since stripe only mark
13837
- // the address as complete when both fields are filled.
13838
- firstName: shippingFirstName,
13839
- lastName: shippingLastName,
13840
- phone: translatedShippingAddress.phone,
13841
- },
13842
- isTest: !!isE2ETest,
13843
- landedCostAdjustments: cartStore.promoCode
13844
- ? [
13845
- {
13846
- amount: 0,
13847
- productId: null,
13848
- promoCode: cartStore.promoCode,
13849
- sku: null,
13850
- type: 'PROMO_CODE',
13851
- },
13852
- ]
13853
- : [],
13854
- shipToTaxId: stripeStore.taxId,
13855
- shippingAddress: {
13856
- addressLine1: translatedShippingAddress.line1,
13857
- addressLine2: translatedShippingAddress.line2,
13858
- city: translatedShippingAddress.city,
13859
- country: translatedShippingAddress.country,
13860
- postalCode: translatedShippingAddress.postal_code,
13861
- state: translatedShippingAddress.state,
13862
- },
13863
- };
13864
- };
13865
- const prepCalculateLandedCost = () => {
13866
- const isE2ETest = new URLSearchParams(window.location.search).get('zonosE2ETest') === '1';
13867
- // maybe we don't need email now for prefetch the landed cost
13868
- const stripeLinkData = stripeStore.stripeLinkEventData;
13869
- const stripeAddressData = stripeStore.stripeAddressEventData;
13870
- const stripeBillingAddressData = stripeStore.stripeShippingSameAsBilling
13871
- ? stripeStore.stripeAddressEventData
13872
- : stripeStore.stripeBillingAddressEventData;
13873
- handleFetch.log({ stripeAddressData, stripeBillingAddressData }, 'info');
13874
- if (!(stripeAddressData === null || stripeAddressData === void 0 ? void 0 : stripeAddressData.complete) || !(stripeBillingAddressData === null || stripeBillingAddressData === void 0 ? void 0 : stripeBillingAddressData.complete)) {
13875
- throw new Error('Missing stripe address data');
13876
- }
13877
- // Attempt to get translated address if available
13878
- const translatedShippingAddress = getTranslatedAddress({
13879
- currentAddress: stripeAddressData,
13880
- translatedAddress: stripeStore.translatedAddress.address,
13881
- });
13882
- const shippingFirstName = translatedShippingAddress.name.split(' ')[0] || '';
13883
- const shippingLastName = translatedShippingAddress.name.split(' ').splice(1).join(' ') || '';
13884
- const translatedBillingAddress = getTranslatedAddress({
13885
- currentAddress: stripeBillingAddressData,
13886
- translatedAddress: stripeStore.translatedAddress.address,
13887
- });
13888
- const billingFirstName = translatedBillingAddress.name.split(' ')[0] || '';
13889
- const billingLastName = translatedBillingAddress.name.split(' ').splice(1).join(' ') || '';
13890
- const convertedCartAdjuments = cartStore.adjustments.map(adjustment => ({
13891
- amount: adjustment.amount,
13892
- name: adjustment.description || null,
13893
- productId: adjustment.productId,
13894
- sku: adjustment.sku,
13895
- type: adjustment.type,
13896
- }));
13897
- const adjustments = cartStore.promoCode
13898
- ? [
13899
- {
13900
- amount: 0,
13901
- productId: null,
13902
- promoCode: cartStore.promoCode,
13903
- sku: null,
13904
- type: 'PROMO_CODE',
13905
- },
13906
- ...convertedCartAdjuments,
13907
- ]
13908
- : convertedCartAdjuments;
13909
- return {
13910
- billingAddress: {
13911
- addressLine1: translatedBillingAddress.line1,
13912
- addressLine2: translatedBillingAddress.line2 || '',
13913
- city: translatedBillingAddress.city,
13914
- country: translatedBillingAddress.country,
13915
- postalCode: translatedBillingAddress.postal_code,
13916
- state: translatedBillingAddress.state,
13917
- },
13918
- billingContact: {
13919
- // firstName and lastName should be valid now since stripe only mark
13920
- // the address as complete when both fields are filled.
13921
- firstName: billingFirstName,
13922
- lastName: billingLastName,
13923
- phone: translatedBillingAddress.phone,
13924
- },
13925
- checkoutSessionId: cartStore.checkoutSessionId || '',
13926
- contact: {
13927
- companyName: stripeStore.companyName,
13928
- email: stripeLinkData === null || stripeLinkData === void 0 ? void 0 : stripeLinkData.value.email,
13929
- // firstName and lastName should be valid now since stripe only mark
13930
- // the address as complete when both fields are filled.
13931
- firstName: shippingFirstName,
13932
- lastName: shippingLastName,
13933
- phone: translatedShippingAddress.phone,
13934
- },
13935
- isTest: isE2ETest,
13936
- items: cartStore.items,
13937
- landedCostAdjustments: adjustments,
13938
- shipToTaxId: stripeStore.taxId,
13939
- shippingAddress: {
13940
- addressLine1: translatedShippingAddress.line1,
13941
- addressLine2: translatedShippingAddress.line2,
13942
- city: translatedShippingAddress.city,
13943
- country: translatedShippingAddress.country,
13944
- postalCode: translatedShippingAddress.postal_code,
13945
- state: translatedShippingAddress.state,
13946
- },
13947
- };
13948
- };
13949
-
13950
- const triggerBuildLandedCost = async (buildLandedCost) => {
13951
- var _a, _b, _c, _d, _e;
13952
- const data = prepCalculateLandedCost();
13953
- const landedCost = await buildLandedCost({
13954
- billingAddress: data.billingAddress,
13955
- billingContact: data.billingContact,
13956
- checkoutSessionId: data.checkoutSessionId,
13957
- contact: data.contact,
13958
- landedCostAdjustments: data.landedCostAdjustments,
13959
- // zonosApiKey should always be available
13960
- publicCredential: window.Zonos.zonosApiKey || '',
13961
- shippingAddress: data.shippingAddress,
13962
- zonosApiRoute: handleFetch.fallbackApiList['vercel'],
13963
- });
13964
- if (!landedCost ||
13965
- // Only show errors if there are no rate back (checkoutSessionWorkflow) and there are errors
13966
- (!((_a = landedCost.checkoutSessionWorkflow) === null || _a === void 0 ? void 0 : _a.length) && ((_b = landedCost.errors) === null || _b === void 0 ? void 0 : _b.length))) {
13967
- throw new Error(`Failed to build landed cost: ${((_d = (_c = landedCost === null || landedCost === void 0 ? void 0 : landedCost.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.message) || 'Unknown error'}`);
13968
- }
13969
- // Validate the landed cost object to make sure the returned value from buildLandedCost has a valid schema
13970
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/validate-landed-cost', {
13971
- body: landedCost,
13972
- headers: {
13973
- 'Content-Type': 'application/json',
13974
- },
13975
- method: 'POST',
13976
- });
13977
- if (!json || errors.length) {
13978
- throw new Error(`Invalid landed cost object: ${((_e = errors.find(Boolean)) === null || _e === void 0 ? void 0 : _e.message) || 'Unknown error'}`);
13979
- }
13980
- return landedCost;
13981
- };
13982
-
13983
- const calculateLandedCost = async (abortController) => {
13984
- var _a;
13985
- // If buildLandedCost callback is supplied, use that instead of our regular request to '/calculate-landed-cost'
13986
- const buildLandedCost = zonosStore.zonosStore.checkoutSettings.buildLandedCost;
13987
- if (buildLandedCost) {
13988
- const json = await triggerBuildLandedCost(buildLandedCost);
13989
- return json;
13990
- }
13991
- // request to get landed cost info
13992
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/calculate-landed-cost', {
13993
- body: prepCalculateLandedCost(),
13994
- method: 'POST',
13995
- signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
13996
- });
13997
- if (errors.length || !json) {
13998
- const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
13999
- if (isAbortedRequest) {
14000
- throw new Error('The landed cost calculation request was aborted to initiate a new one.');
14001
- }
14002
- // We want to show any successful quotes even if there are errors
14003
- errors.forEach(error => {
14004
- // eslint-disable-next-line no-console
14005
- console.warn(`Error calculating landed cost: ${error.message}`);
14006
- });
14007
- if (!json) {
14008
- throw new Error('Failed to calculate landed cost');
14009
- }
14010
- return json;
14011
- }
14012
- return json;
14013
- };
14014
-
14015
- const cartCalculateLandedCost = async ({ abortController, cartId, }) => {
14016
- var _a;
14017
- // request to get landed cost info
14018
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/cart-calculate-landed-cost', {
14019
- body: prepCartCalculateLandedCost(cartId),
14020
- method: 'POST',
14021
- signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal,
14022
- });
14023
- if (errors.length || !json) {
14024
- const isAbortedRequest = ((_a = errors[0]) === null || _a === void 0 ? void 0 : _a.message) === 'The user aborted a request.';
14025
- const errorMessage = isAbortedRequest
14026
- ? 'The landed cost calculation request was aborted to initiate a new one.'
14027
- : 'Failed to calculate landed cost';
14028
- throw new Error(errorMessage);
14029
- }
14030
- return json;
14031
- };
14032
-
14033
- var __rest = (undefined && undefined.__rest) || function (s, e) {
14034
- var t = {};
14035
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14036
- t[p] = s[p];
14037
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
14038
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
14039
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
14040
- t[p[i]] = s[p[i]];
14041
- }
14042
- return t;
14043
- };
14044
- const calculateLandedCostNormalized = async (abortController) => {
14045
- const cartId = window.Zonos.cartId;
14046
- // Calculate landed cost as usual if no cartId is available
14047
- if (!cartId) {
14048
- const landedCostResult = await calculateLandedCost(abortController);
14049
- return landedCostResult;
14050
- }
14051
- // Calculate landed cost using cartId
14052
- const _a = await cartCalculateLandedCost({
14053
- abortController,
14054
- cartId,
14055
- }), { cartWorkflow } = _a, rest = __rest(_a, ["cartWorkflow"]);
14056
- return Object.assign(Object.assign({}, rest), { itemCreateWorkflow: cartWorkflow.items });
14057
- };
14058
-
14059
- const trackConversionEvent = async ({ checkoutSessionId, eventName, metadata, }) => {
14060
- var _a, _b;
14061
- const eventCreated = Date.now();
14062
- const trackLogMetadata = [...window.Zonos.trackEventLogs];
14063
- window.Zonos.trackEventLogs.push({
14064
- checkoutSessionId,
14065
- eventCreated,
14066
- eventName,
14067
- });
14068
- const isDevelopment =
14069
- // if the url includes zonos.com and not hosted checkout (checkout.zonos.com), it means we are on the development site (dashboard, preview zonos domain or main zonos.com)
14070
- (window.location.href.includes('zonos.com') &&
14071
- !window.location.href.includes('checkout.zonos.com')) ||
14072
- !!((_a = window.Zonos) === null || _a === void 0 ? void 0 : _a.zonosQaUrl) ||
14073
- !!((_b = window.Zonos) === null || _b === void 0 ? void 0 : _b.debug);
14074
- const isTest = handleFetch.getIsTestMode() || handleFetch.getIsStagingMode();
14075
- if ((isTest || isDevelopment) &&
14076
- // if found, it means we want to test the conversion event in development site, or test mode and staging mode
14077
- !window.Zonos.zonosConversionTest) {
14078
- return;
14079
- }
14080
- const countryCode = localizationStore.selectedCountryCode;
14081
- const organizationId = zonosStore.zonosStore.organizationId;
14082
- if (!checkoutSessionId) {
14083
- void handleFetch.sendErrorLog({
14084
- endpoint: 'trackConversionEventMetric',
14085
- errors: [`Event "${eventName}" - No checkout session id found`],
14086
- metadata: {
14087
- allLogs: handleFetch.allLogs,
14088
- checkoutSessionId,
14089
- eventName,
14090
- metadata,
14091
- organizationId,
14092
- trackEventLogs: trackLogMetadata,
14093
- },
14094
- });
14095
- // checkoutSessionId is required for tracking conversion events to work properly
14096
- return;
14097
- }
14098
- if (!organizationId) {
14099
- void handleFetch.sendErrorLog({
14100
- endpoint: 'trackConversionEventMetric',
14101
- errors: [`Event "${eventName}" - No organization id found`],
14102
- metadata: {
14103
- allLogs: handleFetch.allLogs,
14104
- checkoutSessionId,
14105
- eventName,
14106
- metadata,
14107
- organizationId,
14108
- trackEventLogs: trackLogMetadata,
14109
- },
14110
- });
14111
- }
14112
- const body = {
14113
- checkoutSessionId,
14114
- countryCode,
14115
- eventCreated,
14116
- eventName,
14117
- metadata: Object.assign(Object.assign({}, metadata), { trackEventLogs: trackLogMetadata }),
14118
- organizationId,
14119
- };
14120
- await handleFetch.handleFetch('/api/zonos-elements/track-conversion-event', {
14121
- body,
14122
- method: 'POST',
14123
- });
14124
- };
14125
-
14126
- /**
14127
- * This function generates an object that contains the fields of an address that have invalid characters.
14128
- *
14129
- * @param {Object} params - The parameters for the function.
14130
- * @param {Address | null} params.address - The address to check for invalid characters.
14131
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.invalidAdddressList - The list of address fields that contain invalid characters.
14132
- *
14133
- * @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.
14134
- */
14135
- const getExcludeAddressFieldsObject = ({ address, invalidAdddressList, }) => {
14136
- if (!address) {
14137
- return;
14138
- }
14139
- // if there are no invalid characters, return an empty object
14140
- if (!invalidAdddressList) {
14141
- return;
14142
- }
14143
- const excludeFields = {};
14144
- if (invalidAdddressList.city) {
14145
- excludeFields.city = address.city;
14146
- }
14147
- if (invalidAdddressList.line1) {
14148
- excludeFields.line1 = address.line1;
14149
- }
14150
- if (invalidAdddressList.line2) {
14151
- excludeFields.line2 = address.line2;
14152
- }
14153
- if (invalidAdddressList.postal_code) {
14154
- excludeFields.postal_code = address.postal_code;
14155
- }
14156
- if (invalidAdddressList.state) {
14157
- excludeFields.state = address.state;
14158
- }
14159
- if (invalidAdddressList.name) {
14160
- excludeFields.name = address.name;
14161
- }
14162
- // return null if there are no fields to exclude
14163
- return Object.keys(excludeFields).length ? excludeFields : undefined;
14164
- };
14165
- /**
14166
- * 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.
14167
- * 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.
14168
- * If the conditions are not met, it returns null.
14169
- *
14170
- * @param {Object} params - The parameters for the function.
14171
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
14172
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
14173
- * @param {StripeAddressEventData} params.stripeAddressEventData - The Stripe event data for the address.
14174
- * @param {StripeAddressEventData} params.stripeBillingAddressEventData - The Stripe event data for the billing address.
14175
- * @param {boolean} params.stripeShippingSameAsBilling - A flag indicating whether the shipping address is the same as the billing address.
14176
- *
14177
- * @returns {ValidateAddressRequest | 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.
14178
- */
14179
- const buildTranslateRequest = ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, stripeAddressEventData, stripeBillingAddressEventData, stripeShippingSameAsBilling, }) => {
14180
- var _a, _b, _c, _d;
14181
- const isStripeAddressReady = !!(stripeAddressEventData === null || stripeAddressEventData === void 0 ? void 0 : stripeAddressEventData.complete);
14182
- const isStripeBillingAddressReady = stripeShippingSameAsBilling
14183
- ? isStripeAddressReady
14184
- : !!(stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.complete);
14185
- // only translate if both address and billing address are ready
14186
- if (!isStripeAddressReady || !isStripeBillingAddressReady) {
14187
- return null;
14188
- }
14189
- // only translate if there are invalid characters
14190
- if (!addressInvalidCharactersList && !billingAddressInvalidCharactersList) {
14191
- return null;
14192
- }
14193
- const stripeAddressValue = stripeAddressEventData.value;
14194
- const stripeBillingAddressValue = (stripeBillingAddressEventData === null || stripeBillingAddressEventData === void 0 ? void 0 : stripeBillingAddressEventData.value) || null;
14195
- // Returns undefined if the name is Latin so it won't be included in the request body
14196
- const firstName = stripeAddressValue.firstName || ((_a = stripeAddressValue.name) === null || _a === void 0 ? void 0 : _a.split(' ')[0]);
14197
- const lastName = stripeAddressValue.lastName || ((_b = stripeAddressValue.name) === null || _b === void 0 ? void 0 : _b.split(' ')[1]);
14198
- const name = `${firstName} ${lastName}`;
14199
- const billingFirstName = stripeAddressValue.firstName ||
14200
- ((_c = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _c === void 0 ? void 0 : _c.split(' ')[0]);
14201
- const billingLastName = stripeAddressValue.lastName ||
14202
- ((_d = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.name) === null || _d === void 0 ? void 0 : _d.split(' ')[1]);
14203
- const billingName = billingFirstName && billingLastName
14204
- ? `${billingFirstName} ${billingLastName}`
14205
- : '';
14206
- const address = stripeAddressValue.address;
14207
- const billingAddress = stripeBillingAddressValue === null || stripeBillingAddressValue === void 0 ? void 0 : stripeBillingAddressValue.address;
14208
- return {
14209
- address: getExcludeAddressFieldsObject({
14210
- address: Object.assign(Object.assign({}, address), { name }),
14211
- invalidAdddressList: addressInvalidCharactersList,
14212
- }),
14213
- // only include billing address if it's different from the shipping address
14214
- billingAddress: !stripeShippingSameAsBilling
14215
- ? getExcludeAddressFieldsObject({
14216
- address: billingAddress
14217
- ? Object.assign(Object.assign({}, billingAddress), { name: billingName }) : null,
14218
- invalidAdddressList: billingAddressInvalidCharactersList,
14219
- })
14220
- : undefined,
14221
- destinationCountry: address.country,
14222
- };
14223
- };
14224
-
14225
- /**
14226
- * Sorts service levels with lower cost first
14227
- */
14228
- const sortServiceLevelOptionsByAmount = (serviceLevels) => {
14229
- const sortedServiceLevels = serviceLevels.sort((a, b) => {
14230
- return a.amount - b.amount;
14231
- });
14232
- return sortedServiceLevels;
14233
- };
14234
-
14235
- const getCheckoutSession = async () => {
14236
- if (!cartStore.checkoutSessionId) {
14237
- return {
14238
- errors: [{ message: 'No checkout session id found' }],
14239
- json: null,
14240
- };
14241
- }
14242
- const searchParams = new URLSearchParams();
14243
- searchParams.set('checkoutSessionId', cartStore.checkoutSessionId);
14244
- const { errors, json } = await handleFetch.handleFetch(`/api/zonos-elements/get-checkout-session?${searchParams.toString()}`);
14245
- return { errors, json };
14246
- };
14247
-
14248
- /**
14249
- * Validate checkout session before confirming payment
14250
- */
14251
- const validateCheckoutSession = async () => {
14252
- var _a;
14253
- // get checkout session info
14254
- const { errors, json } = await getCheckoutSession();
14255
- if (errors.length || !json) {
14256
- handleFetch.logError('Failed to retrieve checkout session info before confirming payment ', errors);
14257
- void handleFetch.sendErrorLog({
14258
- endpoint: 'validateCheckoutSession',
14259
- errors: errors.map(error => error.message),
14260
- metadata: { allLogs: handleFetch.allLogs },
14261
- });
14262
- return {
14263
- errorMessage: translate('Unable to retrieve the checkout session at the moment. Please try again or contact our support team.'),
14264
- valid: false,
14265
- };
14266
- }
14267
- // Make sure landed cost is found in the checkout session
14268
- if (!((_a = json.checkoutSession.landedCost) === null || _a === void 0 ? void 0 : _a.id)) {
14269
- handleFetch.logError('Landed cost is not found in the checkout session before confirming payment.');
14270
- void handleFetch.sendErrorLog({
14271
- endpoint: 'validateCheckoutSession',
14272
- errors: ['No landed cost found before confirming payment'],
14273
- metadata: { allLogs: handleFetch.allLogs },
14274
- });
14275
- return {
14276
- errorMessage: translate('No shipment rating selected. Please go back to the "Shipping" step and select a shipment rating to proceed.'),
14277
- valid: false,
14278
- };
14279
- }
14280
- return { errorMessage: '', valid: true };
14281
- };
14282
-
14283
- const addressRuleStyle = ({ theme, }) => {
14284
- const defaultStyle = {
14285
- '.AccordionItem': {
14286
- color: 'var(--colorText)',
14287
- },
14288
- '.AccordionItem--selected': {
14289
- color: 'var(--colorText)',
14290
- },
14291
- '.Action': {
14292
- color: 'var(--colorText)',
14293
- },
14294
- '.Input': {
14295
- boxShadow: 'none',
14296
- fontSize: zonosStore.zonosStore.appearance.fontSizeInputValue
14297
- ? `${zonosStore.zonosStore.appearance.fontSizeInputValue}px`
14298
- : undefined,
14299
- // need to reset everything and the paddingTop to default, otherwise the paddingTop will not be updated.
14300
- padding: '0',
14301
- paddingBottom: '8px',
14302
- paddingLeft: '16px',
14303
- paddingRight: '8px',
14304
- // any value here will be add up to the default paddingTop (20px).
14305
- paddingTop: '6px',
14306
- },
14307
- '.Label--resting': {
14308
- fontSize: zonosStore.zonosStore.appearance.fontSizeInputLabel
14309
- ? `${zonosStore.zonosStore.appearance.fontSizeInputLabel}px`
14310
- : undefined,
14311
- },
14312
- '.PickerItem--highlight': {
14313
- boxShadow: '0 0 0 2px var(--colorBackground)',
14314
- },
14315
- '.PickerItem--highlight:hover': {
14316
- backgroundColor: 'var(--colorBackground)',
14317
- boxShadow: 'none',
14318
- },
14319
- '.PickerItem--new': {
14320
- color: 'var(--colorText)',
14321
- },
14322
- '.Tab--selected': {
14323
- borderStyle: 'solid',
14324
- borderWidth: '1px',
14325
- },
14326
- };
14327
- switch (theme) {
14328
- case 'DARK': {
14329
- 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' }) });
14330
- }
14331
- default:
14332
- return defaultStyle;
14333
- }
14334
- };
14335
-
14336
- const defaultVariable = ({ borderStyle, theme, }) => {
14337
- switch (theme) {
14338
- case 'DARK':
14339
- return {
14340
- borderRadius: getBorderRadius.getBorderRadius({ overrideBorderStyle: borderStyle }),
14341
- colorBackground: '#101117',
14342
- colorBackgroundText: '#C5C6CA',
14343
- colorText: '#C5C6CA',
14344
- colorTextPlaceholder: '#C5C6CA',
14345
- };
14346
- default:
14347
- return {
14348
- borderRadius: getBorderRadius.getBorderRadius({ overrideBorderStyle: borderStyle }),
14349
- iconMenuColor: 'var(--colorText)',
14350
- iconMenuHoverColor: 'var(--colorText)',
14351
- };
14352
- }
14353
- };
14354
-
14355
- const { onChange: onChange$1, reset: reset$1, state: stripeStore, } = zonosStore.createStore(() => ({
14356
- checkoutSettlementCurrency: 'USD',
14357
- clientSecret: sessionStorage.getItem('zonos--client-secret') || '',
14358
- companyName: '',
14359
- customAddressErrors: {
14360
- city: '',
14361
- firstName: '',
14362
- lastName: '',
14363
- line1: '',
14364
- phone: '',
14365
- postalCode: '',
14366
- showError: false,
14367
- state: '',
14368
- },
14369
- customBillingAddressErrors: {
14370
- city: '',
14371
- firstName: '',
14372
- lastName: '',
14373
- line1: '',
14374
- phone: '',
14375
- postalCode: '',
14376
- showError: false,
14377
- state: '',
14378
- },
14379
- customErrorMessage: null,
14380
- customerProfile: null,
14381
- fetchingLandedCostAbortController: null,
14382
- hasPaymentError: false,
14383
- isFetchingLandedCost: false,
14384
- isFetchingSession: false,
14385
- shouldInventoryRefund: false,
14386
- shouldRenderPayInUsdButton: false,
14387
- /**
14388
- * Default to skip payment intent, only create payment intent when "skipPaymentIntent" in url's query params is set "0"
14389
- * @default true
14390
- */
14391
- skipPaymentIntent: new URLSearchParams(window.location.search).get('skipPaymentIntent') === '0'
14392
- ? false
14393
- : true,
14394
- stripe: null,
14395
- stripeAddressElement: null,
14396
- stripeAddressEventData: null,
14397
- stripeAddressUsedWhenFetchingLC: null,
14398
- stripeAddressUsedWhenValidatingAddress: null,
14399
- stripeBillingAddressElement: null,
14400
- stripeBillingAddressEventData: null,
14401
- stripeBillingAddressUsedWhenFetchingLC: null,
14402
- stripeBillingAddressUsedWhenValidatingAddress: null,
14403
- stripeCustomerSessionClientSecret: null,
14404
- stripeElements: null,
14405
- stripeElementsForBillingAddress: null,
14406
- stripeElementsOptions: null,
14407
- stripeLinkElement: null,
14408
- stripeLinkEventData: null,
14409
- stripeLinkUsedWhenFetchingLC: null,
14410
- stripePaymentElement: null,
14411
- stripePaymentEventData: null,
14412
- stripeShippingSameAsBilling: true,
14413
- taxId: '',
14414
- taxIdUsedWhenFetchingLC: '',
14415
- translatedAddress: {
14416
- address: {},
14417
- billingAddress: {},
14418
- firstName: {},
14419
- lastName: {},
14420
- name: {},
14421
- },
14422
- }));
14423
- const getStripeOptions = ({ clientSecret, overrideBorderRadius, overridePrimaryColor, overrideSecondaryColor, overrideTheme, paypalEnabled, }) => {
14424
- const primaryColor = overridePrimaryColor || zonosStore.zonosStore.appearance.colorPrimary;
14425
- const secondaryColor = overrideSecondaryColor || zonosStore.zonosStore.appearance.colorSecondary;
14426
- const themeBasedColor = primaryColor && isDarkColor.isDarkColor(primaryColor) ? 'night' : 'flat';
14427
- // if overrideTheme is provided, use it. Otherwise, use theme based on primary color
14428
- const theme = overrideTheme === 'DARK' ? 'night' : 'flat';
14429
- const paypalPaymentType = paypalEnabled ? ['external_paypal'] : [];
14430
- return {
14431
- appearance: {
14432
- labels: 'floating',
14433
- rules: Object.assign({}, addressRuleStyle({ theme: overrideTheme || 'LIGHT' })),
14434
- // get contrast theme color base on primary color
14435
- theme: overrideTheme ? theme : themeBasedColor,
14436
- variables: Object.assign(Object.assign({}, defaultVariable({
14437
- borderStyle: overrideBorderRadius,
14438
- theme: 'LIGHT',
14439
- })), {
14440
- // use the button background color for input glow color
14441
- colorPrimary: secondaryColor }),
14442
- },
14443
- // Client secret can be undefined since we will load other elements that doesn't require client secret first, then load client secret and render one that requires it later
14444
- clientSecret: clientSecret || undefined,
14445
- customerSessionClientSecret: stripeStore.stripeCustomerSessionClientSecret || undefined,
14446
- externalPaymentMethodTypes: [...paypalPaymentType],
14447
- locale: localizationStore.selectedLocale,
14448
- };
14449
- };
14450
- const stripeStoreCleanupDomesticShippingSession = () => {
14451
- window.sessionStorage.removeItem('zonos--bigcommerce-domestic-checkout-shipping');
14452
- };
14453
- // Save shipping address to session storage
14454
- const stripeStoreSaveDomesticShippingSession = (props) => {
14455
- window.sessionStorage.setItem('zonos--bigcommerce-domestic-checkout-shipping', JSON.stringify(props));
14456
- };
14457
- const stripeStoreGetDomesticShippingSession = () => {
14458
- const session = window.sessionStorage.getItem('zonos--bigcommerce-domestic-checkout-shipping');
14459
- return handleFetch.jsonParse(session);
14460
- };
14461
- const initStripeElements = async (props) => {
14462
- var _a, _b;
14463
- const clientSecret = stripeStore.clientSecret;
14464
- if (!stripeStore.stripe) {
14465
- handleFetch.log('Skip. Stripe is not initialized');
14466
- return;
14467
- }
14468
- const stripeOptions = getStripeOptions({
14469
- clientSecret,
14470
- overrideBorderRadius: props === null || props === void 0 ? void 0 : props.overrideBorderRadius,
14471
- overridePrimaryColor: props === null || props === void 0 ? void 0 : props.overridePrimaryColor,
14472
- overrideSecondaryColor: props === null || props === void 0 ? void 0 : props.overrideSecondaryColor,
14473
- overrideTheme: props === null || props === void 0 ? void 0 : props.overrideTheme,
14474
- paypalEnabled: props === null || props === void 0 ? void 0 : props.paypalEnabled,
14475
- });
14476
- // compare with the previous options to see if we need to update
14477
- const isSameOptions = JSON.stringify(stripeOptions) ===
14478
- JSON.stringify(stripeStore.stripeElementsOptions);
14479
- if (!stripeStore.stripeElements ||
14480
- !stripeStore.stripeElementsForBillingAddress) {
14481
- // init stripe elements if it doesn't exist
14482
- stripeStore.stripeElements = (_a = stripeStore.stripe) === null || _a === void 0 ? void 0 : _a.elements(stripeOptions);
14483
- // save stripe elements options for later comparison
14484
- stripeStore.stripeElementsOptions = stripeOptions;
14485
- handleFetch.log('Stripe elements initialized');
14486
- // init stripe elements for billing address
14487
- stripeStore.stripeElementsForBillingAddress =
14488
- (_b = stripeStore.stripe) === null || _b === void 0 ? void 0 : _b.elements(stripeOptions);
14489
- handleFetch.log('Stripe elements for billing address initialized');
14490
- return;
14491
- }
14492
- if (!isSameOptions) {
14493
- // update elements with new option if it already exists
14494
- stripeStore.stripeElements.update(stripeOptions);
14495
- // update elements for stripe billing address
14496
- stripeStore.stripeElementsForBillingAddress.update(stripeOptions);
14497
- // save stripe elements options for later comparison
14498
- stripeStore.stripeElementsOptions = stripeOptions;
14499
- void stripeStore.stripeElements.fetchUpdates();
14500
- }
14501
- handleFetch.log('Stripe elements updated');
14502
- };
14503
- const stripeStoreReset = () => {
14504
- // clean clientSecret so that we can start the new one.
14505
- sessionStorage.removeItem('zonos--client-secret');
14506
- // cleanup stripe elements
14507
- reset$1();
14508
- // set stripe back to window.Zonos.stripe
14509
- stripeStore.stripe = window.Zonos.stripe;
14510
- };
14511
- const checkIsAddressOutdatedForValidation = () => {
14512
- var _a, _b, _c, _d;
14513
- 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);
14514
- const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
14515
- JSON.stringify((_c = stripeStore.stripeBillingAddressEventData) === null || _c === void 0 ? void 0 : _c.value) !==
14516
- JSON.stringify((_d = stripeStore.stripeBillingAddressUsedWhenValidatingAddress) === null || _d === void 0 ? void 0 : _d.value);
14517
- return isAddressDataDirty || isBillingAddressDataDirty;
14518
- };
14519
- const checkIsAddressOutdatedForLCPrefetch = () => {
14520
- var _a, _b, _c, _d, _e, _f;
14521
- const isLinkDataDirty = JSON.stringify((_a = stripeStore.stripeLinkUsedWhenFetchingLC) === null || _a === void 0 ? void 0 : _a.value) !==
14522
- JSON.stringify((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.value);
14523
- const isAddressDataDirty = JSON.stringify((_c = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _c === void 0 ? void 0 : _c.value) !==
14524
- JSON.stringify((_d = stripeStore.stripeAddressEventData) === null || _d === void 0 ? void 0 : _d.value);
14525
- const isBillingAddressDataDirty = !stripeStore.stripeShippingSameAsBilling &&
14526
- JSON.stringify((_e = stripeStore.stripeBillingAddressEventData) === null || _e === void 0 ? void 0 : _e.value) !==
14527
- JSON.stringify((_f = stripeStore.stripeBillingAddressUsedWhenFetchingLC) === null || _f === void 0 ? void 0 : _f.value);
14528
- return isLinkDataDirty || isAddressDataDirty || isBillingAddressDataDirty;
14529
- };
14530
- /**
14531
- * Check if the address and email info used when fetching landed cost with the current email and address info are different
14532
- * Purpose is to resend the request if the info used when fetching landed cost is different from the current info
14533
- */
14534
- const isPrefetchInfoOutdated = () => {
14535
- var _a;
14536
- // Mark the landed cost is outdated since the item total amount has changed (items total didn't match with the cart subtotal)
14537
- const isTotalAmountChanged = cartStore.landedCostData &&
14538
- ((_a = cartStore.landedCostData.find(Boolean)) === null || _a === void 0 ? void 0 : _a.subtotals.items) !==
14539
- cartStore.subtotal;
14540
- const isAddressOutdated = checkIsAddressOutdatedForLCPrefetch();
14541
- // Auto prefetch landed cost if tax id is updated
14542
- const isTaxIdDirty = stripeStore.taxIdUsedWhenFetchingLC !== stripeStore.taxId;
14543
- return (
14544
- // if landed cost data is not available, we need to fetch it
14545
- !cartStore.landedCostData ||
14546
- isAddressOutdated ||
14547
- isTotalAmountChanged ||
14548
- isTaxIdDirty);
14549
- };
14550
- const stripeCalculateLandedCost = async () => {
14551
- var _a;
14552
- const abortController = new AbortController();
14553
- stripeStore.fetchingLandedCostAbortController = abortController;
14554
- // Reset cart items to non-restricted state and restricted item list
14555
- cartStoreResetCartItems();
14556
- const { checkoutSessionWorkflow, errors, itemCreateWorkflow, landedCostCalculateWorkflow, partyCreateWorkflow, shipmentRatingCalculateWorkflow, } = await calculateLandedCostNormalized(abortController);
14557
- // update the error message with customized error message that rule is applying to and disabled shippment rating if there is any
14558
- cartStore.customQuotingError =
14559
- ((_a = errors === null || errors === void 0 ? void 0 : errors.find(error => { var _a; return ((_a = error.extensions) === null || _a === void 0 ? void 0 : _a.ruleMessageType) === 'CUSTOM'; })) === null || _a === void 0 ? void 0 : _a.message) || null;
14560
- cartStore.shippingData = sortServiceLevelOptionsByAmount((shipmentRatingCalculateWorkflow === null || shipmentRatingCalculateWorkflow === void 0 ? void 0 : shipmentRatingCalculateWorkflow.filter(Boolean)) || []);
14561
- // check and update cart items with restrictions
14562
- cartStoreCheckItemRestrictions(itemCreateWorkflow);
14563
- // reset abort controller after we are done
14564
- stripeStore.fetchingLandedCostAbortController = null;
14565
- cartStore.partiesData = (partyCreateWorkflow === null || partyCreateWorkflow === void 0 ? void 0 : partyCreateWorkflow.filter(Boolean)) || [];
14566
- // update cart store with landed cost info
14567
- cartStore.landedCostData =
14568
- (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.map(checkoutSession => {
14569
- const foundLandedCost = landedCostCalculateWorkflow === null || landedCostCalculateWorkflow === void 0 ? void 0 : landedCostCalculateWorkflow.find(item => (item === null || item === void 0 ? void 0 : item.id) === checkoutSession.landedCostId);
14570
- if (!foundLandedCost) {
14571
- return null;
14572
- }
14573
- return Object.assign(Object.assign({}, checkoutSession), { landedCost: foundLandedCost });
14574
- }).filter(Boolean)) || [];
14575
- // Send event when we get the quote back after the customer clicked "Continue to shipping"
14576
- const checkoutSessionId = cartStore.checkoutSessionId;
14577
- if (checkoutSessionWorkflow === null || checkoutSessionWorkflow === void 0 ? void 0 : checkoutSessionWorkflow.length) {
14578
- void trackConversionEvent({
14579
- checkoutSessionId,
14580
- eventName: 'checkout_quoteReceived',
14581
- });
14582
- }
14583
- // update adjustmentTotal
14584
- // highlight promocode input error if promocode is applied but no adjustment applied in landed cost
14585
- const isInvalidPromoCode = cartStore.promoCodeApplied &&
14586
- !cartStore.landedCostData.find(item => {
14587
- var _a;
14588
- return (_a = item.landedCost.appliedAdjustments) === null || _a === void 0 ? void 0 : _a.find(_item => _item.type === 'PROMO_CODE');
14589
- });
14590
- cartStore.promoCodeError = isInvalidPromoCode;
14591
- // When promocode is valid, set promoCode to session storage so if user close the modal, we can still reapply for them
14592
- if (!isInvalidPromoCode) {
14593
- sessionStorage.setItem('promoCode', cartStore.promoCode);
14594
- }
14595
- };
14596
- const stripeStorePrefetchLandedCost = async (params) => {
14597
- var _a, _b, _c, _d, _e, _f, _g, _h;
14598
- const retries = (params === null || params === void 0 ? void 0 : params.retries) || 0;
14599
- const applyingPromocode = !!(params === null || params === void 0 ? void 0 : params.applyingPromocode);
14600
- const stripeAddressReady = !!((_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.complete);
14601
- const stripeLinkReady = !!((_b = stripeStore.stripeLinkEventData) === null || _b === void 0 ? void 0 : _b.complete);
14602
- const stripeBillingAddressReady = stripeStore.stripeShippingSameAsBilling
14603
- ? !!((_c = stripeStore.stripeLinkEventData) === null || _c === void 0 ? void 0 : _c.complete)
14604
- : !!((_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.complete);
14605
- const shouldRefetch = isPrefetchInfoOutdated();
14606
- if (shouldRefetch) {
14607
- // if the info used when fetching landed cost is different from the current info, abort the previous request
14608
- (_e = stripeStore.fetchingLandedCostAbortController) === null || _e === void 0 ? void 0 : _e.abort();
14609
- stripeStore.fetchingLandedCostAbortController = null;
14610
- }
14611
- // Do not fetch if we are not ready or data is not outdated
14612
- if ((!shouldRefetch && !applyingPromocode) ||
14613
- !stripeAddressReady ||
14614
- !stripeLinkReady ||
14615
- !stripeBillingAddressReady) {
14616
- return;
14617
- }
14618
- // If there is retries, stop loading for a moment and then showing the spinner again (this is just so customer can see that checkout is doing something and not stuck)
14619
- if (retries) {
14620
- stripeStore.isFetchingLandedCost = false;
14621
- setTimeout(() => {
14622
- stripeStore.isFetchingLandedCost = true;
14623
- }, 300);
14624
- }
14625
- else {
14626
- stripeStore.isFetchingLandedCost = true;
14627
- }
14628
- if (stripeStore.stripeAddressEventData) {
14629
- stripeStore.stripeAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeAddressEventData);
14630
- }
14631
- if (stripeStore.stripeBillingAddressEventData) {
14632
- stripeStore.stripeBillingAddressUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeBillingAddressEventData);
14633
- }
14634
- if (stripeStore.stripeLinkEventData) {
14635
- stripeStore.stripeLinkUsedWhenFetchingLC = Object.assign({}, stripeStore.stripeLinkEventData);
14636
- }
14637
- stripeStore.taxIdUsedWhenFetchingLC = stripeStore.taxId;
14638
- try {
14639
- // Reset cart items to non-restricted state and restricted item list
14640
- cartStoreResetCartItems();
14641
- // fetch and apply landed cost
14642
- await stripeCalculateLandedCost();
14643
- // This is the cheapest service level since we already sorted them after fetching landed cost
14644
- const cheapestServiceLevel = (_f = cartStore.shippingData) === null || _f === void 0 ? void 0 : _f.find(Boolean);
14645
- // Landed cost that matches with service level
14646
- const matchLandedCost = (_g = cartStore.landedCostData) === null || _g === void 0 ? void 0 : _g.find(x => x.landedCost.shipmentRating.id === (cheapestServiceLevel === null || cheapestServiceLevel === void 0 ? void 0 : cheapestServiceLevel.id));
14647
- // apply new subtotal and total, this is mainly to show items in the presentment currency
14648
- const subtotals = !!matchLandedCost ? matchLandedCost.subtotals : null;
14649
- if (subtotals) {
14650
- // prefetch landed cost will not update shipping and taxes since we haven't selected shipping method yet
14651
- cartStoreApplySubtotals({
14652
- method: (matchLandedCost === null || matchLandedCost === void 0 ? void 0 : matchLandedCost.landedCost.method) || 'DDP',
14653
- subtotals,
14654
- });
14655
- }
14656
- }
14657
- catch (err) {
14658
- // default to empty array if we failed to fetch landed cost, so we can show the error message
14659
- cartStore.landedCostData = [];
14660
- cartStore.shippingData = [];
14661
- const excludeErrors = [
14662
- 'The landed cost calculation request was aborted to initiate a new one.',
14663
- ];
14664
- if (err instanceof Error &&
14665
- err.message &&
14666
- !excludeErrors.includes(err.message)) {
14667
- if (retries < 1) {
14668
- // retry fetching landed cost one more time
14669
- await stripeStorePrefetchLandedCost(Object.assign(Object.assign({}, params), { retries: (retries || 0) + 1 }));
14670
- return;
14671
- }
14672
- const shipToAddress = (_h = stripeStore.stripeAddressUsedWhenFetchingLC) === null || _h === void 0 ? void 0 : _h.value;
14673
- void handleFetch.sendErrorLog({
14674
- endpoint: `Failed to fetch landed cost (${retries} retries)`,
14675
- errors: [err.message],
14676
- metadata: {
14677
- cartId: window.Zonos.cartId,
14678
- shipToAddress,
14679
- },
14680
- });
14681
- }
14682
- handleFetch.logError(err);
14683
- }
14684
- stripeStore.isFetchingLandedCost = false;
14685
- };
14686
- const stripeStoreApplyPromoCode = async () => {
14687
- var _a, _b;
14688
- await stripeStorePrefetchLandedCost({
14689
- applyingPromocode: true,
14690
- });
14691
- // Go back to shipping step if we are in payment step so user can reselect shipping method
14692
- if (cartStore.step === 'payment') {
14693
- cartStorePreviousStep();
14694
- }
14695
- // This is the cheapest service level since we already sorted them after fetching landed cost
14696
- const cheapestServiceLevel = (_a = cartStore.shippingData) === null || _a === void 0 ? void 0 : _a.find(Boolean);
14697
- // Landed cost that matches with service level
14698
- const matchLandedCost = (_b = cartStore.landedCostData) === null || _b === void 0 ? void 0 : _b.find(x => x.landedCost.id === (cheapestServiceLevel === null || cheapestServiceLevel === void 0 ? void 0 : cheapestServiceLevel.id));
14699
- if (!cheapestServiceLevel || !matchLandedCost) {
14700
- return;
14701
- }
14702
- await cartStoreUpdateSelectedShippingOption(cheapestServiceLevel, matchLandedCost.landedCostId);
14703
- };
14704
- const stripeStoreResetPromoCode = () => {
14705
- cartStore.promoCode = '';
14706
- sessionStorage.removeItem('promoCode');
14707
- // reset promocode error state
14708
- cartStore.promoCodeError = false;
14709
- cartStore.promoCodeApplied = false;
14710
- };
14711
- const stripeStoreRemovePromoCode = async () => {
14712
- // Go back to shipping step if we are in payment step so user can reselect shipping method
14713
- if (cartStore.step === 'payment') {
14714
- cartStorePreviousStep();
14715
- }
14716
- stripeStoreResetPromoCode();
14717
- await stripeStoreApplyPromoCode();
14718
- };
14719
- const stripeStoreMessageBasedOnStatus = (status) => {
14720
- let messages = [];
14721
- let isError = true;
14722
- // Inspect the PaymentIntent `status` to indicate the status of the payment
14723
- // to your customer.
14724
- //
14725
- // Some payment methods will [immediately succeed or fail][0] upon
14726
- // confirmation, while others will first enter a `processing` state.
14727
- //
14728
- // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
14729
- switch (status) {
14730
- case 'succeeded': {
14731
- messages = [
14732
- 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.'),
14733
- '',
14734
- 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."),
14735
- ];
14736
- isError = false;
14737
- break;
14738
- }
14739
- case 'requires_capture':
14740
- case 'processing': {
14741
- messages = [
14742
- translate("Payment processing. We'll update you when payment is received."),
14743
- ];
14744
- isError = false;
14745
- break;
14746
- }
14747
- case 'requires_payment_method': {
14748
- messages = [
14749
- translate('Payment failed. Please try another payment method.'),
14750
- ];
14751
- break;
14752
- }
14753
- case 'requires_action': {
14754
- isError = false;
14755
- messages = [
14756
- translate('Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.'),
14757
- ];
14758
- }
14759
- default: {
14760
- messages = [translate('Something went wrong.')];
14761
- break;
14762
- }
14763
- }
14764
- return {
14765
- isError,
14766
- messages,
14767
- };
14768
- };
14769
- /**
14770
- * Handle inventory check and returns error message if the callback provided.
14771
- */
14772
- const stripeStoreHandleInventoryCheck = async () => {
14773
- var _a, _b;
14774
- const { onInventoryCheck } = zonosStore.zonosStore.checkoutSettings;
14775
- const hasReferenceId = !!((_b = (_a = window.Zonos.cartData) === null || _a === void 0 ? void 0 : _a.metadata.find(meta => meta.key === 'referenceId')) === null || _b === void 0 ? void 0 : _b.value);
14776
- // default inventory check is only available for legacy checkout and store has referenceId in metadata
14777
- if (window.Zonos.isLegacyCheckout &&
14778
- window.Zonos.cartData &&
14779
- hasReferenceId) {
14780
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/legacy/inventory-check', {
14781
- body: {
14782
- cartData: window.Zonos.cartData,
14783
- },
14784
- method: 'POST',
14785
- });
14786
- if (errors.length || !json) {
14787
- handleFetch.logError('Error occurs when handling inventory refund', 'warn', JSON.stringify(errors));
14788
- return null;
14789
- }
14790
- // Proceed if the item is available
14791
- if (!json.available || json.status === 204) {
14792
- return translate("The item you're looking for is currently unavailable in our inventory. Please check back later or contact support for assistance with availability.");
14793
- }
14794
- if (json.available || json.status === 200) {
14795
- stripeStore.shouldInventoryRefund = true;
14796
- return null;
14797
- }
14798
- return null;
14799
- }
14800
- if (typeof onInventoryCheck !== 'function') {
14801
- return null;
14802
- }
14803
- const message = await onInventoryCheck({ items: cartStore.items });
14804
- return message;
14805
- };
14806
- /**
14807
- * Handle inventory check and returns error message if the callback provided.
14808
- */
14809
- const stripeStoreHandleInventoryRefund = async () => {
14810
- var _a, _b;
14811
- const hasReferenceId = !!((_b = (_a = window.Zonos.cartData) === null || _a === void 0 ? void 0 : _a.metadata.find(meta => meta.key === 'referenceId')) === null || _b === void 0 ? void 0 : _b.value);
14812
- // inventory refund is only available for legacy checkout and store has referenceId in metadata
14813
- if (!window.Zonos.isLegacyCheckout ||
14814
- !window.Zonos.cartData ||
14815
- !hasReferenceId) {
14816
- return;
14817
- }
14818
- // handle inventory check on legacy checkout
14819
- await handleFetch.handleFetch('/api/zonos-elements/legacy/inventory-refund', {
14820
- body: {
14821
- cartData: window.Zonos.cartData,
14822
- },
14823
- method: 'POST',
14824
- });
14825
- };
14826
- const stripeStoreRetrievePayment = async ({ clientSecret: _clientSecret, storybookForceStatus, }) => {
14827
- if (storybookForceStatus) {
14828
- // return status right away if we are in storybook mode
14829
- const { isError, messages } = stripeStoreMessageBasedOnStatus(storybookForceStatus);
14830
- return { error: isError, messages };
14831
- }
14832
- const clientSecret = _clientSecret || stripeStore.clientSecret;
14833
- if (!stripeStore.stripe || !clientSecret) {
14834
- handleFetch.logError('Failed to retrieve payment intent. Stripe is not initialized');
14835
- return { error: true, message: [translate('Something went wrong.')] };
14836
- }
14837
- const { paymentIntent } = await stripeStore.stripe.retrievePaymentIntent(clientSecret);
14838
- const status = paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status;
14839
- const { isError, messages } = stripeStoreMessageBasedOnStatus(status);
14840
- return {
14841
- error: isError,
14842
- messages,
14843
- paymentIntentId: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.id,
14844
- paymentMethod: paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.payment_method,
14845
- status,
14846
- };
14847
- };
14848
- const stripeStoreConfirmPayment = async () => {
14849
- var _a, _b;
14850
- const stripePaymentReady = !!((_a = stripeStore.stripePaymentEventData) === null || _a === void 0 ? void 0 : _a.complete);
14851
- const stripeElements = stripeStore.stripeElements;
14852
- const stripe = stripeStore.stripe;
14853
- const stripeClientSecret = stripeStore.clientSecret;
14854
- stripeStore.customErrorMessage = null;
14855
- if (!((_b = cartStore.selectedLandedCost) === null || _b === void 0 ? void 0 : _b.landedCost.id)) {
14856
- throw new Error('Attempted to confirm the payment when no landed cost is found in store');
14857
- }
14858
- // Check if the checkout session is valid before proceeding
14859
- const checkoutSessionStatus = await validateCheckoutSession();
14860
- if (!checkoutSessionStatus.valid) {
14861
- stripeStore.customErrorMessage = checkoutSessionStatus.errorMessage;
14862
- throw new Error(checkoutSessionStatus.errorMessage);
14863
- }
14864
- const checkoutSessionId = cartStore.checkoutSessionId;
14865
- if (stripe &&
14866
- stripeElements &&
14867
- stripePaymentReady &&
14868
- stripeClientSecret &&
14869
- checkoutSessionId) {
14870
- const buildUrl = new URL(window.location.href);
14871
- buildUrl.searchParams.set('payment_intent_client_secret', stripeClientSecret);
14872
- buildUrl.searchParams.set('zonosCheckoutSessionId', checkoutSessionId);
14873
- void trackConversionEvent({
14874
- checkoutSessionId,
14875
- eventName: 'checkout_paymentInfoCompleted',
14876
- });
14877
- const { error, paymentIntent } = await stripe.confirmPayment({
14878
- confirmParams: {
14879
- return_url: buildUrl.toString(),
14880
- },
14881
- elements: stripeElements,
14882
- redirect: 'if_required',
14883
- });
14884
- handleFetch.log('Payment intent confirmed', 'info', { error, paymentIntent });
14885
- if ((paymentIntent === null || paymentIntent === void 0 ? void 0 : paymentIntent.status) === 'requires_action') {
14886
- throw new Error(translate('Your selected payment method requires additional verification. Please follow the instructions provided by your payment provider to complete the transaction.'));
14887
- }
14888
- if (error) {
14889
- if (error.type === 'card_error' || error.type === 'validation_error') {
14890
- throw new Error(error.message);
14891
- }
14892
- if (error.type === 'invalid_request_error') {
14893
- if (error.code === 'payment_intent_unexpected_state') {
14894
- // PaymentIntent was canceled or expired, or status is `require_capture`.
14895
- // don't throw error here because we will reset the checkout session last step
14896
- return;
14897
- }
14898
- }
14899
- throw new Error('An unexpected error occurred.');
14900
- }
14901
- if (paymentIntent.status === 'requires_payment_method') {
14902
- // Failed to confirm payment, allows user to try another payment method
14903
- throw new Error(translate('Payment failed. Please try another payment method.'));
14904
- }
14905
- }
14906
- };
14907
- const getCheckoutSessionBody = () => {
14908
- var _a;
14909
- const total = cartStore.items.reduce((amount, item) => amount + item.amount * item.quantity, 0);
14910
- const body = {
14911
- adjustmentsAmount: cartStore.adjustments.reduce((prev, adj) => prev + adj.amount, 0),
14912
- cartId: window.Zonos.cartId,
14913
- currency: ((_a = cartStore.items.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode) || '',
14914
- customerAuthenticationToken: cartStore.customerAuthenticationToken || undefined,
14915
- itemsAmount: total,
14916
- metadata: [
14917
- {
14918
- key: 'language',
14919
- value: localizationStore.selectedLocale,
14920
- },
14921
- {
14922
- key: 'appVersion',
14923
- value: window.Zonos.version,
14924
- },
14925
- {
14926
- key: 'appVersionNpmIntegration',
14927
- value: window.Zonos.isNpm ? '1' : '0',
14928
- },
14929
- {
14930
- key: 'legacyCheckoutFacade',
14931
- value: window.Zonos.isLegacyCheckout ? '1' : '0',
14932
- },
14933
- ],
14934
- presentmentCountryCode: localizationStore.selectedCountryCode,
14935
- skipPaymentIntent: stripeStore.skipPaymentIntent,
14936
- };
14937
- return body;
14938
- };
14939
- const stripeStoreGetPaymentIntent = async () => {
14940
- var _a;
14941
- if (!cartStore.checkoutSessionId) {
14942
- // We want to log the error anytime we fail to create a checkout session
14943
- void handleFetch.sendErrorLog({
14944
- endpoint: 'Error creating payment intent',
14945
- errors: ['No checkout session id found when retrieving payment intent'],
14946
- metadata: {
14947
- allLogs: handleFetch.allLogs,
14948
- cartId: window.Zonos.cartId,
14949
- },
14950
- });
14951
- cartStoreUpdateToErrorState({
14952
- messages: [
14953
- translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
14954
- ],
14955
- title: translate('Error creating Checkout'),
14956
- });
14957
- return;
14958
- }
14959
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/create-payment-intent', {
14960
- body: {
14961
- checkoutSessionId: cartStore.checkoutSessionId,
14962
- },
14963
- method: 'POST',
14964
- });
14965
- const clientSecret = (_a = json === null || json === void 0 ? void 0 : json.checkoutSessionPaymentIntentCreate) === null || _a === void 0 ? void 0 : _a.clientSecret;
14966
- if (errors.length || !clientSecret) {
14967
- handleFetch.logError('Error occurs when getting payment intent', JSON.stringify(errors, null, 2));
14968
- // We want to log the error anytime we fail to create a payment intent
14969
- void handleFetch.sendErrorLog({
14970
- endpoint: 'Error creating payment intent',
14971
- errors: errors.map(error => error.message),
14972
- metadata: {
14973
- allLogs: handleFetch.allLogs,
14974
- cartId: window.Zonos.cartId,
14975
- checkoutSessionId: cartStore.checkoutSessionId,
14976
- clientSecret,
14977
- },
14978
- });
14979
- cartStoreUpdateToErrorState({
14980
- messages: [
14981
- translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
14982
- ],
14983
- title: translate('Error creating Checkout'),
14984
- });
14985
- return;
14986
- }
14987
- // update cart store checkout session with updated from checkout session payment intent creation call so the checkout session and payment intent are in sync
14988
- cartStoreSetCheckoutSession(json.checkoutSessionPaymentIntentCreate);
14989
- };
14990
- /**
14991
- * Init checkout session
14992
- * @returns {boolean} whether or not the checkout session is successfully created
14993
- */
14994
- const stripeStoreInitCheckoutSession = async () => {
14995
- var _a, _b;
14996
- if (!localizationStore.targetCurrency) {
14997
- handleFetch.logError(`Failed to create checkout session - missing localizationStore.targetCurrency`);
14998
- return false;
14999
- }
15000
- stripeStore.isFetchingSession = true;
15001
- const body = getCheckoutSessionBody();
15002
- handleFetch.log('Checkout session body', 'info', body);
15003
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/create-checkout-session', {
15004
- body,
15005
- method: 'POST',
15006
- });
15007
- stripeStore.isFetchingSession = false;
15008
- if (errors.length || !json) {
15009
- const messages = (_a = errors.find(error => error.message)) === null || _a === void 0 ? void 0 : _a.message;
15010
- // check if the error is related to expired cart and thow error so we can show error message accordingly
15011
- if (messages.some(message => message.message === 'Cart is expired.')) {
15012
- throw new Error('Cart is expired.');
15013
- }
15014
- handleFetch.logError('Error occurred when creating checkout session', JSON.stringify(errors, null, 2));
15015
- return false;
15016
- }
15017
- const result = json.checkoutSessionCreate;
15018
- // update cart store with updated information
15019
- cartStoreSetCheckoutSession(result);
15020
- cartStoreApplySubtotals({
15021
- method: ((_b = result.landedCost) === null || _b === void 0 ? void 0 : _b.method) || 'DDP',
15022
- subtotals: result.subtotals,
15023
- });
15024
- handleFetch.log('Exchange rate updated for cart items (checkout session create)', 'info', cartStore.exchangeRate);
15025
- handleFetch.log('done-init-checkout-session');
15026
- return true;
15027
- };
15028
- const stripeStoreUpdateCheckoutSessionBaseCurrency = async () => {
15029
- const checkoutSessionId = cartStore.checkoutSessionId;
15030
- // Checkout session id should be available at this point
15031
- if (!checkoutSessionId) {
15032
- handleFetch.logError('Failed to update checkout session base currency');
15033
- return false;
15034
- }
15035
- // Only update checkout session currency if setting is enabled
15036
- if (zonosStore.zonosStore.checkoutSettings.allowedSettlementCurrencies === 'LOCAL') {
15037
- handleFetch.log('allowedSettlementCurrencies: "LOCAL". Skip updating checkout session base currency');
15038
- return true;
15039
- }
15040
- const { json } = await handleFetch.handleFetch('/api/zonos-elements/update-checkout-session-base-currency', {
15041
- body: {
15042
- checkoutSessionId,
15043
- currencyCode: stripeStore.checkoutSettlementCurrency,
15044
- },
15045
- method: 'POST',
15046
- });
15047
- const settlementCurrencyCode = json === null || json === void 0 ? void 0 : json.checkoutSessionBaseCurrencyUpdate.subtotals.presentmentCurrencyCode;
15048
- // S
15049
- if (!json ||
15050
- settlementCurrencyCode !== stripeStore.checkoutSettlementCurrency) {
15051
- handleFetch.logError('Failed to update checkout session base currency');
15052
- return false;
15053
- }
15054
- handleFetch.log(`Updated checkout session to settlement currency "${settlementCurrencyCode}".`);
15055
- return true;
15056
- };
15057
- /**
15058
- * Update checkout session. Use for updating amount with landed cost id, or update session when cart items change
15059
- */
15060
- const stripeStoreUpdateCheckoutSession = async ({ adjustmentsAmount, cartId, currency, id, itemsAmount, landedCostId, presentmentCountryCode, }) => {
15061
- // No need to set loading state here because this function will be called under the hood to update
15062
- // landed cost id for the section.
15063
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/update-checkout-session', {
15064
- body: {
15065
- adjustmentsAmount,
15066
- cartId,
15067
- currency,
15068
- customerAuthenticationToken: cartStore.customerAuthenticationToken || undefined,
15069
- id,
15070
- itemsAmount,
15071
- landedCostId,
15072
- metadata: [
15073
- {
15074
- key: 'language',
15075
- value: localizationStore.selectedLocale,
15076
- },
15077
- {
15078
- key: 'appVersion',
15079
- value: window.Zonos.version,
15080
- },
15081
- {
15082
- key: 'appVersionNpmIntegration',
15083
- value: window.Zonos.isNpm ? '1' : '0',
15084
- },
15085
- {
15086
- key: 'legacyCheckoutFacade',
15087
- value: window.Zonos.isLegacyCheckout ? '1' : '0',
15088
- },
15089
- ],
15090
- presentmentCountryCode,
15091
- skipPaymentIntent: stripeStore.skipPaymentIntent,
15092
- },
15093
- method: 'POST',
15094
- });
15095
- if (errors.length || !json) {
15096
- handleFetch.logError('Error occurs when updating checkout session', JSON.stringify(errors, null, 2));
15097
- return { errors, json };
15098
- }
15099
- return { errors: [], json };
15100
- };
15101
- /**
15102
- * This function builds a translated address object from the current address and the translated address result.
15103
- * 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.
15104
- * 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.
15105
- *
15106
- * @param {Object} params - The parameters for the function.
15107
- * @param {Address} params.currentAddress - The current address information.
15108
- * @param {Address} params.translatedAddressResult - The translated address result.
15109
- *
15110
- * @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.
15111
- */
15112
- const buildTranslatedAddress = ({ currentAddress, translatedAddressResult, }) => {
15113
- const translatedAddress = {};
15114
- if (!translatedAddressResult) {
15115
- return translatedAddress;
15116
- }
15117
- const { city, line1, line2, name, postal_code, state } = translatedAddressResult;
15118
- // If we have translated address, add it to the translated address object
15119
- if (currentAddress.city && city) {
15120
- translatedAddress.city = {
15121
- [currentAddress.city]: city,
15122
- };
15123
- }
15124
- if (currentAddress.line1 && line1) {
15125
- translatedAddress.line1 = {
15126
- [currentAddress.line1]: line1,
15127
- };
15128
- }
15129
- if (currentAddress.line2 && line2) {
15130
- translatedAddress.line2 = {
15131
- [currentAddress.line2]: line2,
15132
- };
15133
- }
15134
- if (currentAddress.postal_code && postal_code) {
15135
- translatedAddress.postal_code = {
15136
- [currentAddress.postal_code]: postal_code,
15137
- };
15138
- }
15139
- if (currentAddress.state && state) {
15140
- translatedAddress.state = {
15141
- [currentAddress.state]: state,
15142
- };
15143
- }
15144
- if (currentAddress.name && name) {
15145
- translatedAddress.name = {
15146
- [currentAddress.name]: name,
15147
- };
15148
- }
15149
- return translatedAddress;
15150
- };
15151
- /**
15152
- * This function translates an address to Latin characters using the Zonos API.
15153
- * 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.
15154
- * If the address is not outdated, it returns without making the API call.
15155
- * 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.
15156
- * 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.
15157
- *
15158
- * @param {Object} params - The parameters for the function.
15159
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.addressInvalidCharactersList - The list of address fields that contain invalid characters.
15160
- * @param {ReturnType<typeof containsNonLatinChars> | null} params.billingAddressInvalidCharactersList - The list of billing address fields that contain invalid characters.
15161
- */
15162
- const stripeStoreTranslateAddressToLatin = async ({ addressInvalidCharactersList, billingAddressInvalidCharactersList, }) => {
15163
- var _a, _b, _c, _d;
15164
- const requestBody = buildTranslateRequest({
15165
- addressInvalidCharactersList,
15166
- billingAddressInvalidCharactersList,
15167
- stripeAddressEventData: stripeStore.stripeAddressEventData,
15168
- stripeBillingAddressEventData: stripeStore.stripeBillingAddressEventData,
15169
- stripeShippingSameAsBilling: stripeStore.stripeShippingSameAsBilling,
15170
- });
15171
- if (!requestBody) {
15172
- // reset translated address if we don't have any address to translate
15173
- stripeStore.translatedAddress = {
15174
- address: {},
15175
- billingAddress: {},
15176
- };
15177
- return;
15178
- }
15179
- // only translate address if the address is out of date
15180
- const isAddressOutdated = checkIsAddressOutdatedForValidation();
15181
- if (!isAddressOutdated) {
15182
- return;
15183
- }
15184
- const { errors, json } = await handleFetch.handleFetch('/api/zonos-elements/validate-address', {
15185
- body: requestBody,
15186
- method: 'POST',
15187
- });
15188
- if (errors.length || !json) {
15189
- handleFetch.logError('Error occurs when translating address to latin', JSON.stringify(errors, null, 2));
15190
- // reset translated address if we Failed to translate and let user manually fix it
15191
- stripeStore.translatedAddress = {
15192
- address: {},
15193
- billingAddress: {},
15194
- };
15195
- return;
15196
- }
15197
- // Set current address to the store so we can compare it later to determine if we need to re-translate the address
15198
- stripeStore.stripeAddressUsedWhenValidatingAddress =
15199
- stripeStore.stripeAddressEventData;
15200
- stripeStore.stripeBillingAddressUsedWhenValidatingAddress =
15201
- stripeStore.stripeBillingAddressEventData;
15202
- const address = (_a = stripeStore.stripeAddressEventData) === null || _a === void 0 ? void 0 : _a.value.address;
15203
- const billingAddress = (_b = stripeStore.stripeBillingAddressEventData) === null || _b === void 0 ? void 0 : _b.value.address;
15204
- // Set the translated address to the store so we can populate it to the address element for user to update
15205
- stripeStore.translatedAddress = {
15206
- address: address
15207
- ? buildTranslatedAddress({
15208
- currentAddress: Object.assign(Object.assign({}, address), { name: (_c = stripeStore.stripeAddressEventData) === null || _c === void 0 ? void 0 : _c.value.name }),
15209
- translatedAddressResult: json.address || null,
15210
- })
15211
- : {},
15212
- billingAddress: !stripeStore.stripeShippingSameAsBilling
15213
- ? buildTranslatedAddress({
15214
- currentAddress: Object.assign(Object.assign({}, billingAddress), { name: (_d = stripeStore.stripeBillingAddressEventData) === null || _d === void 0 ? void 0 : _d.value.name }),
15215
- translatedAddressResult: json.billingAddress || null,
15216
- })
15217
- : {},
15218
- };
15219
- };
15220
- onChange$1('clientSecret', clientSecret => {
15221
- // update stripe elements when client secret changes
15222
- if (clientSecret && stripeStore.stripe) {
15223
- sessionStorage.setItem('zonos--client-secret', clientSecret);
15224
- }
15225
- if (!clientSecret) {
15226
- sessionStorage.removeItem('zonos--client-secret');
15227
- }
15228
- });
15229
-
15230
- const { onChange, reset, state: cartStore, } = zonosStore.createStore(() => ({
15231
- adjustmentTotal: 0,
15232
- adjustments: [],
15233
- checkoutSession: null,
15234
- checkoutSessionId: sessionStorage.getItem('zonos--checkout-session-id') || null,
15235
- checkoutSessionTimeoutShow: false,
15236
- checkoutTimeoutInterval: null,
15237
- currency: 'USD',
15238
- customQuotingError: null,
15239
- customerAuthenticationToken: null,
15240
- displayBaseCurrency: false,
15241
- dutiesTaxesFees: null,
15242
- dutiesTaxesFeesEstimate: null,
15243
- error: null,
15244
- exchangeRate: null,
15245
- externalConfirmationPageURL: null,
15246
- inventoryCheckErrorMessage: null,
15247
- isSelectedShippingAboveDeminimis: false,
15248
- isSelectedShippingGuarantee: false,
15249
- isStagingMode: handleFetch.getIsStagingMode(),
15250
- items: [],
15251
- landedCostData: null,
15252
- landedCostMethod: 'DDP',
15253
- partiesData: [],
15254
- promoCode: sessionStorage.getItem('promoCode') || '',
15255
- // When user clicked applied button, save promocode into session storage for later use. So if session has promocode, applied button is clicked
15256
- promoCodeApplied: !!sessionStorage.getItem('promoCode'),
15257
- promoCodeError: false,
15258
- restrictedItems: [],
15259
- selectedLandedCost: null,
15260
- selectedShippingOption: null,
15261
- selectedShippingOptionExpectedDate: '',
15262
- selectedShippingOptionTransitTime: '',
15263
- shipping: 0,
15264
- shippingData: null,
15265
- shouldHideDiscountInput: false,
15266
- step: 'customer-info',
15267
- subtotal: 0,
15268
- tabItems: {
15269
- 'customer-info': {
15270
- index: 1,
15271
- isDone: false,
15272
- label: 'Customer',
15273
- value: 'customer-info',
15274
- },
15275
- shipping: {
15276
- index: 2,
15277
- isDone: false,
15278
- label: 'Shipping',
15279
- value: 'shipping',
15280
- },
15281
- // eslint-disable-next-line sort-keys/sort-keys-fix
15282
- payment: {
15283
- index: 3,
15284
- isDone: false,
15285
- label: 'Payment',
15286
- value: 'payment',
15287
- },
15288
- },
15289
- total: 0,
15290
- }));
15291
- const getTransitUnit = (type) => {
15292
- switch (type) {
15293
- case 'DAYS':
15294
- return translate('days');
15295
- case 'WEEKS':
15296
- return translate('weeks');
15297
- case 'BUSINESS_DAYS':
15298
- default:
15299
- return translate('business days');
15300
- }
15301
- };
15302
- /**
15303
- * Format shipping transit info to be displayed on UI
15304
- * @returns
15305
- * - expectedDate: Thursday, Aug 12
15306
- * - maxTransit: 5
15307
- * - minTransit: 3
15308
- */
15309
- const cartStoreGetShippingTransitInfo = (item) => {
15310
- var _a;
15311
- const transitTime = (_a = item.shippingProfile) === null || _a === void 0 ? void 0 : _a.transitTime;
15312
- // Don't care about falsy 0 values because this is international shipping and 0 days is not feasible
15313
- if (!(transitTime === null || transitTime === void 0 ? void 0 : transitTime.min) || !(transitTime === null || transitTime === void 0 ? void 0 : transitTime.max) || !(transitTime === null || transitTime === void 0 ? void 0 : transitTime.type)) {
15314
- return null;
15315
- }
15316
- return {
15317
- maxTransit: transitTime.max,
15318
- minTransit: transitTime.min,
15319
- unit: getTransitUnit(transitTime.type),
15320
- };
15321
- };
15322
- const getMatchItem = ({ item1, item2, }) => {
15323
- if (!item1 || !item2) {
15324
- return false;
15325
- }
15326
- return ((item2.sku && item1.sku && item1.sku === item2.sku) ||
15327
- (item2.description &&
15328
- item1.description &&
15329
- item1.description === item2.description) ||
15330
- (item1.name && item2.name && item1.name === item2.name));
15331
- };
15332
- /**
15333
- * Check and set restricted items in cart
15334
- */
15335
- const cartStoreCheckItemRestrictions = (itemsWorkflow) => {
15336
- handleFetch.log('Checking item restrictions');
15337
- const mappedRestrictedItems = itemsWorkflow
15338
- .map(item => {
15339
- if (!item.restriction) {
15340
- return null;
15341
- }
15342
- const { restriction } = item;
15343
- const matchedItem = cartStore.items.find(x => getMatchItem({ item1: x, item2: item }));
15344
- return Object.assign(Object.assign({ matchedItem }, item), { restriction });
15345
- })
15346
- .filter(Boolean);
15347
- cartStore.restrictedItems = mappedRestrictedItems;
15348
- // remove items that are restricted from cart
15349
- cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: !!mappedRestrictedItems.find(x => getMatchItem({ item1: x, item2: item })) })));
15350
- return {
15351
- cartItems: cartStore.items,
15352
- restrictedItems: mappedRestrictedItems,
15353
- };
15354
- };
15355
- const cartStoreReset = () => {
15356
- sessionStorage.removeItem('zonos--checkout-session-id');
15357
- // reset cart store
15358
- reset();
15359
- };
15360
- const cartStoreUpdateToErrorState = ({ messages, title, }) => {
15361
- cartStoreReset();
15362
- stripeStoreReset();
15363
- cartStore.step = 'error';
15364
- cartStore.error = {
15365
- messages,
15366
- title,
15367
- };
15368
- };
15369
- const cartStoreApplySubtotals = ({ dutiesTaxesFeesEstimate, method, subtotals, }) => {
15370
- // update exchange rate so we can use it to display cart items
15371
- cartStore.exchangeRate = subtotals.exchangeRate;
15372
- cartStore.adjustmentTotal = subtotals.adjustments;
15373
- cartStore.dutiesTaxesFees =
15374
- method === 'DAP' ? null : subtotals.landedCostTotal;
15375
- cartStore.subtotal = subtotals.items;
15376
- cartStore.total = subtotals.total;
15377
- cartStore.currency = subtotals.presentmentCurrencyCode;
15378
- cartStore.dutiesTaxesFeesEstimate = dutiesTaxesFeesEstimate || null;
15379
- };
15380
- /**
15381
- * Detect if there are any items in cart that are not restricted and have positive amount, exclude negative amount items
15382
- */
15383
- const cartStoreHasOneEligibleItem = () => {
15384
- // filter all items with positive amount
15385
- const checkItems = cartStore.items.filter(item => item.amount > 0);
15386
- // only check restricted status for items with positive amount
15387
- // if there is no item restricted found => all items are restricted
15388
- return !!checkItems.find(item => !item.isRestricted);
15389
- };
15390
- const cartStoreSetCheckoutSession = (checkoutSession) => {
15391
- var _a, _b, _c, _d, _e;
15392
- // update stripe store with updated information
15393
- stripeStore.clientSecret = checkoutSession.clientSecret;
15394
- stripeStore.stripeCustomerSessionClientSecret =
15395
- checkoutSession.customerSessionClientSecret;
15396
- stripeStore.customerProfile = checkoutSession.customerProfile;
15397
- cartStore.checkoutSession = checkoutSession;
15398
- if (!checkoutSession.id) {
15399
- // Log error to track down the issue
15400
- void handleFetch.sendErrorLog({
15401
- endpoint: 'cartStoreSetCheckoutSession',
15402
- errors: ['Missing checkout session id in checkout session'],
15403
- metadata: {
15404
- allLogs: handleFetch.allLogs,
15405
- checkoutSession,
15406
- },
15407
- });
15408
- }
15409
- // Only update checkout session id if it's not empty
15410
- if (checkoutSession.id) {
15411
- cartStore.checkoutSessionId = checkoutSession.id;
15412
- }
15413
- // Check if there is a redirect URL in the metadata to override
15414
- const externalConfirmationPageURL = ((_c = (_b = (_a = cartStore.checkoutSession) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.find(entry => (entry === null || entry === void 0 ? void 0 : entry.key) === 'externalConfirmationPageURL')) === null || _c === void 0 ? void 0 : _c.value) ||
15415
- (
15416
- // Sometimes externalConfirmationPageURL is not in checkoutSession create/update, check if there is a redirect URL in the cart metadata to override
15417
- (_e = (_d = window.Zonos.cartData) === null || _d === void 0 ? void 0 : _d.metadata.find(entry => (entry === null || entry === void 0 ? void 0 : entry.key) === 'externalConfirmationPageURL')) === null || _e === void 0 ? void 0 : _e.value) ||
15418
- null;
15419
- if (externalConfirmationPageURL) {
15420
- handleFetch.log(`Found externalConfirmationPageURL: ${externalConfirmationPageURL}`);
15421
- cartStore.externalConfirmationPageURL = externalConfirmationPageURL;
15422
- }
15423
- };
15424
- const cartStoreReCalculateTotal = async ({ adjustmentsAmount, cartId, currency, dutiesTaxesFeesEstimate, itemsAmount, landedCostId, shouldInitSessionOnFailure, }) => {
15425
- var _a;
15426
- if (landedCostId && cartStore.selectedLandedCost) {
15427
- // update cart total right away if we have landed cost id to avoid order total flickering
15428
- const subtotals = cartStore.selectedLandedCost.subtotals;
15429
- cartStoreApplySubtotals({
15430
- dutiesTaxesFeesEstimate,
15431
- method: cartStore.landedCostMethod,
15432
- subtotals,
15433
- });
15434
- handleFetch.log('Exchange rate updated for cart items (landed cost subtotal)', 'info', cartStore.exchangeRate);
15435
- }
15436
- // update checkout session
15437
- if (!cartStore.checkoutSessionId) {
15438
- handleFetch.log('Could not update cart total without checkout session id', 'info');
15439
- return false;
15440
- }
15441
- const { errors, json } = await stripeStoreUpdateCheckoutSession({
15442
- adjustmentsAmount,
15443
- cartId,
15444
- currency,
15445
- id: cartStore.checkoutSessionId,
15446
- itemsAmount,
15447
- landedCostId,
15448
- presentmentCountryCode: localizationStore.selectedCountryCode,
15449
- });
15450
- if (errors.length > 0 || !json) {
15451
- handleFetch.logError('Error occurs when updating checkout session.');
15452
- if (shouldInitSessionOnFailure) {
15453
- handleFetch.log('Initiating checkout session on failure', 'info');
15454
- const success = await stripeStoreInitCheckoutSession();
15455
- handleFetch.log(`stripeStoreInitCheckoutSession: ${success}`);
15456
- if (!success) {
15457
- cartStoreUpdateToErrorState({
15458
- messages: [
15459
- translate("There's been an error creating your checkout session. Please reload and try again or contact support if the error persists"),
15460
- ],
15461
- title: translate('Error creating Checkout'),
15462
- });
15463
- return false;
15464
- }
15465
- return true;
15466
- }
15467
- return false;
15468
- }
15469
- if (!landedCostId) {
15470
- // This is when we first open the checkout modal and we just want to get info from the old cart session.
15471
- // use subtotals from checkout session to update cart total
15472
- cartStoreApplySubtotals({
15473
- method: ((_a = json.checkoutSessionUpdate.landedCost) === null || _a === void 0 ? void 0 : _a.method) || 'DDP',
15474
- subtotals: json.checkoutSessionUpdate.subtotals,
15475
- });
15476
- handleFetch.log('Exchange rate updated for cart items (checkout session update)', 'info', cartStore.exchangeRate);
15477
- }
15478
- cartStoreSetCheckoutSession(json.checkoutSessionUpdate);
15479
- return true;
15480
- };
15481
- const cartStoreUpdateSelectedShippingOption = async (selectedShippingOption, landedCostId) => {
15482
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
15483
- cartStore.selectedShippingOption = selectedShippingOption;
15484
- // update shipping transit info
15485
- const transitData = cartStoreGetShippingTransitInfo(cartStore.selectedShippingOption);
15486
- if (transitData) {
15487
- const { maxTransit, minTransit, unit } = transitData;
15488
- cartStore.selectedShippingOptionTransitTime = `${minTransit}-${maxTransit} ${unit}`;
15489
- }
15490
- else {
15491
- cartStore.selectedShippingOptionTransitTime = '';
15492
- }
15493
- const selectedLandedCost = (_a = cartStore.landedCostData) === null || _a === void 0 ? void 0 : _a.find(x => x.landedCostId === landedCostId);
15494
- // save selected landed cost for later use
15495
- cartStore.selectedLandedCost = selectedLandedCost || null;
15496
- if (!selectedLandedCost) {
15497
- // do nothing if we can't find landed cost for selected shipping option
15498
- return false;
15499
- }
15500
- // If the quote is DAP, then convert manually.
15501
- const landedCostAmount = ((_b = selectedLandedCost.landedCost.amountSubtotals) === null || _b === void 0 ? void 0 : _b.landedCostTotal) || 0;
15502
- // Convert using checkout presentment exchange rate
15503
- const exchangeRate = selectedLandedCost.subtotals.exchangeRate.rate;
15504
- const dutiesTaxesFeesEstimate = landedCostAmount * exchangeRate;
15505
- if (dutiesTaxesFeesEstimate) {
15506
- handleFetch.log(`DAP quote, using estimate: ${dutiesTaxesFeesEstimate}`, 'info');
15507
- }
15508
- cartStore.landedCostMethod = selectedLandedCost.landedCost.method || 'DDP';
15509
- // update shipping value and dutiesTaxFees on selectedShippingOption change
15510
- cartStore.shipping = selectedLandedCost.subtotals.shipping;
15511
- // update deminimis status
15512
- const isGuarantee = ((_c = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _c === void 0 ? void 0 : _c.landedCostGuaranteeCode) === 'ZONOS';
15513
- // one item in deminimis with type of duty and tax has threshold value is "ABOVE"
15514
- const isAboveDeminimis = !!((_e = (_d = selectedLandedCost === null || selectedLandedCost === void 0 ? void 0 : selectedLandedCost.landedCost) === null || _d === void 0 ? void 0 : _d.deMinimis) === null || _e === void 0 ? void 0 : _e.find(item => ['DUTY', 'TAX'].includes(item.type) && item.threshold === 'ABOVE'));
15515
- cartStore.isSelectedShippingAboveDeminimis = isAboveDeminimis;
15516
- cartStore.isSelectedShippingGuarantee = isGuarantee;
15517
- // update session with selected landed cost
15518
- const updateCalculateStatus = await cartStoreReCalculateTotal({
15519
- adjustmentsAmount: cartStore.adjustmentTotal,
15520
- cartId: window.Zonos.cartId,
15521
- dutiesTaxesFeesEstimate: dutiesTaxesFeesEstimate,
15522
- landedCostId: (_f = selectedLandedCost.landedCost) === null || _f === void 0 ? void 0 : _f.id,
15523
- });
15524
- // update conditionally render pay in USD button
15525
- const firstItem = (_g = cartStore.items.find(Boolean)) === null || _g === void 0 ? void 0 : _g.currencyCode;
15526
- // Stripe address event data should be available at this point
15527
- const shipToCountry = ((_h = stripeStore.stripeAddressEventData) === null || _h === void 0 ? void 0 : _h.value.address.country) || 'US';
15528
- // Only show pay in USD button if item's currency is in USD, the setting is enabled and the order presentment currency is not USD, also only in USD settlement ship to country list
15529
- stripeStore.shouldRenderPayInUsdButton =
15530
- firstItem === 'USD' &&
15531
- zonosStore.zonosStore.checkoutSettings.allowedSettlementCurrencies ===
15532
- 'LOCAL_AND_USD' &&
15533
- ((_j = cartStore.checkoutSession) === null || _j === void 0 ? void 0 : _j.subtotals.presentmentCurrencyCode) !== 'USD' &&
15534
- !!((_l = (_k = zonosStore.zonosStore.genericSettings) === null || _k === void 0 ? void 0 : _k.usdSettlementCountryEnabled) === null || _l === void 0 ? void 0 : _l.includes(shipToCountry));
15535
- return updateCalculateStatus;
15536
- };
15537
- onChange('checkoutSessionId', () => {
15538
- handleFetch.log('checkoutSessionId changed', 'info', cartStore.checkoutSessionId);
15539
- if (!cartStore.checkoutSessionId) {
15540
- sessionStorage.removeItem('zonos--checkout-session-id');
15541
- return;
15542
- }
15543
- sessionStorage.setItem('zonos--checkout-session-id', cartStore.checkoutSessionId);
15544
- });
15545
- const cartStoreStartCheckoutInterval = ({ isPreview, sessionTimeout, }) => {
15546
- // do nothing if in preview mode
15547
- if (isPreview) {
15548
- return;
15549
- }
15550
- const timeoutQuery = new URLSearchParams(window.location.search).get('zonosCheckoutTimeout');
15551
- const timeout =
15552
- // timeout query is mainly for testing purpose
15553
- timeoutQuery && !isNaN(parseInt(timeoutQuery, 10))
15554
- ? parseInt(timeoutQuery, 10)
15555
- : sessionTimeout;
15556
- handleFetch.log(`==START CHECKOUT TIMEOUT - ${timeout}==`);
15557
- cartStore.checkoutTimeoutInterval = setTimeout(() => {
15558
- cartStore.checkoutSessionTimeoutShow = true;
15559
- }, timeout);
15560
- };
15561
- const cartStoreClearCheckoutInterval = () => {
15562
- if (cartStore.checkoutTimeoutInterval) {
15563
- clearTimeout(cartStore.checkoutTimeoutInterval);
15564
- cartStore.checkoutTimeoutInterval = null;
15565
- }
15566
- };
15567
- const getCartItemToUse = (items) => items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
15568
- const cartStoreResetCartItems = () => {
15569
- // mark all items as not restricted
15570
- cartStore.items = cartStore.items.map(item => (Object.assign(Object.assign({}, item), { isRestricted: false })));
15571
- cartStore.restrictedItems = [];
15572
- };
15573
- const cartStoreUpdateItems = async ({ adjustments, cartItems, }) => {
15574
- var _a;
15575
- // Update adjustments and items
15576
- cartStore.adjustments = adjustments;
15577
- cartStore.items = getCartItemToUse(cartItems);
15578
- const currency = (_a = cartItems.find(Boolean)) === null || _a === void 0 ? void 0 : _a.currencyCode;
15579
- const total = cartItems.reduce((amt, item) => {
15580
- return amt + item.amount * item.quantity;
15581
- }, 0);
15582
- const adjustmentTotal = adjustments.reduce((amt, adjustment) => amt + adjustment.amount, 0);
15583
- if (!currency || !total) {
15584
- // do nothing if we can't get currency or total
15585
- return;
15586
- }
15587
- cartStore.currency = currency;
15588
- // set loading state here because this is the first load checkout session when we already have checkout session id stored
15589
- stripeStore.isFetchingSession = true;
15590
- await cartStoreReCalculateTotal({
15591
- adjustmentsAmount: adjustmentTotal,
15592
- cartId: window.Zonos.cartId,
15593
- currency: currency,
15594
- dutiesTaxesFeesEstimate: 0,
15595
- itemsAmount: total,
15596
- // attempt to init session on failure to update checkout session
15597
- shouldInitSessionOnFailure: true,
15598
- });
15599
- stripeStore.isFetchingSession = false;
15600
- };
15601
- const cartStoreResetSelectedShippingOption = () => {
15602
- cartStore.selectedShippingOption = null;
15603
- cartStore.isSelectedShippingAboveDeminimis = false;
15604
- cartStore.isSelectedShippingGuarantee = false;
15605
- cartStore.selectedShippingOptionTransitTime = '';
15606
- cartStore.dutiesTaxesFees = 0;
15607
- cartStore.dutiesTaxesFeesEstimate = 0;
15608
- cartStore.shipping = 0;
15609
- // reset total to subtotal
15610
- cartStore.total = cartStore.subtotal;
15611
- };
15612
- const cartStorePreviousStep = () => {
15613
- if (cartStore.step === 'shipping') {
15614
- cartStore.step = 'customer-info';
15615
- // set shipping step to done
15616
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
15617
- }
15618
- else if (cartStore.step === 'payment') {
15619
- cartStore.step = 'shipping';
15620
- // set shipping step to done
15621
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: false }) });
15622
- }
15623
- else if (cartStore.step === 'finish') {
15624
- cartStore.step = 'payment';
15625
- // set shipping step to done
15626
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { payment: Object.assign(Object.assign({}, cartStore.tabItems.payment), { isDone: false }) });
15627
- }
15628
- };
15629
- const cartStoreNextStep = () => {
15630
- if (cartStore.step === 'customer-info') {
15631
- cartStore.step = 'shipping';
15632
- // set customer-info step to done
15633
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { 'customer-info': Object.assign(Object.assign({}, cartStore.tabItems['customer-info']), { isDone: true }) });
15634
- }
15635
- else if (cartStore.step === 'shipping') {
15636
- cartStore.step = 'payment';
15637
- // set shipping step to done
15638
- cartStore.tabItems = Object.assign(Object.assign({}, cartStore.tabItems), { shipping: Object.assign(Object.assign({}, cartStore.tabItems.shipping), { isDone: true }) });
15639
- }
15640
- else if (cartStore.step === 'payment') {
15641
- cartStore.step = 'finish';
15642
- }
15643
- };
15644
- const cartStoreResetTabItems = () => {
15645
- cartStore.step = 'customer-info';
15646
- 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 }) });
15647
- cartStoreResetSelectedShippingOption();
15648
- };
15649
-
15650
- exports.cartStore = cartStore;
15651
- exports.cartStoreClearCheckoutInterval = cartStoreClearCheckoutInterval;
15652
- exports.cartStoreGetShippingTransitInfo = cartStoreGetShippingTransitInfo;
15653
- exports.cartStoreHasOneEligibleItem = cartStoreHasOneEligibleItem;
15654
- exports.cartStoreNextStep = cartStoreNextStep;
15655
- exports.cartStoreReset = cartStoreReset;
15656
- exports.cartStoreResetTabItems = cartStoreResetTabItems;
15657
- exports.cartStoreSetCheckoutSession = cartStoreSetCheckoutSession;
15658
- exports.cartStoreStartCheckoutInterval = cartStoreStartCheckoutInterval;
15659
- exports.cartStoreUpdateItems = cartStoreUpdateItems;
15660
- exports.cartStoreUpdateSelectedShippingOption = cartStoreUpdateSelectedShippingOption;
15661
- exports.cartStoreUpdateToErrorState = cartStoreUpdateToErrorState;
13828
+ exports.VARIANT_TEST_KEY_EXPIRATION = VARIANT_TEST_KEY_EXPIRATION;
15662
13829
  exports.currencyConvert = currencyConvert;
15663
13830
  exports.currencyConvertAndFormat = currencyConvertAndFormat;
15664
13831
  exports.currencyDisplay = currencyDisplay;
15665
13832
  exports.currencyFormat = currencyFormat;
15666
- exports.getCheckoutSessionBody = getCheckoutSessionBody;
13833
+ exports.filterValidTests = filterValidTests;
15667
13834
  exports.getFallbackDefaultCountryCode = getFallbackDefaultCountryCode;
15668
13835
  exports.getZCountryUrlParam = getZCountryUrlParam;
15669
13836
  exports.initLocalizationStore = initLocalizationStore;
15670
- exports.initStripeElements = initStripeElements;
15671
13837
  exports.isValidSelector = isValidSelector;
15672
13838
  exports.localizationStore = localizationStore;
15673
- exports.localizationStoreOnUpdate = localizationStoreOnUpdate;
13839
+ exports.localizationStoreOnChange = localizationStoreOnChange;
15674
13840
  exports.localizationStoreUpdateSelectedCountryCode = localizationStoreUpdateSelectedCountryCode;
15675
13841
  exports.localizationStoreUpdateSelectedLocale = localizationStoreUpdateSelectedLocale;
15676
13842
  exports.setZCountryUrlParam = setZCountryUrlParam;
15677
- exports.sortServiceLevelOptionsByAmount = sortServiceLevelOptionsByAmount;
15678
- exports.stripeStore = stripeStore;
15679
- exports.stripeStoreApplyPromoCode = stripeStoreApplyPromoCode;
15680
- exports.stripeStoreCleanupDomesticShippingSession = stripeStoreCleanupDomesticShippingSession;
15681
- exports.stripeStoreConfirmPayment = stripeStoreConfirmPayment;
15682
- exports.stripeStoreGetDomesticShippingSession = stripeStoreGetDomesticShippingSession;
15683
- exports.stripeStoreGetPaymentIntent = stripeStoreGetPaymentIntent;
15684
- exports.stripeStoreHandleInventoryCheck = stripeStoreHandleInventoryCheck;
15685
- exports.stripeStoreHandleInventoryRefund = stripeStoreHandleInventoryRefund;
15686
- exports.stripeStoreInitCheckoutSession = stripeStoreInitCheckoutSession;
15687
- exports.stripeStoreMessageBasedOnStatus = stripeStoreMessageBasedOnStatus;
15688
- exports.stripeStorePrefetchLandedCost = stripeStorePrefetchLandedCost;
15689
- exports.stripeStoreRemovePromoCode = stripeStoreRemovePromoCode;
15690
- exports.stripeStoreReset = stripeStoreReset;
15691
- exports.stripeStoreResetPromoCode = stripeStoreResetPromoCode;
15692
- exports.stripeStoreRetrievePayment = stripeStoreRetrievePayment;
15693
- exports.stripeStoreSaveDomesticShippingSession = stripeStoreSaveDomesticShippingSession;
15694
- exports.stripeStoreTranslateAddressToLatin = stripeStoreTranslateAddressToLatin;
15695
- exports.stripeStoreUpdateCheckoutSessionBaseCurrency = stripeStoreUpdateCheckoutSessionBaseCurrency;
15696
- exports.trackConversionEvent = trackConversionEvent;
13843
+ exports.storageStore = storageStore;
13844
+ exports.storageStoreOnChange = storageStoreOnChange;
13845
+ exports.storageStoreSetEnabledVariantTestKeys = storageStoreSetEnabledVariantTestKeys;
15697
13846
  exports.translate = translate;
15698
- exports.validateCheckoutSession = validateCheckoutSession;