@salla.sa/twilight-components 2.14.392 → 2.14.394

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 (290) hide show
  1. package/dist/cjs/{filepond-D-ur1GA-.js → filepond-C_gLbAbF.js} +10 -5
  2. package/dist/cjs/{filepond-plugin-file-poster-DigEeKId.js → filepond-plugin-file-poster-DXWo2FUU.js} +10 -6
  3. package/dist/cjs/{filepond-plugin-file-validate-size-R9el3Yro.js → filepond-plugin-file-validate-size-fBXMP7ez.js} +1 -1
  4. package/dist/cjs/filepond-plugin-file-validate-type-DEo7juC7.js +271 -0
  5. package/dist/cjs/{filepond-plugin-image-edit-bhI8kqN_.js → filepond-plugin-image-edit-4j4e1VEp.js} +1 -1
  6. package/dist/cjs/{filepond-plugin-image-exif-orientation-COXZUVRV.js → filepond-plugin-image-exif-orientation-DWqiXxv1.js} +1 -1
  7. package/dist/cjs/{filepond-plugin-image-preview-COP8QJBf.js → filepond-plugin-image-preview-emT_teia.js} +1 -1
  8. package/dist/cjs/{index-CGnPURjZ.js → index-B03mYCWz.js} +1206 -817
  9. package/dist/cjs/{index-BILBEE9f.js → index-Y-2uyQDK.js} +1 -1
  10. package/dist/cjs/loader.cjs.js +1 -1
  11. package/dist/cjs/salla-accordion-body_2.cjs.entry.js +1 -1
  12. package/dist/cjs/salla-accordion_6.cjs.entry.js +1 -1
  13. package/dist/cjs/salla-add-product-button_4.cjs.entry.js +1 -1
  14. package/dist/cjs/salla-advertisement.cjs.entry.js +1 -1
  15. package/dist/cjs/salla-alert_2.cjs.entry.js +1 -1
  16. package/dist/cjs/salla-app-install-alert.cjs.entry.js +1 -1
  17. package/dist/cjs/salla-apps-icons.cjs.entry.js +1 -1
  18. package/dist/cjs/salla-booking-field_7.cjs.entry.js +11 -11
  19. package/dist/cjs/salla-bullet-delivery.cjs.entry.js +1 -1
  20. package/dist/cjs/salla-cart-coupons.cjs.entry.js +1 -1
  21. package/dist/cjs/salla-cart-item-offers_2.cjs.entry.js +1 -1
  22. package/dist/cjs/salla-comment-form_8.cjs.entry.js +1 -1
  23. package/dist/cjs/salla-conditional-offer.cjs.entry.js +1 -1
  24. package/dist/cjs/salla-contacts.cjs.entry.js +1 -1
  25. package/dist/cjs/salla-cookies-bar.cjs.entry.js +1 -1
  26. package/dist/cjs/salla-count-down.cjs.entry.js +33 -9
  27. package/dist/cjs/salla-custom-fields.cjs.entry.js +1 -1
  28. package/dist/cjs/salla-delivery-promise.cjs.entry.js +1 -1
  29. package/dist/cjs/salla-filters-widget.cjs.entry.js +1 -1
  30. package/dist/cjs/salla-filters.cjs.entry.js +1 -1
  31. package/dist/cjs/salla-fulfillment-methods.cjs.entry.js +1 -1
  32. package/dist/cjs/salla-gifting.cjs.entry.js +1 -1
  33. package/dist/cjs/salla-hook.cjs.entry.js +1 -1
  34. package/dist/cjs/salla-infinite-scroll.cjs.entry.js +1 -1
  35. package/dist/cjs/salla-installment.cjs.entry.js +1 -1
  36. package/dist/cjs/salla-list-tile.cjs.entry.js +1 -1
  37. package/dist/cjs/salla-localization-modal.cjs.entry.js +1 -1
  38. package/dist/cjs/salla-login-modal.cjs.entry.js +1 -1
  39. package/dist/cjs/salla-loyalty-prize-item.cjs.entry.js +1 -1
  40. package/dist/cjs/salla-loyalty-program.cjs.entry.js +1 -1
  41. package/dist/cjs/salla-loyalty.cjs.entry.js +1 -1
  42. package/dist/cjs/salla-maintenance-alert.cjs.entry.js +1 -1
  43. package/dist/cjs/salla-map.cjs.entry.js +1 -1
  44. package/dist/cjs/salla-menu.cjs.entry.js +1 -1
  45. package/dist/cjs/salla-metadata.cjs.entry.js +1 -1
  46. package/dist/cjs/salla-multiple-bundle-product-cart_2.cjs.entry.js +1 -1
  47. package/dist/cjs/salla-multiple-bundle-product-options-modal_2.cjs.entry.js +1 -1
  48. package/dist/cjs/salla-multiple-bundle-product.cjs.entry.js +1 -1
  49. package/dist/cjs/salla-notification-item.cjs.entry.js +1 -1
  50. package/dist/cjs/salla-notifications.cjs.entry.js +48 -3
  51. package/dist/cjs/salla-offer-modal.cjs.entry.js +1 -1
  52. package/dist/cjs/salla-offer.cjs.entry.js +1 -1
  53. package/dist/cjs/salla-order-details-multiple-bundle-product.cjs.entry.js +1 -1
  54. package/dist/cjs/salla-order-details-options.cjs.entry.js +1 -1
  55. package/dist/cjs/salla-order-details.cjs.entry.js +1 -1
  56. package/dist/cjs/salla-order-edit-item.cjs.entry.js +1 -1
  57. package/dist/cjs/salla-order-edit.cjs.entry.js +1 -1
  58. package/dist/cjs/salla-order-summary.cjs.entry.js +1 -1
  59. package/dist/cjs/salla-order-totals-card.cjs.entry.js +1 -1
  60. package/dist/cjs/salla-orders.cjs.entry.js +1 -1
  61. package/dist/cjs/salla-payments.cjs.entry.js +1 -1
  62. package/dist/cjs/salla-placeholder.cjs.entry.js +1 -1
  63. package/dist/cjs/salla-price-range.cjs.entry.js +1 -1
  64. package/dist/cjs/salla-product-card.cjs.entry.js +1 -1
  65. package/dist/cjs/salla-product-size-guide.cjs.entry.js +1 -1
  66. package/dist/cjs/salla-products-list.cjs.entry.js +1 -1
  67. package/dist/cjs/salla-products-slider.cjs.entry.js +1 -1
  68. package/dist/cjs/salla-progress-bar.cjs.entry.js +1 -1
  69. package/dist/cjs/salla-quick-order.cjs.entry.js +1 -1
  70. package/dist/cjs/salla-rating-modal.cjs.entry.js +1 -1
  71. package/dist/cjs/salla-scopes.cjs.entry.js +1 -1
  72. package/dist/cjs/salla-search.cjs.entry.js +1 -1
  73. package/dist/cjs/salla-skeleton.cjs.entry.js +1 -1
  74. package/dist/cjs/salla-slider.cjs.entry.js +19 -13
  75. package/dist/cjs/salla-social-share.cjs.entry.js +1 -1
  76. package/dist/cjs/salla-social.cjs.entry.js +1 -1
  77. package/dist/cjs/salla-tab-content_3.cjs.entry.js +1 -1
  78. package/dist/cjs/salla-tiered-offer.cjs.entry.js +1 -1
  79. package/dist/cjs/salla-tooltip.cjs.entry.js +1 -1
  80. package/dist/cjs/salla-trust-badges.cjs.entry.js +1 -1
  81. package/dist/cjs/salla-user-menu.cjs.entry.js +1 -1
  82. package/dist/cjs/salla-user-profile.cjs.entry.js +1 -1
  83. package/dist/cjs/salla-user-settings.cjs.entry.js +1 -1
  84. package/dist/cjs/salla-verify.cjs.entry.js +1 -1
  85. package/dist/cjs/salla-wallet.cjs.entry.js +1 -1
  86. package/dist/cjs/twilight.cjs.js +1 -1
  87. package/dist/cjs/{vanilla-picker-DI3TImGd.js → vanilla-picker-CKZvBtHS.js} +1 -1
  88. package/dist/collection/components/salla-count-down/salla-count-down.js +32 -8
  89. package/dist/collection/components/salla-file-upload/salla-file-upload.css +1 -1
  90. package/dist/collection/components/salla-file-upload/salla-file-upload.js +1 -1
  91. package/dist/collection/components/salla-notifications/salla-notifications.js +47 -2
  92. package/dist/collection/components/salla-slider/salla-slider.css +9 -2
  93. package/dist/components/axios.js +1123 -791
  94. package/dist/components/filepond-plugin-file-poster.js +9 -5
  95. package/dist/components/filepond-plugin-file-validate-type.js +215 -231
  96. package/dist/components/filepond.js +9 -4
  97. package/dist/components/index.js +83 -26
  98. package/dist/components/salla-count-down2.js +32 -8
  99. package/dist/components/salla-file-upload2.js +1 -1
  100. package/dist/components/salla-notifications.js +47 -2
  101. package/dist/components/salla-slider2.js +18 -12
  102. package/dist/esm/{filepond-kTbl0kuh.js → filepond-Be7JObSq.js} +10 -5
  103. package/dist/esm/{filepond-plugin-file-poster-CyywnjKv.js → filepond-plugin-file-poster-DF0NWKCQ.js} +10 -6
  104. package/dist/esm/{filepond-plugin-file-validate-size-DgteZhje.js → filepond-plugin-file-validate-size-DJFlJHtE.js} +1 -1
  105. package/dist/esm/filepond-plugin-file-validate-type-DykpLW1Z.js +269 -0
  106. package/dist/esm/{filepond-plugin-image-edit-pZ_mETE7.js → filepond-plugin-image-edit-CyIHxrnW.js} +1 -1
  107. package/dist/esm/{filepond-plugin-image-exif-orientation-CjKYl7HL.js → filepond-plugin-image-exif-orientation-DbCOAhSu.js} +1 -1
  108. package/dist/esm/{filepond-plugin-image-preview-BzJTl_2A.js → filepond-plugin-image-preview-CGRGZcft.js} +1 -1
  109. package/dist/esm/{index-C23tPnnH.js → index-Cz6cYzxG.js} +1206 -817
  110. package/dist/esm/{index-3Kis_Ivk.js → index-_kPnZdm0.js} +1 -1
  111. package/dist/esm/loader.js +2 -2
  112. package/dist/esm/salla-accordion-body_2.entry.js +1 -1
  113. package/dist/esm/salla-accordion_6.entry.js +1 -1
  114. package/dist/esm/salla-add-product-button_4.entry.js +1 -1
  115. package/dist/esm/salla-advertisement.entry.js +1 -1
  116. package/dist/esm/salla-alert_2.entry.js +1 -1
  117. package/dist/esm/salla-app-install-alert.entry.js +1 -1
  118. package/dist/esm/salla-apps-icons.entry.js +1 -1
  119. package/dist/esm/salla-booking-field_7.entry.js +11 -11
  120. package/dist/esm/salla-bullet-delivery.entry.js +1 -1
  121. package/dist/esm/salla-cart-coupons.entry.js +1 -1
  122. package/dist/esm/salla-cart-item-offers_2.entry.js +1 -1
  123. package/dist/esm/salla-comment-form_8.entry.js +1 -1
  124. package/dist/esm/salla-conditional-offer.entry.js +1 -1
  125. package/dist/esm/salla-contacts.entry.js +1 -1
  126. package/dist/esm/salla-cookies-bar.entry.js +1 -1
  127. package/dist/esm/salla-count-down.entry.js +33 -9
  128. package/dist/esm/salla-custom-fields.entry.js +1 -1
  129. package/dist/esm/salla-delivery-promise.entry.js +1 -1
  130. package/dist/esm/salla-filters-widget.entry.js +1 -1
  131. package/dist/esm/salla-filters.entry.js +1 -1
  132. package/dist/esm/salla-fulfillment-methods.entry.js +1 -1
  133. package/dist/esm/salla-gifting.entry.js +1 -1
  134. package/dist/esm/salla-hook.entry.js +1 -1
  135. package/dist/esm/salla-infinite-scroll.entry.js +1 -1
  136. package/dist/esm/salla-installment.entry.js +1 -1
  137. package/dist/esm/salla-list-tile.entry.js +1 -1
  138. package/dist/esm/salla-localization-modal.entry.js +1 -1
  139. package/dist/esm/salla-login-modal.entry.js +1 -1
  140. package/dist/esm/salla-loyalty-prize-item.entry.js +1 -1
  141. package/dist/esm/salla-loyalty-program.entry.js +1 -1
  142. package/dist/esm/salla-loyalty.entry.js +1 -1
  143. package/dist/esm/salla-maintenance-alert.entry.js +1 -1
  144. package/dist/esm/salla-map.entry.js +1 -1
  145. package/dist/esm/salla-menu.entry.js +1 -1
  146. package/dist/esm/salla-metadata.entry.js +1 -1
  147. package/dist/esm/salla-multiple-bundle-product-cart_2.entry.js +1 -1
  148. package/dist/esm/salla-multiple-bundle-product-options-modal_2.entry.js +1 -1
  149. package/dist/esm/salla-multiple-bundle-product.entry.js +1 -1
  150. package/dist/esm/salla-notification-item.entry.js +1 -1
  151. package/dist/esm/salla-notifications.entry.js +48 -3
  152. package/dist/esm/salla-offer-modal.entry.js +1 -1
  153. package/dist/esm/salla-offer.entry.js +1 -1
  154. package/dist/esm/salla-order-details-multiple-bundle-product.entry.js +1 -1
  155. package/dist/esm/salla-order-details-options.entry.js +1 -1
  156. package/dist/esm/salla-order-details.entry.js +1 -1
  157. package/dist/esm/salla-order-edit-item.entry.js +1 -1
  158. package/dist/esm/salla-order-edit.entry.js +1 -1
  159. package/dist/esm/salla-order-summary.entry.js +1 -1
  160. package/dist/esm/salla-order-totals-card.entry.js +1 -1
  161. package/dist/esm/salla-orders.entry.js +1 -1
  162. package/dist/esm/salla-payments.entry.js +1 -1
  163. package/dist/esm/salla-placeholder.entry.js +1 -1
  164. package/dist/esm/salla-price-range.entry.js +1 -1
  165. package/dist/esm/salla-product-card.entry.js +1 -1
  166. package/dist/esm/salla-product-size-guide.entry.js +1 -1
  167. package/dist/esm/salla-products-list.entry.js +1 -1
  168. package/dist/esm/salla-products-slider.entry.js +1 -1
  169. package/dist/esm/salla-progress-bar.entry.js +1 -1
  170. package/dist/esm/salla-quick-order.entry.js +1 -1
  171. package/dist/esm/salla-rating-modal.entry.js +1 -1
  172. package/dist/esm/salla-scopes.entry.js +1 -1
  173. package/dist/esm/salla-search.entry.js +1 -1
  174. package/dist/esm/salla-skeleton.entry.js +1 -1
  175. package/dist/esm/salla-slider.entry.js +19 -13
  176. package/dist/esm/salla-social-share.entry.js +1 -1
  177. package/dist/esm/salla-social.entry.js +1 -1
  178. package/dist/esm/salla-tab-content_3.entry.js +1 -1
  179. package/dist/esm/salla-tiered-offer.entry.js +1 -1
  180. package/dist/esm/salla-tooltip.entry.js +1 -1
  181. package/dist/esm/salla-trust-badges.entry.js +1 -1
  182. package/dist/esm/salla-user-menu.entry.js +1 -1
  183. package/dist/esm/salla-user-profile.entry.js +1 -1
  184. package/dist/esm/salla-user-settings.entry.js +1 -1
  185. package/dist/esm/salla-verify.entry.js +1 -1
  186. package/dist/esm/salla-wallet.entry.js +1 -1
  187. package/dist/esm/twilight.js +2 -2
  188. package/dist/esm/{vanilla-picker-CEy5x8Cf.js → vanilla-picker-C_YV5LtA.js} +1 -1
  189. package/dist/twilight/p-0200cddd.entry.js +4 -0
  190. package/dist/twilight/p-04dc0b71.entry.js +4 -0
  191. package/dist/twilight/{p-f251e744.entry.js → p-0bac200e.entry.js} +1 -1
  192. package/dist/twilight/{p-1899f283.entry.js → p-0ef99df1.entry.js} +1 -1
  193. package/dist/twilight/{p-82e3c734.entry.js → p-1087f0dd.entry.js} +1 -1
  194. package/dist/twilight/{p-2a1871c2.entry.js → p-17dd8b68.entry.js} +1 -1
  195. package/dist/twilight/{p-5d37cc33.entry.js → p-25a9bf1b.entry.js} +1 -1
  196. package/dist/twilight/{p-3745a7d0.entry.js → p-2602927d.entry.js} +1 -1
  197. package/dist/twilight/{p-54f65187.entry.js → p-268695ff.entry.js} +1 -1
  198. package/dist/twilight/{p-b6ded196.entry.js → p-34920aac.entry.js} +1 -1
  199. package/dist/twilight/p-3656b48d.entry.js +4 -0
  200. package/dist/twilight/{p-b4f07395.entry.js → p-3857beb4.entry.js} +1 -1
  201. package/dist/twilight/{p-f1f74b41.entry.js → p-39c601e3.entry.js} +1 -1
  202. package/dist/twilight/{p-c68f3054.entry.js → p-3c810881.entry.js} +1 -1
  203. package/dist/twilight/{p-7b717899.entry.js → p-3cf5c61f.entry.js} +1 -1
  204. package/dist/twilight/{p-9f23dd30.entry.js → p-413a7236.entry.js} +1 -1
  205. package/dist/twilight/{p-1dbaefb8.entry.js → p-42778349.entry.js} +1 -1
  206. package/dist/twilight/{p-bdcf3926.entry.js → p-45e4f6f4.entry.js} +1 -1
  207. package/dist/twilight/{p-3a5aaa20.entry.js → p-4680956b.entry.js} +1 -1
  208. package/dist/twilight/{p-4e00f827.entry.js → p-468b999f.entry.js} +1 -1
  209. package/dist/twilight/{p-e89812d8.entry.js → p-46d1823f.entry.js} +1 -1
  210. package/dist/twilight/{p-9deae4f4.entry.js → p-49db497f.entry.js} +1 -1
  211. package/dist/twilight/{p-ff6f769c.entry.js → p-4b033276.entry.js} +1 -1
  212. package/dist/twilight/{p-866b297b.entry.js → p-4f7bc9c3.entry.js} +1 -1
  213. package/dist/twilight/{p-81f6638f.entry.js → p-543ee624.entry.js} +1 -1
  214. package/dist/twilight/{p-81f648a2.entry.js → p-5957f774.entry.js} +1 -1
  215. package/dist/twilight/{p-97df32eb.entry.js → p-5a4f0b99.entry.js} +1 -1
  216. package/dist/twilight/{p-5ef1b170.entry.js → p-5a8c0fd2.entry.js} +1 -1
  217. package/dist/twilight/{p-05663bb1.entry.js → p-5ab7a295.entry.js} +1 -1
  218. package/dist/twilight/{p-ba4b672c.entry.js → p-5e496aaa.entry.js} +1 -1
  219. package/dist/twilight/{p-1c215c8c.entry.js → p-5f440956.entry.js} +1 -1
  220. package/dist/twilight/{p-face0448.entry.js → p-60fafcd9.entry.js} +1 -1
  221. package/dist/twilight/{p-2aa48902.entry.js → p-708f02db.entry.js} +1 -1
  222. package/dist/twilight/{p-8c6db6d7.entry.js → p-7829ea8a.entry.js} +1 -1
  223. package/dist/twilight/{p-c8aa5377.entry.js → p-7d3e592a.entry.js} +1 -1
  224. package/dist/twilight/{p-81f76d49.entry.js → p-81876026.entry.js} +1 -1
  225. package/dist/twilight/{p-194d87c6.entry.js → p-8306ef5e.entry.js} +1 -1
  226. package/dist/twilight/{p-f8b6967f.entry.js → p-8403cd93.entry.js} +1 -1
  227. package/dist/twilight/{p-ce9fee6d.entry.js → p-8474c4f6.entry.js} +1 -1
  228. package/dist/twilight/{p-549f59ed.entry.js → p-8552160a.entry.js} +1 -1
  229. package/dist/twilight/p-8c9b0e2a.entry.js +4 -0
  230. package/dist/twilight/{p-27f34c85.entry.js → p-8f2dfc57.entry.js} +1 -1
  231. package/dist/twilight/{p-1b1f9f71.entry.js → p-94b1a2ae.entry.js} +1 -1
  232. package/dist/twilight/{p-85ceef78.entry.js → p-95dad1af.entry.js} +1 -1
  233. package/dist/twilight/{p-d81ad2c3.entry.js → p-964b7db9.entry.js} +1 -1
  234. package/dist/twilight/{p-a76b3dba.entry.js → p-99735748.entry.js} +1 -1
  235. package/dist/twilight/{p-BgG5eq1x.js → p-BZKDQg1s.js} +1 -1
  236. package/dist/twilight/{p-IoI86ovS.js → p-B_sN7OnY.js} +1 -1
  237. package/dist/twilight/{p-BHjlzmYy.js → p-Bpi0aG1F.js} +1 -1
  238. package/dist/twilight/p-CP8rFQ5n.js +9 -0
  239. package/dist/twilight/p-CfmIbM8B.js +9 -0
  240. package/dist/twilight/{p-BqCmPfAo.js → p-CpO1SrBd.js} +2 -2
  241. package/dist/twilight/p-Cz6cYzxG.js +5 -0
  242. package/dist/twilight/p-Do4hSOGo.js +9 -0
  243. package/dist/twilight/p-JJmlh-ji.js +9 -0
  244. package/dist/twilight/{p-ff9b33bb.entry.js → p-a4aedcfe.entry.js} +1 -1
  245. package/dist/twilight/{p-651fe6e4.entry.js → p-b0d01f9f.entry.js} +1 -1
  246. package/dist/twilight/{p-eb5a8329.entry.js → p-b8404cfb.entry.js} +1 -1
  247. package/dist/twilight/{p-407828e4.entry.js → p-b8e3e180.entry.js} +1 -1
  248. package/dist/twilight/{p-d1dd1db6.entry.js → p-bd687cd0.entry.js} +1 -1
  249. package/dist/twilight/{p-67fe5680.entry.js → p-c0037fac.entry.js} +1 -1
  250. package/dist/twilight/{p-c3d0c062.entry.js → p-c121f8e4.entry.js} +1 -1
  251. package/dist/twilight/{p-d022b6ec.entry.js → p-c29907df.entry.js} +1 -1
  252. package/dist/twilight/{p-4e9e3ab1.entry.js → p-c39675ef.entry.js} +1 -1
  253. package/dist/twilight/{p-344c1910.entry.js → p-cb7a985e.entry.js} +1 -1
  254. package/dist/twilight/{p-346b55d6.entry.js → p-cbe620c4.entry.js} +1 -1
  255. package/dist/twilight/{p-b55da21d.entry.js → p-d2fd79b4.entry.js} +1 -1
  256. package/dist/twilight/{p-98eb495e.entry.js → p-d6cf0ffd.entry.js} +1 -1
  257. package/dist/twilight/{p-f201122a.entry.js → p-d8f60f2f.entry.js} +1 -1
  258. package/dist/twilight/{p-0652987b.entry.js → p-d99610f9.entry.js} +1 -1
  259. package/dist/twilight/{p-11767786.entry.js → p-dc897bdd.entry.js} +1 -1
  260. package/dist/twilight/{p-50621375.entry.js → p-dca46236.entry.js} +1 -1
  261. package/dist/twilight/{p-1ca75c99.entry.js → p-e48853c9.entry.js} +1 -1
  262. package/dist/twilight/{p-a50f7f70.entry.js → p-e4fdb206.entry.js} +1 -1
  263. package/dist/twilight/{p-1c8394db.entry.js → p-ed913ae7.entry.js} +1 -1
  264. package/dist/twilight/{p-3962c34c.entry.js → p-f067fcd6.entry.js} +1 -1
  265. package/dist/twilight/{p-a00e249b.entry.js → p-f2cd6975.entry.js} +1 -1
  266. package/dist/twilight/{p-713590e2.entry.js → p-f2ffbfbb.entry.js} +1 -1
  267. package/dist/twilight/p-f3166e60.entry.js +4 -0
  268. package/dist/twilight/{p-827edf95.entry.js → p-f8fcc8f4.entry.js} +1 -1
  269. package/dist/twilight/{p-775b42ec.entry.js → p-f9e52fd9.entry.js} +1 -1
  270. package/dist/twilight/{p-753464fd.entry.js → p-fcddbfc3.entry.js} +1 -1
  271. package/dist/twilight/{p-f2ee9ceb.entry.js → p-fe7ac9bb.entry.js} +1 -1
  272. package/dist/twilight/{p-744d6394.entry.js → p-ff14dca3.entry.js} +1 -1
  273. package/dist/twilight/{p-CU-HtXWh.js → p-mlFGjxcj.js} +1 -1
  274. package/dist/twilight/twilight.esm.js +1 -1
  275. package/dist/types/components/salla-count-down/salla-count-down.d.ts +6 -0
  276. package/dist/types/components/salla-notifications/interfaces.d.ts +20 -0
  277. package/dist/types/components/salla-notifications/salla-notifications.d.ts +17 -0
  278. package/package.json +5 -5
  279. package/dist/cjs/filepond-plugin-file-validate-type-Dfy66STE.js +0 -287
  280. package/dist/esm/filepond-plugin-file-validate-type-BYs_scJr.js +0 -285
  281. package/dist/twilight/p-14529fd6.entry.js +0 -4
  282. package/dist/twilight/p-726513f8.entry.js +0 -4
  283. package/dist/twilight/p-AfW2b46_.js +0 -9
  284. package/dist/twilight/p-C23tPnnH.js +0 -5
  285. package/dist/twilight/p-CrYUKEsF.js +0 -9
  286. package/dist/twilight/p-HWjjIZ9_.js +0 -9
  287. package/dist/twilight/p-Ig1Tafsp.js +0 -9
  288. package/dist/twilight/p-c9001d7f.entry.js +0 -4
  289. package/dist/twilight/p-cf9573fd.entry.js +0 -4
  290. package/dist/twilight/p-e6124fab.entry.js +0 -4
@@ -4001,7 +4001,7 @@ var a$4 = /*#__PURE__*/_mergeNamespaces({
4001
4001
  default: memoryStorage
4002
4002
  }, [memoryStorageExports]);
4003
4003
 
4004
- function s$1(t,e){ void 0===e&&(e=false),t+="";for(var r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],o=["0","1","2","3","4","5","6","7","8","9"],i=(e=e||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:o,a=e?o:n,s=0;s<i.length;s++)r=new RegExp(i[s],"g"),t=t.replace(r,a[s]);return t.replace(e?"٫":".",e?".":"٫")}function l$2(t){var e=("".concat(t).match(/\./g)||[]).length;return e&&1!==e?l$2(t.replace(/\.(.+)\./g,".$1")):t}function c$3(t){return "".concat(t).startsWith("https://")||"".concat(t).startsWith("http://")}function u$3(t){if(c$3(t))return t;var e=Salla.config.get("store.url");return e||(e=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",e)),e.rtrim("/")+"/"+(null==t?void 0:t.ltrim("/"))}function p$1(t,e,r){if(r=r||window.location.href,!e||!t)return r;var n=new RegExp("([?&])"+t+"=[^&]+[&]?","g");return (r=r.replace(n,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+t+"="+encodeURIComponent(e)).replace(/&$|\?$/,"")}function d$3(t){return window.location.origin+"/"+(null==t?void 0:t.ltrim("/"))}function f$2(t){return c$3(t)?t:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==t?void 0:t.ltrim("/")):d$3("themes/"+Salla.config.get("theme.name")+"/"+(null==t?void 0:t.ltrim("/")))}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(t){return t.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this.toString():"#"+this.toString()},String.prototype.replaceArray=function(t,e){for(var r,n=this,o=0;o<t.length;o++)r=new RegExp(t[o],"g"),n=n.replace(r,e[o]);return n},String.prototype.rtrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("["+t+"]*$"),"")},String.prototype.ltrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("^["+t+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var h$3=Object.freeze({__proto__:null,addParamToUrl:p$1,api:function(t){var e;return (null===(e=Salla.config.get("store.api",u$3("")))||void 0===e?void 0:e.rtrim("/"))+"/"+(null==t?void 0:t.ltrim("/"))},asset:f$2,base:function(t){return c$3(t)?t:"https://"+new URL(u$3("/")).hostname+"/"+(null==t?void 0:t.ltrim("/"))},baseUrl:d$3,cdn:function(t,e,r){var n="https://cdn.salla.network/";return (e||r)&&(e=e?",width=".concat(e):"",r=r?",height=".concat(r):"",n+="cdn-cgi/image/fit=scale-down".concat(e).concat(r,",onerror=redirect,format=auto/")),n+(null==t?void 0:t.ltrim("/"))},create:function(t,e){return "custom"===t?e:u$3("offers"===t?t:"redirect/".concat(t,"/").concat(e))},domain:function(t){return c$3(t)?t:"".concat(Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/"),"/").concat(null==t?void 0:t.ltrim("/"))},get:u$3,is_full_url:c$3,is_page:function(t){return t&&Salla.config.get("page.slug")===t},is_placeholder:function(t){return f$2(salla.config.get("theme.settings.placeholder"))===f$2(t)}}),g$3=function(t,e){return g$3=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);},g$3(t,e)};var v$2=function(){return v$2=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},v$2.apply(this,arguments)};function y$3(t,e,r){if(2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}function m$3(t){return t instanceof FormData}function w$2(t){return t instanceof File}function S$2(t){return t instanceof Blob}"function"==typeof SuppressedError&&SuppressedError;var b$5=function(){function t(t){this.data=t,this.proxy=this.createProxy();}return t.prototype.createProxy=function(){var t=this;return new Proxy(this,{get:function(e,r){return r in e?e[r]:"string"==typeof r?t.get(r):void 0},set:function(e,r,n){return "string"==typeof r&&(t.set(r,n),true)},has:function(e,r){return "string"==typeof r?t.has(r):r in e},deleteProperty:function(e,r){return "string"==typeof r&&t.delete(r)}})},t.prototype.get=function(t){return m$3(this.data)?this.data.get(t):this.data[t]},t.prototype.getAll=function(t){if(m$3(this.data))return this.data.getAll(t);var e=this.data[t];return void 0===e?[]:[e]},t.prototype.set=function(t,e){var r=this;m$3(this.data)?(this.data.delete(t),null!=e&&(Array.isArray(e)?e.forEach((function(e){w$2(e)||S$2(e)?r.data.append(t,e):r.data.append(t,String(e));})):w$2(e)||S$2(e)?this.data.append(t,e):this.data.append(t,String(e)))):this.data[t]=e;},t.prototype.append=function(t,e){if(m$3(this.data))w$2(e)||S$2(e)?this.data.append(t,e):null!=e&&this.data.append(t,String(e));else {var r=this.data[t];void 0===r?this.data[t]=e:Array.isArray(r)?r.push(e):this.data[t]=[r,e];}},t.prototype.setFile=function(t,e){this.set(t,e);},t.prototype.getFile=function(t){var e=this.get(t);return w$2(e)?e:null},t.prototype.getFiles=function(t){return this.getAll(t).filter(w$2)},t.prototype.has=function(t){return m$3(this.data)?this.data.has(t):t in this.data},t.prototype.delete=function(t){return m$3(this.data)?(this.data.delete(t),true):delete this.data[t]},t.prototype.keys=function(){if(!m$3(this.data))return Object.keys(this.data);for(var t=new Set,e=0,r=this.data.entries();e<r.length;e++){var n=r[e][0];t.add(n);}return Array.from(t)},t.prototype.values=function(){if(!m$3(this.data))return Object.values(this.data);for(var t=[],e=0,r=this.data.entries();e<r.length;e++){var n=r[e][1];t.push(n);}return t},t.prototype.entries=function(){return m$3(this.data)?Array.from(this.data.entries()):Object.entries(this.data)},t.prototype.toObject=function(){if(!m$3(this.data))return v$2({},this.data);for(var t={},e=0,r=this.data.entries();e<r.length;e++){var n=r[e],o=n[0],i=n[1];void 0!==t[o]?(Array.isArray(t[o])||(t[o]=[t[o]]),t[o].push(i)):t[o]=i;}return t},t.prototype.getFileInfo=function(t){var e=this.getFiles(t);return 0===e.length?null:e.map((function(t){return {name:t.name,size:t.size,type:t.type}}))},t.prototype.isFile=function(t){var e=this.get(t);return w$2(e)||S$2(e)},t.prototype.getRawData=function(){return this.data},t.prototype.getProxy=function(){return this.proxy},t}();function _$2(t,e,r){var n,o=t[0];return r&&0==t.length?Array.isArray(r)?(r.push(e),r):[r,e]:Array.isArray(r)?(r.push(e),r):"string"==typeof r?[r,e]:r?(r[o]=_$2(t.slice(1),e,r[o]),r):o?((n={})[o]=_$2(t.slice(1),e),n):""===o?[e]:e}function x$3(){return window.self!==window.top}var A$3,E$3,k$3,P$2,O$2={digitsOnly:function(t){return s$1(t,true).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function t(e,r){if(void 0===r&&(r=false),"string"==typeof e)return document.querySelectorAll(e).forEach((function(e){return t(e,r)}));if(e){var n=Salla.helpers.digitsOnly(e.value);return e.min&&n<parseInt(e.min)?e.value=e.min:e.max&&n>parseInt(e.max)?e.value=e.max:e.maxLength>=1&&n.toString().length>e.maxLength?e.value=n.toString().substring(0,e.maxLength):e.value=r||e.dataset.hasOwnProperty("digitsWithDecimal")?l$2(n):n.replace(/\D/g,"")}Salla.logger.warn("Can't find Object With Id: "+e);},number:s$1,money:function(t,e){ void 0===e&&(e=true);var r=Salla.config.currency(null==t?void 0:t.currency).symbol;return t=s$1(t="object"==typeof t?t.amount:t)+" "+r,e&&["SAR","ر.س"].includes(r)&&Salla.config.get("store.settings.use_sar_symbol")&&(t=t.replace(r,"<i class=sicon-sar></i>")),t},isIframe:x$3,isPreview:function(){return x$3()},setNested:function(t,e,r){for(var n=t,o=e.split("."),i=o.length,a=0;a<i-1;a++){var s=o[a];n[s]||(n[s]={}),n=n[s];}return n[o[i-1]]=r,t},getNested:function(e,r,n){var o=t$2.default?t$2.default(e,r):t$2(e,r);return void 0!==o?o:n},inputData:function(t,e,r){if(void 0===r&&(r={}),t.includes("[")){var n=t.split("]").join("").split("["),o=n[0],i=r&&"object"==typeof r?r[o]:void 0;return {name:o,value:_$2(n.slice(1),e,i)}}return {name:t,value:e}},url:h$3,addParamToUrl:p$1,debounce:function(t,e){e=e||100;var r,n=[];return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];return clearTimeout(r),r=setTimeout((function(){var e=t.apply(void 0,o);n.forEach((function(t){return t(e)})),n=[];}),e),new Promise((function(t){return n.push(t)}))}},hasApplePay:function(){var t;try{return !!(null===(t=window.ApplePaySession)||void 0===t?void 0:t.canMakePayments())}catch(t){return console.error(t),false}},createFormDataWrapper:function(t){return new b$5(t).getProxy()},isAppleDevice:function(){try{var t=navigator.userAgent||"",e=navigator.platform||"",r=/iPhone|iPad|iPod/i.test(t),n=/Mac/i.test(e);return r||n}catch(t){return console.error(t),false}},isIOSDevice:function(){try{var t=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(t)}catch(t){return console.error(t),false}},isWebView:function(){try{if(void 0===window.navigator)return false;var t=window.navigator.userAgent,e=/iP(hone|od|ad)/.test(t)&&/AppleWebKit/.test(t)&&!/Safari/.test(t),r=/\bwv\b/.test(t)||/Android/.test(t)&&/AppleWebKit/.test(t)&&!/Chrome/.test(t);return e||r}catch(t){return console.error(t),false}}},j$3=(A$3=console,E$3=[],k$3=[],P$2={log:function(t,e){if(A$3&&salla.config.isDebug()){E$3.push([e,t]),"trace"===salla.config.get("debug")&&(e="trace");var r=A$3.log,n=void 0===e?r:this.__dict__[e]||r,o=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"];k$3.forEach((function(t){o[0]+=t[0],o.push(t[1]);}));var i={event:"#CFF680",backend:"#7b68ee"}[e];i&&(o[0]+="%c"+e[0].toUpperCase()+e.substring(1),o.push("margin-left: 5px;color: ".concat(i,";font-weight:bold; border:1px solid ").concat(i,"; padding: 2px 6px; border-radius: 5px;"))),n.call.apply(n,y$3([A$3],o.concat.apply(o,t),false));}},__dict__:{trace:A$3.trace,debug:A$3.debug,info:A$3.info,warn:A$3.warn,error:A$3.error}},{event:function(){P$2.log(arguments,"event");},trace:function(){P$2.log(arguments,"trace");},debug:function(){P$2.log(arguments,"debug");},info:function(){P$2.log(arguments,"info");},warn:function(){P$2.log(arguments,"warn");},error:function(){P$2.log(arguments,"error");},log:function(){P$2.log(arguments,void 0);},backend:function(){P$2.log(arguments,"backend");},logs:function(t){[t].flat().forEach((function(t){return t&&P$2.log([t].flat(),"backend")}));},history:function(){return E$3.map((function(t){return A$3.log.apply(A$3,y$3([t[0]],t[1],false))})),E$3},addPrefix:function(t){return Array.isArray(t)?k$3.unshift(t):this.warn("addPrefix receives array only!"),this}}),T$2=function(){function t(t,e){ void 0===t&&(t={}),void 0===e&&(e={}),this.default_properties=e,this.properties_=v$2(v$2({},this.default_properties),t);}return t.prototype.merge=function(t){var e;return this.properties_=v$2(v$2({},this.properties_),t),this.properties_.store=v$2(v$2({},(null===(e=this.default_properties)||void 0===e?void 0:e.store)||{}),this.properties_.store),this},t.prototype.set=function(t,e){return t.includes(".")?(Salla.helpers.setNested(this.properties_,t,e),this):(this.properties_[t]=e,this)},t.prototype.currency=function(t){return void 0===t&&(t=void 0),t=t||this.get("user.currency_code"),this.get("currencies."+t)||Object.values(this.get("currencies"))[0]},t.prototype.get=function(t,e){return void 0===e&&(e=null),t.includes(".")?Salla.helpers.getNested(this.properties_,t,e):this.properties_.hasOwnProperty(t)?this.properties_[t]||e:e||void 0},t.prototype.all=function(){return this.properties_},t.prototype.isDebug=function(){return this.get("debug")||Salla.storage.get("debug")},t}(),L$3=function(t){function e(){var e=this;return (e=t.call(this,{wildcard:true,delimiter:"::",newListener:false,removeListener:false,maxListeners:10,verboseMemoryLeak:false,ignoreErrors:false})||this).delimiter="::","undefined"!=typeof document&&(e.body=document.querySelector("body")),e.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],e.ingoreLogEvents=["document::click","document::keyup","document::change"],e.noneFireableActions=["document.request"],e.emittedEvents=new Set,e}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t;}g$3(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);}(e,t),e.prototype.createAndDispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];this.dispatch.apply(this,y$3([t],e,false));},e.prototype.emit=function(e){for(var r,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];this.emittedEvents.add(e);var i=e.replace("::",".");if(!this.noneFireableActions.includes(i)&&Salla.call&&"function"==typeof Salla.call(i))return Salla.log("'Salla.".concat(i,"(...)' triggered using event '").concat(e,"'")),i=i.split("."),Array.isArray(n[0])&&(n=n[0]),void(r=salla[i[0]])[i[1]].apply(r,n);t.prototype.emit.apply(this,y$3([e],n,false)),this.trackEvents.apply(this,y$3([e],n,false));},e.prototype.onlyWhen=function(t,e){var r=this;return e=e||function(){},new Promise((function(n){return r.emittedEvents.has(t)?n(e()):r.once(t,(function(){return n(e())}))}))},e.prototype.emitAsync=function(e){for(var r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];this.emittedEvents.add(e);var o=t.prototype.emitAsync.apply(this,y$3([e],r,false));try{this.trackEvents.apply(this,y$3([e],r,false));}catch(t){Salla.logger.warn("error on tracking event (".concat(e,")"),r,t);}return o},e.prototype.trackEvents=function(t){for(var e,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if("undefined"!=typeof window)try{window.dataLayer=window.dataLayer||[];var o={event:t};r.map((function(t){return "object"==typeof t&&(o=v$2(v$2({},o),t))})),window.dataLayer.push(o);}catch(t){salla.logger.error(t.message);}Salla.logger&&!this.ingoreLogEvents.includes(t)&&(e=Salla.logger).event.apply(e,y$3([t],r,false)),this.dispatchMobileEvent.apply(this,y$3([t],r,false));},e.prototype.dispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return this.emit.apply(this,y$3([t],e,false))},e.prototype.dispatchEvents=function(t){if(t)if("object"!=typeof t||Array.isArray(t))Salla.log("Events object is wrong, it should be object of {event:payload}",t);else for(var e=0,r=Object.entries(t);e<r.length;e++){var n=r[e],o=n[0],i=n[1];this.dispatch(o,i);}else Salla.log("No Events To Dispatch!",t);},e.prototype.addListener=function(t,e,r){return this.on(t,e,r)},e.prototype.addEventListener=function(t,e,r){return this.on(t,e,r)},e.prototype.listen=function(t,e){return this.on(t,e)},e.prototype.registerGlobalListener=function(t,e){return this.onAny(e)},e.prototype.dispatchMobileEvent=function(t,e){var r;if(void 0===e&&(e={}),"undefined"!=typeof window){if(window.webkit)try{return void window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:t,details:e}))}catch(t){Salla.log(t,"The native context does not exist yet");}if(null===(r=window.Android)||void 0===r?void 0:r.customEventWithData)try{window.Android.customEventWithData(t,JSON.stringify({details:e}));}catch(t){Salla.log(t,"The native context does not exist yet");}else if(window.flutter_inappwebview)try{window.flutter_inappwebview.callHandler("sallaEvent",{event:t,details:e});}catch(t){Salla.log(t,"The Flutter context does not exist yet");}else;}},e}(eventemitter2Exports.EventEmitter2),W$2=storeEngineExports.createStore([n$4,o$3,i$3,a$4],[]),D$2=storeEngineExports.createStore([o$3],[]),C$3=storeEngineExports.createStore([i$3],[]),F$3=function(){function t(){var t=this;this.clearableItems=["cart","user","salla::wishlist","token"],Salla.event.on("storage::item.remove",(function(e){return t.remove(e)})),Salla.event.on("storage::item.set",(function(e,r){return t.set(e,r)})),this.store=W$2,this.session=D$2,this.cookie=C$3;}return t.prototype.set=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0],o=((r={})[n]=this.store.get(n),r);return o=Salla.helpers.setNested(o,t,e),this.store.set(n,o[n])}return this.store.set(t,e)},t.prototype.remove=function(t){return this.store.remove(t)},t.prototype.clearAll=function(t){var e=this;if(void 0===t&&(t=false),t)return this.store.clearAll();this.clearableItems.forEach((function(t){e.store.remove(t);}));},t.prototype.get=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0];return Salla.helpers.getNested(((r={})[n]=this.store.get(n),r),t)}return this.store.get(t,e)},t.prototype.prefixKey=function(t){return "".concat(t,"_").concat(Salla.config.get("store.id"))},t.prototype.setWithTTL=function(t,e,r,n){ void 0===r&&(r=10),void 0===n&&(n="store");var o=this.prefixKey(t),i=(new Date).getTime()+60*r*1e3;return this[n].set(o,{value:e,expiry:i})},t.prototype.getWithTTL=function(t,e,r){ void 0===e&&(e=null),void 0===r&&(r="store");var n=this.prefixKey(t),o=this[r].get(n);return o?(new Date).getTime()>o.expiry?(this[r].remove(n),e):o.value:e},t}(),R$3=function(){function t(){var t=this;this.keysToRemove=["__said","__ssid","theme_edit","ws_port","s-token"],this.dynamicKeysToRemove=["affiliate","cart"],Salla.event.on("cookies::remove",(function(e){return t.remove(e)})),Salla.event.on("cookies::add",(function(e,r){return t.set(e,r)}));}return t.prototype.get=function(t){var e;return null===(e=document.cookie.split("; ").find((function(e){return e.startsWith(t+"=")})))||void 0===e?void 0:e.split("=")[1]},t.prototype.set=function(t,e,r){ void 0===e&&(e=""),void 0===r&&(r=10);var n="";if(r){var o=new Date;o.setTime(o.getTime()+24*r*60*60*1e3),n="; expires="+o.toUTCString();}var i=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=").concat(e).concat(n,"; path=/; SameSite=").concat(i,"; secure"),this},t.prototype.remove=function(t){var e=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=; Max-Age=0; path=/; SameSite=").concat(e,"; secure"),this},t.prototype.clearAll=function(t){return void 0===t&&(t=false),this.clean(t)},t.prototype.clean=function(t){var e=this;return document.cookie.split(";").map((function(t){return t.split("=")[0].trim()})).filter((function(r){return t||e.keysToRemove.includes(r)||e.dynamicKeysToRemove.some((function(t){return r.startsWith(t)}))})).forEach((function(t){return e.remove(t)})),this},t.prototype.getCookieByPrefix=function(t){return document.cookie.split("; ").map((function(t){return t.split("=")[0]})).filter((function(e){return e.startsWith(t)}))},t.prototype.clearCookieByPrefix=function(t){var e=this;return this.getCookieByPrefix(t).forEach((function(t){return e.remove(t)}))},t}();"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),"undefined"!=typeof global&&(global.salla=global.salla||global.Salla||{},global.Salla=global.salla),Salla.status="base",Salla.config=new T$2,Salla.logger=j$3,Salla.event=new L$3,Salla.helpers=O$2,Salla.storage=new F$3,Salla.cookie=new R$3,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"2.14.391"};var N$3=Salla;
4004
+ function s$1(t,e){ void 0===e&&(e=false),t+="";for(var r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],o=["0","1","2","3","4","5","6","7","8","9"],i=(e=e||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:o,a=e?o:n,s=0;s<i.length;s++)r=new RegExp(i[s],"g"),t=t.replace(r,a[s]);return t.replace(e?"٫":".",e?".":"٫")}function l$2(t){var e=("".concat(t).match(/\./g)||[]).length;return e&&1!==e?l$2(t.replace(/\.(.+)\./g,".$1")):t}function c$3(t){return "".concat(t).startsWith("https://")||"".concat(t).startsWith("http://")}function u$3(t){if(c$3(t))return t;var e=Salla.config.get("store.url");return e||(e=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",e)),e.rtrim("/")+"/"+(null==t?void 0:t.ltrim("/"))}function p$1(t,e,r){if(r=r||window.location.href,!e||!t)return r;var n=new RegExp("([?&])"+t+"=[^&]+[&]?","g");return (r=r.replace(n,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+t+"="+encodeURIComponent(e)).replace(/&$|\?$/,"")}function d$3(t){return window.location.origin+"/"+(null==t?void 0:t.ltrim("/"))}function f$2(t){return c$3(t)?t:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==t?void 0:t.ltrim("/")):d$3("themes/"+Salla.config.get("theme.name")+"/"+(null==t?void 0:t.ltrim("/")))}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,function(t){return t.toUpperCase().replace(/[^a-zA-Z\d]/g,"")})},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this.toString():"#"+this.toString()},String.prototype.replaceArray=function(t,e){for(var r,n=this,o=0;o<t.length;o++)r=new RegExp(t[o],"g"),n=n.replace(r,e[o]);return n},String.prototype.rtrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("["+t+"]*$"),"")},String.prototype.ltrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("^["+t+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var h$3=Object.freeze({__proto__:null,addParamToUrl:p$1,api:function(t){var e;return (null===(e=Salla.config.get("store.api",u$3("")))||void 0===e?void 0:e.rtrim("/"))+"/"+(null==t?void 0:t.ltrim("/"))},asset:f$2,base:function(t){return c$3(t)?t:"https://"+new URL(u$3("/")).hostname+"/"+(null==t?void 0:t.ltrim("/"))},baseUrl:d$3,cdn:function(t,e,r){var n="https://cdn.salla.network/";return (e||r)&&(e=e?",width=".concat(e):"",r=r?",height=".concat(r):"",n+="cdn-cgi/image/fit=scale-down".concat(e).concat(r,",onerror=redirect,format=auto/")),n+(null==t?void 0:t.ltrim("/"))},create:function(t,e){return "custom"===t?e:u$3("offers"===t?t:"redirect/".concat(t,"/").concat(e))},domain:function(t){return c$3(t)?t:"".concat(Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/"),"/").concat(null==t?void 0:t.ltrim("/"))},get:u$3,is_full_url:c$3,is_page:function(t){return t&&Salla.config.get("page.slug")===t},is_placeholder:function(t){return f$2(salla.config.get("theme.settings.placeholder"))===f$2(t)}}),g$3=function(t,e){return g$3=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);},g$3(t,e)};var v$2=function(){return v$2=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},v$2.apply(this,arguments)};function y$3(t,e,r){if(2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}function m$3(t){return t instanceof FormData}function w$2(t){return t instanceof File}function S$2(t){return t instanceof Blob}"function"==typeof SuppressedError&&SuppressedError;var b$5=function(){function t(t){this.data=t,this.proxy=this.createProxy();}return t.prototype.createProxy=function(){var t=this;return new Proxy(this,{get:function(e,r){return r in e?e[r]:"string"==typeof r?t.get(r):void 0},set:function(e,r,n){return "string"==typeof r&&(t.set(r,n),true)},has:function(e,r){return "string"==typeof r?t.has(r):r in e},deleteProperty:function(e,r){return "string"==typeof r&&t.delete(r)}})},t.prototype.get=function(t){return m$3(this.data)?this.data.get(t):this.data[t]},t.prototype.getAll=function(t){if(m$3(this.data))return this.data.getAll(t);var e=this.data[t];return void 0===e?[]:[e]},t.prototype.set=function(t,e){var r=this;m$3(this.data)?(this.data.delete(t),null!=e&&(Array.isArray(e)?e.forEach(function(e){w$2(e)||S$2(e)?r.data.append(t,e):r.data.append(t,String(e));}):w$2(e)||S$2(e)?this.data.append(t,e):this.data.append(t,String(e)))):this.data[t]=e;},t.prototype.append=function(t,e){if(m$3(this.data))w$2(e)||S$2(e)?this.data.append(t,e):null!=e&&this.data.append(t,String(e));else {var r=this.data[t];void 0===r?this.data[t]=e:Array.isArray(r)?r.push(e):this.data[t]=[r,e];}},t.prototype.setFile=function(t,e){this.set(t,e);},t.prototype.getFile=function(t){var e=this.get(t);return w$2(e)?e:null},t.prototype.getFiles=function(t){return this.getAll(t).filter(w$2)},t.prototype.has=function(t){return m$3(this.data)?this.data.has(t):t in this.data},t.prototype.delete=function(t){return m$3(this.data)?(this.data.delete(t),true):delete this.data[t]},t.prototype.keys=function(){if(!m$3(this.data))return Object.keys(this.data);for(var t=new Set,e=0,r=this.data.entries();e<r.length;e++){var n=r[e][0];t.add(n);}return Array.from(t)},t.prototype.values=function(){if(!m$3(this.data))return Object.values(this.data);for(var t=[],e=0,r=this.data.entries();e<r.length;e++){var n=r[e][1];t.push(n);}return t},t.prototype.entries=function(){return m$3(this.data)?Array.from(this.data.entries()):Object.entries(this.data)},t.prototype.toObject=function(){if(!m$3(this.data))return v$2({},this.data);for(var t={},e=0,r=this.data.entries();e<r.length;e++){var n=r[e],o=n[0],i=n[1];void 0!==t[o]?(Array.isArray(t[o])||(t[o]=[t[o]]),t[o].push(i)):t[o]=i;}return t},t.prototype.getFileInfo=function(t){var e=this.getFiles(t);return 0===e.length?null:e.map(function(t){return {name:t.name,size:t.size,type:t.type}})},t.prototype.isFile=function(t){var e=this.get(t);return w$2(e)||S$2(e)},t.prototype.getRawData=function(){return this.data},t.prototype.getProxy=function(){return this.proxy},t}();function _$2(t,e,r){var n,o=t[0];return r&&0==t.length?Array.isArray(r)?(r.push(e),r):[r,e]:Array.isArray(r)?(r.push(e),r):"string"==typeof r?[r,e]:r?(r[o]=_$2(t.slice(1),e,r[o]),r):o?((n={})[o]=_$2(t.slice(1),e),n):""===o?[e]:e}function x$3(){return window.self!==window.top}var A$3,E$3,k$3,P$2,O$2={digitsOnly:function(t){return s$1(t,true).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function t(e,r){if(void 0===r&&(r=false),"string"==typeof e)return document.querySelectorAll(e).forEach(function(e){return t(e,r)});if(e){var n=Salla.helpers.digitsOnly(e.value);return e.min&&n<parseInt(e.min)?e.value=e.min:e.max&&n>parseInt(e.max)?e.value=e.max:e.maxLength>=1&&n.toString().length>e.maxLength?e.value=n.toString().substring(0,e.maxLength):e.value=r||e.dataset.hasOwnProperty("digitsWithDecimal")?l$2(n):n.replace(/\D/g,"")}Salla.logger.warn("Can't find Object With Id: "+e);},number:s$1,money:function(t,e){ void 0===e&&(e=true);var r=Salla.config.currency(null==t?void 0:t.currency).symbol;return t=s$1(t="object"==typeof t?t.amount:t)+" "+r,e&&["SAR","ر.س"].includes(r)&&Salla.config.get("store.settings.use_sar_symbol")&&(t=t.replace(r,"<i class=sicon-sar></i>")),t},isIframe:x$3,isPreview:function(){return x$3()},setNested:function(t,e,r){for(var n=t,o=e.split("."),i=o.length,a=0;a<i-1;a++){var s=o[a];n[s]||(n[s]={}),n=n[s];}return n[o[i-1]]=r,t},getNested:function(e,r,n){var o=t$2.default?t$2.default(e,r):t$2(e,r);return void 0!==o?o:n},inputData:function(t,e,r){if(void 0===r&&(r={}),t.includes("[")){var n=t.split("]").join("").split("["),o=n[0],i=r&&"object"==typeof r?r[o]:void 0;return {name:o,value:_$2(n.slice(1),e,i)}}return {name:t,value:e}},url:h$3,addParamToUrl:p$1,debounce:function(t,e){e=e||100;var r,n=[];return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];return clearTimeout(r),r=setTimeout(function(){var e=t.apply(void 0,o);n.forEach(function(t){return t(e)}),n=[];},e),new Promise(function(t){return n.push(t)})}},hasApplePay:function(){var t;try{return !!(null===(t=window.ApplePaySession)||void 0===t?void 0:t.canMakePayments())}catch(t){return console.error(t),false}},createFormDataWrapper:function(t){return new b$5(t).getProxy()},isAppleDevice:function(){try{var t=navigator.userAgent||"",e=navigator.platform||"",r=/iPhone|iPad|iPod/i.test(t),n=/Mac/i.test(e);return r||n}catch(t){return console.error(t),false}},isIOSDevice:function(){try{var t=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(t)}catch(t){return console.error(t),false}},isWebView:function(){try{if(void 0===window.navigator)return false;var t=window.navigator.userAgent,e=/iP(hone|od|ad)/.test(t)&&/AppleWebKit/.test(t)&&!/Safari/.test(t),r=/\bwv\b/.test(t)||/Android/.test(t)&&/AppleWebKit/.test(t)&&!/Chrome/.test(t);return e||r}catch(t){return console.error(t),false}}},j$3=(A$3=console,E$3=[],k$3=[],P$2={log:function(t,e){if(A$3&&salla.config.isDebug()){E$3.push([e,t]),"trace"===salla.config.get("debug")&&(e="trace");var r=A$3.log,n=void 0===e?r:this.__dict__[e]||r,o=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"];k$3.forEach(function(t){o[0]+=t[0],o.push(t[1]);});var i={event:"#CFF680",backend:"#7b68ee"}[e];i&&(o[0]+="%c"+e[0].toUpperCase()+e.substring(1),o.push("margin-left: 5px;color: ".concat(i,";font-weight:bold; border:1px solid ").concat(i,"; padding: 2px 6px; border-radius: 5px;"))),n.call.apply(n,y$3([A$3],o.concat.apply(o,t),false));}},__dict__:{trace:A$3.trace,debug:A$3.debug,info:A$3.info,warn:A$3.warn,error:A$3.error}},{event:function(){P$2.log(arguments,"event");},trace:function(){P$2.log(arguments,"trace");},debug:function(){P$2.log(arguments,"debug");},info:function(){P$2.log(arguments,"info");},warn:function(){P$2.log(arguments,"warn");},error:function(){P$2.log(arguments,"error");},log:function(){P$2.log(arguments,void 0);},backend:function(){P$2.log(arguments,"backend");},logs:function(t){[t].flat().forEach(function(t){return t&&P$2.log([t].flat(),"backend")});},history:function(){return E$3.map(function(t){return A$3.log.apply(A$3,y$3([t[0]],t[1],false))}),E$3},addPrefix:function(t){return Array.isArray(t)?k$3.unshift(t):this.warn("addPrefix receives array only!"),this}}),T$2=function(){function t(t,e){ void 0===t&&(t={}),void 0===e&&(e={}),this.default_properties=e,this.properties_=v$2(v$2({},this.default_properties),t);}return t.prototype.merge=function(t){var e;return this.properties_=v$2(v$2({},this.properties_),t),this.properties_.store=v$2(v$2({},(null===(e=this.default_properties)||void 0===e?void 0:e.store)||{}),this.properties_.store),this},t.prototype.set=function(t,e){return t.includes(".")?(Salla.helpers.setNested(this.properties_,t,e),this):(this.properties_[t]=e,this)},t.prototype.currency=function(t){return void 0===t&&(t=void 0),t=t||this.get("user.currency_code"),this.get("currencies."+t)||Object.values(this.get("currencies"))[0]},t.prototype.get=function(t,e){return void 0===e&&(e=null),t.includes(".")?Salla.helpers.getNested(this.properties_,t,e):this.properties_.hasOwnProperty(t)?this.properties_[t]||e:e||void 0},t.prototype.all=function(){return this.properties_},t.prototype.isDebug=function(){return this.get("debug")||Salla.storage.get("debug")},t}(),L$3=function(t){function e(){var e=this;return (e=t.call(this,{wildcard:true,delimiter:"::",newListener:false,removeListener:false,maxListeners:10,verboseMemoryLeak:false,ignoreErrors:false})||this).delimiter="::","undefined"!=typeof document&&(e.body=document.querySelector("body")),e.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],e.ingoreLogEvents=["document::click","document::keyup","document::change"],e.noneFireableActions=["document.request"],e.emittedEvents=new Set,e}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t;}g$3(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);}(e,t),e.prototype.createAndDispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];this.dispatch.apply(this,y$3([t],e,false));},e.prototype.emit=function(e){for(var r,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];this.emittedEvents.add(e);var i=e.replace("::",".");if(!this.noneFireableActions.includes(i)&&Salla.call&&"function"==typeof Salla.call(i))return Salla.log("'Salla.".concat(i,"(...)' triggered using event '").concat(e,"'")),i=i.split("."),Array.isArray(n[0])&&(n=n[0]),void(r=salla[i[0]])[i[1]].apply(r,n);t.prototype.emit.apply(this,y$3([e],n,false)),this.trackEvents.apply(this,y$3([e],n,false));},e.prototype.onlyWhen=function(t,e){var r=this;return e=e||function(){},new Promise(function(n){return r.emittedEvents.has(t)?n(e()):r.once(t,function(){return n(e())})})},e.prototype.emitAsync=function(e){for(var r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];this.emittedEvents.add(e);var o=t.prototype.emitAsync.apply(this,y$3([e],r,false));try{this.trackEvents.apply(this,y$3([e],r,false));}catch(t){Salla.logger.warn("error on tracking event (".concat(e,")"),r,t);}return o},e.prototype.trackEvents=function(t){for(var e,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if("undefined"!=typeof window)try{window.dataLayer=window.dataLayer||[];var o={event:t};r.map(function(t){return "object"==typeof t&&(o=v$2(v$2({},o),t))}),window.dataLayer.push(o);}catch(t){salla.logger.error(t.message);}Salla.logger&&!this.ingoreLogEvents.includes(t)&&(e=Salla.logger).event.apply(e,y$3([t],r,false)),this.dispatchMobileEvent.apply(this,y$3([t],r,false));},e.prototype.dispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return this.emit.apply(this,y$3([t],e,false))},e.prototype.dispatchEvents=function(t){if(t)if("object"!=typeof t||Array.isArray(t))Salla.log("Events object is wrong, it should be object of {event:payload}",t);else for(var e=0,r=Object.entries(t);e<r.length;e++){var n=r[e],o=n[0],i=n[1];this.dispatch(o,i);}else Salla.log("No Events To Dispatch!",t);},e.prototype.addListener=function(t,e,r){return this.on(t,e,r)},e.prototype.addEventListener=function(t,e,r){return this.on(t,e,r)},e.prototype.listen=function(t,e){return this.on(t,e)},e.prototype.registerGlobalListener=function(t,e){return this.onAny(e)},e.prototype.dispatchMobileEvent=function(t,e){var r;if(void 0===e&&(e={}),"undefined"!=typeof window){if(window.webkit)try{return void window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:t,details:e}))}catch(t){Salla.log(t,"The native context does not exist yet");}if(null===(r=window.Android)||void 0===r?void 0:r.customEventWithData)try{window.Android.customEventWithData(t,JSON.stringify({details:e}));}catch(t){Salla.log(t,"The native context does not exist yet");}else if(window.flutter_inappwebview)try{window.flutter_inappwebview.callHandler("sallaEvent",{event:t,details:e});}catch(t){Salla.log(t,"The Flutter context does not exist yet");}else;}},e}(eventemitter2Exports.EventEmitter2),W$2=storeEngineExports.createStore([n$4,o$3,i$3,a$4],[]),D$2=storeEngineExports.createStore([o$3],[]),C$3=storeEngineExports.createStore([i$3],[]),F$3=function(){function t(){var t=this;this.clearableItems=["cart","user","salla::wishlist","token"],Salla.event.on("storage::item.remove",function(e){return t.remove(e)}),Salla.event.on("storage::item.set",function(e,r){return t.set(e,r)}),this.store=W$2,this.session=D$2,this.cookie=C$3;}return t.prototype.set=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0],o=((r={})[n]=this.store.get(n),r);return o=Salla.helpers.setNested(o,t,e),this.store.set(n,o[n])}return this.store.set(t,e)},t.prototype.remove=function(t){return this.store.remove(t)},t.prototype.clearAll=function(t){var e=this;if(void 0===t&&(t=false),t)return this.store.clearAll();this.clearableItems.forEach(function(t){e.store.remove(t);});},t.prototype.get=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0];return Salla.helpers.getNested(((r={})[n]=this.store.get(n),r),t)}return this.store.get(t,e)},t.prototype.prefixKey=function(t){return "".concat(t,"_").concat(Salla.config.get("store.id"))},t.prototype.setWithTTL=function(t,e,r,n){ void 0===r&&(r=10),void 0===n&&(n="store");var o=this.prefixKey(t),i=(new Date).getTime()+60*r*1e3;return this[n].set(o,{value:e,expiry:i})},t.prototype.getWithTTL=function(t,e,r){ void 0===e&&(e=null),void 0===r&&(r="store");var n=this.prefixKey(t),o=this[r].get(n);return o?(new Date).getTime()>o.expiry?(this[r].remove(n),e):o.value:e},t}(),R$3=function(){function t(){var t=this;this.keysToRemove=["__said","__ssid","theme_edit","ws_port","s-token"],this.dynamicKeysToRemove=["affiliate","cart"],Salla.event.on("cookies::remove",function(e){return t.remove(e)}),Salla.event.on("cookies::add",function(e,r){return t.set(e,r)});}return t.prototype.get=function(t){var e;return null===(e=document.cookie.split("; ").find(function(e){return e.startsWith(t+"=")}))||void 0===e?void 0:e.split("=")[1]},t.prototype.set=function(t,e,r){ void 0===e&&(e=""),void 0===r&&(r=10);var n="";if(r){var o=new Date;o.setTime(o.getTime()+24*r*60*60*1e3),n="; expires="+o.toUTCString();}var i=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=").concat(e).concat(n,"; path=/; SameSite=").concat(i,"; secure"),this},t.prototype.remove=function(t){var e=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=; Max-Age=0; path=/; SameSite=").concat(e,"; secure"),this},t.prototype.clearAll=function(t){return void 0===t&&(t=false),this.clean(t)},t.prototype.clean=function(t){var e=this;return document.cookie.split(";").map(function(t){return t.split("=")[0].trim()}).filter(function(r){return t||e.keysToRemove.includes(r)||e.dynamicKeysToRemove.some(function(t){return r.startsWith(t)})}).forEach(function(t){return e.remove(t)}),this},t.prototype.getCookieByPrefix=function(t){return document.cookie.split("; ").map(function(t){return t.split("=")[0]}).filter(function(e){return e.startsWith(t)})},t.prototype.clearCookieByPrefix=function(t){var e=this;return this.getCookieByPrefix(t).forEach(function(t){return e.remove(t)})},t}();"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),"undefined"!=typeof global&&(global.salla=global.salla||global.Salla||{},global.Salla=global.salla),Salla.status="base",Salla.config=new T$2,Salla.logger=j$3,Salla.event=new L$3,Salla.helpers=O$2,Salla.storage=new F$3,Salla.cookie=new R$3,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"2.14.393"};var N$3=Salla;
4005
4005
 
4006
4006
  var js = {exports: {}};
4007
4007
 
@@ -6249,7 +6249,7 @@ function requireLang () {
6249
6249
  var langExports = requireLang();
6250
6250
  var a$3 = /*@__PURE__*/getDefaultExportFromCjs(langExports);
6251
6251
 
6252
- /*! Axios v1.13.3 Copyright (c) 2026 Matt Zabriskie and contributors */
6252
+ /*! Axios v1.14.0 Copyright (c) 2026 Matt Zabriskie and contributors */
6253
6253
 
6254
6254
  var axios_1;
6255
6255
  var hasRequiredAxios;
@@ -6273,30 +6273,30 @@ function requireAxios () {
6273
6273
 
6274
6274
  // utils is a library of generic helper functions non-specific to axios
6275
6275
 
6276
- const {toString} = Object.prototype;
6277
- const {getPrototypeOf} = Object;
6278
- const {iterator, toStringTag} = Symbol;
6276
+ const { toString } = Object.prototype;
6277
+ const { getPrototypeOf } = Object;
6278
+ const { iterator, toStringTag } = Symbol;
6279
6279
 
6280
- const kindOf = (cache => thing => {
6281
- const str = toString.call(thing);
6282
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
6280
+ const kindOf = ((cache) => (thing) => {
6281
+ const str = toString.call(thing);
6282
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
6283
6283
  })(Object.create(null));
6284
6284
 
6285
6285
  const kindOfTest = (type) => {
6286
6286
  type = type.toLowerCase();
6287
- return (thing) => kindOf(thing) === type
6287
+ return (thing) => kindOf(thing) === type;
6288
6288
  };
6289
6289
 
6290
- const typeOfTest = type => thing => typeof thing === type;
6290
+ const typeOfTest = (type) => (thing) => typeof thing === type;
6291
6291
 
6292
6292
  /**
6293
- * Determine if a value is an Array
6293
+ * Determine if a value is a non-null object
6294
6294
  *
6295
6295
  * @param {Object} val The value to test
6296
6296
  *
6297
6297
  * @returns {boolean} True if value is an Array, otherwise false
6298
6298
  */
6299
- const {isArray} = Array;
6299
+ const { isArray } = Array;
6300
6300
 
6301
6301
  /**
6302
6302
  * Determine if a value is undefined
@@ -6315,8 +6315,14 @@ function requireAxios () {
6315
6315
  * @returns {boolean} True if value is a Buffer, otherwise false
6316
6316
  */
6317
6317
  function isBuffer(val) {
6318
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
6319
- && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
6318
+ return (
6319
+ val !== null &&
6320
+ !isUndefined(val) &&
6321
+ val.constructor !== null &&
6322
+ !isUndefined(val.constructor) &&
6323
+ isFunction$1(val.constructor.isBuffer) &&
6324
+ val.constructor.isBuffer(val)
6325
+ );
6320
6326
  }
6321
6327
 
6322
6328
  /**
@@ -6328,7 +6334,6 @@ function requireAxios () {
6328
6334
  */
6329
6335
  const isArrayBuffer = kindOfTest('ArrayBuffer');
6330
6336
 
6331
-
6332
6337
  /**
6333
6338
  * Determine if a value is a view on an ArrayBuffer
6334
6339
  *
@@ -6338,10 +6343,10 @@ function requireAxios () {
6338
6343
  */
6339
6344
  function isArrayBufferView(val) {
6340
6345
  let result;
6341
- if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
6346
+ if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
6342
6347
  result = ArrayBuffer.isView(val);
6343
6348
  } else {
6344
- result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
6349
+ result = val && val.buffer && isArrayBuffer(val.buffer);
6345
6350
  }
6346
6351
  return result;
6347
6352
  }
@@ -6387,7 +6392,7 @@ function requireAxios () {
6387
6392
  * @param {*} thing The value to test
6388
6393
  * @returns {boolean} True if value is a Boolean, otherwise false
6389
6394
  */
6390
- const isBoolean = thing => thing === true || thing === false;
6395
+ const isBoolean = (thing) => thing === true || thing === false;
6391
6396
 
6392
6397
  /**
6393
6398
  * Determine if a value is a plain Object
@@ -6402,7 +6407,13 @@ function requireAxios () {
6402
6407
  }
6403
6408
 
6404
6409
  const prototype = getPrototypeOf(val);
6405
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val);
6410
+ return (
6411
+ (prototype === null ||
6412
+ prototype === Object.prototype ||
6413
+ Object.getPrototypeOf(prototype) === null) &&
6414
+ !(toStringTag in val) &&
6415
+ !(iterator in val)
6416
+ );
6406
6417
  };
6407
6418
 
6408
6419
  /**
@@ -6444,6 +6455,31 @@ function requireAxios () {
6444
6455
  */
6445
6456
  const isFile = kindOfTest('File');
6446
6457
 
6458
+ /**
6459
+ * Determine if a value is a React Native Blob
6460
+ * React Native "blob": an object with a `uri` attribute. Optionally, it can
6461
+ * also have a `name` and `type` attribute to specify filename and content type
6462
+ *
6463
+ * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
6464
+ *
6465
+ * @param {*} value The value to test
6466
+ *
6467
+ * @returns {boolean} True if value is a React Native Blob, otherwise false
6468
+ */
6469
+ const isReactNativeBlob = (value) => {
6470
+ return !!(value && typeof value.uri !== 'undefined');
6471
+ };
6472
+
6473
+ /**
6474
+ * Determine if environment is React Native
6475
+ * ReactNative `FormData` has a non-standard `getParts()` method
6476
+ *
6477
+ * @param {*} formData The formData to test
6478
+ *
6479
+ * @returns {boolean} True if environment is React Native, otherwise false
6480
+ */
6481
+ const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
6482
+
6447
6483
  /**
6448
6484
  * Determine if a value is a Blob
6449
6485
  *
@@ -6478,17 +6514,28 @@ function requireAxios () {
6478
6514
  *
6479
6515
  * @returns {boolean} True if value is an FormData, otherwise false
6480
6516
  */
6517
+ function getGlobal() {
6518
+ if (typeof globalThis !== 'undefined') return globalThis;
6519
+ if (typeof self !== 'undefined') return self;
6520
+ if (typeof window !== 'undefined') return window;
6521
+ if (typeof commonjsGlobal !== 'undefined') return commonjsGlobal;
6522
+ return {};
6523
+ }
6524
+
6525
+ const G = getGlobal();
6526
+ const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
6527
+
6481
6528
  const isFormData = (thing) => {
6482
6529
  let kind;
6483
6530
  return thing && (
6484
- (typeof FormData === 'function' && thing instanceof FormData) || (
6531
+ (FormDataCtor && thing instanceof FormDataCtor) || (
6485
6532
  isFunction$1(thing.append) && (
6486
6533
  (kind = kindOf(thing)) === 'formdata' ||
6487
6534
  // detect form-data instance
6488
6535
  (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
6489
6536
  )
6490
6537
  )
6491
- )
6538
+ );
6492
6539
  };
6493
6540
 
6494
6541
  /**
@@ -6500,7 +6547,12 @@ function requireAxios () {
6500
6547
  */
6501
6548
  const isURLSearchParams = kindOfTest('URLSearchParams');
6502
6549
 
6503
- const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
6550
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
6551
+ 'ReadableStream',
6552
+ 'Request',
6553
+ 'Response',
6554
+ 'Headers',
6555
+ ].map(kindOfTest);
6504
6556
 
6505
6557
  /**
6506
6558
  * Trim excess whitespace off the beginning and end of a string
@@ -6509,9 +6561,9 @@ function requireAxios () {
6509
6561
  *
6510
6562
  * @returns {String} The String freed of excess whitespace
6511
6563
  */
6512
- const trim = (str) => str.trim ?
6513
- str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
6514
-
6564
+ const trim = (str) => {
6565
+ return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
6566
+ };
6515
6567
  /**
6516
6568
  * Iterate over an Array or an Object invoking a function for each item.
6517
6569
  *
@@ -6528,7 +6580,7 @@ function requireAxios () {
6528
6580
  * @param {Boolean} [options.allOwnKeys = false]
6529
6581
  * @returns {any}
6530
6582
  */
6531
- function forEach(obj, fn, {allOwnKeys = false} = {}) {
6583
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
6532
6584
  // Don't bother if no value provided
6533
6585
  if (obj === null || typeof obj === 'undefined') {
6534
6586
  return;
@@ -6566,8 +6618,16 @@ function requireAxios () {
6566
6618
  }
6567
6619
  }
6568
6620
 
6621
+ /**
6622
+ * Finds a key in an object, case-insensitive, returning the actual key name.
6623
+ * Returns null if the object is a Buffer or if no match is found.
6624
+ *
6625
+ * @param {Object} obj - The object to search.
6626
+ * @param {string} key - The key to find (case-insensitive).
6627
+ * @returns {?string} The actual key name if found, otherwise null.
6628
+ */
6569
6629
  function findKey(obj, key) {
6570
- if (isBuffer(obj)){
6630
+ if (isBuffer(obj)) {
6571
6631
  return null;
6572
6632
  }
6573
6633
 
@@ -6586,8 +6646,8 @@ function requireAxios () {
6586
6646
 
6587
6647
  const _global = (() => {
6588
6648
  /*eslint no-undef:0*/
6589
- if (typeof globalThis !== "undefined") return globalThis;
6590
- return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : commonjsGlobal)
6649
+ if (typeof globalThis !== 'undefined') return globalThis;
6650
+ return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : commonjsGlobal;
6591
6651
  })();
6592
6652
 
6593
6653
  const isContextDefined = (context) => !isUndefined(context) && context !== _global;
@@ -6611,10 +6671,15 @@ function requireAxios () {
6611
6671
  * @returns {Object} Result of all merge properties
6612
6672
  */
6613
6673
  function merge(/* obj1, obj2, obj3, ... */) {
6614
- const {caseless, skipUndefined} = isContextDefined(this) && this || {};
6674
+ const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
6615
6675
  const result = {};
6616
6676
  const assignValue = (val, key) => {
6617
- const targetKey = caseless && findKey(result, key) || key;
6677
+ // Skip dangerous property names to prevent prototype pollution
6678
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
6679
+ return;
6680
+ }
6681
+
6682
+ const targetKey = (caseless && findKey(result, key)) || key;
6618
6683
  if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
6619
6684
  result[targetKey] = merge(result[targetKey], val);
6620
6685
  } else if (isPlainObject(val)) {
@@ -6643,24 +6708,28 @@ function requireAxios () {
6643
6708
  * @param {Boolean} [options.allOwnKeys]
6644
6709
  * @returns {Object} The resulting value of object a
6645
6710
  */
6646
- const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
6647
- forEach(b, (val, key) => {
6648
- if (thisArg && isFunction$1(val)) {
6649
- Object.defineProperty(a, key, {
6650
- value: bind(val, thisArg),
6651
- writable: true,
6652
- enumerable: true,
6653
- configurable: true
6654
- });
6655
- } else {
6656
- Object.defineProperty(a, key, {
6657
- value: val,
6658
- writable: true,
6659
- enumerable: true,
6660
- configurable: true
6661
- });
6662
- }
6663
- }, {allOwnKeys});
6711
+ const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
6712
+ forEach(
6713
+ b,
6714
+ (val, key) => {
6715
+ if (thisArg && isFunction$1(val)) {
6716
+ Object.defineProperty(a, key, {
6717
+ value: bind(val, thisArg),
6718
+ writable: true,
6719
+ enumerable: true,
6720
+ configurable: true,
6721
+ });
6722
+ } else {
6723
+ Object.defineProperty(a, key, {
6724
+ value: val,
6725
+ writable: true,
6726
+ enumerable: true,
6727
+ configurable: true,
6728
+ });
6729
+ }
6730
+ },
6731
+ { allOwnKeys }
6732
+ );
6664
6733
  return a;
6665
6734
  };
6666
6735
 
@@ -6672,7 +6741,7 @@ function requireAxios () {
6672
6741
  * @returns {string} content value without BOM
6673
6742
  */
6674
6743
  const stripBOM = (content) => {
6675
- if (content.charCodeAt(0) === 0xFEFF) {
6744
+ if (content.charCodeAt(0) === 0xfeff) {
6676
6745
  content = content.slice(1);
6677
6746
  }
6678
6747
  return content;
@@ -6693,10 +6762,10 @@ function requireAxios () {
6693
6762
  value: constructor,
6694
6763
  writable: true,
6695
6764
  enumerable: false,
6696
- configurable: true
6765
+ configurable: true,
6697
6766
  });
6698
6767
  Object.defineProperty(constructor, 'super', {
6699
- value: superConstructor.prototype
6768
+ value: superConstructor.prototype,
6700
6769
  });
6701
6770
  props && Object.assign(constructor.prototype, props);
6702
6771
  };
@@ -6755,7 +6824,6 @@ function requireAxios () {
6755
6824
  return lastIndex !== -1 && lastIndex === position;
6756
6825
  };
6757
6826
 
6758
-
6759
6827
  /**
6760
6828
  * Returns new array from array like object or null if failed
6761
6829
  *
@@ -6784,9 +6852,9 @@ function requireAxios () {
6784
6852
  * @returns {Array}
6785
6853
  */
6786
6854
  // eslint-disable-next-line func-names
6787
- const isTypedArray = (TypedArray => {
6855
+ const isTypedArray = ((TypedArray) => {
6788
6856
  // eslint-disable-next-line func-names
6789
- return thing => {
6857
+ return (thing) => {
6790
6858
  return TypedArray && thing instanceof TypedArray;
6791
6859
  };
6792
6860
  })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
@@ -6834,16 +6902,18 @@ function requireAxios () {
6834
6902
  /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
6835
6903
  const isHTMLForm = kindOfTest('HTMLFormElement');
6836
6904
 
6837
- const toCamelCase = str => {
6838
- return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
6839
- function replacer(m, p1, p2) {
6840
- return p1.toUpperCase() + p2;
6841
- }
6842
- );
6905
+ const toCamelCase = (str) => {
6906
+ return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
6907
+ return p1.toUpperCase() + p2;
6908
+ });
6843
6909
  };
6844
6910
 
6845
6911
  /* Creating a function that will check if an object has a property. */
6846
- const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
6912
+ const hasOwnProperty = (
6913
+ ({ hasOwnProperty }) =>
6914
+ (obj, prop) =>
6915
+ hasOwnProperty.call(obj, prop)
6916
+ )(Object.prototype);
6847
6917
 
6848
6918
  /**
6849
6919
  * Determine if a value is a RegExp object
@@ -6893,17 +6963,25 @@ function requireAxios () {
6893
6963
 
6894
6964
  if (!descriptor.set) {
6895
6965
  descriptor.set = () => {
6896
- throw Error('Can not rewrite read-only method \'' + name + '\'');
6966
+ throw Error("Can not rewrite read-only method '" + name + "'");
6897
6967
  };
6898
6968
  }
6899
6969
  });
6900
6970
  };
6901
6971
 
6972
+ /**
6973
+ * Converts an array or a delimited string into an object set with values as keys and true as values.
6974
+ * Useful for fast membership checks.
6975
+ *
6976
+ * @param {Array|string} arrayOrString - The array or string to convert.
6977
+ * @param {string} delimiter - The delimiter to use if input is a string.
6978
+ * @returns {Object} An object with keys from the array or string, values set to true.
6979
+ */
6902
6980
  const toObjectSet = (arrayOrString, delimiter) => {
6903
6981
  const obj = {};
6904
6982
 
6905
6983
  const define = (arr) => {
6906
- arr.forEach(value => {
6984
+ arr.forEach((value) => {
6907
6985
  obj[value] = true;
6908
6986
  });
6909
6987
  };
@@ -6916,11 +6994,9 @@ function requireAxios () {
6916
6994
  const noop = () => {};
6917
6995
 
6918
6996
  const toFiniteNumber = (value, defaultValue) => {
6919
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
6997
+ return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
6920
6998
  };
6921
6999
 
6922
-
6923
-
6924
7000
  /**
6925
7001
  * If the thing is a FormData object, return true, otherwise return false.
6926
7002
  *
@@ -6929,14 +7005,24 @@ function requireAxios () {
6929
7005
  * @returns {boolean}
6930
7006
  */
6931
7007
  function isSpecCompliantForm(thing) {
6932
- return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
7008
+ return !!(
7009
+ thing &&
7010
+ isFunction$1(thing.append) &&
7011
+ thing[toStringTag] === 'FormData' &&
7012
+ thing[iterator]
7013
+ );
6933
7014
  }
6934
7015
 
7016
+ /**
7017
+ * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
7018
+ *
7019
+ * @param {Object} obj - The object to convert.
7020
+ * @returns {Object} The JSON-compatible object.
7021
+ */
6935
7022
  const toJSONObject = (obj) => {
6936
7023
  const stack = new Array(10);
6937
7024
 
6938
7025
  const visit = (source, i) => {
6939
-
6940
7026
  if (isObject(source)) {
6941
7027
  if (stack.indexOf(source) >= 0) {
6942
7028
  return;
@@ -6947,7 +7033,7 @@ function requireAxios () {
6947
7033
  return source;
6948
7034
  }
6949
7035
 
6950
- if(!('toJSON' in source)) {
7036
+ if (!('toJSON' in source)) {
6951
7037
  stack[i] = source;
6952
7038
  const target = isArray(source) ? [] : {};
6953
7039
 
@@ -6968,45 +7054,77 @@ function requireAxios () {
6968
7054
  return visit(obj, 0);
6969
7055
  };
6970
7056
 
7057
+ /**
7058
+ * Determines if a value is an async function.
7059
+ *
7060
+ * @param {*} thing - The value to test.
7061
+ * @returns {boolean} True if value is an async function, otherwise false.
7062
+ */
6971
7063
  const isAsyncFn = kindOfTest('AsyncFunction');
6972
7064
 
7065
+ /**
7066
+ * Determines if a value is thenable (has then and catch methods).
7067
+ *
7068
+ * @param {*} thing - The value to test.
7069
+ * @returns {boolean} True if value is thenable, otherwise false.
7070
+ */
6973
7071
  const isThenable = (thing) =>
6974
- thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
7072
+ thing &&
7073
+ (isObject(thing) || isFunction$1(thing)) &&
7074
+ isFunction$1(thing.then) &&
7075
+ isFunction$1(thing.catch);
6975
7076
 
6976
7077
  // original code
6977
7078
  // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
6978
7079
 
7080
+ /**
7081
+ * Provides a cross-platform setImmediate implementation.
7082
+ * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
7083
+ *
7084
+ * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
7085
+ * @param {boolean} postMessageSupported - Whether postMessage is supported.
7086
+ * @returns {Function} A function to schedule a callback asynchronously.
7087
+ */
6979
7088
  const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
6980
7089
  if (setImmediateSupported) {
6981
7090
  return setImmediate;
6982
7091
  }
6983
7092
 
6984
- return postMessageSupported ? ((token, callbacks) => {
6985
- _global.addEventListener("message", ({source, data}) => {
6986
- if (source === _global && data === token) {
6987
- callbacks.length && callbacks.shift()();
6988
- }
6989
- }, false);
7093
+ return postMessageSupported
7094
+ ? ((token, callbacks) => {
7095
+ _global.addEventListener(
7096
+ 'message',
7097
+ ({ source, data }) => {
7098
+ if (source === _global && data === token) {
7099
+ callbacks.length && callbacks.shift()();
7100
+ }
7101
+ },
7102
+ false
7103
+ );
6990
7104
 
6991
- return (cb) => {
6992
- callbacks.push(cb);
6993
- _global.postMessage(token, "*");
6994
- }
6995
- })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
6996
- })(
6997
- typeof setImmediate === 'function',
6998
- isFunction$1(_global.postMessage)
6999
- );
7105
+ return (cb) => {
7106
+ callbacks.push(cb);
7107
+ _global.postMessage(token, '*');
7108
+ };
7109
+ })(`axios@${Math.random()}`, [])
7110
+ : (cb) => setTimeout(cb);
7111
+ })(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
7000
7112
 
7001
- const asap = typeof queueMicrotask !== 'undefined' ?
7002
- queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
7113
+ /**
7114
+ * Schedules a microtask or asynchronous callback as soon as possible.
7115
+ * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
7116
+ *
7117
+ * @type {Function}
7118
+ */
7119
+ const asap =
7120
+ typeof queueMicrotask !== 'undefined'
7121
+ ? queueMicrotask.bind(_global)
7122
+ : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
7003
7123
 
7004
7124
  // *********************
7005
7125
 
7006
-
7007
7126
  const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
7008
7127
 
7009
-
7010
7128
  var utils$1 = {
7011
7129
  isArray,
7012
7130
  isArrayBuffer,
@@ -7026,6 +7144,8 @@ function requireAxios () {
7026
7144
  isUndefined,
7027
7145
  isDate,
7028
7146
  isFile,
7147
+ isReactNativeBlob,
7148
+ isReactNative,
7029
7149
  isBlob,
7030
7150
  isRegExp,
7031
7151
  isFunction: isFunction$1,
@@ -7064,18 +7184,24 @@ function requireAxios () {
7064
7184
  isThenable,
7065
7185
  setImmediate: _setImmediate,
7066
7186
  asap,
7067
- isIterable
7187
+ isIterable,
7068
7188
  };
7069
7189
 
7070
7190
  class AxiosError extends Error {
7071
- static from(error, code, config, request, response, customProps) {
7072
- const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
7073
- axiosError.cause = error;
7074
- axiosError.name = error.name;
7075
- customProps && Object.assign(axiosError, customProps);
7076
- return axiosError;
7191
+ static from(error, code, config, request, response, customProps) {
7192
+ const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
7193
+ axiosError.cause = error;
7194
+ axiosError.name = error.name;
7195
+
7196
+ // Preserve status from the original error if not already set from response
7197
+ if (error.status != null && axiosError.status == null) {
7198
+ axiosError.status = error.status;
7077
7199
  }
7078
7200
 
7201
+ customProps && Object.assign(axiosError, customProps);
7202
+ return axiosError;
7203
+ }
7204
+
7079
7205
  /**
7080
7206
  * Create an Error with the specified message, config, error code, request and response.
7081
7207
  *
@@ -7088,37 +7214,48 @@ function requireAxios () {
7088
7214
  * @returns {Error} The created error.
7089
7215
  */
7090
7216
  constructor(message, code, config, request, response) {
7091
- super(message);
7092
- this.name = 'AxiosError';
7093
- this.isAxiosError = true;
7094
- code && (this.code = code);
7095
- config && (this.config = config);
7096
- request && (this.request = request);
7097
- if (response) {
7098
- this.response = response;
7099
- this.status = response.status;
7100
- }
7217
+ super(message);
7218
+
7219
+ // Make message enumerable to maintain backward compatibility
7220
+ // The native Error constructor sets message as non-enumerable,
7221
+ // but axios < v1.13.3 had it as enumerable
7222
+ Object.defineProperty(this, 'message', {
7223
+ value: message,
7224
+ enumerable: true,
7225
+ writable: true,
7226
+ configurable: true
7227
+ });
7228
+
7229
+ this.name = 'AxiosError';
7230
+ this.isAxiosError = true;
7231
+ code && (this.code = code);
7232
+ config && (this.config = config);
7233
+ request && (this.request = request);
7234
+ if (response) {
7235
+ this.response = response;
7236
+ this.status = response.status;
7237
+ }
7101
7238
  }
7102
7239
 
7103
- toJSON() {
7104
- return {
7105
- // Standard
7106
- message: this.message,
7107
- name: this.name,
7108
- // Microsoft
7109
- description: this.description,
7110
- number: this.number,
7111
- // Mozilla
7112
- fileName: this.fileName,
7113
- lineNumber: this.lineNumber,
7114
- columnNumber: this.columnNumber,
7115
- stack: this.stack,
7116
- // Axios
7117
- config: utils$1.toJSONObject(this.config),
7118
- code: this.code,
7119
- status: this.status,
7120
- };
7121
- }
7240
+ toJSON() {
7241
+ return {
7242
+ // Standard
7243
+ message: this.message,
7244
+ name: this.name,
7245
+ // Microsoft
7246
+ description: this.description,
7247
+ number: this.number,
7248
+ // Mozilla
7249
+ fileName: this.fileName,
7250
+ lineNumber: this.lineNumber,
7251
+ columnNumber: this.columnNumber,
7252
+ stack: this.stack,
7253
+ // Axios
7254
+ config: utils$1.toJSONObject(this.config),
7255
+ code: this.code,
7256
+ status: this.status,
7257
+ };
7258
+ }
7122
7259
  }
7123
7260
 
7124
7261
  // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
@@ -7135,8 +7272,6 @@ function requireAxios () {
7135
7272
  AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
7136
7273
  AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
7137
7274
 
7138
- var AxiosError$1 = AxiosError;
7139
-
7140
7275
  // eslint-disable-next-line strict
7141
7276
  var httpAdapter = null;
7142
7277
 
@@ -7173,11 +7308,14 @@ function requireAxios () {
7173
7308
  */
7174
7309
  function renderKey(path, key, dots) {
7175
7310
  if (!path) return key;
7176
- return path.concat(key).map(function each(token, i) {
7177
- // eslint-disable-next-line no-param-reassign
7178
- token = removeBrackets(token);
7179
- return !dots && i ? '[' + token + ']' : token;
7180
- }).join(dots ? '.' : '');
7311
+ return path
7312
+ .concat(key)
7313
+ .map(function each(token, i) {
7314
+ // eslint-disable-next-line no-param-reassign
7315
+ token = removeBrackets(token);
7316
+ return !dots && i ? '[' + token + ']' : token;
7317
+ })
7318
+ .join(dots ? '.' : '');
7181
7319
  }
7182
7320
 
7183
7321
  /**
@@ -7227,21 +7365,26 @@ function requireAxios () {
7227
7365
  formData = formData || new (FormData)();
7228
7366
 
7229
7367
  // eslint-disable-next-line no-param-reassign
7230
- options = utils$1.toFlatObject(options, {
7231
- metaTokens: true,
7232
- dots: false,
7233
- indexes: false
7234
- }, false, function defined(option, source) {
7235
- // eslint-disable-next-line no-eq-null,eqeqeq
7236
- return !utils$1.isUndefined(source[option]);
7237
- });
7368
+ options = utils$1.toFlatObject(
7369
+ options,
7370
+ {
7371
+ metaTokens: true,
7372
+ dots: false,
7373
+ indexes: false,
7374
+ },
7375
+ false,
7376
+ function defined(option, source) {
7377
+ // eslint-disable-next-line no-eq-null,eqeqeq
7378
+ return !utils$1.isUndefined(source[option]);
7379
+ }
7380
+ );
7238
7381
 
7239
7382
  const metaTokens = options.metaTokens;
7240
7383
  // eslint-disable-next-line no-use-before-define
7241
7384
  const visitor = options.visitor || defaultVisitor;
7242
7385
  const dots = options.dots;
7243
7386
  const indexes = options.indexes;
7244
- const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
7387
+ const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
7245
7388
  const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
7246
7389
 
7247
7390
  if (!utils$1.isFunction(visitor)) {
@@ -7260,7 +7403,7 @@ function requireAxios () {
7260
7403
  }
7261
7404
 
7262
7405
  if (!useBlob && utils$1.isBlob(value)) {
7263
- throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
7406
+ throw new AxiosError('Blob is not supported. Use a Buffer instead.');
7264
7407
  }
7265
7408
 
7266
7409
  if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
@@ -7283,6 +7426,11 @@ function requireAxios () {
7283
7426
  function defaultVisitor(value, key, path) {
7284
7427
  let arr = value;
7285
7428
 
7429
+ if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
7430
+ formData.append(renderKey(path, key, dots), convertValue(value));
7431
+ return false;
7432
+ }
7433
+
7286
7434
  if (value && !path && typeof value === 'object') {
7287
7435
  if (utils$1.endsWith(key, '{}')) {
7288
7436
  // eslint-disable-next-line no-param-reassign
@@ -7291,17 +7439,22 @@ function requireAxios () {
7291
7439
  value = JSON.stringify(value);
7292
7440
  } else if (
7293
7441
  (utils$1.isArray(value) && isFlatArray(value)) ||
7294
- ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
7295
- )) {
7442
+ ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)))
7443
+ ) {
7296
7444
  // eslint-disable-next-line no-param-reassign
7297
7445
  key = removeBrackets(key);
7298
7446
 
7299
7447
  arr.forEach(function each(el, index) {
7300
- !(utils$1.isUndefined(el) || el === null) && formData.append(
7301
- // eslint-disable-next-line no-nested-ternary
7302
- indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
7303
- convertValue(el)
7304
- );
7448
+ !(utils$1.isUndefined(el) || el === null) &&
7449
+ formData.append(
7450
+ // eslint-disable-next-line no-nested-ternary
7451
+ indexes === true
7452
+ ? renderKey([key], index, dots)
7453
+ : indexes === null
7454
+ ? key
7455
+ : key + '[]',
7456
+ convertValue(el)
7457
+ );
7305
7458
  });
7306
7459
  return false;
7307
7460
  }
@@ -7321,7 +7474,7 @@ function requireAxios () {
7321
7474
  const exposedHelpers = Object.assign(predicates, {
7322
7475
  defaultVisitor,
7323
7476
  convertValue,
7324
- isVisitable
7477
+ isVisitable,
7325
7478
  });
7326
7479
 
7327
7480
  function build(value, path) {
@@ -7334,9 +7487,9 @@ function requireAxios () {
7334
7487
  stack.push(value);
7335
7488
 
7336
7489
  utils$1.forEach(value, function each(el, key) {
7337
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
7338
- formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
7339
- );
7490
+ const result =
7491
+ !(utils$1.isUndefined(el) || el === null) &&
7492
+ visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
7340
7493
 
7341
7494
  if (result === true) {
7342
7495
  build(el, path ? path.concat(key) : [key]);
@@ -7371,7 +7524,7 @@ function requireAxios () {
7371
7524
  ')': '%29',
7372
7525
  '~': '%7E',
7373
7526
  '%20': '+',
7374
- '%00': '\x00'
7527
+ '%00': '\x00',
7375
7528
  };
7376
7529
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
7377
7530
  return charMap[match];
@@ -7399,29 +7552,33 @@ function requireAxios () {
7399
7552
  };
7400
7553
 
7401
7554
  prototype.toString = function toString(encoder) {
7402
- const _encode = encoder ? function(value) {
7403
- return encoder.call(this, value, encode$1);
7404
- } : encode$1;
7555
+ const _encode = encoder
7556
+ ? function (value) {
7557
+ return encoder.call(this, value, encode$1);
7558
+ }
7559
+ : encode$1;
7405
7560
 
7406
- return this._pairs.map(function each(pair) {
7407
- return _encode(pair[0]) + '=' + _encode(pair[1]);
7408
- }, '').join('&');
7561
+ return this._pairs
7562
+ .map(function each(pair) {
7563
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
7564
+ }, '')
7565
+ .join('&');
7409
7566
  };
7410
7567
 
7411
7568
  /**
7412
- * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
7413
- * URI encoded counterparts
7569
+ * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
7570
+ * their plain counterparts (`:`, `$`, `,`, `+`).
7414
7571
  *
7415
7572
  * @param {string} val The value to be encoded.
7416
7573
  *
7417
7574
  * @returns {string} The encoded value.
7418
7575
  */
7419
7576
  function encode(val) {
7420
- return encodeURIComponent(val).
7421
- replace(/%3A/gi, ':').
7422
- replace(/%24/g, '$').
7423
- replace(/%2C/gi, ',').
7424
- replace(/%20/g, '+');
7577
+ return encodeURIComponent(val)
7578
+ .replace(/%3A/gi, ':')
7579
+ .replace(/%24/g, '$')
7580
+ .replace(/%2C/gi, ',')
7581
+ .replace(/%20/g, '+');
7425
7582
  }
7426
7583
 
7427
7584
  /**
@@ -7438,11 +7595,13 @@ function requireAxios () {
7438
7595
  return url;
7439
7596
  }
7440
7597
 
7441
- const _encode = options && options.encode || encode;
7598
+ const _encode = (options && options.encode) || encode;
7442
7599
 
7443
- const _options = utils$1.isFunction(options) ? {
7444
- serialize: options
7445
- } : options;
7600
+ const _options = utils$1.isFunction(options)
7601
+ ? {
7602
+ serialize: options,
7603
+ }
7604
+ : options;
7446
7605
 
7447
7606
  const serializeFn = _options && _options.serialize;
7448
7607
 
@@ -7451,13 +7610,13 @@ function requireAxios () {
7451
7610
  if (serializeFn) {
7452
7611
  serializedParams = serializeFn(params, _options);
7453
7612
  } else {
7454
- serializedParams = utils$1.isURLSearchParams(params) ?
7455
- params.toString() :
7456
- new AxiosURLSearchParams(params, _options).toString(_encode);
7613
+ serializedParams = utils$1.isURLSearchParams(params)
7614
+ ? params.toString()
7615
+ : new AxiosURLSearchParams(params, _options).toString(_encode);
7457
7616
  }
7458
7617
 
7459
7618
  if (serializedParams) {
7460
- const hashmarkIndex = url.indexOf("#");
7619
+ const hashmarkIndex = url.indexOf('#');
7461
7620
 
7462
7621
  if (hashmarkIndex !== -1) {
7463
7622
  url = url.slice(0, hashmarkIndex);
@@ -7487,7 +7646,7 @@ function requireAxios () {
7487
7646
  fulfilled,
7488
7647
  rejected,
7489
7648
  synchronous: options ? options.synchronous : false,
7490
- runWhen: options ? options.runWhen : null
7649
+ runWhen: options ? options.runWhen : null,
7491
7650
  });
7492
7651
  return this.handlers.length - 1;
7493
7652
  }
@@ -7535,12 +7694,11 @@ function requireAxios () {
7535
7694
  }
7536
7695
  }
7537
7696
 
7538
- var InterceptorManager$1 = InterceptorManager;
7539
-
7540
7697
  var transitionalDefaults = {
7541
7698
  silentJSONParsing: true,
7542
7699
  forcedJSONParsing: true,
7543
- clarifyTimeoutError: false
7700
+ clarifyTimeoutError: false,
7701
+ legacyInterceptorReqResOrdering: true,
7544
7702
  };
7545
7703
 
7546
7704
  var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
@@ -7554,14 +7712,14 @@ function requireAxios () {
7554
7712
  classes: {
7555
7713
  URLSearchParams: URLSearchParams$1,
7556
7714
  FormData: FormData$1,
7557
- Blob: Blob$1
7715
+ Blob: Blob$1,
7558
7716
  },
7559
- protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
7717
+ protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],
7560
7718
  };
7561
7719
 
7562
7720
  const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
7563
7721
 
7564
- const _navigator = typeof navigator === 'object' && navigator || undefined;
7722
+ const _navigator = (typeof navigator === 'object' && navigator) || undefined;
7565
7723
 
7566
7724
  /**
7567
7725
  * Determine if we're running in a standard browser environment
@@ -7580,7 +7738,8 @@ function requireAxios () {
7580
7738
  *
7581
7739
  * @returns {boolean}
7582
7740
  */
7583
- const hasStandardBrowserEnv = hasBrowserEnv &&
7741
+ const hasStandardBrowserEnv =
7742
+ hasBrowserEnv &&
7584
7743
  (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
7585
7744
 
7586
7745
  /**
@@ -7601,25 +7760,25 @@ function requireAxios () {
7601
7760
  );
7602
7761
  })();
7603
7762
 
7604
- const origin = hasBrowserEnv && window.location.href || 'http://localhost';
7763
+ const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';
7605
7764
 
7606
7765
  var utils = /*#__PURE__*/Object.freeze({
7607
7766
  __proto__: null,
7608
7767
  hasBrowserEnv: hasBrowserEnv,
7609
- hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
7610
7768
  hasStandardBrowserEnv: hasStandardBrowserEnv,
7769
+ hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
7611
7770
  navigator: _navigator,
7612
7771
  origin: origin
7613
7772
  });
7614
7773
 
7615
7774
  var platform = {
7616
7775
  ...utils,
7617
- ...platform$1
7776
+ ...platform$1,
7618
7777
  };
7619
7778
 
7620
7779
  function toURLEncodedForm(data, options) {
7621
7780
  return toFormData(data, new platform.classes.URLSearchParams(), {
7622
- visitor: function(value, key, path, helpers) {
7781
+ visitor: function (value, key, path, helpers) {
7623
7782
  if (platform.isNode && utils$1.isBuffer(value)) {
7624
7783
  this.append(key, value.toString('base64'));
7625
7784
  return false;
@@ -7627,7 +7786,7 @@ function requireAxios () {
7627
7786
 
7628
7787
  return helpers.defaultVisitor.apply(this, arguments);
7629
7788
  },
7630
- ...options
7789
+ ...options,
7631
7790
  });
7632
7791
  }
7633
7792
 
@@ -7643,7 +7802,7 @@ function requireAxios () {
7643
7802
  // foo.x.y.z
7644
7803
  // foo-x-y-z
7645
7804
  // foo x y z
7646
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
7805
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
7647
7806
  return match[0] === '[]' ? '' : match[1] || match[0];
7648
7807
  });
7649
7808
  }
@@ -7747,96 +7906,107 @@ function requireAxios () {
7747
7906
  }
7748
7907
 
7749
7908
  const defaults = {
7750
-
7751
7909
  transitional: transitionalDefaults,
7752
7910
 
7753
7911
  adapter: ['xhr', 'http', 'fetch'],
7754
7912
 
7755
- transformRequest: [function transformRequest(data, headers) {
7756
- const contentType = headers.getContentType() || '';
7757
- const hasJSONContentType = contentType.indexOf('application/json') > -1;
7758
- const isObjectPayload = utils$1.isObject(data);
7913
+ transformRequest: [
7914
+ function transformRequest(data, headers) {
7915
+ const contentType = headers.getContentType() || '';
7916
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
7917
+ const isObjectPayload = utils$1.isObject(data);
7759
7918
 
7760
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
7761
- data = new FormData(data);
7762
- }
7919
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
7920
+ data = new FormData(data);
7921
+ }
7763
7922
 
7764
- const isFormData = utils$1.isFormData(data);
7923
+ const isFormData = utils$1.isFormData(data);
7765
7924
 
7766
- if (isFormData) {
7767
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
7768
- }
7925
+ if (isFormData) {
7926
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
7927
+ }
7769
7928
 
7770
- if (utils$1.isArrayBuffer(data) ||
7771
- utils$1.isBuffer(data) ||
7772
- utils$1.isStream(data) ||
7773
- utils$1.isFile(data) ||
7774
- utils$1.isBlob(data) ||
7775
- utils$1.isReadableStream(data)
7776
- ) {
7777
- return data;
7778
- }
7779
- if (utils$1.isArrayBufferView(data)) {
7780
- return data.buffer;
7781
- }
7782
- if (utils$1.isURLSearchParams(data)) {
7783
- headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
7784
- return data.toString();
7785
- }
7929
+ if (
7930
+ utils$1.isArrayBuffer(data) ||
7931
+ utils$1.isBuffer(data) ||
7932
+ utils$1.isStream(data) ||
7933
+ utils$1.isFile(data) ||
7934
+ utils$1.isBlob(data) ||
7935
+ utils$1.isReadableStream(data)
7936
+ ) {
7937
+ return data;
7938
+ }
7939
+ if (utils$1.isArrayBufferView(data)) {
7940
+ return data.buffer;
7941
+ }
7942
+ if (utils$1.isURLSearchParams(data)) {
7943
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
7944
+ return data.toString();
7945
+ }
7786
7946
 
7787
- let isFileList;
7947
+ let isFileList;
7788
7948
 
7789
- if (isObjectPayload) {
7790
- if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
7791
- return toURLEncodedForm(data, this.formSerializer).toString();
7792
- }
7949
+ if (isObjectPayload) {
7950
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
7951
+ return toURLEncodedForm(data, this.formSerializer).toString();
7952
+ }
7793
7953
 
7794
- if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
7795
- const _FormData = this.env && this.env.FormData;
7954
+ if (
7955
+ (isFileList = utils$1.isFileList(data)) ||
7956
+ contentType.indexOf('multipart/form-data') > -1
7957
+ ) {
7958
+ const _FormData = this.env && this.env.FormData;
7796
7959
 
7797
- return toFormData(
7798
- isFileList ? {'files[]': data} : data,
7799
- _FormData && new _FormData(),
7800
- this.formSerializer
7801
- );
7960
+ return toFormData(
7961
+ isFileList ? { 'files[]': data } : data,
7962
+ _FormData && new _FormData(),
7963
+ this.formSerializer
7964
+ );
7965
+ }
7802
7966
  }
7803
- }
7804
7967
 
7805
- if (isObjectPayload || hasJSONContentType ) {
7806
- headers.setContentType('application/json', false);
7807
- return stringifySafely(data);
7808
- }
7968
+ if (isObjectPayload || hasJSONContentType) {
7969
+ headers.setContentType('application/json', false);
7970
+ return stringifySafely(data);
7971
+ }
7809
7972
 
7810
- return data;
7811
- }],
7973
+ return data;
7974
+ },
7975
+ ],
7812
7976
 
7813
- transformResponse: [function transformResponse(data) {
7814
- const transitional = this.transitional || defaults.transitional;
7815
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
7816
- const JSONRequested = this.responseType === 'json';
7977
+ transformResponse: [
7978
+ function transformResponse(data) {
7979
+ const transitional = this.transitional || defaults.transitional;
7980
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
7981
+ const JSONRequested = this.responseType === 'json';
7817
7982
 
7818
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
7819
- return data;
7820
- }
7983
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
7984
+ return data;
7985
+ }
7821
7986
 
7822
- if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
7823
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
7824
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
7987
+ if (
7988
+ data &&
7989
+ utils$1.isString(data) &&
7990
+ ((forcedJSONParsing && !this.responseType) || JSONRequested)
7991
+ ) {
7992
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
7993
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
7825
7994
 
7826
- try {
7827
- return JSON.parse(data, this.parseReviver);
7828
- } catch (e) {
7829
- if (strictJSONParsing) {
7830
- if (e.name === 'SyntaxError') {
7831
- throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
7995
+ try {
7996
+ return JSON.parse(data, this.parseReviver);
7997
+ } catch (e) {
7998
+ if (strictJSONParsing) {
7999
+ if (e.name === 'SyntaxError') {
8000
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
8001
+ }
8002
+ throw e;
7832
8003
  }
7833
- throw e;
7834
8004
  }
7835
8005
  }
7836
- }
7837
8006
 
7838
- return data;
7839
- }],
8007
+ return data;
8008
+ },
8009
+ ],
7840
8010
 
7841
8011
  /**
7842
8012
  * A timeout in milliseconds to abort a request. If set to 0 (default) a
@@ -7852,7 +8022,7 @@ function requireAxios () {
7852
8022
 
7853
8023
  env: {
7854
8024
  FormData: platform.classes.FormData,
7855
- Blob: platform.classes.Blob
8025
+ Blob: platform.classes.Blob,
7856
8026
  },
7857
8027
 
7858
8028
  validateStatus: function validateStatus(status) {
@@ -7861,25 +8031,36 @@ function requireAxios () {
7861
8031
 
7862
8032
  headers: {
7863
8033
  common: {
7864
- 'Accept': 'application/json, text/plain, */*',
7865
- 'Content-Type': undefined
7866
- }
7867
- }
8034
+ Accept: 'application/json, text/plain, */*',
8035
+ 'Content-Type': undefined,
8036
+ },
8037
+ },
7868
8038
  };
7869
8039
 
7870
8040
  utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
7871
8041
  defaults.headers[method] = {};
7872
8042
  });
7873
8043
 
7874
- var defaults$1 = defaults;
7875
-
7876
8044
  // RawAxiosHeaders whose duplicates are ignored by node
7877
8045
  // c.f. https://nodejs.org/api/http.html#http_message_headers
7878
8046
  const ignoreDuplicateOf = utils$1.toObjectSet([
7879
- 'age', 'authorization', 'content-length', 'content-type', 'etag',
7880
- 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
7881
- 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
7882
- 'referer', 'retry-after', 'user-agent'
8047
+ 'age',
8048
+ 'authorization',
8049
+ 'content-length',
8050
+ 'content-type',
8051
+ 'etag',
8052
+ 'expires',
8053
+ 'from',
8054
+ 'host',
8055
+ 'if-modified-since',
8056
+ 'if-unmodified-since',
8057
+ 'last-modified',
8058
+ 'location',
8059
+ 'max-forwards',
8060
+ 'proxy-authorization',
8061
+ 'referer',
8062
+ 'retry-after',
8063
+ 'user-agent',
7883
8064
  ]);
7884
8065
 
7885
8066
  /**
@@ -7896,31 +8077,32 @@ function requireAxios () {
7896
8077
  *
7897
8078
  * @returns {Object} Headers parsed into an object
7898
8079
  */
7899
- var parseHeaders = rawHeaders => {
8080
+ var parseHeaders = (rawHeaders) => {
7900
8081
  const parsed = {};
7901
8082
  let key;
7902
8083
  let val;
7903
8084
  let i;
7904
8085
 
7905
- rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
7906
- i = line.indexOf(':');
7907
- key = line.substring(0, i).trim().toLowerCase();
7908
- val = line.substring(i + 1).trim();
8086
+ rawHeaders &&
8087
+ rawHeaders.split('\n').forEach(function parser(line) {
8088
+ i = line.indexOf(':');
8089
+ key = line.substring(0, i).trim().toLowerCase();
8090
+ val = line.substring(i + 1).trim();
7909
8091
 
7910
- if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
7911
- return;
7912
- }
8092
+ if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
8093
+ return;
8094
+ }
7913
8095
 
7914
- if (key === 'set-cookie') {
7915
- if (parsed[key]) {
7916
- parsed[key].push(val);
8096
+ if (key === 'set-cookie') {
8097
+ if (parsed[key]) {
8098
+ parsed[key].push(val);
8099
+ } else {
8100
+ parsed[key] = [val];
8101
+ }
7917
8102
  } else {
7918
- parsed[key] = [val];
8103
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
7919
8104
  }
7920
- } else {
7921
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
7922
- }
7923
- });
8105
+ });
7924
8106
 
7925
8107
  return parsed;
7926
8108
  };
@@ -7936,7 +8118,9 @@ function requireAxios () {
7936
8118
  return value;
7937
8119
  }
7938
8120
 
7939
- return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
8121
+ return utils$1.isArray(value)
8122
+ ? value.map(normalizeValue)
8123
+ : String(value).replace(/[\r\n]+$/, '');
7940
8124
  }
7941
8125
 
7942
8126
  function parseTokens(str) {
@@ -7974,8 +8158,10 @@ function requireAxios () {
7974
8158
  }
7975
8159
 
7976
8160
  function formatHeader(header) {
7977
- return header.trim()
7978
- .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
8161
+ return header
8162
+ .trim()
8163
+ .toLowerCase()
8164
+ .replace(/([a-z\d])(\w*)/g, (w, char, str) => {
7979
8165
  return char.toUpperCase() + str;
7980
8166
  });
7981
8167
  }
@@ -7983,12 +8169,12 @@ function requireAxios () {
7983
8169
  function buildAccessors(obj, header) {
7984
8170
  const accessorName = utils$1.toCamelCase(' ' + header);
7985
8171
 
7986
- ['get', 'set', 'has'].forEach(methodName => {
8172
+ ['get', 'set', 'has'].forEach((methodName) => {
7987
8173
  Object.defineProperty(obj, methodName + accessorName, {
7988
- value: function(arg1, arg2, arg3) {
8174
+ value: function (arg1, arg2, arg3) {
7989
8175
  return this[methodName].call(this, header, arg1, arg2, arg3);
7990
8176
  },
7991
- configurable: true
8177
+ configurable: true,
7992
8178
  });
7993
8179
  });
7994
8180
  }
@@ -8010,7 +8196,12 @@ function requireAxios () {
8010
8196
 
8011
8197
  const key = utils$1.findKey(self, lHeader);
8012
8198
 
8013
- if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
8199
+ if (
8200
+ !key ||
8201
+ self[key] === undefined ||
8202
+ _rewrite === true ||
8203
+ (_rewrite === undefined && self[key] !== false)
8204
+ ) {
8014
8205
  self[key || _header] = normalizeValue(_value);
8015
8206
  }
8016
8207
  }
@@ -8020,17 +8211,22 @@ function requireAxios () {
8020
8211
 
8021
8212
  if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
8022
8213
  setHeaders(header, valueOrRewrite);
8023
- } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
8214
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
8024
8215
  setHeaders(parseHeaders(header), valueOrRewrite);
8025
8216
  } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
8026
- let obj = {}, dest, key;
8217
+ let obj = {},
8218
+ dest,
8219
+ key;
8027
8220
  for (const entry of header) {
8028
8221
  if (!utils$1.isArray(entry)) {
8029
8222
  throw TypeError('Object iterator must return a key-value pair');
8030
8223
  }
8031
8224
 
8032
- obj[key = entry[0]] = (dest = obj[key]) ?
8033
- (utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1];
8225
+ obj[(key = entry[0])] = (dest = obj[key])
8226
+ ? utils$1.isArray(dest)
8227
+ ? [...dest, entry[1]]
8228
+ : [dest, entry[1]]
8229
+ : entry[1];
8034
8230
  }
8035
8231
 
8036
8232
  setHeaders(obj, valueOrRewrite);
@@ -8077,7 +8273,11 @@ function requireAxios () {
8077
8273
  if (header) {
8078
8274
  const key = utils$1.findKey(this, header);
8079
8275
 
8080
- return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
8276
+ return !!(
8277
+ key &&
8278
+ this[key] !== undefined &&
8279
+ (!matcher || matchHeaderValue(this, this[key], key, matcher))
8280
+ );
8081
8281
  }
8082
8282
 
8083
8283
  return false;
@@ -8117,7 +8317,7 @@ function requireAxios () {
8117
8317
 
8118
8318
  while (i--) {
8119
8319
  const key = keys[i];
8120
- if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
8320
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
8121
8321
  delete this[key];
8122
8322
  deleted = true;
8123
8323
  }
@@ -8161,7 +8361,9 @@ function requireAxios () {
8161
8361
  const obj = Object.create(null);
8162
8362
 
8163
8363
  utils$1.forEach(this, (value, header) => {
8164
- value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
8364
+ value != null &&
8365
+ value !== false &&
8366
+ (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
8165
8367
  });
8166
8368
 
8167
8369
  return obj;
@@ -8172,11 +8374,13 @@ function requireAxios () {
8172
8374
  }
8173
8375
 
8174
8376
  toString() {
8175
- return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
8377
+ return Object.entries(this.toJSON())
8378
+ .map(([header, value]) => header + ': ' + value)
8379
+ .join('\n');
8176
8380
  }
8177
8381
 
8178
8382
  getSetCookie() {
8179
- return this.get("set-cookie") || [];
8383
+ return this.get('set-cookie') || [];
8180
8384
  }
8181
8385
 
8182
8386
  get [Symbol.toStringTag]() {
@@ -8196,9 +8400,12 @@ function requireAxios () {
8196
8400
  }
8197
8401
 
8198
8402
  static accessor(header) {
8199
- const internals = this[$internals] = (this[$internals] = {
8200
- accessors: {}
8201
- });
8403
+ const internals =
8404
+ (this[$internals] =
8405
+ this[$internals] =
8406
+ {
8407
+ accessors: {},
8408
+ });
8202
8409
 
8203
8410
  const accessors = internals.accessors;
8204
8411
  const prototype = this.prototype;
@@ -8218,23 +8425,28 @@ function requireAxios () {
8218
8425
  }
8219
8426
  }
8220
8427
 
8221
- AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
8428
+ AxiosHeaders.accessor([
8429
+ 'Content-Type',
8430
+ 'Content-Length',
8431
+ 'Accept',
8432
+ 'Accept-Encoding',
8433
+ 'User-Agent',
8434
+ 'Authorization',
8435
+ ]);
8222
8436
 
8223
8437
  // reserved names hotfix
8224
- utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
8438
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
8225
8439
  let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
8226
8440
  return {
8227
8441
  get: () => value,
8228
8442
  set(headerValue) {
8229
8443
  this[mapped] = headerValue;
8230
- }
8231
- }
8444
+ },
8445
+ };
8232
8446
  });
8233
8447
 
8234
8448
  utils$1.freezeMethods(AxiosHeaders);
8235
8449
 
8236
- var AxiosHeaders$1 = AxiosHeaders;
8237
-
8238
8450
  /**
8239
8451
  * Transform the data for a request or a response
8240
8452
  *
@@ -8244,9 +8456,9 @@ function requireAxios () {
8244
8456
  * @returns {*} The resulting transformed data
8245
8457
  */
8246
8458
  function transformData(fns, response) {
8247
- const config = this || defaults$1;
8459
+ const config = this || defaults;
8248
8460
  const context = response || config;
8249
- const headers = AxiosHeaders$1.from(context.headers);
8461
+ const headers = AxiosHeaders.from(context.headers);
8250
8462
  let data = context.data;
8251
8463
 
8252
8464
  utils$1.forEach(fns, function transform(fn) {
@@ -8262,7 +8474,7 @@ function requireAxios () {
8262
8474
  return !!(value && value.__CANCEL__);
8263
8475
  }
8264
8476
 
8265
- class CanceledError extends AxiosError$1 {
8477
+ class CanceledError extends AxiosError {
8266
8478
  /**
8267
8479
  * A `CanceledError` is an object that is thrown when an operation is canceled.
8268
8480
  *
@@ -8273,14 +8485,12 @@ function requireAxios () {
8273
8485
  * @returns {CanceledError} The created error.
8274
8486
  */
8275
8487
  constructor(message, config, request) {
8276
- super(message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
8488
+ super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
8277
8489
  this.name = 'CanceledError';
8278
8490
  this.__CANCEL__ = true;
8279
8491
  }
8280
8492
  }
8281
8493
 
8282
- var CanceledError$1 = CanceledError;
8283
-
8284
8494
  /**
8285
8495
  * Resolve or reject a Promise based on response status.
8286
8496
  *
@@ -8295,19 +8505,23 @@ function requireAxios () {
8295
8505
  if (!response.status || !validateStatus || validateStatus(response.status)) {
8296
8506
  resolve(response);
8297
8507
  } else {
8298
- reject(new AxiosError$1(
8299
- 'Request failed with status code ' + response.status,
8300
- [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
8301
- response.config,
8302
- response.request,
8303
- response
8304
- ));
8508
+ reject(
8509
+ new AxiosError(
8510
+ 'Request failed with status code ' + response.status,
8511
+ [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][
8512
+ Math.floor(response.status / 100) - 4
8513
+ ],
8514
+ response.config,
8515
+ response.request,
8516
+ response
8517
+ )
8518
+ );
8305
8519
  }
8306
8520
  }
8307
8521
 
8308
8522
  function parseProtocol(url) {
8309
8523
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
8310
- return match && match[1] || '';
8524
+ return (match && match[1]) || '';
8311
8525
  }
8312
8526
 
8313
8527
  /**
@@ -8358,7 +8572,7 @@ function requireAxios () {
8358
8572
 
8359
8573
  const passed = startedAt && now - startedAt;
8360
8574
 
8361
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
8575
+ return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
8362
8576
  };
8363
8577
  }
8364
8578
 
@@ -8387,7 +8601,7 @@ function requireAxios () {
8387
8601
  const throttled = (...args) => {
8388
8602
  const now = Date.now();
8389
8603
  const passed = now - timestamp;
8390
- if ( passed >= threshold) {
8604
+ if (passed >= threshold) {
8391
8605
  invoke(args, now);
8392
8606
  } else {
8393
8607
  lastArgs = args;
@@ -8409,7 +8623,7 @@ function requireAxios () {
8409
8623
  let bytesNotified = 0;
8410
8624
  const _speedometer = speedometer(50, 250);
8411
8625
 
8412
- return throttle(e => {
8626
+ return throttle((e) => {
8413
8627
  const loaded = e.loaded;
8414
8628
  const total = e.lengthComputable ? e.total : undefined;
8415
8629
  const progressBytes = loaded - bytesNotified;
@@ -8421,13 +8635,13 @@ function requireAxios () {
8421
8635
  const data = {
8422
8636
  loaded,
8423
8637
  total,
8424
- progress: total ? (loaded / total) : undefined,
8638
+ progress: total ? loaded / total : undefined,
8425
8639
  bytes: progressBytes,
8426
8640
  rate: rate ? rate : undefined,
8427
8641
  estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
8428
8642
  event: e,
8429
8643
  lengthComputable: total != null,
8430
- [isDownloadStream ? 'download' : 'upload']: true
8644
+ [isDownloadStream ? 'download' : 'upload']: true,
8431
8645
  };
8432
8646
 
8433
8647
  listener(data);
@@ -8437,77 +8651,82 @@ function requireAxios () {
8437
8651
  const progressEventDecorator = (total, throttled) => {
8438
8652
  const lengthComputable = total != null;
8439
8653
 
8440
- return [(loaded) => throttled[0]({
8441
- lengthComputable,
8442
- total,
8443
- loaded
8444
- }), throttled[1]];
8654
+ return [
8655
+ (loaded) =>
8656
+ throttled[0]({
8657
+ lengthComputable,
8658
+ total,
8659
+ loaded,
8660
+ }),
8661
+ throttled[1],
8662
+ ];
8445
8663
  };
8446
8664
 
8447
- const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
8665
+ const asyncDecorator =
8666
+ (fn) =>
8667
+ (...args) =>
8668
+ utils$1.asap(() => fn(...args));
8448
8669
 
8449
- var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
8450
- url = new URL(url, platform.origin);
8670
+ var isURLSameOrigin = platform.hasStandardBrowserEnv
8671
+ ? ((origin, isMSIE) => (url) => {
8672
+ url = new URL(url, platform.origin);
8451
8673
 
8452
- return (
8453
- origin.protocol === url.protocol &&
8454
- origin.host === url.host &&
8455
- (isMSIE || origin.port === url.port)
8456
- );
8457
- })(
8458
- new URL(platform.origin),
8459
- platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
8460
- ) : () => true;
8461
-
8462
- var cookies = platform.hasStandardBrowserEnv ?
8674
+ return (
8675
+ origin.protocol === url.protocol &&
8676
+ origin.host === url.host &&
8677
+ (isMSIE || origin.port === url.port)
8678
+ );
8679
+ })(
8680
+ new URL(platform.origin),
8681
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
8682
+ )
8683
+ : () => true;
8463
8684
 
8464
- // Standard browser envs support document.cookie
8465
- {
8466
- write(name, value, expires, path, domain, secure, sameSite) {
8467
- if (typeof document === 'undefined') return;
8685
+ var cookies = platform.hasStandardBrowserEnv
8686
+ ? // Standard browser envs support document.cookie
8687
+ {
8688
+ write(name, value, expires, path, domain, secure, sameSite) {
8689
+ if (typeof document === 'undefined') return;
8468
8690
 
8469
- const cookie = [`${name}=${encodeURIComponent(value)}`];
8691
+ const cookie = [`${name}=${encodeURIComponent(value)}`];
8470
8692
 
8471
- if (utils$1.isNumber(expires)) {
8472
- cookie.push(`expires=${new Date(expires).toUTCString()}`);
8473
- }
8474
- if (utils$1.isString(path)) {
8475
- cookie.push(`path=${path}`);
8476
- }
8477
- if (utils$1.isString(domain)) {
8478
- cookie.push(`domain=${domain}`);
8479
- }
8480
- if (secure === true) {
8481
- cookie.push('secure');
8482
- }
8483
- if (utils$1.isString(sameSite)) {
8484
- cookie.push(`SameSite=${sameSite}`);
8485
- }
8693
+ if (utils$1.isNumber(expires)) {
8694
+ cookie.push(`expires=${new Date(expires).toUTCString()}`);
8695
+ }
8696
+ if (utils$1.isString(path)) {
8697
+ cookie.push(`path=${path}`);
8698
+ }
8699
+ if (utils$1.isString(domain)) {
8700
+ cookie.push(`domain=${domain}`);
8701
+ }
8702
+ if (secure === true) {
8703
+ cookie.push('secure');
8704
+ }
8705
+ if (utils$1.isString(sameSite)) {
8706
+ cookie.push(`SameSite=${sameSite}`);
8707
+ }
8486
8708
 
8487
- document.cookie = cookie.join('; ');
8488
- },
8709
+ document.cookie = cookie.join('; ');
8710
+ },
8489
8711
 
8490
- read(name) {
8491
- if (typeof document === 'undefined') return null;
8492
- const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
8493
- return match ? decodeURIComponent(match[1]) : null;
8494
- },
8712
+ read(name) {
8713
+ if (typeof document === 'undefined') return null;
8714
+ const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
8715
+ return match ? decodeURIComponent(match[1]) : null;
8716
+ },
8495
8717
 
8496
- remove(name) {
8497
- this.write(name, '', Date.now() - 86400000, '/');
8718
+ remove(name) {
8719
+ this.write(name, '', Date.now() - 86400000, '/');
8720
+ },
8498
8721
  }
8499
- }
8500
-
8501
- :
8502
-
8503
- // Non-standard browser env (web workers, react-native) lack needed support.
8504
- {
8505
- write() {},
8506
- read() {
8507
- return null;
8508
- },
8509
- remove() {}
8510
- };
8722
+ : // Non-standard browser env (web workers, react-native) lack needed support.
8723
+ {
8724
+ write() {},
8725
+ read() {
8726
+ return null;
8727
+ },
8728
+ remove() {},
8729
+ };
8511
8730
 
8512
8731
  /**
8513
8732
  * Determines whether the specified URL is absolute
@@ -8520,6 +8739,10 @@ function requireAxios () {
8520
8739
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
8521
8740
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
8522
8741
  // by any combination of letters, digits, plus, period, or hyphen.
8742
+ if (typeof url !== 'string') {
8743
+ return false;
8744
+ }
8745
+
8523
8746
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
8524
8747
  }
8525
8748
 
@@ -8555,7 +8778,7 @@ function requireAxios () {
8555
8778
  return requestedURL;
8556
8779
  }
8557
8780
 
8558
- const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
8781
+ const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing);
8559
8782
 
8560
8783
  /**
8561
8784
  * Config-specific merge-function which creates a new config-object
@@ -8644,11 +8867,13 @@ function requireAxios () {
8644
8867
  socketPath: defaultToConfig2,
8645
8868
  responseEncoding: defaultToConfig2,
8646
8869
  validateStatus: mergeDirectKeys,
8647
- headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
8870
+ headers: (a, b, prop) =>
8871
+ mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
8648
8872
  };
8649
8873
 
8650
8874
  utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
8651
- const merge = mergeMap[prop] || mergeDeepProperties;
8875
+ if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
8876
+ const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
8652
8877
  const configValue = merge(config1[prop], config2[prop], prop);
8653
8878
  (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
8654
8879
  });
@@ -8661,14 +8886,24 @@ function requireAxios () {
8661
8886
 
8662
8887
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
8663
8888
 
8664
- newConfig.headers = headers = AxiosHeaders$1.from(headers);
8889
+ newConfig.headers = headers = AxiosHeaders.from(headers);
8665
8890
 
8666
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
8891
+ newConfig.url = buildURL(
8892
+ buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls),
8893
+ config.params,
8894
+ config.paramsSerializer
8895
+ );
8667
8896
 
8668
8897
  // HTTP basic authentication
8669
8898
  if (auth) {
8670
- headers.set('Authorization', 'Basic ' +
8671
- btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
8899
+ headers.set(
8900
+ 'Authorization',
8901
+ 'Basic ' +
8902
+ btoa(
8903
+ (auth.username || '') +
8904
+ ':' +
8905
+ (auth.password ? unescape(encodeURIComponent(auth.password)) : '')
8906
+ )
8672
8907
  );
8673
8908
  }
8674
8909
 
@@ -8686,7 +8921,7 @@ function requireAxios () {
8686
8921
  }
8687
8922
  });
8688
8923
  }
8689
- }
8924
+ }
8690
8925
 
8691
8926
  // Add xsrf header
8692
8927
  // This is only done if running in a standard browser environment.
@@ -8710,196 +8945,218 @@ function requireAxios () {
8710
8945
 
8711
8946
  const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
8712
8947
 
8713
- var xhrAdapter = isXHRAdapterSupported && function (config) {
8714
- return new Promise(function dispatchXhrRequest(resolve, reject) {
8715
- const _config = resolveConfig(config);
8716
- let requestData = _config.data;
8717
- const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
8718
- let {responseType, onUploadProgress, onDownloadProgress} = _config;
8719
- let onCanceled;
8720
- let uploadThrottled, downloadThrottled;
8721
- let flushUpload, flushDownload;
8948
+ var xhrAdapter = isXHRAdapterSupported &&
8949
+ function (config) {
8950
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
8951
+ const _config = resolveConfig(config);
8952
+ let requestData = _config.data;
8953
+ const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
8954
+ let { responseType, onUploadProgress, onDownloadProgress } = _config;
8955
+ let onCanceled;
8956
+ let uploadThrottled, downloadThrottled;
8957
+ let flushUpload, flushDownload;
8722
8958
 
8723
- function done() {
8724
- flushUpload && flushUpload(); // flush events
8725
- flushDownload && flushDownload(); // flush events
8959
+ function done() {
8960
+ flushUpload && flushUpload(); // flush events
8961
+ flushDownload && flushDownload(); // flush events
8726
8962
 
8727
- _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
8963
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
8728
8964
 
8729
- _config.signal && _config.signal.removeEventListener('abort', onCanceled);
8730
- }
8965
+ _config.signal && _config.signal.removeEventListener('abort', onCanceled);
8966
+ }
8731
8967
 
8732
- let request = new XMLHttpRequest();
8968
+ let request = new XMLHttpRequest();
8733
8969
 
8734
- request.open(_config.method.toUpperCase(), _config.url, true);
8970
+ request.open(_config.method.toUpperCase(), _config.url, true);
8735
8971
 
8736
- // Set the request timeout in MS
8737
- request.timeout = _config.timeout;
8972
+ // Set the request timeout in MS
8973
+ request.timeout = _config.timeout;
8738
8974
 
8739
- function onloadend() {
8740
- if (!request) {
8741
- return;
8975
+ function onloadend() {
8976
+ if (!request) {
8977
+ return;
8978
+ }
8979
+ // Prepare the response
8980
+ const responseHeaders = AxiosHeaders.from(
8981
+ 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
8982
+ );
8983
+ const responseData =
8984
+ !responseType || responseType === 'text' || responseType === 'json'
8985
+ ? request.responseText
8986
+ : request.response;
8987
+ const response = {
8988
+ data: responseData,
8989
+ status: request.status,
8990
+ statusText: request.statusText,
8991
+ headers: responseHeaders,
8992
+ config,
8993
+ request,
8994
+ };
8995
+
8996
+ settle(
8997
+ function _resolve(value) {
8998
+ resolve(value);
8999
+ done();
9000
+ },
9001
+ function _reject(err) {
9002
+ reject(err);
9003
+ done();
9004
+ },
9005
+ response
9006
+ );
9007
+
9008
+ // Clean up request
9009
+ request = null;
8742
9010
  }
8743
- // Prepare the response
8744
- const responseHeaders = AxiosHeaders$1.from(
8745
- 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
8746
- );
8747
- const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
8748
- request.responseText : request.response;
8749
- const response = {
8750
- data: responseData,
8751
- status: request.status,
8752
- statusText: request.statusText,
8753
- headers: responseHeaders,
8754
- config,
8755
- request
8756
- };
8757
9011
 
8758
- settle(function _resolve(value) {
8759
- resolve(value);
8760
- done();
8761
- }, function _reject(err) {
8762
- reject(err);
8763
- done();
8764
- }, response);
9012
+ if ('onloadend' in request) {
9013
+ // Use onloadend if available
9014
+ request.onloadend = onloadend;
9015
+ } else {
9016
+ // Listen for ready state to emulate onloadend
9017
+ request.onreadystatechange = function handleLoad() {
9018
+ if (!request || request.readyState !== 4) {
9019
+ return;
9020
+ }
8765
9021
 
8766
- // Clean up request
8767
- request = null;
8768
- }
9022
+ // The request errored out and we didn't get a response, this will be
9023
+ // handled by onerror instead
9024
+ // With one exception: request that using file: protocol, most browsers
9025
+ // will return status as 0 even though it's a successful request
9026
+ if (
9027
+ request.status === 0 &&
9028
+ !(request.responseURL && request.responseURL.indexOf('file:') === 0)
9029
+ ) {
9030
+ return;
9031
+ }
9032
+ // readystate handler is calling before onerror or ontimeout handlers,
9033
+ // so we should call onloadend on the next 'tick'
9034
+ setTimeout(onloadend);
9035
+ };
9036
+ }
8769
9037
 
8770
- if ('onloadend' in request) {
8771
- // Use onloadend if available
8772
- request.onloadend = onloadend;
8773
- } else {
8774
- // Listen for ready state to emulate onloadend
8775
- request.onreadystatechange = function handleLoad() {
8776
- if (!request || request.readyState !== 4) {
9038
+ // Handle browser request cancellation (as opposed to a manual cancellation)
9039
+ request.onabort = function handleAbort() {
9040
+ if (!request) {
8777
9041
  return;
8778
9042
  }
8779
9043
 
8780
- // The request errored out and we didn't get a response, this will be
8781
- // handled by onerror instead
8782
- // With one exception: request that using file: protocol, most browsers
8783
- // will return status as 0 even though it's a successful request
8784
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
8785
- return;
8786
- }
8787
- // readystate handler is calling before onerror or ontimeout handlers,
8788
- // so we should call onloadend on the next 'tick'
8789
- setTimeout(onloadend);
9044
+ reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
9045
+
9046
+ // Clean up request
9047
+ request = null;
8790
9048
  };
8791
- }
8792
9049
 
8793
- // Handle browser request cancellation (as opposed to a manual cancellation)
8794
- request.onabort = function handleAbort() {
8795
- if (!request) {
8796
- return;
8797
- }
9050
+ // Handle low level network errors
9051
+ request.onerror = function handleError(event) {
9052
+ // Browsers deliver a ProgressEvent in XHR onerror
9053
+ // (message may be empty; when present, surface it)
9054
+ // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
9055
+ const msg = event && event.message ? event.message : 'Network Error';
9056
+ const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
9057
+ // attach the underlying event for consumers who want details
9058
+ err.event = event || null;
9059
+ reject(err);
9060
+ request = null;
9061
+ };
8798
9062
 
8799
- reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
9063
+ // Handle timeout
9064
+ request.ontimeout = function handleTimeout() {
9065
+ let timeoutErrorMessage = _config.timeout
9066
+ ? 'timeout of ' + _config.timeout + 'ms exceeded'
9067
+ : 'timeout exceeded';
9068
+ const transitional = _config.transitional || transitionalDefaults;
9069
+ if (_config.timeoutErrorMessage) {
9070
+ timeoutErrorMessage = _config.timeoutErrorMessage;
9071
+ }
9072
+ reject(
9073
+ new AxiosError(
9074
+ timeoutErrorMessage,
9075
+ transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
9076
+ config,
9077
+ request
9078
+ )
9079
+ );
8800
9080
 
8801
- // Clean up request
8802
- request = null;
8803
- };
9081
+ // Clean up request
9082
+ request = null;
9083
+ };
8804
9084
 
8805
- // Handle low level network errors
8806
- request.onerror = function handleError(event) {
8807
- // Browsers deliver a ProgressEvent in XHR onerror
8808
- // (message may be empty; when present, surface it)
8809
- // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
8810
- const msg = event && event.message ? event.message : 'Network Error';
8811
- const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request);
8812
- // attach the underlying event for consumers who want details
8813
- err.event = event || null;
8814
- reject(err);
8815
- request = null;
8816
- };
8817
-
8818
- // Handle timeout
8819
- request.ontimeout = function handleTimeout() {
8820
- let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
8821
- const transitional = _config.transitional || transitionalDefaults;
8822
- if (_config.timeoutErrorMessage) {
8823
- timeoutErrorMessage = _config.timeoutErrorMessage;
8824
- }
8825
- reject(new AxiosError$1(
8826
- timeoutErrorMessage,
8827
- transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
8828
- config,
8829
- request));
8830
-
8831
- // Clean up request
8832
- request = null;
8833
- };
9085
+ // Remove Content-Type if data is undefined
9086
+ requestData === undefined && requestHeaders.setContentType(null);
8834
9087
 
8835
- // Remove Content-Type if data is undefined
8836
- requestData === undefined && requestHeaders.setContentType(null);
9088
+ // Add headers to the request
9089
+ if ('setRequestHeader' in request) {
9090
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
9091
+ request.setRequestHeader(key, val);
9092
+ });
9093
+ }
8837
9094
 
8838
- // Add headers to the request
8839
- if ('setRequestHeader' in request) {
8840
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
8841
- request.setRequestHeader(key, val);
8842
- });
8843
- }
9095
+ // Add withCredentials to request if needed
9096
+ if (!utils$1.isUndefined(_config.withCredentials)) {
9097
+ request.withCredentials = !!_config.withCredentials;
9098
+ }
8844
9099
 
8845
- // Add withCredentials to request if needed
8846
- if (!utils$1.isUndefined(_config.withCredentials)) {
8847
- request.withCredentials = !!_config.withCredentials;
8848
- }
9100
+ // Add responseType to request if needed
9101
+ if (responseType && responseType !== 'json') {
9102
+ request.responseType = _config.responseType;
9103
+ }
8849
9104
 
8850
- // Add responseType to request if needed
8851
- if (responseType && responseType !== 'json') {
8852
- request.responseType = _config.responseType;
8853
- }
9105
+ // Handle progress if needed
9106
+ if (onDownloadProgress) {
9107
+ [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
9108
+ request.addEventListener('progress', downloadThrottled);
9109
+ }
8854
9110
 
8855
- // Handle progress if needed
8856
- if (onDownloadProgress) {
8857
- ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
8858
- request.addEventListener('progress', downloadThrottled);
8859
- }
9111
+ // Not all browsers support upload events
9112
+ if (onUploadProgress && request.upload) {
9113
+ [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
8860
9114
 
8861
- // Not all browsers support upload events
8862
- if (onUploadProgress && request.upload) {
8863
- ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
9115
+ request.upload.addEventListener('progress', uploadThrottled);
8864
9116
 
8865
- request.upload.addEventListener('progress', uploadThrottled);
9117
+ request.upload.addEventListener('loadend', flushUpload);
9118
+ }
8866
9119
 
8867
- request.upload.addEventListener('loadend', flushUpload);
8868
- }
9120
+ if (_config.cancelToken || _config.signal) {
9121
+ // Handle cancellation
9122
+ // eslint-disable-next-line func-names
9123
+ onCanceled = (cancel) => {
9124
+ if (!request) {
9125
+ return;
9126
+ }
9127
+ reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
9128
+ request.abort();
9129
+ request = null;
9130
+ };
8869
9131
 
8870
- if (_config.cancelToken || _config.signal) {
8871
- // Handle cancellation
8872
- // eslint-disable-next-line func-names
8873
- onCanceled = cancel => {
8874
- if (!request) {
8875
- return;
9132
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
9133
+ if (_config.signal) {
9134
+ _config.signal.aborted
9135
+ ? onCanceled()
9136
+ : _config.signal.addEventListener('abort', onCanceled);
8876
9137
  }
8877
- reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
8878
- request.abort();
8879
- request = null;
8880
- };
8881
-
8882
- _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
8883
- if (_config.signal) {
8884
- _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
8885
9138
  }
8886
- }
8887
9139
 
8888
- const protocol = parseProtocol(_config.url);
8889
-
8890
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
8891
- reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
8892
- return;
8893
- }
9140
+ const protocol = parseProtocol(_config.url);
8894
9141
 
9142
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
9143
+ reject(
9144
+ new AxiosError(
9145
+ 'Unsupported protocol ' + protocol + ':',
9146
+ AxiosError.ERR_BAD_REQUEST,
9147
+ config
9148
+ )
9149
+ );
9150
+ return;
9151
+ }
8895
9152
 
8896
- // Send the request
8897
- request.send(requestData || null);
8898
- });
8899
- };
9153
+ // Send the request
9154
+ request.send(requestData || null);
9155
+ });
9156
+ };
8900
9157
 
8901
9158
  const composeSignals = (signals, timeout) => {
8902
- const {length} = (signals = signals ? signals.filter(Boolean) : []);
9159
+ const { length } = (signals = signals ? signals.filter(Boolean) : []);
8903
9160
 
8904
9161
  if (timeout || length) {
8905
9162
  let controller = new AbortController();
@@ -8911,21 +9168,29 @@ function requireAxios () {
8911
9168
  aborted = true;
8912
9169
  unsubscribe();
8913
9170
  const err = reason instanceof Error ? reason : this.reason;
8914
- controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
9171
+ controller.abort(
9172
+ err instanceof AxiosError
9173
+ ? err
9174
+ : new CanceledError(err instanceof Error ? err.message : err)
9175
+ );
8915
9176
  }
8916
9177
  };
8917
9178
 
8918
- let timer = timeout && setTimeout(() => {
8919
- timer = null;
8920
- onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT));
8921
- }, timeout);
9179
+ let timer =
9180
+ timeout &&
9181
+ setTimeout(() => {
9182
+ timer = null;
9183
+ onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
9184
+ }, timeout);
8922
9185
 
8923
9186
  const unsubscribe = () => {
8924
9187
  if (signals) {
8925
9188
  timer && clearTimeout(timer);
8926
9189
  timer = null;
8927
- signals.forEach(signal => {
8928
- signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
9190
+ signals.forEach((signal) => {
9191
+ signal.unsubscribe
9192
+ ? signal.unsubscribe(onabort)
9193
+ : signal.removeEventListener('abort', onabort);
8929
9194
  });
8930
9195
  signals = null;
8931
9196
  }
@@ -8933,7 +9198,7 @@ function requireAxios () {
8933
9198
 
8934
9199
  signals.forEach((signal) => signal.addEventListener('abort', onabort));
8935
9200
 
8936
- const {signal} = controller;
9201
+ const { signal } = controller;
8937
9202
 
8938
9203
  signal.unsubscribe = () => utils$1.asap(unsubscribe);
8939
9204
 
@@ -8941,8 +9206,6 @@ function requireAxios () {
8941
9206
  }
8942
9207
  };
8943
9208
 
8944
- var composeSignals$1 = composeSignals;
8945
-
8946
9209
  const streamChunk = function* (chunk, chunkSize) {
8947
9210
  let len = chunk.byteLength;
8948
9211
 
@@ -8976,7 +9239,7 @@ function requireAxios () {
8976
9239
  const reader = stream.getReader();
8977
9240
  try {
8978
9241
  for (;;) {
8979
- const {done, value} = await reader.read();
9242
+ const { done, value } = await reader.read();
8980
9243
  if (done) {
8981
9244
  break;
8982
9245
  }
@@ -8999,64 +9262,69 @@ function requireAxios () {
8999
9262
  }
9000
9263
  };
9001
9264
 
9002
- return new ReadableStream({
9003
- async pull(controller) {
9004
- try {
9005
- const {done, value} = await iterator.next();
9265
+ return new ReadableStream(
9266
+ {
9267
+ async pull(controller) {
9268
+ try {
9269
+ const { done, value } = await iterator.next();
9006
9270
 
9007
- if (done) {
9008
- _onFinish();
9009
- controller.close();
9010
- return;
9011
- }
9271
+ if (done) {
9272
+ _onFinish();
9273
+ controller.close();
9274
+ return;
9275
+ }
9012
9276
 
9013
- let len = value.byteLength;
9014
- if (onProgress) {
9015
- let loadedBytes = bytes += len;
9016
- onProgress(loadedBytes);
9277
+ let len = value.byteLength;
9278
+ if (onProgress) {
9279
+ let loadedBytes = (bytes += len);
9280
+ onProgress(loadedBytes);
9281
+ }
9282
+ controller.enqueue(new Uint8Array(value));
9283
+ } catch (err) {
9284
+ _onFinish(err);
9285
+ throw err;
9017
9286
  }
9018
- controller.enqueue(new Uint8Array(value));
9019
- } catch (err) {
9020
- _onFinish(err);
9021
- throw err;
9022
- }
9287
+ },
9288
+ cancel(reason) {
9289
+ _onFinish(reason);
9290
+ return iterator.return();
9291
+ },
9023
9292
  },
9024
- cancel(reason) {
9025
- _onFinish(reason);
9026
- return iterator.return();
9293
+ {
9294
+ highWaterMark: 2,
9027
9295
  }
9028
- }, {
9029
- highWaterMark: 2
9030
- })
9296
+ );
9031
9297
  };
9032
9298
 
9033
9299
  const DEFAULT_CHUNK_SIZE = 64 * 1024;
9034
9300
 
9035
- const {isFunction} = utils$1;
9301
+ const { isFunction } = utils$1;
9036
9302
 
9037
- const globalFetchAPI = (({Request, Response}) => ({
9038
- Request, Response
9303
+ const globalFetchAPI = (({ Request, Response }) => ({
9304
+ Request,
9305
+ Response,
9039
9306
  }))(utils$1.global);
9040
9307
 
9041
- const {
9042
- ReadableStream: ReadableStream$1, TextEncoder
9043
- } = utils$1.global;
9044
-
9308
+ const { ReadableStream: ReadableStream$1, TextEncoder } = utils$1.global;
9045
9309
 
9046
9310
  const test = (fn, ...args) => {
9047
9311
  try {
9048
9312
  return !!fn(...args);
9049
9313
  } catch (e) {
9050
- return false
9314
+ return false;
9051
9315
  }
9052
9316
  };
9053
9317
 
9054
9318
  const factory = (env) => {
9055
- env = utils$1.merge.call({
9056
- skipUndefined: true
9057
- }, globalFetchAPI, env);
9319
+ env = utils$1.merge.call(
9320
+ {
9321
+ skipUndefined: true,
9322
+ },
9323
+ globalFetchAPI,
9324
+ env
9325
+ );
9058
9326
 
9059
- const {fetch: envFetch, Request, Response} = env;
9327
+ const { fetch: envFetch, Request, Response } = env;
9060
9328
  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
9061
9329
  const isRequestSupported = isFunction(Request);
9062
9330
  const isResponseSupported = isFunction(Response);
@@ -9067,46 +9335,65 @@ function requireAxios () {
9067
9335
 
9068
9336
  const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
9069
9337
 
9070
- const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
9071
- ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
9072
- async (str) => new Uint8Array(await new Request(str).arrayBuffer())
9073
- );
9338
+ const encodeText =
9339
+ isFetchSupported &&
9340
+ (typeof TextEncoder === 'function'
9341
+ ? (
9342
+ (encoder) => (str) =>
9343
+ encoder.encode(str)
9344
+ )(new TextEncoder())
9345
+ : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
9074
9346
 
9075
- const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
9076
- let duplexAccessed = false;
9347
+ const supportsRequestStream =
9348
+ isRequestSupported &&
9349
+ isReadableStreamSupported &&
9350
+ test(() => {
9351
+ let duplexAccessed = false;
9077
9352
 
9078
- const hasContentType = new Request(platform.origin, {
9079
- body: new ReadableStream$1(),
9080
- method: 'POST',
9081
- get duplex() {
9082
- duplexAccessed = true;
9083
- return 'half';
9084
- },
9085
- }).headers.has('Content-Type');
9353
+ const body = new ReadableStream$1();
9086
9354
 
9087
- return duplexAccessed && !hasContentType;
9088
- });
9355
+ const hasContentType = new Request(platform.origin, {
9356
+ body,
9357
+ method: 'POST',
9358
+ get duplex() {
9359
+ duplexAccessed = true;
9360
+ return 'half';
9361
+ },
9362
+ }).headers.has('Content-Type');
9363
+
9364
+ body.cancel();
9365
+
9366
+ return duplexAccessed && !hasContentType;
9367
+ });
9089
9368
 
9090
- const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
9369
+ const supportsResponseStream =
9370
+ isResponseSupported &&
9371
+ isReadableStreamSupported &&
9091
9372
  test(() => utils$1.isReadableStream(new Response('').body));
9092
9373
 
9093
9374
  const resolvers = {
9094
- stream: supportsResponseStream && ((res) => res.body)
9375
+ stream: supportsResponseStream && ((res) => res.body),
9095
9376
  };
9096
9377
 
9097
- isFetchSupported && ((() => {
9098
- ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
9099
- !resolvers[type] && (resolvers[type] = (res, config) => {
9100
- let method = res && res[type];
9101
-
9102
- if (method) {
9103
- return method.call(res);
9104
- }
9105
-
9106
- throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
9378
+ isFetchSupported &&
9379
+ (() => {
9380
+ ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
9381
+ !resolvers[type] &&
9382
+ (resolvers[type] = (res, config) => {
9383
+ let method = res && res[type];
9384
+
9385
+ if (method) {
9386
+ return method.call(res);
9387
+ }
9388
+
9389
+ throw new AxiosError(
9390
+ `Response type '${type}' is not supported`,
9391
+ AxiosError.ERR_NOT_SUPPORT,
9392
+ config
9393
+ );
9394
+ });
9107
9395
  });
9108
- });
9109
- })());
9396
+ })();
9110
9397
 
9111
9398
  const getBodyLength = async (body) => {
9112
9399
  if (body == null) {
@@ -9157,32 +9444,41 @@ function requireAxios () {
9157
9444
  responseType,
9158
9445
  headers,
9159
9446
  withCredentials = 'same-origin',
9160
- fetchOptions
9447
+ fetchOptions,
9161
9448
  } = resolveConfig(config);
9162
9449
 
9163
9450
  let _fetch = envFetch || fetch;
9164
9451
 
9165
9452
  responseType = responseType ? (responseType + '').toLowerCase() : 'text';
9166
9453
 
9167
- let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
9454
+ let composedSignal = composeSignals(
9455
+ [signal, cancelToken && cancelToken.toAbortSignal()],
9456
+ timeout
9457
+ );
9168
9458
 
9169
9459
  let request = null;
9170
9460
 
9171
- const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
9172
- composedSignal.unsubscribe();
9173
- });
9461
+ const unsubscribe =
9462
+ composedSignal &&
9463
+ composedSignal.unsubscribe &&
9464
+ (() => {
9465
+ composedSignal.unsubscribe();
9466
+ });
9174
9467
 
9175
9468
  let requestContentLength;
9176
9469
 
9177
9470
  try {
9178
9471
  if (
9179
- onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
9472
+ onUploadProgress &&
9473
+ supportsRequestStream &&
9474
+ method !== 'get' &&
9475
+ method !== 'head' &&
9180
9476
  (requestContentLength = await resolveBodyLength(headers, data)) !== 0
9181
9477
  ) {
9182
9478
  let _request = new Request(url, {
9183
9479
  method: 'POST',
9184
9480
  body: data,
9185
- duplex: "half"
9481
+ duplex: 'half',
9186
9482
  });
9187
9483
 
9188
9484
  let contentTypeHeader;
@@ -9207,7 +9503,7 @@ function requireAxios () {
9207
9503
 
9208
9504
  // Cloudflare Workers throws when credentials are defined
9209
9505
  // see https://github.com/cloudflare/workerd/issues/902
9210
- const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
9506
+ const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
9211
9507
 
9212
9508
  const resolvedOptions = {
9213
9509
  ...fetchOptions,
@@ -9215,29 +9511,35 @@ function requireAxios () {
9215
9511
  method: method.toUpperCase(),
9216
9512
  headers: headers.normalize().toJSON(),
9217
9513
  body: data,
9218
- duplex: "half",
9219
- credentials: isCredentialsSupported ? withCredentials : undefined
9514
+ duplex: 'half',
9515
+ credentials: isCredentialsSupported ? withCredentials : undefined,
9220
9516
  };
9221
9517
 
9222
9518
  request = isRequestSupported && new Request(url, resolvedOptions);
9223
9519
 
9224
- let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
9520
+ let response = await (isRequestSupported
9521
+ ? _fetch(request, fetchOptions)
9522
+ : _fetch(url, resolvedOptions));
9225
9523
 
9226
- const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
9524
+ const isStreamResponse =
9525
+ supportsResponseStream && (responseType === 'stream' || responseType === 'response');
9227
9526
 
9228
9527
  if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
9229
9528
  const options = {};
9230
9529
 
9231
- ['status', 'statusText', 'headers'].forEach(prop => {
9530
+ ['status', 'statusText', 'headers'].forEach((prop) => {
9232
9531
  options[prop] = response[prop];
9233
9532
  });
9234
9533
 
9235
9534
  const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
9236
9535
 
9237
- const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
9238
- responseContentLength,
9239
- progressEventReducer(asyncDecorator(onDownloadProgress), true)
9240
- ) || [];
9536
+ const [onProgress, flush] =
9537
+ (onDownloadProgress &&
9538
+ progressEventDecorator(
9539
+ responseContentLength,
9540
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
9541
+ )) ||
9542
+ [];
9241
9543
 
9242
9544
  response = new Response(
9243
9545
  trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
@@ -9250,54 +9552,64 @@ function requireAxios () {
9250
9552
 
9251
9553
  responseType = responseType || 'text';
9252
9554
 
9253
- let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
9555
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](
9556
+ response,
9557
+ config
9558
+ );
9254
9559
 
9255
9560
  !isStreamResponse && unsubscribe && unsubscribe();
9256
9561
 
9257
9562
  return await new Promise((resolve, reject) => {
9258
9563
  settle(resolve, reject, {
9259
9564
  data: responseData,
9260
- headers: AxiosHeaders$1.from(response.headers),
9565
+ headers: AxiosHeaders.from(response.headers),
9261
9566
  status: response.status,
9262
9567
  statusText: response.statusText,
9263
9568
  config,
9264
- request
9569
+ request,
9265
9570
  });
9266
- })
9571
+ });
9267
9572
  } catch (err) {
9268
9573
  unsubscribe && unsubscribe();
9269
9574
 
9270
9575
  if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
9271
9576
  throw Object.assign(
9272
- new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request),
9577
+ new AxiosError(
9578
+ 'Network Error',
9579
+ AxiosError.ERR_NETWORK,
9580
+ config,
9581
+ request,
9582
+ err && err.response
9583
+ ),
9273
9584
  {
9274
- cause: err.cause || err
9585
+ cause: err.cause || err,
9275
9586
  }
9276
- )
9587
+ );
9277
9588
  }
9278
9589
 
9279
- throw AxiosError$1.from(err, err && err.code, config, request);
9590
+ throw AxiosError.from(err, err && err.code, config, request, err && err.response);
9280
9591
  }
9281
- }
9592
+ };
9282
9593
  };
9283
9594
 
9284
9595
  const seedCache = new Map();
9285
9596
 
9286
9597
  const getFetch = (config) => {
9287
9598
  let env = (config && config.env) || {};
9288
- const {fetch, Request, Response} = env;
9289
- const seeds = [
9290
- Request, Response, fetch
9291
- ];
9599
+ const { fetch, Request, Response } = env;
9600
+ const seeds = [Request, Response, fetch];
9292
9601
 
9293
- let len = seeds.length, i = len,
9294
- seed, target, map = seedCache;
9602
+ let len = seeds.length,
9603
+ i = len,
9604
+ seed,
9605
+ target,
9606
+ map = seedCache;
9295
9607
 
9296
9608
  while (i--) {
9297
9609
  seed = seeds[i];
9298
9610
  target = map.get(seed);
9299
9611
 
9300
- target === undefined && map.set(seed, target = (i ? new Map() : factory(env)));
9612
+ target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
9301
9613
 
9302
9614
  map = target;
9303
9615
  }
@@ -9313,7 +9625,7 @@ function requireAxios () {
9313
9625
  * - `http` for Node.js
9314
9626
  * - `xhr` for browsers
9315
9627
  * - `fetch` for fetch API-based requests
9316
- *
9628
+ *
9317
9629
  * @type {Object<string, Function|Object>}
9318
9630
  */
9319
9631
  const knownAdapters = {
@@ -9321,7 +9633,7 @@ function requireAxios () {
9321
9633
  xhr: xhrAdapter,
9322
9634
  fetch: {
9323
9635
  get: getFetch,
9324
- }
9636
+ },
9325
9637
  };
9326
9638
 
9327
9639
  // Assign adapter names for easier debugging and identification
@@ -9338,7 +9650,7 @@ function requireAxios () {
9338
9650
 
9339
9651
  /**
9340
9652
  * Render a rejection reason string for unknown or unsupported adapters
9341
- *
9653
+ *
9342
9654
  * @param {string} reason
9343
9655
  * @returns {string}
9344
9656
  */
@@ -9346,17 +9658,18 @@ function requireAxios () {
9346
9658
 
9347
9659
  /**
9348
9660
  * Check if the adapter is resolved (function, null, or false)
9349
- *
9661
+ *
9350
9662
  * @param {Function|null|false} adapter
9351
9663
  * @returns {boolean}
9352
9664
  */
9353
- const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
9665
+ const isResolvedHandle = (adapter) =>
9666
+ utils$1.isFunction(adapter) || adapter === null || adapter === false;
9354
9667
 
9355
9668
  /**
9356
9669
  * Get the first suitable adapter from the provided list.
9357
9670
  * Tries each adapter in order until a supported one is found.
9358
9671
  * Throws an AxiosError if no adapter is suitable.
9359
- *
9672
+ *
9360
9673
  * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
9361
9674
  * @param {Object} config - Axios request configuration
9362
9675
  * @throws {AxiosError} If no suitable adapter is available
@@ -9381,7 +9694,7 @@ function requireAxios () {
9381
9694
  adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
9382
9695
 
9383
9696
  if (adapter === undefined) {
9384
- throw new AxiosError$1(`Unknown adapter '${id}'`);
9697
+ throw new AxiosError(`Unknown adapter '${id}'`);
9385
9698
  }
9386
9699
  }
9387
9700
 
@@ -9393,16 +9706,19 @@ function requireAxios () {
9393
9706
  }
9394
9707
 
9395
9708
  if (!adapter) {
9396
- const reasons = Object.entries(rejectedReasons)
9397
- .map(([id, state]) => `adapter ${id} ` +
9709
+ const reasons = Object.entries(rejectedReasons).map(
9710
+ ([id, state]) =>
9711
+ `adapter ${id} ` +
9398
9712
  (state === false ? 'is not supported by the environment' : 'is not available in the build')
9399
- );
9713
+ );
9400
9714
 
9401
- let s = length ?
9402
- (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
9403
- 'as no adapter specified';
9715
+ let s = length
9716
+ ? reasons.length > 1
9717
+ ? 'since :\n' + reasons.map(renderReason).join('\n')
9718
+ : ' ' + renderReason(reasons[0])
9719
+ : 'as no adapter specified';
9404
9720
 
9405
- throw new AxiosError$1(
9721
+ throw new AxiosError(
9406
9722
  `There is no suitable adapter to dispatch the request ` + s,
9407
9723
  'ERR_NOT_SUPPORT'
9408
9724
  );
@@ -9425,7 +9741,7 @@ function requireAxios () {
9425
9741
  * Exposes all known adapters
9426
9742
  * @type {Object<string, Function|Object>}
9427
9743
  */
9428
- adapters: knownAdapters
9744
+ adapters: knownAdapters,
9429
9745
  };
9430
9746
 
9431
9747
  /**
@@ -9441,7 +9757,7 @@ function requireAxios () {
9441
9757
  }
9442
9758
 
9443
9759
  if (config.signal && config.signal.aborted) {
9444
- throw new CanceledError$1(null, config);
9760
+ throw new CanceledError(null, config);
9445
9761
  }
9446
9762
  }
9447
9763
 
@@ -9455,53 +9771,49 @@ function requireAxios () {
9455
9771
  function dispatchRequest(config) {
9456
9772
  throwIfCancellationRequested(config);
9457
9773
 
9458
- config.headers = AxiosHeaders$1.from(config.headers);
9774
+ config.headers = AxiosHeaders.from(config.headers);
9459
9775
 
9460
9776
  // Transform request data
9461
- config.data = transformData.call(
9462
- config,
9463
- config.transformRequest
9464
- );
9777
+ config.data = transformData.call(config, config.transformRequest);
9465
9778
 
9466
9779
  if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
9467
9780
  config.headers.setContentType('application/x-www-form-urlencoded', false);
9468
9781
  }
9469
9782
 
9470
- const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config);
9471
-
9472
- return adapter(config).then(function onAdapterResolution(response) {
9473
- throwIfCancellationRequested(config);
9474
-
9475
- // Transform response data
9476
- response.data = transformData.call(
9477
- config,
9478
- config.transformResponse,
9479
- response
9480
- );
9481
-
9482
- response.headers = AxiosHeaders$1.from(response.headers);
9783
+ const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
9483
9784
 
9484
- return response;
9485
- }, function onAdapterRejection(reason) {
9486
- if (!isCancel(reason)) {
9785
+ return adapter(config).then(
9786
+ function onAdapterResolution(response) {
9487
9787
  throwIfCancellationRequested(config);
9488
9788
 
9489
9789
  // Transform response data
9490
- if (reason && reason.response) {
9491
- reason.response.data = transformData.call(
9492
- config,
9493
- config.transformResponse,
9494
- reason.response
9495
- );
9496
- reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
9790
+ response.data = transformData.call(config, config.transformResponse, response);
9791
+
9792
+ response.headers = AxiosHeaders.from(response.headers);
9793
+
9794
+ return response;
9795
+ },
9796
+ function onAdapterRejection(reason) {
9797
+ if (!isCancel(reason)) {
9798
+ throwIfCancellationRequested(config);
9799
+
9800
+ // Transform response data
9801
+ if (reason && reason.response) {
9802
+ reason.response.data = transformData.call(
9803
+ config,
9804
+ config.transformResponse,
9805
+ reason.response
9806
+ );
9807
+ reason.response.headers = AxiosHeaders.from(reason.response.headers);
9808
+ }
9497
9809
  }
9498
- }
9499
9810
 
9500
- return Promise.reject(reason);
9501
- });
9811
+ return Promise.reject(reason);
9812
+ }
9813
+ );
9502
9814
  }
9503
9815
 
9504
- const VERSION = "1.13.3";
9816
+ const VERSION = "1.14.0";
9505
9817
 
9506
9818
  const validators$1 = {};
9507
9819
 
@@ -9525,15 +9837,23 @@ function requireAxios () {
9525
9837
  */
9526
9838
  validators$1.transitional = function transitional(validator, version, message) {
9527
9839
  function formatMessage(opt, desc) {
9528
- return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
9840
+ return (
9841
+ '[Axios v' +
9842
+ VERSION +
9843
+ "] Transitional option '" +
9844
+ opt +
9845
+ "'" +
9846
+ desc +
9847
+ (message ? '. ' + message : '')
9848
+ );
9529
9849
  }
9530
9850
 
9531
9851
  // eslint-disable-next-line func-names
9532
9852
  return (value, opt, opts) => {
9533
9853
  if (validator === false) {
9534
- throw new AxiosError$1(
9854
+ throw new AxiosError(
9535
9855
  formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
9536
- AxiosError$1.ERR_DEPRECATED
9856
+ AxiosError.ERR_DEPRECATED
9537
9857
  );
9538
9858
  }
9539
9859
 
@@ -9557,7 +9877,7 @@ function requireAxios () {
9557
9877
  // eslint-disable-next-line no-console
9558
9878
  console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
9559
9879
  return true;
9560
- }
9880
+ };
9561
9881
  };
9562
9882
 
9563
9883
  /**
@@ -9572,7 +9892,7 @@ function requireAxios () {
9572
9892
 
9573
9893
  function assertOptions(options, schema, allowUnknown) {
9574
9894
  if (typeof options !== 'object') {
9575
- throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
9895
+ throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
9576
9896
  }
9577
9897
  const keys = Object.keys(options);
9578
9898
  let i = keys.length;
@@ -9583,19 +9903,22 @@ function requireAxios () {
9583
9903
  const value = options[opt];
9584
9904
  const result = value === undefined || validator(value, opt, options);
9585
9905
  if (result !== true) {
9586
- throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
9906
+ throw new AxiosError(
9907
+ 'option ' + opt + ' must be ' + result,
9908
+ AxiosError.ERR_BAD_OPTION_VALUE
9909
+ );
9587
9910
  }
9588
9911
  continue;
9589
9912
  }
9590
9913
  if (allowUnknown !== true) {
9591
- throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
9914
+ throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
9592
9915
  }
9593
9916
  }
9594
9917
  }
9595
9918
 
9596
9919
  var validator = {
9597
9920
  assertOptions,
9598
- validators: validators$1
9921
+ validators: validators$1,
9599
9922
  };
9600
9923
 
9601
9924
  const validators = validator.validators;
@@ -9611,8 +9934,8 @@ function requireAxios () {
9611
9934
  constructor(instanceConfig) {
9612
9935
  this.defaults = instanceConfig || {};
9613
9936
  this.interceptors = {
9614
- request: new InterceptorManager$1(),
9615
- response: new InterceptorManager$1()
9937
+ request: new InterceptorManager(),
9938
+ response: new InterceptorManager(),
9616
9939
  };
9617
9940
  }
9618
9941
 
@@ -9663,26 +9986,35 @@ function requireAxios () {
9663
9986
 
9664
9987
  config = mergeConfig(this.defaults, config);
9665
9988
 
9666
- const {transitional, paramsSerializer, headers} = config;
9989
+ const { transitional, paramsSerializer, headers } = config;
9667
9990
 
9668
9991
  if (transitional !== undefined) {
9669
- validator.assertOptions(transitional, {
9670
- silentJSONParsing: validators.transitional(validators.boolean),
9671
- forcedJSONParsing: validators.transitional(validators.boolean),
9672
- clarifyTimeoutError: validators.transitional(validators.boolean)
9673
- }, false);
9992
+ validator.assertOptions(
9993
+ transitional,
9994
+ {
9995
+ silentJSONParsing: validators.transitional(validators.boolean),
9996
+ forcedJSONParsing: validators.transitional(validators.boolean),
9997
+ clarifyTimeoutError: validators.transitional(validators.boolean),
9998
+ legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
9999
+ },
10000
+ false
10001
+ );
9674
10002
  }
9675
10003
 
9676
10004
  if (paramsSerializer != null) {
9677
10005
  if (utils$1.isFunction(paramsSerializer)) {
9678
10006
  config.paramsSerializer = {
9679
- serialize: paramsSerializer
10007
+ serialize: paramsSerializer,
9680
10008
  };
9681
10009
  } else {
9682
- validator.assertOptions(paramsSerializer, {
9683
- encode: validators.function,
9684
- serialize: validators.function
9685
- }, true);
10010
+ validator.assertOptions(
10011
+ paramsSerializer,
10012
+ {
10013
+ encode: validators.function,
10014
+ serialize: validators.function,
10015
+ },
10016
+ true
10017
+ );
9686
10018
  }
9687
10019
  }
9688
10020
 
@@ -9693,28 +10025,27 @@ function requireAxios () {
9693
10025
  config.allowAbsoluteUrls = true;
9694
10026
  }
9695
10027
 
9696
- validator.assertOptions(config, {
9697
- baseUrl: validators.spelling('baseURL'),
9698
- withXsrfToken: validators.spelling('withXSRFToken')
9699
- }, true);
10028
+ validator.assertOptions(
10029
+ config,
10030
+ {
10031
+ baseUrl: validators.spelling('baseURL'),
10032
+ withXsrfToken: validators.spelling('withXSRFToken'),
10033
+ },
10034
+ true
10035
+ );
9700
10036
 
9701
10037
  // Set config.method
9702
10038
  config.method = (config.method || this.defaults.method || 'get').toLowerCase();
9703
10039
 
9704
10040
  // Flatten headers
9705
- let contextHeaders = headers && utils$1.merge(
9706
- headers.common,
9707
- headers[config.method]
9708
- );
10041
+ let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
9709
10042
 
9710
- headers && utils$1.forEach(
9711
- ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
9712
- (method) => {
10043
+ headers &&
10044
+ utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], (method) => {
9713
10045
  delete headers[method];
9714
- }
9715
- );
10046
+ });
9716
10047
 
9717
- config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
10048
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
9718
10049
 
9719
10050
  // filter out skipped interceptors
9720
10051
  const requestInterceptorChain = [];
@@ -9726,7 +10057,15 @@ function requireAxios () {
9726
10057
 
9727
10058
  synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
9728
10059
 
9729
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
10060
+ const transitional = config.transitional || transitionalDefaults;
10061
+ const legacyInterceptorReqResOrdering =
10062
+ transitional && transitional.legacyInterceptorReqResOrdering;
10063
+
10064
+ if (legacyInterceptorReqResOrdering) {
10065
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
10066
+ } else {
10067
+ requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
10068
+ }
9730
10069
  });
9731
10070
 
9732
10071
  const responseInterceptorChain = [];
@@ -9746,13 +10085,8 @@ function requireAxios () {
9746
10085
 
9747
10086
  promise = Promise.resolve(config);
9748
10087
 
9749
- let prevResult = config;
9750
10088
  while (i < len) {
9751
- promise = promise
9752
- .then(chain[i++])
9753
- .then(result => { prevResult = result !== undefined ? result : prevResult; })
9754
- .catch(chain[i++])
9755
- .then(() => prevResult);
10089
+ promise = promise.then(chain[i++], chain[i++]);
9756
10090
  }
9757
10091
 
9758
10092
  return promise;
@@ -9783,7 +10117,7 @@ function requireAxios () {
9783
10117
  len = responseInterceptorChain.length;
9784
10118
 
9785
10119
  while (i < len) {
9786
- promise = promise.then(responseInterceptorChain[i++]).catch(responseInterceptorChain[i++]);
10120
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
9787
10121
  }
9788
10122
 
9789
10123
  return promise;
@@ -9799,28 +10133,32 @@ function requireAxios () {
9799
10133
  // Provide aliases for supported request methods
9800
10134
  utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
9801
10135
  /*eslint func-names:0*/
9802
- Axios.prototype[method] = function(url, config) {
9803
- return this.request(mergeConfig(config || {}, {
9804
- method,
9805
- url,
9806
- data: (config || {}).data
9807
- }));
10136
+ Axios.prototype[method] = function (url, config) {
10137
+ return this.request(
10138
+ mergeConfig(config || {}, {
10139
+ method,
10140
+ url,
10141
+ data: (config || {}).data,
10142
+ })
10143
+ );
9808
10144
  };
9809
10145
  });
9810
10146
 
9811
10147
  utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
9812
- /*eslint func-names:0*/
9813
-
9814
10148
  function generateHTTPMethod(isForm) {
9815
10149
  return function httpMethod(url, data, config) {
9816
- return this.request(mergeConfig(config || {}, {
9817
- method,
9818
- headers: isForm ? {
9819
- 'Content-Type': 'multipart/form-data'
9820
- } : {},
9821
- url,
9822
- data
9823
- }));
10150
+ return this.request(
10151
+ mergeConfig(config || {}, {
10152
+ method,
10153
+ headers: isForm
10154
+ ? {
10155
+ 'Content-Type': 'multipart/form-data',
10156
+ }
10157
+ : {},
10158
+ url,
10159
+ data,
10160
+ })
10161
+ );
9824
10162
  };
9825
10163
  }
9826
10164
 
@@ -9829,8 +10167,6 @@ function requireAxios () {
9829
10167
  Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
9830
10168
  });
9831
10169
 
9832
- var Axios$1 = Axios;
9833
-
9834
10170
  /**
9835
10171
  * A `CancelToken` is an object that can be used to request cancellation of an operation.
9836
10172
  *
@@ -9853,7 +10189,7 @@ function requireAxios () {
9853
10189
  const token = this;
9854
10190
 
9855
10191
  // eslint-disable-next-line func-names
9856
- this.promise.then(cancel => {
10192
+ this.promise.then((cancel) => {
9857
10193
  if (!token._listeners) return;
9858
10194
 
9859
10195
  let i = token._listeners.length;
@@ -9865,10 +10201,10 @@ function requireAxios () {
9865
10201
  });
9866
10202
 
9867
10203
  // eslint-disable-next-line func-names
9868
- this.promise.then = onfulfilled => {
10204
+ this.promise.then = (onfulfilled) => {
9869
10205
  let _resolve;
9870
10206
  // eslint-disable-next-line func-names
9871
- const promise = new Promise(resolve => {
10207
+ const promise = new Promise((resolve) => {
9872
10208
  token.subscribe(resolve);
9873
10209
  _resolve = resolve;
9874
10210
  }).then(onfulfilled);
@@ -9886,7 +10222,7 @@ function requireAxios () {
9886
10222
  return;
9887
10223
  }
9888
10224
 
9889
- token.reason = new CanceledError$1(message, config, request);
10225
+ token.reason = new CanceledError(message, config, request);
9890
10226
  resolvePromise(token.reason);
9891
10227
  });
9892
10228
  }
@@ -9956,13 +10292,11 @@ function requireAxios () {
9956
10292
  });
9957
10293
  return {
9958
10294
  token,
9959
- cancel
10295
+ cancel,
9960
10296
  };
9961
10297
  }
9962
10298
  }
9963
10299
 
9964
- var CancelToken$1 = CancelToken;
9965
-
9966
10300
  /**
9967
10301
  * Syntactic sugar for invoking a function and expanding an array for arguments.
9968
10302
  *
@@ -9998,7 +10332,7 @@ function requireAxios () {
9998
10332
  * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
9999
10333
  */
10000
10334
  function isAxiosError(payload) {
10001
- return utils$1.isObject(payload) && (payload.isAxiosError === true);
10335
+ return utils$1.isObject(payload) && payload.isAxiosError === true;
10002
10336
  }
10003
10337
 
10004
10338
  const HttpStatusCode = {
@@ -10077,8 +10411,6 @@ function requireAxios () {
10077
10411
  HttpStatusCode[value] = key;
10078
10412
  });
10079
10413
 
10080
- var HttpStatusCode$1 = HttpStatusCode;
10081
-
10082
10414
  /**
10083
10415
  * Create an instance of Axios
10084
10416
  *
@@ -10087,14 +10419,14 @@ function requireAxios () {
10087
10419
  * @returns {Axios} A new instance of Axios
10088
10420
  */
10089
10421
  function createInstance(defaultConfig) {
10090
- const context = new Axios$1(defaultConfig);
10091
- const instance = bind(Axios$1.prototype.request, context);
10422
+ const context = new Axios(defaultConfig);
10423
+ const instance = bind(Axios.prototype.request, context);
10092
10424
 
10093
10425
  // Copy axios.prototype to instance
10094
- utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
10426
+ utils$1.extend(instance, Axios.prototype, context, { allOwnKeys: true });
10095
10427
 
10096
10428
  // Copy context to instance
10097
- utils$1.extend(instance, context, null, {allOwnKeys: true});
10429
+ utils$1.extend(instance, context, null, { allOwnKeys: true });
10098
10430
 
10099
10431
  // Factory for creating new instances
10100
10432
  instance.create = function create(instanceConfig) {
@@ -10105,20 +10437,20 @@ function requireAxios () {
10105
10437
  }
10106
10438
 
10107
10439
  // Create the default instance to be exported
10108
- const axios = createInstance(defaults$1);
10440
+ const axios = createInstance(defaults);
10109
10441
 
10110
10442
  // Expose Axios class to allow class inheritance
10111
- axios.Axios = Axios$1;
10443
+ axios.Axios = Axios;
10112
10444
 
10113
10445
  // Expose Cancel & CancelToken
10114
- axios.CanceledError = CanceledError$1;
10115
- axios.CancelToken = CancelToken$1;
10446
+ axios.CanceledError = CanceledError;
10447
+ axios.CancelToken = CancelToken;
10116
10448
  axios.isCancel = isCancel;
10117
10449
  axios.VERSION = VERSION;
10118
10450
  axios.toFormData = toFormData;
10119
10451
 
10120
10452
  // Expose AxiosError class
10121
- axios.AxiosError = AxiosError$1;
10453
+ axios.AxiosError = AxiosError;
10122
10454
 
10123
10455
  // alias for CanceledError for backward compatibility
10124
10456
  axios.Cancel = axios.CanceledError;
@@ -10136,13 +10468,13 @@ function requireAxios () {
10136
10468
  // Expose mergeConfig
10137
10469
  axios.mergeConfig = mergeConfig;
10138
10470
 
10139
- axios.AxiosHeaders = AxiosHeaders$1;
10471
+ axios.AxiosHeaders = AxiosHeaders;
10140
10472
 
10141
- axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
10473
+ axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
10142
10474
 
10143
10475
  axios.getAdapter = adapters.getAdapter;
10144
10476
 
10145
- axios.HttpStatusCode = HttpStatusCode$1;
10477
+ axios.HttpStatusCode = HttpStatusCode;
10146
10478
 
10147
10479
  axios.default = axios;
10148
10480
 
@@ -11285,7 +11617,7 @@ const defaultConfig = {
11285
11617
  dontSend: false,
11286
11618
  disableUserIds: false,
11287
11619
  ipPolicy: "keep",
11288
- consentCategories: undefined,
11620
+ consentCategories: {},
11289
11621
  },
11290
11622
  };
11291
11623
  // mergeConfig merges newConfig into currentConfig also making sure that all undefined values are replaced with defaultConfig values
@@ -11294,11 +11626,14 @@ const mergeConfig = (current, newConfig) => {
11294
11626
  const value = newConfig[key];
11295
11627
  if (key === "privacy") {
11296
11628
  if (typeof value === "object") {
11297
- current.privacy = Object.assign(Object.assign(Object.assign({}, defaultConfig.privacy), current.privacy), value);
11629
+ current.privacy = Object.assign(Object.assign(Object.assign(Object.assign({}, defaultConfig.privacy), { consentCategories: Object.assign({}, defaultConfig.privacy.consentCategories) }), current.privacy), value);
11298
11630
  }
11299
- else if (newConfig.hasOwnProperty("privacy") && typeof value === "undefined") {
11300
- // explicitly set to undefined - reset to default
11301
- current.privacy = Object.assign({}, defaultConfig.privacy);
11631
+ else if (typeof value === "undefined") {
11632
+ if (newConfig.hasOwnProperty("privacy") || !current.hasOwnProperty("privacy")) {
11633
+ // explicitly set to undefined - reset to default
11634
+ // or was not set at all - set to default
11635
+ current.privacy = Object.assign(Object.assign({}, defaultConfig.privacy), { consentCategories: Object.assign({}, defaultConfig.privacy.consentCategories) });
11636
+ }
11302
11637
  }
11303
11638
  }
11304
11639
  else if (typeof value === "undefined") {
@@ -11373,6 +11708,19 @@ function getClientIds(runtime, customCookieCapture) {
11373
11708
  }, {});
11374
11709
  return Object.assign(Object.assign({}, clientIds), getGa4Ids(runtime));
11375
11710
  }
11711
+ function parseGa4SessionId(cookieValue) {
11712
+ if (typeof cookieValue !== "string") {
11713
+ return undefined;
11714
+ }
11715
+ if (cookieValue.startsWith("GA1") || cookieValue.startsWith("GS1")) {
11716
+ return cookieValue.split(".")[2];
11717
+ }
11718
+ else {
11719
+ // parse new GA4 cookie format, e.g.: GS2.1.s1747323152$o28$g0$t1747323152$j60$l0$h69286059
11720
+ const match = cookieValue.match(/^GS\d+\.\d+\.(?:[\w_-]+[$])*s(\d+)(?:$|[$])/);
11721
+ return match ? match[1] : undefined;
11722
+ }
11723
+ }
11376
11724
  function getGa4Ids(runtime) {
11377
11725
  var _a;
11378
11726
  const allCookies = runtime.getCookies();
@@ -11381,14 +11729,11 @@ function getGa4Ids(runtime) {
11381
11729
  const sessionIds = gaSessionCookies.length > 0
11382
11730
  ? Object.fromEntries(gaSessionCookies
11383
11731
  .map(([key, value]) => {
11384
- if (typeof value !== "string") {
11385
- return null;
11386
- }
11387
- const parts = value.split(".");
11388
- if (parts.length < 3) {
11732
+ const sessionId = parseGa4SessionId(value);
11733
+ if (!sessionId) {
11389
11734
  return null;
11390
11735
  }
11391
- return [key.substring("_ga_".length), parts[2]];
11736
+ return [key.substring("_ga_".length), sessionId];
11392
11737
  })
11393
11738
  .filter(v => v !== null))
11394
11739
  : undefined;
@@ -11612,6 +11957,15 @@ const emptyRuntime = (config) => ({
11612
11957
  return undefined;
11613
11958
  },
11614
11959
  });
11960
+ function deepCopy(o) {
11961
+ if (typeof o !== "object") {
11962
+ return o;
11963
+ }
11964
+ if (!o) {
11965
+ return o;
11966
+ }
11967
+ return JSON.parse(JSON.stringify(o));
11968
+ }
11615
11969
  function deepMerge(target, source) {
11616
11970
  if (typeof source !== "object" || source === null) {
11617
11971
  return source;
@@ -11648,17 +12002,46 @@ function urlPath(url) {
11648
12002
  const pathMatch = matches && matches[3] ? matches[3].split("?")[0].replace(hashRegex, "") : "";
11649
12003
  return "/" + pathMatch;
11650
12004
  }
12005
+ function canonicalUrl() {
12006
+ if (!isInBrowser())
12007
+ return;
12008
+ const tags = document.getElementsByTagName("link");
12009
+ for (var i = 0, tag; (tag = tags[i]); i++) {
12010
+ if (tag.getAttribute("rel") === "canonical") {
12011
+ return tag.getAttribute("href");
12012
+ }
12013
+ }
12014
+ }
12015
+ /**
12016
+ * bugged analytics.js logic that produces 'url' parameter by concating canonical URL with current search part
12017
+ * I produces broken results in some cases like SPA where path is changed but canonical URL is not updated
12018
+ */
12019
+ function analyticsJsUrl() {
12020
+ if (!isInBrowser())
12021
+ return;
12022
+ const canonical = canonicalUrl();
12023
+ if (!canonical)
12024
+ return window.location.href.replace(hashRegex, "");
12025
+ return canonical.match(/\?/) ? canonical : canonical + window.location.search;
12026
+ }
11651
12027
  function adjustPayload(payload, config, storage, s2s) {
11652
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
12028
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
11653
12029
  const runtime = config.runtime || (isInBrowser() ? windowRuntime(config) : emptyRuntime(config));
11654
12030
  const url = runtime.pageUrl();
11655
12031
  const parsedUrl = safeCall$1(() => new URL(url), undefined);
11656
12032
  const query = parsedUrl ? parseQuery(parsedUrl.search) : {};
11657
12033
  const properties = payload.properties || {};
11658
12034
  if (payload.type === "page" && (properties.url || url)) {
11659
- const targetUrl = properties.url || url;
12035
+ // we don't trust analytics.js URL logic since it's sticks with canonical URL on SPA pages
12036
+ let targetUrl = url || properties.url;
12037
+ if (properties.url && properties.url !== analyticsJsUrl()) {
12038
+ // properties.url is not the same as provided by analytics.js
12039
+ // it means that it was not overridden by user and we should use it
12040
+ targetUrl = properties.url;
12041
+ }
11660
12042
  properties.url = targetUrl.replace(hashRegex, "");
11661
12043
  properties.path = fixPath(urlPath(targetUrl));
12044
+ // other properties are correctly based on window.location in analytics.js
11662
12045
  }
11663
12046
  const customContext = deepMerge(config.defaultPayloadContext, ((_a = payload.properties) === null || _a === void 0 ? void 0 : _a.context) || ((_b = payload.options) === null || _b === void 0 ? void 0 : _b.context) || {});
11664
12047
  (_c = payload.properties) === null || _c === void 0 ? true : delete _c.context;
@@ -11669,17 +12052,17 @@ function adjustPayload(payload, config, storage, s2s) {
11669
12052
  version: jitsuVersion,
11670
12053
  env: isInBrowser() ? "browser" : "node",
11671
12054
  },
11672
- consent: ((_d = config.privacy) === null || _d === void 0 ? void 0 : _d.consentCategories)
12055
+ consent: typeof ((_d = config.privacy) === null || _d === void 0 ? void 0 : _d.consentCategories) === "object" && Object.keys((_e = config.privacy) === null || _e === void 0 ? void 0 : _e.consentCategories).length
11673
12056
  ? {
11674
12057
  categoryPreferences: config.privacy.consentCategories,
11675
12058
  }
11676
12059
  : undefined,
11677
- userAgent: (_e = runtime.userAgent) === null || _e === void 0 ? void 0 : _e.call(runtime),
11678
- locale: (_f = runtime.language) === null || _f === void 0 ? void 0 : _f.call(runtime),
11679
- screen: (_g = runtime.screen) === null || _g === void 0 ? void 0 : _g.call(runtime),
11680
- ip: (_h = runtime === null || runtime === void 0 ? void 0 : runtime.ip) === null || _h === void 0 ? void 0 : _h.call(runtime),
12060
+ userAgent: (_f = runtime.userAgent) === null || _f === void 0 ? void 0 : _f.call(runtime),
12061
+ locale: (_g = runtime.language) === null || _g === void 0 ? void 0 : _g.call(runtime),
12062
+ screen: (_h = runtime.screen) === null || _h === void 0 ? void 0 : _h.call(runtime),
12063
+ ip: (_j = runtime === null || runtime === void 0 ? void 0 : runtime.ip) === null || _j === void 0 ? void 0 : _j.call(runtime),
11681
12064
  traits: payload.type != "identify" && payload.type != "group"
11682
- ? Object.assign(Object.assign({}, (restoreTraits(storage) || {})), (((_j = payload === null || payload === void 0 ? void 0 : payload.options) === null || _j === void 0 ? void 0 : _j.traits) || {})) : undefined,
12065
+ ? Object.assign(Object.assign({}, (restoreTraits(storage) || {})), (((_k = payload === null || payload === void 0 ? void 0 : payload.options) === null || _k === void 0 ? void 0 : _k.traits) || {})) : undefined,
11683
12066
  page: {
11684
12067
  path: properties.path || (parsedUrl && parsedUrl.pathname),
11685
12068
  referrer: referrer,
@@ -11690,13 +12073,13 @@ function adjustPayload(payload, config, storage, s2s) {
11690
12073
  url: properties.url || url,
11691
12074
  encoding: properties.encoding || runtime.documentEncoding(),
11692
12075
  },
11693
- clientIds: !((_k = config.privacy) === null || _k === void 0 ? void 0 : _k.disableUserIds) ? getClientIds(runtime, config.cookieCapture) : undefined,
12076
+ clientIds: !((_l = config.privacy) === null || _l === void 0 ? void 0 : _l.disableUserIds) ? getClientIds(runtime, config.cookieCapture) : undefined,
11694
12077
  campaign: parseUtms(query),
11695
12078
  };
11696
- const withContext = Object.assign(Object.assign({}, payload), { userId: ((_l = payload === null || payload === void 0 ? void 0 : payload.options) === null || _l === void 0 ? void 0 : _l.userId) || (payload === null || payload === void 0 ? void 0 : payload.userId), anonymousId: ((_m = payload === null || payload === void 0 ? void 0 : payload.options) === null || _m === void 0 ? void 0 : _m.anonymousId) || (payload === null || payload === void 0 ? void 0 : payload.anonymousId), groupId: ((_o = payload === null || payload === void 0 ? void 0 : payload.options) === null || _o === void 0 ? void 0 : _o.groupId) || storage.getItem("__group_id"), timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: maskWriteKey(config.writeKey), context: deepMerge(context, customContext) });
12079
+ const withContext = Object.assign(Object.assign({}, payload), { userId: ((_m = payload === null || payload === void 0 ? void 0 : payload.options) === null || _m === void 0 ? void 0 : _m.userId) || (payload === null || payload === void 0 ? void 0 : payload.userId), anonymousId: ((_o = payload === null || payload === void 0 ? void 0 : payload.options) === null || _o === void 0 ? void 0 : _o.anonymousId) || (payload === null || payload === void 0 ? void 0 : payload.anonymousId), groupId: ((_p = payload === null || payload === void 0 ? void 0 : payload.options) === null || _p === void 0 ? void 0 : _p.groupId) || storage.getItem("__group_id"), timestamp: new Date().toISOString(), sentAt: new Date().toISOString(), messageId: randomId(properties.path || (parsedUrl && parsedUrl.pathname)), writeKey: maskWriteKey(config.writeKey), context: deepMerge(context, customContext) });
11697
12080
  delete withContext.meta;
11698
12081
  delete withContext.options;
11699
- if ((_p = config.privacy) === null || _p === void 0 ? void 0 : _p.disableUserIds) {
12082
+ if ((_q = config.privacy) === null || _q === void 0 ? void 0 : _q.disableUserIds) {
11700
12083
  delete withContext.userId;
11701
12084
  delete withContext.anonymousId;
11702
12085
  delete withContext.context.traits;
@@ -11712,15 +12095,18 @@ function processDestinations(destinations, method, originalEvent, debug, analyti
11712
12095
  return __awaiter$1(this, void 0, void 0, function* () {
11713
12096
  const promises = [];
11714
12097
  for (const destination of destinations) {
11715
- let newEvents = [originalEvent];
12098
+ let newEvents = [];
11716
12099
  if (destination.newEvents) {
11717
12100
  try {
11718
- newEvents = destination.newEvents.map(e => e === "same" ? originalEvent : isDiff(e) ? diff.patch(originalEvent, e.__diff) : e);
12101
+ newEvents = destination.newEvents.map(e => e === "same" ? deepCopy(originalEvent) : isDiff(e) ? diff.patch(deepCopy(originalEvent), e.__diff) : e);
11719
12102
  }
11720
12103
  catch (e) {
11721
12104
  console.error(`[JITSU] Error applying '${destination.id}' changes to event: ${e === null || e === void 0 ? void 0 : e.message}`, e);
11722
12105
  }
11723
12106
  }
12107
+ else {
12108
+ newEvents = [deepCopy(originalEvent)];
12109
+ }
11724
12110
  const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
11725
12111
  if (destination.deviceOptions.type === "internal-plugin") {
11726
12112
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
@@ -12266,6 +12652,9 @@ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
12266
12652
  //However, since returned values are used for debugging purposes only, it's ok
12267
12653
  return results[0];
12268
12654
  });
12655
+ },
12656
+ getConfiguration() {
12657
+ return opts;
12269
12658
  } });
12270
12659
  if (((_b = opts.privacy) === null || _b === void 0 ? void 0 : _b.disableUserIds) || ((_c = opts.privacy) === null || _c === void 0 ? void 0 : _c.dontSend)) {
12271
12660
  storage.reset();
@@ -12311,7 +12700,7 @@ function jitsuAnalytics(_opts) {
12311
12700
  // }
12312
12701
  }
12313
12702
 
12314
- let n=function(e,t,a){return alert(e)},o=function(e,t){return n(e,l.error,t)},l={error:"error",success:"success",info:"info"};var u={fire:function(e,t,a){return n(e,t,a)},setNotifier:function(e){n=e,salla.event.emit("twilight::notifier.changed");},error:o,success:function(e,t){return n(e,l.success,t)},info:function(e,t){return n(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,o(t.innerHTML),salla.event.emit("twilight::error",e);}));})));},types:l};class c{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let s=r.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return s.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return false},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||(null==a?void 0:a.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let s=(null==a?void 0:a.dataset[r])||this.dataset[r];if(s){var i=window[s];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${s}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+s+"() not found!");}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class d{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);}));}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,(async function(...e){return t(...e)}))};}getEventName(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,a={}){return Salla.event.addListener(this.getEventName(e),t,a)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function h$1(){return h$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e},h$1.apply(null,arguments)}function p(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=true);}Salla.event.auth=new class extends d{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends d{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},this.after_init();}updated(e,t={}){var a;return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(a=e.cart.free_shipping_bar)&&a.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",h$1({},e.cart,{fromLatestFetched:t.fromLatestFetched}))):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated",{fromLatestFetched:t.fromLatestFetched}))}latestFetched(e){return this.updated(e.data,{fromLatestFetched:true}),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends d{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched",orderEdited:"order.edited",orderNotEdited:"order.not.edited"},this.after_init();}},Salla.event.scope=new class extends d{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init();}},Salla.event.rating=new class extends d{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init();}},Salla.event.booking=new class extends d{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.comment=new class extends d{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.landing=new class extends d{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.loyalty=new class extends d{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init();}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends d{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed",productOptionsFetched:"options.fetched",productOptionsNotFetched:"options.not.fetched"},this.after_init();}},Salla.event.profile=new class extends d{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends d{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends d{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,(e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);}));}fireEvent(e,t,...a){return this.fireEventForElements(e,t,false,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,true,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,false,...r)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const s=new CustomEvent(t,...r);return e.dispatchEvent(s)}},Salla.event.wishlist=new class extends d{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init();}},Salla.event.infiniteScroll=new class extends d{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init();}},Salla.event.notifications=new class extends d{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.component=new class extends d{constructor(){super(),this.namespace="component",this.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},this.after_init();}},Salla.event.advertisement=new class extends d{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init();}},Salla.event.navigation=new class extends d{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.metadata=new class extends d{constructor(){super(),this.namespace="metadata",this.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},this.after_init();}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(p(e),Object.keys(e).forEach((t=>{p(e[t]);})));}));})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"==="production",token:null,fastRequests:true,canLeave:true,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=false,Salla.config.triedToGetLanguages_=false,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{var e;if(Salla.config.triedToGetLanguages_||Salla.config.get("languages",[]).length>0)return Salla.config.get("languages",[]);Salla.config.triedToGetLanguages_=true;let t=true,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map((e=>{t&&(a=[],t=false),e.code=e.code||e.iso_code,e.url=salla.url.get(e.code),e.is_rtl=e.is_rtl||e.rtl,a.push(e);})),Salla.config.set("languages",a),a},Salla.config.currencies=async()=>{var e;if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=true;let t=true,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map((e=>{t&&(a={},t=false),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e;})),Salla.config.set("currencies",a),a},Salla.config.isMobileApp=()=>{var e;return ["ios","android"].includes(null==(e=Salla.analytics)||null==(e=e.jitsuAnalytics)||null==(e=e.getContextProperty("app"))||null==(e=e.platform)?void 0:e.toLowerCase())};class g{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:true,exclude:[]};}after_init(){}normalRequest(e,t=void 0,a=null){let r=Array.isArray(e),s=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1];})),t={params:e};}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?s=salla.url.get(s):"http"!==s.substring(0,4)&&(s=salla.url.api(s)),Salla.api.request(s,t,a,{headers:i})}request(e,t=void 0,a=null){return !salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class m extends g{constructor(){super(),this.addToCartTries=0,this.guestCartAssigned=false,this.namespace="cart",this._pendingCartIdRequest=null,this._pendingAssignRequest=null,this.endpoints={latest:"cart/latest",latestApi:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote",offers:"offers/cart/{cartId}",giftCartDetails:"cart/{cartId}/buy-as-gift",cartGiftToCart:"cart/{cart_id}/buy-as-gift",assign:"cart/{cartId}/assign?merge=1"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>salla.api.cart.getCurrentCartId(false,"api::initiated"))),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",(async function(){try{await Salla.api.cart.assign();}catch(e){Salla.log("Error on assign after verified",e);}return Salla.api.cart.getCurrentCartId(true,"auth::verified")}),{async:true}),salla.event.on("twilight::initiated",(()=>salla.api.cart.syncGuestCart())),salla.event.on("profile::info.fetched",(()=>this._checkCurrentCart(true))),salla.event.on("twilight::error",(e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()));}_checkCurrentCart(e=false){var t,a;let r=salla.storage.get("cart"),s=null==(t=salla.config.get("user"))?void 0:t.id,i=null==(a=salla.config.get("store"))?void 0:a.id;r&&r.id&&!e&&(r.user_id===s&&r.store_id===i||(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log("Api:: case2 => The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),salla.cart.api.reset()),salla.url.is_page("cart")&&r.id!==salla.config.get("page.id")&&(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log(`Api:: case2 => The cart is different between storage:${r.id} & session:${salla.config.get("page.id")} !`),salla.cart.api.reset()));}async getCurrentCartId(e=false,t="getCurrentCartId"){if(Salla.cart.api._pendingCartIdRequest)return Salla.cart.api._pendingCartIdRequest;Salla.cart.api._pendingCartIdRequest=async function(){try{if(!e){if(Salla.cart.api.latestCart)return Salla.cart.api.latestCart.cart.id;let e=Salla.storage.get("cart.id");if(e)return e}let a=await Salla.cart.api.latest(t);return Salla.cart.api.latestCart=a.data,Salla.cart.api.latestCart.cart.id}finally{Salla.cart.api._pendingCartIdRequest=null;}}();let a=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,a}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request(salla.auth.api.isSessionless()?"latestApi":"latest",{params:{source:"",callerName:e}}).then((e=>(salla.api.cart.set(e.data.cart),salla.event.cart.latestFetched(e),e))).catch((e=>{throw salla.api.cart.reset(),salla.event.cart.latestFailed(e),e}))}async details(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.details"),this.request(["details",e],{params:{with:t}}).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e,t,a){return this.addItem({id:e,quantity:t,offerType:a,endpoint:"quickAdd"})}async addItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let r=salla.form.getPossibleValue(a.payload,["endpoint"]);r&&["addItem","quickAdd"].includes(r)||(r=salla.form.getPossibleValue(a.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let s=null==(t=a.payload)?void 0:t.source;a.payload&&delete a.payload.source,Salla.cart.api.addToCartSource=s||null;let i=await Salla.api.cart.getCurrentCartId(false,"salla.api.cart.addItem");try{a.payload=Salla.helpers.createFormDataWrapper(a.payload||{}),await Salla.cart.event.beforeAddItem(a);}catch(e){}return this.request([r,i,a.id],a.payload.getRawData()).then((function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,a.id);}catch(e){Salla.log(e);}return e})).catch((function(t){if(!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(t,a.id),t}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteItem");return this.request(["deleteItem",a,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.updateItem");return "Object"===(null==(t=a.payload.constructor)?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),this.request(["updateItem",r,a.id],a.payload).then((function(e){return salla.cart.event.itemUpdated(e,a.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,a.id),e}))}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteImage");return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e,t=false){e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.status");const a={has_apple_pay:salla.helpers.hasApplePay()};t&&(a.guest_checkout=1);try{await salla.cart.event.submitting();}catch(e){salla.log("Error on: salla.cart.event.submitting()");}return this.request(["status",e],{params:a})}async submit(e=false,t=false){const a=salla.config.get("store.features",[]).includes("embedded-login-checkout");if(salla.config.isGuest()){if(!a&&!t)return salla.cart.loginOnCartPage();try{await salla.api.cart.syncGuestCart();}catch(e){salla.log("Error on syncGuestCart during guest checkout",e);}}let r;if(e)try{var s;const e=await Salla.api.cart.assign();r=null==e||null==(s=e.data)?void 0:s.cart_id;}catch(e){Salla.log("Error on assign after login from submit",e);}const i=salla.config.isGuest()&&(t||a);this.status(null!=r?r:await salla.api.cart.getCurrentCartId(false,"salla.api.cart.submit"),i).then((e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(!a)return window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",false===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload();if(!["checkout","refresh","login"].includes(a)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===a)return salla.cart.loginOnCartPage();if("checkout"===a){var r;let t=null==(r=e.data.next_step)?void 0:r.url;if(!t){let e="Checkout URL is missing from response";throw salla.cart.event.submitFailed(e),e}return salla.helpers.hasApplePay()&&(t+=(t.includes("?")?"&":"?")+"has_apple_pay=true"),window.location.href=t}window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),window.location.reload();})).catch((function(a){var r;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let s=404===(null==a||null==(r=a.response)||null==(r=r.data)?void 0:r.status);if(s&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit(e,t);throw s&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(a),a}));}getCartPayload(e){var t;let a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,a="object"==typeof a?a:void 0,{id:e,payload:a}}normalRequest(e,t=void 0,a=null){var r=this;return super.normalRequest(e,t,a).catch((async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset();}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.addCoupon");return this.request(["addCoupon",t],{coupon:e}).then((function(e){var a;let r=salla.storage.get("cart");return r&&null!=(a=e.data)&&null!=(a=a.cart)&&a.coupon&&(r.coupon=e.data.cart.coupon,salla.storage.set("cart",r)),salla.event.cart.couponAdded(e,t),e})).catch((function(e){throw salla.event.cart.couponAdditionFailed(e,t),e}))}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then((function(t){let a=salla.storage.get("cart");return a&&a.coupon&&(delete a.coupon,salla.storage.set("cart",a)),salla.event.cart.couponDeleted(t,e),t})).catch((function(t){throw salla.event.cart.couponDeletionFailed(t,e),t}))}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then((e=>(salla.event.cart.quickOrderSettingFetched(e),e))).catch((e=>{throw salla.event.cart.quickOrderSettingFailed(e),e}))}createQuickOrder(e){return this.request("createQuickOrder",e).then((e=>(salla.event.cart.quickOrderSucceeded(e),e))).catch((e=>{throw salla.event.cart.quickOrderFailed(e),e}))}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.priceQuote")]).then((e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then((()=>(setTimeout((()=>window.location.href=salla.url.get("/")),1e3),e)))))).catch((e=>salla.event.cart.priceQuoteFailed(e).then((()=>{var t;throw 404===(null==(t=e.error)?void 0:t.code)&&window.location.reload(),e}))))}loginOnCartPage(){salla.auth.setCanRedirect(false),salla.event.dispatch("login::open",{withoutReload:true,source:"cart-submit"}),salla.auth.event.onLoggedIn((()=>{salla.event.dispatch("login::close"),salla.cart.submit(true);}));}set(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart();}async offers(){const e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.offers");return this.request(["offers",e]).then((e=>(salla.event.cart.offersFetched(e),e))).catch((e=>{throw salla.event.cart.offersFailed(e),e}))}async getGiftCartDetails(){let e=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.getGiftCartDetails");return this.request(["giftCartDetails",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}async addCartGiftToCart(e,t=false){let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then((e=>(salla.product.event.addGiftToCartSucceeded(e,a),t&&(window.location.href=e.redirect),e))).catch((e=>{throw salla.product.event.addGiftToCartFailed(e,a),e}))}async syncGuestCart(){if(!salla.config.isGuest())return;const e=salla.api.cart.getCartCookiePrefix(),t=salla.cookie.getCookieByPrefix(e),a=salla.storage.get("cart.id");if(!a&&t.length)try{var r;const t=null==(r=(await salla.api.cart.latest()).data)||null==(r=r.cart)?void 0:r.id;t&&salla.api.cart.setCartCookie(e,t);}catch(e){salla.log("Failed to fetch latest cart:",e);}salla.cookie.clearCookieByPrefix(e),a&&(salla.config.set("headers.s-cart-id",a),salla.api.cart.setCartCookie(e,a));}async assign(){var e=this;if(Salla.api.cart._pendingAssignRequest)return Salla.api.cart._pendingAssignRequest;let t=Salla.storage.get("cart.id");return !(!t||Salla.api.cart.guestCartAssigned)&&(Salla.api.cart._pendingAssignRequest=async function(){try{const a=await e.request(["assign",t]);return Salla.api.cart.guestCartAssigned=true,a}catch(e){throw e}finally{Salla.api.cart._pendingAssignRequest=null;}}(),Salla.api.cart._pendingAssignRequest)}setCartCookie(e,t){salla.cookie.set(`${e}-${t}`,t,1);}getCartCookiePrefix(){return "cart-id-"+salla.config.get("store.id")}}class f extends g{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.reset"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class D extends g{constructor(){super(),this.namespace="auth",this.canRedirect_=true,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.inIframe=salla.helpers.isIframe(),Salla.event.on("twilight::init",(function(){if(Salla.config.isGuest()&&location.href.includes("force_logout"))return delete Salla.api.axios.defaults.headers.common.Authorization,Salla.api.auth.logout("twilight",false)})),this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){var t;null!=(t=e)&&t.data&&(e=e.data);let a=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(a)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",a],e).then((function(e){return salla.auth.event.codeSent(e,a),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,a),salla.auth.api.trackBlockedError(e,"login"),e}))}async verify(e,t=true){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=false!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let r=await salla.auth.api.request(["verify",a],e);return 200!==(null==r?void 0:r.status)?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)}async handlAfterAuthenticatedResponse(e,t){var a;e.data||(e={data:e});let r="authenticated"===(null==(a=e.data)?void 0:a.case);return r&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),r&&await salla.auth.event.loggedIn(e).then((()=>salla.auth.api.afterUserLogin())),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),salla.auth.api.trackBlockedError(t,"resend"),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){var t=this;let a;return e.data&&(a=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async function(e){var r;return salla.auth.event.registered.call(a,e),"authenticated"===(null==(r=e.data)?void 0:r.case)&&(salla.auth.event.tokenFetched(e.data.token),!t.inIframe&&!t.isSessionless()&&await salla.auth.request("auth/jwt",{callerName:"salla.auth.api.register"}),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(a,e),salla.auth.api.trackBlockedError(e,"register"),e}))}handleIframeReadyAction(e,t){var a;null==(a=e.contentWindow)||a.postMessage({source:"logout",type:"init",data:{id:salla.config.get("store.id"),lang:"ar",appUrl:t,apiUrl:salla.config.get("store.api").replace(/\/+$/,""),settings:salla.config.all(),storage:{}}},"*");}appendIframeAndLogout(){return new Promise((e=>{let t=salla.config.get("login.url","https://accounts.salla.com");const a=document.createElement("iframe");a.style.display="none",a.src=`${t}/logout`;const r=s=>{if("login"!==s.data.source)return;let i=s.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",s.data),["logged-out","ready"].includes(i)){if("ready"===i)return this.handleIframeReadyAction(a,t);window.removeEventListener("message",r),a.remove(),e();}};window.addEventListener("message",r),document.body.appendChild(a);}))}logout(e="twilight",t=true){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then((()=>this.appendIframeAndLogout())).then((()=>{if(!t)return;let a=salla.url.get(`logout?from=${e}`);console.log(`Going to ${a}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=a;}catch(e){salla.log(e);}})).catch((e=>console.error("Error during logout:",e)))}refresh(){return this.request("refresh").then((function(e){return salla.auth.event.tokenFetched(e.data.token),e})).catch((function(e){throw salla.auth.event.refreshFailed(e),e}))}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload);}isSessionless(){var e;return "sessionless"===(null!=(e=salla.config.get("auth.mode"))?e:salla.config.get("login.mode"))}trackBlockedError(e,t){var a;void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"])&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message});}}class F extends g{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders",editOrder:"orders/{id}"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get",editOrder:"put"},this.after_init();}show(e){let t=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["url"]);}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:salla.helpers.hasApplePay()}}).then((function(t){return salla.event.order.canceled(t,e),t})).catch((function(t){throw salla.event.order.notCanceled(t,e),t}))}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then((function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t})).catch((function(t){throw salla.event.order.orderCreationFailed(t,e),t}))}reorderProduct(e){return e=e||salla.config.get("page.id"),this.request(["reorderProduct",e]).then((function(t){const a=h$1({},t.data,{type:"reorder",id:e}),r=h$1({},t,{data:a});return salla.event.order.orderCreated(r,t.data.order_id),window.location.href=t.data.url,t})).catch((function(t){throw salla.event.order.orderCreationFailed(t,e),t}))}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then((e=>(salla.event.order.invoiceSent(e,t),e))).catch((e=>{throw salla.event.order.invoiceNotSent(e,t),e}))}editOrder(e,t){return e=e||salla.config.get("page.id"),this.request(["editOrder",e],t).then((function(t){return salla.event.order.orderEdited(t,e),t})).catch((function(t){throw salla.event.order.orderNotEdited(t,e),t}))}fetch(e){return this.request(["fetch"],{params:e}).then((function(e){return salla.event.order.ordersFetched(e),e})).catch((function(e){throw salla.event.order.ordersNotFetched(e),e}))}}class v extends g{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftProductDetails:"products/{product_id}/buy-as-gift",productGiftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},this.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get"},this.after_init();}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}search(e){var t;let a=e.data;if(a||(a={params:"string"==typeof e?{query:e}:e}),!(e=a instanceof FormData?a.get("query"):a.query||(null==(t=a.params)?void 0:t.query))){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",a,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){var t;if(!(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then((function(t){return salla.product.event.offersFetched(t,e),t})).catch((function(t){throw salla.product.event.fetchOffersFailed(t,e),t}))}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then((t=>(salla.product.event.sizeGuideFetched(t,e),t))).catch((t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t}))}getGiftProductDetails(e){return this.request(["giftProductDetails",e]).then((t=>(salla.product.event.giftFetched(t,e),t))).catch((t=>{throw salla.product.event.giftFetchFailed(t,e),t}))}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t}))}addProductGiftToCart(e,t,a=false){return this.request(["productGiftToCart",e],t).then((t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t))).catch((t=>{throw salla.product.event.addGiftToCartFailed(t,e),t}))}uploadGiftImage(e){return this.request("giftImage",e).then((e=>(salla.product.event.giftImageUploadSucceeded(e),e))).catch((e=>{throw salla.product.event.giftImageUploadFailed(e),e}))}fetch(e){if(!e.source){const e="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}const t=!e.source_value,a="string"==typeof e.source_value&&"[]"===e.source_value,r=Array.isArray(e.source_value)&&!e.source_value.length;if((t||a||r)&&!["offers","latest","sales","wishlist","top-rated","reorder"].includes(e.source)){const e="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){const e="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("search"===e.source&&"string"!=typeof e.source_value){const e="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("related"===e.source&&isNaN(e.source_value)){const e="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then((async function(e){return salla.product.event.productListFetchSucceeded(e),e})).catch((e=>{throw salla.product.event.productListFetchFailed(e),e}))}fetchOptions(e,t={}){if(!e||0===e.length){const e="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(e),salla.api.errorPromise(e)}const{with:a=[]}=t,r={selected:e};return a.length>0&&(r.with=a),this.request(this.endpoints.fetchOptions,{params:r},"get").then((e=>(salla.product.event.productOptionsFetched(e),e))).catch((e=>{throw salla.product.event.productOptionsNotFetched(e),e}))}}class y extends g{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init();}syncUserData(e){let t={id:e.id,type:"user",email:e.email,mobile:e.phone.code+e.phone.number,country_code:e.phone.country,language_code:e.language,currency_code:e.currency,notifications:e.notifications,pending_orders:e.pending_orders,avatar:e.avatar,first_name:e.first_name,last_name:e.last_name,is_hidden_name:e.is_hidden_name,is_notifiable:e.is_notifiable,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",t),salla.storage.set("user",t);}info(){return this.request("info",null,"get").then((e=>(this.syncUserData(e.data),salla.profile.event.infoFetched(e),e))).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}update(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("update",e).then((e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e))).catch((e=>{throw salla.event.profile.updateFailed(e),e}))}updateCustomFields(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("updateCustomFields",e).then((e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e))).catch((e=>{throw salla.event.profile.updateFailed(e),e}))}updateContacts(e){return this.request("updateContacts",e).then((e=>(salla.profile.event.verificationCodeSent(e),e))).catch((e=>{throw salla.event.profile.updateContactsFailed(e),e}))}verify(e){return this.request("verify",e).then((e=>(salla.profile.event.verified(e),e))).catch((e=>{throw salla.event.profile.unverified(e),e}))}updateSettings(e){return this.request("updateSettings",e).then((e=>(salla.event.profile.settingsUpdated(e),e))).catch((e=>{throw salla.event.profile.updateSettingsFailed(e),e}))}delete(){return this.request("delete").then((e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.api.appendIframeAndLogout().then((()=>{salla.event.profile.deleted(e),window.location.href=salla.url.get("logout");})),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class C extends g{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init();}add(e){var t;if(null!=(t=e)&&t.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,true)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["addComment","blog"==e.type?"blogs":e.type,e.id],{comment:e.comment}).then((function(t){return salla.event.comment.added(t,e.id),t})).catch((function(t){throw salla.event.comment.additionFailed(t,e.id),t}))}getCommentPayload(e,t=false){let a={};if(["id","type","comment","per_page","page","sort"].forEach((t=>{let r=salla.form.getPossibleValue(e,[t]);r&&(a[t]=r);})),!t){let t=e.ids;if(t&&(a.ids=Array.isArray(t)?t:[t]),!a.ids||!a.ids.length)return "Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"}fetchComments(e){const t=e.customerId;if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const a={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(a.sort=e.sort),t&&(a.private_comments=t),this.request(["comments"],{params:a},"get").then((function(t){return salla.event.comment.fetched(t,e),t})).catch((function(t){throw salla.event.comment.fetchFailed(t,e),t}))}getComments(e,t,a=1,r=5,s,i=null){const n=Array.isArray(t)?t:[t];return this.fetchComments({ids:n,type:`${e}s`,page:a,per_page:r,sort:s,customerId:i})}}class S extends g{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init();}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then((function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t})).catch((function(t){throw salla.currency.event.failed(t,e),t}))}list(){return this.request("list").then((function(e){return salla.currency.event.fetched(e),e})).catch((function(e){throw salla.currency.event.failedToFetch(e),e}))}}class w extends g{constructor(){super(),this.namespace="document";}reload(){window.location.reload();}}class A extends g{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init();}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",a],t).then((function(e){return salla.event.rating.orderFetched(e,a),e})).catch((function(e){throw salla.event.rating.orderNotFetched(e,a),e}))}store(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then((function(t){return salla.event.rating.storeRated(t,e),t})).catch((function(t){throw salla.event.rating.storeFailed(t,e),t}))}products(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then((function(t){return salla.event.rating.productsRated(t,e),t})).catch((function(t){throw salla.event.rating.productsFailed(t,e),t}))}shipping(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then((function(t){return salla.event.rating.shippingRated(t,e),t})).catch((function(t){throw salla.event.rating.shippingFailed(t,e),t}))}}class E extends g{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},Salla.onReady((()=>{var e;"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||this.injectSourceIntoRequest());}));}injectSourceIntoRequest(){Salla.api.axios.interceptors.request.use((e=>(e.headers=h$1({},e.headers,{"s-utm-source":"wishlist"}),e)),(e=>Promise.reject(e)));}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["add",e]).then((t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t))).catch((function(t){throw salla.wishlist.event.additionFailed(t,e),t})):(salla.wishlist.event.additionFailed(a="Failed to get product id!"),salla.api.errorPromise(a))}remove(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,false),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(a="Failed to get id!"),salla.api.errorPromise(a))}updateWishlistStorage(e,t=true){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a);}}class b extends g{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init();}get(){return this.request("scopes",null,"get").then((e=>(salla.scope.event.fetched(e),e))).catch((e=>{throw salla.scope.event.notFetched(e),e}))}change(e){return this.request("scopes",e).then((e=>(salla.scope.event.changeSucceeded(e),e))).catch((e=>{throw salla.scope.event.changeFailed(e),e}))}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then((t=>(salla.scope.event.productAvailabilityFetched(t,e),t))).catch((e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e}))}}class _ extends g{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"};}async add(e,t=true){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then((function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e})).catch((function(e){throw salla.booking.event.additionFailed(e),e}))}}class k extends g{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init();}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then((function(t){return salla.event.landing.detailsFetched(t,e),t})).catch((function(t){throw salla.event.landing.getDetailsFailed(t,e),t}))}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then((function(t){return salla.event.landing.orderCreated(t,e).then((()=>location.href=t.data.url)),t})).catch((function(t){throw salla.event.landing.orderCreationFailed(t,e),t}))}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then((function(e){return salla.event.landing.breadcrumbFetched(e),e})).catch((function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e}))}}class x extends g{constructor(){super(),this.namespace="notifications",this.endpoints={fetch:"notifications"},this.endpointsMethods={fetch:"get"},this.after_init();}fetch(e){return this.request(["fetch"],{params:e}).then((function(e){return salla.event.notifications.fetched(e),e})).catch((function(e){throw salla.event.notifications.fetchFailed(e),e}))}}class B{constructor(){var e,t=this;this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",(async function(e){return await t.initiateRequest(e)})),salla.event.on("profile::info.fetched",(e=>this.setCurrencyAndLanguage(e))),salla.event.on("auth::token.fetched",(e=>{salla.storage.set("token",e),this.inIframe&&salla.log("token fetched iframe"),this.inIframe&&salla.cookie.set("s-token",e,60),this.setToken(e);})),salla.event.on("auth::token.invalid",(()=>{salla.storage.remove("user"),salla.storage.remove("token");})),this.notifier_handler_disabled=false,this.axios=axios.create({baseURL:Salla.config.get("store.api",Salla.config.get("store.url")),headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":(null==(e=Salla)||null==(e=e.versions)?void 0:e.twilight)||"2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}}),this.axios.interceptors.request.use((e=>{"preview"===Salla.config.get("theme.mode")&&(e.url=Salla.url.addParamToUrl("use_username_url",1,e.url));try{var t;const a=Salla.config.get("swoole",[]),r=new RegExp(a.join("|"),"i");a.length>0&&r.test(e.url)&&(e.headers["s-store-api-version"]="swoole");const s=null==(t=Salla.analytics)?void 0:t.getAnonymousId();s&&(e.headers["s-anonymous-id"]=s);}catch(e){Salla.log("Error in request interceptor:",e);}return e}),(e=>Promise.reject(e)));}getHeaders(){let e=h$1({},this.axios.defaults.headers.common);return delete e["Content-Type"],e}getHeader(e){var t;return null==(t=Object.entries(this.getHeaders()).filter((([t])=>t.toLowerCase()===e.toLowerCase()))[0])?void 0:t[1]}setHeaders(e){return Object.entries(e).forEach((e=>this.setHeader(e[0],e[1]))),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=true,await e().finally((()=>{this.notifier_handler_disabled=false;}))}async initiateRequest(e){var t,a,r;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(h$1({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(r=e.user)?void 0:r.country_code},e.headers||{}));const s=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search),n=i.get("scope"),o=i.get("allocation_type"),l=i.get("allocation_id");if(n&&s&&!Salla.url.is_page("cart")){const e=Salla.storage.get("scope")||{};Salla.storage.set("scope",h$1({},e,{type:s.type,id:n},o&&{allocation_type:o},l&&{allocation_id:l})),s.id=n,Salla.cart.reset();}if((o||l)&&(Salla.url.is_page("cart")||!n||!s)){const e=Salla.storage.get("scope")||{};var u,c;if(null!=e&&e.id||null!=s&&s.id)Salla.storage.set("scope",h$1({},e,{id:null!=(u=null==e?void 0:e.id)?u:null==s?void 0:s.id,type:null!=(c=null==e?void 0:e.type)?c:null==s?void 0:s.type},o&&{allocation_type:o},l&&{allocation_id:l}));}if(s){this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const e=Salla.storage.get("scope")||{};e.allocation_type&&this.setHeader("s-scope-allocation-type",e.allocation_type),e.allocation_id&&this.setHeader("s-scope-allocation-id",e.allocation_id);}const d=Salla.storage.getWithTTL("s-utms");if(d){const e={};Object.entries(d).forEach((([t,a])=>{e[t]="string"==typeof a&&/[^\x00-\x7F]/.test(a)?encodeURIComponent(a):a;})),this.setHeaders(e);}await this.injectTokenToTheRequests(e),Salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",Salla.storage.get("affiliate_code"));}async injectTokenToTheRequests(e){var t,a,r=this;let i,n,o=this.getToken(),l="guest"===(null==(t=e.user)?void 0:t.type),u=parseInt((null==(a=e.user)?void 0:a.id)||0),c=parseInt(salla.storage.get("user.id")||0),d=salla.auth.api.isSessionless(),h=e=>{this.setToken(e),salla.event.emit("api::initiated");},p=async function(){l||d||!u?salla.auth.event.tokenInvalid():(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then((async function(){await salla.profile.info();})).catch((()=>salla.auth.event.tokenInvalid())));};if(!o)return salla.log("Api:: case 1 => current is is guest"),void await p();try{i=jwtDecode(o);}catch(e){return Salla.logger.warn("Failed to decode JWT token",e),void Salla.auth.event.tokenInvalid()}return Date.now()/1e3>i.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await p()):(n=d?parseInt(i.sub)!==c:!c||!u||c!==u||parseInt(i.sub)!==u,n?(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${i.sub} userIdInWeb:${u} userIdInStorage:${c}, isSessionless:${d}`,i.sub,u,c),this.setHeader("Authorization","Bearer "+o),void await salla.profile.info().then((async function(e){!r.inIframe&&!d&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),h(o);})).catch((()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid();}))):(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void h(o)))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}cleanupTokenFromUrl(){try{const e=new URL(window.location.href);if(!e.searchParams.has("token"))return;e.searchParams.delete("token"),window.history.replaceState({},document.title,e.toString());}catch(e){Salla.logger.warn("Failed to cleanup token from URL",e);}}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t=void 0,a="get",r={}){let s={endPoint:e,payload:t,method:a,options:r},i="undefined"!=typeof event?event.currentTarget:null,n=false;return "SALLA-BUTTON"===(null==i?void 0:i.tagName)&&(n=true),n&&(null==i||i.load()),this.axios[s.method](s.endPoint,s.payload,s.options).then((e=>(n&&(null==i||i.stop()),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&(null==i||i.stop()),salla.event.document.requestFailed(s,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;try{dataLayer&&r&&dataLayer.push(r);}catch(e){salla.logger.error(e.message);}this.fireEventsForResponse(e),this.showAlert(e);}fireEventsForResponse(e){var t,a;let r=(null==e?void 0:e.events)||(null==(t=e.data)?void 0:t.events)||(null==(a=e.error)?void 0:a.events);"string"==typeof r&&(r=JSON.parse(r)),r&&Object.keys(r).forEach((e=>salla.event.dispatch(e,r[e])));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){var t,a;if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&null!=(t=e.data)&&t.message?salla.notify.fire(null==(a=e.data)?void 0:a.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach((e=>{let r=t[e];Array.isArray(r)?r.forEach((e=>a.push(e))):a.push(r);}));let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=true){return new Promise(((a,r)=>t?a(e):r(e)))}errorPromise(e){return this.promise(e,false)}successPromise(e){return this.promise(e,true)}getToken(){if(Salla.storage.get("token"))return Salla.storage.get("token");try{var e;const t=null==(e=new URLSearchParams(window.location.search))?void 0:e.get("token");if(!t)return;if(3!==t.split(".").length)return;return this.cleanupTokenFromUrl(),t}catch(e){Salla.logger.warn("Failed to extract or validate token from URL",e);}}}class P extends g{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}?store_id={store}&lang={lang}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"};}async getMenus(e="header"){return this.request(["getMenus",e,salla.config.get("store.id"),salla.lang.getLocale()]).then((function(e){return salla.event.component.menuFetched(e),e})).catch((function(e){throw salla.event.component.menuFetchFailed(e),e}))}async getReviews({per_page:e=5,type:t="all",items:a}){if(!t){const e="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}const r=!a||"string"==typeof a&&"[]"===a||Array.isArray(a)&&!a.length;if(!new Set(["all","store","categories","products","json"]).has(t)){const e="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if("all"!==t&&"store"!==t&&r){const e="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if(new Set(["products","categories"]).has(t)&&!Array.isArray(a)){const e=`Items value must be an array of ${t} id for review type of ${t}.`;return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}return this.request(["reviews"],{params:{per_page:e,type:t,items:a}},"get").then((function(e){return salla.event.component.reviewsFetched(e),e})).catch((function(e){throw salla.event.component.reviewsFetchFailed(e),e}))}}class I extends g{constructor(){super(),this.namespace="booking",this.endpoints={fetch:"advertisements"},this.endpointsMethods={fetch:"get"};}async fetch(e=null){const t=e?{page:e}:{};return this.request(["fetch"],{params:t}).then((function(e){return salla.event.advertisement.fetched(e),e})).catch((function(e){throw salla.event.advertisement.fetchFailed(e),e}))}}class q extends g{constructor(){super(),this.namespace="navigation",this.endpoints={breadcrumbs:"breadcrumbs"},this.endpointsMethods={breadcrumbs:"get"},this.after_init();}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.single","product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then((function(e){return salla.event.navigation.breadcrumbFetched(e),e})).catch((function(e){throw salla.event.navigation.breadcrumbFetchFailed(e),e}))}}class T extends g{constructor(){super(),this.namespace="metadata",this.endpoints={fetchValues:"https://api.salla.dev/store/v1/metadata/values"},this.endpointsMethods={fetchValues:"get"};}async fetchValues(e,t){if(!e||!t){const e="Please provide entity type and entity ids.";return salla.metadata.event.valueNotFetch(e),salla.api.errorPromise(e)}const a={type:e,entities:Array.isArray(t)?t:[t]};return this.request(this.endpoints.fetchValues,{params:a},"get").then((e=>(salla.metadata.event.valueFetched(e),e))).catch((e=>{throw salla.metadata.event.valueNotFetch(e),e}))}}class L{constructor(e){this.config=e,this.configKey="s-twilight-config",this.tempUser=e.user;}async getConfig(){if(Object.entries(this.config.store).length>2)return this.config;let e=await this.getConfigFromSession();return e||(e=await this.getConfigFromApi()),e.user=this.tempUser,e}async getConfigFromSession(){var e;let t=salla.storage.getWithTTL("session",this.configKey);return t&&"object"==typeof t&&null!=(e=t.store)&&e.id?this.config.store.id==t.store.id?t:(salla.storage.session.remove(this.configKey),null):null}getConfigFromApi(){console.log("getting Twilight initiate config using store.id ...");const e=new URL(`${(this.config.store.api||Salla.config.get("store.api")).replace(/\/$/,"")}/store/settings`);return fetch(e,{headers:Salla.api.getHeaders()}).then((e=>e.json())).then((e=>{if(200!==e.status)throw {response:e};return this.setConfigToSession(e.data)})).catch((e=>{throw Salla.api.handleErrorResponse(e),e}))}setConfigToSession(e){return Salla.storage.setWithTTL("session",this.configKey,e,1800),e}}class R{constructor(){Salla.event.on("twilight::before.ready",(()=>this.renderAll()));}async renderAll(){Salla.hooks.renderAutoComponents([{hook:"product:single.description",tag:"salla-delivery-promise",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("delivery-promises")},{hook:"product:single.form.end",tag:"salla-fulfillment-methods",canRender:()=>Salla.url.is_page("product.single")&&!Salla.config.get("store.features",[]).includes("bullet-delivery-v2")},{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}},{hook:"body:end",tag:"salla-bullet-delivery",canRender:()=>{var e;return (null==(e=Salla.config.get("store.features"))?void 0:e.includes("bullet-delivery-v2"))&&true===Salla.config.get("store.settings.bullet_delivery.enabled")}}]),await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.helpers.isIframe()||(this.renderMaintenance(),this.renderThemePreview());}renderMaintenance(){Salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?Salla.logger.warn("salla-maintenance-alert element Existed before!"):document.body.prepend(document.createElement("salla-maintenance-alert")));}renderTemplateStore(){Salla.config.get("store.template")&&(document.body.classList.add("has-bottom-alert"),document.querySelector("salla-bottom-alert")?Salla.logger.warn("salla-bottom-alert element Existed before!"):document.body.append(document.createElement("salla-bottom-alert")));}renderAppInstall(){Salla.config.get("store.app_install_prompt")&&Salla.config.get("store.apps")&&!Salla.storage.get("app_install_prompt_disabled")&&!Salla.config.isMobileApp()&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?Salla.logger.warn("salla-app-install-alert element Existed before!"):document.body.append(document.createElement("salla-app-install-alert")));}renderThemePreview(){if("preview"!==Salla.config.get("theme.mode"))return;if(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar"))return void Salla.logger.warn("#s-theme_preview_bar element Existed before!");let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://cdn.salla.network/images/logo/logo-light.svg">\n <span style="margin:0 10px;">${Salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${Salla.config.get("theme.name")}</span></span>\n </div>\n <a href="${Salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e);}renderEdit(){let e=Salla.config.get("edit");if(!e)return;if(document.querySelector("#s-edit-alert"))return void Salla.logger.warn("#s-edit-alert element Existed before!");let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${Salla.config.get("theme.color.primary","#5cd5c4")}; color:${Salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${Salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t);}applyContentCopyright(){if(!Salla.config.get("store.settings.content_copyright"))return;["contextmenu","selectstart","copy"].forEach((e=>{document.addEventListener(e,(e=>{(e=>{var t;if(!e)return false;const a=null==(t=e.tagName)?void 0:t.toLowerCase();return "input"===a||"textarea"===a})(e.target)||e.preventDefault();}));})),document.addEventListener("keydown",(e=>{const t=e.key.toLowerCase();("f12"===t||e.ctrlKey&&e.shiftKey&&["i","j","c"].includes(t)||e.ctrlKey&&"u"===t)&&(e.preventDefault(),e.stopPropagation());}));const e=document.createElement("style");e.textContent="\n body {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n input, textarea {\n -webkit-touch-callout: auto;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n -ms-user-select: auto;\n user-select: auto;\n }\n img {\n pointer-events: none;\n -webkit-user-drag: none;\n }\n ",document.head.appendChild(e);}}class j{constructor(e){this.storeUserKey="s-store-user",Salla.event.on("twilight::initiated",(()=>this.embedStoreUser())),this.embedUser(e);}embedUser(e){return e.user||(e.user=this.getUser(),e.user.language_code=Salla.cookie.get("s-lang",e.user.language_code),e.user.currency_code=Salla.cookie.get("s-curr",e.user.currency_code)),e}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return {type:"guest",language_code:Salla.cookie.get("s-lang",Salla.lang.getLocale()),currency_code:Salla.cookie.get("s-curr","SAR")}}async embedStoreUser(){if(Salla.config.isGuest())return;let e=Salla.storage.getWithTTL("session",this.storeUserKey);e||(e=await this.getStoreUserFromApi()),Salla.config.set("user",h$1({},Salla.config.get("user"),e)),Salla.log("Store user is embeded to the user object.");}async getStoreUserFromApi(){let e={};try{const t=await Salla.api.request("profile/notifications/unread");if(e.notification=t.data.count,e.is_notifiable=t.data.is_notifiable,Salla.config.get("store.features",[]).includes("loyalty-system")){const t=await Salla.api.request("profile/loyalty/points");t&&(e.loyalty_points=t.data.points);}}catch(e){Salla.log("Failed to get user services",e);}return Salla.storage.setWithTTL("session",this.storeUserKey,e,300),e}}class U{constructor(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat",sccid:"snapchat"},t=Object.keys(e),a=["utm_source","utm_medium","utm_campaign","utm_term","utm_content",...t],r={},s={};window.location.search.replace("?","").split("&").map((e=>e.split("="))).filter((([e])=>a.includes(e.toLowerCase()))).forEach((([e,t])=>{let a=t||"",s=false;try{a=decodeURIComponent(t),s=true;}catch(e){Salla.log("Failed to decode UTM param:",e);}r[e.toLowerCase()]=s?a.replace(/(?:[\0-\x1F!-,\.\/:-@\[-`\{-\xA9\xAB-\xB1\xB4\xB6-\xB8\xBB\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u036F\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482-\u0489\u0530\u0557\u0558\u055A-\u055F\u0589-\u05CF\u05EB-\u05EE\u05F3-\u061F\u064B-\u065F\u066A-\u066D\u0670\u06D4\u06D6-\u06E4\u06E7-\u06ED\u06FD\u06FE\u0700-\u070F\u0711\u0730-\u074C\u07A6-\u07B0\u07B2-\u07BF\u07EB-\u07F3\u07F6-\u07F9\u07FB-\u07FF\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u083F\u0859-\u085F\u086B-\u086F\u0888\u0890-\u089F\u08CA-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962-\u0965\u0970\u0981-\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA-\u09BC\u09BE-\u09CD\u09CF-\u09DB\u09DE\u09E2-\u09E5\u09F2\u09F3\u09FA\u09FB\u09FD-\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A-\u0A58\u0A5D\u0A5F-\u0A65\u0A70\u0A71\u0A75-\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA-\u0ABC\u0ABE-\u0ACF\u0AD1-\u0ADF\u0AE2-\u0AE5\u0AF0-\u0AF8\u0AFA-\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A-\u0B3C\u0B3E-\u0B5B\u0B5E\u0B62-\u0B65\u0B70\u0B78-\u0B82\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BCF\u0BD1-\u0BE5\u0BF3-\u0C04\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C3E-\u0C57\u0C5B\u0C5E\u0C5F\u0C62-\u0C65\u0C70-\u0C77\u0C7F\u0C81-\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA-\u0CBC\u0CBE-\u0CDB\u0CDF\u0CE2-\u0CE5\u0CF0\u0CF3-\u0D03\u0D0D\u0D11\u0D3B\u0D3C\u0D3E-\u0D4D\u0D4F-\u0D53\u0D57\u0D62-\u0D65\u0D79\u0D80-\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DE5\u0DF0-\u0E00\u0E31\u0E34-\u0E3F\u0E47-\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EB1\u0EB4-\u0EBC\u0EBE\u0EBF\u0EC5\u0EC7-\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F1F\u0F34-\u0F3F\u0F48\u0F6D-\u0F87\u0F8D-\u0FFF\u102B-\u103E\u104A-\u104F\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B-\u1368\u137D-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u1712-\u171E\u1732-\u173F\u1752-\u175F\u176D\u1771-\u177F\u17B4-\u17D6\u17D8-\u17DB\u17DD-\u17DF\u17EA-\u17EF\u17FA-\u180F\u181A-\u181F\u1879-\u187F\u1885\u1886\u18A9\u18AB-\u18AF\u18F6-\u18FF\u191F-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19FF\u1A17-\u1A1F\u1A55-\u1A7F\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1B04\u1B34-\u1B44\u1B4D-\u1B4F\u1B5A-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BFF\u1C24-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C8B-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1CFB-\u1CFF\u1DC0-\u1DFF\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u206F\u2072\u2073\u207A-\u207E\u208A-\u208F\u209D-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A-\u245F\u249C-\u24E9\u2500-\u2775\u2794-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF4-\u2CFC\u2CFE\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF-\u2E2E\u2E30-\u3004\u3008-\u3020\u302A-\u3030\u3036\u3037\u303D-\u3040\u3097-\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u3191\u3196-\u319F\u31C0-\u31EF\u3200-\u321F\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA66F-\uA67E\uA69E\uA69F\uA6F0-\uA716\uA720\uA721\uA789\uA78A\uA7DD-\uA7F0\uA802\uA806\uA80B\uA823-\uA82F\uA836-\uA83F\uA874-\uA881\uA8B4-\uA8CF\uA8DA-\uA8F1\uA8F8-\uA8FA\uA8FC\uA8FF\uA926-\uA92F\uA947-\uA95F\uA97D-\uA983\uA9B3-\uA9CE\uA9DA-\uA9DF\uA9E5\uA9FF\uAA29-\uAA3F\uAA43\uAA4C-\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAC3-\uAADA\uAADE\uAADF\uAAEB-\uAAF1\uAAF5-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABE3-\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB1E\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD06\uDD34-\uDD3F\uDD79-\uDD89\uDD8C-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEE0\uDEFC-\uDEFF\uDF24-\uDF2C\uDF4B-\uDF4F\uDF76-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDD6F\uDD7B\uDD8B\uDD93\uDD96\uDDA2\uDDB2\uDDBA\uDDBD-\uDDBF\uDDF4-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDF7F\uDF86\uDFB1\uDFBB-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56\uDC57\uDC77\uDC78\uDC9F-\uDCA6\uDCB0-\uDCDF\uDCF3\uDCF6-\uDCFA\uDD1C-\uDD1F\uDD3A-\uDD3F\uDD5A-\uDD7F\uDDB8-\uDDBB\uDDD0\uDDD1\uDE01-\uDE0F\uDE14\uDE18\uDE36-\uDE3F\uDE49-\uDE5F\uDE7F\uDEA0-\uDEBF\uDEC8\uDEE5-\uDEEA\uDEF0-\uDEFF\uDF36-\uDF3F\uDF56\uDF57\uDF73-\uDF77\uDF92-\uDFA8\uDFB0-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCF9\uDD24-\uDD2F\uDD3A-\uDD3F\uDD66-\uDD6E\uDD86-\uDE5F\uDE7F\uDEAA-\uDEAF\uDEB2-\uDEC1\uDEC8-\uDEFF\uDF28-\uDF2F\uDF46-\uDF50\uDF55-\uDF6F\uDF82-\uDFAF\uDFCC-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC00-\uDC02\uDC38-\uDC51\uDC70\uDC73\uDC74\uDC76-\uDC82\uDCB0-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDD02\uDD27-\uDD35\uDD40-\uDD43\uDD45\uDD46\uDD48-\uDD4F\uDD73-\uDD75\uDD77-\uDD82\uDDB3-\uDDC0\uDDC5-\uDDCF\uDDDB\uDDDD-\uDDE0\uDDF5-\uDDFF\uDE12\uDE2C-\uDE3E\uDE41-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEDF-\uDEEF\uDEFA-\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A-\uDF3C\uDF3E-\uDF4F\uDF51-\uDF5C\uDF62-\uDF7F\uDF8A\uDF8C\uDF8D\uDF8F\uDFB6\uDFB8-\uDFD0\uDFD2\uDFD4-\uDFFF]|\uD805[\uDC35-\uDC46\uDC4B-\uDC4F\uDC5A-\uDC5E\uDC62-\uDC7F\uDCB0-\uDCC3\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDAF-\uDDD7\uDDDC-\uDDFF\uDE30-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEAB-\uDEB7\uDEB9-\uDEBF\uDECA-\uDECF\uDEE4-\uDEFF\uDF1B-\uDF2F\uDF3C-\uDF3F\uDF47-\uDFFF]|\uD806[\uDC2C-\uDC9F\uDCF3-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD30-\uDD3E\uDD40\uDD42-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD1-\uDDE0\uDDE2\uDDE4-\uDDFF\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE4F\uDE51-\uDE5B\uDE8A-\uDE9C\uDE9E-\uDEAF\uDEF9-\uDFBF\uDFE1-\uDFEF\uDFFA-\uDFFF]|\uD807[\uDC09\uDC2F-\uDC3F\uDC41-\uDC4F\uDC6D-\uDC71\uDC90-\uDCFF\uDD07\uDD0A\uDD31-\uDD45\uDD47-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8A-\uDD97\uDD99-\uDD9F\uDDAA-\uDDAF\uDDDC-\uDDDF\uDDEA-\uDEDF\uDEF3-\uDF01\uDF03\uDF11\uDF34-\uDF4F\uDF5A-\uDFAF\uDFB1-\uDFBF\uDFD5-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD812-\uD817\uD819\uD824-\uD82A\uD82D\uD82E\uD830-\uD832\uD836\uD83D\uD83F\uD87C\uD87D\uD87F\uD88E-\uDBFF][\uDC00-\uDFFF]|\uD80B[\uDC00-\uDF8F\uDFF1-\uDFFF]|\uD80D[\uDC30-\uDC40\uDC47-\uDC5F]|\uD810[\uDFFB-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD818[\uDC00-\uDCFF\uDD1E-\uDD2F\uDD3A-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDE6F\uDEBF\uDECA-\uDECF\uDEEE-\uDEFF\uDF30-\uDF3F\uDF44-\uDF4F\uDF5A\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDD3F\uDD6D-\uDD6F\uDD7A-\uDE3F\uDE97-\uDE9F\uDEB9\uDEBA\uDED4-\uDEFF\uDF4B-\uDF4F\uDF51-\uDF92\uDFA0-\uDFDF\uDFE2\uDFE4-\uDFF1\uDFF7-\uDFFF]|\uD823[\uDCD6-\uDCFE\uDD1F-\uDD7F\uDDF3-\uDFFF]|\uD82B[\uDC00-\uDFEF\uDFF4\uDFFC\uDFFF]|\uD82C[\uDD23-\uDD31\uDD33-\uDD4F\uDD53\uDD54\uDD56-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDFFF]|\uD833[\uDC00-\uDCEF\uDCFA-\uDFFF]|\uD834[\uDC00-\uDEBF\uDED4-\uDEDF\uDEF4-\uDF5F\uDF79-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD837[\uDC00-\uDEFF\uDF1F-\uDF24\uDF2B-\uDFFF]|\uD838[\uDC00-\uDC2F\uDC6E-\uDCFF\uDD2D-\uDD36\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDE8F\uDEAE-\uDEBF\uDEEC-\uDEEF\uDEFA-\uDFFF]|\uD839[\uDC00-\uDCCF\uDCEC-\uDCEF\uDCFA-\uDDCF\uDDEE\uDDEF\uDDFB-\uDEBF\uDEDF\uDEE3\uDEE6\uDEEE\uDEEF\uDEF5-\uDEFD\uDF00-\uDFDF\uDFE7\uDFEC\uDFEF\uDFFF]|\uD83A[\uDCC5\uDCC6\uDCD0-\uDCFF\uDD44-\uDD4A\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDC70\uDCAC\uDCB0\uDCB5-\uDD00\uDD2E\uDD3E-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDCFF\uDD0D-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEE0-\uDEFF]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEAE\uDEAF]|\uD87A[\uDFE1-\uDFEF]|\uD87B[\uDE5E-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDF4F]|\uD88D[\uDC7A-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g," ").replace(/ +/g," ").trim():a;}));const i=t.find((e=>r[e]));!r.utm_source&&i&&(r.utm_source=e[i],r.utm_campaign=r.utm_campaign||`Using the CLICKID ${i} provided by ${r.utm_source}`,r.utm_term=r.utm_term||`${i}: ${r[i]}`),r.utm_source&&(Object.entries(r).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{s[`s-${e.replace("_","-")}`]=t;})),s["s-utm-referrer"]=document.referrer,Salla.storage.setWithTTL("s-utms",s,129600),this.logUTMVisitData(s));}async logUTMVisitData(e){const t=e["s-utm-source"],a=e["s-utm-medium"],r=e["s-utm-campaign"],s=Salla.config.get("store.id");e&&"affiliate"===t&&a&&r&&fetch(Salla.config.get("affiliate.utm_url"),{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","s-utm-source":t,"s-utm-medium":a,"s-utm-campaign":r,"s-store-id":s}}).then((e=>{if(!e.ok)return;const t=new URL(window.location.href),a=window.history.state;t.searchParams.delete("utm_source"),t.searchParams.delete("utm_medium"),t.searchParams.delete("utm_campaign"),window.history.replaceState(a,"",t);}));}}class O{constructor(e){var t,a,r;if("ready"!==Salla.status){if(null==e||null==(t=e.store)||!t.id)return console.error("Trying to init Twilight without store.id!"),void console.log("you can initiate twilight using this line only: Salla.init({store:{id:1234}})");var s;if(Salla.config.merge(e),!["salla.sa","salla.group"].includes(location.hostname)||null!=(a=Salla.config.get("store.url"))&&a.includes(location.hostname)||!Salla.config.get("store.username")||Salla.config.set("store.url",window.location.origin+"/"+Salla.config.get("store.username")),(null==e?void 0:e.events)&&Salla.event.dispatchEvents(null==e?void 0:e.events),new R,new j(e),null!=e&&null!=(r=e.user)&&r.language_code)Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);Salla.storage.get("scope.id")!=Salla.config.get("store.scope.id")&&Salla.storage.set("scope",Salla.config.get("store.scope",Salla.config.get("scope"))),new L(e).getConfig().then((e=>{Salla.config.merge(e),this.setSallaReady(e),this.afterInit();})).catch((e=>console.error("failed to initite twilight😢",e)));}else Salla.log("Trying to re-initiate Salla, while its status === 'ready'!");}afterInit(){Salla.url.is_page("product.single")&&Salla.config.isGuest()&&window.addEventListener("mini-checkout::before-init",(e=>{e.preventDefault(),Salla.event.emit("login::open");}));}setSallaReady(e){new U,Salla.event.emitAsync("twilight::before.ready",e),Salla.status="ready",Salla.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}));}}class N{constructor(e){const t=null==e?void 0:e.nextPage;this.listId=salla.config.get("page.slug"),Salla.config.get("page.id")&&(this.listId+=`_${salla.config.get("page.id")}`),this.sorts=null;try{if(t){const e=new URL(t).searchParams.get("sort");e&&(this.sorts=[{type:"sort",value:e}]);}e.source&&(this.listId=`${this.listId}_${e.source}`),e.sourceValue&&(this.listId=`${this.listId}_${Array.isArray(e.sourceValue)?e.sourceValue.join("_"):e.sourceValue}`);}catch(e){salla.logger.error(e);}this.products=null==e?void 0:e.data;}toSegment(){const e=(salla.config.get("page.title")||"").split("|").map((e=>e.trim())),t=e[0],a=e[1]||null;return {event:"Product List Viewed",properties:{list_id:this.listId,category:t,sub_category:a,sorts:this.sorts,products:this.products.map((e=>{var t,a,r,s,i,n;return {product_id:e.id,category:null==(t=e.category)?void 0:t.name,currency:null==(a=Salla.config.currency())?void 0:a.code,name:e.name,brand:null==(r=e.brand)?void 0:r.name,variant:null==(s=e.variant)?void 0:s.toString(),coupon:null==(i=e.coupon)?void 0:i.toString(),price:e.price,quantity:Number(e.quantity),sku:e.sku,position:0,url:e.url,image_url:null==(n=e.image)?void 0:n.url}}))}}}static shouldSend(e){return !((null==e?void 0:e.nextPage)||"").includes("filters")&&!["index","customer.wishlist"].includes(salla.config.get("page.slug"))}}class M{constructor(){this.user=JSON.parse(localStorage.getItem("user"));}toSegment(){var e,t,a,r,s;return {event:"Signed In",properties:{first_name:null==(e=this.user)?void 0:e.first_name,last_name:null==(t=this.user)?void 0:t.last_name,type:null==(a=this.user)?void 0:a.type,mobile:null==(r=this.user)?void 0:r.mobile,email:null==(s=this.user)?void 0:s.email}}}static shouldSend(){return "user"===Salla.config.get("user.type")?!Salla.analytics.history.find((({eventName:e})=>"Signed In"===e)):(Salla.profile.event.onInfoFetched((()=>Salla.event.emit("Signed In"))),false)}}class ${constructor(e){this.details=null==e?void 0:e.data;}toSegment(){const e=["first_name","last_name","birthday","gender"].filter((e=>{var t,a;return $.user[e]!==(null==(t=this.details)?void 0:t[e])&&(void 0!==$.user[e]||void 0!==(null==(a=this.details)?void 0:a[e]))}));return $.setUser(this.details),{event:"User Profile Updated",properties:{updated_fields:e}}}static registerEvent(){Salla.onReady((()=>{salla.url.is_page("customer.profile")&&$.setUser(Salla.config.get("user"));}));}static setUser(e){$.user={first_name:null==e?void 0:e.first_name,last_name:null==e?void 0:e.last_name,gender:null==e?void 0:e.gender,birthday:null==e?void 0:e.birthday,avatar:null==e?void 0:e.avatar};}static shouldSend(){return "user"===Salla.config.get("user.type")}}$.user={};class H{static registerEvents(){Object.values(this.events).forEach((e=>{e.forEach((e=>{"function"==typeof e.registerEvent&&e.registerEvent();}));}));}static transform(e,t){try{const a=this.events[e]||[];for(const e of a){if(!e||"function"==typeof e.shouldSend&&!e.shouldSend(t))continue;const a=new e(t).toSegment();return {event:a.event,properties:a.properties}}return null}catch(e){return console.error("Failed to transform event:",e),null}}}H.events={"Order Completed":[class{constructor(e){this.details=e[0];}toSegment(){return {event:"Order Completed",properties:this.details}}}],"Product Added":[class{constructor(e){var t,a;this.item=e[0],this.source=(null==(t=Salla.cart)||null==(t=t.api)?void 0:t.addToCartSource)||null,null!=(a=Salla.cart)&&a.api&&(Salla.cart.api.addToCartSource=null);}toSegment(){var e,t,a,r,s;return {event:"Product Added",properties:{cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),cart_item_id:null==(t=this.item.cart_item_id)?void 0:t.toString(),product_id:null==(a=this.item.id)?void 0:a.toString(),category:this.item.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:this.item.name,brand:this.item.brand,variant:null==(s=this.item.variant)?void 0:s.toString(),price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url,source:this.source}}}static shouldSend(){return "customer.wishlist"!==salla.config.get("page.slug")}},class{constructor(e){this.item=e[0];}toSegment(){var e,t;return {event:"Wishlist Product Added to Cart",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,name:this.item.name,brand:this.item.brand,variant:this.item.variant,price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}}static shouldSend(){return "customer.wishlist"===salla.config.get("page.slug")}}],"Product Removed":[class{constructor(e){this.item=e[0];}toSegment(){var e,t,a,r,s,i,n,o,l,u,c,d,h,p;return {event:"Product Removed",properties:{cart_id:null==(e=this.item)||null==(e=e.cart_id)?void 0:e.toString(),product_id:null==(t=this.item)||null==(t=t.id)?void 0:t.toString(),category:null==(a=this.item)?void 0:a.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:null==(s=this.item)?void 0:s.name,brand:null==(i=this.item)?void 0:i.brand,variant:null==(n=this.item)?void 0:n.variant,price:null==(o=this.item)?void 0:o.price,quantity:null==(l=this.item)?void 0:l.quantity,sku:null==(u=this.item)?void 0:u.sku,coupon:null==(c=this.item)?void 0:c.coupon,position:null==(d=this.item)?void 0:d.position,url:null==(h=this.item)?void 0:h.url,image_url:null==(p=this.item)?void 0:p.image_url}}}}],"Product Viewed":[class{constructor(e){this.product=e[0];try{this.source=sessionStorage.getItem("s-viewed-source")||null,sessionStorage.removeItem("s-viewed-source");}catch(e){this.source=null;}}toSegment(){var e;return {event:"Product Viewed",properties:{product_id:null==(e=this.product.id)?void 0:e.toString(),category:this.product.category,name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:this.product.quantity,currency:this.product.currency,coupon:this.product.coupon,position:this.product.position,value:this.product.value,sku:this.product.sku,url:this.product.url,image_url:this.product.image_url,source:this.source}}}}],"Product Added to Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Added to Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,position:Number(this.product.position||0),url:this.product.url,image_url:(null==(t=this.product)?void 0:t.image)||null,category:this.product.category,currency:null==(a=Salla.config.currency())?void 0:a.code,brand:this.product.brand}}}}],"Product Removed from Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Removed from Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,coupon:this.product.coupon||null,position:Number(this.product.position||0),currency:null==(t=Salla.config.currency())?void 0:t.code,url:this.product.url,image_url:(null==(a=this.product)?void 0:a.image)||null,category:this.product.category,brand:this.product.brand}}}}],"Cart Viewed":[class{constructor(e){this.cart=e[0];}toSegment(){var e;return {event:"Cart Viewed",properties:{cart_id:null==(e=this.cart.cart_id)?void 0:e.toString(),products:this.cart.products.map((e=>{var t,a,r;return {product_id:null==(t=e.id)?void 0:t.toString(),cart_item_id:null==(a=e.cart_item_id)?void 0:a.toString(),name:e.name,price:e.price,category:e.category,sku:e.sku,position:e.position,url:e.url,image_url:e.image_url,brand:e.brand,currency:null==(r=Salla.config.currency())?void 0:r.code,variant:e.variant,coupon:e.coupon,quantity:e.quantity}}))}}}}],"Products Searched":[class{constructor(e){this.query=e;}toSegment(){return {event:"Products Searched",properties:{query:this.query}}}}],"Product List Viewed":[N],"Product List Filtered":[class extends N{constructor(e){super(e);const t=(null==e?void 0:e.nextPage)||"";this.filters=this.extractFilters(t);}extractFilters(e){if(!e)return null;try{const t=new URL(e),a=[];return Array.from(t.searchParams.entries()).forEach((([e,t])=>{if(e.startsWith("filters[")){const r=e.match(/^filters\[(.*?)\]/),s=r?r[1]:e;a.push({type:s,value:t});}})),a.length>0?a:null}catch(e){return console.warn("Error extracting filters from URL:",e),null}}toSegment(){const e=super.toSegment();return {event:"Product List Filtered",properties:h$1({},null==e?void 0:e.properties,{filters:this.filters})}}static shouldSend(e){return ((null==e?void 0:e.nextPage)||"").includes("filters")}}],"Signed Up":[class extends M{toSegment(){const e=super.toSegment();return {event:"Signed Up",properties:null==e?void 0:e.properties}}static shouldSend(){return "user"===Salla.config.get("user.type")||(Salla.profile.event.onInfoFetched((()=>Salla.event.emit("Signed Up"))),false)}}],"Signed In":[M],"Signed Out":[class{toSegment(){return {event:"Signed Out",properties:{}}}}],"Product Reviewed":[class{constructor(e){this.details=e;}toSegment(){return {event:"Product Reviewed",properties:this.details}}static registerEvent(){salla.event.rating.onProductsRated((function(e,t){const{products:a,order_id:r}=t;Object.values(a).forEach((e=>{var t;Salla.event.emit("Product Reviewed",{product_id:null==(t=e.product_id)?void 0:t.toString(),review_id:null==r?void 0:r.toString(),review_body:e.comment,rating:e.rating});}));}));}}],"Product Shared":[class{constructor(e){this.data=e;}toSegment(){var e;const t=(null==(e=Salla.analytics.history.find((({eventName:e})=>"Product Viewed"===e)))?void 0:e.payload)||{};return t.share_via=this.data.share_via,{event:"Product Shared",properties:t}}static shouldSend(){return "product.single"===salla.config.get("page.slug")}}],"Promotion Viewed":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Viewed",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Promotion Clicked":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Clicked",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Coupon Applied":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Applied",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Removed":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Removed",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Denied":[class{constructor(e){this.transaction=e;}getCartId(){var e;return "cart"===salla.config.get("page.slug")?null==(e=salla.config.get("page.id"))?void 0:e.toString():""}getCouponCode(){try{var e,t;const a=null==(e=this.transaction.response)||null==(e=e.config)?void 0:e.data;return a?null==(t=JSON.parse(a))?void 0:t.coupon:""}catch(e){return ""}}toSegment(){var e;return {event:"Coupon Denied",properties:{cart_id:this.getCartId(),coupon_name:this.getCouponCode(),reason:(null==(e=this.transaction.response)||null==(e=e.data)||null==(e=e.error)?void 0:e.message)||"Unknown error"}}}}],"User Profile Updated":[$],"Cart Updated":[class{constructor(e){this.cart=e;}toSegment(){var e,t,a,r;return {event:"Cart Updated",properties:{cart_id:null==(e=this.cart.id)?void 0:e.toString(),value:this.cart.total,revenue:this.cart.sub_total,tax:this.cart.tax_amount,discount:this.cart.total_discount,shipping:this.cart.real_shipping_cost,currency:null==(t=Salla.config.currency())?void 0:t.code,affiliation:null==(a=Salla.storage.getWithTTL("s-utms"))?void 0:a["s-utm-source"],products:null==(r=this.cart.items)?void 0:r.map((e=>{var t,a,r,s,i,n;return {product_id:null==(t=e.product_id)?void 0:t.toString(),name:e.product_name,price:e.product_price,category:null==(a=e.category)?void 0:a.toString(),sku:null==(r=e.product_sku)?void 0:r.toString(),position:e.position,url:e.url,image_url:e.product_image,brand:null==(s=e.brand)?void 0:s.toString(),currency:null==(i=Salla.config.currency())?void 0:i.code,variant:null==(n=e.variant)?void 0:n.toString(),coupon:this.cart.coupon,quantity:e.quantity}}))}}}static shouldSend(e){return "cart"===salla.config.get("page.slug")&&!(null!=e&&e.fromLatestFetched)}}],"Market Selected":[class{constructor(e){this.scope=e.data;}toSegment(){return {event:"Market Selected",properties:h$1({},this.getScope(this.scope),{prev:this.getScope(Salla.config.get("store.scope"))})}}getScope(e){var t;return {id:null==(t=(e=e||{}).id)?void 0:t.toString(),country:this.getScopeAttribute(e,"countries"),currency:this.getScopeAttribute(e,"currencies"),locale:this.getScopeAttribute(e,"languages")}}getScopeAttribute(e,t){return e=e[t],Array.isArray(e)?e[0]:e}}],"Product Reordered":[class{constructor(e){this.details=e;}toSegment(){var e;return {event:"Product Reordered",properties:{product_id:null==(e=this.details)||null==(e=e.data)||null==(e=e.id)?void 0:e.toString()}}}static shouldSend(e){const t=null==e?void 0:e.data;return (null==t?void 0:t.id)&&!isNaN(null==t?void 0:t.id)&&"reorder"===(null==t?void 0:t.type)}}]};const V="s-session-id";N$3.versions.twilight="2.14.391",N$3.onInitiated=e=>salla.event.once("twilight::initiated",e),N$3.onReady=N$3.onReady||function(t){return new Promise((function(a){return "ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):N$3.onInitiated((e=>a(t?t(e):e)))}))},N$3.status="loading",N$3.notify=u,N$3.lang=new class extends a$3{constructor(e){e=e||{};const t=salla.cookie.get("s-lang");e.messages=e.messages||window.translations,e.locale=e.locale||(t||window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=false,Salla.event.on("twilight::before.ready",(()=>this.loadStoreTranslations()));}onLoaded(e){return new Promise((t=>{if(this.translationsLoaded)return t(e?e():null);Salla.event.once("languages::translations.loaded",(()=>t(e?e():null)));}))}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=true)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",false);}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=true;}loadScript(e,t=true){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",false);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}getWithDefault(e,t,a,r){let s=this.get(e,a,r);return s!==e?s:t}get(e,t,a){let r=e;(window.translations||this.translationsLoaded)&&(r="trans."+e);let s=super.get(r,t,a);return s!==r?s:super.get(r,t,"en").replace(r,e)}set(e,t){return salla.helpers.setNested(this.messages[`${this.getLocale()}.trans`],e,t),this}add(e,t){return Object.entries(t).forEach((t=>salla.helpers.setNested(this.messages[t[0]+".trans"],e,t[1]))),this}addBulk(e){return Object.entries(e).forEach((([e,t])=>{this.add(e,t);})),this}},N$3.form=new class{async submit(e,t=null){var a;let r=t;if("SubmitEvent"===(null==t||null==(a=t.constructor)?void 0:a.name)||"submit"===(null==t?void 0:t.type)){var s,i;if(t.preventDefault(),"FORM"!==(null==(s=t.target)?void 0:s.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise((()=>{throw "Failed find the target element for submit action. make sure you submit a form element"}));"SALLA-BUTTON"===(null==t||null==(i=t.submitter)||null==(i=i.parentElement)?void 0:i.tagName)&&t.submitter.parentElement.load(),r=t.target.getElementSallaData(),salla.log("Data from element",r);}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.request(e,r,"post").finally((()=>{var e;loaderSupported&&(null==t||null==(e=t.submitter)||e.parentElement.stop());}));let n=e.split("."),o=n.splice(-1);return await salla.call(n.join("."))[o](r).finally((()=>{var e;return null==t||null==(e=t.submitter)||null==(e=e.parentElement)?void 0:e.stop()})).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),false}onChange(e,t){var a;return null!=t&&t.currentTarget?"FORM"!==(null==t||null==(a=t.currentTarget)?void 0:a.tagName)||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),true):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),false):(salla.logger.warn(`Trying to trigger '${e}' without event!`),false)}getPossibleValue(e,t,a=false){if(!e)return;if("object"!=typeof e)return e;let r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},N$3.infiniteScroll=new class extends c{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":true,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[];}initiate(e,a,r,s=false){s?((r=r||{}).fetchOptions=h$1({},this.fetchOptions,r.fetchOptions||{}),r.responseBody="json"):r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),n=r.path;if(!i||!n||"string"==typeof n&&!document.querySelector(n))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let o=new t$1(i,r);return o.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),o.on("request",Salla.infiniteScroll.event.request),o.on("load",Salla.infiniteScroll.event.load),o.on("append",Salla.infiniteScroll.event.append),o.on("error",Salla.infiniteScroll.event.error),o.on("last",Salla.infiniteScroll.event.last),o.on("history",Salla.infiniteScroll.event.history),this.instances.push(o),o}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage();}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy();}}(void 0,salla.event.infiniteScroll),N$3.api=new class extends B{constructor(){super(),this.auth=new D,this.cart=new m,this.loyalty=new f,this.order=new F,this.rating=new A,this.product=new v,this.profile=new y,this.comment=new C,this.currency=new S,this.document=new w,this.wishlist=new E,this.scope=new b,this.booking=new _,this.landing=new k,this.notifications=new x,this.component=new P,this.advertisement=new I,this.navigation=new q,this.metadata=new T;}beaconRequest(e,t={}){var a;if(null==(a=window.navigator)||!a.sendBeacon)return fetch(e,t);const r="string"==typeof(null==t?void 0:t.body)?null==t?void 0:t.body:JSON.stringify((null==t?void 0:t.body)||{}),s=new Blob([r],{type:"application/json"});return Salla.log(`Beacon payload size: ${s.size} bytes (~${(s.size/1024).toFixed(2)} KB)`),navigator.sendBeacon(e,s),Promise.resolve(new Response('{"status":"sent_via_beacon"}',{status:200,headers:{"Content-Type":"application/json"}}))}},N$3.sso=new class{constructor(){Salla.onReady((()=>this.init()));}init(){var e;if(salla.config.get("store.features",[]).includes("sso-login")){if(window.location.hostname.includes("salla"))return salla.log("SSO is not supported yet for stores without custom domain.");salla.auth.event.onLoggedOut((()=>new Promise((e=>{const t=document.createElement("iframe");t.style.display="none",t.src=salla.url.get("sso/logout"),document.body.appendChild(t),t.onload=()=>{document.body.removeChild(t),e();};})))),null==(e=document.querySelector("salla-login-modal"))||e.remove(),Salla.event.removeAllListeners("login::open"),Salla.event.prependListener("login::open",(()=>this.redirect())),window.addEventListener("mini-checkout::before-init",(e=>{Salla.config.isUser()||(e.preventDefault(),this.redirect());}));}}redirect(){const e=window.location.pathname+window.location.search,t=`${window.location.origin}/sso/login?intended_to=${encodeURIComponent(e)}`;return console.log("Redirecting to:",t),window.location.href=t,true}},N$3.intend=new class{constructor(){Salla.onReady((()=>this.init()));}init(){if(Salla.config.isUser())return;const e=new URLSearchParams(window.location.search);if(e.has("intended_to"))try{const t=new URL(e.get("intended_to"));if(t.hostname!==window.location.hostname)return;return this.handleAfterLoginEvent(t)}catch(e){return void console.warn("Invalid URL provided in intended_to parameter")}}handleAfterLoginEvent(e){let t="intend::user.logged.in";Salla.event.on(t,(()=>window.location=e)),Salla.api.auth.setAfterLoginEvent(t),Salla.api.auth.setCanRedirect(false),Salla.event.on("salla-login::ready",(()=>Salla.event.emit("login::open",{withoutReload:true})));}},N$3.hooks=new class{constructor(){this._store=new Map,this._whitelist=new Map([["salla-add-product-button",new Set(["validate","componentDidLoad"])],["salla-product-options",new Set(["componentDidLoad"])],["salla-products-list",new Set(["componentDidLoad"])],["salla-products-slider",new Set(["componentDidLoad"])],["salla-hook",new Set(["componentDidLoad"])],["salla-scopes",new Set(["componentDidLoad"])]]),this._themeSlots=["head","head:start","head:end","body:start","body:end","product:index.items.start","product:index.items.end","product:single.description.start","product:single.description","product:single.description.end","product:single.form.start","product:single.form.end","blog:index.items.start","blog:index.items.end","blog:single.items.start","blog:single.items.end","brands:index.items.start","brands:index.items.end","brands:single.details.start","brands:single.details.end","brands:single.items.start","brands:single.items.end","cart:items.start","cart:items.end","cart:summary.start","cart:summary.end","cart:submit.start","cart:submit.end","customer:notifications.items.start","customer:notifications.items.end","customer:orders.index.items.start","customer:orders.index.items.end","customer:orders.single.details.start","customer:orders.single.details.end","customer:wishlist.items.start","customer:wishlist.items.end","customer:profile.form.start","customer:profile.form.fields.start","customer:profile.form.fields.end","customer:profile.form.submit.start","customer:profile.form.submit.end","customer:profile.form.end","thank-you:start","thank-you:items.start","thank-you:items.end","thank-you:end"];const e=Salla.config.get("page.slug");e&&(this._themeSlots.push(e+":start"),this._themeSlots.push(e+":end")),Salla.onReady((()=>{const e=Salla.config.get("page.slug");e&&(this._themeSlots.includes(e+":start")||this._themeSlots.push(e+":start"),this._themeSlots.includes(e+":end")||this._themeSlots.push(e+":end"));})),this._componentHistory=new Map;}renderAutoComponents(e){Array.isArray(e)&&0!==e.length&&e.forEach((({hook:e,tag:t,canRender:a})=>{a&&!a()||this.mount(e,document.createElement(t));}));}registerHook(e,t,a,r={}){if(!this._isAllowed(e,t))return console.warn(`[Hooks] Hook "${e}:${t}" is not allowed`),()=>{};const s=0|r.priority,i=!!r.once,n=this._ensureTag(e),o=n.get(t)||[];return o.push({cb:a,p:s,once:i}),o.sort(((e,t)=>t.p-e.p)),n.set(t,o),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),()=>this.removeHook(e,t,a)}registerHookOnce(e,t,a,r={}){return this.registerHook(e,t,a,h$1({},r,{once:true}))}async call(e,t,a){const r=this._store.get(e);if(!r)return;const s=r.get(t);if(s&&0!==s.length)for(const r of [...s]){try{await r.cb(a);}catch(a){console.warn(`[Hooks] "${e}:${t}" callback failed:`,a);}r.once&&this.removeHook(e,t,r.cb);}}removeHook(e,t,a){const r=this._store.get(e);if(!r)return false;if(!r.has(t))return false;if(!a)return r.delete(t),0===r.size&&this._store.delete(e),true;const s=r.get(t),i=s.findIndex((e=>e.cb===a));return i>-1&&(s.splice(i,1),0===s.length&&r.delete(t),0===r.size&&this._store.delete(e),true)}clear(e){e?this._store.delete(e):this._store.clear();}get(e,t){var a;const r=this._store.get(e);return r&&(null==(a=r.get(t))?void 0:a.map((e=>e.cb)))||[]}_ensureTag(e){let t=this._store.get(e);return t||(t=new Map,this._store.set(e,t)),t}_isAllowed(e,t){const a=this._whitelist.get(e);return a?!!a.has(t)||(console.warn(`[Hooks] Hook "${t}" is not allowed for tag "${e}"`),false):(console.warn(`[Hooks] Tag "${e}" is not in the whitelist`),false)}registerComponent(e,t){this._componentHistory.has(e)||this._componentHistory.set(e,new Set);const a=this._componentHistory.get(e);if(!a.has(t))return a.add(t),this.call(e,"componentDidLoad",t)}async _callForLoadedComponents(e,t){const a=this._componentHistory.get(e);if(a&&0!==a.size)for(const r of a)try{await t(r);}catch(t){console.warn(`[Hooks] "${e.replace(/[^a-zA-Z0-9-_]/g,"")}:componentDidLoad" callback failed:`,t);}}mount(e,t){return this._themeSlots.includes(e)?new Promise((a=>{this.registerHook("salla-hook","componentDidLoad",(r=>{r.name===e&&(r.mount(t),a(t));}));})):(console.warn(`[Hooks] Hook "${e}" is not allowed`),Promise.reject(t))}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing","metadata"].forEach((t=>N$3[t]=new c(N$3.api[t],N$3.event[t]))),N$3.call=t=>{let a=N$3,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},N$3.analytics=new class{constructor(){this.history=[],this.customTrackers=[],this.context={},this._anonymousId=null,this._sessionId=null,this._jitsuConfig=null,this.mappedEvents={"wishlist::added":"Product Added to Wishlist","wishlist::removed":"Product Removed from Wishlist","salla-products-list::products.fetched":["Product List Viewed","Product List Filtered"],"auth::registered":"Signed Up","auth::logged.in":"Signed In","auth::logged.out":"Signed Out","share-element":"Product Shared","promotion::viewed":"Promotion Viewed","promotion::clicked":"Promotion Clicked","salla::offer.promotion.viewed":"Promotion Viewed","salla::offer.promotion.clicked":"Promotion Clicked","cart::coupon.added":"Coupon Applied","cart::coupon.deleted":"Coupon Removed","cart::coupon.addition.failed":"Coupon Denied","profile::updated":"User Profile Updated","cart::updated":"Cart Updated","scope::changed":"Market Selected","order::order.created":"Product Reordered"},Salla.event.onAny(((e,t)=>{try{if(Object.keys(this.mappedEvents).includes(e)){const a=this.mappedEvents[e];return void(Array.isArray(a)?a:[a]).forEach((e=>Salla.event.emit(e,t)))}if(!Salla.config.get("jitsu.events",[]).includes(e))return;const a=H.transform(e,t);a&&this.track(a.event,a.properties);}catch(e){Salla.log("Error in analytics event handling:",e);}})),Salla.event.on("salla-cookies-bar::accepted",(()=>this.setConsent("accepted"))),Salla.event.on("salla-cookies-bar::rejected",(()=>this.setConsent("rejected"))),Salla.event.on("auth::logged.out",(()=>this.clearSessionId())),Salla.event.on("twilight::before.ready",(e=>{var t,a,r,s,n,o,l;this.debugAnalytics=jitsuAnalytics({host:"https://st.salla.dev",writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p"});const{host:u,key:c}=(null==e?void 0:e.jitsu)||{};if(this.jitsuAnalytics=null,!u||!c)return void salla.log("Jitsu configuration is missing. Analytics will not be tracked.");H.registerEvents(),this._jitsuConfig=h$1({host:this.getAnalyticsHost(e),writeKey:c,cookieCapture:Object.fromEntries(Salla.cookie.getCookieByPrefix("sa_").map((e=>[e,e])))},Salla.helpers.isIframe()&&{fetch:(e,t)=>this.customFetch(e,t)});const d=this.getConsentPolicies();var p;(this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,d)),e.jitsu.anonymous_id&&this.jitsuAnalytics.setAnonymousId(e.jitsu.anonymous_id),this._anonymousId=(null==(t=this.jitsuAnalytics)||null==(t=t.user())?void 0:t.anonymousId)||null,e.jitsu.session_id&&this.setContext("session_id",e.jitsu.session_id),this._sessionId=null==(a=this.jitsuAnalytics)?void 0:a.getContextProperty("session_id"),this.setContext("store_id",null==(r=e.store)?void 0:r.id),this.setContext("version",null==(s=e.jitsu)?void 0:s.version),this.setContext("library",{twilight:Salla.versions}),null!=(n=e.jitsu)&&null!=(n=n.context)&&n.extra&&this.setExtraContext(e.jitsu.context.extra),null!=(o=e.store)&&null!=(o=o.scope)&&o.id)&&this.setContext("scope",null==(p=e.store)?void 0:p.scope);"user"===(null==e||null==(l=e.user)?void 0:l.type)&&this.setContext("traits",this.getFormattedUser(e.user)),this.registerTracker({name:"DefaultSallaTracker",track:(e,t)=>this.jitsuAnalytics.track(e,t),page:e=>this.jitsuAnalytics.page(e)});})),Salla.onReady((()=>{var e;this.initSessionId();const t={name:Salla.config.get("page.slug",""),id:null==(e=Salla.config.get("page.id",""))?void 0:e.toString()};this.setContext("page",t),Salla.config.set("jitsu.anonymous_id",this._anonymousId),Salla.config.set("jitsu.session_id",this._sessionId),this.page(t);}));}setExtraContext(e){var t;null!=e&&null!=(t=e.headers)&&t["s-app-os"]&&(this.setContext("app",{version:e.headers["s-app-os-version"],app_release_tag:e.headers["s-app-version"],platform:e.headers["s-app-os"].toLowerCase()}),delete e.headers["s-app-os"],delete e.headers["s-app-os-version"],delete e.headers["s-app-version"],delete e.headers["s-source"]),this.setContext("system",e);}getAnalyticsHost(e){var t;const a="https://salla.cloud/_app/e";var r,s;if(Salla.helpers.isIframe())return null!=(r=null==(s=e.jitsu)?void 0:s.host)?r:a;if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;const i=e.store.url;try{let e="";const t=i;if(/https:\/\/demostore\.salla\.sa/.test(t)){const e=t.match(/demostore\.salla\.sa\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/);if(e&&e[2]){const a=e[2];return `${new URL(t).origin}/${a}/_app/e`}return a}const r=/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/,s=t.match(r);if(s){const r=s[3];if(!r||0===r.trim().length||"ar"===r||"en"===r)return Salla.log("Error: invalid or empty store name in salla.sa URL"),a;e=`${new URL(t).origin}/${r}`;}else {e=new URL(t).origin;}return `${e}/_app/e`}catch(e){return Salla.log("Error getting store url, forwarding to salla.cloud:",e),a}}setContext(e,t){var a,r;null==(a=this.jitsuAnalytics)||a.setContextProperty(e,t),null==(r=this.debugAnalytics)||r.setContextProperty(e,t),this.context[e]=t;}setAppContext(e,t){if(!this.jitsuAnalytics)return void Salla.log("setAppContext: Analytics not initialized yet");if(!e||"string"!=typeof e)return void Salla.log("setAppContext: appId must be a non-empty string");if(!t||"object"!=typeof t)return void Salla.log("setAppContext: payload must be an object");const a=this.context.apps_context||{};a[e]=h$1({},a[e],t),this.setContext("apps_context",a);}withAppScope(e,t){if(!e||"string"!=typeof e)return void Salla.log("withAppScope: appId must be a non-empty string");if("function"!=typeof t)return void Salla.log("withAppScope: callback must be a function");const a=this.context.apps_context?h$1({},this.context.apps_context):void 0,r=this,s={appId:e,setContext(t,a){r.setAppContext(e,{[t]:a});}};try{t(s);}finally{setTimeout((()=>{a?r.setContext("apps_context",a):r.setContext("apps_context",void 0);}),0);}}customFetch(e,t){return fetch(e,h$1({},t,{keepalive:true}))}track(e,t={}){t=this.finalPayload(t),this.history.push({action:"track",eventName:e,payload:t}),this.pushEventToCustomTrackers("track",e,t);}log(e,t={}){var a;return null==(a=this.debugAnalytics)?void 0:a.track(e,t).catch((e=>(Salla.log("Error tracking event:",e),Promise.reject(e))))}page(e={}){var t,a;(e=this.finalPayload(e)).id=null==(t=e.id||Salla.config.get("page.id",""))?void 0:t.toString(),e.name=e.name||Salla.config.get("page.slug"),e.keywords=e.keywords||(null==(a=document.querySelector("meta[name=keywords]"))?void 0:a.content),e.referrer=e.referrer||document.referrer,this.history.push({action:"page",payload:e}),this.pushEventToCustomTrackers("page",e);}finalPayload(e={}){return this.attachRealtimeContext(),h$1({},{},e)}attachRealtimeContext(){try{const e=["user.id","cart.id","cart.user_id","cart.count","cart.summary.count","scope.id","branch-choosed-before"].reduce(((e,t)=>{const a=Salla.storage.get(t);return a&&(e[t.replace(".","_")]=a),e}),{});Object.keys(e).length>0&&this.setContext("localStorage",e);}catch(e){Salla.analytics.log("attachRealtimeContext",{error:e.message}),Salla.log("Error attaching realtime context:",e);}const e=Salla.storage.getWithTTL("s-utms");if(!e)return;const{"s-utm-campaign":t,"s-utm-source":a,"s-utm-medium":r,"s-utm-term":s,"s-utm-content":i,"s-utm-referrer":n}=e;this.setContext("campaign",{name:t,source:a,medium:r,term:s,content:i,referrer:n});}registerTracker(e){"object"==typeof e?"string"==typeof e.name&&e.name?"function"==typeof e.track?"function"==typeof e.page?this.customTrackers.find((t=>t.name===e.name))?Salla.log("tracker with the same name already exists!"):(this.customTrackers.push(e),this.history.forEach((t=>"track"===t.action?e.track(t.eventName,t.payload):"page"===t.action?e.page(t.payload):void 0))):Salla.log("tracker.page most be a function!"):Salla.log("tracker.track most be a function!"):Salla.log("tracker.name most be a string!"):Salla.log('tracker most be an object {name:"tracker name", track: callback, page: callback}!');}pushEventToCustomTrackers(e,t,a={}){const r="page"===e?[t]:[t,a];return Promise.allSettled(this.customTrackers.map((t=>this.pushEventToCustomTracker(t[e],r)))).then((t=>t.filter((e=>"rejected"===e.status)).map((t=>Salla.log("Error on customTracker to send "+e,t)))))}pushEventToCustomTracker(e,t){try{const a=e(...t);return Promise.resolve(a).catch((e=>Promise.reject(e)))}catch(e){return Promise.reject(e)}}getConsentState(){return Salla.storage.get("cookies-consent","unknown")}getConsentPolicies(e=null){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return {};const a="accepted"===(e=e||this.getConsentState());return {privacy:{dontSend:false,disableUserIds:!a,ipPolicy:a?"keep":"remove"}}}setConsent(e){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return;if(!["accepted","rejected"].includes(e))return;const a=this.getConsentState();if(this._jitsuConfig&&this.jitsuAnalytics&&a!==e)try{var r;const t=this.getConsentPolicies(e);this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,t)),this._anonymousId=(null==(r=this.jitsuAnalytics)||null==(r=r.user())?void 0:r.anonymousId)||null,Salla.config.set("jitsu.anonymous_id",this._anonymousId),Object.entries(this.context).forEach((([e,t])=>{this.jitsuAnalytics.setContextProperty(e,t);}));}catch(e){Salla.log("Error re-initializing Jitsu on consent change:",e);}}getFormattedUser(e){return e.phone=e.mobile,e.country=e.country_code,e.language=e.language_code,e.currency=e.currency_code,e}generateSessionId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)}))}initSessionId(){this._sessionId=this._sessionId||Salla.storage.getWithTTL(V)||this.generateSessionId(),Salla.storage.setWithTTL(V,this._sessionId,30),this.setContext("session_id",this._sessionId);}clearSessionId(){this._sessionId=null,Salla.storage.setWithTTL(V,null,0),this.setContext("session_id",null);}getAnonymousId(){try{if(this._anonymousId)return this._anonymousId;if(this.jitsuAnalytics){var e;const t=null==(e=this.jitsuAnalytics.user())?void 0:e.anonymousId;if(t)return this._anonymousId=t,t}return null}catch(e){return Salla.log("Error getting anonymous ID from Jitsu:",e),null}}},N$3.init=e=>new O(e),new class{constructor(e={}){this.config=h$1({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=false,Salla.onReady((()=>this.init()));}normalizeUrl(e){try{return new URL(e,location.href)}catch(e){return null}}shouldIgnoreUrl(e){if(!e)return false;const t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some((e=>a.startsWith(e))))return true;try{const e=new URL(t,location.href).hostname.toLowerCase();return ["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some((t=>e===t||e.endsWith("."+t)))}catch(e){return false}}isWhitelisted(e){if(!e)return false;const t=e.hostname.toLowerCase();for(const e of this.config.WHITELIST){const a=String(e||"").toLowerCase().trim();if(a&&(t===a||t.endsWith("."+a)))return true}return false}emit(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e);}catch(e){}}catch(e){}}logRedirect(e,t,a){if(this.shouldIgnoreUrl(t))return;const r=this.normalizeUrl(t),s=this.normalizeUrl(location.href),i=this.isWhitelisted(r),n={redirect_source:e,redirect_from:s?s.href:String(location.href),redirect_to:r?r.href:String(t),redirect_host:r?r.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(n);}hookHistoryAPIs(){["pushState","replaceState"].forEach((e=>{try{const t=history[e];"function"==typeof t&&(this.originalMethods[`history.${e}`]=t,history[e]=(...a)=>{try{var r;this.logRedirect(e,null!=(r=a[2])?r:location.href);}catch(e){}return t.apply(history,a)});}catch(e){}})),window.addEventListener("popstate",(()=>{this.logRedirect("popstate",location.href);})),window.addEventListener("hashchange",(()=>{this.logRedirect("hashchange",location.href);}));}hookLocationMethods(){try{const e=location.assign.bind(location);this.originalMethods["location.assign"]=e,location.assign=t=>(this.logRedirect("location.assign",t,{stack:(new Error).stack}),e(t));}catch(e){}try{const e=location.replace.bind(location);this.originalMethods["location.replace"]=e,location.replace=t=>(this.logRedirect("location.replace",t,{stack:(new Error).stack}),e(t));}catch(e){}}hookWindowOpen(){try{const e=window.open;this.originalMethods["window.open"]=e,window.open=(t,...a)=>(t&&this.logRedirect("window.open",t,{stack:(new Error).stack}),e.apply(window,[t,...a]));}catch(e){}}setupEventListeners(){this.handleLinkClick=e=>{const t=e.target&&e.target.closest?e.target.closest("a[href]"):null;if(!t)return;const a=t.getAttribute("href");if(!a||a.startsWith("#"))return;if(this.shouldIgnoreUrl(a))return;const r=t.getAttribute("target")||"_self";setTimeout((()=>{this.logRedirect("link-click",a,{target:r});}),0);},document.addEventListener("click",this.handleLinkClick,true),this.handleFormSubmit=e=>{const t=e.target,a=t&&t.getAttribute&&t.getAttribute("action")||location.href,r=(t&&t.method?String(t.method):"GET").toUpperCase();this.logRedirect("form-submit",a,{method:r});},document.addEventListener("submit",this.handleFormSubmit,true);}setupPerformanceObserver(){try{this.performanceObserver=new PerformanceObserver((e=>{for(const t of e.getEntries())"navigation"===t.entryType&&this.logRedirect("performance-navigation",location.href,{type:t.type,redirectCount:t.redirectCount});})),this.performanceObserver.observe({type:"navigation",buffered:true});}catch(e){}}init(){if(this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug")))return;if(this.isInitialized)return;const e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=true;}destroy(){this.isInitialized&&(Object.keys(this.originalMethods).forEach((e=>{const[t,a]=e.split(".");"history"===t&&this.originalMethods[e]?history[a]=this.originalMethods[e]:"location"===t&&this.originalMethods[e]?location[a]=this.originalMethods[e]:"window"===t&&"open"===a&&this.originalMethods[e]&&(window.open=this.originalMethods[e]);})),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,true),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,true),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=false);}},salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",(e=>{let t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t);})),N$3.success=N$3.notify.success,N$3.error=N$3.notify.error,window.dispatchEvent(new CustomEvent("salla::created"));
12703
+ let n=function(e,t,a){return alert(e)},o=function(e,t){return n(e,l.error,t)},l={error:"error",success:"success",info:"info"};var u={fire:function(e,t,a){return n(e,t,a)},setNotifier:function(e){n=e,salla.event.emit("twilight::notifier.changed");},error:o,success:function(e,t){return n(e,l.success,t)},info:function(e,t){return n(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",()=>{e.forEach(e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,o(t.innerHTML),salla.event.emit("twilight::error",e);});}));},types:l};class c{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let s=r.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return s.forEach(e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}}),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return false},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach(e=>{e.files.length||e.setAttribute("disabled","");});var a=new FormData(this);return t.forEach(e=>{e.files.length||e.removeAttribute("disabled");}),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||(null==a?void 0:a.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach(r=>{let s=(null==a?void 0:a.dataset[r])||this.dataset[r];if(s){var i=window[s];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${s}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+s+"() not found!");}}),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class d{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);});}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,async function(...e){return t(...e)})};}getEventName(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,a={}){return Salla.event.addListener(this.getEventName(e),t,a)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function h$1(){return h$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e},h$1.apply(null,arguments)}function p(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=true);}Salla.event.auth=new class extends d{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally(()=>this.dispatch("loggedIn",e))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends d{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},this.after_init();}updated(e,t={}){var a;return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(a=e.cart.free_shipping_bar)&&a.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",h$1({},e.cart,{fromLatestFetched:t.fromLatestFetched}))):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated",{fromLatestFetched:t.fromLatestFetched}))}latestFetched(e){return this.updated(e.data,{fromLatestFetched:true}),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends d{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched",orderEdited:"order.edited",orderNotEdited:"order.not.edited"},this.after_init();}},Salla.event.scope=new class extends d{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init();}},Salla.event.rating=new class extends d{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init();}},Salla.event.booking=new class extends d{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.comment=new class extends d{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.landing=new class extends d{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.loyalty=new class extends d{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init();}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends d{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed",productOptionsFetched:"options.fetched",productOptionsNotFetched:"options.not.fetched"},this.after_init();}},Salla.event.profile=new class extends d{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends d{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends d{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);});}fireEvent(e,t,...a){return this.fireEventForElements(e,t,false,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,true,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,false,...r));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const s=new CustomEvent(t,...r);return e.dispatchEvent(s)}},Salla.event.wishlist=new class extends d{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init();}},Salla.event.infiniteScroll=new class extends d{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init();}},Salla.event.notifications=new class extends d{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.component=new class extends d{constructor(){super(),this.namespace="component",this.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},this.after_init();}},Salla.event.advertisement=new class extends d{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init();}},Salla.event.navigation=new class extends d{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.metadata=new class extends d{constructor(){super(),this.namespace="metadata",this.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},this.after_init();}},Salla.event.on("twilight::initiated",()=>{Object.keys(Salla).forEach(e=>{"object"==typeof(e=Salla[e])&&(p(e),Object.keys(e).forEach(t=>{p(e[t]);}));});}),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"==="production",token:null,fastRequests:true,canLeave:true,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=false,Salla.config.triedToGetLanguages_=false,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{var e;if(Salla.config.triedToGetLanguages_||Salla.config.get("languages",[]).length>0)return Salla.config.get("languages",[]);Salla.config.triedToGetLanguages_=true;let t=true,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map(e=>{t&&(a=[],t=false),e.code=e.code||e.iso_code,e.url=salla.url.get(e.code),e.is_rtl=e.is_rtl||e.rtl,a.push(e);}),Salla.config.set("languages",a),a},Salla.config.currencies=async()=>{var e;if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=true;let t=true,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map(e=>{t&&(a={},t=false),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e;}),Salla.config.set("currencies",a),a},Salla.config.isMobileApp=()=>{var e;return ["ios","android"].includes(null==(e=Salla.analytics)||null==(e=e.jitsuAnalytics)||null==(e=e.getContextProperty("app"))||null==(e=e.platform)?void 0:e.toLowerCase())};class g{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:true,exclude:[]};}after_init(){}normalRequest(e,t=void 0,a=null){let r=Array.isArray(e),s=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach(function(t){e[t[0]]=t[1];}),t={params:e};}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?s=salla.url.get(s):"http"!==s.substring(0,4)&&(s=salla.url.api(s)),Salla.api.request(s,t,a,{headers:i})}request(e,t=void 0,a=null){return !salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class m extends g{constructor(){super(),this.addToCartTries=0,this.guestCartAssigned=false,this.namespace="cart",this._pendingCartIdRequest=null,this._pendingAssignRequest=null,this.endpoints={latest:"cart/latest",latestApi:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote",offers:"offers/cart/{cartId}",giftCartDetails:"cart/{cartId}/buy-as-gift",cartGiftToCart:"cart/{cart_id}/buy-as-gift",assign:"cart/{cartId}/assign?merge=1"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",()=>salla.api.cart.getCurrentCartId(false,"api::initiated")),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",async function(){try{await Salla.api.cart.assign();}catch(e){Salla.log("Error on assign after verified",e);}return Salla.api.cart.getCurrentCartId(true,"auth::verified")},{async:true}),salla.event.on("twilight::initiated",()=>salla.api.cart.syncGuestCart()),salla.event.on("profile::info.fetched",()=>this._checkCurrentCart(true)),salla.event.on("twilight::error",e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset());}_checkCurrentCart(e=false){var t,a;let r=salla.storage.get("cart"),s=null==(t=salla.config.get("user"))?void 0:t.id,i=null==(a=salla.config.get("store"))?void 0:a.id;r&&r.id&&!e&&(r.user_id===s&&r.store_id===i||(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log("Api:: case2 => The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),salla.cart.api.reset()),salla.url.is_page("cart")&&r.id!==salla.config.get("page.id")&&(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log(`Api:: case2 => The cart is different between storage:${r.id} & session:${salla.config.get("page.id")} !`),salla.cart.api.reset()));}async getCurrentCartId(e=false,t="getCurrentCartId"){if(Salla.cart.api._pendingCartIdRequest)return Salla.cart.api._pendingCartIdRequest;Salla.cart.api._pendingCartIdRequest=async function(){try{if(!e){if(Salla.cart.api.latestCart)return Salla.cart.api.latestCart.cart.id;let e=Salla.storage.get("cart.id");if(e)return e}let a=await Salla.cart.api.latest(t);return Salla.cart.api.latestCart=a.data,Salla.cart.api.latestCart.cart.id}finally{Salla.cart.api._pendingCartIdRequest=null;}}();let a=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,a}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request(salla.auth.api.isSessionless()?"latestApi":"latest",{params:{source:"",callerName:e}}).then(e=>(salla.api.cart.set(e.data.cart),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.api.cart.reset(),salla.event.cart.latestFailed(e),e})}async details(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.details"),this.request(["details",e],{params:{with:t}}).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async quickAdd(e,t,a){return this.addItem({id:e,quantity:t,offerType:a,endpoint:"quickAdd"})}async addItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let r=salla.form.getPossibleValue(a.payload,["endpoint"]);r&&["addItem","quickAdd"].includes(r)||(r=salla.form.getPossibleValue(a.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let s=null==(t=a.payload)?void 0:t.source;a.payload&&delete a.payload.source,Salla.cart.api.addToCartSource=s||null;let i=await Salla.api.cart.getCurrentCartId(false,"salla.api.cart.addItem");try{a.payload=Salla.helpers.createFormDataWrapper(a.payload||{}),await Salla.cart.event.beforeAddItem(a);}catch(e){}return this.request([r,i,a.id],a.payload.getRawData()).then(function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,a.id);}catch(e){Salla.log(e);}return e}).catch(function(t){if(!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(t,a.id),t})}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteItem");return this.request(["deleteItem",a,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.updateItem");return "Object"===(null==(t=a.payload.constructor)?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),this.request(["updateItem",r,a.id],a.payload).then(function(e){return salla.cart.event.itemUpdated(e,a.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,a.id),e})}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteImage");return this.request(["deleteImage",t,e]).then(function(t){return salla.cart.event.imageDeleted(t,e),t}).catch(function(t){throw salla.cart.event.imageNotDeleted(t,e),t})}async status(e,t=false){e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.status");const a={has_apple_pay:salla.helpers.hasApplePay()};t&&(a.guest_checkout=1);try{await salla.cart.event.submitting();}catch(e){salla.log("Error on: salla.cart.event.submitting()");}return this.request(["status",e],{params:a})}async submit(e=false,t=false){const a=salla.config.get("store.features",[]).includes("embedded-login-checkout");if(salla.config.isGuest()){if(!a&&!t)return salla.cart.loginOnCartPage();try{await salla.api.cart.syncGuestCart();}catch(e){salla.log("Error on syncGuestCart during guest checkout",e);}}let r;if(e)try{var s;const e=await Salla.api.cart.assign();r=null==e||null==(s=e.data)?void 0:s.cart_id;}catch(e){Salla.log("Error on assign after login from submit",e);}const i=salla.config.isGuest()&&(t||a);this.status(null!=r?r:await salla.api.cart.getCurrentCartId(false,"salla.api.cart.submit"),i).then(e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(!a)return window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",false===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload();if(!["checkout","refresh","login"].includes(a)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===a)return salla.cart.loginOnCartPage();if("checkout"===a){var r;let t=null==(r=e.data.next_step)?void 0:r.url;if(!t){let e="Checkout URL is missing from response";throw salla.cart.event.submitFailed(e),e}return salla.helpers.hasApplePay()&&(t+=(t.includes("?")?"&":"?")+"has_apple_pay=true"),window.location.href=t}window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),window.location.reload();}).catch(function(a){var r;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let s=404===(null==a||null==(r=a.response)||null==(r=r.data)?void 0:r.status);if(s&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit(e,t);throw s&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(a),a});}getCartPayload(e){var t;let a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,a="object"==typeof a?a:void 0,{id:e,payload:a}}normalRequest(e,t=void 0,a=null){var r=this;return super.normalRequest(e,t,a).catch(async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e})}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset();}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.addCoupon");return this.request(["addCoupon",t],{coupon:e}).then(function(e){var a;let r=salla.storage.get("cart");return r&&null!=(a=e.data)&&null!=(a=a.cart)&&a.coupon&&(r.coupon=e.data.cart.coupon,salla.storage.set("cart",r)),salla.event.cart.couponAdded(e,t),e}).catch(function(e){throw salla.event.cart.couponAdditionFailed(e,t),e})}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then(function(t){let a=salla.storage.get("cart");return a&&a.coupon&&(delete a.coupon,salla.storage.set("cart",a)),salla.event.cart.couponDeleted(t,e),t}).catch(function(t){throw salla.event.cart.couponDeletionFailed(t,e),t})}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then(e=>(salla.event.cart.quickOrderSettingFetched(e),e)).catch(e=>{throw salla.event.cart.quickOrderSettingFailed(e),e})}createQuickOrder(e){return this.request("createQuickOrder",e).then(e=>(salla.event.cart.quickOrderSucceeded(e),e)).catch(e=>{throw salla.event.cart.quickOrderFailed(e),e})}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.priceQuote")]).then(e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then(()=>(setTimeout(()=>window.location.href=salla.url.get("/"),1e3),e)))).catch(e=>salla.event.cart.priceQuoteFailed(e).then(()=>{var t;throw 404===(null==(t=e.error)?void 0:t.code)&&window.location.reload(),e}))}loginOnCartPage(){salla.auth.setCanRedirect(false),salla.event.dispatch("login::open",{withoutReload:true,source:"cart-submit"}),salla.auth.event.onLoggedIn(()=>{salla.event.dispatch("login::close"),salla.cart.submit(true);});}set(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart();}async offers(){const e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.offers");return this.request(["offers",e]).then(e=>(salla.event.cart.offersFetched(e),e)).catch(e=>{throw salla.event.cart.offersFailed(e),e})}async getGiftCartDetails(){let e=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.getGiftCartDetails");return this.request(["giftCartDetails",e]).then(t=>(salla.product.event.giftFetched(t,e),t)).catch(t=>{throw salla.product.event.giftFetchFailed(t,e),t})}async addCartGiftToCart(e,t=false){let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then(e=>(salla.product.event.addGiftToCartSucceeded(e,a),t&&(window.location.href=e.redirect),e)).catch(e=>{throw salla.product.event.addGiftToCartFailed(e,a),e})}async syncGuestCart(){if(!salla.config.isGuest())return;const e=salla.api.cart.getCartCookiePrefix(),t=salla.cookie.getCookieByPrefix(e),a=salla.storage.get("cart.id");if(!a&&t.length)try{var r;const t=null==(r=(await salla.api.cart.latest()).data)||null==(r=r.cart)?void 0:r.id;t&&salla.api.cart.setCartCookie(e,t);}catch(e){salla.log("Failed to fetch latest cart:",e);}salla.cookie.clearCookieByPrefix(e),a&&(salla.config.set("headers.s-cart-id",a),salla.api.cart.setCartCookie(e,a));}async assign(){var e=this;if(Salla.api.cart._pendingAssignRequest)return Salla.api.cart._pendingAssignRequest;let t=Salla.storage.get("cart.id");return !(!t||Salla.api.cart.guestCartAssigned)&&(Salla.api.cart._pendingAssignRequest=async function(){try{const a=await e.request(["assign",t]);return Salla.api.cart.guestCartAssigned=true,a}catch(e){throw e}finally{Salla.api.cart._pendingAssignRequest=null;}}(),Salla.api.cart._pendingAssignRequest)}setCartCookie(e,t){salla.cookie.set(`${e}-${t}`,t,1);}getCartCookiePrefix(){return "cart-id-"+salla.config.get("store.id")}}class f extends g{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then(e=>(salla.loyalty.event.programFetched(e),e)).catch(e=>{throw salla.loyalty.event.programNotFetched(e),e})}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then(function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t}).catch(function(t){throw salla.loyalty.event.exchangeFailed(t,e),t})}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.reset"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then(e=>(salla.loyalty.event.resetSucceeded(e),e)).catch(e=>{throw salla.loyalty.event.resetFailed(e),e})}}class D extends g{constructor(){super(),this.namespace="auth",this.canRedirect_=true,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.inIframe=salla.helpers.isIframe(),Salla.event.on("twilight::init",function(){if(Salla.config.isGuest()&&location.href.includes("force_logout"))return delete Salla.api.axios.defaults.headers.common.Authorization,Salla.api.auth.logout("twilight",false)}),this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){var t;null!=(t=e)&&t.data&&(e=e.data);let a=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(a)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",a],e).then(function(e){return salla.auth.event.codeSent(e,a),e}).catch(function(e){throw salla.auth.event.codeNotSent(e,a),salla.auth.api.trackBlockedError(e,"login"),e})}async verify(e,t=true){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=false!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let r=await salla.auth.api.request(["verify",a],e);return 200!==(null==r?void 0:r.status)?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)}async handlAfterAuthenticatedResponse(e,t){var a;e.data||(e={data:e});let r="authenticated"===(null==(a=e.data)?void 0:a.case);return r&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),r&&await salla.auth.event.loggedIn(e).then(()=>salla.auth.api.afterUserLogin()),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then(function(t){return salla.auth.event.codeSent(t,e),t}).catch(function(t){throw salla.auth.event.codeNotSent(t,e),salla.auth.api.trackBlockedError(t,"resend"),t}):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){var t=this;let a;return e.data&&(a=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(async function(e){var r;return salla.auth.event.registered.call(a,e),"authenticated"===(null==(r=e.data)?void 0:r.case)&&(salla.auth.event.tokenFetched(e.data.token),!t.inIframe&&!t.isSessionless()&&await salla.auth.request("auth/jwt",{callerName:"salla.auth.api.register"}),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(a,e),salla.auth.api.trackBlockedError(e,"register"),e})}handleIframeReadyAction(e,t){var a;null==(a=e.contentWindow)||a.postMessage({source:"logout",type:"init",data:{id:salla.config.get("store.id"),lang:"ar",appUrl:t,apiUrl:salla.config.get("store.api").replace(/\/+$/,""),settings:salla.config.all(),storage:{}}},"*");}appendIframeAndLogout(){return new Promise(e=>{let t=salla.config.get("login.url","https://accounts.salla.com");const a=document.createElement("iframe");a.style.display="none",a.src=`${t}/logout`;const r=s=>{if("login"!==s.data.source)return;let i=s.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",s.data),["logged-out","ready"].includes(i)){if("ready"===i)return this.handleIframeReadyAction(a,t);window.removeEventListener("message",r),a.remove(),e();}};window.addEventListener("message",r),document.body.appendChild(a);})}logout(e="twilight",t=true){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then(()=>this.appendIframeAndLogout()).then(()=>{if(!t)return;let a=salla.url.get(`logout?from=${e}`);console.log(`Going to ${a}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=a;}catch(e){salla.log(e);}}).catch(e=>console.error("Error during logout:",e))}refresh(){return this.request("refresh").then(function(e){return salla.auth.event.tokenFetched(e.data.token),e}).catch(function(e){throw salla.auth.event.refreshFailed(e),e})}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload);}isSessionless(){var e;return "sessionless"===(null!=(e=salla.config.get("auth.mode"))?e:salla.config.get("login.mode"))}trackBlockedError(e,t){var a;void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"])&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message});}}class F extends g{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders",editOrder:"orders/{id}"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get",editOrder:"put"},this.after_init();}show(e){let t=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["url"]);}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:salla.helpers.hasApplePay()}}).then(function(t){return salla.event.order.canceled(t,e),t}).catch(function(t){throw salla.event.order.notCanceled(t,e),t})}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then(function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}reorderProduct(e){return e=e||salla.config.get("page.id"),this.request(["reorderProduct",e]).then(function(t){const a=h$1({},t.data,{type:"reorder",id:e}),r=h$1({},t,{data:a});return salla.event.order.orderCreated(r,t.data.order_id),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then(e=>(salla.event.order.invoiceSent(e,t),e)).catch(e=>{throw salla.event.order.invoiceNotSent(e,t),e})}editOrder(e,t){return e=e||salla.config.get("page.id"),this.request(["editOrder",e],t).then(function(t){return salla.event.order.orderEdited(t,e),t}).catch(function(t){throw salla.event.order.orderNotEdited(t,e),t})}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.order.ordersFetched(e),e}).catch(function(e){throw salla.event.order.ordersNotFetched(e),e})}}class v extends g{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftProductDetails:"products/{product_id}/buy-as-gift",productGiftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},this.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get"},this.after_init();}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then(function(e){return salla.product.event.priceUpdated(e,a),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,a),e})}categories(e){return this.request(["categories",e||""],null,"get").then(function(e){return salla.product.event.categoriesFetched(e),e}).catch(function(e){throw salla.product.event.categoriesFailed(e),e})}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then(function(t){return salla.product.event.availabilitySubscribed(t,e),t}).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}search(e){var t;let a=e.data;if(a||(a={params:"string"==typeof e?{query:e}:e}),!(e=a instanceof FormData?a.get("query"):a.query||(null==(t=a.params)?void 0:t.query))){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",a,"get").then(function(t){return salla.product.event.searchResults(t,e),t}).catch(function(t){throw salla.product.event.searchFailed(t,e),t})}offers(e){var t;if(!(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then(function(t){return salla.product.event.offersFetched(t,e),t}).catch(function(t){throw salla.product.event.fetchOffersFailed(t,e),t})}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then(t=>(salla.product.event.sizeGuideFetched(t,e),t)).catch(t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t})}getGiftProductDetails(e){return this.request(["giftProductDetails",e]).then(t=>(salla.product.event.giftFetched(t,e),t)).catch(t=>{throw salla.product.event.giftFetchFailed(t,e),t})}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then(function(t){return salla.product.event.detailFetched(t,e),t}).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}addProductGiftToCart(e,t,a=false){return this.request(["productGiftToCart",e],t).then(t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t)).catch(t=>{throw salla.product.event.addGiftToCartFailed(t,e),t})}uploadGiftImage(e){return this.request("giftImage",e).then(e=>(salla.product.event.giftImageUploadSucceeded(e),e)).catch(e=>{throw salla.product.event.giftImageUploadFailed(e),e})}fetch(e){if(!e.source){const e="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}const t=!e.source_value,a="string"==typeof e.source_value&&"[]"===e.source_value,r=Array.isArray(e.source_value)&&!e.source_value.length;if((t||a||r)&&!["offers","latest","sales","wishlist","top-rated","reorder"].includes(e.source)){const e="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){const e="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("search"===e.source&&"string"!=typeof e.source_value){const e="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("related"===e.source&&isNaN(e.source_value)){const e="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then(async function(e){return salla.product.event.productListFetchSucceeded(e),e}).catch(e=>{throw salla.product.event.productListFetchFailed(e),e})}fetchOptions(e,t={}){if(!e||0===e.length){const e="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(e),salla.api.errorPromise(e)}const{with:a=[]}=t,r={selected:e};return a.length>0&&(r.with=a),this.request(this.endpoints.fetchOptions,{params:r},"get").then(e=>(salla.product.event.productOptionsFetched(e),e)).catch(e=>{throw salla.product.event.productOptionsNotFetched(e),e})}}class y extends g{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init();}syncUserData(e){let t={id:e.id,type:"user",email:e.email,mobile:e.phone.code+e.phone.number,country_code:e.phone.country,language_code:e.language,currency_code:e.currency,notifications:e.notifications,pending_orders:e.pending_orders,avatar:e.avatar,first_name:e.first_name,last_name:e.last_name,is_hidden_name:e.is_hidden_name,is_notifiable:e.is_notifiable,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",t),salla.storage.set("user",t);}info(){return this.request("info",null,"get").then(e=>(this.syncUserData(e.data),salla.profile.event.infoFetched(e),e)).catch(e=>{throw salla.profile.event.infoNotFetched(e),e})}update(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("update",e).then(e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateCustomFields(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("updateCustomFields",e).then(e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateContacts(e){return this.request("updateContacts",e).then(e=>(salla.profile.event.verificationCodeSent(e),e)).catch(e=>{throw salla.event.profile.updateContactsFailed(e),e})}verify(e){return this.request("verify",e).then(e=>(salla.profile.event.verified(e),e)).catch(e=>{throw salla.event.profile.unverified(e),e})}updateSettings(e){return this.request("updateSettings",e).then(e=>(salla.event.profile.settingsUpdated(e),e)).catch(e=>{throw salla.event.profile.updateSettingsFailed(e),e})}delete(){return this.request("delete").then(e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.api.appendIframeAndLogout().then(()=>{salla.event.profile.deleted(e),window.location.href=salla.url.get("logout");}),e)).catch(e=>{throw salla.event.profile.notDeleted(e),e})}}class C extends g{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init();}add(e){var t;if(null!=(t=e)&&t.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,true)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["addComment","blog"==e.type?"blogs":e.type,e.id],{comment:e.comment}).then(function(t){return salla.event.comment.added(t,e.id),t}).catch(function(t){throw salla.event.comment.additionFailed(t,e.id),t})}getCommentPayload(e,t=false){let a={};if(["id","type","comment","per_page","page","sort"].forEach(t=>{let r=salla.form.getPossibleValue(e,[t]);r&&(a[t]=r);}),!t){let t=e.ids;if(t&&(a.ids=Array.isArray(t)?t:[t]),!a.ids||!a.ids.length)return "Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"}fetchComments(e){const t=e.customerId;if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const a={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(a.sort=e.sort),t&&(a.private_comments=t),this.request(["comments"],{params:a},"get").then(function(t){return salla.event.comment.fetched(t,e),t}).catch(function(t){throw salla.event.comment.fetchFailed(t,e),t})}getComments(e,t,a=1,r=5,s,i=null){const n=Array.isArray(t)?t:[t];return this.fetchComments({ids:n,type:`${e}s`,page:a,per_page:r,sort:s,customerId:i})}}class S extends g{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init();}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then(function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t}).catch(function(t){throw salla.currency.event.failed(t,e),t})}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class w extends g{constructor(){super(),this.namespace="document";}reload(){window.location.reload();}}class A extends g{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init();}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",a],t).then(function(e){return salla.event.rating.orderFetched(e,a),e}).catch(function(e){throw salla.event.rating.orderNotFetched(e,a),e})}store(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then(function(t){return salla.event.rating.storeRated(t,e),t}).catch(function(t){throw salla.event.rating.storeFailed(t,e),t})}products(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then(function(t){return salla.event.rating.productsRated(t,e),t}).catch(function(t){throw salla.event.rating.productsFailed(t,e),t})}shipping(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then(function(t){return salla.event.rating.shippingRated(t,e),t}).catch(function(t){throw salla.event.rating.shippingFailed(t,e),t})}}class E extends g{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},Salla.onReady(()=>{var e;"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||this.injectSourceIntoRequest());});}injectSourceIntoRequest(){Salla.api.axios.interceptors.request.use(e=>(e.headers=h$1({},e.headers,{"s-utm-source":"wishlist"}),e),e=>Promise.reject(e));}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["add",e]).then(t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t)).catch(function(t){throw salla.wishlist.event.additionFailed(t,e),t}):(salla.wishlist.event.additionFailed(a="Failed to get product id!"),salla.api.errorPromise(a))}remove(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["remove",e]).then(t=>(this.updateWishlistStorage(e,false),salla.wishlist.event.removed(t,e),t)).catch(function(t){throw salla.wishlist.event.removingFailed(t,e),t}):(salla.wishlist.event.removingFailed(a="Failed to get id!"),salla.api.errorPromise(a))}updateWishlistStorage(e,t=true){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a);}}class b extends g{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init();}get(){return this.request("scopes",null,"get").then(e=>(salla.scope.event.fetched(e),e)).catch(e=>{throw salla.scope.event.notFetched(e),e})}change(e){return this.request("scopes",e).then(e=>(salla.scope.event.changeSucceeded(e),e)).catch(e=>{throw salla.scope.event.changeFailed(e),e})}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then(t=>(salla.scope.event.productAvailabilityFetched(t,e),t)).catch(e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e})}}class _ extends g{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"};}async add(e,t=true){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then(function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e}).catch(function(e){throw salla.booking.event.additionFailed(e),e})}}class k extends g{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init();}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then(function(t){return salla.event.landing.detailsFetched(t,e),t}).catch(function(t){throw salla.event.landing.getDetailsFailed(t,e),t})}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then(function(t){return salla.event.landing.orderCreated(t,e).then(()=>location.href=t.data.url),t}).catch(function(t){throw salla.event.landing.orderCreationFailed(t,e),t})}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.landing.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e})}}class x extends g{constructor(){super(),this.namespace="notifications",this.endpoints={fetch:"notifications"},this.endpointsMethods={fetch:"get"},this.after_init();}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.notifications.fetched(e),e}).catch(function(e){throw salla.event.notifications.fetchFailed(e),e})}}class B{constructor(){var e,t=this;this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",async function(e){return await t.initiateRequest(e)}),salla.event.on("profile::info.fetched",e=>this.setCurrencyAndLanguage(e)),salla.event.on("auth::token.fetched",e=>{salla.storage.set("token",e),this.inIframe&&salla.log("token fetched iframe"),this.inIframe&&salla.cookie.set("s-token",e,60),this.setToken(e);}),salla.event.on("auth::token.invalid",()=>{salla.storage.remove("user"),salla.storage.remove("token");}),this.notifier_handler_disabled=false,this.axios=axios.create({baseURL:Salla.config.get("store.api",Salla.config.get("store.url")),headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":(null==(e=Salla)||null==(e=e.versions)?void 0:e.twilight)||"2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}}),this.axios.interceptors.request.use(e=>{"preview"===Salla.config.get("theme.mode")&&(e.url=Salla.url.addParamToUrl("use_username_url",1,e.url));try{var t;const a=Salla.config.get("swoole",[]),r=new RegExp(a.join("|"),"i");a.length>0&&r.test(e.url)&&(e.headers["s-store-api-version"]="swoole");const s=null==(t=Salla.analytics)?void 0:t.getAnonymousId();s&&(e.headers["s-anonymous-id"]=s);}catch(e){Salla.log("Error in request interceptor:",e);}return e},e=>Promise.reject(e));}getHeaders(){let e=h$1({},this.axios.defaults.headers.common);return delete e["Content-Type"],e}getHeader(e){var t;return null==(t=Object.entries(this.getHeaders()).filter(([t])=>t.toLowerCase()===e.toLowerCase())[0])?void 0:t[1]}setHeaders(e){return Object.entries(e).forEach(e=>this.setHeader(e[0],e[1])),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=true,await e().finally(()=>{this.notifier_handler_disabled=false;})}async initiateRequest(e){var t,a,r;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(h$1({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(r=e.user)?void 0:r.country_code},e.headers||{}));const s=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search),n=i.get("scope"),o=i.get("allocation_type"),l=i.get("allocation_id");if(n&&s&&!Salla.url.is_page("cart")){const e=Salla.storage.get("scope")||{};Salla.storage.set("scope",h$1({},e,{type:s.type,id:n},o&&{allocation_type:o},l&&{allocation_id:l})),s.id=n,Salla.cart.reset();}if((o||l)&&(Salla.url.is_page("cart")||!n||!s)){const e=Salla.storage.get("scope")||{};var u,c;if(null!=e&&e.id||null!=s&&s.id)Salla.storage.set("scope",h$1({},e,{id:null!=(u=null==e?void 0:e.id)?u:null==s?void 0:s.id,type:null!=(c=null==e?void 0:e.type)?c:null==s?void 0:s.type},o&&{allocation_type:o},l&&{allocation_id:l}));}if(s){this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const e=Salla.storage.get("scope")||{};e.allocation_type&&this.setHeader("s-scope-allocation-type",e.allocation_type),e.allocation_id&&this.setHeader("s-scope-allocation-id",e.allocation_id);}const d=Salla.storage.getWithTTL("s-utms");if(d){const e={};Object.entries(d).forEach(([t,a])=>{e[t]="string"==typeof a&&/[^\x00-\x7F]/.test(a)?encodeURIComponent(a):a;}),this.setHeaders(e);}await this.injectTokenToTheRequests(e),Salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",Salla.storage.get("affiliate_code"));}async injectTokenToTheRequests(e){var t,a,r=this;let i,n,o=this.getToken(),l="guest"===(null==(t=e.user)?void 0:t.type),u=parseInt((null==(a=e.user)?void 0:a.id)||0),c=parseInt(salla.storage.get("user.id")||0),d=salla.auth.api.isSessionless(),h=e=>{this.setToken(e),salla.event.emit("api::initiated");},p=async function(){l||d||!u?salla.auth.event.tokenInvalid():(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then(async function(){await salla.profile.info();}).catch(()=>salla.auth.event.tokenInvalid()));};if(!o)return salla.log("Api:: case 1 => current is is guest"),void await p();try{i=jwtDecode(o);}catch(e){return Salla.logger.warn("Failed to decode JWT token",e),void Salla.auth.event.tokenInvalid()}return Date.now()/1e3>i.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await p()):(n=d?parseInt(i.sub)!==c:!c||!u||c!==u||parseInt(i.sub)!==u,n?(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${i.sub} userIdInWeb:${u} userIdInStorage:${c}, isSessionless:${d}`,i.sub,u,c),this.setHeader("Authorization","Bearer "+o),void await salla.profile.info().then(async function(e){!r.inIframe&&!d&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),h(o);}).catch(()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid();})):(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void h(o)))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}cleanupTokenFromUrl(){try{const e=new URL(window.location.href);if(!e.searchParams.has("token"))return;e.searchParams.delete("token"),window.history.replaceState({},document.title,e.toString());}catch(e){Salla.logger.warn("Failed to cleanup token from URL",e);}}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t=void 0,a="get",r={}){let s={endPoint:e,payload:t,method:a,options:r},i="undefined"!=typeof event?event.currentTarget:null,n=false;return "SALLA-BUTTON"===(null==i?void 0:i.tagName)&&(n=true),n&&(null==i||i.load()),this.axios[s.method](s.endPoint,s.payload,s.options).then(e=>(n&&(null==i||i.stop()),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e)).catch(e=>{throw n&&(null==i||i.stop()),salla.event.document.requestFailed(s,e),this.handleErrorResponse(e),e})}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;try{dataLayer&&r&&dataLayer.push(r);}catch(e){salla.logger.error(e.message);}this.fireEventsForResponse(e),this.showAlert(e);}fireEventsForResponse(e){var t,a;let r=(null==e?void 0:e.events)||(null==(t=e.data)?void 0:t.events)||(null==(a=e.error)?void 0:a.events);"string"==typeof r&&(r=JSON.parse(r)),r&&Object.keys(r).forEach(e=>salla.event.dispatch(e,r[e]));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){var t,a;if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&null!=(t=e.data)&&t.message?salla.notify.fire(null==(a=e.data)?void 0:a.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach(e=>{let r=t[e];Array.isArray(r)?r.forEach(e=>a.push(e)):a.push(r);});let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=true){return new Promise((a,r)=>t?a(e):r(e))}errorPromise(e){return this.promise(e,false)}successPromise(e){return this.promise(e,true)}getToken(){if(Salla.storage.get("token"))return Salla.storage.get("token");try{var e;const t=null==(e=new URLSearchParams(window.location.search))?void 0:e.get("token");if(!t)return;if(3!==t.split(".").length)return;return this.cleanupTokenFromUrl(),t}catch(e){Salla.logger.warn("Failed to extract or validate token from URL",e);}}}class P extends g{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}?store_id={store}&lang={lang}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"};}async getMenus(e="header"){return this.request(["getMenus",e,salla.config.get("store.id"),salla.lang.getLocale()]).then(function(e){return salla.event.component.menuFetched(e),e}).catch(function(e){throw salla.event.component.menuFetchFailed(e),e})}async getReviews({per_page:e=5,type:t="all",items:a}){if(!t){const e="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}const r=!a||"string"==typeof a&&"[]"===a||Array.isArray(a)&&!a.length;if(!new Set(["all","store","categories","products","json"]).has(t)){const e="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if("all"!==t&&"store"!==t&&r){const e="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if(new Set(["products","categories"]).has(t)&&!Array.isArray(a)){const e=`Items value must be an array of ${t} id for review type of ${t}.`;return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}return this.request(["reviews"],{params:{per_page:e,type:t,items:a}},"get").then(function(e){return salla.event.component.reviewsFetched(e),e}).catch(function(e){throw salla.event.component.reviewsFetchFailed(e),e})}}class I extends g{constructor(){super(),this.namespace="booking",this.endpoints={fetch:"advertisements"},this.endpointsMethods={fetch:"get"};}async fetch(e=null){const t=e?{page:e}:{};return this.request(["fetch"],{params:t}).then(function(e){return salla.event.advertisement.fetched(e),e}).catch(function(e){throw salla.event.advertisement.fetchFailed(e),e})}}class q extends g{constructor(){super(),this.namespace="navigation",this.endpoints={breadcrumbs:"breadcrumbs"},this.endpointsMethods={breadcrumbs:"get"},this.after_init();}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.single","product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.navigation.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.navigation.breadcrumbFetchFailed(e),e})}}class T extends g{constructor(){super(),this.namespace="metadata",this.endpoints={fetchValues:"https://api.salla.dev/store/v1/metadata/values"},this.endpointsMethods={fetchValues:"get"};}async fetchValues(e,t){if(!e||!t){const e="Please provide entity type and entity ids.";return salla.metadata.event.valueNotFetch(e),salla.api.errorPromise(e)}const a={type:e,entities:Array.isArray(t)?t:[t]};return this.request(this.endpoints.fetchValues,{params:a},"get").then(e=>(salla.metadata.event.valueFetched(e),e)).catch(e=>{throw salla.metadata.event.valueNotFetch(e),e})}}class L{constructor(e){this.config=e,this.configKey="s-twilight-config",this.tempUser=e.user;}async getConfig(){if(Object.entries(this.config.store).length>2)return this.config;let e=await this.getConfigFromSession();return e||(e=await this.getConfigFromApi()),e.user=this.tempUser,e}async getConfigFromSession(){var e;let t=salla.storage.getWithTTL("session",this.configKey);return t&&"object"==typeof t&&null!=(e=t.store)&&e.id?this.config.store.id==t.store.id?t:(salla.storage.session.remove(this.configKey),null):null}getConfigFromApi(){console.log("getting Twilight initiate config using store.id ...");const e=new URL(`${(this.config.store.api||Salla.config.get("store.api")).replace(/\/$/,"")}/store/settings`);return fetch(e,{headers:Salla.api.getHeaders()}).then(e=>e.json()).then(e=>{if(200!==e.status)throw {response:e};return this.setConfigToSession(e.data)}).catch(e=>{throw Salla.api.handleErrorResponse(e),e})}setConfigToSession(e){return Salla.storage.setWithTTL("session",this.configKey,e,1800),e}}class R{constructor(){Salla.event.on("twilight::before.ready",()=>this.renderAll());}async renderAll(){Salla.hooks.renderAutoComponents([{hook:"product:single.description",tag:"salla-delivery-promise",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("delivery-promises")},{hook:"product:single.form.end",tag:"salla-fulfillment-methods",canRender:()=>Salla.url.is_page("product.single")&&!Salla.config.get("store.features",[]).includes("bullet-delivery-v2")},{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}},{hook:"body:end",tag:"salla-bullet-delivery",canRender:()=>{var e;return (null==(e=Salla.config.get("store.features"))?void 0:e.includes("bullet-delivery-v2"))&&true===Salla.config.get("store.settings.bullet_delivery.enabled")}}]),await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.helpers.isIframe()||(this.renderMaintenance(),this.renderThemePreview());}renderMaintenance(){Salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?Salla.logger.warn("salla-maintenance-alert element Existed before!"):document.body.prepend(document.createElement("salla-maintenance-alert")));}renderTemplateStore(){Salla.config.get("store.template")&&(document.body.classList.add("has-bottom-alert"),document.querySelector("salla-bottom-alert")?Salla.logger.warn("salla-bottom-alert element Existed before!"):document.body.append(document.createElement("salla-bottom-alert")));}renderAppInstall(){Salla.config.get("store.app_install_prompt")&&Salla.config.get("store.apps")&&!Salla.storage.get("app_install_prompt_disabled")&&!Salla.config.isMobileApp()&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?Salla.logger.warn("salla-app-install-alert element Existed before!"):document.body.append(document.createElement("salla-app-install-alert")));}renderThemePreview(){if("preview"!==Salla.config.get("theme.mode"))return;if(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar"))return void Salla.logger.warn("#s-theme_preview_bar element Existed before!");let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://cdn.salla.network/images/logo/logo-light.svg">\n <span style="margin:0 10px;">${Salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${Salla.config.get("theme.name")}</span></span>\n </div>\n <a href="${Salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e);}renderEdit(){let e=Salla.config.get("edit");if(!e)return;if(document.querySelector("#s-edit-alert"))return void Salla.logger.warn("#s-edit-alert element Existed before!");let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${Salla.config.get("theme.color.primary","#5cd5c4")}; color:${Salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${Salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t);}applyContentCopyright(){if(!Salla.config.get("store.settings.content_copyright"))return;["contextmenu","selectstart","copy"].forEach(e=>{document.addEventListener(e,e=>{(e=>{var t;if(!e)return false;const a=null==(t=e.tagName)?void 0:t.toLowerCase();return "input"===a||"textarea"===a})(e.target)||e.preventDefault();});}),document.addEventListener("keydown",e=>{const t=e.key.toLowerCase();("f12"===t||e.ctrlKey&&e.shiftKey&&["i","j","c"].includes(t)||e.ctrlKey&&"u"===t)&&(e.preventDefault(),e.stopPropagation());});const e=document.createElement("style");e.textContent="\n body {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n input, textarea {\n -webkit-touch-callout: auto;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n -ms-user-select: auto;\n user-select: auto;\n }\n img {\n pointer-events: none;\n -webkit-user-drag: none;\n }\n ",document.head.appendChild(e);}}class j{constructor(e){this.storeUserKey="s-store-user",Salla.event.on("twilight::initiated",()=>this.embedStoreUser()),this.embedUser(e);}embedUser(e){return e.user||(e.user=this.getUser(),e.user.language_code=Salla.cookie.get("s-lang",e.user.language_code),e.user.currency_code=Salla.cookie.get("s-curr",e.user.currency_code)),e}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return {type:"guest",language_code:Salla.cookie.get("s-lang",Salla.lang.getLocale()),currency_code:Salla.cookie.get("s-curr","SAR")}}async embedStoreUser(){if(Salla.config.isGuest())return;let e=Salla.storage.getWithTTL("session",this.storeUserKey);e||(e=await this.getStoreUserFromApi()),Salla.config.set("user",h$1({},Salla.config.get("user"),e)),Salla.log("Store user is embeded to the user object.");}async getStoreUserFromApi(){let e={};try{const t=await Salla.api.request("profile/notifications/unread");if(e.notification=t.data.count,e.is_notifiable=t.data.is_notifiable,Salla.config.get("store.features",[]).includes("loyalty-system")){const t=await Salla.api.request("profile/loyalty/points");t&&(e.loyalty_points=t.data.points);}}catch(e){Salla.log("Failed to get user services",e);}return Salla.storage.setWithTTL("session",this.storeUserKey,e,300),e}}class U{constructor(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat",sccid:"snapchat"},t=Object.keys(e),a=["utm_source","utm_medium","utm_campaign","utm_term","utm_content",...t],r={},s={};window.location.search.replace("?","").split("&").map(e=>e.split("=")).filter(([e])=>a.includes(e.toLowerCase())).forEach(([e,t])=>{let a=t||"",s=false;try{a=decodeURIComponent(t),s=true;}catch(e){Salla.log("Failed to decode UTM param:",e);}r[e.toLowerCase()]=s?a.replace(/(?:[\0-\x1F!-,\.\/:-@\[-`\{-\xA9\xAB-\xB1\xB4\xB6-\xB8\xBB\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u036F\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482-\u0489\u0530\u0557\u0558\u055A-\u055F\u0589-\u05CF\u05EB-\u05EE\u05F3-\u061F\u064B-\u065F\u066A-\u066D\u0670\u06D4\u06D6-\u06E4\u06E7-\u06ED\u06FD\u06FE\u0700-\u070F\u0711\u0730-\u074C\u07A6-\u07B0\u07B2-\u07BF\u07EB-\u07F3\u07F6-\u07F9\u07FB-\u07FF\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u083F\u0859-\u085F\u086B-\u086F\u0888\u0890-\u089F\u08CA-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962-\u0965\u0970\u0981-\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA-\u09BC\u09BE-\u09CD\u09CF-\u09DB\u09DE\u09E2-\u09E5\u09F2\u09F3\u09FA\u09FB\u09FD-\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A-\u0A58\u0A5D\u0A5F-\u0A65\u0A70\u0A71\u0A75-\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA-\u0ABC\u0ABE-\u0ACF\u0AD1-\u0ADF\u0AE2-\u0AE5\u0AF0-\u0AF8\u0AFA-\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A-\u0B3C\u0B3E-\u0B5B\u0B5E\u0B62-\u0B65\u0B70\u0B78-\u0B82\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BCF\u0BD1-\u0BE5\u0BF3-\u0C04\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C3E-\u0C57\u0C5B\u0C5E\u0C5F\u0C62-\u0C65\u0C70-\u0C77\u0C7F\u0C81-\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA-\u0CBC\u0CBE-\u0CDB\u0CDF\u0CE2-\u0CE5\u0CF0\u0CF3-\u0D03\u0D0D\u0D11\u0D3B\u0D3C\u0D3E-\u0D4D\u0D4F-\u0D53\u0D57\u0D62-\u0D65\u0D79\u0D80-\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DE5\u0DF0-\u0E00\u0E31\u0E34-\u0E3F\u0E47-\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EB1\u0EB4-\u0EBC\u0EBE\u0EBF\u0EC5\u0EC7-\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F1F\u0F34-\u0F3F\u0F48\u0F6D-\u0F87\u0F8D-\u0FFF\u102B-\u103E\u104A-\u104F\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B-\u1368\u137D-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u1712-\u171E\u1732-\u173F\u1752-\u175F\u176D\u1771-\u177F\u17B4-\u17D6\u17D8-\u17DB\u17DD-\u17DF\u17EA-\u17EF\u17FA-\u180F\u181A-\u181F\u1879-\u187F\u1885\u1886\u18A9\u18AB-\u18AF\u18F6-\u18FF\u191F-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19FF\u1A17-\u1A1F\u1A55-\u1A7F\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1B04\u1B34-\u1B44\u1B4D-\u1B4F\u1B5A-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BFF\u1C24-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C8B-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1CFB-\u1CFF\u1DC0-\u1DFF\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u206F\u2072\u2073\u207A-\u207E\u208A-\u208F\u209D-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A-\u245F\u249C-\u24E9\u2500-\u2775\u2794-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF4-\u2CFC\u2CFE\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF-\u2E2E\u2E30-\u3004\u3008-\u3020\u302A-\u3030\u3036\u3037\u303D-\u3040\u3097-\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u3191\u3196-\u319F\u31C0-\u31EF\u3200-\u321F\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA66F-\uA67E\uA69E\uA69F\uA6F0-\uA716\uA720\uA721\uA789\uA78A\uA7DD-\uA7F0\uA802\uA806\uA80B\uA823-\uA82F\uA836-\uA83F\uA874-\uA881\uA8B4-\uA8CF\uA8DA-\uA8F1\uA8F8-\uA8FA\uA8FC\uA8FF\uA926-\uA92F\uA947-\uA95F\uA97D-\uA983\uA9B3-\uA9CE\uA9DA-\uA9DF\uA9E5\uA9FF\uAA29-\uAA3F\uAA43\uAA4C-\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAC3-\uAADA\uAADE\uAADF\uAAEB-\uAAF1\uAAF5-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABE3-\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB1E\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD06\uDD34-\uDD3F\uDD79-\uDD89\uDD8C-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEE0\uDEFC-\uDEFF\uDF24-\uDF2C\uDF4B-\uDF4F\uDF76-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDD6F\uDD7B\uDD8B\uDD93\uDD96\uDDA2\uDDB2\uDDBA\uDDBD-\uDDBF\uDDF4-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDF7F\uDF86\uDFB1\uDFBB-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56\uDC57\uDC77\uDC78\uDC9F-\uDCA6\uDCB0-\uDCDF\uDCF3\uDCF6-\uDCFA\uDD1C-\uDD1F\uDD3A-\uDD3F\uDD5A-\uDD7F\uDDB8-\uDDBB\uDDD0\uDDD1\uDE01-\uDE0F\uDE14\uDE18\uDE36-\uDE3F\uDE49-\uDE5F\uDE7F\uDEA0-\uDEBF\uDEC8\uDEE5-\uDEEA\uDEF0-\uDEFF\uDF36-\uDF3F\uDF56\uDF57\uDF73-\uDF77\uDF92-\uDFA8\uDFB0-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCF9\uDD24-\uDD2F\uDD3A-\uDD3F\uDD66-\uDD6E\uDD86-\uDE5F\uDE7F\uDEAA-\uDEAF\uDEB2-\uDEC1\uDEC8-\uDEFF\uDF28-\uDF2F\uDF46-\uDF50\uDF55-\uDF6F\uDF82-\uDFAF\uDFCC-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC00-\uDC02\uDC38-\uDC51\uDC70\uDC73\uDC74\uDC76-\uDC82\uDCB0-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDD02\uDD27-\uDD35\uDD40-\uDD43\uDD45\uDD46\uDD48-\uDD4F\uDD73-\uDD75\uDD77-\uDD82\uDDB3-\uDDC0\uDDC5-\uDDCF\uDDDB\uDDDD-\uDDE0\uDDF5-\uDDFF\uDE12\uDE2C-\uDE3E\uDE41-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEDF-\uDEEF\uDEFA-\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A-\uDF3C\uDF3E-\uDF4F\uDF51-\uDF5C\uDF62-\uDF7F\uDF8A\uDF8C\uDF8D\uDF8F\uDFB6\uDFB8-\uDFD0\uDFD2\uDFD4-\uDFFF]|\uD805[\uDC35-\uDC46\uDC4B-\uDC4F\uDC5A-\uDC5E\uDC62-\uDC7F\uDCB0-\uDCC3\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDAF-\uDDD7\uDDDC-\uDDFF\uDE30-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEAB-\uDEB7\uDEB9-\uDEBF\uDECA-\uDECF\uDEE4-\uDEFF\uDF1B-\uDF2F\uDF3C-\uDF3F\uDF47-\uDFFF]|\uD806[\uDC2C-\uDC9F\uDCF3-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD30-\uDD3E\uDD40\uDD42-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD1-\uDDE0\uDDE2\uDDE4-\uDDFF\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE4F\uDE51-\uDE5B\uDE8A-\uDE9C\uDE9E-\uDEAF\uDEF9-\uDFBF\uDFE1-\uDFEF\uDFFA-\uDFFF]|\uD807[\uDC09\uDC2F-\uDC3F\uDC41-\uDC4F\uDC6D-\uDC71\uDC90-\uDCFF\uDD07\uDD0A\uDD31-\uDD45\uDD47-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8A-\uDD97\uDD99-\uDD9F\uDDAA-\uDDAF\uDDDC-\uDDDF\uDDEA-\uDEDF\uDEF3-\uDF01\uDF03\uDF11\uDF34-\uDF4F\uDF5A-\uDFAF\uDFB1-\uDFBF\uDFD5-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD812-\uD817\uD819\uD824-\uD82A\uD82D\uD82E\uD830-\uD832\uD836\uD83D\uD83F\uD87C\uD87D\uD87F\uD88E-\uDBFF][\uDC00-\uDFFF]|\uD80B[\uDC00-\uDF8F\uDFF1-\uDFFF]|\uD80D[\uDC30-\uDC40\uDC47-\uDC5F]|\uD810[\uDFFB-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD818[\uDC00-\uDCFF\uDD1E-\uDD2F\uDD3A-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDE6F\uDEBF\uDECA-\uDECF\uDEEE-\uDEFF\uDF30-\uDF3F\uDF44-\uDF4F\uDF5A\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDD3F\uDD6D-\uDD6F\uDD7A-\uDE3F\uDE97-\uDE9F\uDEB9\uDEBA\uDED4-\uDEFF\uDF4B-\uDF4F\uDF51-\uDF92\uDFA0-\uDFDF\uDFE2\uDFE4-\uDFF1\uDFF7-\uDFFF]|\uD823[\uDCD6-\uDCFE\uDD1F-\uDD7F\uDDF3-\uDFFF]|\uD82B[\uDC00-\uDFEF\uDFF4\uDFFC\uDFFF]|\uD82C[\uDD23-\uDD31\uDD33-\uDD4F\uDD53\uDD54\uDD56-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDFFF]|\uD833[\uDC00-\uDCEF\uDCFA-\uDFFF]|\uD834[\uDC00-\uDEBF\uDED4-\uDEDF\uDEF4-\uDF5F\uDF79-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD837[\uDC00-\uDEFF\uDF1F-\uDF24\uDF2B-\uDFFF]|\uD838[\uDC00-\uDC2F\uDC6E-\uDCFF\uDD2D-\uDD36\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDE8F\uDEAE-\uDEBF\uDEEC-\uDEEF\uDEFA-\uDFFF]|\uD839[\uDC00-\uDCCF\uDCEC-\uDCEF\uDCFA-\uDDCF\uDDEE\uDDEF\uDDFB-\uDEBF\uDEDF\uDEE3\uDEE6\uDEEE\uDEEF\uDEF5-\uDEFD\uDF00-\uDFDF\uDFE7\uDFEC\uDFEF\uDFFF]|\uD83A[\uDCC5\uDCC6\uDCD0-\uDCFF\uDD44-\uDD4A\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDC70\uDCAC\uDCB0\uDCB5-\uDD00\uDD2E\uDD3E-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDCFF\uDD0D-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEE0-\uDEFF]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEAE\uDEAF]|\uD87A[\uDFE1-\uDFEF]|\uD87B[\uDE5E-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDF4F]|\uD88D[\uDC7A-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g," ").replace(/ +/g," ").trim():a;});const i=t.find(e=>r[e]);!r.utm_source&&i&&(r.utm_source=e[i],r.utm_campaign=r.utm_campaign||`Using the CLICKID ${i} provided by ${r.utm_source}`,r.utm_term=r.utm_term||`${i}: ${r[i]}`),r.utm_source&&(Object.entries(r).filter(([e])=>!t.includes(e)).forEach(([e,t])=>{s[`s-${e.replace("_","-")}`]=t;}),s["s-utm-referrer"]=document.referrer,Salla.storage.setWithTTL("s-utms",s,129600),this.logUTMVisitData(s));}async logUTMVisitData(e){const t=e["s-utm-source"],a=e["s-utm-medium"],r=e["s-utm-campaign"],s=Salla.config.get("store.id");e&&"affiliate"===t&&a&&r&&fetch(Salla.config.get("affiliate.utm_url"),{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","s-utm-source":t,"s-utm-medium":a,"s-utm-campaign":r,"s-store-id":s}}).then(e=>{if(!e.ok)return;const t=new URL(window.location.href),a=window.history.state;t.searchParams.delete("utm_source"),t.searchParams.delete("utm_medium"),t.searchParams.delete("utm_campaign"),window.history.replaceState(a,"",t);});}}class O{constructor(e){var t,a,r;if("ready"!==Salla.status){if(null==e||null==(t=e.store)||!t.id)return console.error("Trying to init Twilight without store.id!"),void console.log("you can initiate twilight using this line only: Salla.init({store:{id:1234}})");var s;if(Salla.config.merge(e),!["salla.sa","salla.group"].includes(location.hostname)||null!=(a=Salla.config.get("store.url"))&&a.includes(location.hostname)||!Salla.config.get("store.username")||Salla.config.set("store.url",window.location.origin+"/"+Salla.config.get("store.username")),(null==e?void 0:e.events)&&Salla.event.dispatchEvents(null==e?void 0:e.events),new R,new j(e),null!=e&&null!=(r=e.user)&&r.language_code)Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);Salla.storage.get("scope.id")!=Salla.config.get("store.scope.id")&&Salla.storage.set("scope",Salla.config.get("store.scope",Salla.config.get("scope"))),new L(e).getConfig().then(e=>{Salla.config.merge(e),this.setSallaReady(e),this.afterInit();}).catch(e=>console.error("failed to initite twilight😢",e));}else Salla.log("Trying to re-initiate Salla, while its status === 'ready'!");}afterInit(){Salla.url.is_page("product.single")&&Salla.config.isGuest()&&window.addEventListener("mini-checkout::before-init",e=>{e.preventDefault(),Salla.event.emit("login::open");});}setSallaReady(e){new U,Salla.event.emitAsync("twilight::before.ready",e),Salla.status="ready",Salla.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}));}}class N{constructor(e){const t=null==e?void 0:e.nextPage;this.listId=salla.config.get("page.slug"),Salla.config.get("page.id")&&(this.listId+=`_${salla.config.get("page.id")}`),this.sorts=null;try{if(t){const e=new URL(t).searchParams.get("sort");e&&(this.sorts=[{type:"sort",value:e}]);}e.source&&(this.listId=`${this.listId}_${e.source}`),e.sourceValue&&(this.listId=`${this.listId}_${Array.isArray(e.sourceValue)?e.sourceValue.join("_"):e.sourceValue}`);}catch(e){salla.logger.error(e);}this.products=null==e?void 0:e.data;}toSegment(){const e=(salla.config.get("page.title")||"").split("|").map(e=>e.trim()),t=e[0],a=e[1]||null;return {event:"Product List Viewed",properties:{list_id:this.listId,category:t,sub_category:a,sorts:this.sorts,products:this.products.map(e=>{var t,a,r,s,i,n;return {product_id:e.id,category:null==(t=e.category)?void 0:t.name,currency:null==(a=Salla.config.currency())?void 0:a.code,name:e.name,brand:null==(r=e.brand)?void 0:r.name,variant:null==(s=e.variant)?void 0:s.toString(),coupon:null==(i=e.coupon)?void 0:i.toString(),price:e.price,quantity:Number(e.quantity),sku:e.sku,position:0,url:e.url,image_url:null==(n=e.image)?void 0:n.url}})}}}static shouldSend(e){return !((null==e?void 0:e.nextPage)||"").includes("filters")&&!["index","customer.wishlist"].includes(salla.config.get("page.slug"))}}class M{constructor(){this.user=JSON.parse(localStorage.getItem("user"));}toSegment(){var e,t,a,r,s;return {event:"Signed In",properties:{first_name:null==(e=this.user)?void 0:e.first_name,last_name:null==(t=this.user)?void 0:t.last_name,type:null==(a=this.user)?void 0:a.type,mobile:null==(r=this.user)?void 0:r.mobile,email:null==(s=this.user)?void 0:s.email}}}static shouldSend(){return "user"===Salla.config.get("user.type")?!Salla.analytics.history.find(({eventName:e})=>"Signed In"===e):(Salla.profile.event.onInfoFetched(()=>Salla.event.emit("Signed In")),false)}}class ${constructor(e){this.details=null==e?void 0:e.data;}toSegment(){const e=["first_name","last_name","birthday","gender"].filter(e=>{var t,a;return $.user[e]!==(null==(t=this.details)?void 0:t[e])&&(void 0!==$.user[e]||void 0!==(null==(a=this.details)?void 0:a[e]))});return $.setUser(this.details),{event:"User Profile Updated",properties:{updated_fields:e}}}static registerEvent(){Salla.onReady(()=>{salla.url.is_page("customer.profile")&&$.setUser(Salla.config.get("user"));});}static setUser(e){$.user={first_name:null==e?void 0:e.first_name,last_name:null==e?void 0:e.last_name,gender:null==e?void 0:e.gender,birthday:null==e?void 0:e.birthday,avatar:null==e?void 0:e.avatar};}static shouldSend(){return "user"===Salla.config.get("user.type")}}$.user={};class H{static registerEvents(){Object.values(this.events).forEach(e=>{e.forEach(e=>{"function"==typeof e.registerEvent&&e.registerEvent();});});}static transform(e,t){try{const a=this.events[e]||[];for(const e of a){if(!e||"function"==typeof e.shouldSend&&!e.shouldSend(t))continue;const a=new e(t).toSegment();return {event:a.event,properties:a.properties}}return null}catch(e){return console.error("Failed to transform event:",e),null}}}H.events={"Order Completed":[class{constructor(e){this.details=e[0];}toSegment(){return {event:"Order Completed",properties:this.details}}}],"Product Added":[class{constructor(e){var t,a;this.item=e[0],this.source=(null==(t=Salla.cart)||null==(t=t.api)?void 0:t.addToCartSource)||null,null!=(a=Salla.cart)&&a.api&&(Salla.cart.api.addToCartSource=null);}toSegment(){var e,t,a,r,s;return {event:"Product Added",properties:{cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),cart_item_id:null==(t=this.item.cart_item_id)?void 0:t.toString(),product_id:null==(a=this.item.id)?void 0:a.toString(),category:this.item.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:this.item.name,brand:this.item.brand,variant:null==(s=this.item.variant)?void 0:s.toString(),price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url,source:this.source}}}static shouldSend(){return "customer.wishlist"!==salla.config.get("page.slug")}},class{constructor(e){this.item=e[0];}toSegment(){var e,t;return {event:"Wishlist Product Added to Cart",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,name:this.item.name,brand:this.item.brand,variant:this.item.variant,price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}}static shouldSend(){return "customer.wishlist"===salla.config.get("page.slug")}}],"Product Removed":[class{constructor(e){this.item=e[0];}toSegment(){var e,t,a,r,s,i,n,o,l,u,c,d,h,p;return {event:"Product Removed",properties:{cart_id:null==(e=this.item)||null==(e=e.cart_id)?void 0:e.toString(),product_id:null==(t=this.item)||null==(t=t.id)?void 0:t.toString(),category:null==(a=this.item)?void 0:a.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:null==(s=this.item)?void 0:s.name,brand:null==(i=this.item)?void 0:i.brand,variant:null==(n=this.item)?void 0:n.variant,price:null==(o=this.item)?void 0:o.price,quantity:null==(l=this.item)?void 0:l.quantity,sku:null==(u=this.item)?void 0:u.sku,coupon:null==(c=this.item)?void 0:c.coupon,position:null==(d=this.item)?void 0:d.position,url:null==(h=this.item)?void 0:h.url,image_url:null==(p=this.item)?void 0:p.image_url}}}}],"Product Viewed":[class{constructor(e){this.product=e[0];try{this.source=sessionStorage.getItem("s-viewed-source")||null,sessionStorage.removeItem("s-viewed-source");}catch(e){this.source=null;}}toSegment(){var e;return {event:"Product Viewed",properties:{product_id:null==(e=this.product.id)?void 0:e.toString(),category:this.product.category,name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:this.product.quantity,currency:this.product.currency,coupon:this.product.coupon,position:this.product.position,value:this.product.value,sku:this.product.sku,url:this.product.url,image_url:this.product.image_url,source:this.source}}}}],"Product Added to Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Added to Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,position:Number(this.product.position||0),url:this.product.url,image_url:(null==(t=this.product)?void 0:t.image)||null,category:this.product.category,currency:null==(a=Salla.config.currency())?void 0:a.code,brand:this.product.brand}}}}],"Product Removed from Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Removed from Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,coupon:this.product.coupon||null,position:Number(this.product.position||0),currency:null==(t=Salla.config.currency())?void 0:t.code,url:this.product.url,image_url:(null==(a=this.product)?void 0:a.image)||null,category:this.product.category,brand:this.product.brand}}}}],"Cart Viewed":[class{constructor(e){this.cart=e[0];}toSegment(){var e;return {event:"Cart Viewed",properties:{cart_id:null==(e=this.cart.cart_id)?void 0:e.toString(),products:this.cart.products.map(e=>{var t,a,r;return {product_id:null==(t=e.id)?void 0:t.toString(),cart_item_id:null==(a=e.cart_item_id)?void 0:a.toString(),name:e.name,price:e.price,category:e.category,sku:e.sku,position:e.position,url:e.url,image_url:e.image_url,brand:e.brand,currency:null==(r=Salla.config.currency())?void 0:r.code,variant:e.variant,coupon:e.coupon,quantity:e.quantity}})}}}}],"Products Searched":[class{constructor(e){this.query=e;}toSegment(){return {event:"Products Searched",properties:{query:this.query}}}}],"Product List Viewed":[N],"Product List Filtered":[class extends N{constructor(e){super(e);const t=(null==e?void 0:e.nextPage)||"";this.filters=this.extractFilters(t);}extractFilters(e){if(!e)return null;try{const t=new URL(e),a=[];return Array.from(t.searchParams.entries()).forEach(([e,t])=>{if(e.startsWith("filters[")){const r=e.match(/^filters\[(.*?)\]/),s=r?r[1]:e;a.push({type:s,value:t});}}),a.length>0?a:null}catch(e){return console.warn("Error extracting filters from URL:",e),null}}toSegment(){const e=super.toSegment();return {event:"Product List Filtered",properties:h$1({},null==e?void 0:e.properties,{filters:this.filters})}}static shouldSend(e){return ((null==e?void 0:e.nextPage)||"").includes("filters")}}],"Signed Up":[class extends M{toSegment(){const e=super.toSegment();return {event:"Signed Up",properties:null==e?void 0:e.properties}}static shouldSend(){return "user"===Salla.config.get("user.type")||(Salla.profile.event.onInfoFetched(()=>Salla.event.emit("Signed Up")),false)}}],"Signed In":[M],"Signed Out":[class{toSegment(){return {event:"Signed Out",properties:{}}}}],"Product Reviewed":[class{constructor(e){this.details=e;}toSegment(){return {event:"Product Reviewed",properties:this.details}}static registerEvent(){salla.event.rating.onProductsRated(function(e,t){const{products:a,order_id:r}=t;Object.values(a).forEach(e=>{var t;Salla.event.emit("Product Reviewed",{product_id:null==(t=e.product_id)?void 0:t.toString(),review_id:null==r?void 0:r.toString(),review_body:e.comment,rating:e.rating});});});}}],"Product Shared":[class{constructor(e){this.data=e;}toSegment(){var e;const t=(null==(e=Salla.analytics.history.find(({eventName:e})=>"Product Viewed"===e))?void 0:e.payload)||{};return t.share_via=this.data.share_via,{event:"Product Shared",properties:t}}static shouldSend(){return "product.single"===salla.config.get("page.slug")}}],"Promotion Viewed":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Viewed",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Promotion Clicked":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Clicked",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Coupon Applied":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Applied",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Removed":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Removed",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Denied":[class{constructor(e){this.transaction=e;}getCartId(){var e;return "cart"===salla.config.get("page.slug")?null==(e=salla.config.get("page.id"))?void 0:e.toString():""}getCouponCode(){try{var e,t;const a=null==(e=this.transaction.response)||null==(e=e.config)?void 0:e.data;return a?null==(t=JSON.parse(a))?void 0:t.coupon:""}catch(e){return ""}}toSegment(){var e;return {event:"Coupon Denied",properties:{cart_id:this.getCartId(),coupon_name:this.getCouponCode(),reason:(null==(e=this.transaction.response)||null==(e=e.data)||null==(e=e.error)?void 0:e.message)||"Unknown error"}}}}],"User Profile Updated":[$],"Cart Updated":[class{constructor(e){this.cart=e;}toSegment(){var e,t,a,r;return {event:"Cart Updated",properties:{cart_id:null==(e=this.cart.id)?void 0:e.toString(),value:this.cart.total,revenue:this.cart.sub_total,tax:this.cart.tax_amount,discount:this.cart.total_discount,shipping:this.cart.real_shipping_cost,currency:null==(t=Salla.config.currency())?void 0:t.code,affiliation:null==(a=Salla.storage.getWithTTL("s-utms"))?void 0:a["s-utm-source"],products:null==(r=this.cart.items)?void 0:r.map(e=>{var t,a,r,s,i,n;return {product_id:null==(t=e.product_id)?void 0:t.toString(),name:e.product_name,price:e.product_price,category:null==(a=e.category)?void 0:a.toString(),sku:null==(r=e.product_sku)?void 0:r.toString(),position:e.position,url:e.url,image_url:e.product_image,brand:null==(s=e.brand)?void 0:s.toString(),currency:null==(i=Salla.config.currency())?void 0:i.code,variant:null==(n=e.variant)?void 0:n.toString(),coupon:this.cart.coupon,quantity:e.quantity}})}}}static shouldSend(e){return "cart"===salla.config.get("page.slug")&&!(null!=e&&e.fromLatestFetched)}}],"Market Selected":[class{constructor(e){this.scope=e.data;}toSegment(){return {event:"Market Selected",properties:h$1({},this.getScope(this.scope),{prev:this.getScope(Salla.config.get("store.scope"))})}}getScope(e){var t;return {id:null==(t=(e=e||{}).id)?void 0:t.toString(),country:this.getScopeAttribute(e,"countries"),currency:this.getScopeAttribute(e,"currencies"),locale:this.getScopeAttribute(e,"languages")}}getScopeAttribute(e,t){return e=e[t],Array.isArray(e)?e[0]:e}}],"Product Reordered":[class{constructor(e){this.details=e;}toSegment(){var e;return {event:"Product Reordered",properties:{product_id:null==(e=this.details)||null==(e=e.data)||null==(e=e.id)?void 0:e.toString()}}}static shouldSend(e){const t=null==e?void 0:e.data;return (null==t?void 0:t.id)&&!isNaN(null==t?void 0:t.id)&&"reorder"===(null==t?void 0:t.type)}}]};const V="s-session-id";N$3.versions.twilight="2.14.393",N$3.onInitiated=e=>salla.event.once("twilight::initiated",e),N$3.onReady=N$3.onReady||function(t){return new Promise(function(a){return "ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):N$3.onInitiated(e=>a(t?t(e):e))})},N$3.status="loading",N$3.notify=u,N$3.lang=new class extends a$3{constructor(e){e=e||{};const t=salla.cookie.get("s-lang");e.messages=e.messages||window.translations,e.locale=e.locale||(t||window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=false,Salla.event.on("twilight::before.ready",()=>this.loadStoreTranslations());}onLoaded(e){return new Promise(t=>{if(this.translationsLoaded)return t(e?e():null);Salla.event.once("languages::translations.loaded",()=>t(e?e():null));})}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=true)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",false);}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=true;}loadScript(e,t=true){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",false);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}getWithDefault(e,t,a,r){let s=this.get(e,a,r);return s!==e?s:t}get(e,t,a){let r=e;(window.translations||this.translationsLoaded)&&(r="trans."+e);let s=super.get(r,t,a);return s!==r?s:super.get(r,t,"en").replace(r,e)}set(e,t){return salla.helpers.setNested(this.messages[`${this.getLocale()}.trans`],e,t),this}add(e,t){return Object.entries(t).forEach(t=>salla.helpers.setNested(this.messages[t[0]+".trans"],e,t[1])),this}addBulk(e){return Object.entries(e).forEach(([e,t])=>{this.add(e,t);}),this}},N$3.form=new class{async submit(e,t=null){var a;let r=t;if("SubmitEvent"===(null==t||null==(a=t.constructor)?void 0:a.name)||"submit"===(null==t?void 0:t.type)){var s,i;if(t.preventDefault(),"FORM"!==(null==(s=t.target)?void 0:s.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise(()=>{throw "Failed find the target element for submit action. make sure you submit a form element"});"SALLA-BUTTON"===(null==t||null==(i=t.submitter)||null==(i=i.parentElement)?void 0:i.tagName)&&t.submitter.parentElement.load(),r=t.target.getElementSallaData(),salla.log("Data from element",r);}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.request(e,r,"post").finally(()=>{var e;loaderSupported&&(null==t||null==(e=t.submitter)||e.parentElement.stop());});let n=e.split("."),o=n.splice(-1);return await salla.call(n.join("."))[o](r).finally(()=>{var e;return null==t||null==(e=t.submitter)||null==(e=e.parentElement)?void 0:e.stop()}).catch(e=>{throw salla.logger.warn(e),e})}onSubmit(e,t){return salla.form.submit(e,t),false}onChange(e,t){var a;return null!=t&&t.currentTarget?"FORM"!==(null==t||null==(a=t.currentTarget)?void 0:a.tagName)||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),true):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),false):(salla.logger.warn(`Trying to trigger '${e}' without event!`),false)}getPossibleValue(e,t,a=false){if(!e)return;if("object"!=typeof e)return e;let r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},N$3.infiniteScroll=new class extends c{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":true,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[];}initiate(e,a,r,s=false){s?((r=r||{}).fetchOptions=h$1({},this.fetchOptions,r.fetchOptions||{}),r.responseBody="json"):r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),n=r.path;if(!i||!n||"string"==typeof n&&!document.querySelector(n))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let o=new t$1(i,r);return o.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),o.on("request",Salla.infiniteScroll.event.request),o.on("load",Salla.infiniteScroll.event.load),o.on("append",Salla.infiniteScroll.event.append),o.on("error",Salla.infiniteScroll.event.error),o.on("last",Salla.infiniteScroll.event.last),o.on("history",Salla.infiniteScroll.event.history),this.instances.push(o),o}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage();}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy();}}(void 0,salla.event.infiniteScroll),N$3.api=new class extends B{constructor(){super(),this.auth=new D,this.cart=new m,this.loyalty=new f,this.order=new F,this.rating=new A,this.product=new v,this.profile=new y,this.comment=new C,this.currency=new S,this.document=new w,this.wishlist=new E,this.scope=new b,this.booking=new _,this.landing=new k,this.notifications=new x,this.component=new P,this.advertisement=new I,this.navigation=new q,this.metadata=new T;}beaconRequest(e,t={}){var a;if(null==(a=window.navigator)||!a.sendBeacon)return fetch(e,t);const r="string"==typeof(null==t?void 0:t.body)?null==t?void 0:t.body:JSON.stringify((null==t?void 0:t.body)||{}),s=new Blob([r],{type:"application/json"});return Salla.log(`Beacon payload size: ${s.size} bytes (~${(s.size/1024).toFixed(2)} KB)`),navigator.sendBeacon(e,s),Promise.resolve(new Response('{"status":"sent_via_beacon"}',{status:200,headers:{"Content-Type":"application/json"}}))}},N$3.sso=new class{constructor(){Salla.onReady(()=>this.init());}init(){var e;if(salla.config.get("store.features",[]).includes("sso-login")){if(window.location.hostname.includes("salla"))return salla.log("SSO is not supported yet for stores without custom domain.");salla.auth.event.onLoggedOut(()=>new Promise(e=>{const t=document.createElement("iframe");t.style.display="none",t.src=salla.url.get("sso/logout"),document.body.appendChild(t),t.onload=()=>{document.body.removeChild(t),e();};})),null==(e=document.querySelector("salla-login-modal"))||e.remove(),Salla.event.removeAllListeners("login::open"),Salla.event.prependListener("login::open",()=>this.redirect()),window.addEventListener("mini-checkout::before-init",e=>{Salla.config.isUser()||(e.preventDefault(),this.redirect());});}}redirect(){const e=window.location.pathname+window.location.search,t=`${window.location.origin}/sso/login?intended_to=${encodeURIComponent(e)}`;return console.log("Redirecting to:",t),window.location.href=t,true}},N$3.intend=new class{constructor(){Salla.onReady(()=>this.init());}init(){if(Salla.config.isUser())return;const e=new URLSearchParams(window.location.search);if(e.has("intended_to"))try{const t=new URL(e.get("intended_to"));if(t.hostname!==window.location.hostname)return;return this.handleAfterLoginEvent(t)}catch(e){return void console.warn("Invalid URL provided in intended_to parameter")}}handleAfterLoginEvent(e){let t="intend::user.logged.in";Salla.event.on(t,()=>window.location=e),Salla.api.auth.setAfterLoginEvent(t),Salla.api.auth.setCanRedirect(false),Salla.event.on("salla-login::ready",()=>Salla.event.emit("login::open",{withoutReload:true}));}},N$3.hooks=new class{constructor(){this._store=new Map,this._whitelist=new Map([["salla-add-product-button",new Set(["validate","componentDidLoad"])],["salla-product-options",new Set(["componentDidLoad"])],["salla-products-list",new Set(["componentDidLoad"])],["salla-products-slider",new Set(["componentDidLoad"])],["salla-hook",new Set(["componentDidLoad"])],["salla-scopes",new Set(["componentDidLoad"])]]),this._themeSlots=["head","head:start","head:end","body:start","body:end","product:index.items.start","product:index.items.end","product:single.description.start","product:single.description","product:single.description.end","product:single.form.start","product:single.form.end","blog:index.items.start","blog:index.items.end","blog:single.items.start","blog:single.items.end","brands:index.items.start","brands:index.items.end","brands:single.details.start","brands:single.details.end","brands:single.items.start","brands:single.items.end","cart:items.start","cart:items.end","cart:summary.start","cart:summary.end","cart:submit.start","cart:submit.end","customer:notifications.items.start","customer:notifications.items.end","customer:orders.index.items.start","customer:orders.index.items.end","customer:orders.single.details.start","customer:orders.single.details.end","customer:wishlist.items.start","customer:wishlist.items.end","customer:profile.form.start","customer:profile.form.fields.start","customer:profile.form.fields.end","customer:profile.form.submit.start","customer:profile.form.submit.end","customer:profile.form.end","thank-you:start","thank-you:items.start","thank-you:items.end","thank-you:end"];const e=Salla.config.get("page.slug");e&&(this._themeSlots.push(e+":start"),this._themeSlots.push(e+":end")),Salla.onReady(()=>{const e=Salla.config.get("page.slug");e&&(this._themeSlots.includes(e+":start")||this._themeSlots.push(e+":start"),this._themeSlots.includes(e+":end")||this._themeSlots.push(e+":end"));}),this._componentHistory=new Map;}renderAutoComponents(e){Array.isArray(e)&&0!==e.length&&e.forEach(({hook:e,tag:t,canRender:a})=>{a&&!a()||this.mount(e,document.createElement(t));});}registerHook(e,t,a,r={}){if(!this._isAllowed(e,t))return console.warn(`[Hooks] Hook "${e}:${t}" is not allowed`),()=>{};const s=0|r.priority,i=!!r.once,n=this._ensureTag(e),o=n.get(t)||[];return o.push({cb:a,p:s,once:i}),o.sort((e,t)=>t.p-e.p),n.set(t,o),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),()=>this.removeHook(e,t,a)}registerHookOnce(e,t,a,r={}){return this.registerHook(e,t,a,h$1({},r,{once:true}))}async call(e,t,a){const r=this._store.get(e);if(!r)return;const s=r.get(t);if(s&&0!==s.length)for(const r of [...s]){try{await r.cb(a);}catch(a){console.warn(`[Hooks] "${e}:${t}" callback failed:`,a);}r.once&&this.removeHook(e,t,r.cb);}}removeHook(e,t,a){const r=this._store.get(e);if(!r)return false;if(!r.has(t))return false;if(!a)return r.delete(t),0===r.size&&this._store.delete(e),true;const s=r.get(t),i=s.findIndex(e=>e.cb===a);return i>-1&&(s.splice(i,1),0===s.length&&r.delete(t),0===r.size&&this._store.delete(e),true)}clear(e){e?this._store.delete(e):this._store.clear();}get(e,t){var a;const r=this._store.get(e);return r&&(null==(a=r.get(t))?void 0:a.map(e=>e.cb))||[]}_ensureTag(e){let t=this._store.get(e);return t||(t=new Map,this._store.set(e,t)),t}_isAllowed(e,t){const a=this._whitelist.get(e);return a?!!a.has(t)||(console.warn(`[Hooks] Hook "${t}" is not allowed for tag "${e}"`),false):(console.warn(`[Hooks] Tag "${e}" is not in the whitelist`),false)}registerComponent(e,t){this._componentHistory.has(e)||this._componentHistory.set(e,new Set);const a=this._componentHistory.get(e);if(!a.has(t))return a.add(t),this.call(e,"componentDidLoad",t)}async _callForLoadedComponents(e,t){const a=this._componentHistory.get(e);if(a&&0!==a.size)for(const r of a)try{await t(r);}catch(t){console.warn(`[Hooks] "${e.replace(/[^a-zA-Z0-9-_]/g,"")}:componentDidLoad" callback failed:`,t);}}mount(e,t){return this._themeSlots.includes(e)?new Promise(a=>{this.registerHook("salla-hook","componentDidLoad",r=>{r.name===e&&(r.mount(t),a(t));});}):(console.warn(`[Hooks] Hook "${e}" is not allowed`),Promise.reject(t))}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing","metadata"].forEach(t=>N$3[t]=new c(N$3.api[t],N$3.event[t])),N$3.call=t=>{let a=N$3,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},N$3.analytics=new class{constructor(){this.history=[],this.customTrackers=[],this.context={},this._anonymousId=null,this._sessionId=null,this._jitsuConfig=null,this.mappedEvents={"wishlist::added":"Product Added to Wishlist","wishlist::removed":"Product Removed from Wishlist","salla-products-list::products.fetched":["Product List Viewed","Product List Filtered"],"auth::registered":"Signed Up","auth::logged.in":"Signed In","auth::logged.out":"Signed Out","share-element":"Product Shared","promotion::viewed":"Promotion Viewed","promotion::clicked":"Promotion Clicked","salla::offer.promotion.viewed":"Promotion Viewed","salla::offer.promotion.clicked":"Promotion Clicked","cart::coupon.added":"Coupon Applied","cart::coupon.deleted":"Coupon Removed","cart::coupon.addition.failed":"Coupon Denied","profile::updated":"User Profile Updated","cart::updated":"Cart Updated","scope::changed":"Market Selected","order::order.created":"Product Reordered"},Salla.event.onAny((e,t)=>{try{if(Object.keys(this.mappedEvents).includes(e)){const a=this.mappedEvents[e];return void(Array.isArray(a)?a:[a]).forEach(e=>Salla.event.emit(e,t))}if(!Salla.config.get("jitsu.events",[]).includes(e))return;const a=H.transform(e,t);a&&this.track(a.event,a.properties);}catch(e){Salla.log("Error in analytics event handling:",e);}}),Salla.event.on("salla-cookies-bar::accepted",()=>this.setConsent("accepted")),Salla.event.on("salla-cookies-bar::rejected",()=>this.setConsent("rejected")),Salla.event.on("auth::logged.out",()=>this.clearSessionId()),Salla.event.on("twilight::before.ready",e=>{var t,a,r,s,n,o,l;this.debugAnalytics=jitsuAnalytics({host:"https://st.salla.dev",writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p"});const{host:u,key:c}=(null==e?void 0:e.jitsu)||{};if(this.jitsuAnalytics=null,!u||!c)return void salla.log("Jitsu configuration is missing. Analytics will not be tracked.");H.registerEvents(),this._jitsuConfig=h$1({host:this.getAnalyticsHost(e),writeKey:c,cookieCapture:Object.fromEntries(Salla.cookie.getCookieByPrefix("sa_").map(e=>[e,e]))},Salla.helpers.isIframe()&&{fetch:(e,t)=>this.customFetch(e,t)});const d=this.getConsentPolicies();var p;(this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,d)),e.jitsu.anonymous_id&&this.jitsuAnalytics.setAnonymousId(e.jitsu.anonymous_id),this._anonymousId=(null==(t=this.jitsuAnalytics)||null==(t=t.user())?void 0:t.anonymousId)||null,e.jitsu.session_id&&this.setContext("session_id",e.jitsu.session_id),this._sessionId=null==(a=this.jitsuAnalytics)?void 0:a.getContextProperty("session_id"),this.setContext("store_id",null==(r=e.store)?void 0:r.id),this.setContext("version",null==(s=e.jitsu)?void 0:s.version),this.setContext("library",{twilight:Salla.versions}),null!=(n=e.jitsu)&&null!=(n=n.context)&&n.extra&&this.setExtraContext(e.jitsu.context.extra),null!=(o=e.store)&&null!=(o=o.scope)&&o.id)&&this.setContext("scope",null==(p=e.store)?void 0:p.scope);"user"===(null==e||null==(l=e.user)?void 0:l.type)&&this.setContext("traits",this.getFormattedUser(e.user)),this.registerTracker({name:"DefaultSallaTracker",track:(e,t)=>this.jitsuAnalytics.track(e,t),page:e=>this.jitsuAnalytics.page(e)});}),Salla.onReady(()=>{var e;this.initSessionId();const t={name:Salla.config.get("page.slug",""),id:null==(e=Salla.config.get("page.id",""))?void 0:e.toString()};this.setContext("page",t),Salla.config.set("jitsu.anonymous_id",this._anonymousId),Salla.config.set("jitsu.session_id",this._sessionId),this.page(t);});}setExtraContext(e){var t;null!=e&&null!=(t=e.headers)&&t["s-app-os"]&&(this.setContext("app",{version:e.headers["s-app-os-version"],app_release_tag:e.headers["s-app-version"],platform:e.headers["s-app-os"].toLowerCase()}),delete e.headers["s-app-os"],delete e.headers["s-app-os-version"],delete e.headers["s-app-version"],delete e.headers["s-source"]),this.setContext("system",e);}getAnalyticsHost(e){var t;const a="https://salla.cloud/_app/e";var r,s;if(Salla.helpers.isIframe())return null!=(r=null==(s=e.jitsu)?void 0:s.host)?r:a;if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;const i=e.store.url;try{let e="";const t=i;if(/https:\/\/demostore\.salla\.sa/.test(t)){const e=t.match(/demostore\.salla\.sa\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/);if(e&&e[2]){const a=e[2];return `${new URL(t).origin}/${a}/_app/e`}return a}const r=/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/,s=t.match(r);if(s){const r=s[3];if(!r||0===r.trim().length||"ar"===r||"en"===r)return Salla.log("Error: invalid or empty store name in salla.sa URL"),a;e=`${new URL(t).origin}/${r}`;}else {e=new URL(t).origin;}return `${e}/_app/e`}catch(e){return Salla.log("Error getting store url, forwarding to salla.cloud:",e),a}}setContext(e,t){var a,r;null==(a=this.jitsuAnalytics)||a.setContextProperty(e,t),null==(r=this.debugAnalytics)||r.setContextProperty(e,t),this.context[e]=t;}setAppContext(e,t){if(!this.jitsuAnalytics)return void Salla.log("setAppContext: Analytics not initialized yet");if(!e||"string"!=typeof e)return void Salla.log("setAppContext: appId must be a non-empty string");if(!t||"object"!=typeof t)return void Salla.log("setAppContext: payload must be an object");const a=this.context.apps_context||{};a[e]=h$1({},a[e],t),this.setContext("apps_context",a);}withAppScope(e,t){if(!e||"string"!=typeof e)return void Salla.log("withAppScope: appId must be a non-empty string");if("function"!=typeof t)return void Salla.log("withAppScope: callback must be a function");const a=this.context.apps_context?h$1({},this.context.apps_context):void 0,r=this,s={appId:e,setContext(t,a){r.setAppContext(e,{[t]:a});}};try{t(s);}finally{setTimeout(()=>{a?r.setContext("apps_context",a):r.setContext("apps_context",void 0);},0);}}customFetch(e,t){return fetch(e,h$1({},t,{keepalive:true}))}track(e,t={}){t=this.finalPayload(t),this.history.push({action:"track",eventName:e,payload:t}),this.pushEventToCustomTrackers("track",e,t);}log(e,t={}){var a;return null==(a=this.debugAnalytics)?void 0:a.track(e,t).catch(e=>(Salla.log("Error tracking event:",e),Promise.reject(e)))}page(e={}){var t,a;(e=this.finalPayload(e)).id=null==(t=e.id||Salla.config.get("page.id",""))?void 0:t.toString(),e.name=e.name||Salla.config.get("page.slug"),e.keywords=e.keywords||(null==(a=document.querySelector("meta[name=keywords]"))?void 0:a.content),e.referrer=e.referrer||document.referrer,this.history.push({action:"page",payload:e}),this.pushEventToCustomTrackers("page",e);}finalPayload(e={}){return this.attachRealtimeContext(),h$1({},{},e)}attachRealtimeContext(){try{const e=["user.id","cart.id","cart.user_id","cart.count","cart.summary.count","scope.id","branch-choosed-before"].reduce((e,t)=>{const a=Salla.storage.get(t);return a&&(e[t.replace(".","_")]=a),e},{});Object.keys(e).length>0&&this.setContext("localStorage",e);}catch(e){Salla.analytics.log("attachRealtimeContext",{error:e.message}),Salla.log("Error attaching realtime context:",e);}const e=Salla.storage.getWithTTL("s-utms");if(!e)return;const{"s-utm-campaign":t,"s-utm-source":a,"s-utm-medium":r,"s-utm-term":s,"s-utm-content":i,"s-utm-referrer":n}=e;this.setContext("campaign",{name:t,source:a,medium:r,term:s,content:i,referrer:n});}registerTracker(e){"object"==typeof e?"string"==typeof e.name&&e.name?"function"==typeof e.track?"function"==typeof e.page?this.customTrackers.find(t=>t.name===e.name)?Salla.log("tracker with the same name already exists!"):(this.customTrackers.push(e),this.history.forEach(t=>"track"===t.action?e.track(t.eventName,t.payload):"page"===t.action?e.page(t.payload):void 0)):Salla.log("tracker.page most be a function!"):Salla.log("tracker.track most be a function!"):Salla.log("tracker.name most be a string!"):Salla.log('tracker most be an object {name:"tracker name", track: callback, page: callback}!');}pushEventToCustomTrackers(e,t,a={}){const r="page"===e?[t]:[t,a];return Promise.allSettled(this.customTrackers.map(t=>this.pushEventToCustomTracker(t[e],r))).then(t=>t.filter(e=>"rejected"===e.status).map(t=>Salla.log("Error on customTracker to send "+e,t)))}pushEventToCustomTracker(e,t){try{const a=e(...t);return Promise.resolve(a).catch(e=>Promise.reject(e))}catch(e){return Promise.reject(e)}}getConsentState(){return Salla.storage.get("cookies-consent","unknown")}getConsentPolicies(e=null){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return {};const a="accepted"===(e=e||this.getConsentState());return {privacy:{dontSend:false,disableUserIds:!a,ipPolicy:a?"keep":"remove"}}}setConsent(e){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return;if(!["accepted","rejected"].includes(e))return;const a=this.getConsentState();if(this._jitsuConfig&&this.jitsuAnalytics&&a!==e)try{var r;const t=this.getConsentPolicies(e);this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,t)),this._anonymousId=(null==(r=this.jitsuAnalytics)||null==(r=r.user())?void 0:r.anonymousId)||null,Salla.config.set("jitsu.anonymous_id",this._anonymousId),Object.entries(this.context).forEach(([e,t])=>{this.jitsuAnalytics.setContextProperty(e,t);});}catch(e){Salla.log("Error re-initializing Jitsu on consent change:",e);}}getFormattedUser(e){return e.phone=e.mobile,e.country=e.country_code,e.language=e.language_code,e.currency=e.currency_code,e}generateSessionId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)})}initSessionId(){this._sessionId=this._sessionId||Salla.storage.getWithTTL(V)||this.generateSessionId(),Salla.storage.setWithTTL(V,this._sessionId,30),this.setContext("session_id",this._sessionId);}clearSessionId(){this._sessionId=null,Salla.storage.setWithTTL(V,null,0),this.setContext("session_id",null);}getAnonymousId(){try{if(this._anonymousId)return this._anonymousId;if(this.jitsuAnalytics){var e;const t=null==(e=this.jitsuAnalytics.user())?void 0:e.anonymousId;if(t)return this._anonymousId=t,t}return null}catch(e){return Salla.log("Error getting anonymous ID from Jitsu:",e),null}}},N$3.init=e=>new O(e),new class{constructor(e={}){this.config=h$1({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=false,Salla.onReady(()=>this.init());}normalizeUrl(e){try{return new URL(e,location.href)}catch(e){return null}}shouldIgnoreUrl(e){if(!e)return false;const t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some(e=>a.startsWith(e)))return true;try{const e=new URL(t,location.href).hostname.toLowerCase();return ["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some(t=>e===t||e.endsWith("."+t))}catch(e){return false}}isWhitelisted(e){if(!e)return false;const t=e.hostname.toLowerCase();for(const e of this.config.WHITELIST){const a=String(e||"").toLowerCase().trim();if(a&&(t===a||t.endsWith("."+a)))return true}return false}emit(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e);}catch(e){}}catch(e){}}logRedirect(e,t,a){if(this.shouldIgnoreUrl(t))return;const r=this.normalizeUrl(t),s=this.normalizeUrl(location.href),i=this.isWhitelisted(r),n={redirect_source:e,redirect_from:s?s.href:String(location.href),redirect_to:r?r.href:String(t),redirect_host:r?r.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(n);}hookHistoryAPIs(){["pushState","replaceState"].forEach(e=>{try{const t=history[e];"function"==typeof t&&(this.originalMethods[`history.${e}`]=t,history[e]=(...a)=>{try{var r;this.logRedirect(e,null!=(r=a[2])?r:location.href);}catch(e){}return t.apply(history,a)});}catch(e){}}),window.addEventListener("popstate",()=>{this.logRedirect("popstate",location.href);}),window.addEventListener("hashchange",()=>{this.logRedirect("hashchange",location.href);});}hookLocationMethods(){try{const e=location.assign.bind(location);this.originalMethods["location.assign"]=e,location.assign=t=>(this.logRedirect("location.assign",t,{stack:(new Error).stack}),e(t));}catch(e){}try{const e=location.replace.bind(location);this.originalMethods["location.replace"]=e,location.replace=t=>(this.logRedirect("location.replace",t,{stack:(new Error).stack}),e(t));}catch(e){}}hookWindowOpen(){try{const e=window.open;this.originalMethods["window.open"]=e,window.open=(t,...a)=>(t&&this.logRedirect("window.open",t,{stack:(new Error).stack}),e.apply(window,[t,...a]));}catch(e){}}setupEventListeners(){this.handleLinkClick=e=>{const t=e.target&&e.target.closest?e.target.closest("a[href]"):null;if(!t)return;const a=t.getAttribute("href");if(!a||a.startsWith("#"))return;if(this.shouldIgnoreUrl(a))return;const r=t.getAttribute("target")||"_self";setTimeout(()=>{this.logRedirect("link-click",a,{target:r});},0);},document.addEventListener("click",this.handleLinkClick,true),this.handleFormSubmit=e=>{const t=e.target,a=t&&t.getAttribute&&t.getAttribute("action")||location.href,r=(t&&t.method?String(t.method):"GET").toUpperCase();this.logRedirect("form-submit",a,{method:r});},document.addEventListener("submit",this.handleFormSubmit,true);}setupPerformanceObserver(){try{this.performanceObserver=new PerformanceObserver(e=>{for(const t of e.getEntries())"navigation"===t.entryType&&this.logRedirect("performance-navigation",location.href,{type:t.type,redirectCount:t.redirectCount});}),this.performanceObserver.observe({type:"navigation",buffered:true});}catch(e){}}init(){if(this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug")))return;if(this.isInitialized)return;const e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=true;}destroy(){this.isInitialized&&(Object.keys(this.originalMethods).forEach(e=>{const[t,a]=e.split(".");"history"===t&&this.originalMethods[e]?history[a]=this.originalMethods[e]:"location"===t&&this.originalMethods[e]?location[a]=this.originalMethods[e]:"window"===t&&"open"===a&&this.originalMethods[e]&&(window.open=this.originalMethods[e]);}),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,true),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,true),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=false);}},salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",e=>{let t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t);}),N$3.success=N$3.notify.success,N$3.error=N$3.notify.error,window.dispatchEvent(new CustomEvent("salla::created"));
12315
12704
 
12316
12705
  var lazyload_min$1 = {exports: {}};
12317
12706