@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
@@ -4021,7 +4021,7 @@ var a$4 = /*#__PURE__*/_mergeNamespaces({
4021
4021
  default: memoryStorage
4022
4022
  }, [memoryStorageExports]);
4023
4023
 
4024
- 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;
4024
+ 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;
4025
4025
 
4026
4026
  var js = {exports: {}};
4027
4027
 
@@ -6269,7 +6269,7 @@ function requireLang () {
6269
6269
  var langExports = requireLang();
6270
6270
  var a$3 = /*@__PURE__*/getDefaultExportFromCjs(langExports);
6271
6271
 
6272
- /*! Axios v1.13.3 Copyright (c) 2026 Matt Zabriskie and contributors */
6272
+ /*! Axios v1.14.0 Copyright (c) 2026 Matt Zabriskie and contributors */
6273
6273
 
6274
6274
  var axios_1;
6275
6275
  var hasRequiredAxios;
@@ -6293,30 +6293,30 @@ function requireAxios () {
6293
6293
 
6294
6294
  // utils is a library of generic helper functions non-specific to axios
6295
6295
 
6296
- const {toString} = Object.prototype;
6297
- const {getPrototypeOf} = Object;
6298
- const {iterator, toStringTag} = Symbol;
6296
+ const { toString } = Object.prototype;
6297
+ const { getPrototypeOf } = Object;
6298
+ const { iterator, toStringTag } = Symbol;
6299
6299
 
6300
- const kindOf = (cache => thing => {
6301
- const str = toString.call(thing);
6302
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
6300
+ const kindOf = ((cache) => (thing) => {
6301
+ const str = toString.call(thing);
6302
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
6303
6303
  })(Object.create(null));
6304
6304
 
6305
6305
  const kindOfTest = (type) => {
6306
6306
  type = type.toLowerCase();
6307
- return (thing) => kindOf(thing) === type
6307
+ return (thing) => kindOf(thing) === type;
6308
6308
  };
6309
6309
 
6310
- const typeOfTest = type => thing => typeof thing === type;
6310
+ const typeOfTest = (type) => (thing) => typeof thing === type;
6311
6311
 
6312
6312
  /**
6313
- * Determine if a value is an Array
6313
+ * Determine if a value is a non-null object
6314
6314
  *
6315
6315
  * @param {Object} val The value to test
6316
6316
  *
6317
6317
  * @returns {boolean} True if value is an Array, otherwise false
6318
6318
  */
6319
- const {isArray} = Array;
6319
+ const { isArray } = Array;
6320
6320
 
6321
6321
  /**
6322
6322
  * Determine if a value is undefined
@@ -6335,8 +6335,14 @@ function requireAxios () {
6335
6335
  * @returns {boolean} True if value is a Buffer, otherwise false
6336
6336
  */
6337
6337
  function isBuffer(val) {
6338
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
6339
- && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
6338
+ return (
6339
+ val !== null &&
6340
+ !isUndefined(val) &&
6341
+ val.constructor !== null &&
6342
+ !isUndefined(val.constructor) &&
6343
+ isFunction$1(val.constructor.isBuffer) &&
6344
+ val.constructor.isBuffer(val)
6345
+ );
6340
6346
  }
6341
6347
 
6342
6348
  /**
@@ -6348,7 +6354,6 @@ function requireAxios () {
6348
6354
  */
6349
6355
  const isArrayBuffer = kindOfTest('ArrayBuffer');
6350
6356
 
6351
-
6352
6357
  /**
6353
6358
  * Determine if a value is a view on an ArrayBuffer
6354
6359
  *
@@ -6358,10 +6363,10 @@ function requireAxios () {
6358
6363
  */
6359
6364
  function isArrayBufferView(val) {
6360
6365
  let result;
6361
- if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
6366
+ if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
6362
6367
  result = ArrayBuffer.isView(val);
6363
6368
  } else {
6364
- result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
6369
+ result = val && val.buffer && isArrayBuffer(val.buffer);
6365
6370
  }
6366
6371
  return result;
6367
6372
  }
@@ -6407,7 +6412,7 @@ function requireAxios () {
6407
6412
  * @param {*} thing The value to test
6408
6413
  * @returns {boolean} True if value is a Boolean, otherwise false
6409
6414
  */
6410
- const isBoolean = thing => thing === true || thing === false;
6415
+ const isBoolean = (thing) => thing === true || thing === false;
6411
6416
 
6412
6417
  /**
6413
6418
  * Determine if a value is a plain Object
@@ -6422,7 +6427,13 @@ function requireAxios () {
6422
6427
  }
6423
6428
 
6424
6429
  const prototype = getPrototypeOf(val);
6425
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val);
6430
+ return (
6431
+ (prototype === null ||
6432
+ prototype === Object.prototype ||
6433
+ Object.getPrototypeOf(prototype) === null) &&
6434
+ !(toStringTag in val) &&
6435
+ !(iterator in val)
6436
+ );
6426
6437
  };
6427
6438
 
6428
6439
  /**
@@ -6464,6 +6475,31 @@ function requireAxios () {
6464
6475
  */
6465
6476
  const isFile = kindOfTest('File');
6466
6477
 
6478
+ /**
6479
+ * Determine if a value is a React Native Blob
6480
+ * React Native "blob": an object with a `uri` attribute. Optionally, it can
6481
+ * also have a `name` and `type` attribute to specify filename and content type
6482
+ *
6483
+ * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
6484
+ *
6485
+ * @param {*} value The value to test
6486
+ *
6487
+ * @returns {boolean} True if value is a React Native Blob, otherwise false
6488
+ */
6489
+ const isReactNativeBlob = (value) => {
6490
+ return !!(value && typeof value.uri !== 'undefined');
6491
+ };
6492
+
6493
+ /**
6494
+ * Determine if environment is React Native
6495
+ * ReactNative `FormData` has a non-standard `getParts()` method
6496
+ *
6497
+ * @param {*} formData The formData to test
6498
+ *
6499
+ * @returns {boolean} True if environment is React Native, otherwise false
6500
+ */
6501
+ const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
6502
+
6467
6503
  /**
6468
6504
  * Determine if a value is a Blob
6469
6505
  *
@@ -6498,17 +6534,28 @@ function requireAxios () {
6498
6534
  *
6499
6535
  * @returns {boolean} True if value is an FormData, otherwise false
6500
6536
  */
6537
+ function getGlobal() {
6538
+ if (typeof globalThis !== 'undefined') return globalThis;
6539
+ if (typeof self !== 'undefined') return self;
6540
+ if (typeof window !== 'undefined') return window;
6541
+ if (typeof commonjsGlobal !== 'undefined') return commonjsGlobal;
6542
+ return {};
6543
+ }
6544
+
6545
+ const G = getGlobal();
6546
+ const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
6547
+
6501
6548
  const isFormData = (thing) => {
6502
6549
  let kind;
6503
6550
  return thing && (
6504
- (typeof FormData === 'function' && thing instanceof FormData) || (
6551
+ (FormDataCtor && thing instanceof FormDataCtor) || (
6505
6552
  isFunction$1(thing.append) && (
6506
6553
  (kind = kindOf(thing)) === 'formdata' ||
6507
6554
  // detect form-data instance
6508
6555
  (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
6509
6556
  )
6510
6557
  )
6511
- )
6558
+ );
6512
6559
  };
6513
6560
 
6514
6561
  /**
@@ -6520,7 +6567,12 @@ function requireAxios () {
6520
6567
  */
6521
6568
  const isURLSearchParams = kindOfTest('URLSearchParams');
6522
6569
 
6523
- const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
6570
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
6571
+ 'ReadableStream',
6572
+ 'Request',
6573
+ 'Response',
6574
+ 'Headers',
6575
+ ].map(kindOfTest);
6524
6576
 
6525
6577
  /**
6526
6578
  * Trim excess whitespace off the beginning and end of a string
@@ -6529,9 +6581,9 @@ function requireAxios () {
6529
6581
  *
6530
6582
  * @returns {String} The String freed of excess whitespace
6531
6583
  */
6532
- const trim = (str) => str.trim ?
6533
- str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
6534
-
6584
+ const trim = (str) => {
6585
+ return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
6586
+ };
6535
6587
  /**
6536
6588
  * Iterate over an Array or an Object invoking a function for each item.
6537
6589
  *
@@ -6548,7 +6600,7 @@ function requireAxios () {
6548
6600
  * @param {Boolean} [options.allOwnKeys = false]
6549
6601
  * @returns {any}
6550
6602
  */
6551
- function forEach(obj, fn, {allOwnKeys = false} = {}) {
6603
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
6552
6604
  // Don't bother if no value provided
6553
6605
  if (obj === null || typeof obj === 'undefined') {
6554
6606
  return;
@@ -6586,8 +6638,16 @@ function requireAxios () {
6586
6638
  }
6587
6639
  }
6588
6640
 
6641
+ /**
6642
+ * Finds a key in an object, case-insensitive, returning the actual key name.
6643
+ * Returns null if the object is a Buffer or if no match is found.
6644
+ *
6645
+ * @param {Object} obj - The object to search.
6646
+ * @param {string} key - The key to find (case-insensitive).
6647
+ * @returns {?string} The actual key name if found, otherwise null.
6648
+ */
6589
6649
  function findKey(obj, key) {
6590
- if (isBuffer(obj)){
6650
+ if (isBuffer(obj)) {
6591
6651
  return null;
6592
6652
  }
6593
6653
 
@@ -6606,8 +6666,8 @@ function requireAxios () {
6606
6666
 
6607
6667
  const _global = (() => {
6608
6668
  /*eslint no-undef:0*/
6609
- if (typeof globalThis !== "undefined") return globalThis;
6610
- return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : commonjsGlobal)
6669
+ if (typeof globalThis !== 'undefined') return globalThis;
6670
+ return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : commonjsGlobal;
6611
6671
  })();
6612
6672
 
6613
6673
  const isContextDefined = (context) => !isUndefined(context) && context !== _global;
@@ -6631,10 +6691,15 @@ function requireAxios () {
6631
6691
  * @returns {Object} Result of all merge properties
6632
6692
  */
6633
6693
  function merge(/* obj1, obj2, obj3, ... */) {
6634
- const {caseless, skipUndefined} = isContextDefined(this) && this || {};
6694
+ const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
6635
6695
  const result = {};
6636
6696
  const assignValue = (val, key) => {
6637
- const targetKey = caseless && findKey(result, key) || key;
6697
+ // Skip dangerous property names to prevent prototype pollution
6698
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
6699
+ return;
6700
+ }
6701
+
6702
+ const targetKey = (caseless && findKey(result, key)) || key;
6638
6703
  if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
6639
6704
  result[targetKey] = merge(result[targetKey], val);
6640
6705
  } else if (isPlainObject(val)) {
@@ -6663,24 +6728,28 @@ function requireAxios () {
6663
6728
  * @param {Boolean} [options.allOwnKeys]
6664
6729
  * @returns {Object} The resulting value of object a
6665
6730
  */
6666
- const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
6667
- forEach(b, (val, key) => {
6668
- if (thisArg && isFunction$1(val)) {
6669
- Object.defineProperty(a, key, {
6670
- value: bind(val, thisArg),
6671
- writable: true,
6672
- enumerable: true,
6673
- configurable: true
6674
- });
6675
- } else {
6676
- Object.defineProperty(a, key, {
6677
- value: val,
6678
- writable: true,
6679
- enumerable: true,
6680
- configurable: true
6681
- });
6682
- }
6683
- }, {allOwnKeys});
6731
+ const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
6732
+ forEach(
6733
+ b,
6734
+ (val, key) => {
6735
+ if (thisArg && isFunction$1(val)) {
6736
+ Object.defineProperty(a, key, {
6737
+ value: bind(val, thisArg),
6738
+ writable: true,
6739
+ enumerable: true,
6740
+ configurable: true,
6741
+ });
6742
+ } else {
6743
+ Object.defineProperty(a, key, {
6744
+ value: val,
6745
+ writable: true,
6746
+ enumerable: true,
6747
+ configurable: true,
6748
+ });
6749
+ }
6750
+ },
6751
+ { allOwnKeys }
6752
+ );
6684
6753
  return a;
6685
6754
  };
6686
6755
 
@@ -6692,7 +6761,7 @@ function requireAxios () {
6692
6761
  * @returns {string} content value without BOM
6693
6762
  */
6694
6763
  const stripBOM = (content) => {
6695
- if (content.charCodeAt(0) === 0xFEFF) {
6764
+ if (content.charCodeAt(0) === 0xfeff) {
6696
6765
  content = content.slice(1);
6697
6766
  }
6698
6767
  return content;
@@ -6713,10 +6782,10 @@ function requireAxios () {
6713
6782
  value: constructor,
6714
6783
  writable: true,
6715
6784
  enumerable: false,
6716
- configurable: true
6785
+ configurable: true,
6717
6786
  });
6718
6787
  Object.defineProperty(constructor, 'super', {
6719
- value: superConstructor.prototype
6788
+ value: superConstructor.prototype,
6720
6789
  });
6721
6790
  props && Object.assign(constructor.prototype, props);
6722
6791
  };
@@ -6775,7 +6844,6 @@ function requireAxios () {
6775
6844
  return lastIndex !== -1 && lastIndex === position;
6776
6845
  };
6777
6846
 
6778
-
6779
6847
  /**
6780
6848
  * Returns new array from array like object or null if failed
6781
6849
  *
@@ -6804,9 +6872,9 @@ function requireAxios () {
6804
6872
  * @returns {Array}
6805
6873
  */
6806
6874
  // eslint-disable-next-line func-names
6807
- const isTypedArray = (TypedArray => {
6875
+ const isTypedArray = ((TypedArray) => {
6808
6876
  // eslint-disable-next-line func-names
6809
- return thing => {
6877
+ return (thing) => {
6810
6878
  return TypedArray && thing instanceof TypedArray;
6811
6879
  };
6812
6880
  })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
@@ -6854,16 +6922,18 @@ function requireAxios () {
6854
6922
  /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
6855
6923
  const isHTMLForm = kindOfTest('HTMLFormElement');
6856
6924
 
6857
- const toCamelCase = str => {
6858
- return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
6859
- function replacer(m, p1, p2) {
6860
- return p1.toUpperCase() + p2;
6861
- }
6862
- );
6925
+ const toCamelCase = (str) => {
6926
+ return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
6927
+ return p1.toUpperCase() + p2;
6928
+ });
6863
6929
  };
6864
6930
 
6865
6931
  /* Creating a function that will check if an object has a property. */
6866
- const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
6932
+ const hasOwnProperty = (
6933
+ ({ hasOwnProperty }) =>
6934
+ (obj, prop) =>
6935
+ hasOwnProperty.call(obj, prop)
6936
+ )(Object.prototype);
6867
6937
 
6868
6938
  /**
6869
6939
  * Determine if a value is a RegExp object
@@ -6913,17 +6983,25 @@ function requireAxios () {
6913
6983
 
6914
6984
  if (!descriptor.set) {
6915
6985
  descriptor.set = () => {
6916
- throw Error('Can not rewrite read-only method \'' + name + '\'');
6986
+ throw Error("Can not rewrite read-only method '" + name + "'");
6917
6987
  };
6918
6988
  }
6919
6989
  });
6920
6990
  };
6921
6991
 
6992
+ /**
6993
+ * Converts an array or a delimited string into an object set with values as keys and true as values.
6994
+ * Useful for fast membership checks.
6995
+ *
6996
+ * @param {Array|string} arrayOrString - The array or string to convert.
6997
+ * @param {string} delimiter - The delimiter to use if input is a string.
6998
+ * @returns {Object} An object with keys from the array or string, values set to true.
6999
+ */
6922
7000
  const toObjectSet = (arrayOrString, delimiter) => {
6923
7001
  const obj = {};
6924
7002
 
6925
7003
  const define = (arr) => {
6926
- arr.forEach(value => {
7004
+ arr.forEach((value) => {
6927
7005
  obj[value] = true;
6928
7006
  });
6929
7007
  };
@@ -6936,11 +7014,9 @@ function requireAxios () {
6936
7014
  const noop = () => {};
6937
7015
 
6938
7016
  const toFiniteNumber = (value, defaultValue) => {
6939
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
7017
+ return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
6940
7018
  };
6941
7019
 
6942
-
6943
-
6944
7020
  /**
6945
7021
  * If the thing is a FormData object, return true, otherwise return false.
6946
7022
  *
@@ -6949,14 +7025,24 @@ function requireAxios () {
6949
7025
  * @returns {boolean}
6950
7026
  */
6951
7027
  function isSpecCompliantForm(thing) {
6952
- return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
7028
+ return !!(
7029
+ thing &&
7030
+ isFunction$1(thing.append) &&
7031
+ thing[toStringTag] === 'FormData' &&
7032
+ thing[iterator]
7033
+ );
6953
7034
  }
6954
7035
 
7036
+ /**
7037
+ * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
7038
+ *
7039
+ * @param {Object} obj - The object to convert.
7040
+ * @returns {Object} The JSON-compatible object.
7041
+ */
6955
7042
  const toJSONObject = (obj) => {
6956
7043
  const stack = new Array(10);
6957
7044
 
6958
7045
  const visit = (source, i) => {
6959
-
6960
7046
  if (isObject(source)) {
6961
7047
  if (stack.indexOf(source) >= 0) {
6962
7048
  return;
@@ -6967,7 +7053,7 @@ function requireAxios () {
6967
7053
  return source;
6968
7054
  }
6969
7055
 
6970
- if(!('toJSON' in source)) {
7056
+ if (!('toJSON' in source)) {
6971
7057
  stack[i] = source;
6972
7058
  const target = isArray(source) ? [] : {};
6973
7059
 
@@ -6988,45 +7074,77 @@ function requireAxios () {
6988
7074
  return visit(obj, 0);
6989
7075
  };
6990
7076
 
7077
+ /**
7078
+ * Determines if a value is an async function.
7079
+ *
7080
+ * @param {*} thing - The value to test.
7081
+ * @returns {boolean} True if value is an async function, otherwise false.
7082
+ */
6991
7083
  const isAsyncFn = kindOfTest('AsyncFunction');
6992
7084
 
7085
+ /**
7086
+ * Determines if a value is thenable (has then and catch methods).
7087
+ *
7088
+ * @param {*} thing - The value to test.
7089
+ * @returns {boolean} True if value is thenable, otherwise false.
7090
+ */
6993
7091
  const isThenable = (thing) =>
6994
- thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
7092
+ thing &&
7093
+ (isObject(thing) || isFunction$1(thing)) &&
7094
+ isFunction$1(thing.then) &&
7095
+ isFunction$1(thing.catch);
6995
7096
 
6996
7097
  // original code
6997
7098
  // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
6998
7099
 
7100
+ /**
7101
+ * Provides a cross-platform setImmediate implementation.
7102
+ * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
7103
+ *
7104
+ * @param {boolean} setImmediateSupported - Whether setImmediate is supported.
7105
+ * @param {boolean} postMessageSupported - Whether postMessage is supported.
7106
+ * @returns {Function} A function to schedule a callback asynchronously.
7107
+ */
6999
7108
  const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
7000
7109
  if (setImmediateSupported) {
7001
7110
  return setImmediate;
7002
7111
  }
7003
7112
 
7004
- return postMessageSupported ? ((token, callbacks) => {
7005
- _global.addEventListener("message", ({source, data}) => {
7006
- if (source === _global && data === token) {
7007
- callbacks.length && callbacks.shift()();
7008
- }
7009
- }, false);
7113
+ return postMessageSupported
7114
+ ? ((token, callbacks) => {
7115
+ _global.addEventListener(
7116
+ 'message',
7117
+ ({ source, data }) => {
7118
+ if (source === _global && data === token) {
7119
+ callbacks.length && callbacks.shift()();
7120
+ }
7121
+ },
7122
+ false
7123
+ );
7010
7124
 
7011
- return (cb) => {
7012
- callbacks.push(cb);
7013
- _global.postMessage(token, "*");
7014
- }
7015
- })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
7016
- })(
7017
- typeof setImmediate === 'function',
7018
- isFunction$1(_global.postMessage)
7019
- );
7125
+ return (cb) => {
7126
+ callbacks.push(cb);
7127
+ _global.postMessage(token, '*');
7128
+ };
7129
+ })(`axios@${Math.random()}`, [])
7130
+ : (cb) => setTimeout(cb);
7131
+ })(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
7020
7132
 
7021
- const asap = typeof queueMicrotask !== 'undefined' ?
7022
- queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
7133
+ /**
7134
+ * Schedules a microtask or asynchronous callback as soon as possible.
7135
+ * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
7136
+ *
7137
+ * @type {Function}
7138
+ */
7139
+ const asap =
7140
+ typeof queueMicrotask !== 'undefined'
7141
+ ? queueMicrotask.bind(_global)
7142
+ : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
7023
7143
 
7024
7144
  // *********************
7025
7145
 
7026
-
7027
7146
  const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
7028
7147
 
7029
-
7030
7148
  var utils$1 = {
7031
7149
  isArray,
7032
7150
  isArrayBuffer,
@@ -7046,6 +7164,8 @@ function requireAxios () {
7046
7164
  isUndefined,
7047
7165
  isDate,
7048
7166
  isFile,
7167
+ isReactNativeBlob,
7168
+ isReactNative,
7049
7169
  isBlob,
7050
7170
  isRegExp,
7051
7171
  isFunction: isFunction$1,
@@ -7084,18 +7204,24 @@ function requireAxios () {
7084
7204
  isThenable,
7085
7205
  setImmediate: _setImmediate,
7086
7206
  asap,
7087
- isIterable
7207
+ isIterable,
7088
7208
  };
7089
7209
 
7090
7210
  class AxiosError extends Error {
7091
- static from(error, code, config, request, response, customProps) {
7092
- const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
7093
- axiosError.cause = error;
7094
- axiosError.name = error.name;
7095
- customProps && Object.assign(axiosError, customProps);
7096
- return axiosError;
7211
+ static from(error, code, config, request, response, customProps) {
7212
+ const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
7213
+ axiosError.cause = error;
7214
+ axiosError.name = error.name;
7215
+
7216
+ // Preserve status from the original error if not already set from response
7217
+ if (error.status != null && axiosError.status == null) {
7218
+ axiosError.status = error.status;
7097
7219
  }
7098
7220
 
7221
+ customProps && Object.assign(axiosError, customProps);
7222
+ return axiosError;
7223
+ }
7224
+
7099
7225
  /**
7100
7226
  * Create an Error with the specified message, config, error code, request and response.
7101
7227
  *
@@ -7108,37 +7234,48 @@ function requireAxios () {
7108
7234
  * @returns {Error} The created error.
7109
7235
  */
7110
7236
  constructor(message, code, config, request, response) {
7111
- super(message);
7112
- this.name = 'AxiosError';
7113
- this.isAxiosError = true;
7114
- code && (this.code = code);
7115
- config && (this.config = config);
7116
- request && (this.request = request);
7117
- if (response) {
7118
- this.response = response;
7119
- this.status = response.status;
7120
- }
7237
+ super(message);
7238
+
7239
+ // Make message enumerable to maintain backward compatibility
7240
+ // The native Error constructor sets message as non-enumerable,
7241
+ // but axios < v1.13.3 had it as enumerable
7242
+ Object.defineProperty(this, 'message', {
7243
+ value: message,
7244
+ enumerable: true,
7245
+ writable: true,
7246
+ configurable: true
7247
+ });
7248
+
7249
+ this.name = 'AxiosError';
7250
+ this.isAxiosError = true;
7251
+ code && (this.code = code);
7252
+ config && (this.config = config);
7253
+ request && (this.request = request);
7254
+ if (response) {
7255
+ this.response = response;
7256
+ this.status = response.status;
7257
+ }
7121
7258
  }
7122
7259
 
7123
- toJSON() {
7124
- return {
7125
- // Standard
7126
- message: this.message,
7127
- name: this.name,
7128
- // Microsoft
7129
- description: this.description,
7130
- number: this.number,
7131
- // Mozilla
7132
- fileName: this.fileName,
7133
- lineNumber: this.lineNumber,
7134
- columnNumber: this.columnNumber,
7135
- stack: this.stack,
7136
- // Axios
7137
- config: utils$1.toJSONObject(this.config),
7138
- code: this.code,
7139
- status: this.status,
7140
- };
7141
- }
7260
+ toJSON() {
7261
+ return {
7262
+ // Standard
7263
+ message: this.message,
7264
+ name: this.name,
7265
+ // Microsoft
7266
+ description: this.description,
7267
+ number: this.number,
7268
+ // Mozilla
7269
+ fileName: this.fileName,
7270
+ lineNumber: this.lineNumber,
7271
+ columnNumber: this.columnNumber,
7272
+ stack: this.stack,
7273
+ // Axios
7274
+ config: utils$1.toJSONObject(this.config),
7275
+ code: this.code,
7276
+ status: this.status,
7277
+ };
7278
+ }
7142
7279
  }
7143
7280
 
7144
7281
  // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
@@ -7155,8 +7292,6 @@ function requireAxios () {
7155
7292
  AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
7156
7293
  AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
7157
7294
 
7158
- var AxiosError$1 = AxiosError;
7159
-
7160
7295
  // eslint-disable-next-line strict
7161
7296
  var httpAdapter = null;
7162
7297
 
@@ -7193,11 +7328,14 @@ function requireAxios () {
7193
7328
  */
7194
7329
  function renderKey(path, key, dots) {
7195
7330
  if (!path) return key;
7196
- return path.concat(key).map(function each(token, i) {
7197
- // eslint-disable-next-line no-param-reassign
7198
- token = removeBrackets(token);
7199
- return !dots && i ? '[' + token + ']' : token;
7200
- }).join(dots ? '.' : '');
7331
+ return path
7332
+ .concat(key)
7333
+ .map(function each(token, i) {
7334
+ // eslint-disable-next-line no-param-reassign
7335
+ token = removeBrackets(token);
7336
+ return !dots && i ? '[' + token + ']' : token;
7337
+ })
7338
+ .join(dots ? '.' : '');
7201
7339
  }
7202
7340
 
7203
7341
  /**
@@ -7247,21 +7385,26 @@ function requireAxios () {
7247
7385
  formData = formData || new (FormData)();
7248
7386
 
7249
7387
  // eslint-disable-next-line no-param-reassign
7250
- options = utils$1.toFlatObject(options, {
7251
- metaTokens: true,
7252
- dots: false,
7253
- indexes: false
7254
- }, false, function defined(option, source) {
7255
- // eslint-disable-next-line no-eq-null,eqeqeq
7256
- return !utils$1.isUndefined(source[option]);
7257
- });
7388
+ options = utils$1.toFlatObject(
7389
+ options,
7390
+ {
7391
+ metaTokens: true,
7392
+ dots: false,
7393
+ indexes: false,
7394
+ },
7395
+ false,
7396
+ function defined(option, source) {
7397
+ // eslint-disable-next-line no-eq-null,eqeqeq
7398
+ return !utils$1.isUndefined(source[option]);
7399
+ }
7400
+ );
7258
7401
 
7259
7402
  const metaTokens = options.metaTokens;
7260
7403
  // eslint-disable-next-line no-use-before-define
7261
7404
  const visitor = options.visitor || defaultVisitor;
7262
7405
  const dots = options.dots;
7263
7406
  const indexes = options.indexes;
7264
- const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
7407
+ const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
7265
7408
  const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
7266
7409
 
7267
7410
  if (!utils$1.isFunction(visitor)) {
@@ -7280,7 +7423,7 @@ function requireAxios () {
7280
7423
  }
7281
7424
 
7282
7425
  if (!useBlob && utils$1.isBlob(value)) {
7283
- throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
7426
+ throw new AxiosError('Blob is not supported. Use a Buffer instead.');
7284
7427
  }
7285
7428
 
7286
7429
  if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
@@ -7303,6 +7446,11 @@ function requireAxios () {
7303
7446
  function defaultVisitor(value, key, path) {
7304
7447
  let arr = value;
7305
7448
 
7449
+ if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
7450
+ formData.append(renderKey(path, key, dots), convertValue(value));
7451
+ return false;
7452
+ }
7453
+
7306
7454
  if (value && !path && typeof value === 'object') {
7307
7455
  if (utils$1.endsWith(key, '{}')) {
7308
7456
  // eslint-disable-next-line no-param-reassign
@@ -7311,17 +7459,22 @@ function requireAxios () {
7311
7459
  value = JSON.stringify(value);
7312
7460
  } else if (
7313
7461
  (utils$1.isArray(value) && isFlatArray(value)) ||
7314
- ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
7315
- )) {
7462
+ ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)))
7463
+ ) {
7316
7464
  // eslint-disable-next-line no-param-reassign
7317
7465
  key = removeBrackets(key);
7318
7466
 
7319
7467
  arr.forEach(function each(el, index) {
7320
- !(utils$1.isUndefined(el) || el === null) && formData.append(
7321
- // eslint-disable-next-line no-nested-ternary
7322
- indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
7323
- convertValue(el)
7324
- );
7468
+ !(utils$1.isUndefined(el) || el === null) &&
7469
+ formData.append(
7470
+ // eslint-disable-next-line no-nested-ternary
7471
+ indexes === true
7472
+ ? renderKey([key], index, dots)
7473
+ : indexes === null
7474
+ ? key
7475
+ : key + '[]',
7476
+ convertValue(el)
7477
+ );
7325
7478
  });
7326
7479
  return false;
7327
7480
  }
@@ -7341,7 +7494,7 @@ function requireAxios () {
7341
7494
  const exposedHelpers = Object.assign(predicates, {
7342
7495
  defaultVisitor,
7343
7496
  convertValue,
7344
- isVisitable
7497
+ isVisitable,
7345
7498
  });
7346
7499
 
7347
7500
  function build(value, path) {
@@ -7354,9 +7507,9 @@ function requireAxios () {
7354
7507
  stack.push(value);
7355
7508
 
7356
7509
  utils$1.forEach(value, function each(el, key) {
7357
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
7358
- formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
7359
- );
7510
+ const result =
7511
+ !(utils$1.isUndefined(el) || el === null) &&
7512
+ visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
7360
7513
 
7361
7514
  if (result === true) {
7362
7515
  build(el, path ? path.concat(key) : [key]);
@@ -7391,7 +7544,7 @@ function requireAxios () {
7391
7544
  ')': '%29',
7392
7545
  '~': '%7E',
7393
7546
  '%20': '+',
7394
- '%00': '\x00'
7547
+ '%00': '\x00',
7395
7548
  };
7396
7549
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
7397
7550
  return charMap[match];
@@ -7419,29 +7572,33 @@ function requireAxios () {
7419
7572
  };
7420
7573
 
7421
7574
  prototype.toString = function toString(encoder) {
7422
- const _encode = encoder ? function(value) {
7423
- return encoder.call(this, value, encode$1);
7424
- } : encode$1;
7575
+ const _encode = encoder
7576
+ ? function (value) {
7577
+ return encoder.call(this, value, encode$1);
7578
+ }
7579
+ : encode$1;
7425
7580
 
7426
- return this._pairs.map(function each(pair) {
7427
- return _encode(pair[0]) + '=' + _encode(pair[1]);
7428
- }, '').join('&');
7581
+ return this._pairs
7582
+ .map(function each(pair) {
7583
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
7584
+ }, '')
7585
+ .join('&');
7429
7586
  };
7430
7587
 
7431
7588
  /**
7432
- * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
7433
- * URI encoded counterparts
7589
+ * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
7590
+ * their plain counterparts (`:`, `$`, `,`, `+`).
7434
7591
  *
7435
7592
  * @param {string} val The value to be encoded.
7436
7593
  *
7437
7594
  * @returns {string} The encoded value.
7438
7595
  */
7439
7596
  function encode(val) {
7440
- return encodeURIComponent(val).
7441
- replace(/%3A/gi, ':').
7442
- replace(/%24/g, '$').
7443
- replace(/%2C/gi, ',').
7444
- replace(/%20/g, '+');
7597
+ return encodeURIComponent(val)
7598
+ .replace(/%3A/gi, ':')
7599
+ .replace(/%24/g, '$')
7600
+ .replace(/%2C/gi, ',')
7601
+ .replace(/%20/g, '+');
7445
7602
  }
7446
7603
 
7447
7604
  /**
@@ -7458,11 +7615,13 @@ function requireAxios () {
7458
7615
  return url;
7459
7616
  }
7460
7617
 
7461
- const _encode = options && options.encode || encode;
7618
+ const _encode = (options && options.encode) || encode;
7462
7619
 
7463
- const _options = utils$1.isFunction(options) ? {
7464
- serialize: options
7465
- } : options;
7620
+ const _options = utils$1.isFunction(options)
7621
+ ? {
7622
+ serialize: options,
7623
+ }
7624
+ : options;
7466
7625
 
7467
7626
  const serializeFn = _options && _options.serialize;
7468
7627
 
@@ -7471,13 +7630,13 @@ function requireAxios () {
7471
7630
  if (serializeFn) {
7472
7631
  serializedParams = serializeFn(params, _options);
7473
7632
  } else {
7474
- serializedParams = utils$1.isURLSearchParams(params) ?
7475
- params.toString() :
7476
- new AxiosURLSearchParams(params, _options).toString(_encode);
7633
+ serializedParams = utils$1.isURLSearchParams(params)
7634
+ ? params.toString()
7635
+ : new AxiosURLSearchParams(params, _options).toString(_encode);
7477
7636
  }
7478
7637
 
7479
7638
  if (serializedParams) {
7480
- const hashmarkIndex = url.indexOf("#");
7639
+ const hashmarkIndex = url.indexOf('#');
7481
7640
 
7482
7641
  if (hashmarkIndex !== -1) {
7483
7642
  url = url.slice(0, hashmarkIndex);
@@ -7507,7 +7666,7 @@ function requireAxios () {
7507
7666
  fulfilled,
7508
7667
  rejected,
7509
7668
  synchronous: options ? options.synchronous : false,
7510
- runWhen: options ? options.runWhen : null
7669
+ runWhen: options ? options.runWhen : null,
7511
7670
  });
7512
7671
  return this.handlers.length - 1;
7513
7672
  }
@@ -7555,12 +7714,11 @@ function requireAxios () {
7555
7714
  }
7556
7715
  }
7557
7716
 
7558
- var InterceptorManager$1 = InterceptorManager;
7559
-
7560
7717
  var transitionalDefaults = {
7561
7718
  silentJSONParsing: true,
7562
7719
  forcedJSONParsing: true,
7563
- clarifyTimeoutError: false
7720
+ clarifyTimeoutError: false,
7721
+ legacyInterceptorReqResOrdering: true,
7564
7722
  };
7565
7723
 
7566
7724
  var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
@@ -7574,14 +7732,14 @@ function requireAxios () {
7574
7732
  classes: {
7575
7733
  URLSearchParams: URLSearchParams$1,
7576
7734
  FormData: FormData$1,
7577
- Blob: Blob$1
7735
+ Blob: Blob$1,
7578
7736
  },
7579
- protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
7737
+ protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],
7580
7738
  };
7581
7739
 
7582
7740
  const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
7583
7741
 
7584
- const _navigator = typeof navigator === 'object' && navigator || undefined;
7742
+ const _navigator = (typeof navigator === 'object' && navigator) || undefined;
7585
7743
 
7586
7744
  /**
7587
7745
  * Determine if we're running in a standard browser environment
@@ -7600,7 +7758,8 @@ function requireAxios () {
7600
7758
  *
7601
7759
  * @returns {boolean}
7602
7760
  */
7603
- const hasStandardBrowserEnv = hasBrowserEnv &&
7761
+ const hasStandardBrowserEnv =
7762
+ hasBrowserEnv &&
7604
7763
  (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
7605
7764
 
7606
7765
  /**
@@ -7621,25 +7780,25 @@ function requireAxios () {
7621
7780
  );
7622
7781
  })();
7623
7782
 
7624
- const origin = hasBrowserEnv && window.location.href || 'http://localhost';
7783
+ const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';
7625
7784
 
7626
7785
  var utils = /*#__PURE__*/Object.freeze({
7627
7786
  __proto__: null,
7628
7787
  hasBrowserEnv: hasBrowserEnv,
7629
- hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
7630
7788
  hasStandardBrowserEnv: hasStandardBrowserEnv,
7789
+ hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
7631
7790
  navigator: _navigator,
7632
7791
  origin: origin
7633
7792
  });
7634
7793
 
7635
7794
  var platform = {
7636
7795
  ...utils,
7637
- ...platform$1
7796
+ ...platform$1,
7638
7797
  };
7639
7798
 
7640
7799
  function toURLEncodedForm(data, options) {
7641
7800
  return toFormData(data, new platform.classes.URLSearchParams(), {
7642
- visitor: function(value, key, path, helpers) {
7801
+ visitor: function (value, key, path, helpers) {
7643
7802
  if (platform.isNode && utils$1.isBuffer(value)) {
7644
7803
  this.append(key, value.toString('base64'));
7645
7804
  return false;
@@ -7647,7 +7806,7 @@ function requireAxios () {
7647
7806
 
7648
7807
  return helpers.defaultVisitor.apply(this, arguments);
7649
7808
  },
7650
- ...options
7809
+ ...options,
7651
7810
  });
7652
7811
  }
7653
7812
 
@@ -7663,7 +7822,7 @@ function requireAxios () {
7663
7822
  // foo.x.y.z
7664
7823
  // foo-x-y-z
7665
7824
  // foo x y z
7666
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
7825
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
7667
7826
  return match[0] === '[]' ? '' : match[1] || match[0];
7668
7827
  });
7669
7828
  }
@@ -7767,96 +7926,107 @@ function requireAxios () {
7767
7926
  }
7768
7927
 
7769
7928
  const defaults = {
7770
-
7771
7929
  transitional: transitionalDefaults,
7772
7930
 
7773
7931
  adapter: ['xhr', 'http', 'fetch'],
7774
7932
 
7775
- transformRequest: [function transformRequest(data, headers) {
7776
- const contentType = headers.getContentType() || '';
7777
- const hasJSONContentType = contentType.indexOf('application/json') > -1;
7778
- const isObjectPayload = utils$1.isObject(data);
7933
+ transformRequest: [
7934
+ function transformRequest(data, headers) {
7935
+ const contentType = headers.getContentType() || '';
7936
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
7937
+ const isObjectPayload = utils$1.isObject(data);
7779
7938
 
7780
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
7781
- data = new FormData(data);
7782
- }
7939
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
7940
+ data = new FormData(data);
7941
+ }
7783
7942
 
7784
- const isFormData = utils$1.isFormData(data);
7943
+ const isFormData = utils$1.isFormData(data);
7785
7944
 
7786
- if (isFormData) {
7787
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
7788
- }
7945
+ if (isFormData) {
7946
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
7947
+ }
7789
7948
 
7790
- if (utils$1.isArrayBuffer(data) ||
7791
- utils$1.isBuffer(data) ||
7792
- utils$1.isStream(data) ||
7793
- utils$1.isFile(data) ||
7794
- utils$1.isBlob(data) ||
7795
- utils$1.isReadableStream(data)
7796
- ) {
7797
- return data;
7798
- }
7799
- if (utils$1.isArrayBufferView(data)) {
7800
- return data.buffer;
7801
- }
7802
- if (utils$1.isURLSearchParams(data)) {
7803
- headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
7804
- return data.toString();
7805
- }
7949
+ if (
7950
+ utils$1.isArrayBuffer(data) ||
7951
+ utils$1.isBuffer(data) ||
7952
+ utils$1.isStream(data) ||
7953
+ utils$1.isFile(data) ||
7954
+ utils$1.isBlob(data) ||
7955
+ utils$1.isReadableStream(data)
7956
+ ) {
7957
+ return data;
7958
+ }
7959
+ if (utils$1.isArrayBufferView(data)) {
7960
+ return data.buffer;
7961
+ }
7962
+ if (utils$1.isURLSearchParams(data)) {
7963
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
7964
+ return data.toString();
7965
+ }
7806
7966
 
7807
- let isFileList;
7967
+ let isFileList;
7808
7968
 
7809
- if (isObjectPayload) {
7810
- if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
7811
- return toURLEncodedForm(data, this.formSerializer).toString();
7812
- }
7969
+ if (isObjectPayload) {
7970
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
7971
+ return toURLEncodedForm(data, this.formSerializer).toString();
7972
+ }
7813
7973
 
7814
- if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
7815
- const _FormData = this.env && this.env.FormData;
7974
+ if (
7975
+ (isFileList = utils$1.isFileList(data)) ||
7976
+ contentType.indexOf('multipart/form-data') > -1
7977
+ ) {
7978
+ const _FormData = this.env && this.env.FormData;
7816
7979
 
7817
- return toFormData(
7818
- isFileList ? {'files[]': data} : data,
7819
- _FormData && new _FormData(),
7820
- this.formSerializer
7821
- );
7980
+ return toFormData(
7981
+ isFileList ? { 'files[]': data } : data,
7982
+ _FormData && new _FormData(),
7983
+ this.formSerializer
7984
+ );
7985
+ }
7822
7986
  }
7823
- }
7824
7987
 
7825
- if (isObjectPayload || hasJSONContentType ) {
7826
- headers.setContentType('application/json', false);
7827
- return stringifySafely(data);
7828
- }
7988
+ if (isObjectPayload || hasJSONContentType) {
7989
+ headers.setContentType('application/json', false);
7990
+ return stringifySafely(data);
7991
+ }
7829
7992
 
7830
- return data;
7831
- }],
7993
+ return data;
7994
+ },
7995
+ ],
7832
7996
 
7833
- transformResponse: [function transformResponse(data) {
7834
- const transitional = this.transitional || defaults.transitional;
7835
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
7836
- const JSONRequested = this.responseType === 'json';
7997
+ transformResponse: [
7998
+ function transformResponse(data) {
7999
+ const transitional = this.transitional || defaults.transitional;
8000
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
8001
+ const JSONRequested = this.responseType === 'json';
7837
8002
 
7838
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
7839
- return data;
7840
- }
8003
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
8004
+ return data;
8005
+ }
7841
8006
 
7842
- if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
7843
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
7844
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
8007
+ if (
8008
+ data &&
8009
+ utils$1.isString(data) &&
8010
+ ((forcedJSONParsing && !this.responseType) || JSONRequested)
8011
+ ) {
8012
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
8013
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
7845
8014
 
7846
- try {
7847
- return JSON.parse(data, this.parseReviver);
7848
- } catch (e) {
7849
- if (strictJSONParsing) {
7850
- if (e.name === 'SyntaxError') {
7851
- throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
8015
+ try {
8016
+ return JSON.parse(data, this.parseReviver);
8017
+ } catch (e) {
8018
+ if (strictJSONParsing) {
8019
+ if (e.name === 'SyntaxError') {
8020
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
8021
+ }
8022
+ throw e;
7852
8023
  }
7853
- throw e;
7854
8024
  }
7855
8025
  }
7856
- }
7857
8026
 
7858
- return data;
7859
- }],
8027
+ return data;
8028
+ },
8029
+ ],
7860
8030
 
7861
8031
  /**
7862
8032
  * A timeout in milliseconds to abort a request. If set to 0 (default) a
@@ -7872,7 +8042,7 @@ function requireAxios () {
7872
8042
 
7873
8043
  env: {
7874
8044
  FormData: platform.classes.FormData,
7875
- Blob: platform.classes.Blob
8045
+ Blob: platform.classes.Blob,
7876
8046
  },
7877
8047
 
7878
8048
  validateStatus: function validateStatus(status) {
@@ -7881,25 +8051,36 @@ function requireAxios () {
7881
8051
 
7882
8052
  headers: {
7883
8053
  common: {
7884
- 'Accept': 'application/json, text/plain, */*',
7885
- 'Content-Type': undefined
7886
- }
7887
- }
8054
+ Accept: 'application/json, text/plain, */*',
8055
+ 'Content-Type': undefined,
8056
+ },
8057
+ },
7888
8058
  };
7889
8059
 
7890
8060
  utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
7891
8061
  defaults.headers[method] = {};
7892
8062
  });
7893
8063
 
7894
- var defaults$1 = defaults;
7895
-
7896
8064
  // RawAxiosHeaders whose duplicates are ignored by node
7897
8065
  // c.f. https://nodejs.org/api/http.html#http_message_headers
7898
8066
  const ignoreDuplicateOf = utils$1.toObjectSet([
7899
- 'age', 'authorization', 'content-length', 'content-type', 'etag',
7900
- 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
7901
- 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
7902
- 'referer', 'retry-after', 'user-agent'
8067
+ 'age',
8068
+ 'authorization',
8069
+ 'content-length',
8070
+ 'content-type',
8071
+ 'etag',
8072
+ 'expires',
8073
+ 'from',
8074
+ 'host',
8075
+ 'if-modified-since',
8076
+ 'if-unmodified-since',
8077
+ 'last-modified',
8078
+ 'location',
8079
+ 'max-forwards',
8080
+ 'proxy-authorization',
8081
+ 'referer',
8082
+ 'retry-after',
8083
+ 'user-agent',
7903
8084
  ]);
7904
8085
 
7905
8086
  /**
@@ -7916,31 +8097,32 @@ function requireAxios () {
7916
8097
  *
7917
8098
  * @returns {Object} Headers parsed into an object
7918
8099
  */
7919
- var parseHeaders = rawHeaders => {
8100
+ var parseHeaders = (rawHeaders) => {
7920
8101
  const parsed = {};
7921
8102
  let key;
7922
8103
  let val;
7923
8104
  let i;
7924
8105
 
7925
- rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
7926
- i = line.indexOf(':');
7927
- key = line.substring(0, i).trim().toLowerCase();
7928
- val = line.substring(i + 1).trim();
8106
+ rawHeaders &&
8107
+ rawHeaders.split('\n').forEach(function parser(line) {
8108
+ i = line.indexOf(':');
8109
+ key = line.substring(0, i).trim().toLowerCase();
8110
+ val = line.substring(i + 1).trim();
7929
8111
 
7930
- if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
7931
- return;
7932
- }
8112
+ if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
8113
+ return;
8114
+ }
7933
8115
 
7934
- if (key === 'set-cookie') {
7935
- if (parsed[key]) {
7936
- parsed[key].push(val);
8116
+ if (key === 'set-cookie') {
8117
+ if (parsed[key]) {
8118
+ parsed[key].push(val);
8119
+ } else {
8120
+ parsed[key] = [val];
8121
+ }
7937
8122
  } else {
7938
- parsed[key] = [val];
8123
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
7939
8124
  }
7940
- } else {
7941
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
7942
- }
7943
- });
8125
+ });
7944
8126
 
7945
8127
  return parsed;
7946
8128
  };
@@ -7956,7 +8138,9 @@ function requireAxios () {
7956
8138
  return value;
7957
8139
  }
7958
8140
 
7959
- return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
8141
+ return utils$1.isArray(value)
8142
+ ? value.map(normalizeValue)
8143
+ : String(value).replace(/[\r\n]+$/, '');
7960
8144
  }
7961
8145
 
7962
8146
  function parseTokens(str) {
@@ -7994,8 +8178,10 @@ function requireAxios () {
7994
8178
  }
7995
8179
 
7996
8180
  function formatHeader(header) {
7997
- return header.trim()
7998
- .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
8181
+ return header
8182
+ .trim()
8183
+ .toLowerCase()
8184
+ .replace(/([a-z\d])(\w*)/g, (w, char, str) => {
7999
8185
  return char.toUpperCase() + str;
8000
8186
  });
8001
8187
  }
@@ -8003,12 +8189,12 @@ function requireAxios () {
8003
8189
  function buildAccessors(obj, header) {
8004
8190
  const accessorName = utils$1.toCamelCase(' ' + header);
8005
8191
 
8006
- ['get', 'set', 'has'].forEach(methodName => {
8192
+ ['get', 'set', 'has'].forEach((methodName) => {
8007
8193
  Object.defineProperty(obj, methodName + accessorName, {
8008
- value: function(arg1, arg2, arg3) {
8194
+ value: function (arg1, arg2, arg3) {
8009
8195
  return this[methodName].call(this, header, arg1, arg2, arg3);
8010
8196
  },
8011
- configurable: true
8197
+ configurable: true,
8012
8198
  });
8013
8199
  });
8014
8200
  }
@@ -8030,7 +8216,12 @@ function requireAxios () {
8030
8216
 
8031
8217
  const key = utils$1.findKey(self, lHeader);
8032
8218
 
8033
- if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
8219
+ if (
8220
+ !key ||
8221
+ self[key] === undefined ||
8222
+ _rewrite === true ||
8223
+ (_rewrite === undefined && self[key] !== false)
8224
+ ) {
8034
8225
  self[key || _header] = normalizeValue(_value);
8035
8226
  }
8036
8227
  }
@@ -8040,17 +8231,22 @@ function requireAxios () {
8040
8231
 
8041
8232
  if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
8042
8233
  setHeaders(header, valueOrRewrite);
8043
- } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
8234
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
8044
8235
  setHeaders(parseHeaders(header), valueOrRewrite);
8045
8236
  } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
8046
- let obj = {}, dest, key;
8237
+ let obj = {},
8238
+ dest,
8239
+ key;
8047
8240
  for (const entry of header) {
8048
8241
  if (!utils$1.isArray(entry)) {
8049
8242
  throw TypeError('Object iterator must return a key-value pair');
8050
8243
  }
8051
8244
 
8052
- obj[key = entry[0]] = (dest = obj[key]) ?
8053
- (utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1];
8245
+ obj[(key = entry[0])] = (dest = obj[key])
8246
+ ? utils$1.isArray(dest)
8247
+ ? [...dest, entry[1]]
8248
+ : [dest, entry[1]]
8249
+ : entry[1];
8054
8250
  }
8055
8251
 
8056
8252
  setHeaders(obj, valueOrRewrite);
@@ -8097,7 +8293,11 @@ function requireAxios () {
8097
8293
  if (header) {
8098
8294
  const key = utils$1.findKey(this, header);
8099
8295
 
8100
- return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
8296
+ return !!(
8297
+ key &&
8298
+ this[key] !== undefined &&
8299
+ (!matcher || matchHeaderValue(this, this[key], key, matcher))
8300
+ );
8101
8301
  }
8102
8302
 
8103
8303
  return false;
@@ -8137,7 +8337,7 @@ function requireAxios () {
8137
8337
 
8138
8338
  while (i--) {
8139
8339
  const key = keys[i];
8140
- if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
8340
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
8141
8341
  delete this[key];
8142
8342
  deleted = true;
8143
8343
  }
@@ -8181,7 +8381,9 @@ function requireAxios () {
8181
8381
  const obj = Object.create(null);
8182
8382
 
8183
8383
  utils$1.forEach(this, (value, header) => {
8184
- value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
8384
+ value != null &&
8385
+ value !== false &&
8386
+ (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
8185
8387
  });
8186
8388
 
8187
8389
  return obj;
@@ -8192,11 +8394,13 @@ function requireAxios () {
8192
8394
  }
8193
8395
 
8194
8396
  toString() {
8195
- return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
8397
+ return Object.entries(this.toJSON())
8398
+ .map(([header, value]) => header + ': ' + value)
8399
+ .join('\n');
8196
8400
  }
8197
8401
 
8198
8402
  getSetCookie() {
8199
- return this.get("set-cookie") || [];
8403
+ return this.get('set-cookie') || [];
8200
8404
  }
8201
8405
 
8202
8406
  get [Symbol.toStringTag]() {
@@ -8216,9 +8420,12 @@ function requireAxios () {
8216
8420
  }
8217
8421
 
8218
8422
  static accessor(header) {
8219
- const internals = this[$internals] = (this[$internals] = {
8220
- accessors: {}
8221
- });
8423
+ const internals =
8424
+ (this[$internals] =
8425
+ this[$internals] =
8426
+ {
8427
+ accessors: {},
8428
+ });
8222
8429
 
8223
8430
  const accessors = internals.accessors;
8224
8431
  const prototype = this.prototype;
@@ -8238,23 +8445,28 @@ function requireAxios () {
8238
8445
  }
8239
8446
  }
8240
8447
 
8241
- AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
8448
+ AxiosHeaders.accessor([
8449
+ 'Content-Type',
8450
+ 'Content-Length',
8451
+ 'Accept',
8452
+ 'Accept-Encoding',
8453
+ 'User-Agent',
8454
+ 'Authorization',
8455
+ ]);
8242
8456
 
8243
8457
  // reserved names hotfix
8244
- utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
8458
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
8245
8459
  let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
8246
8460
  return {
8247
8461
  get: () => value,
8248
8462
  set(headerValue) {
8249
8463
  this[mapped] = headerValue;
8250
- }
8251
- }
8464
+ },
8465
+ };
8252
8466
  });
8253
8467
 
8254
8468
  utils$1.freezeMethods(AxiosHeaders);
8255
8469
 
8256
- var AxiosHeaders$1 = AxiosHeaders;
8257
-
8258
8470
  /**
8259
8471
  * Transform the data for a request or a response
8260
8472
  *
@@ -8264,9 +8476,9 @@ function requireAxios () {
8264
8476
  * @returns {*} The resulting transformed data
8265
8477
  */
8266
8478
  function transformData(fns, response) {
8267
- const config = this || defaults$1;
8479
+ const config = this || defaults;
8268
8480
  const context = response || config;
8269
- const headers = AxiosHeaders$1.from(context.headers);
8481
+ const headers = AxiosHeaders.from(context.headers);
8270
8482
  let data = context.data;
8271
8483
 
8272
8484
  utils$1.forEach(fns, function transform(fn) {
@@ -8282,7 +8494,7 @@ function requireAxios () {
8282
8494
  return !!(value && value.__CANCEL__);
8283
8495
  }
8284
8496
 
8285
- class CanceledError extends AxiosError$1 {
8497
+ class CanceledError extends AxiosError {
8286
8498
  /**
8287
8499
  * A `CanceledError` is an object that is thrown when an operation is canceled.
8288
8500
  *
@@ -8293,14 +8505,12 @@ function requireAxios () {
8293
8505
  * @returns {CanceledError} The created error.
8294
8506
  */
8295
8507
  constructor(message, config, request) {
8296
- super(message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
8508
+ super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
8297
8509
  this.name = 'CanceledError';
8298
8510
  this.__CANCEL__ = true;
8299
8511
  }
8300
8512
  }
8301
8513
 
8302
- var CanceledError$1 = CanceledError;
8303
-
8304
8514
  /**
8305
8515
  * Resolve or reject a Promise based on response status.
8306
8516
  *
@@ -8315,19 +8525,23 @@ function requireAxios () {
8315
8525
  if (!response.status || !validateStatus || validateStatus(response.status)) {
8316
8526
  resolve(response);
8317
8527
  } else {
8318
- reject(new AxiosError$1(
8319
- 'Request failed with status code ' + response.status,
8320
- [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
8321
- response.config,
8322
- response.request,
8323
- response
8324
- ));
8528
+ reject(
8529
+ new AxiosError(
8530
+ 'Request failed with status code ' + response.status,
8531
+ [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][
8532
+ Math.floor(response.status / 100) - 4
8533
+ ],
8534
+ response.config,
8535
+ response.request,
8536
+ response
8537
+ )
8538
+ );
8325
8539
  }
8326
8540
  }
8327
8541
 
8328
8542
  function parseProtocol(url) {
8329
8543
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
8330
- return match && match[1] || '';
8544
+ return (match && match[1]) || '';
8331
8545
  }
8332
8546
 
8333
8547
  /**
@@ -8378,7 +8592,7 @@ function requireAxios () {
8378
8592
 
8379
8593
  const passed = startedAt && now - startedAt;
8380
8594
 
8381
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
8595
+ return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
8382
8596
  };
8383
8597
  }
8384
8598
 
@@ -8407,7 +8621,7 @@ function requireAxios () {
8407
8621
  const throttled = (...args) => {
8408
8622
  const now = Date.now();
8409
8623
  const passed = now - timestamp;
8410
- if ( passed >= threshold) {
8624
+ if (passed >= threshold) {
8411
8625
  invoke(args, now);
8412
8626
  } else {
8413
8627
  lastArgs = args;
@@ -8429,7 +8643,7 @@ function requireAxios () {
8429
8643
  let bytesNotified = 0;
8430
8644
  const _speedometer = speedometer(50, 250);
8431
8645
 
8432
- return throttle(e => {
8646
+ return throttle((e) => {
8433
8647
  const loaded = e.loaded;
8434
8648
  const total = e.lengthComputable ? e.total : undefined;
8435
8649
  const progressBytes = loaded - bytesNotified;
@@ -8441,13 +8655,13 @@ function requireAxios () {
8441
8655
  const data = {
8442
8656
  loaded,
8443
8657
  total,
8444
- progress: total ? (loaded / total) : undefined,
8658
+ progress: total ? loaded / total : undefined,
8445
8659
  bytes: progressBytes,
8446
8660
  rate: rate ? rate : undefined,
8447
8661
  estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
8448
8662
  event: e,
8449
8663
  lengthComputable: total != null,
8450
- [isDownloadStream ? 'download' : 'upload']: true
8664
+ [isDownloadStream ? 'download' : 'upload']: true,
8451
8665
  };
8452
8666
 
8453
8667
  listener(data);
@@ -8457,77 +8671,82 @@ function requireAxios () {
8457
8671
  const progressEventDecorator = (total, throttled) => {
8458
8672
  const lengthComputable = total != null;
8459
8673
 
8460
- return [(loaded) => throttled[0]({
8461
- lengthComputable,
8462
- total,
8463
- loaded
8464
- }), throttled[1]];
8674
+ return [
8675
+ (loaded) =>
8676
+ throttled[0]({
8677
+ lengthComputable,
8678
+ total,
8679
+ loaded,
8680
+ }),
8681
+ throttled[1],
8682
+ ];
8465
8683
  };
8466
8684
 
8467
- const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
8685
+ const asyncDecorator =
8686
+ (fn) =>
8687
+ (...args) =>
8688
+ utils$1.asap(() => fn(...args));
8468
8689
 
8469
- var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
8470
- url = new URL(url, platform.origin);
8690
+ var isURLSameOrigin = platform.hasStandardBrowserEnv
8691
+ ? ((origin, isMSIE) => (url) => {
8692
+ url = new URL(url, platform.origin);
8471
8693
 
8472
- return (
8473
- origin.protocol === url.protocol &&
8474
- origin.host === url.host &&
8475
- (isMSIE || origin.port === url.port)
8476
- );
8477
- })(
8478
- new URL(platform.origin),
8479
- platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
8480
- ) : () => true;
8481
-
8482
- var cookies = platform.hasStandardBrowserEnv ?
8694
+ return (
8695
+ origin.protocol === url.protocol &&
8696
+ origin.host === url.host &&
8697
+ (isMSIE || origin.port === url.port)
8698
+ );
8699
+ })(
8700
+ new URL(platform.origin),
8701
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
8702
+ )
8703
+ : () => true;
8483
8704
 
8484
- // Standard browser envs support document.cookie
8485
- {
8486
- write(name, value, expires, path, domain, secure, sameSite) {
8487
- if (typeof document === 'undefined') return;
8705
+ var cookies = platform.hasStandardBrowserEnv
8706
+ ? // Standard browser envs support document.cookie
8707
+ {
8708
+ write(name, value, expires, path, domain, secure, sameSite) {
8709
+ if (typeof document === 'undefined') return;
8488
8710
 
8489
- const cookie = [`${name}=${encodeURIComponent(value)}`];
8711
+ const cookie = [`${name}=${encodeURIComponent(value)}`];
8490
8712
 
8491
- if (utils$1.isNumber(expires)) {
8492
- cookie.push(`expires=${new Date(expires).toUTCString()}`);
8493
- }
8494
- if (utils$1.isString(path)) {
8495
- cookie.push(`path=${path}`);
8496
- }
8497
- if (utils$1.isString(domain)) {
8498
- cookie.push(`domain=${domain}`);
8499
- }
8500
- if (secure === true) {
8501
- cookie.push('secure');
8502
- }
8503
- if (utils$1.isString(sameSite)) {
8504
- cookie.push(`SameSite=${sameSite}`);
8505
- }
8713
+ if (utils$1.isNumber(expires)) {
8714
+ cookie.push(`expires=${new Date(expires).toUTCString()}`);
8715
+ }
8716
+ if (utils$1.isString(path)) {
8717
+ cookie.push(`path=${path}`);
8718
+ }
8719
+ if (utils$1.isString(domain)) {
8720
+ cookie.push(`domain=${domain}`);
8721
+ }
8722
+ if (secure === true) {
8723
+ cookie.push('secure');
8724
+ }
8725
+ if (utils$1.isString(sameSite)) {
8726
+ cookie.push(`SameSite=${sameSite}`);
8727
+ }
8506
8728
 
8507
- document.cookie = cookie.join('; ');
8508
- },
8729
+ document.cookie = cookie.join('; ');
8730
+ },
8509
8731
 
8510
- read(name) {
8511
- if (typeof document === 'undefined') return null;
8512
- const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
8513
- return match ? decodeURIComponent(match[1]) : null;
8514
- },
8732
+ read(name) {
8733
+ if (typeof document === 'undefined') return null;
8734
+ const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
8735
+ return match ? decodeURIComponent(match[1]) : null;
8736
+ },
8515
8737
 
8516
- remove(name) {
8517
- this.write(name, '', Date.now() - 86400000, '/');
8738
+ remove(name) {
8739
+ this.write(name, '', Date.now() - 86400000, '/');
8740
+ },
8518
8741
  }
8519
- }
8520
-
8521
- :
8522
-
8523
- // Non-standard browser env (web workers, react-native) lack needed support.
8524
- {
8525
- write() {},
8526
- read() {
8527
- return null;
8528
- },
8529
- remove() {}
8530
- };
8742
+ : // Non-standard browser env (web workers, react-native) lack needed support.
8743
+ {
8744
+ write() {},
8745
+ read() {
8746
+ return null;
8747
+ },
8748
+ remove() {},
8749
+ };
8531
8750
 
8532
8751
  /**
8533
8752
  * Determines whether the specified URL is absolute
@@ -8540,6 +8759,10 @@ function requireAxios () {
8540
8759
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
8541
8760
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
8542
8761
  // by any combination of letters, digits, plus, period, or hyphen.
8762
+ if (typeof url !== 'string') {
8763
+ return false;
8764
+ }
8765
+
8543
8766
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
8544
8767
  }
8545
8768
 
@@ -8575,7 +8798,7 @@ function requireAxios () {
8575
8798
  return requestedURL;
8576
8799
  }
8577
8800
 
8578
- const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
8801
+ const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing);
8579
8802
 
8580
8803
  /**
8581
8804
  * Config-specific merge-function which creates a new config-object
@@ -8664,11 +8887,13 @@ function requireAxios () {
8664
8887
  socketPath: defaultToConfig2,
8665
8888
  responseEncoding: defaultToConfig2,
8666
8889
  validateStatus: mergeDirectKeys,
8667
- headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
8890
+ headers: (a, b, prop) =>
8891
+ mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
8668
8892
  };
8669
8893
 
8670
8894
  utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
8671
- const merge = mergeMap[prop] || mergeDeepProperties;
8895
+ if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
8896
+ const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
8672
8897
  const configValue = merge(config1[prop], config2[prop], prop);
8673
8898
  (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
8674
8899
  });
@@ -8681,14 +8906,24 @@ function requireAxios () {
8681
8906
 
8682
8907
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
8683
8908
 
8684
- newConfig.headers = headers = AxiosHeaders$1.from(headers);
8909
+ newConfig.headers = headers = AxiosHeaders.from(headers);
8685
8910
 
8686
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
8911
+ newConfig.url = buildURL(
8912
+ buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls),
8913
+ config.params,
8914
+ config.paramsSerializer
8915
+ );
8687
8916
 
8688
8917
  // HTTP basic authentication
8689
8918
  if (auth) {
8690
- headers.set('Authorization', 'Basic ' +
8691
- btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
8919
+ headers.set(
8920
+ 'Authorization',
8921
+ 'Basic ' +
8922
+ btoa(
8923
+ (auth.username || '') +
8924
+ ':' +
8925
+ (auth.password ? unescape(encodeURIComponent(auth.password)) : '')
8926
+ )
8692
8927
  );
8693
8928
  }
8694
8929
 
@@ -8706,7 +8941,7 @@ function requireAxios () {
8706
8941
  }
8707
8942
  });
8708
8943
  }
8709
- }
8944
+ }
8710
8945
 
8711
8946
  // Add xsrf header
8712
8947
  // This is only done if running in a standard browser environment.
@@ -8730,196 +8965,218 @@ function requireAxios () {
8730
8965
 
8731
8966
  const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
8732
8967
 
8733
- var xhrAdapter = isXHRAdapterSupported && function (config) {
8734
- return new Promise(function dispatchXhrRequest(resolve, reject) {
8735
- const _config = resolveConfig(config);
8736
- let requestData = _config.data;
8737
- const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
8738
- let {responseType, onUploadProgress, onDownloadProgress} = _config;
8739
- let onCanceled;
8740
- let uploadThrottled, downloadThrottled;
8741
- let flushUpload, flushDownload;
8968
+ var xhrAdapter = isXHRAdapterSupported &&
8969
+ function (config) {
8970
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
8971
+ const _config = resolveConfig(config);
8972
+ let requestData = _config.data;
8973
+ const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
8974
+ let { responseType, onUploadProgress, onDownloadProgress } = _config;
8975
+ let onCanceled;
8976
+ let uploadThrottled, downloadThrottled;
8977
+ let flushUpload, flushDownload;
8742
8978
 
8743
- function done() {
8744
- flushUpload && flushUpload(); // flush events
8745
- flushDownload && flushDownload(); // flush events
8979
+ function done() {
8980
+ flushUpload && flushUpload(); // flush events
8981
+ flushDownload && flushDownload(); // flush events
8746
8982
 
8747
- _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
8983
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
8748
8984
 
8749
- _config.signal && _config.signal.removeEventListener('abort', onCanceled);
8750
- }
8985
+ _config.signal && _config.signal.removeEventListener('abort', onCanceled);
8986
+ }
8751
8987
 
8752
- let request = new XMLHttpRequest();
8988
+ let request = new XMLHttpRequest();
8753
8989
 
8754
- request.open(_config.method.toUpperCase(), _config.url, true);
8990
+ request.open(_config.method.toUpperCase(), _config.url, true);
8755
8991
 
8756
- // Set the request timeout in MS
8757
- request.timeout = _config.timeout;
8992
+ // Set the request timeout in MS
8993
+ request.timeout = _config.timeout;
8758
8994
 
8759
- function onloadend() {
8760
- if (!request) {
8761
- return;
8995
+ function onloadend() {
8996
+ if (!request) {
8997
+ return;
8998
+ }
8999
+ // Prepare the response
9000
+ const responseHeaders = AxiosHeaders.from(
9001
+ 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
9002
+ );
9003
+ const responseData =
9004
+ !responseType || responseType === 'text' || responseType === 'json'
9005
+ ? request.responseText
9006
+ : request.response;
9007
+ const response = {
9008
+ data: responseData,
9009
+ status: request.status,
9010
+ statusText: request.statusText,
9011
+ headers: responseHeaders,
9012
+ config,
9013
+ request,
9014
+ };
9015
+
9016
+ settle(
9017
+ function _resolve(value) {
9018
+ resolve(value);
9019
+ done();
9020
+ },
9021
+ function _reject(err) {
9022
+ reject(err);
9023
+ done();
9024
+ },
9025
+ response
9026
+ );
9027
+
9028
+ // Clean up request
9029
+ request = null;
8762
9030
  }
8763
- // Prepare the response
8764
- const responseHeaders = AxiosHeaders$1.from(
8765
- 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
8766
- );
8767
- const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
8768
- request.responseText : request.response;
8769
- const response = {
8770
- data: responseData,
8771
- status: request.status,
8772
- statusText: request.statusText,
8773
- headers: responseHeaders,
8774
- config,
8775
- request
8776
- };
8777
9031
 
8778
- settle(function _resolve(value) {
8779
- resolve(value);
8780
- done();
8781
- }, function _reject(err) {
8782
- reject(err);
8783
- done();
8784
- }, response);
9032
+ if ('onloadend' in request) {
9033
+ // Use onloadend if available
9034
+ request.onloadend = onloadend;
9035
+ } else {
9036
+ // Listen for ready state to emulate onloadend
9037
+ request.onreadystatechange = function handleLoad() {
9038
+ if (!request || request.readyState !== 4) {
9039
+ return;
9040
+ }
8785
9041
 
8786
- // Clean up request
8787
- request = null;
8788
- }
9042
+ // The request errored out and we didn't get a response, this will be
9043
+ // handled by onerror instead
9044
+ // With one exception: request that using file: protocol, most browsers
9045
+ // will return status as 0 even though it's a successful request
9046
+ if (
9047
+ request.status === 0 &&
9048
+ !(request.responseURL && request.responseURL.indexOf('file:') === 0)
9049
+ ) {
9050
+ return;
9051
+ }
9052
+ // readystate handler is calling before onerror or ontimeout handlers,
9053
+ // so we should call onloadend on the next 'tick'
9054
+ setTimeout(onloadend);
9055
+ };
9056
+ }
8789
9057
 
8790
- if ('onloadend' in request) {
8791
- // Use onloadend if available
8792
- request.onloadend = onloadend;
8793
- } else {
8794
- // Listen for ready state to emulate onloadend
8795
- request.onreadystatechange = function handleLoad() {
8796
- if (!request || request.readyState !== 4) {
9058
+ // Handle browser request cancellation (as opposed to a manual cancellation)
9059
+ request.onabort = function handleAbort() {
9060
+ if (!request) {
8797
9061
  return;
8798
9062
  }
8799
9063
 
8800
- // The request errored out and we didn't get a response, this will be
8801
- // handled by onerror instead
8802
- // With one exception: request that using file: protocol, most browsers
8803
- // will return status as 0 even though it's a successful request
8804
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
8805
- return;
8806
- }
8807
- // readystate handler is calling before onerror or ontimeout handlers,
8808
- // so we should call onloadend on the next 'tick'
8809
- setTimeout(onloadend);
9064
+ reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
9065
+
9066
+ // Clean up request
9067
+ request = null;
8810
9068
  };
8811
- }
8812
9069
 
8813
- // Handle browser request cancellation (as opposed to a manual cancellation)
8814
- request.onabort = function handleAbort() {
8815
- if (!request) {
8816
- return;
8817
- }
9070
+ // Handle low level network errors
9071
+ request.onerror = function handleError(event) {
9072
+ // Browsers deliver a ProgressEvent in XHR onerror
9073
+ // (message may be empty; when present, surface it)
9074
+ // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
9075
+ const msg = event && event.message ? event.message : 'Network Error';
9076
+ const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
9077
+ // attach the underlying event for consumers who want details
9078
+ err.event = event || null;
9079
+ reject(err);
9080
+ request = null;
9081
+ };
8818
9082
 
8819
- reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
9083
+ // Handle timeout
9084
+ request.ontimeout = function handleTimeout() {
9085
+ let timeoutErrorMessage = _config.timeout
9086
+ ? 'timeout of ' + _config.timeout + 'ms exceeded'
9087
+ : 'timeout exceeded';
9088
+ const transitional = _config.transitional || transitionalDefaults;
9089
+ if (_config.timeoutErrorMessage) {
9090
+ timeoutErrorMessage = _config.timeoutErrorMessage;
9091
+ }
9092
+ reject(
9093
+ new AxiosError(
9094
+ timeoutErrorMessage,
9095
+ transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
9096
+ config,
9097
+ request
9098
+ )
9099
+ );
8820
9100
 
8821
- // Clean up request
8822
- request = null;
8823
- };
9101
+ // Clean up request
9102
+ request = null;
9103
+ };
8824
9104
 
8825
- // Handle low level network errors
8826
- request.onerror = function handleError(event) {
8827
- // Browsers deliver a ProgressEvent in XHR onerror
8828
- // (message may be empty; when present, surface it)
8829
- // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
8830
- const msg = event && event.message ? event.message : 'Network Error';
8831
- const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request);
8832
- // attach the underlying event for consumers who want details
8833
- err.event = event || null;
8834
- reject(err);
8835
- request = null;
8836
- };
8837
-
8838
- // Handle timeout
8839
- request.ontimeout = function handleTimeout() {
8840
- let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
8841
- const transitional = _config.transitional || transitionalDefaults;
8842
- if (_config.timeoutErrorMessage) {
8843
- timeoutErrorMessage = _config.timeoutErrorMessage;
8844
- }
8845
- reject(new AxiosError$1(
8846
- timeoutErrorMessage,
8847
- transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
8848
- config,
8849
- request));
8850
-
8851
- // Clean up request
8852
- request = null;
8853
- };
9105
+ // Remove Content-Type if data is undefined
9106
+ requestData === undefined && requestHeaders.setContentType(null);
8854
9107
 
8855
- // Remove Content-Type if data is undefined
8856
- requestData === undefined && requestHeaders.setContentType(null);
9108
+ // Add headers to the request
9109
+ if ('setRequestHeader' in request) {
9110
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
9111
+ request.setRequestHeader(key, val);
9112
+ });
9113
+ }
8857
9114
 
8858
- // Add headers to the request
8859
- if ('setRequestHeader' in request) {
8860
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
8861
- request.setRequestHeader(key, val);
8862
- });
8863
- }
9115
+ // Add withCredentials to request if needed
9116
+ if (!utils$1.isUndefined(_config.withCredentials)) {
9117
+ request.withCredentials = !!_config.withCredentials;
9118
+ }
8864
9119
 
8865
- // Add withCredentials to request if needed
8866
- if (!utils$1.isUndefined(_config.withCredentials)) {
8867
- request.withCredentials = !!_config.withCredentials;
8868
- }
9120
+ // Add responseType to request if needed
9121
+ if (responseType && responseType !== 'json') {
9122
+ request.responseType = _config.responseType;
9123
+ }
8869
9124
 
8870
- // Add responseType to request if needed
8871
- if (responseType && responseType !== 'json') {
8872
- request.responseType = _config.responseType;
8873
- }
9125
+ // Handle progress if needed
9126
+ if (onDownloadProgress) {
9127
+ [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
9128
+ request.addEventListener('progress', downloadThrottled);
9129
+ }
8874
9130
 
8875
- // Handle progress if needed
8876
- if (onDownloadProgress) {
8877
- ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
8878
- request.addEventListener('progress', downloadThrottled);
8879
- }
9131
+ // Not all browsers support upload events
9132
+ if (onUploadProgress && request.upload) {
9133
+ [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
8880
9134
 
8881
- // Not all browsers support upload events
8882
- if (onUploadProgress && request.upload) {
8883
- ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
9135
+ request.upload.addEventListener('progress', uploadThrottled);
8884
9136
 
8885
- request.upload.addEventListener('progress', uploadThrottled);
9137
+ request.upload.addEventListener('loadend', flushUpload);
9138
+ }
8886
9139
 
8887
- request.upload.addEventListener('loadend', flushUpload);
8888
- }
9140
+ if (_config.cancelToken || _config.signal) {
9141
+ // Handle cancellation
9142
+ // eslint-disable-next-line func-names
9143
+ onCanceled = (cancel) => {
9144
+ if (!request) {
9145
+ return;
9146
+ }
9147
+ reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
9148
+ request.abort();
9149
+ request = null;
9150
+ };
8889
9151
 
8890
- if (_config.cancelToken || _config.signal) {
8891
- // Handle cancellation
8892
- // eslint-disable-next-line func-names
8893
- onCanceled = cancel => {
8894
- if (!request) {
8895
- return;
9152
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
9153
+ if (_config.signal) {
9154
+ _config.signal.aborted
9155
+ ? onCanceled()
9156
+ : _config.signal.addEventListener('abort', onCanceled);
8896
9157
  }
8897
- reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
8898
- request.abort();
8899
- request = null;
8900
- };
8901
-
8902
- _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
8903
- if (_config.signal) {
8904
- _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
8905
9158
  }
8906
- }
8907
9159
 
8908
- const protocol = parseProtocol(_config.url);
8909
-
8910
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
8911
- reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
8912
- return;
8913
- }
9160
+ const protocol = parseProtocol(_config.url);
8914
9161
 
9162
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
9163
+ reject(
9164
+ new AxiosError(
9165
+ 'Unsupported protocol ' + protocol + ':',
9166
+ AxiosError.ERR_BAD_REQUEST,
9167
+ config
9168
+ )
9169
+ );
9170
+ return;
9171
+ }
8915
9172
 
8916
- // Send the request
8917
- request.send(requestData || null);
8918
- });
8919
- };
9173
+ // Send the request
9174
+ request.send(requestData || null);
9175
+ });
9176
+ };
8920
9177
 
8921
9178
  const composeSignals = (signals, timeout) => {
8922
- const {length} = (signals = signals ? signals.filter(Boolean) : []);
9179
+ const { length } = (signals = signals ? signals.filter(Boolean) : []);
8923
9180
 
8924
9181
  if (timeout || length) {
8925
9182
  let controller = new AbortController();
@@ -8931,21 +9188,29 @@ function requireAxios () {
8931
9188
  aborted = true;
8932
9189
  unsubscribe();
8933
9190
  const err = reason instanceof Error ? reason : this.reason;
8934
- controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
9191
+ controller.abort(
9192
+ err instanceof AxiosError
9193
+ ? err
9194
+ : new CanceledError(err instanceof Error ? err.message : err)
9195
+ );
8935
9196
  }
8936
9197
  };
8937
9198
 
8938
- let timer = timeout && setTimeout(() => {
8939
- timer = null;
8940
- onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT));
8941
- }, timeout);
9199
+ let timer =
9200
+ timeout &&
9201
+ setTimeout(() => {
9202
+ timer = null;
9203
+ onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
9204
+ }, timeout);
8942
9205
 
8943
9206
  const unsubscribe = () => {
8944
9207
  if (signals) {
8945
9208
  timer && clearTimeout(timer);
8946
9209
  timer = null;
8947
- signals.forEach(signal => {
8948
- signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
9210
+ signals.forEach((signal) => {
9211
+ signal.unsubscribe
9212
+ ? signal.unsubscribe(onabort)
9213
+ : signal.removeEventListener('abort', onabort);
8949
9214
  });
8950
9215
  signals = null;
8951
9216
  }
@@ -8953,7 +9218,7 @@ function requireAxios () {
8953
9218
 
8954
9219
  signals.forEach((signal) => signal.addEventListener('abort', onabort));
8955
9220
 
8956
- const {signal} = controller;
9221
+ const { signal } = controller;
8957
9222
 
8958
9223
  signal.unsubscribe = () => utils$1.asap(unsubscribe);
8959
9224
 
@@ -8961,8 +9226,6 @@ function requireAxios () {
8961
9226
  }
8962
9227
  };
8963
9228
 
8964
- var composeSignals$1 = composeSignals;
8965
-
8966
9229
  const streamChunk = function* (chunk, chunkSize) {
8967
9230
  let len = chunk.byteLength;
8968
9231
 
@@ -8996,7 +9259,7 @@ function requireAxios () {
8996
9259
  const reader = stream.getReader();
8997
9260
  try {
8998
9261
  for (;;) {
8999
- const {done, value} = await reader.read();
9262
+ const { done, value } = await reader.read();
9000
9263
  if (done) {
9001
9264
  break;
9002
9265
  }
@@ -9019,64 +9282,69 @@ function requireAxios () {
9019
9282
  }
9020
9283
  };
9021
9284
 
9022
- return new ReadableStream({
9023
- async pull(controller) {
9024
- try {
9025
- const {done, value} = await iterator.next();
9285
+ return new ReadableStream(
9286
+ {
9287
+ async pull(controller) {
9288
+ try {
9289
+ const { done, value } = await iterator.next();
9026
9290
 
9027
- if (done) {
9028
- _onFinish();
9029
- controller.close();
9030
- return;
9031
- }
9291
+ if (done) {
9292
+ _onFinish();
9293
+ controller.close();
9294
+ return;
9295
+ }
9032
9296
 
9033
- let len = value.byteLength;
9034
- if (onProgress) {
9035
- let loadedBytes = bytes += len;
9036
- onProgress(loadedBytes);
9297
+ let len = value.byteLength;
9298
+ if (onProgress) {
9299
+ let loadedBytes = (bytes += len);
9300
+ onProgress(loadedBytes);
9301
+ }
9302
+ controller.enqueue(new Uint8Array(value));
9303
+ } catch (err) {
9304
+ _onFinish(err);
9305
+ throw err;
9037
9306
  }
9038
- controller.enqueue(new Uint8Array(value));
9039
- } catch (err) {
9040
- _onFinish(err);
9041
- throw err;
9042
- }
9307
+ },
9308
+ cancel(reason) {
9309
+ _onFinish(reason);
9310
+ return iterator.return();
9311
+ },
9043
9312
  },
9044
- cancel(reason) {
9045
- _onFinish(reason);
9046
- return iterator.return();
9313
+ {
9314
+ highWaterMark: 2,
9047
9315
  }
9048
- }, {
9049
- highWaterMark: 2
9050
- })
9316
+ );
9051
9317
  };
9052
9318
 
9053
9319
  const DEFAULT_CHUNK_SIZE = 64 * 1024;
9054
9320
 
9055
- const {isFunction} = utils$1;
9321
+ const { isFunction } = utils$1;
9056
9322
 
9057
- const globalFetchAPI = (({Request, Response}) => ({
9058
- Request, Response
9323
+ const globalFetchAPI = (({ Request, Response }) => ({
9324
+ Request,
9325
+ Response,
9059
9326
  }))(utils$1.global);
9060
9327
 
9061
- const {
9062
- ReadableStream: ReadableStream$1, TextEncoder
9063
- } = utils$1.global;
9064
-
9328
+ const { ReadableStream: ReadableStream$1, TextEncoder } = utils$1.global;
9065
9329
 
9066
9330
  const test = (fn, ...args) => {
9067
9331
  try {
9068
9332
  return !!fn(...args);
9069
9333
  } catch (e) {
9070
- return false
9334
+ return false;
9071
9335
  }
9072
9336
  };
9073
9337
 
9074
9338
  const factory = (env) => {
9075
- env = utils$1.merge.call({
9076
- skipUndefined: true
9077
- }, globalFetchAPI, env);
9339
+ env = utils$1.merge.call(
9340
+ {
9341
+ skipUndefined: true,
9342
+ },
9343
+ globalFetchAPI,
9344
+ env
9345
+ );
9078
9346
 
9079
- const {fetch: envFetch, Request, Response} = env;
9347
+ const { fetch: envFetch, Request, Response } = env;
9080
9348
  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
9081
9349
  const isRequestSupported = isFunction(Request);
9082
9350
  const isResponseSupported = isFunction(Response);
@@ -9087,46 +9355,65 @@ function requireAxios () {
9087
9355
 
9088
9356
  const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
9089
9357
 
9090
- const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
9091
- ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
9092
- async (str) => new Uint8Array(await new Request(str).arrayBuffer())
9093
- );
9358
+ const encodeText =
9359
+ isFetchSupported &&
9360
+ (typeof TextEncoder === 'function'
9361
+ ? (
9362
+ (encoder) => (str) =>
9363
+ encoder.encode(str)
9364
+ )(new TextEncoder())
9365
+ : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
9094
9366
 
9095
- const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
9096
- let duplexAccessed = false;
9367
+ const supportsRequestStream =
9368
+ isRequestSupported &&
9369
+ isReadableStreamSupported &&
9370
+ test(() => {
9371
+ let duplexAccessed = false;
9097
9372
 
9098
- const hasContentType = new Request(platform.origin, {
9099
- body: new ReadableStream$1(),
9100
- method: 'POST',
9101
- get duplex() {
9102
- duplexAccessed = true;
9103
- return 'half';
9104
- },
9105
- }).headers.has('Content-Type');
9373
+ const body = new ReadableStream$1();
9106
9374
 
9107
- return duplexAccessed && !hasContentType;
9108
- });
9375
+ const hasContentType = new Request(platform.origin, {
9376
+ body,
9377
+ method: 'POST',
9378
+ get duplex() {
9379
+ duplexAccessed = true;
9380
+ return 'half';
9381
+ },
9382
+ }).headers.has('Content-Type');
9383
+
9384
+ body.cancel();
9385
+
9386
+ return duplexAccessed && !hasContentType;
9387
+ });
9109
9388
 
9110
- const supportsResponseStream = isResponseSupported && isReadableStreamSupported &&
9389
+ const supportsResponseStream =
9390
+ isResponseSupported &&
9391
+ isReadableStreamSupported &&
9111
9392
  test(() => utils$1.isReadableStream(new Response('').body));
9112
9393
 
9113
9394
  const resolvers = {
9114
- stream: supportsResponseStream && ((res) => res.body)
9395
+ stream: supportsResponseStream && ((res) => res.body),
9115
9396
  };
9116
9397
 
9117
- isFetchSupported && ((() => {
9118
- ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
9119
- !resolvers[type] && (resolvers[type] = (res, config) => {
9120
- let method = res && res[type];
9121
-
9122
- if (method) {
9123
- return method.call(res);
9124
- }
9125
-
9126
- throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
9398
+ isFetchSupported &&
9399
+ (() => {
9400
+ ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
9401
+ !resolvers[type] &&
9402
+ (resolvers[type] = (res, config) => {
9403
+ let method = res && res[type];
9404
+
9405
+ if (method) {
9406
+ return method.call(res);
9407
+ }
9408
+
9409
+ throw new AxiosError(
9410
+ `Response type '${type}' is not supported`,
9411
+ AxiosError.ERR_NOT_SUPPORT,
9412
+ config
9413
+ );
9414
+ });
9127
9415
  });
9128
- });
9129
- })());
9416
+ })();
9130
9417
 
9131
9418
  const getBodyLength = async (body) => {
9132
9419
  if (body == null) {
@@ -9177,32 +9464,41 @@ function requireAxios () {
9177
9464
  responseType,
9178
9465
  headers,
9179
9466
  withCredentials = 'same-origin',
9180
- fetchOptions
9467
+ fetchOptions,
9181
9468
  } = resolveConfig(config);
9182
9469
 
9183
9470
  let _fetch = envFetch || fetch;
9184
9471
 
9185
9472
  responseType = responseType ? (responseType + '').toLowerCase() : 'text';
9186
9473
 
9187
- let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
9474
+ let composedSignal = composeSignals(
9475
+ [signal, cancelToken && cancelToken.toAbortSignal()],
9476
+ timeout
9477
+ );
9188
9478
 
9189
9479
  let request = null;
9190
9480
 
9191
- const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
9192
- composedSignal.unsubscribe();
9193
- });
9481
+ const unsubscribe =
9482
+ composedSignal &&
9483
+ composedSignal.unsubscribe &&
9484
+ (() => {
9485
+ composedSignal.unsubscribe();
9486
+ });
9194
9487
 
9195
9488
  let requestContentLength;
9196
9489
 
9197
9490
  try {
9198
9491
  if (
9199
- onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
9492
+ onUploadProgress &&
9493
+ supportsRequestStream &&
9494
+ method !== 'get' &&
9495
+ method !== 'head' &&
9200
9496
  (requestContentLength = await resolveBodyLength(headers, data)) !== 0
9201
9497
  ) {
9202
9498
  let _request = new Request(url, {
9203
9499
  method: 'POST',
9204
9500
  body: data,
9205
- duplex: "half"
9501
+ duplex: 'half',
9206
9502
  });
9207
9503
 
9208
9504
  let contentTypeHeader;
@@ -9227,7 +9523,7 @@ function requireAxios () {
9227
9523
 
9228
9524
  // Cloudflare Workers throws when credentials are defined
9229
9525
  // see https://github.com/cloudflare/workerd/issues/902
9230
- const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
9526
+ const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
9231
9527
 
9232
9528
  const resolvedOptions = {
9233
9529
  ...fetchOptions,
@@ -9235,29 +9531,35 @@ function requireAxios () {
9235
9531
  method: method.toUpperCase(),
9236
9532
  headers: headers.normalize().toJSON(),
9237
9533
  body: data,
9238
- duplex: "half",
9239
- credentials: isCredentialsSupported ? withCredentials : undefined
9534
+ duplex: 'half',
9535
+ credentials: isCredentialsSupported ? withCredentials : undefined,
9240
9536
  };
9241
9537
 
9242
9538
  request = isRequestSupported && new Request(url, resolvedOptions);
9243
9539
 
9244
- let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
9540
+ let response = await (isRequestSupported
9541
+ ? _fetch(request, fetchOptions)
9542
+ : _fetch(url, resolvedOptions));
9245
9543
 
9246
- const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
9544
+ const isStreamResponse =
9545
+ supportsResponseStream && (responseType === 'stream' || responseType === 'response');
9247
9546
 
9248
9547
  if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
9249
9548
  const options = {};
9250
9549
 
9251
- ['status', 'statusText', 'headers'].forEach(prop => {
9550
+ ['status', 'statusText', 'headers'].forEach((prop) => {
9252
9551
  options[prop] = response[prop];
9253
9552
  });
9254
9553
 
9255
9554
  const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
9256
9555
 
9257
- const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
9258
- responseContentLength,
9259
- progressEventReducer(asyncDecorator(onDownloadProgress), true)
9260
- ) || [];
9556
+ const [onProgress, flush] =
9557
+ (onDownloadProgress &&
9558
+ progressEventDecorator(
9559
+ responseContentLength,
9560
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
9561
+ )) ||
9562
+ [];
9261
9563
 
9262
9564
  response = new Response(
9263
9565
  trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
@@ -9270,54 +9572,64 @@ function requireAxios () {
9270
9572
 
9271
9573
  responseType = responseType || 'text';
9272
9574
 
9273
- let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
9575
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](
9576
+ response,
9577
+ config
9578
+ );
9274
9579
 
9275
9580
  !isStreamResponse && unsubscribe && unsubscribe();
9276
9581
 
9277
9582
  return await new Promise((resolve, reject) => {
9278
9583
  settle(resolve, reject, {
9279
9584
  data: responseData,
9280
- headers: AxiosHeaders$1.from(response.headers),
9585
+ headers: AxiosHeaders.from(response.headers),
9281
9586
  status: response.status,
9282
9587
  statusText: response.statusText,
9283
9588
  config,
9284
- request
9589
+ request,
9285
9590
  });
9286
- })
9591
+ });
9287
9592
  } catch (err) {
9288
9593
  unsubscribe && unsubscribe();
9289
9594
 
9290
9595
  if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
9291
9596
  throw Object.assign(
9292
- new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request),
9597
+ new AxiosError(
9598
+ 'Network Error',
9599
+ AxiosError.ERR_NETWORK,
9600
+ config,
9601
+ request,
9602
+ err && err.response
9603
+ ),
9293
9604
  {
9294
- cause: err.cause || err
9605
+ cause: err.cause || err,
9295
9606
  }
9296
- )
9607
+ );
9297
9608
  }
9298
9609
 
9299
- throw AxiosError$1.from(err, err && err.code, config, request);
9610
+ throw AxiosError.from(err, err && err.code, config, request, err && err.response);
9300
9611
  }
9301
- }
9612
+ };
9302
9613
  };
9303
9614
 
9304
9615
  const seedCache = new Map();
9305
9616
 
9306
9617
  const getFetch = (config) => {
9307
9618
  let env = (config && config.env) || {};
9308
- const {fetch, Request, Response} = env;
9309
- const seeds = [
9310
- Request, Response, fetch
9311
- ];
9619
+ const { fetch, Request, Response } = env;
9620
+ const seeds = [Request, Response, fetch];
9312
9621
 
9313
- let len = seeds.length, i = len,
9314
- seed, target, map = seedCache;
9622
+ let len = seeds.length,
9623
+ i = len,
9624
+ seed,
9625
+ target,
9626
+ map = seedCache;
9315
9627
 
9316
9628
  while (i--) {
9317
9629
  seed = seeds[i];
9318
9630
  target = map.get(seed);
9319
9631
 
9320
- target === undefined && map.set(seed, target = (i ? new Map() : factory(env)));
9632
+ target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
9321
9633
 
9322
9634
  map = target;
9323
9635
  }
@@ -9333,7 +9645,7 @@ function requireAxios () {
9333
9645
  * - `http` for Node.js
9334
9646
  * - `xhr` for browsers
9335
9647
  * - `fetch` for fetch API-based requests
9336
- *
9648
+ *
9337
9649
  * @type {Object<string, Function|Object>}
9338
9650
  */
9339
9651
  const knownAdapters = {
@@ -9341,7 +9653,7 @@ function requireAxios () {
9341
9653
  xhr: xhrAdapter,
9342
9654
  fetch: {
9343
9655
  get: getFetch,
9344
- }
9656
+ },
9345
9657
  };
9346
9658
 
9347
9659
  // Assign adapter names for easier debugging and identification
@@ -9358,7 +9670,7 @@ function requireAxios () {
9358
9670
 
9359
9671
  /**
9360
9672
  * Render a rejection reason string for unknown or unsupported adapters
9361
- *
9673
+ *
9362
9674
  * @param {string} reason
9363
9675
  * @returns {string}
9364
9676
  */
@@ -9366,17 +9678,18 @@ function requireAxios () {
9366
9678
 
9367
9679
  /**
9368
9680
  * Check if the adapter is resolved (function, null, or false)
9369
- *
9681
+ *
9370
9682
  * @param {Function|null|false} adapter
9371
9683
  * @returns {boolean}
9372
9684
  */
9373
- const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
9685
+ const isResolvedHandle = (adapter) =>
9686
+ utils$1.isFunction(adapter) || adapter === null || adapter === false;
9374
9687
 
9375
9688
  /**
9376
9689
  * Get the first suitable adapter from the provided list.
9377
9690
  * Tries each adapter in order until a supported one is found.
9378
9691
  * Throws an AxiosError if no adapter is suitable.
9379
- *
9692
+ *
9380
9693
  * @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
9381
9694
  * @param {Object} config - Axios request configuration
9382
9695
  * @throws {AxiosError} If no suitable adapter is available
@@ -9401,7 +9714,7 @@ function requireAxios () {
9401
9714
  adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
9402
9715
 
9403
9716
  if (adapter === undefined) {
9404
- throw new AxiosError$1(`Unknown adapter '${id}'`);
9717
+ throw new AxiosError(`Unknown adapter '${id}'`);
9405
9718
  }
9406
9719
  }
9407
9720
 
@@ -9413,16 +9726,19 @@ function requireAxios () {
9413
9726
  }
9414
9727
 
9415
9728
  if (!adapter) {
9416
- const reasons = Object.entries(rejectedReasons)
9417
- .map(([id, state]) => `adapter ${id} ` +
9729
+ const reasons = Object.entries(rejectedReasons).map(
9730
+ ([id, state]) =>
9731
+ `adapter ${id} ` +
9418
9732
  (state === false ? 'is not supported by the environment' : 'is not available in the build')
9419
- );
9733
+ );
9420
9734
 
9421
- let s = length ?
9422
- (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
9423
- 'as no adapter specified';
9735
+ let s = length
9736
+ ? reasons.length > 1
9737
+ ? 'since :\n' + reasons.map(renderReason).join('\n')
9738
+ : ' ' + renderReason(reasons[0])
9739
+ : 'as no adapter specified';
9424
9740
 
9425
- throw new AxiosError$1(
9741
+ throw new AxiosError(
9426
9742
  `There is no suitable adapter to dispatch the request ` + s,
9427
9743
  'ERR_NOT_SUPPORT'
9428
9744
  );
@@ -9445,7 +9761,7 @@ function requireAxios () {
9445
9761
  * Exposes all known adapters
9446
9762
  * @type {Object<string, Function|Object>}
9447
9763
  */
9448
- adapters: knownAdapters
9764
+ adapters: knownAdapters,
9449
9765
  };
9450
9766
 
9451
9767
  /**
@@ -9461,7 +9777,7 @@ function requireAxios () {
9461
9777
  }
9462
9778
 
9463
9779
  if (config.signal && config.signal.aborted) {
9464
- throw new CanceledError$1(null, config);
9780
+ throw new CanceledError(null, config);
9465
9781
  }
9466
9782
  }
9467
9783
 
@@ -9475,53 +9791,49 @@ function requireAxios () {
9475
9791
  function dispatchRequest(config) {
9476
9792
  throwIfCancellationRequested(config);
9477
9793
 
9478
- config.headers = AxiosHeaders$1.from(config.headers);
9794
+ config.headers = AxiosHeaders.from(config.headers);
9479
9795
 
9480
9796
  // Transform request data
9481
- config.data = transformData.call(
9482
- config,
9483
- config.transformRequest
9484
- );
9797
+ config.data = transformData.call(config, config.transformRequest);
9485
9798
 
9486
9799
  if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
9487
9800
  config.headers.setContentType('application/x-www-form-urlencoded', false);
9488
9801
  }
9489
9802
 
9490
- const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config);
9491
-
9492
- return adapter(config).then(function onAdapterResolution(response) {
9493
- throwIfCancellationRequested(config);
9494
-
9495
- // Transform response data
9496
- response.data = transformData.call(
9497
- config,
9498
- config.transformResponse,
9499
- response
9500
- );
9501
-
9502
- response.headers = AxiosHeaders$1.from(response.headers);
9803
+ const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
9503
9804
 
9504
- return response;
9505
- }, function onAdapterRejection(reason) {
9506
- if (!isCancel(reason)) {
9805
+ return adapter(config).then(
9806
+ function onAdapterResolution(response) {
9507
9807
  throwIfCancellationRequested(config);
9508
9808
 
9509
9809
  // Transform response data
9510
- if (reason && reason.response) {
9511
- reason.response.data = transformData.call(
9512
- config,
9513
- config.transformResponse,
9514
- reason.response
9515
- );
9516
- reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
9810
+ response.data = transformData.call(config, config.transformResponse, response);
9811
+
9812
+ response.headers = AxiosHeaders.from(response.headers);
9813
+
9814
+ return response;
9815
+ },
9816
+ function onAdapterRejection(reason) {
9817
+ if (!isCancel(reason)) {
9818
+ throwIfCancellationRequested(config);
9819
+
9820
+ // Transform response data
9821
+ if (reason && reason.response) {
9822
+ reason.response.data = transformData.call(
9823
+ config,
9824
+ config.transformResponse,
9825
+ reason.response
9826
+ );
9827
+ reason.response.headers = AxiosHeaders.from(reason.response.headers);
9828
+ }
9517
9829
  }
9518
- }
9519
9830
 
9520
- return Promise.reject(reason);
9521
- });
9831
+ return Promise.reject(reason);
9832
+ }
9833
+ );
9522
9834
  }
9523
9835
 
9524
- const VERSION = "1.13.3";
9836
+ const VERSION = "1.14.0";
9525
9837
 
9526
9838
  const validators$1 = {};
9527
9839
 
@@ -9545,15 +9857,23 @@ function requireAxios () {
9545
9857
  */
9546
9858
  validators$1.transitional = function transitional(validator, version, message) {
9547
9859
  function formatMessage(opt, desc) {
9548
- return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
9860
+ return (
9861
+ '[Axios v' +
9862
+ VERSION +
9863
+ "] Transitional option '" +
9864
+ opt +
9865
+ "'" +
9866
+ desc +
9867
+ (message ? '. ' + message : '')
9868
+ );
9549
9869
  }
9550
9870
 
9551
9871
  // eslint-disable-next-line func-names
9552
9872
  return (value, opt, opts) => {
9553
9873
  if (validator === false) {
9554
- throw new AxiosError$1(
9874
+ throw new AxiosError(
9555
9875
  formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
9556
- AxiosError$1.ERR_DEPRECATED
9876
+ AxiosError.ERR_DEPRECATED
9557
9877
  );
9558
9878
  }
9559
9879
 
@@ -9577,7 +9897,7 @@ function requireAxios () {
9577
9897
  // eslint-disable-next-line no-console
9578
9898
  console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
9579
9899
  return true;
9580
- }
9900
+ };
9581
9901
  };
9582
9902
 
9583
9903
  /**
@@ -9592,7 +9912,7 @@ function requireAxios () {
9592
9912
 
9593
9913
  function assertOptions(options, schema, allowUnknown) {
9594
9914
  if (typeof options !== 'object') {
9595
- throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
9915
+ throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
9596
9916
  }
9597
9917
  const keys = Object.keys(options);
9598
9918
  let i = keys.length;
@@ -9603,19 +9923,22 @@ function requireAxios () {
9603
9923
  const value = options[opt];
9604
9924
  const result = value === undefined || validator(value, opt, options);
9605
9925
  if (result !== true) {
9606
- throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
9926
+ throw new AxiosError(
9927
+ 'option ' + opt + ' must be ' + result,
9928
+ AxiosError.ERR_BAD_OPTION_VALUE
9929
+ );
9607
9930
  }
9608
9931
  continue;
9609
9932
  }
9610
9933
  if (allowUnknown !== true) {
9611
- throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
9934
+ throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
9612
9935
  }
9613
9936
  }
9614
9937
  }
9615
9938
 
9616
9939
  var validator = {
9617
9940
  assertOptions,
9618
- validators: validators$1
9941
+ validators: validators$1,
9619
9942
  };
9620
9943
 
9621
9944
  const validators = validator.validators;
@@ -9631,8 +9954,8 @@ function requireAxios () {
9631
9954
  constructor(instanceConfig) {
9632
9955
  this.defaults = instanceConfig || {};
9633
9956
  this.interceptors = {
9634
- request: new InterceptorManager$1(),
9635
- response: new InterceptorManager$1()
9957
+ request: new InterceptorManager(),
9958
+ response: new InterceptorManager(),
9636
9959
  };
9637
9960
  }
9638
9961
 
@@ -9683,26 +10006,35 @@ function requireAxios () {
9683
10006
 
9684
10007
  config = mergeConfig(this.defaults, config);
9685
10008
 
9686
- const {transitional, paramsSerializer, headers} = config;
10009
+ const { transitional, paramsSerializer, headers } = config;
9687
10010
 
9688
10011
  if (transitional !== undefined) {
9689
- validator.assertOptions(transitional, {
9690
- silentJSONParsing: validators.transitional(validators.boolean),
9691
- forcedJSONParsing: validators.transitional(validators.boolean),
9692
- clarifyTimeoutError: validators.transitional(validators.boolean)
9693
- }, false);
10012
+ validator.assertOptions(
10013
+ transitional,
10014
+ {
10015
+ silentJSONParsing: validators.transitional(validators.boolean),
10016
+ forcedJSONParsing: validators.transitional(validators.boolean),
10017
+ clarifyTimeoutError: validators.transitional(validators.boolean),
10018
+ legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
10019
+ },
10020
+ false
10021
+ );
9694
10022
  }
9695
10023
 
9696
10024
  if (paramsSerializer != null) {
9697
10025
  if (utils$1.isFunction(paramsSerializer)) {
9698
10026
  config.paramsSerializer = {
9699
- serialize: paramsSerializer
10027
+ serialize: paramsSerializer,
9700
10028
  };
9701
10029
  } else {
9702
- validator.assertOptions(paramsSerializer, {
9703
- encode: validators.function,
9704
- serialize: validators.function
9705
- }, true);
10030
+ validator.assertOptions(
10031
+ paramsSerializer,
10032
+ {
10033
+ encode: validators.function,
10034
+ serialize: validators.function,
10035
+ },
10036
+ true
10037
+ );
9706
10038
  }
9707
10039
  }
9708
10040
 
@@ -9713,28 +10045,27 @@ function requireAxios () {
9713
10045
  config.allowAbsoluteUrls = true;
9714
10046
  }
9715
10047
 
9716
- validator.assertOptions(config, {
9717
- baseUrl: validators.spelling('baseURL'),
9718
- withXsrfToken: validators.spelling('withXSRFToken')
9719
- }, true);
10048
+ validator.assertOptions(
10049
+ config,
10050
+ {
10051
+ baseUrl: validators.spelling('baseURL'),
10052
+ withXsrfToken: validators.spelling('withXSRFToken'),
10053
+ },
10054
+ true
10055
+ );
9720
10056
 
9721
10057
  // Set config.method
9722
10058
  config.method = (config.method || this.defaults.method || 'get').toLowerCase();
9723
10059
 
9724
10060
  // Flatten headers
9725
- let contextHeaders = headers && utils$1.merge(
9726
- headers.common,
9727
- headers[config.method]
9728
- );
10061
+ let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
9729
10062
 
9730
- headers && utils$1.forEach(
9731
- ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
9732
- (method) => {
10063
+ headers &&
10064
+ utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], (method) => {
9733
10065
  delete headers[method];
9734
- }
9735
- );
10066
+ });
9736
10067
 
9737
- config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
10068
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
9738
10069
 
9739
10070
  // filter out skipped interceptors
9740
10071
  const requestInterceptorChain = [];
@@ -9746,7 +10077,15 @@ function requireAxios () {
9746
10077
 
9747
10078
  synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
9748
10079
 
9749
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
10080
+ const transitional = config.transitional || transitionalDefaults;
10081
+ const legacyInterceptorReqResOrdering =
10082
+ transitional && transitional.legacyInterceptorReqResOrdering;
10083
+
10084
+ if (legacyInterceptorReqResOrdering) {
10085
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
10086
+ } else {
10087
+ requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
10088
+ }
9750
10089
  });
9751
10090
 
9752
10091
  const responseInterceptorChain = [];
@@ -9766,13 +10105,8 @@ function requireAxios () {
9766
10105
 
9767
10106
  promise = Promise.resolve(config);
9768
10107
 
9769
- let prevResult = config;
9770
10108
  while (i < len) {
9771
- promise = promise
9772
- .then(chain[i++])
9773
- .then(result => { prevResult = result !== undefined ? result : prevResult; })
9774
- .catch(chain[i++])
9775
- .then(() => prevResult);
10109
+ promise = promise.then(chain[i++], chain[i++]);
9776
10110
  }
9777
10111
 
9778
10112
  return promise;
@@ -9803,7 +10137,7 @@ function requireAxios () {
9803
10137
  len = responseInterceptorChain.length;
9804
10138
 
9805
10139
  while (i < len) {
9806
- promise = promise.then(responseInterceptorChain[i++]).catch(responseInterceptorChain[i++]);
10140
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
9807
10141
  }
9808
10142
 
9809
10143
  return promise;
@@ -9819,28 +10153,32 @@ function requireAxios () {
9819
10153
  // Provide aliases for supported request methods
9820
10154
  utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
9821
10155
  /*eslint func-names:0*/
9822
- Axios.prototype[method] = function(url, config) {
9823
- return this.request(mergeConfig(config || {}, {
9824
- method,
9825
- url,
9826
- data: (config || {}).data
9827
- }));
10156
+ Axios.prototype[method] = function (url, config) {
10157
+ return this.request(
10158
+ mergeConfig(config || {}, {
10159
+ method,
10160
+ url,
10161
+ data: (config || {}).data,
10162
+ })
10163
+ );
9828
10164
  };
9829
10165
  });
9830
10166
 
9831
10167
  utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
9832
- /*eslint func-names:0*/
9833
-
9834
10168
  function generateHTTPMethod(isForm) {
9835
10169
  return function httpMethod(url, data, config) {
9836
- return this.request(mergeConfig(config || {}, {
9837
- method,
9838
- headers: isForm ? {
9839
- 'Content-Type': 'multipart/form-data'
9840
- } : {},
9841
- url,
9842
- data
9843
- }));
10170
+ return this.request(
10171
+ mergeConfig(config || {}, {
10172
+ method,
10173
+ headers: isForm
10174
+ ? {
10175
+ 'Content-Type': 'multipart/form-data',
10176
+ }
10177
+ : {},
10178
+ url,
10179
+ data,
10180
+ })
10181
+ );
9844
10182
  };
9845
10183
  }
9846
10184
 
@@ -9849,8 +10187,6 @@ function requireAxios () {
9849
10187
  Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
9850
10188
  });
9851
10189
 
9852
- var Axios$1 = Axios;
9853
-
9854
10190
  /**
9855
10191
  * A `CancelToken` is an object that can be used to request cancellation of an operation.
9856
10192
  *
@@ -9873,7 +10209,7 @@ function requireAxios () {
9873
10209
  const token = this;
9874
10210
 
9875
10211
  // eslint-disable-next-line func-names
9876
- this.promise.then(cancel => {
10212
+ this.promise.then((cancel) => {
9877
10213
  if (!token._listeners) return;
9878
10214
 
9879
10215
  let i = token._listeners.length;
@@ -9885,10 +10221,10 @@ function requireAxios () {
9885
10221
  });
9886
10222
 
9887
10223
  // eslint-disable-next-line func-names
9888
- this.promise.then = onfulfilled => {
10224
+ this.promise.then = (onfulfilled) => {
9889
10225
  let _resolve;
9890
10226
  // eslint-disable-next-line func-names
9891
- const promise = new Promise(resolve => {
10227
+ const promise = new Promise((resolve) => {
9892
10228
  token.subscribe(resolve);
9893
10229
  _resolve = resolve;
9894
10230
  }).then(onfulfilled);
@@ -9906,7 +10242,7 @@ function requireAxios () {
9906
10242
  return;
9907
10243
  }
9908
10244
 
9909
- token.reason = new CanceledError$1(message, config, request);
10245
+ token.reason = new CanceledError(message, config, request);
9910
10246
  resolvePromise(token.reason);
9911
10247
  });
9912
10248
  }
@@ -9976,13 +10312,11 @@ function requireAxios () {
9976
10312
  });
9977
10313
  return {
9978
10314
  token,
9979
- cancel
10315
+ cancel,
9980
10316
  };
9981
10317
  }
9982
10318
  }
9983
10319
 
9984
- var CancelToken$1 = CancelToken;
9985
-
9986
10320
  /**
9987
10321
  * Syntactic sugar for invoking a function and expanding an array for arguments.
9988
10322
  *
@@ -10018,7 +10352,7 @@ function requireAxios () {
10018
10352
  * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
10019
10353
  */
10020
10354
  function isAxiosError(payload) {
10021
- return utils$1.isObject(payload) && (payload.isAxiosError === true);
10355
+ return utils$1.isObject(payload) && payload.isAxiosError === true;
10022
10356
  }
10023
10357
 
10024
10358
  const HttpStatusCode = {
@@ -10097,8 +10431,6 @@ function requireAxios () {
10097
10431
  HttpStatusCode[value] = key;
10098
10432
  });
10099
10433
 
10100
- var HttpStatusCode$1 = HttpStatusCode;
10101
-
10102
10434
  /**
10103
10435
  * Create an instance of Axios
10104
10436
  *
@@ -10107,14 +10439,14 @@ function requireAxios () {
10107
10439
  * @returns {Axios} A new instance of Axios
10108
10440
  */
10109
10441
  function createInstance(defaultConfig) {
10110
- const context = new Axios$1(defaultConfig);
10111
- const instance = bind(Axios$1.prototype.request, context);
10442
+ const context = new Axios(defaultConfig);
10443
+ const instance = bind(Axios.prototype.request, context);
10112
10444
 
10113
10445
  // Copy axios.prototype to instance
10114
- utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
10446
+ utils$1.extend(instance, Axios.prototype, context, { allOwnKeys: true });
10115
10447
 
10116
10448
  // Copy context to instance
10117
- utils$1.extend(instance, context, null, {allOwnKeys: true});
10449
+ utils$1.extend(instance, context, null, { allOwnKeys: true });
10118
10450
 
10119
10451
  // Factory for creating new instances
10120
10452
  instance.create = function create(instanceConfig) {
@@ -10125,20 +10457,20 @@ function requireAxios () {
10125
10457
  }
10126
10458
 
10127
10459
  // Create the default instance to be exported
10128
- const axios = createInstance(defaults$1);
10460
+ const axios = createInstance(defaults);
10129
10461
 
10130
10462
  // Expose Axios class to allow class inheritance
10131
- axios.Axios = Axios$1;
10463
+ axios.Axios = Axios;
10132
10464
 
10133
10465
  // Expose Cancel & CancelToken
10134
- axios.CanceledError = CanceledError$1;
10135
- axios.CancelToken = CancelToken$1;
10466
+ axios.CanceledError = CanceledError;
10467
+ axios.CancelToken = CancelToken;
10136
10468
  axios.isCancel = isCancel;
10137
10469
  axios.VERSION = VERSION;
10138
10470
  axios.toFormData = toFormData;
10139
10471
 
10140
10472
  // Expose AxiosError class
10141
- axios.AxiosError = AxiosError$1;
10473
+ axios.AxiosError = AxiosError;
10142
10474
 
10143
10475
  // alias for CanceledError for backward compatibility
10144
10476
  axios.Cancel = axios.CanceledError;
@@ -10156,13 +10488,13 @@ function requireAxios () {
10156
10488
  // Expose mergeConfig
10157
10489
  axios.mergeConfig = mergeConfig;
10158
10490
 
10159
- axios.AxiosHeaders = AxiosHeaders$1;
10491
+ axios.AxiosHeaders = AxiosHeaders;
10160
10492
 
10161
- axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
10493
+ axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
10162
10494
 
10163
10495
  axios.getAdapter = adapters.getAdapter;
10164
10496
 
10165
- axios.HttpStatusCode = HttpStatusCode$1;
10497
+ axios.HttpStatusCode = HttpStatusCode;
10166
10498
 
10167
10499
  axios.default = axios;
10168
10500
 
@@ -11305,7 +11637,7 @@ const defaultConfig = {
11305
11637
  dontSend: false,
11306
11638
  disableUserIds: false,
11307
11639
  ipPolicy: "keep",
11308
- consentCategories: undefined,
11640
+ consentCategories: {},
11309
11641
  },
11310
11642
  };
11311
11643
  // mergeConfig merges newConfig into currentConfig also making sure that all undefined values are replaced with defaultConfig values
@@ -11314,11 +11646,14 @@ const mergeConfig = (current, newConfig) => {
11314
11646
  const value = newConfig[key];
11315
11647
  if (key === "privacy") {
11316
11648
  if (typeof value === "object") {
11317
- current.privacy = Object.assign(Object.assign(Object.assign({}, defaultConfig.privacy), current.privacy), value);
11649
+ current.privacy = Object.assign(Object.assign(Object.assign(Object.assign({}, defaultConfig.privacy), { consentCategories: Object.assign({}, defaultConfig.privacy.consentCategories) }), current.privacy), value);
11318
11650
  }
11319
- else if (newConfig.hasOwnProperty("privacy") && typeof value === "undefined") {
11320
- // explicitly set to undefined - reset to default
11321
- current.privacy = Object.assign({}, defaultConfig.privacy);
11651
+ else if (typeof value === "undefined") {
11652
+ if (newConfig.hasOwnProperty("privacy") || !current.hasOwnProperty("privacy")) {
11653
+ // explicitly set to undefined - reset to default
11654
+ // or was not set at all - set to default
11655
+ current.privacy = Object.assign(Object.assign({}, defaultConfig.privacy), { consentCategories: Object.assign({}, defaultConfig.privacy.consentCategories) });
11656
+ }
11322
11657
  }
11323
11658
  }
11324
11659
  else if (typeof value === "undefined") {
@@ -11393,6 +11728,19 @@ function getClientIds(runtime, customCookieCapture) {
11393
11728
  }, {});
11394
11729
  return Object.assign(Object.assign({}, clientIds), getGa4Ids(runtime));
11395
11730
  }
11731
+ function parseGa4SessionId(cookieValue) {
11732
+ if (typeof cookieValue !== "string") {
11733
+ return undefined;
11734
+ }
11735
+ if (cookieValue.startsWith("GA1") || cookieValue.startsWith("GS1")) {
11736
+ return cookieValue.split(".")[2];
11737
+ }
11738
+ else {
11739
+ // parse new GA4 cookie format, e.g.: GS2.1.s1747323152$o28$g0$t1747323152$j60$l0$h69286059
11740
+ const match = cookieValue.match(/^GS\d+\.\d+\.(?:[\w_-]+[$])*s(\d+)(?:$|[$])/);
11741
+ return match ? match[1] : undefined;
11742
+ }
11743
+ }
11396
11744
  function getGa4Ids(runtime) {
11397
11745
  var _a;
11398
11746
  const allCookies = runtime.getCookies();
@@ -11401,14 +11749,11 @@ function getGa4Ids(runtime) {
11401
11749
  const sessionIds = gaSessionCookies.length > 0
11402
11750
  ? Object.fromEntries(gaSessionCookies
11403
11751
  .map(([key, value]) => {
11404
- if (typeof value !== "string") {
11405
- return null;
11406
- }
11407
- const parts = value.split(".");
11408
- if (parts.length < 3) {
11752
+ const sessionId = parseGa4SessionId(value);
11753
+ if (!sessionId) {
11409
11754
  return null;
11410
11755
  }
11411
- return [key.substring("_ga_".length), parts[2]];
11756
+ return [key.substring("_ga_".length), sessionId];
11412
11757
  })
11413
11758
  .filter(v => v !== null))
11414
11759
  : undefined;
@@ -11632,6 +11977,15 @@ const emptyRuntime = (config) => ({
11632
11977
  return undefined;
11633
11978
  },
11634
11979
  });
11980
+ function deepCopy(o) {
11981
+ if (typeof o !== "object") {
11982
+ return o;
11983
+ }
11984
+ if (!o) {
11985
+ return o;
11986
+ }
11987
+ return JSON.parse(JSON.stringify(o));
11988
+ }
11635
11989
  function deepMerge(target, source) {
11636
11990
  if (typeof source !== "object" || source === null) {
11637
11991
  return source;
@@ -11668,17 +12022,46 @@ function urlPath(url) {
11668
12022
  const pathMatch = matches && matches[3] ? matches[3].split("?")[0].replace(hashRegex, "") : "";
11669
12023
  return "/" + pathMatch;
11670
12024
  }
12025
+ function canonicalUrl() {
12026
+ if (!isInBrowser())
12027
+ return;
12028
+ const tags = document.getElementsByTagName("link");
12029
+ for (var i = 0, tag; (tag = tags[i]); i++) {
12030
+ if (tag.getAttribute("rel") === "canonical") {
12031
+ return tag.getAttribute("href");
12032
+ }
12033
+ }
12034
+ }
12035
+ /**
12036
+ * bugged analytics.js logic that produces 'url' parameter by concating canonical URL with current search part
12037
+ * I produces broken results in some cases like SPA where path is changed but canonical URL is not updated
12038
+ */
12039
+ function analyticsJsUrl() {
12040
+ if (!isInBrowser())
12041
+ return;
12042
+ const canonical = canonicalUrl();
12043
+ if (!canonical)
12044
+ return window.location.href.replace(hashRegex, "");
12045
+ return canonical.match(/\?/) ? canonical : canonical + window.location.search;
12046
+ }
11671
12047
  function adjustPayload(payload, config, storage, s2s) {
11672
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
12048
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
11673
12049
  const runtime = config.runtime || (isInBrowser() ? windowRuntime(config) : emptyRuntime(config));
11674
12050
  const url = runtime.pageUrl();
11675
12051
  const parsedUrl = safeCall$1(() => new URL(url), undefined);
11676
12052
  const query = parsedUrl ? parseQuery(parsedUrl.search) : {};
11677
12053
  const properties = payload.properties || {};
11678
12054
  if (payload.type === "page" && (properties.url || url)) {
11679
- const targetUrl = properties.url || url;
12055
+ // we don't trust analytics.js URL logic since it's sticks with canonical URL on SPA pages
12056
+ let targetUrl = url || properties.url;
12057
+ if (properties.url && properties.url !== analyticsJsUrl()) {
12058
+ // properties.url is not the same as provided by analytics.js
12059
+ // it means that it was not overridden by user and we should use it
12060
+ targetUrl = properties.url;
12061
+ }
11680
12062
  properties.url = targetUrl.replace(hashRegex, "");
11681
12063
  properties.path = fixPath(urlPath(targetUrl));
12064
+ // other properties are correctly based on window.location in analytics.js
11682
12065
  }
11683
12066
  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) || {});
11684
12067
  (_c = payload.properties) === null || _c === void 0 ? true : delete _c.context;
@@ -11689,17 +12072,17 @@ function adjustPayload(payload, config, storage, s2s) {
11689
12072
  version: jitsuVersion,
11690
12073
  env: isInBrowser() ? "browser" : "node",
11691
12074
  },
11692
- consent: ((_d = config.privacy) === null || _d === void 0 ? void 0 : _d.consentCategories)
12075
+ 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
11693
12076
  ? {
11694
12077
  categoryPreferences: config.privacy.consentCategories,
11695
12078
  }
11696
12079
  : undefined,
11697
- userAgent: (_e = runtime.userAgent) === null || _e === void 0 ? void 0 : _e.call(runtime),
11698
- locale: (_f = runtime.language) === null || _f === void 0 ? void 0 : _f.call(runtime),
11699
- screen: (_g = runtime.screen) === null || _g === void 0 ? void 0 : _g.call(runtime),
11700
- ip: (_h = runtime === null || runtime === void 0 ? void 0 : runtime.ip) === null || _h === void 0 ? void 0 : _h.call(runtime),
12080
+ userAgent: (_f = runtime.userAgent) === null || _f === void 0 ? void 0 : _f.call(runtime),
12081
+ locale: (_g = runtime.language) === null || _g === void 0 ? void 0 : _g.call(runtime),
12082
+ screen: (_h = runtime.screen) === null || _h === void 0 ? void 0 : _h.call(runtime),
12083
+ ip: (_j = runtime === null || runtime === void 0 ? void 0 : runtime.ip) === null || _j === void 0 ? void 0 : _j.call(runtime),
11701
12084
  traits: payload.type != "identify" && payload.type != "group"
11702
- ? 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,
12085
+ ? 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,
11703
12086
  page: {
11704
12087
  path: properties.path || (parsedUrl && parsedUrl.pathname),
11705
12088
  referrer: referrer,
@@ -11710,13 +12093,13 @@ function adjustPayload(payload, config, storage, s2s) {
11710
12093
  url: properties.url || url,
11711
12094
  encoding: properties.encoding || runtime.documentEncoding(),
11712
12095
  },
11713
- clientIds: !((_k = config.privacy) === null || _k === void 0 ? void 0 : _k.disableUserIds) ? getClientIds(runtime, config.cookieCapture) : undefined,
12096
+ clientIds: !((_l = config.privacy) === null || _l === void 0 ? void 0 : _l.disableUserIds) ? getClientIds(runtime, config.cookieCapture) : undefined,
11714
12097
  campaign: parseUtms(query),
11715
12098
  };
11716
- 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) });
12099
+ 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) });
11717
12100
  delete withContext.meta;
11718
12101
  delete withContext.options;
11719
- if ((_p = config.privacy) === null || _p === void 0 ? void 0 : _p.disableUserIds) {
12102
+ if ((_q = config.privacy) === null || _q === void 0 ? void 0 : _q.disableUserIds) {
11720
12103
  delete withContext.userId;
11721
12104
  delete withContext.anonymousId;
11722
12105
  delete withContext.context.traits;
@@ -11732,15 +12115,18 @@ function processDestinations(destinations, method, originalEvent, debug, analyti
11732
12115
  return __awaiter$1(this, void 0, void 0, function* () {
11733
12116
  const promises = [];
11734
12117
  for (const destination of destinations) {
11735
- let newEvents = [originalEvent];
12118
+ let newEvents = [];
11736
12119
  if (destination.newEvents) {
11737
12120
  try {
11738
- newEvents = destination.newEvents.map(e => e === "same" ? originalEvent : isDiff(e) ? diff.patch(originalEvent, e.__diff) : e);
12121
+ newEvents = destination.newEvents.map(e => e === "same" ? deepCopy(originalEvent) : isDiff(e) ? diff.patch(deepCopy(originalEvent), e.__diff) : e);
11739
12122
  }
11740
12123
  catch (e) {
11741
12124
  console.error(`[JITSU] Error applying '${destination.id}' changes to event: ${e === null || e === void 0 ? void 0 : e.message}`, e);
11742
12125
  }
11743
12126
  }
12127
+ else {
12128
+ newEvents = [deepCopy(originalEvent)];
12129
+ }
11744
12130
  const credentials = Object.assign(Object.assign({}, destination.credentials), destination.options);
11745
12131
  if (destination.deviceOptions.type === "internal-plugin") {
11746
12132
  const plugin = internalDestinationPlugins[destination.deviceOptions.name];
@@ -12286,6 +12672,9 @@ function createUnderlyingAnalyticsInstance(opts, rt, plugins = []) {
12286
12672
  //However, since returned values are used for debugging purposes only, it's ok
12287
12673
  return results[0];
12288
12674
  });
12675
+ },
12676
+ getConfiguration() {
12677
+ return opts;
12289
12678
  } });
12290
12679
  if (((_b = opts.privacy) === null || _b === void 0 ? void 0 : _b.disableUserIds) || ((_c = opts.privacy) === null || _c === void 0 ? void 0 : _c.dontSend)) {
12291
12680
  storage.reset();
@@ -12331,7 +12720,7 @@ function jitsuAnalytics(_opts) {
12331
12720
  // }
12332
12721
  }
12333
12722
 
12334
- 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"));
12723
+ 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"));
12335
12724
 
12336
12725
  var lazyload_min$1 = {exports: {}};
12337
12726