@salla.sa/twilight-components 2.14.393 → 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 (555) hide show
  1. package/dist/cjs/{filepond-D7RVR_w_.js → filepond-C_gLbAbF.js} +1 -1
  2. package/dist/cjs/{filepond-plugin-file-poster-DTuZK2ot.js → filepond-plugin-file-poster-DXWo2FUU.js} +2 -2
  3. package/dist/cjs/{filepond-plugin-file-validate-size-DHc6pF_j.js → filepond-plugin-file-validate-size-fBXMP7ez.js} +1 -1
  4. package/dist/cjs/{filepond-plugin-file-validate-type-DnkcvJVc.js → filepond-plugin-file-validate-type-DEo7juC7.js} +1 -1
  5. package/dist/cjs/{filepond-plugin-image-edit-vrZ1s7kw.js → filepond-plugin-image-edit-4j4e1VEp.js} +1 -1
  6. package/dist/cjs/{filepond-plugin-image-exif-orientation-Bn5JSzQK.js → filepond-plugin-image-exif-orientation-DWqiXxv1.js} +1 -1
  7. package/dist/cjs/{filepond-plugin-image-preview-8qWUFe9n.js → filepond-plugin-image-preview-emT_teia.js} +1 -1
  8. package/dist/cjs/{index-C5VeFDQ0.js → index-B03mYCWz.js} +547 -780
  9. package/dist/cjs/{index-CwD81m7i.js → index-Y-2uyQDK.js} +1 -1
  10. package/dist/cjs/loader.cjs.js +3 -4
  11. package/dist/cjs/salla-accordion-body_2.cjs.entry.js +5 -5
  12. package/dist/cjs/salla-accordion_6.cjs.entry.js +15 -19
  13. package/dist/cjs/salla-add-product-button_4.cjs.entry.js +10 -12
  14. package/dist/cjs/salla-advertisement.cjs.entry.js +3 -3
  15. package/dist/cjs/salla-alert_2.cjs.entry.js +5 -5
  16. package/dist/cjs/salla-app-install-alert.cjs.entry.js +3 -3
  17. package/dist/cjs/salla-apps-icons.cjs.entry.js +3 -3
  18. package/dist/cjs/salla-booking-field_7.cjs.entry.js +23 -25
  19. package/dist/cjs/salla-bullet-delivery.cjs.entry.js +3 -3
  20. package/dist/cjs/salla-cart-coupons.cjs.entry.js +3 -3
  21. package/dist/cjs/salla-cart-item-offers_2.cjs.entry.js +5 -5
  22. package/dist/cjs/salla-comment-form_8.cjs.entry.js +17 -17
  23. package/dist/cjs/salla-conditional-offer.cjs.entry.js +3 -3
  24. package/dist/cjs/salla-contacts.cjs.entry.js +3 -3
  25. package/dist/cjs/salla-cookies-bar.cjs.entry.js +3 -3
  26. package/dist/cjs/salla-count-down.cjs.entry.js +3 -3
  27. package/dist/cjs/salla-custom-fields.cjs.entry.js +3 -3
  28. package/dist/cjs/salla-delivery-promise.cjs.entry.js +1 -1
  29. package/dist/cjs/salla-filters-widget.cjs.entry.js +3 -3
  30. package/dist/cjs/salla-filters.cjs.entry.js +3 -3
  31. package/dist/cjs/salla-fulfillment-methods.cjs.entry.js +1 -1
  32. package/dist/cjs/salla-gifting.cjs.entry.js +3 -3
  33. package/dist/cjs/salla-hook.cjs.entry.js +2 -5
  34. package/dist/cjs/salla-infinite-scroll.cjs.entry.js +3 -3
  35. package/dist/cjs/salla-installment.cjs.entry.js +3 -3
  36. package/dist/cjs/salla-list-tile.cjs.entry.js +3 -3
  37. package/dist/cjs/salla-localization-modal.cjs.entry.js +1 -1
  38. package/dist/cjs/salla-login-modal.cjs.entry.js +3 -3
  39. package/dist/cjs/salla-loyalty-prize-item.cjs.entry.js +3 -3
  40. package/dist/cjs/salla-loyalty-program.cjs.entry.js +3 -3
  41. package/dist/cjs/salla-loyalty.cjs.entry.js +3 -3
  42. package/dist/cjs/salla-maintenance-alert.cjs.entry.js +3 -3
  43. package/dist/cjs/salla-map.cjs.entry.js +3 -3
  44. package/dist/cjs/salla-menu.cjs.entry.js +3 -3
  45. package/dist/cjs/salla-metadata.cjs.entry.js +3 -3
  46. package/dist/cjs/salla-multiple-bundle-product-cart_2.cjs.entry.js +5 -5
  47. package/dist/cjs/salla-multiple-bundle-product-options-modal_2.cjs.entry.js +6 -8
  48. package/dist/cjs/salla-multiple-bundle-product.cjs.entry.js +4 -6
  49. package/dist/cjs/salla-notification-item.cjs.entry.js +3 -3
  50. package/dist/cjs/salla-notifications.cjs.entry.js +3 -3
  51. package/dist/cjs/salla-offer-modal.cjs.entry.js +3 -3
  52. package/dist/cjs/salla-offer.cjs.entry.js +3 -3
  53. package/dist/cjs/salla-order-details-multiple-bundle-product.cjs.entry.js +3 -3
  54. package/dist/cjs/salla-order-details-options.cjs.entry.js +3 -3
  55. package/dist/cjs/salla-order-details.cjs.entry.js +4 -6
  56. package/dist/cjs/salla-order-edit-item.cjs.entry.js +3 -3
  57. package/dist/cjs/salla-order-edit.cjs.entry.js +3 -3
  58. package/dist/cjs/salla-order-summary.cjs.entry.js +3 -3
  59. package/dist/cjs/salla-order-totals-card.cjs.entry.js +4 -6
  60. package/dist/cjs/salla-orders.cjs.entry.js +3 -3
  61. package/dist/cjs/salla-payments.cjs.entry.js +3 -3
  62. package/dist/cjs/salla-placeholder.cjs.entry.js +3 -3
  63. package/dist/cjs/salla-price-range.cjs.entry.js +3 -3
  64. package/dist/cjs/salla-product-card.cjs.entry.js +3 -3
  65. package/dist/cjs/salla-product-size-guide.cjs.entry.js +3 -3
  66. package/dist/cjs/salla-products-list.cjs.entry.js +3 -3
  67. package/dist/cjs/salla-products-slider.cjs.entry.js +3 -3
  68. package/dist/cjs/salla-progress-bar.cjs.entry.js +3 -3
  69. package/dist/cjs/salla-quick-order.cjs.entry.js +3 -3
  70. package/dist/cjs/salla-rating-modal.cjs.entry.js +3 -3
  71. package/dist/cjs/salla-scopes.cjs.entry.js +3 -3
  72. package/dist/cjs/salla-search.cjs.entry.js +4 -6
  73. package/dist/cjs/salla-skeleton.cjs.entry.js +3 -3
  74. package/dist/cjs/salla-slider.cjs.entry.js +3 -3
  75. package/dist/cjs/salla-social-share.cjs.entry.js +3 -3
  76. package/dist/cjs/salla-social.cjs.entry.js +3 -3
  77. package/dist/cjs/salla-tab-content_3.cjs.entry.js +7 -7
  78. package/dist/cjs/salla-tiered-offer.cjs.entry.js +3 -3
  79. package/dist/cjs/salla-tooltip.cjs.entry.js +3 -3
  80. package/dist/cjs/salla-trust-badges.cjs.entry.js +3 -3
  81. package/dist/cjs/salla-user-menu.cjs.entry.js +3 -3
  82. package/dist/cjs/salla-user-profile.cjs.entry.js +3 -3
  83. package/dist/cjs/salla-user-settings.cjs.entry.js +3 -3
  84. package/dist/cjs/salla-verify.cjs.entry.js +3 -3
  85. package/dist/cjs/salla-wallet.cjs.entry.js +3 -3
  86. package/dist/cjs/twilight.cjs.js +4 -5
  87. package/dist/cjs/{vanilla-picker-yKERbLpx.js → vanilla-picker-CKZvBtHS.js} +1 -1
  88. package/dist/collection/collection-manifest.json +2 -3
  89. package/dist/collection/components/salla-accordion/salla-accordion-head.js +2 -2
  90. package/dist/collection/components/salla-accordion/salla-accordion.js +4 -4
  91. package/dist/collection/components/salla-add-product-button/salla-add-product-button.js +19 -19
  92. package/dist/collection/components/salla-alert/salla-alert.js +5 -5
  93. package/dist/collection/components/salla-apps-icons/salla-apps-icons.js +6 -6
  94. package/dist/collection/components/salla-booking-field/salla-booking-field.js +4 -4
  95. package/dist/collection/components/salla-bottom-alert/salla-bottom-alert.js +9 -9
  96. package/dist/collection/components/salla-bullet-delivery/salla-bullet-delivery.js +3 -6
  97. package/dist/collection/components/salla-button/salla-button.js +11 -11
  98. package/dist/collection/components/salla-cart-coupons/salla-cart-coupons.js +1 -2
  99. package/dist/collection/components/salla-cart-item-offers/salla-cart-item-offers.js +8 -8
  100. package/dist/collection/components/salla-cart-summary/salla-cart-summary.js +2 -2
  101. package/dist/collection/components/salla-color-picker/salla-color-picker.js +14 -20
  102. package/dist/collection/components/salla-comment-form/salla-comment-form.js +6 -6
  103. package/dist/collection/components/salla-comments/salla-comment-item.js +3 -2
  104. package/dist/collection/components/salla-comments/salla-comments.js +17 -18
  105. package/dist/collection/components/salla-contacts/salla-contacts.js +10 -10
  106. package/dist/collection/components/salla-count-down/salla-count-down.js +34 -34
  107. package/dist/collection/components/salla-custom-fields/salla-custom-fields.js +7 -9
  108. package/dist/collection/components/salla-datetime-picker/salla-datetime-picker.js +65 -69
  109. package/dist/collection/components/salla-drawer/salla-drawer.js +11 -11
  110. package/dist/collection/components/salla-file-upload/salla-file-upload.js +84 -85
  111. package/dist/collection/components/salla-filters/salla-filters.js +2 -2
  112. package/dist/collection/components/salla-filters-widget/salla-filters-widget.js +5 -4
  113. package/dist/collection/components/salla-gifting/salla-gifting.js +11 -11
  114. package/dist/collection/components/salla-hook/salla-hook.js +2 -2
  115. package/dist/collection/components/salla-infinite-scroll/salla-infinite-scroll.js +6 -6
  116. package/dist/collection/components/salla-installment/salla-installment.js +5 -5
  117. package/dist/collection/components/salla-list-tile/salla-list-tile.js +2 -2
  118. package/dist/collection/components/salla-loading/salla-loading.js +4 -4
  119. package/dist/collection/components/salla-localization-modal/salla-localization-modal.js +5 -5
  120. package/dist/collection/components/salla-login-modal/salla-login-modal.js +14 -14
  121. package/dist/collection/components/salla-loyalty/salla-loyalty-prize-item.js +3 -4
  122. package/dist/collection/components/salla-loyalty/salla-loyalty.js +12 -13
  123. package/dist/collection/components/salla-map/salla-map.js +14 -14
  124. package/dist/collection/components/salla-menu/salla-menu.js +9 -10
  125. package/dist/collection/components/salla-metadata/salla-metadata.js +3 -3
  126. package/dist/collection/components/salla-modal/salla-modal.js +11 -11
  127. package/dist/collection/components/salla-multiple-bundle-product/components/salla-multiple-bundle-product-cart.js +2 -2
  128. package/dist/collection/components/salla-multiple-bundle-product/components/salla-multiple-bundle-product-details.js +2 -2
  129. package/dist/collection/components/salla-multiple-bundle-product/components/salla-multiple-bundle-product-options-modal.js +2 -4
  130. package/dist/collection/components/salla-multiple-bundle-product/components/salla-multiple-bundle-product-slider.js +7 -8
  131. package/dist/collection/components/salla-multiple-bundle-product/salla-multiple-bundle-product.js +2 -2
  132. package/dist/collection/components/salla-notifications/salla-notification-item.js +2 -2
  133. package/dist/collection/components/salla-notifications/salla-notifications.js +3 -3
  134. package/dist/collection/components/salla-offer/salla-offer.js +1 -1
  135. package/dist/collection/components/salla-order-details/salla-order-details-multiple-bundle-product.js +5 -5
  136. package/dist/collection/components/salla-order-details/salla-order-details-options.js +5 -6
  137. package/dist/collection/components/salla-order-details/salla-order-details.js +3 -4
  138. package/dist/collection/components/salla-order-edit/salla-order-edit-item.js +4 -4
  139. package/dist/collection/components/salla-order-edit/salla-order-edit.js +4 -4
  140. package/dist/collection/components/salla-order-summary/salla-order-summary.js +2 -2
  141. package/dist/collection/components/salla-order-totals-card/salla-order-totals-card.js +3 -4
  142. package/dist/collection/components/salla-orders/salla-orders.js +4 -4
  143. package/dist/collection/components/salla-payments/salla-payments.js +1 -0
  144. package/dist/collection/components/salla-placeholder/salla-placeholder.js +3 -3
  145. package/dist/collection/components/salla-price-range/salla-price-range.js +8 -8
  146. package/dist/collection/components/salla-product-availability/salla-product-availability.js +6 -6
  147. package/dist/collection/components/salla-product-card/salla-product-card.js +18 -18
  148. package/dist/collection/components/salla-product-options/salla-product-options.js +13 -15
  149. package/dist/collection/components/salla-products-list/salla-products-list.js +21 -20
  150. package/dist/collection/components/salla-products-slider/salla-products-slider.js +23 -22
  151. package/dist/collection/components/salla-progress-bar/salla-progress-bar.js +20 -21
  152. package/dist/collection/components/salla-quantity-input/salla-quantity-input.js +2 -2
  153. package/dist/collection/components/salla-quick-buy/salla-quick-buy.js +17 -16
  154. package/dist/collection/components/salla-quick-order/salla-quick-order.js +11 -11
  155. package/dist/collection/components/salla-rating-modal/salla-rating-modal.js +2 -2
  156. package/dist/collection/components/salla-rating-stars/salla-rating-stars.js +8 -8
  157. package/dist/collection/components/salla-review-card/salla-review-card.js +3 -3
  158. package/dist/collection/components/salla-reviews/salla-reviews.js +13 -16
  159. package/dist/collection/components/salla-reviews-summary/salla-reviews-summary.js +2 -2
  160. package/dist/collection/components/salla-scopes/salla-scopes.js +2 -2
  161. package/dist/collection/components/salla-search/salla-search.js +6 -6
  162. package/dist/collection/components/salla-skeleton/salla-skeleton.js +3 -3
  163. package/dist/collection/components/salla-slider/salla-slider.js +25 -25
  164. package/dist/collection/components/salla-social-share/salla-social-share.js +3 -3
  165. package/dist/collection/components/salla-tabs/salla-tab-content.js +2 -2
  166. package/dist/collection/components/salla-tabs/salla-tab-header.js +5 -5
  167. package/dist/collection/components/salla-tabs/salla-tabs.js +2 -2
  168. package/dist/collection/components/salla-tel-input/salla-tel-input.js +8 -9
  169. package/dist/collection/components/salla-tooltip/salla-tooltip.js +5 -5
  170. package/dist/collection/components/salla-trust-badges/salla-trust-badges.js +1 -1
  171. package/dist/collection/components/salla-user-menu/salla-user-menu.js +5 -5
  172. package/dist/collection/components/salla-user-profile/salla-user-profile.js +1 -1
  173. package/dist/collection/components/salla-verify/salla-verify.js +4 -4
  174. package/dist/components/Helper.js +432 -1
  175. package/dist/components/_commonjsHelpers.js +7 -1
  176. package/dist/components/anime.es.js +1310 -1
  177. package/dist/components/arrow-left.js +8 -1
  178. package/dist/components/axios.js +4240 -2
  179. package/dist/components/bell-ring.js +8 -1
  180. package/dist/components/camera.js +8 -1
  181. package/dist/components/cancel.js +8 -1
  182. package/dist/components/cart.js +8 -1
  183. package/dist/components/check-circle2.js +15 -1
  184. package/dist/components/check.js +8 -1
  185. package/dist/components/facebook.js +10 -1
  186. package/dist/components/filepond-plugin-file-poster.js +662 -2
  187. package/dist/components/filepond-plugin-file-validate-size.js +204 -2
  188. package/dist/components/filepond-plugin-file-validate-type.js +262 -2
  189. package/dist/components/filepond-plugin-image-edit.js +487 -2
  190. package/dist/components/filepond-plugin-image-exif-orientation.js +214 -2
  191. package/dist/components/filepond-plugin-image-preview.js +2237 -2
  192. package/dist/components/filepond.js +11286 -2
  193. package/dist/components/gift.js +8 -1
  194. package/dist/components/image.js +8 -1
  195. package/dist/components/index.d.ts +0 -2
  196. package/dist/components/index.js +8220 -1
  197. package/dist/components/index2.js +1709 -1
  198. package/dist/components/index3.js +2550 -1
  199. package/dist/components/interfaces.js +12 -1
  200. package/dist/components/isObject.js +292 -1
  201. package/dist/components/keyboard_arrow_down.js +8 -1
  202. package/dist/components/keyboard_arrow_right.js +15 -1
  203. package/dist/components/location.js +11 -1
  204. package/dist/components/mail.js +8 -1
  205. package/dist/components/minus.js +15 -1
  206. package/dist/components/salla-accordion-body.js +6 -1
  207. package/dist/components/salla-accordion-body2.js +30 -1
  208. package/dist/components/salla-accordion-head.js +6 -1
  209. package/dist/components/salla-accordion-head2.js +63 -1
  210. package/dist/components/salla-accordion.js +6 -1
  211. package/dist/components/salla-accordion2.js +68 -1
  212. package/dist/components/salla-add-product-button.js +6 -1
  213. package/dist/components/salla-add-product-button2.js +306 -1
  214. package/dist/components/salla-advertisement.js +155 -1
  215. package/dist/components/salla-alert.js +59 -1
  216. package/dist/components/salla-app-install-alert.js +91 -1
  217. package/dist/components/salla-apps-icons.js +63 -1
  218. package/dist/components/salla-booking-field.js +6 -1
  219. package/dist/components/salla-booking-field2.js +221 -1
  220. package/dist/components/salla-bottom-alert.js +214 -1
  221. package/dist/components/salla-breadcrumb.js +226 -1
  222. package/dist/components/salla-bullet-delivery.js +2114 -1
  223. package/dist/components/salla-button.js +6 -1
  224. package/dist/components/salla-button2.js +174 -1
  225. package/dist/components/salla-cart-coupons.js +284 -1
  226. package/dist/components/salla-cart-item-offers.js +143 -1
  227. package/dist/components/salla-cart-summary.js +136 -1
  228. package/dist/components/salla-color-picker.js +6 -1
  229. package/dist/components/salla-color-picker2.js +260 -1
  230. package/dist/components/salla-comment-form.js +6 -1
  231. package/dist/components/salla-comment-form2.js +64 -1
  232. package/dist/components/salla-comment-item.js +6 -1
  233. package/dist/components/salla-comment-item2.js +217 -1
  234. package/dist/components/salla-comments.js +395 -1
  235. package/dist/components/salla-conditional-fields.js +6 -1
  236. package/dist/components/salla-conditional-fields2.js +137 -1
  237. package/dist/components/salla-conditional-offer.js +194 -1
  238. package/dist/components/salla-contacts.js +125 -1
  239. package/dist/components/salla-cookies-bar.js +107 -1
  240. package/dist/components/salla-count-down.js +6 -1
  241. package/dist/components/salla-count-down2.js +271 -1
  242. package/dist/components/salla-custom-fields.js +175 -1
  243. package/dist/components/salla-datetime-picker.js +6 -1
  244. package/dist/components/salla-datetime-picker2.js +342 -1
  245. package/dist/components/salla-delivery-promise.js +263 -1
  246. package/dist/components/salla-drawer.js +6 -1
  247. package/dist/components/salla-drawer2.js +214 -1
  248. package/dist/components/salla-file-upload.js +6 -1
  249. package/dist/components/salla-file-upload2.js +583 -1
  250. package/dist/components/salla-filters-widget.js +6 -1
  251. package/dist/components/salla-filters-widget2.js +245 -1
  252. package/dist/components/salla-filters.js +253 -1
  253. package/dist/components/salla-fulfillment-methods.js +61 -1
  254. package/dist/components/salla-gifting.js +732 -1
  255. package/dist/components/salla-hook.js +47 -1
  256. package/dist/components/salla-infinite-scroll.js +112 -1
  257. package/dist/components/salla-installment.js +306 -1
  258. package/dist/components/salla-list-tile.js +6 -1
  259. package/dist/components/salla-list-tile2.js +47 -1
  260. package/dist/components/salla-loading.js +6 -1
  261. package/dist/components/salla-loading2.js +51 -1
  262. package/dist/components/salla-localization-modal.js +296 -1
  263. package/dist/components/salla-login-modal.js +6 -1
  264. package/dist/components/salla-login-modal2.js +359 -1
  265. package/dist/components/salla-loyalty-prize-item.js +39 -1
  266. package/dist/components/salla-loyalty-program.js +115 -1
  267. package/dist/components/salla-loyalty.js +304 -1
  268. package/dist/components/salla-maintenance-alert.js +57 -1
  269. package/dist/components/salla-map.js +6 -1
  270. package/dist/components/salla-map2.js +766 -1
  271. package/dist/components/salla-menu.js +165 -1
  272. package/dist/components/salla-metadata.js +97 -1
  273. package/dist/components/salla-modal.js +6 -1
  274. package/dist/components/salla-modal2.js +215 -1
  275. package/dist/components/salla-multiple-bundle-product-cart.js +6 -1
  276. package/dist/components/salla-multiple-bundle-product-cart2.js +151 -1
  277. package/dist/components/salla-multiple-bundle-product-details.js +6 -1
  278. package/dist/components/salla-multiple-bundle-product-details2.js +296 -1
  279. package/dist/components/salla-multiple-bundle-product-options-modal.js +6 -1
  280. package/dist/components/salla-multiple-bundle-product-options-modal2.js +598 -1
  281. package/dist/components/salla-multiple-bundle-product-slider.js +6 -1
  282. package/dist/components/salla-multiple-bundle-product-slider2.js +136 -1
  283. package/dist/components/salla-multiple-bundle-product.js +207 -1
  284. package/dist/components/salla-notification-item.js +6 -1
  285. package/dist/components/salla-notification-item2.js +32 -1
  286. package/dist/components/salla-notifications.js +190 -1
  287. package/dist/components/salla-offer-modal.js +328 -1
  288. package/dist/components/salla-offer.js +478 -1
  289. package/dist/components/salla-order-details-multiple-bundle-product.js +6 -1
  290. package/dist/components/salla-order-details-multiple-bundle-product2.js +122 -1
  291. package/dist/components/salla-order-details-options.js +6 -1
  292. package/dist/components/salla-order-details-options2.js +140 -1
  293. package/dist/components/salla-order-details.js +122 -1
  294. package/dist/components/salla-order-edit-item.js +6 -1
  295. package/dist/components/salla-order-edit-item2.js +181 -1
  296. package/dist/components/salla-order-edit.js +288 -1
  297. package/dist/components/salla-order-summary.js +132 -1
  298. package/dist/components/salla-order-totals-card.js +87 -1
  299. package/dist/components/salla-orders.js +271 -1
  300. package/dist/components/salla-payments.js +76 -1
  301. package/dist/components/salla-placeholder.js +6 -1
  302. package/dist/components/salla-placeholder2.js +66 -1
  303. package/dist/components/salla-price-range.js +6 -1
  304. package/dist/components/salla-price-range2.js +204 -1
  305. package/dist/components/salla-product-availability.js +6 -1
  306. package/dist/components/salla-product-availability2.js +206 -1
  307. package/dist/components/salla-product-card.js +6 -1
  308. package/dist/components/salla-product-card2.js +241 -1
  309. package/dist/components/salla-product-options.js +6 -1
  310. package/dist/components/salla-product-options2.js +962 -1
  311. package/dist/components/salla-product-size-guide.js +130 -1
  312. package/dist/components/salla-products-list.js +6 -1
  313. package/dist/components/salla-products-list2.js +812 -1
  314. package/dist/components/salla-products-slider.js +6 -1
  315. package/dist/components/salla-products-slider2.js +215 -1
  316. package/dist/components/salla-progress-bar.js +6 -1
  317. package/dist/components/salla-progress-bar2.js +94 -1
  318. package/dist/components/salla-quantity-input.js +6 -1
  319. package/dist/components/salla-quantity-input2.js +127 -1
  320. package/dist/components/salla-quick-buy.js +6 -1
  321. package/dist/components/salla-quick-buy2.js +1181 -1
  322. package/dist/components/salla-quick-order.js +299 -1
  323. package/dist/components/salla-rating-modal.js +530 -1
  324. package/dist/components/salla-rating-stars.js +6 -1
  325. package/dist/components/salla-rating-stars2.js +162 -1
  326. package/dist/components/salla-review-card.js +6 -1
  327. package/dist/components/salla-review-card2.js +198 -1
  328. package/dist/components/salla-reviews-page.js +726 -1
  329. package/dist/components/salla-reviews-summary.js +6 -1
  330. package/dist/components/salla-reviews-summary2.js +132 -1
  331. package/dist/components/salla-reviews.js +143 -1
  332. package/dist/components/salla-scopes.js +249 -1
  333. package/dist/components/salla-search.js +213 -1
  334. package/dist/components/salla-skeleton.js +6 -1
  335. package/dist/components/salla-skeleton2.js +50 -1
  336. package/dist/components/salla-slider.js +6 -1
  337. package/dist/components/salla-slider2.js +10489 -1
  338. package/dist/components/salla-social-share.js +194 -1
  339. package/dist/components/salla-social.js +89 -1
  340. package/dist/components/salla-tab-content.js +6 -1
  341. package/dist/components/salla-tab-content2.js +55 -1
  342. package/dist/components/salla-tab-header.js +6 -1
  343. package/dist/components/salla-tab-header2.js +85 -1
  344. package/dist/components/salla-tabs.js +6 -1
  345. package/dist/components/salla-tabs2.js +75 -1
  346. package/dist/components/salla-tel-input.js +6 -1
  347. package/dist/components/salla-tel-input2.js +168 -1
  348. package/dist/components/salla-tiered-offer.js +366 -1
  349. package/dist/components/salla-tooltip.js +6 -1
  350. package/dist/components/salla-tooltip2.js +57 -1
  351. package/dist/components/salla-trust-badges.js +90 -1
  352. package/dist/components/salla-user-menu.js +344 -1
  353. package/dist/components/salla-user-profile.js +203 -1
  354. package/dist/components/salla-user-settings.js +139 -1
  355. package/dist/components/salla-verify.js +303 -1
  356. package/dist/components/salla-wallet.js +114 -1
  357. package/dist/components/search.js +8 -1
  358. package/dist/components/shopping-bag.js +8 -1
  359. package/dist/components/special-discount.js +8 -1
  360. package/dist/components/star.js +8 -1
  361. package/dist/components/star2.js +8 -1
  362. package/dist/components/vanilla-picker.js +1034 -2
  363. package/dist/components/whatsapp2.js +8 -1
  364. package/dist/esm/{filepond-DlGaLh8N.js → filepond-Be7JObSq.js} +1 -1
  365. package/dist/esm/{filepond-plugin-file-poster-BTVFYcQx.js → filepond-plugin-file-poster-DF0NWKCQ.js} +2 -2
  366. package/dist/esm/{filepond-plugin-file-validate-size-DGryLmWv.js → filepond-plugin-file-validate-size-DJFlJHtE.js} +1 -1
  367. package/dist/esm/{filepond-plugin-file-validate-type-DxKfCD0V.js → filepond-plugin-file-validate-type-DykpLW1Z.js} +1 -1
  368. package/dist/esm/{filepond-plugin-image-edit-2W7pu9hn.js → filepond-plugin-image-edit-CyIHxrnW.js} +1 -1
  369. package/dist/esm/{filepond-plugin-image-exif-orientation-OQu-IvPH.js → filepond-plugin-image-exif-orientation-DbCOAhSu.js} +1 -1
  370. package/dist/esm/{filepond-plugin-image-preview-DEW_tSNR.js → filepond-plugin-image-preview-CGRGZcft.js} +1 -1
  371. package/dist/esm/{index-DYB20YqN.js → index-Cz6cYzxG.js} +547 -780
  372. package/dist/esm/{index-BDqMkCqE.js → index-_kPnZdm0.js} +1 -1
  373. package/dist/esm/loader.js +3 -4
  374. package/dist/esm/salla-accordion-body_2.entry.js +5 -5
  375. package/dist/esm/salla-accordion_6.entry.js +15 -19
  376. package/dist/esm/salla-add-product-button_4.entry.js +10 -12
  377. package/dist/esm/salla-advertisement.entry.js +3 -3
  378. package/dist/esm/salla-alert_2.entry.js +5 -5
  379. package/dist/esm/salla-app-install-alert.entry.js +3 -3
  380. package/dist/esm/salla-apps-icons.entry.js +3 -3
  381. package/dist/esm/salla-booking-field_7.entry.js +23 -25
  382. package/dist/esm/salla-bullet-delivery.entry.js +3 -3
  383. package/dist/esm/salla-cart-coupons.entry.js +3 -3
  384. package/dist/esm/salla-cart-item-offers_2.entry.js +5 -5
  385. package/dist/esm/salla-comment-form_8.entry.js +17 -17
  386. package/dist/esm/salla-conditional-offer.entry.js +3 -3
  387. package/dist/esm/salla-contacts.entry.js +3 -3
  388. package/dist/esm/salla-cookies-bar.entry.js +3 -3
  389. package/dist/esm/salla-count-down.entry.js +3 -3
  390. package/dist/esm/salla-custom-fields.entry.js +3 -3
  391. package/dist/esm/salla-delivery-promise.entry.js +1 -1
  392. package/dist/esm/salla-filters-widget.entry.js +3 -3
  393. package/dist/esm/salla-filters.entry.js +3 -3
  394. package/dist/esm/salla-fulfillment-methods.entry.js +1 -1
  395. package/dist/esm/salla-gifting.entry.js +3 -3
  396. package/dist/esm/salla-hook.entry.js +2 -5
  397. package/dist/esm/salla-infinite-scroll.entry.js +3 -3
  398. package/dist/esm/salla-installment.entry.js +3 -3
  399. package/dist/esm/salla-list-tile.entry.js +3 -3
  400. package/dist/esm/salla-localization-modal.entry.js +1 -1
  401. package/dist/esm/salla-login-modal.entry.js +3 -3
  402. package/dist/esm/salla-loyalty-prize-item.entry.js +3 -3
  403. package/dist/esm/salla-loyalty-program.entry.js +3 -3
  404. package/dist/esm/salla-loyalty.entry.js +3 -3
  405. package/dist/esm/salla-maintenance-alert.entry.js +3 -3
  406. package/dist/esm/salla-map.entry.js +3 -3
  407. package/dist/esm/salla-menu.entry.js +3 -3
  408. package/dist/esm/salla-metadata.entry.js +3 -3
  409. package/dist/esm/salla-multiple-bundle-product-cart_2.entry.js +5 -5
  410. package/dist/esm/salla-multiple-bundle-product-options-modal_2.entry.js +6 -8
  411. package/dist/esm/salla-multiple-bundle-product.entry.js +4 -6
  412. package/dist/esm/salla-notification-item.entry.js +3 -3
  413. package/dist/esm/salla-notifications.entry.js +3 -3
  414. package/dist/esm/salla-offer-modal.entry.js +3 -3
  415. package/dist/esm/salla-offer.entry.js +3 -3
  416. package/dist/esm/salla-order-details-multiple-bundle-product.entry.js +3 -3
  417. package/dist/esm/salla-order-details-options.entry.js +3 -3
  418. package/dist/esm/salla-order-details.entry.js +4 -6
  419. package/dist/esm/salla-order-edit-item.entry.js +3 -3
  420. package/dist/esm/salla-order-edit.entry.js +3 -3
  421. package/dist/esm/salla-order-summary.entry.js +3 -3
  422. package/dist/esm/salla-order-totals-card.entry.js +4 -6
  423. package/dist/esm/salla-orders.entry.js +3 -3
  424. package/dist/esm/salla-payments.entry.js +3 -3
  425. package/dist/esm/salla-placeholder.entry.js +3 -3
  426. package/dist/esm/salla-price-range.entry.js +3 -3
  427. package/dist/esm/salla-product-card.entry.js +3 -3
  428. package/dist/esm/salla-product-size-guide.entry.js +3 -3
  429. package/dist/esm/salla-products-list.entry.js +3 -3
  430. package/dist/esm/salla-products-slider.entry.js +3 -3
  431. package/dist/esm/salla-progress-bar.entry.js +3 -3
  432. package/dist/esm/salla-quick-order.entry.js +3 -3
  433. package/dist/esm/salla-rating-modal.entry.js +3 -3
  434. package/dist/esm/salla-scopes.entry.js +3 -3
  435. package/dist/esm/salla-search.entry.js +4 -6
  436. package/dist/esm/salla-skeleton.entry.js +3 -3
  437. package/dist/esm/salla-slider.entry.js +3 -3
  438. package/dist/esm/salla-social-share.entry.js +3 -3
  439. package/dist/esm/salla-social.entry.js +3 -3
  440. package/dist/esm/salla-tab-content_3.entry.js +7 -7
  441. package/dist/esm/salla-tiered-offer.entry.js +3 -3
  442. package/dist/esm/salla-tooltip.entry.js +3 -3
  443. package/dist/esm/salla-trust-badges.entry.js +3 -3
  444. package/dist/esm/salla-user-menu.entry.js +3 -3
  445. package/dist/esm/salla-user-profile.entry.js +3 -3
  446. package/dist/esm/salla-user-settings.entry.js +3 -3
  447. package/dist/esm/salla-verify.entry.js +3 -3
  448. package/dist/esm/salla-wallet.entry.js +3 -3
  449. package/dist/esm/twilight.js +4 -5
  450. package/dist/esm/{vanilla-picker-Dt9vZPZF.js → vanilla-picker-C_YV5LtA.js} +1 -1
  451. package/dist/twilight/{p-33779828.entry.js → p-0200cddd.entry.js} +1 -1
  452. package/dist/twilight/p-04dc0b71.entry.js +4 -0
  453. package/dist/twilight/{p-105b1dab.entry.js → p-0bac200e.entry.js} +1 -1
  454. package/dist/twilight/{p-ccfe5308.entry.js → p-0ef99df1.entry.js} +1 -1
  455. package/dist/twilight/{p-647b6d76.entry.js → p-1087f0dd.entry.js} +1 -1
  456. package/dist/twilight/{p-1875537e.entry.js → p-17dd8b68.entry.js} +1 -1
  457. package/dist/twilight/{p-aa7c5de0.entry.js → p-25a9bf1b.entry.js} +1 -1
  458. package/dist/twilight/{p-34b670fc.entry.js → p-2602927d.entry.js} +1 -1
  459. package/dist/twilight/p-268695ff.entry.js +4 -0
  460. package/dist/twilight/{p-aaa0c743.entry.js → p-34920aac.entry.js} +1 -1
  461. package/dist/twilight/{p-817b8ba5.entry.js → p-3656b48d.entry.js} +1 -1
  462. package/dist/twilight/{p-4932857d.entry.js → p-3857beb4.entry.js} +1 -1
  463. package/dist/twilight/{p-af3c74f4.entry.js → p-39c601e3.entry.js} +1 -1
  464. package/dist/twilight/{p-b598c0f7.entry.js → p-3c810881.entry.js} +1 -1
  465. package/dist/twilight/{p-d371d450.entry.js → p-3cf5c61f.entry.js} +1 -1
  466. package/dist/twilight/{p-3ccc532d.entry.js → p-413a7236.entry.js} +1 -1
  467. package/dist/twilight/{p-f176d41d.entry.js → p-42778349.entry.js} +1 -1
  468. package/dist/twilight/{p-b17d055d.entry.js → p-45e4f6f4.entry.js} +1 -1
  469. package/dist/twilight/{p-2abaa633.entry.js → p-4680956b.entry.js} +1 -1
  470. package/dist/twilight/{p-96a20515.entry.js → p-468b999f.entry.js} +1 -1
  471. package/dist/twilight/{p-df6853b5.entry.js → p-46d1823f.entry.js} +1 -1
  472. package/dist/twilight/{p-c87951a2.entry.js → p-49db497f.entry.js} +1 -1
  473. package/dist/twilight/{p-18bb0181.entry.js → p-4b033276.entry.js} +1 -1
  474. package/dist/twilight/{p-296d2dd0.entry.js → p-4f7bc9c3.entry.js} +1 -1
  475. package/dist/twilight/{p-4fa4547a.entry.js → p-543ee624.entry.js} +1 -1
  476. package/dist/twilight/{p-2fe01e44.entry.js → p-5957f774.entry.js} +1 -1
  477. package/dist/twilight/{p-96e78428.entry.js → p-5a4f0b99.entry.js} +1 -1
  478. package/dist/twilight/{p-87c0ca91.entry.js → p-5a8c0fd2.entry.js} +1 -1
  479. package/dist/twilight/{p-e28c0773.entry.js → p-5ab7a295.entry.js} +1 -1
  480. package/dist/twilight/{p-542d3277.entry.js → p-5e496aaa.entry.js} +1 -1
  481. package/dist/twilight/{p-c3ffb88a.entry.js → p-5f440956.entry.js} +1 -1
  482. package/dist/twilight/{p-94dbc1e9.entry.js → p-60fafcd9.entry.js} +1 -1
  483. package/dist/twilight/{p-1ef2602d.entry.js → p-708f02db.entry.js} +1 -1
  484. package/dist/twilight/{p-b64f3155.entry.js → p-7829ea8a.entry.js} +1 -1
  485. package/dist/twilight/{p-7093a427.entry.js → p-7d3e592a.entry.js} +1 -1
  486. package/dist/twilight/{p-96d03a28.entry.js → p-81876026.entry.js} +1 -1
  487. package/dist/twilight/{p-d9f5a8cd.entry.js → p-8306ef5e.entry.js} +1 -1
  488. package/dist/twilight/{p-d4a242f8.entry.js → p-8403cd93.entry.js} +1 -1
  489. package/dist/twilight/{p-7abddca8.entry.js → p-8474c4f6.entry.js} +1 -1
  490. package/dist/twilight/p-8552160a.entry.js +4 -0
  491. package/dist/twilight/p-8c9b0e2a.entry.js +4 -0
  492. package/dist/twilight/{p-2881bb33.entry.js → p-8f2dfc57.entry.js} +1 -1
  493. package/dist/twilight/{p-c091e2dc.entry.js → p-94b1a2ae.entry.js} +1 -1
  494. package/dist/twilight/{p-ede67a08.entry.js → p-95dad1af.entry.js} +1 -1
  495. package/dist/twilight/{p-eac718cd.entry.js → p-964b7db9.entry.js} +1 -1
  496. package/dist/twilight/{p-e3b8e0e1.entry.js → p-99735748.entry.js} +1 -1
  497. package/dist/twilight/{p-X6Yi3bYP.js → p-BZKDQg1s.js} +1 -1
  498. package/dist/twilight/{p-Cw3UBzjl.js → p-B_sN7OnY.js} +1 -1
  499. package/dist/twilight/{p-8r0S6BcZ.js → p-Bpi0aG1F.js} +1 -1
  500. package/dist/twilight/{p-BkClxrC4.js → p-CP8rFQ5n.js} +1 -1
  501. package/dist/twilight/{p-bNzv71Xl.js → p-CfmIbM8B.js} +1 -1
  502. package/dist/twilight/{p-bScl0xMh.js → p-CpO1SrBd.js} +1 -1
  503. package/dist/twilight/p-Cz6cYzxG.js +5 -0
  504. package/dist/twilight/p-Do4hSOGo.js +9 -0
  505. package/dist/twilight/{p-Ck4zxCil.js → p-JJmlh-ji.js} +1 -1
  506. package/dist/twilight/{p-dd2bd5dc.entry.js → p-a4aedcfe.entry.js} +1 -1
  507. package/dist/twilight/{p-06fa7327.entry.js → p-b0d01f9f.entry.js} +1 -1
  508. package/dist/twilight/p-b8404cfb.entry.js +4 -0
  509. package/dist/twilight/{p-108d8c8b.entry.js → p-b8e3e180.entry.js} +1 -1
  510. package/dist/twilight/{p-ad07f67a.entry.js → p-bd687cd0.entry.js} +1 -1
  511. package/dist/twilight/{p-44fa7521.entry.js → p-c0037fac.entry.js} +1 -1
  512. package/dist/twilight/{p-293c6cf3.entry.js → p-c121f8e4.entry.js} +1 -1
  513. package/dist/twilight/{p-a01f1992.entry.js → p-c29907df.entry.js} +1 -1
  514. package/dist/twilight/p-c39675ef.entry.js +4 -0
  515. package/dist/twilight/{p-bff4c7b3.entry.js → p-cb7a985e.entry.js} +1 -1
  516. package/dist/twilight/p-cbe620c4.entry.js +4 -0
  517. package/dist/twilight/{p-6f36541a.entry.js → p-d2fd79b4.entry.js} +1 -1
  518. package/dist/twilight/{p-d337c399.entry.js → p-d6cf0ffd.entry.js} +1 -1
  519. package/dist/twilight/{p-748df7e6.entry.js → p-d8f60f2f.entry.js} +1 -1
  520. package/dist/twilight/p-d99610f9.entry.js +4 -0
  521. package/dist/twilight/{p-e6bbf50d.entry.js → p-dc897bdd.entry.js} +1 -1
  522. package/dist/twilight/{p-f7999a6d.entry.js → p-dca46236.entry.js} +1 -1
  523. package/dist/twilight/{p-e94f217b.entry.js → p-e48853c9.entry.js} +1 -1
  524. package/dist/twilight/{p-09d39785.entry.js → p-e4fdb206.entry.js} +1 -1
  525. package/dist/twilight/p-ed913ae7.entry.js +4 -0
  526. package/dist/twilight/p-f067fcd6.entry.js +4 -0
  527. package/dist/twilight/{p-57ff1f25.entry.js → p-f2cd6975.entry.js} +1 -1
  528. package/dist/twilight/{p-ad041ab5.entry.js → p-f2ffbfbb.entry.js} +1 -1
  529. package/dist/twilight/{p-f5d15e71.entry.js → p-f3166e60.entry.js} +1 -1
  530. package/dist/twilight/{p-59ae82bd.entry.js → p-f8fcc8f4.entry.js} +1 -1
  531. package/dist/twilight/{p-c1fd45b1.entry.js → p-f9e52fd9.entry.js} +1 -1
  532. package/dist/twilight/p-fcddbfc3.entry.js +4 -0
  533. package/dist/twilight/{p-41c733c2.entry.js → p-fe7ac9bb.entry.js} +1 -1
  534. package/dist/twilight/{p-0add06f9.entry.js → p-ff14dca3.entry.js} +1 -1
  535. package/dist/twilight/{p-BZnoSB1s.js → p-mlFGjxcj.js} +1 -1
  536. package/dist/twilight/twilight.esm.js +1 -1
  537. package/dist/types/components.d.ts +177 -763
  538. package/dist/types/stencil-public-runtime.d.ts +11 -169
  539. package/package.json +5 -5
  540. package/dist/cjs/app-globals-oehrC7QI.js +0 -39
  541. package/dist/esm/app-globals-BFryt7-C.js +0 -37
  542. package/dist/twilight/p-1daeed6e.entry.js +0 -4
  543. package/dist/twilight/p-2ddb3fce.entry.js +0 -4
  544. package/dist/twilight/p-34968e31.entry.js +0 -4
  545. package/dist/twilight/p-665189b4.entry.js +0 -4
  546. package/dist/twilight/p-776c9d33.entry.js +0 -4
  547. package/dist/twilight/p-7b8313ef.entry.js +0 -4
  548. package/dist/twilight/p-7bd0ede5.entry.js +0 -4
  549. package/dist/twilight/p-8e8d9d7d.entry.js +0 -4
  550. package/dist/twilight/p-D1vqXXNX.js +0 -9
  551. package/dist/twilight/p-DYB20YqN.js +0 -5
  552. package/dist/twilight/p-Vl6qpttb.js +0 -4
  553. package/dist/twilight/p-af60e72a.entry.js +0 -4
  554. package/dist/twilight/p-e679884a.entry.js +0 -4
  555. package/dist/twilight/p-efab88c5.entry.js +0 -4
@@ -17,7 +17,7 @@ function _mergeNamespaces(n, m) {
17
17
  }
18
18
 
19
19
  const NAMESPACE = 'twilight';
20
- const BUILD = /* twilight */ { hotModuleReplacement: false, hydratedSelectorName: "hydrated", lazyLoad: true, propChangeCallback: true, slotRelocation: true, state: true, updatable: true};
20
+ const BUILD = /* twilight */ { hydratedSelectorName: "hydrated", lazyLoad: true, slotRelocation: true, updatable: true};
21
21
 
22
22
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
23
23
 
@@ -4001,7 +4001,7 @@ var a$4 = /*#__PURE__*/_mergeNamespaces({
4001
4001
  default: memoryStorage
4002
4002
  }, [memoryStorageExports]);
4003
4003
 
4004
- function s$1(t,e){ void 0===e&&(e=false),t+="";for(var r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],o=["0","1","2","3","4","5","6","7","8","9"],i=(e=e||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:o,a=e?o:n,s=0;s<i.length;s++)r=new RegExp(i[s],"g"),t=t.replace(r,a[s]);return t.replace(e?"٫":".",e?".":"٫")}function l$2(t){var e=("".concat(t).match(/\./g)||[]).length;return e&&1!==e?l$2(t.replace(/\.(.+)\./g,".$1")):t}function c$3(t){return "".concat(t).startsWith("https://")||"".concat(t).startsWith("http://")}function u$3(t){if(c$3(t))return t;var e=Salla.config.get("store.url");return e||(e=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",e)),e.rtrim("/")+"/"+(null==t?void 0:t.ltrim("/"))}function p$1(t,e,r){if(r=r||window.location.href,!e||!t)return r;var n=new RegExp("([?&])"+t+"=[^&]+[&]?","g");return (r=r.replace(n,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+t+"="+encodeURIComponent(e)).replace(/&$|\?$/,"")}function d$3(t){return window.location.origin+"/"+(null==t?void 0:t.ltrim("/"))}function f$2(t){return c$3(t)?t:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==t?void 0:t.ltrim("/")):d$3("themes/"+Salla.config.get("theme.name")+"/"+(null==t?void 0:t.ltrim("/")))}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,function(t){return t.toUpperCase().replace(/[^a-zA-Z\d]/g,"")})},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this.toString():"#"+this.toString()},String.prototype.replaceArray=function(t,e){for(var r,n=this,o=0;o<t.length;o++)r=new RegExp(t[o],"g"),n=n.replace(r,e[o]);return n},String.prototype.rtrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("["+t+"]*$"),"")},String.prototype.ltrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("^["+t+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var h$3=Object.freeze({__proto__:null,addParamToUrl:p$1,api:function(t){var e;return (null===(e=Salla.config.get("store.api",u$3("")))||void 0===e?void 0:e.rtrim("/"))+"/"+(null==t?void 0:t.ltrim("/"))},asset:f$2,base:function(t){return c$3(t)?t:"https://"+new URL(u$3("/")).hostname+"/"+(null==t?void 0:t.ltrim("/"))},baseUrl:d$3,cdn:function(t,e,r){var n="https://cdn.salla.network/";return (e||r)&&(e=e?",width=".concat(e):"",r=r?",height=".concat(r):"",n+="cdn-cgi/image/fit=scale-down".concat(e).concat(r,",onerror=redirect,format=auto/")),n+(null==t?void 0:t.ltrim("/"))},create:function(t,e){return "custom"===t?e:u$3("offers"===t?t:"redirect/".concat(t,"/").concat(e))},domain:function(t){return c$3(t)?t:"".concat(Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/"),"/").concat(null==t?void 0:t.ltrim("/"))},get:u$3,is_full_url:c$3,is_page:function(t){return t&&Salla.config.get("page.slug")===t},is_placeholder:function(t){return f$2(salla.config.get("theme.settings.placeholder"))===f$2(t)}}),g$3=function(t,e){return g$3=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);},g$3(t,e)};var v$2=function(){return v$2=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},v$2.apply(this,arguments)};function y$3(t,e,r){if(2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}function m$3(t){return t instanceof FormData}function w$2(t){return t instanceof File}function S$2(t){return t instanceof Blob}"function"==typeof SuppressedError&&SuppressedError;var b$5=function(){function t(t){this.data=t,this.proxy=this.createProxy();}return t.prototype.createProxy=function(){var t=this;return new Proxy(this,{get:function(e,r){return r in e?e[r]:"string"==typeof r?t.get(r):void 0},set:function(e,r,n){return "string"==typeof r&&(t.set(r,n),true)},has:function(e,r){return "string"==typeof r?t.has(r):r in e},deleteProperty:function(e,r){return "string"==typeof r&&t.delete(r)}})},t.prototype.get=function(t){return m$3(this.data)?this.data.get(t):this.data[t]},t.prototype.getAll=function(t){if(m$3(this.data))return this.data.getAll(t);var e=this.data[t];return void 0===e?[]:[e]},t.prototype.set=function(t,e){var r=this;m$3(this.data)?(this.data.delete(t),null!=e&&(Array.isArray(e)?e.forEach(function(e){w$2(e)||S$2(e)?r.data.append(t,e):r.data.append(t,String(e));}):w$2(e)||S$2(e)?this.data.append(t,e):this.data.append(t,String(e)))):this.data[t]=e;},t.prototype.append=function(t,e){if(m$3(this.data))w$2(e)||S$2(e)?this.data.append(t,e):null!=e&&this.data.append(t,String(e));else {var r=this.data[t];void 0===r?this.data[t]=e:Array.isArray(r)?r.push(e):this.data[t]=[r,e];}},t.prototype.setFile=function(t,e){this.set(t,e);},t.prototype.getFile=function(t){var e=this.get(t);return w$2(e)?e:null},t.prototype.getFiles=function(t){return this.getAll(t).filter(w$2)},t.prototype.has=function(t){return m$3(this.data)?this.data.has(t):t in this.data},t.prototype.delete=function(t){return m$3(this.data)?(this.data.delete(t),true):delete this.data[t]},t.prototype.keys=function(){if(!m$3(this.data))return Object.keys(this.data);for(var t=new Set,e=0,r=this.data.entries();e<r.length;e++){var n=r[e][0];t.add(n);}return Array.from(t)},t.prototype.values=function(){if(!m$3(this.data))return Object.values(this.data);for(var t=[],e=0,r=this.data.entries();e<r.length;e++){var n=r[e][1];t.push(n);}return t},t.prototype.entries=function(){return m$3(this.data)?Array.from(this.data.entries()):Object.entries(this.data)},t.prototype.toObject=function(){if(!m$3(this.data))return v$2({},this.data);for(var t={},e=0,r=this.data.entries();e<r.length;e++){var n=r[e],o=n[0],i=n[1];void 0!==t[o]?(Array.isArray(t[o])||(t[o]=[t[o]]),t[o].push(i)):t[o]=i;}return t},t.prototype.getFileInfo=function(t){var e=this.getFiles(t);return 0===e.length?null:e.map(function(t){return {name:t.name,size:t.size,type:t.type}})},t.prototype.isFile=function(t){var e=this.get(t);return w$2(e)||S$2(e)},t.prototype.getRawData=function(){return this.data},t.prototype.getProxy=function(){return this.proxy},t}();function _$2(t,e,r){var n,o=t[0];return r&&0==t.length?Array.isArray(r)?(r.push(e),r):[r,e]:Array.isArray(r)?(r.push(e),r):"string"==typeof r?[r,e]:r?(r[o]=_$2(t.slice(1),e,r[o]),r):o?((n={})[o]=_$2(t.slice(1),e),n):""===o?[e]:e}function x$3(){return window.self!==window.top}var A$3,E$3,k$3,P$2,O$2={digitsOnly:function(t){return s$1(t,true).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function t(e,r){if(void 0===r&&(r=false),"string"==typeof e)return document.querySelectorAll(e).forEach(function(e){return t(e,r)});if(e){var n=Salla.helpers.digitsOnly(e.value);return e.min&&n<parseInt(e.min)?e.value=e.min:e.max&&n>parseInt(e.max)?e.value=e.max:e.maxLength>=1&&n.toString().length>e.maxLength?e.value=n.toString().substring(0,e.maxLength):e.value=r||e.dataset.hasOwnProperty("digitsWithDecimal")?l$2(n):n.replace(/\D/g,"")}Salla.logger.warn("Can't find Object With Id: "+e);},number:s$1,money:function(t,e){ void 0===e&&(e=true);var r=Salla.config.currency(null==t?void 0:t.currency).symbol;return t=s$1(t="object"==typeof t?t.amount:t)+" "+r,e&&["SAR","ر.س"].includes(r)&&Salla.config.get("store.settings.use_sar_symbol")&&(t=t.replace(r,"<i class=sicon-sar></i>")),t},isIframe:x$3,isPreview:function(){return x$3()},setNested:function(t,e,r){for(var n=t,o=e.split("."),i=o.length,a=0;a<i-1;a++){var s=o[a];n[s]||(n[s]={}),n=n[s];}return n[o[i-1]]=r,t},getNested:function(e,r,n){var o=t$2.default?t$2.default(e,r):t$2(e,r);return void 0!==o?o:n},inputData:function(t,e,r){if(void 0===r&&(r={}),t.includes("[")){var n=t.split("]").join("").split("["),o=n[0],i=r&&"object"==typeof r?r[o]:void 0;return {name:o,value:_$2(n.slice(1),e,i)}}return {name:t,value:e}},url:h$3,addParamToUrl:p$1,debounce:function(t,e){e=e||100;var r,n=[];return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];return clearTimeout(r),r=setTimeout(function(){var e=t.apply(void 0,o);n.forEach(function(t){return t(e)}),n=[];},e),new Promise(function(t){return n.push(t)})}},hasApplePay:function(){var t;try{return !!(null===(t=window.ApplePaySession)||void 0===t?void 0:t.canMakePayments())}catch(t){return console.error(t),false}},createFormDataWrapper:function(t){return new b$5(t).getProxy()},isAppleDevice:function(){try{var t=navigator.userAgent||"",e=navigator.platform||"",r=/iPhone|iPad|iPod/i.test(t),n=/Mac/i.test(e);return r||n}catch(t){return console.error(t),false}},isIOSDevice:function(){try{var t=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(t)}catch(t){return console.error(t),false}},isWebView:function(){try{if(void 0===window.navigator)return false;var t=window.navigator.userAgent,e=/iP(hone|od|ad)/.test(t)&&/AppleWebKit/.test(t)&&!/Safari/.test(t),r=/\bwv\b/.test(t)||/Android/.test(t)&&/AppleWebKit/.test(t)&&!/Chrome/.test(t);return e||r}catch(t){return console.error(t),false}}},j$3=(A$3=console,E$3=[],k$3=[],P$2={log:function(t,e){if(A$3&&salla.config.isDebug()){E$3.push([e,t]),"trace"===salla.config.get("debug")&&(e="trace");var r=A$3.log,n=void 0===e?r:this.__dict__[e]||r,o=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"];k$3.forEach(function(t){o[0]+=t[0],o.push(t[1]);});var i={event:"#CFF680",backend:"#7b68ee"}[e];i&&(o[0]+="%c"+e[0].toUpperCase()+e.substring(1),o.push("margin-left: 5px;color: ".concat(i,";font-weight:bold; border:1px solid ").concat(i,"; padding: 2px 6px; border-radius: 5px;"))),n.call.apply(n,y$3([A$3],o.concat.apply(o,t),false));}},__dict__:{trace:A$3.trace,debug:A$3.debug,info:A$3.info,warn:A$3.warn,error:A$3.error}},{event:function(){P$2.log(arguments,"event");},trace:function(){P$2.log(arguments,"trace");},debug:function(){P$2.log(arguments,"debug");},info:function(){P$2.log(arguments,"info");},warn:function(){P$2.log(arguments,"warn");},error:function(){P$2.log(arguments,"error");},log:function(){P$2.log(arguments,void 0);},backend:function(){P$2.log(arguments,"backend");},logs:function(t){[t].flat().forEach(function(t){return t&&P$2.log([t].flat(),"backend")});},history:function(){return E$3.map(function(t){return A$3.log.apply(A$3,y$3([t[0]],t[1],false))}),E$3},addPrefix:function(t){return Array.isArray(t)?k$3.unshift(t):this.warn("addPrefix receives array only!"),this}}),T$2=function(){function t(t,e){ void 0===t&&(t={}),void 0===e&&(e={}),this.default_properties=e,this.properties_=v$2(v$2({},this.default_properties),t);}return t.prototype.merge=function(t){var e;return this.properties_=v$2(v$2({},this.properties_),t),this.properties_.store=v$2(v$2({},(null===(e=this.default_properties)||void 0===e?void 0:e.store)||{}),this.properties_.store),this},t.prototype.set=function(t,e){return t.includes(".")?(Salla.helpers.setNested(this.properties_,t,e),this):(this.properties_[t]=e,this)},t.prototype.currency=function(t){return void 0===t&&(t=void 0),t=t||this.get("user.currency_code"),this.get("currencies."+t)||Object.values(this.get("currencies"))[0]},t.prototype.get=function(t,e){return void 0===e&&(e=null),t.includes(".")?Salla.helpers.getNested(this.properties_,t,e):this.properties_.hasOwnProperty(t)?this.properties_[t]||e:e||void 0},t.prototype.all=function(){return this.properties_},t.prototype.isDebug=function(){return this.get("debug")||Salla.storage.get("debug")},t}(),L$3=function(t){function e(){var e=this;return (e=t.call(this,{wildcard:true,delimiter:"::",newListener:false,removeListener:false,maxListeners:10,verboseMemoryLeak:false,ignoreErrors:false})||this).delimiter="::","undefined"!=typeof document&&(e.body=document.querySelector("body")),e.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],e.ingoreLogEvents=["document::click","document::keyup","document::change"],e.noneFireableActions=["document.request"],e.emittedEvents=new Set,e}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t;}g$3(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);}(e,t),e.prototype.createAndDispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];this.dispatch.apply(this,y$3([t],e,false));},e.prototype.emit=function(e){for(var r,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];this.emittedEvents.add(e);var i=e.replace("::",".");if(!this.noneFireableActions.includes(i)&&Salla.call&&"function"==typeof Salla.call(i))return Salla.log("'Salla.".concat(i,"(...)' triggered using event '").concat(e,"'")),i=i.split("."),Array.isArray(n[0])&&(n=n[0]),void(r=salla[i[0]])[i[1]].apply(r,n);t.prototype.emit.apply(this,y$3([e],n,false)),this.trackEvents.apply(this,y$3([e],n,false));},e.prototype.onlyWhen=function(t,e){var r=this;return e=e||function(){},new Promise(function(n){return r.emittedEvents.has(t)?n(e()):r.once(t,function(){return n(e())})})},e.prototype.emitAsync=function(e){for(var r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];this.emittedEvents.add(e);var o=t.prototype.emitAsync.apply(this,y$3([e],r,false));try{this.trackEvents.apply(this,y$3([e],r,false));}catch(t){Salla.logger.warn("error on tracking event (".concat(e,")"),r,t);}return o},e.prototype.trackEvents=function(t){for(var e,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if("undefined"!=typeof window)try{window.dataLayer=window.dataLayer||[];var o={event:t};r.map(function(t){return "object"==typeof t&&(o=v$2(v$2({},o),t))}),window.dataLayer.push(o);}catch(t){salla.logger.error(t.message);}Salla.logger&&!this.ingoreLogEvents.includes(t)&&(e=Salla.logger).event.apply(e,y$3([t],r,false)),this.dispatchMobileEvent.apply(this,y$3([t],r,false));},e.prototype.dispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return this.emit.apply(this,y$3([t],e,false))},e.prototype.dispatchEvents=function(t){if(t)if("object"!=typeof t||Array.isArray(t))Salla.log("Events object is wrong, it should be object of {event:payload}",t);else for(var e=0,r=Object.entries(t);e<r.length;e++){var n=r[e],o=n[0],i=n[1];this.dispatch(o,i);}else Salla.log("No Events To Dispatch!",t);},e.prototype.addListener=function(t,e,r){return this.on(t,e,r)},e.prototype.addEventListener=function(t,e,r){return this.on(t,e,r)},e.prototype.listen=function(t,e){return this.on(t,e)},e.prototype.registerGlobalListener=function(t,e){return this.onAny(e)},e.prototype.dispatchMobileEvent=function(t,e){var r;if(void 0===e&&(e={}),"undefined"!=typeof window){if(window.webkit)try{return void window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:t,details:e}))}catch(t){Salla.log(t,"The native context does not exist yet");}if(null===(r=window.Android)||void 0===r?void 0:r.customEventWithData)try{window.Android.customEventWithData(t,JSON.stringify({details:e}));}catch(t){Salla.log(t,"The native context does not exist yet");}else if(window.flutter_inappwebview)try{window.flutter_inappwebview.callHandler("sallaEvent",{event:t,details:e});}catch(t){Salla.log(t,"The Flutter context does not exist yet");}else;}},e}(eventemitter2Exports.EventEmitter2),W$2=storeEngineExports.createStore([n$4,o$3,i$3,a$4],[]),D$2=storeEngineExports.createStore([o$3],[]),C$3=storeEngineExports.createStore([i$3],[]),F$3=function(){function t(){var t=this;this.clearableItems=["cart","user","salla::wishlist","token"],Salla.event.on("storage::item.remove",function(e){return t.remove(e)}),Salla.event.on("storage::item.set",function(e,r){return t.set(e,r)}),this.store=W$2,this.session=D$2,this.cookie=C$3;}return t.prototype.set=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0],o=((r={})[n]=this.store.get(n),r);return o=Salla.helpers.setNested(o,t,e),this.store.set(n,o[n])}return this.store.set(t,e)},t.prototype.remove=function(t){return this.store.remove(t)},t.prototype.clearAll=function(t){var e=this;if(void 0===t&&(t=false),t)return this.store.clearAll();this.clearableItems.forEach(function(t){e.store.remove(t);});},t.prototype.get=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0];return Salla.helpers.getNested(((r={})[n]=this.store.get(n),r),t)}return this.store.get(t,e)},t.prototype.prefixKey=function(t){return "".concat(t,"_").concat(Salla.config.get("store.id"))},t.prototype.setWithTTL=function(t,e,r,n){ void 0===r&&(r=10),void 0===n&&(n="store");var o=this.prefixKey(t),i=(new Date).getTime()+60*r*1e3;return this[n].set(o,{value:e,expiry:i})},t.prototype.getWithTTL=function(t,e,r){ void 0===e&&(e=null),void 0===r&&(r="store");var n=this.prefixKey(t),o=this[r].get(n);return o?(new Date).getTime()>o.expiry?(this[r].remove(n),e):o.value:e},t}(),R$3=function(){function t(){var t=this;this.keysToRemove=["__said","__ssid","theme_edit","ws_port","s-token"],this.dynamicKeysToRemove=["affiliate","cart"],Salla.event.on("cookies::remove",function(e){return t.remove(e)}),Salla.event.on("cookies::add",function(e,r){return t.set(e,r)});}return t.prototype.get=function(t){var e;return null===(e=document.cookie.split("; ").find(function(e){return e.startsWith(t+"=")}))||void 0===e?void 0:e.split("=")[1]},t.prototype.set=function(t,e,r){ void 0===e&&(e=""),void 0===r&&(r=10);var n="";if(r){var o=new Date;o.setTime(o.getTime()+24*r*60*60*1e3),n="; expires="+o.toUTCString();}var i=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=").concat(e).concat(n,"; path=/; SameSite=").concat(i,"; secure"),this},t.prototype.remove=function(t){var e=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=; Max-Age=0; path=/; SameSite=").concat(e,"; secure"),this},t.prototype.clearAll=function(t){return void 0===t&&(t=false),this.clean(t)},t.prototype.clean=function(t){var e=this;return document.cookie.split(";").map(function(t){return t.split("=")[0].trim()}).filter(function(r){return t||e.keysToRemove.includes(r)||e.dynamicKeysToRemove.some(function(t){return r.startsWith(t)})}).forEach(function(t){return e.remove(t)}),this},t.prototype.getCookieByPrefix=function(t){return document.cookie.split("; ").map(function(t){return t.split("=")[0]}).filter(function(e){return e.startsWith(t)})},t.prototype.clearCookieByPrefix=function(t){var e=this;return this.getCookieByPrefix(t).forEach(function(t){return e.remove(t)})},t}();"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),"undefined"!=typeof global&&(global.salla=global.salla||global.Salla||{},global.Salla=global.salla),Salla.status="base",Salla.config=new T$2,Salla.logger=j$3,Salla.event=new L$3,Salla.helpers=O$2,Salla.storage=new F$3,Salla.cookie=new R$3,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"2.14.392"};var N$3=Salla;
4004
+ function s$1(t,e){ void 0===e&&(e=false),t+="";for(var r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],o=["0","1","2","3","4","5","6","7","8","9"],i=(e=e||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:o,a=e?o:n,s=0;s<i.length;s++)r=new RegExp(i[s],"g"),t=t.replace(r,a[s]);return t.replace(e?"٫":".",e?".":"٫")}function l$2(t){var e=("".concat(t).match(/\./g)||[]).length;return e&&1!==e?l$2(t.replace(/\.(.+)\./g,".$1")):t}function c$3(t){return "".concat(t).startsWith("https://")||"".concat(t).startsWith("http://")}function u$3(t){if(c$3(t))return t;var e=Salla.config.get("store.url");return e||(e=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",e)),e.rtrim("/")+"/"+(null==t?void 0:t.ltrim("/"))}function p$1(t,e,r){if(r=r||window.location.href,!e||!t)return r;var n=new RegExp("([?&])"+t+"=[^&]+[&]?","g");return (r=r.replace(n,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+t+"="+encodeURIComponent(e)).replace(/&$|\?$/,"")}function d$3(t){return window.location.origin+"/"+(null==t?void 0:t.ltrim("/"))}function f$2(t){return c$3(t)?t:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==t?void 0:t.ltrim("/")):d$3("themes/"+Salla.config.get("theme.name")+"/"+(null==t?void 0:t.ltrim("/")))}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,function(t){return t.toUpperCase().replace(/[^a-zA-Z\d]/g,"")})},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this.toString():"#"+this.toString()},String.prototype.replaceArray=function(t,e){for(var r,n=this,o=0;o<t.length;o++)r=new RegExp(t[o],"g"),n=n.replace(r,e[o]);return n},String.prototype.rtrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("["+t+"]*$"),"")},String.prototype.ltrim=function(t){return void 0===t&&(t="\\s"),this.replace(new RegExp("^["+t+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var h$3=Object.freeze({__proto__:null,addParamToUrl:p$1,api:function(t){var e;return (null===(e=Salla.config.get("store.api",u$3("")))||void 0===e?void 0:e.rtrim("/"))+"/"+(null==t?void 0:t.ltrim("/"))},asset:f$2,base:function(t){return c$3(t)?t:"https://"+new URL(u$3("/")).hostname+"/"+(null==t?void 0:t.ltrim("/"))},baseUrl:d$3,cdn:function(t,e,r){var n="https://cdn.salla.network/";return (e||r)&&(e=e?",width=".concat(e):"",r=r?",height=".concat(r):"",n+="cdn-cgi/image/fit=scale-down".concat(e).concat(r,",onerror=redirect,format=auto/")),n+(null==t?void 0:t.ltrim("/"))},create:function(t,e){return "custom"===t?e:u$3("offers"===t?t:"redirect/".concat(t,"/").concat(e))},domain:function(t){return c$3(t)?t:"".concat(Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/"),"/").concat(null==t?void 0:t.ltrim("/"))},get:u$3,is_full_url:c$3,is_page:function(t){return t&&Salla.config.get("page.slug")===t},is_placeholder:function(t){return f$2(salla.config.get("theme.settings.placeholder"))===f$2(t)}}),g$3=function(t,e){return g$3=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);},g$3(t,e)};var v$2=function(){return v$2=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},v$2.apply(this,arguments)};function y$3(t,e,r){if(2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}function m$3(t){return t instanceof FormData}function w$2(t){return t instanceof File}function S$2(t){return t instanceof Blob}"function"==typeof SuppressedError&&SuppressedError;var b$5=function(){function t(t){this.data=t,this.proxy=this.createProxy();}return t.prototype.createProxy=function(){var t=this;return new Proxy(this,{get:function(e,r){return r in e?e[r]:"string"==typeof r?t.get(r):void 0},set:function(e,r,n){return "string"==typeof r&&(t.set(r,n),true)},has:function(e,r){return "string"==typeof r?t.has(r):r in e},deleteProperty:function(e,r){return "string"==typeof r&&t.delete(r)}})},t.prototype.get=function(t){return m$3(this.data)?this.data.get(t):this.data[t]},t.prototype.getAll=function(t){if(m$3(this.data))return this.data.getAll(t);var e=this.data[t];return void 0===e?[]:[e]},t.prototype.set=function(t,e){var r=this;m$3(this.data)?(this.data.delete(t),null!=e&&(Array.isArray(e)?e.forEach(function(e){w$2(e)||S$2(e)?r.data.append(t,e):r.data.append(t,String(e));}):w$2(e)||S$2(e)?this.data.append(t,e):this.data.append(t,String(e)))):this.data[t]=e;},t.prototype.append=function(t,e){if(m$3(this.data))w$2(e)||S$2(e)?this.data.append(t,e):null!=e&&this.data.append(t,String(e));else {var r=this.data[t];void 0===r?this.data[t]=e:Array.isArray(r)?r.push(e):this.data[t]=[r,e];}},t.prototype.setFile=function(t,e){this.set(t,e);},t.prototype.getFile=function(t){var e=this.get(t);return w$2(e)?e:null},t.prototype.getFiles=function(t){return this.getAll(t).filter(w$2)},t.prototype.has=function(t){return m$3(this.data)?this.data.has(t):t in this.data},t.prototype.delete=function(t){return m$3(this.data)?(this.data.delete(t),true):delete this.data[t]},t.prototype.keys=function(){if(!m$3(this.data))return Object.keys(this.data);for(var t=new Set,e=0,r=this.data.entries();e<r.length;e++){var n=r[e][0];t.add(n);}return Array.from(t)},t.prototype.values=function(){if(!m$3(this.data))return Object.values(this.data);for(var t=[],e=0,r=this.data.entries();e<r.length;e++){var n=r[e][1];t.push(n);}return t},t.prototype.entries=function(){return m$3(this.data)?Array.from(this.data.entries()):Object.entries(this.data)},t.prototype.toObject=function(){if(!m$3(this.data))return v$2({},this.data);for(var t={},e=0,r=this.data.entries();e<r.length;e++){var n=r[e],o=n[0],i=n[1];void 0!==t[o]?(Array.isArray(t[o])||(t[o]=[t[o]]),t[o].push(i)):t[o]=i;}return t},t.prototype.getFileInfo=function(t){var e=this.getFiles(t);return 0===e.length?null:e.map(function(t){return {name:t.name,size:t.size,type:t.type}})},t.prototype.isFile=function(t){var e=this.get(t);return w$2(e)||S$2(e)},t.prototype.getRawData=function(){return this.data},t.prototype.getProxy=function(){return this.proxy},t}();function _$2(t,e,r){var n,o=t[0];return r&&0==t.length?Array.isArray(r)?(r.push(e),r):[r,e]:Array.isArray(r)?(r.push(e),r):"string"==typeof r?[r,e]:r?(r[o]=_$2(t.slice(1),e,r[o]),r):o?((n={})[o]=_$2(t.slice(1),e),n):""===o?[e]:e}function x$3(){return window.self!==window.top}var A$3,E$3,k$3,P$2,O$2={digitsOnly:function(t){return s$1(t,true).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function t(e,r){if(void 0===r&&(r=false),"string"==typeof e)return document.querySelectorAll(e).forEach(function(e){return t(e,r)});if(e){var n=Salla.helpers.digitsOnly(e.value);return e.min&&n<parseInt(e.min)?e.value=e.min:e.max&&n>parseInt(e.max)?e.value=e.max:e.maxLength>=1&&n.toString().length>e.maxLength?e.value=n.toString().substring(0,e.maxLength):e.value=r||e.dataset.hasOwnProperty("digitsWithDecimal")?l$2(n):n.replace(/\D/g,"")}Salla.logger.warn("Can't find Object With Id: "+e);},number:s$1,money:function(t,e){ void 0===e&&(e=true);var r=Salla.config.currency(null==t?void 0:t.currency).symbol;return t=s$1(t="object"==typeof t?t.amount:t)+" "+r,e&&["SAR","ر.س"].includes(r)&&Salla.config.get("store.settings.use_sar_symbol")&&(t=t.replace(r,"<i class=sicon-sar></i>")),t},isIframe:x$3,isPreview:function(){return x$3()},setNested:function(t,e,r){for(var n=t,o=e.split("."),i=o.length,a=0;a<i-1;a++){var s=o[a];n[s]||(n[s]={}),n=n[s];}return n[o[i-1]]=r,t},getNested:function(e,r,n){var o=t$2.default?t$2.default(e,r):t$2(e,r);return void 0!==o?o:n},inputData:function(t,e,r){if(void 0===r&&(r={}),t.includes("[")){var n=t.split("]").join("").split("["),o=n[0],i=r&&"object"==typeof r?r[o]:void 0;return {name:o,value:_$2(n.slice(1),e,i)}}return {name:t,value:e}},url:h$3,addParamToUrl:p$1,debounce:function(t,e){e=e||100;var r,n=[];return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];return clearTimeout(r),r=setTimeout(function(){var e=t.apply(void 0,o);n.forEach(function(t){return t(e)}),n=[];},e),new Promise(function(t){return n.push(t)})}},hasApplePay:function(){var t;try{return !!(null===(t=window.ApplePaySession)||void 0===t?void 0:t.canMakePayments())}catch(t){return console.error(t),false}},createFormDataWrapper:function(t){return new b$5(t).getProxy()},isAppleDevice:function(){try{var t=navigator.userAgent||"",e=navigator.platform||"",r=/iPhone|iPad|iPod/i.test(t),n=/Mac/i.test(e);return r||n}catch(t){return console.error(t),false}},isIOSDevice:function(){try{var t=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(t)}catch(t){return console.error(t),false}},isWebView:function(){try{if(void 0===window.navigator)return false;var t=window.navigator.userAgent,e=/iP(hone|od|ad)/.test(t)&&/AppleWebKit/.test(t)&&!/Safari/.test(t),r=/\bwv\b/.test(t)||/Android/.test(t)&&/AppleWebKit/.test(t)&&!/Chrome/.test(t);return e||r}catch(t){return console.error(t),false}}},j$3=(A$3=console,E$3=[],k$3=[],P$2={log:function(t,e){if(A$3&&salla.config.isDebug()){E$3.push([e,t]),"trace"===salla.config.get("debug")&&(e="trace");var r=A$3.log,n=void 0===e?r:this.__dict__[e]||r,o=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"];k$3.forEach(function(t){o[0]+=t[0],o.push(t[1]);});var i={event:"#CFF680",backend:"#7b68ee"}[e];i&&(o[0]+="%c"+e[0].toUpperCase()+e.substring(1),o.push("margin-left: 5px;color: ".concat(i,";font-weight:bold; border:1px solid ").concat(i,"; padding: 2px 6px; border-radius: 5px;"))),n.call.apply(n,y$3([A$3],o.concat.apply(o,t),false));}},__dict__:{trace:A$3.trace,debug:A$3.debug,info:A$3.info,warn:A$3.warn,error:A$3.error}},{event:function(){P$2.log(arguments,"event");},trace:function(){P$2.log(arguments,"trace");},debug:function(){P$2.log(arguments,"debug");},info:function(){P$2.log(arguments,"info");},warn:function(){P$2.log(arguments,"warn");},error:function(){P$2.log(arguments,"error");},log:function(){P$2.log(arguments,void 0);},backend:function(){P$2.log(arguments,"backend");},logs:function(t){[t].flat().forEach(function(t){return t&&P$2.log([t].flat(),"backend")});},history:function(){return E$3.map(function(t){return A$3.log.apply(A$3,y$3([t[0]],t[1],false))}),E$3},addPrefix:function(t){return Array.isArray(t)?k$3.unshift(t):this.warn("addPrefix receives array only!"),this}}),T$2=function(){function t(t,e){ void 0===t&&(t={}),void 0===e&&(e={}),this.default_properties=e,this.properties_=v$2(v$2({},this.default_properties),t);}return t.prototype.merge=function(t){var e;return this.properties_=v$2(v$2({},this.properties_),t),this.properties_.store=v$2(v$2({},(null===(e=this.default_properties)||void 0===e?void 0:e.store)||{}),this.properties_.store),this},t.prototype.set=function(t,e){return t.includes(".")?(Salla.helpers.setNested(this.properties_,t,e),this):(this.properties_[t]=e,this)},t.prototype.currency=function(t){return void 0===t&&(t=void 0),t=t||this.get("user.currency_code"),this.get("currencies."+t)||Object.values(this.get("currencies"))[0]},t.prototype.get=function(t,e){return void 0===e&&(e=null),t.includes(".")?Salla.helpers.getNested(this.properties_,t,e):this.properties_.hasOwnProperty(t)?this.properties_[t]||e:e||void 0},t.prototype.all=function(){return this.properties_},t.prototype.isDebug=function(){return this.get("debug")||Salla.storage.get("debug")},t}(),L$3=function(t){function e(){var e=this;return (e=t.call(this,{wildcard:true,delimiter:"::",newListener:false,removeListener:false,maxListeners:10,verboseMemoryLeak:false,ignoreErrors:false})||this).delimiter="::","undefined"!=typeof document&&(e.body=document.querySelector("body")),e.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],e.ingoreLogEvents=["document::click","document::keyup","document::change"],e.noneFireableActions=["document.request"],e.emittedEvents=new Set,e}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t;}g$3(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);}(e,t),e.prototype.createAndDispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];this.dispatch.apply(this,y$3([t],e,false));},e.prototype.emit=function(e){for(var r,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];this.emittedEvents.add(e);var i=e.replace("::",".");if(!this.noneFireableActions.includes(i)&&Salla.call&&"function"==typeof Salla.call(i))return Salla.log("'Salla.".concat(i,"(...)' triggered using event '").concat(e,"'")),i=i.split("."),Array.isArray(n[0])&&(n=n[0]),void(r=salla[i[0]])[i[1]].apply(r,n);t.prototype.emit.apply(this,y$3([e],n,false)),this.trackEvents.apply(this,y$3([e],n,false));},e.prototype.onlyWhen=function(t,e){var r=this;return e=e||function(){},new Promise(function(n){return r.emittedEvents.has(t)?n(e()):r.once(t,function(){return n(e())})})},e.prototype.emitAsync=function(e){for(var r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];this.emittedEvents.add(e);var o=t.prototype.emitAsync.apply(this,y$3([e],r,false));try{this.trackEvents.apply(this,y$3([e],r,false));}catch(t){Salla.logger.warn("error on tracking event (".concat(e,")"),r,t);}return o},e.prototype.trackEvents=function(t){for(var e,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];if("undefined"!=typeof window)try{window.dataLayer=window.dataLayer||[];var o={event:t};r.map(function(t){return "object"==typeof t&&(o=v$2(v$2({},o),t))}),window.dataLayer.push(o);}catch(t){salla.logger.error(t.message);}Salla.logger&&!this.ingoreLogEvents.includes(t)&&(e=Salla.logger).event.apply(e,y$3([t],r,false)),this.dispatchMobileEvent.apply(this,y$3([t],r,false));},e.prototype.dispatch=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return this.emit.apply(this,y$3([t],e,false))},e.prototype.dispatchEvents=function(t){if(t)if("object"!=typeof t||Array.isArray(t))Salla.log("Events object is wrong, it should be object of {event:payload}",t);else for(var e=0,r=Object.entries(t);e<r.length;e++){var n=r[e],o=n[0],i=n[1];this.dispatch(o,i);}else Salla.log("No Events To Dispatch!",t);},e.prototype.addListener=function(t,e,r){return this.on(t,e,r)},e.prototype.addEventListener=function(t,e,r){return this.on(t,e,r)},e.prototype.listen=function(t,e){return this.on(t,e)},e.prototype.registerGlobalListener=function(t,e){return this.onAny(e)},e.prototype.dispatchMobileEvent=function(t,e){var r;if(void 0===e&&(e={}),"undefined"!=typeof window){if(window.webkit)try{return void window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:t,details:e}))}catch(t){Salla.log(t,"The native context does not exist yet");}if(null===(r=window.Android)||void 0===r?void 0:r.customEventWithData)try{window.Android.customEventWithData(t,JSON.stringify({details:e}));}catch(t){Salla.log(t,"The native context does not exist yet");}else if(window.flutter_inappwebview)try{window.flutter_inappwebview.callHandler("sallaEvent",{event:t,details:e});}catch(t){Salla.log(t,"The Flutter context does not exist yet");}else;}},e}(eventemitter2Exports.EventEmitter2),W$2=storeEngineExports.createStore([n$4,o$3,i$3,a$4],[]),D$2=storeEngineExports.createStore([o$3],[]),C$3=storeEngineExports.createStore([i$3],[]),F$3=function(){function t(){var t=this;this.clearableItems=["cart","user","salla::wishlist","token"],Salla.event.on("storage::item.remove",function(e){return t.remove(e)}),Salla.event.on("storage::item.set",function(e,r){return t.set(e,r)}),this.store=W$2,this.session=D$2,this.cookie=C$3;}return t.prototype.set=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0],o=((r={})[n]=this.store.get(n),r);return o=Salla.helpers.setNested(o,t,e),this.store.set(n,o[n])}return this.store.set(t,e)},t.prototype.remove=function(t){return this.store.remove(t)},t.prototype.clearAll=function(t){var e=this;if(void 0===t&&(t=false),t)return this.store.clearAll();this.clearableItems.forEach(function(t){e.store.remove(t);});},t.prototype.get=function(t,e){var r;if(t.includes(".")){var n=t.split(".")[0];return Salla.helpers.getNested(((r={})[n]=this.store.get(n),r),t)}return this.store.get(t,e)},t.prototype.prefixKey=function(t){return "".concat(t,"_").concat(Salla.config.get("store.id"))},t.prototype.setWithTTL=function(t,e,r,n){ void 0===r&&(r=10),void 0===n&&(n="store");var o=this.prefixKey(t),i=(new Date).getTime()+60*r*1e3;return this[n].set(o,{value:e,expiry:i})},t.prototype.getWithTTL=function(t,e,r){ void 0===e&&(e=null),void 0===r&&(r="store");var n=this.prefixKey(t),o=this[r].get(n);return o?(new Date).getTime()>o.expiry?(this[r].remove(n),e):o.value:e},t}(),R$3=function(){function t(){var t=this;this.keysToRemove=["__said","__ssid","theme_edit","ws_port","s-token"],this.dynamicKeysToRemove=["affiliate","cart"],Salla.event.on("cookies::remove",function(e){return t.remove(e)}),Salla.event.on("cookies::add",function(e,r){return t.set(e,r)});}return t.prototype.get=function(t){var e;return null===(e=document.cookie.split("; ").find(function(e){return e.startsWith(t+"=")}))||void 0===e?void 0:e.split("=")[1]},t.prototype.set=function(t,e,r){ void 0===e&&(e=""),void 0===r&&(r=10);var n="";if(r){var o=new Date;o.setTime(o.getTime()+24*r*60*60*1e3),n="; expires="+o.toUTCString();}var i=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=").concat(e).concat(n,"; path=/; SameSite=").concat(i,"; secure"),this},t.prototype.remove=function(t){var e=salla.helpers.isIframe()?"None":"Lax";return document.cookie="".concat(t,"=; Max-Age=0; path=/; SameSite=").concat(e,"; secure"),this},t.prototype.clearAll=function(t){return void 0===t&&(t=false),this.clean(t)},t.prototype.clean=function(t){var e=this;return document.cookie.split(";").map(function(t){return t.split("=")[0].trim()}).filter(function(r){return t||e.keysToRemove.includes(r)||e.dynamicKeysToRemove.some(function(t){return r.startsWith(t)})}).forEach(function(t){return e.remove(t)}),this},t.prototype.getCookieByPrefix=function(t){return document.cookie.split("; ").map(function(t){return t.split("=")[0]}).filter(function(e){return e.startsWith(t)})},t.prototype.clearCookieByPrefix=function(t){var e=this;return this.getCookieByPrefix(t).forEach(function(t){return e.remove(t)})},t}();"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),"undefined"!=typeof global&&(global.salla=global.salla||global.Salla||{},global.Salla=global.salla),Salla.status="base",Salla.config=new T$2,Salla.logger=j$3,Salla.event=new L$3,Salla.helpers=O$2,Salla.storage=new F$3,Salla.cookie=new R$3,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"2.14.393"};var N$3=Salla;
4005
4005
 
4006
4006
  var js = {exports: {}};
4007
4007
 
@@ -12700,7 +12700,7 @@ function jitsuAnalytics(_opts) {
12700
12700
  // }
12701
12701
  }
12702
12702
 
12703
- let n=function(e,t,a){return alert(e)},o=function(e,t){return n(e,l.error,t)},l={error:"error",success:"success",info:"info"};var u={fire:function(e,t,a){return n(e,t,a)},setNotifier:function(e){n=e,salla.event.emit("twilight::notifier.changed");},error:o,success:function(e,t){return n(e,l.success,t)},info:function(e,t){return n(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",()=>{e.forEach(e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,o(t.innerHTML),salla.event.emit("twilight::error",e);});}));},types:l};class c{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let s=r.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return s.forEach(e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}}),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return false},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach(e=>{e.files.length||e.setAttribute("disabled","");});var a=new FormData(this);return t.forEach(e=>{e.files.length||e.removeAttribute("disabled");}),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||(null==a?void 0:a.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach(r=>{let s=(null==a?void 0:a.dataset[r])||this.dataset[r];if(s){var i=window[s];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${s}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+s+"() not found!");}}),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class d{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);});}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,async function(...e){return t(...e)})};}getEventName(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,a={}){return Salla.event.addListener(this.getEventName(e),t,a)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function h$1(){return h$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e},h$1.apply(null,arguments)}function p(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=true);}Salla.event.auth=new class extends d{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally(()=>this.dispatch("loggedIn",e))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends d{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},this.after_init();}updated(e,t={}){var a;return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(a=e.cart.free_shipping_bar)&&a.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",h$1({},e.cart,{fromLatestFetched:t.fromLatestFetched}))):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated",{fromLatestFetched:t.fromLatestFetched}))}latestFetched(e){return this.updated(e.data,{fromLatestFetched:true}),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends d{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched",orderEdited:"order.edited",orderNotEdited:"order.not.edited"},this.after_init();}},Salla.event.scope=new class extends d{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init();}},Salla.event.rating=new class extends d{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init();}},Salla.event.booking=new class extends d{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.comment=new class extends d{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.landing=new class extends d{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.loyalty=new class extends d{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init();}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends d{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed",productOptionsFetched:"options.fetched",productOptionsNotFetched:"options.not.fetched"},this.after_init();}},Salla.event.profile=new class extends d{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends d{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends d{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);});}fireEvent(e,t,...a){return this.fireEventForElements(e,t,false,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,true,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,false,...r));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const s=new CustomEvent(t,...r);return e.dispatchEvent(s)}},Salla.event.wishlist=new class extends d{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init();}},Salla.event.infiniteScroll=new class extends d{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init();}},Salla.event.notifications=new class extends d{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.component=new class extends d{constructor(){super(),this.namespace="component",this.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},this.after_init();}},Salla.event.advertisement=new class extends d{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init();}},Salla.event.navigation=new class extends d{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.metadata=new class extends d{constructor(){super(),this.namespace="metadata",this.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},this.after_init();}},Salla.event.on("twilight::initiated",()=>{Object.keys(Salla).forEach(e=>{"object"==typeof(e=Salla[e])&&(p(e),Object.keys(e).forEach(t=>{p(e[t]);}));});}),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"==="production",token:null,fastRequests:true,canLeave:true,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=false,Salla.config.triedToGetLanguages_=false,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{var e;if(Salla.config.triedToGetLanguages_||Salla.config.get("languages",[]).length>0)return Salla.config.get("languages",[]);Salla.config.triedToGetLanguages_=true;let t=true,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map(e=>{t&&(a=[],t=false),e.code=e.code||e.iso_code,e.url=salla.url.get(e.code),e.is_rtl=e.is_rtl||e.rtl,a.push(e);}),Salla.config.set("languages",a),a},Salla.config.currencies=async()=>{var e;if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=true;let t=true,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map(e=>{t&&(a={},t=false),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e;}),Salla.config.set("currencies",a),a},Salla.config.isMobileApp=()=>{var e;return ["ios","android"].includes(null==(e=Salla.analytics)||null==(e=e.jitsuAnalytics)||null==(e=e.getContextProperty("app"))||null==(e=e.platform)?void 0:e.toLowerCase())};class g{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:true,exclude:[]};}after_init(){}normalRequest(e,t=void 0,a=null){let r=Array.isArray(e),s=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach(function(t){e[t[0]]=t[1];}),t={params:e};}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?s=salla.url.get(s):"http"!==s.substring(0,4)&&(s=salla.url.api(s)),Salla.api.request(s,t,a,{headers:i})}request(e,t=void 0,a=null){return !salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class m extends g{constructor(){super(),this.addToCartTries=0,this.guestCartAssigned=false,this.namespace="cart",this._pendingCartIdRequest=null,this._pendingAssignRequest=null,this.endpoints={latest:"cart/latest",latestApi:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote",offers:"offers/cart/{cartId}",giftCartDetails:"cart/{cartId}/buy-as-gift",cartGiftToCart:"cart/{cart_id}/buy-as-gift",assign:"cart/{cartId}/assign?merge=1"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",()=>salla.api.cart.getCurrentCartId(false,"api::initiated")),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",async function(){try{await Salla.api.cart.assign();}catch(e){Salla.log("Error on assign after verified",e);}return Salla.api.cart.getCurrentCartId(true,"auth::verified")},{async:true}),salla.event.on("twilight::initiated",()=>salla.api.cart.syncGuestCart()),salla.event.on("profile::info.fetched",()=>this._checkCurrentCart(true)),salla.event.on("twilight::error",e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset());}_checkCurrentCart(e=false){var t,a;let r=salla.storage.get("cart"),s=null==(t=salla.config.get("user"))?void 0:t.id,i=null==(a=salla.config.get("store"))?void 0:a.id;r&&r.id&&!e&&(r.user_id===s&&r.store_id===i||(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log("Api:: case2 => The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),salla.cart.api.reset()),salla.url.is_page("cart")&&r.id!==salla.config.get("page.id")&&(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log(`Api:: case2 => The cart is different between storage:${r.id} & session:${salla.config.get("page.id")} !`),salla.cart.api.reset()));}async getCurrentCartId(e=false,t="getCurrentCartId"){if(Salla.cart.api._pendingCartIdRequest)return Salla.cart.api._pendingCartIdRequest;Salla.cart.api._pendingCartIdRequest=async function(){try{if(!e){if(Salla.cart.api.latestCart)return Salla.cart.api.latestCart.cart.id;let e=Salla.storage.get("cart.id");if(e)return e}let a=await Salla.cart.api.latest(t);return Salla.cart.api.latestCart=a.data,Salla.cart.api.latestCart.cart.id}finally{Salla.cart.api._pendingCartIdRequest=null;}}();let a=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,a}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request(salla.auth.api.isSessionless()?"latestApi":"latest",{params:{source:"",callerName:e}}).then(e=>(salla.api.cart.set(e.data.cart),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.api.cart.reset(),salla.event.cart.latestFailed(e),e})}async details(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.details"),this.request(["details",e],{params:{with:t}}).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async quickAdd(e,t,a){return this.addItem({id:e,quantity:t,offerType:a,endpoint:"quickAdd"})}async addItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let r=salla.form.getPossibleValue(a.payload,["endpoint"]);r&&["addItem","quickAdd"].includes(r)||(r=salla.form.getPossibleValue(a.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let s=null==(t=a.payload)?void 0:t.source;a.payload&&delete a.payload.source,Salla.cart.api.addToCartSource=s||null;let i=await Salla.api.cart.getCurrentCartId(false,"salla.api.cart.addItem");try{a.payload=Salla.helpers.createFormDataWrapper(a.payload||{}),await Salla.cart.event.beforeAddItem(a);}catch(e){}return this.request([r,i,a.id],a.payload.getRawData()).then(function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,a.id);}catch(e){Salla.log(e);}return e}).catch(function(t){if(!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(t,a.id),t})}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteItem");return this.request(["deleteItem",a,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.updateItem");return "Object"===(null==(t=a.payload.constructor)?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),this.request(["updateItem",r,a.id],a.payload).then(function(e){return salla.cart.event.itemUpdated(e,a.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,a.id),e})}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteImage");return this.request(["deleteImage",t,e]).then(function(t){return salla.cart.event.imageDeleted(t,e),t}).catch(function(t){throw salla.cart.event.imageNotDeleted(t,e),t})}async status(e,t=false){e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.status");const a={has_apple_pay:salla.helpers.hasApplePay()};t&&(a.guest_checkout=1);try{await salla.cart.event.submitting();}catch(e){salla.log("Error on: salla.cart.event.submitting()");}return this.request(["status",e],{params:a})}async submit(e=false,t=false){const a=salla.config.get("store.features",[]).includes("embedded-login-checkout");if(salla.config.isGuest()){if(!a&&!t)return salla.cart.loginOnCartPage();try{await salla.api.cart.syncGuestCart();}catch(e){salla.log("Error on syncGuestCart during guest checkout",e);}}let r;if(e)try{var s;const e=await Salla.api.cart.assign();r=null==e||null==(s=e.data)?void 0:s.cart_id;}catch(e){Salla.log("Error on assign after login from submit",e);}const i=salla.config.isGuest()&&(t||a);this.status(null!=r?r:await salla.api.cart.getCurrentCartId(false,"salla.api.cart.submit"),i).then(e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(!a)return window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",false===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload();if(!["checkout","refresh","login"].includes(a)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===a)return salla.cart.loginOnCartPage();if("checkout"===a){var r;let t=null==(r=e.data.next_step)?void 0:r.url;if(!t){let e="Checkout URL is missing from response";throw salla.cart.event.submitFailed(e),e}return salla.helpers.hasApplePay()&&(t+=(t.includes("?")?"&":"?")+"has_apple_pay=true"),window.location.href=t}window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),window.location.reload();}).catch(function(a){var r;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let s=404===(null==a||null==(r=a.response)||null==(r=r.data)?void 0:r.status);if(s&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit(e,t);throw s&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(a),a});}getCartPayload(e){var t;let a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,a="object"==typeof a?a:void 0,{id:e,payload:a}}normalRequest(e,t=void 0,a=null){var r=this;return super.normalRequest(e,t,a).catch(async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e})}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset();}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.addCoupon");return this.request(["addCoupon",t],{coupon:e}).then(function(e){var a;let r=salla.storage.get("cart");return r&&null!=(a=e.data)&&null!=(a=a.cart)&&a.coupon&&(r.coupon=e.data.cart.coupon,salla.storage.set("cart",r)),salla.event.cart.couponAdded(e,t),e}).catch(function(e){throw salla.event.cart.couponAdditionFailed(e,t),e})}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then(function(t){let a=salla.storage.get("cart");return a&&a.coupon&&(delete a.coupon,salla.storage.set("cart",a)),salla.event.cart.couponDeleted(t,e),t}).catch(function(t){throw salla.event.cart.couponDeletionFailed(t,e),t})}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then(e=>(salla.event.cart.quickOrderSettingFetched(e),e)).catch(e=>{throw salla.event.cart.quickOrderSettingFailed(e),e})}createQuickOrder(e){return this.request("createQuickOrder",e).then(e=>(salla.event.cart.quickOrderSucceeded(e),e)).catch(e=>{throw salla.event.cart.quickOrderFailed(e),e})}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.priceQuote")]).then(e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then(()=>(setTimeout(()=>window.location.href=salla.url.get("/"),1e3),e)))).catch(e=>salla.event.cart.priceQuoteFailed(e).then(()=>{var t;throw 404===(null==(t=e.error)?void 0:t.code)&&window.location.reload(),e}))}loginOnCartPage(){salla.auth.setCanRedirect(false),salla.event.dispatch("login::open",{withoutReload:true,source:"cart-submit"}),salla.auth.event.onLoggedIn(()=>{salla.event.dispatch("login::close"),salla.cart.submit(true);});}set(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart();}async offers(){const e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.offers");return this.request(["offers",e]).then(e=>(salla.event.cart.offersFetched(e),e)).catch(e=>{throw salla.event.cart.offersFailed(e),e})}async getGiftCartDetails(){let e=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.getGiftCartDetails");return this.request(["giftCartDetails",e]).then(t=>(salla.product.event.giftFetched(t,e),t)).catch(t=>{throw salla.product.event.giftFetchFailed(t,e),t})}async addCartGiftToCart(e,t=false){let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then(e=>(salla.product.event.addGiftToCartSucceeded(e,a),t&&(window.location.href=e.redirect),e)).catch(e=>{throw salla.product.event.addGiftToCartFailed(e,a),e})}async syncGuestCart(){if(!salla.config.isGuest())return;const e=salla.api.cart.getCartCookiePrefix(),t=salla.cookie.getCookieByPrefix(e),a=salla.storage.get("cart.id");if(!a&&t.length)try{var r;const t=null==(r=(await salla.api.cart.latest()).data)||null==(r=r.cart)?void 0:r.id;t&&salla.api.cart.setCartCookie(e,t);}catch(e){salla.log("Failed to fetch latest cart:",e);}salla.cookie.clearCookieByPrefix(e),a&&(salla.config.set("headers.s-cart-id",a),salla.api.cart.setCartCookie(e,a));}async assign(){var e=this;if(Salla.api.cart._pendingAssignRequest)return Salla.api.cart._pendingAssignRequest;let t=Salla.storage.get("cart.id");return !(!t||Salla.api.cart.guestCartAssigned)&&(Salla.api.cart._pendingAssignRequest=async function(){try{const a=await e.request(["assign",t]);return Salla.api.cart.guestCartAssigned=true,a}catch(e){throw e}finally{Salla.api.cart._pendingAssignRequest=null;}}(),Salla.api.cart._pendingAssignRequest)}setCartCookie(e,t){salla.cookie.set(`${e}-${t}`,t,1);}getCartCookiePrefix(){return "cart-id-"+salla.config.get("store.id")}}class f extends g{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then(e=>(salla.loyalty.event.programFetched(e),e)).catch(e=>{throw salla.loyalty.event.programNotFetched(e),e})}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then(function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t}).catch(function(t){throw salla.loyalty.event.exchangeFailed(t,e),t})}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.reset"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then(e=>(salla.loyalty.event.resetSucceeded(e),e)).catch(e=>{throw salla.loyalty.event.resetFailed(e),e})}}class D extends g{constructor(){super(),this.namespace="auth",this.canRedirect_=true,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.inIframe=salla.helpers.isIframe(),Salla.event.on("twilight::init",function(){if(Salla.config.isGuest()&&location.href.includes("force_logout"))return delete Salla.api.axios.defaults.headers.common.Authorization,Salla.api.auth.logout("twilight",false)}),this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){var t;null!=(t=e)&&t.data&&(e=e.data);let a=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(a)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",a],e).then(function(e){return salla.auth.event.codeSent(e,a),e}).catch(function(e){throw salla.auth.event.codeNotSent(e,a),salla.auth.api.trackBlockedError(e,"login"),e})}async verify(e,t=true){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=false!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let r=await salla.auth.api.request(["verify",a],e);return 200!==(null==r?void 0:r.status)?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)}async handlAfterAuthenticatedResponse(e,t){var a;e.data||(e={data:e});let r="authenticated"===(null==(a=e.data)?void 0:a.case);return r&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),r&&await salla.auth.event.loggedIn(e).then(()=>salla.auth.api.afterUserLogin()),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then(function(t){return salla.auth.event.codeSent(t,e),t}).catch(function(t){throw salla.auth.event.codeNotSent(t,e),salla.auth.api.trackBlockedError(t,"resend"),t}):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){var t=this;let a;return e.data&&(a=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(async function(e){var r;return salla.auth.event.registered.call(a,e),"authenticated"===(null==(r=e.data)?void 0:r.case)&&(salla.auth.event.tokenFetched(e.data.token),!t.inIframe&&!t.isSessionless()&&await salla.auth.request("auth/jwt",{callerName:"salla.auth.api.register"}),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(a,e),salla.auth.api.trackBlockedError(e,"register"),e})}handleIframeReadyAction(e,t){var a;null==(a=e.contentWindow)||a.postMessage({source:"logout",type:"init",data:{id:salla.config.get("store.id"),lang:"ar",appUrl:t,apiUrl:salla.config.get("store.api").replace(/\/+$/,""),settings:salla.config.all(),storage:{}}},"*");}appendIframeAndLogout(){return new Promise(e=>{let t=salla.config.get("login.url","https://accounts.salla.com");const a=document.createElement("iframe");a.style.display="none",a.src=`${t}/logout`;const r=s=>{if("login"!==s.data.source)return;let i=s.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",s.data),["logged-out","ready"].includes(i)){if("ready"===i)return this.handleIframeReadyAction(a,t);window.removeEventListener("message",r),a.remove(),e();}};window.addEventListener("message",r),document.body.appendChild(a);})}logout(e="twilight",t=true){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then(()=>this.appendIframeAndLogout()).then(()=>{if(!t)return;let a=salla.url.get(`logout?from=${e}`);console.log(`Going to ${a}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=a;}catch(e){salla.log(e);}}).catch(e=>console.error("Error during logout:",e))}refresh(){return this.request("refresh").then(function(e){return salla.auth.event.tokenFetched(e.data.token),e}).catch(function(e){throw salla.auth.event.refreshFailed(e),e})}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload);}isSessionless(){var e;return "sessionless"===(null!=(e=salla.config.get("auth.mode"))?e:salla.config.get("login.mode"))}trackBlockedError(e,t){var a;void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"])&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message});}}class F extends g{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders",editOrder:"orders/{id}"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get",editOrder:"put"},this.after_init();}show(e){let t=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["url"]);}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:salla.helpers.hasApplePay()}}).then(function(t){return salla.event.order.canceled(t,e),t}).catch(function(t){throw salla.event.order.notCanceled(t,e),t})}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then(function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}reorderProduct(e){return e=e||salla.config.get("page.id"),this.request(["reorderProduct",e]).then(function(t){const a=h$1({},t.data,{type:"reorder",id:e}),r=h$1({},t,{data:a});return salla.event.order.orderCreated(r,t.data.order_id),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then(e=>(salla.event.order.invoiceSent(e,t),e)).catch(e=>{throw salla.event.order.invoiceNotSent(e,t),e})}editOrder(e,t){return e=e||salla.config.get("page.id"),this.request(["editOrder",e],t).then(function(t){return salla.event.order.orderEdited(t,e),t}).catch(function(t){throw salla.event.order.orderNotEdited(t,e),t})}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.order.ordersFetched(e),e}).catch(function(e){throw salla.event.order.ordersNotFetched(e),e})}}class v extends g{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftProductDetails:"products/{product_id}/buy-as-gift",productGiftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},this.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get"},this.after_init();}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then(function(e){return salla.product.event.priceUpdated(e,a),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,a),e})}categories(e){return this.request(["categories",e||""],null,"get").then(function(e){return salla.product.event.categoriesFetched(e),e}).catch(function(e){throw salla.product.event.categoriesFailed(e),e})}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then(function(t){return salla.product.event.availabilitySubscribed(t,e),t}).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}search(e){var t;let a=e.data;if(a||(a={params:"string"==typeof e?{query:e}:e}),!(e=a instanceof FormData?a.get("query"):a.query||(null==(t=a.params)?void 0:t.query))){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",a,"get").then(function(t){return salla.product.event.searchResults(t,e),t}).catch(function(t){throw salla.product.event.searchFailed(t,e),t})}offers(e){var t;if(!(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then(function(t){return salla.product.event.offersFetched(t,e),t}).catch(function(t){throw salla.product.event.fetchOffersFailed(t,e),t})}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then(t=>(salla.product.event.sizeGuideFetched(t,e),t)).catch(t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t})}getGiftProductDetails(e){return this.request(["giftProductDetails",e]).then(t=>(salla.product.event.giftFetched(t,e),t)).catch(t=>{throw salla.product.event.giftFetchFailed(t,e),t})}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then(function(t){return salla.product.event.detailFetched(t,e),t}).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}addProductGiftToCart(e,t,a=false){return this.request(["productGiftToCart",e],t).then(t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t)).catch(t=>{throw salla.product.event.addGiftToCartFailed(t,e),t})}uploadGiftImage(e){return this.request("giftImage",e).then(e=>(salla.product.event.giftImageUploadSucceeded(e),e)).catch(e=>{throw salla.product.event.giftImageUploadFailed(e),e})}fetch(e){if(!e.source){const e="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}const t=!e.source_value,a="string"==typeof e.source_value&&"[]"===e.source_value,r=Array.isArray(e.source_value)&&!e.source_value.length;if((t||a||r)&&!["offers","latest","sales","wishlist","top-rated","reorder"].includes(e.source)){const e="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){const e="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("search"===e.source&&"string"!=typeof e.source_value){const e="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("related"===e.source&&isNaN(e.source_value)){const e="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then(async function(e){return salla.product.event.productListFetchSucceeded(e),e}).catch(e=>{throw salla.product.event.productListFetchFailed(e),e})}fetchOptions(e,t={}){if(!e||0===e.length){const e="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(e),salla.api.errorPromise(e)}const{with:a=[]}=t,r={selected:e};return a.length>0&&(r.with=a),this.request(this.endpoints.fetchOptions,{params:r},"get").then(e=>(salla.product.event.productOptionsFetched(e),e)).catch(e=>{throw salla.product.event.productOptionsNotFetched(e),e})}}class y extends g{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init();}syncUserData(e){let t={id:e.id,type:"user",email:e.email,mobile:e.phone.code+e.phone.number,country_code:e.phone.country,language_code:e.language,currency_code:e.currency,notifications:e.notifications,pending_orders:e.pending_orders,avatar:e.avatar,first_name:e.first_name,last_name:e.last_name,is_hidden_name:e.is_hidden_name,is_notifiable:e.is_notifiable,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",t),salla.storage.set("user",t);}info(){return this.request("info",null,"get").then(e=>(this.syncUserData(e.data),salla.profile.event.infoFetched(e),e)).catch(e=>{throw salla.profile.event.infoNotFetched(e),e})}update(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("update",e).then(e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateCustomFields(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("updateCustomFields",e).then(e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateContacts(e){return this.request("updateContacts",e).then(e=>(salla.profile.event.verificationCodeSent(e),e)).catch(e=>{throw salla.event.profile.updateContactsFailed(e),e})}verify(e){return this.request("verify",e).then(e=>(salla.profile.event.verified(e),e)).catch(e=>{throw salla.event.profile.unverified(e),e})}updateSettings(e){return this.request("updateSettings",e).then(e=>(salla.event.profile.settingsUpdated(e),e)).catch(e=>{throw salla.event.profile.updateSettingsFailed(e),e})}delete(){return this.request("delete").then(e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.api.appendIframeAndLogout().then(()=>{salla.event.profile.deleted(e),window.location.href=salla.url.get("logout");}),e)).catch(e=>{throw salla.event.profile.notDeleted(e),e})}}class C extends g{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init();}add(e){var t;if(null!=(t=e)&&t.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,true)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["addComment","blog"==e.type?"blogs":e.type,e.id],{comment:e.comment}).then(function(t){return salla.event.comment.added(t,e.id),t}).catch(function(t){throw salla.event.comment.additionFailed(t,e.id),t})}getCommentPayload(e,t=false){let a={};if(["id","type","comment","per_page","page","sort"].forEach(t=>{let r=salla.form.getPossibleValue(e,[t]);r&&(a[t]=r);}),!t){let t=e.ids;if(t&&(a.ids=Array.isArray(t)?t:[t]),!a.ids||!a.ids.length)return "Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"}fetchComments(e){const t=e.customerId;if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const a={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(a.sort=e.sort),t&&(a.private_comments=t),this.request(["comments"],{params:a},"get").then(function(t){return salla.event.comment.fetched(t,e),t}).catch(function(t){throw salla.event.comment.fetchFailed(t,e),t})}getComments(e,t,a=1,r=5,s,i=null){const n=Array.isArray(t)?t:[t];return this.fetchComments({ids:n,type:`${e}s`,page:a,per_page:r,sort:s,customerId:i})}}class S extends g{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init();}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then(function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t}).catch(function(t){throw salla.currency.event.failed(t,e),t})}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class w extends g{constructor(){super(),this.namespace="document";}reload(){window.location.reload();}}class A extends g{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init();}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",a],t).then(function(e){return salla.event.rating.orderFetched(e,a),e}).catch(function(e){throw salla.event.rating.orderNotFetched(e,a),e})}store(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then(function(t){return salla.event.rating.storeRated(t,e),t}).catch(function(t){throw salla.event.rating.storeFailed(t,e),t})}products(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then(function(t){return salla.event.rating.productsRated(t,e),t}).catch(function(t){throw salla.event.rating.productsFailed(t,e),t})}shipping(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then(function(t){return salla.event.rating.shippingRated(t,e),t}).catch(function(t){throw salla.event.rating.shippingFailed(t,e),t})}}class E extends g{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},Salla.onReady(()=>{var e;"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||this.injectSourceIntoRequest());});}injectSourceIntoRequest(){Salla.api.axios.interceptors.request.use(e=>(e.headers=h$1({},e.headers,{"s-utm-source":"wishlist"}),e),e=>Promise.reject(e));}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["add",e]).then(t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t)).catch(function(t){throw salla.wishlist.event.additionFailed(t,e),t}):(salla.wishlist.event.additionFailed(a="Failed to get product id!"),salla.api.errorPromise(a))}remove(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["remove",e]).then(t=>(this.updateWishlistStorage(e,false),salla.wishlist.event.removed(t,e),t)).catch(function(t){throw salla.wishlist.event.removingFailed(t,e),t}):(salla.wishlist.event.removingFailed(a="Failed to get id!"),salla.api.errorPromise(a))}updateWishlistStorage(e,t=true){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a);}}class b extends g{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init();}get(){return this.request("scopes",null,"get").then(e=>(salla.scope.event.fetched(e),e)).catch(e=>{throw salla.scope.event.notFetched(e),e})}change(e){return this.request("scopes",e).then(e=>(salla.scope.event.changeSucceeded(e),e)).catch(e=>{throw salla.scope.event.changeFailed(e),e})}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then(t=>(salla.scope.event.productAvailabilityFetched(t,e),t)).catch(e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e})}}class _ extends g{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"};}async add(e,t=true){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then(function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e}).catch(function(e){throw salla.booking.event.additionFailed(e),e})}}class k extends g{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init();}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then(function(t){return salla.event.landing.detailsFetched(t,e),t}).catch(function(t){throw salla.event.landing.getDetailsFailed(t,e),t})}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then(function(t){return salla.event.landing.orderCreated(t,e).then(()=>location.href=t.data.url),t}).catch(function(t){throw salla.event.landing.orderCreationFailed(t,e),t})}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.landing.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e})}}class x extends g{constructor(){super(),this.namespace="notifications",this.endpoints={fetch:"notifications"},this.endpointsMethods={fetch:"get"},this.after_init();}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.notifications.fetched(e),e}).catch(function(e){throw salla.event.notifications.fetchFailed(e),e})}}class B{constructor(){var e,t=this;this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",async function(e){return await t.initiateRequest(e)}),salla.event.on("profile::info.fetched",e=>this.setCurrencyAndLanguage(e)),salla.event.on("auth::token.fetched",e=>{salla.storage.set("token",e),this.inIframe&&salla.log("token fetched iframe"),this.inIframe&&salla.cookie.set("s-token",e,60),this.setToken(e);}),salla.event.on("auth::token.invalid",()=>{salla.storage.remove("user"),salla.storage.remove("token");}),this.notifier_handler_disabled=false,this.axios=axios.create({baseURL:Salla.config.get("store.api",Salla.config.get("store.url")),headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":(null==(e=Salla)||null==(e=e.versions)?void 0:e.twilight)||"2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}}),this.axios.interceptors.request.use(e=>{"preview"===Salla.config.get("theme.mode")&&(e.url=Salla.url.addParamToUrl("use_username_url",1,e.url));try{var t;const a=Salla.config.get("swoole",[]),r=new RegExp(a.join("|"),"i");a.length>0&&r.test(e.url)&&(e.headers["s-store-api-version"]="swoole");const s=null==(t=Salla.analytics)?void 0:t.getAnonymousId();s&&(e.headers["s-anonymous-id"]=s);}catch(e){Salla.log("Error in request interceptor:",e);}return e},e=>Promise.reject(e));}getHeaders(){let e=h$1({},this.axios.defaults.headers.common);return delete e["Content-Type"],e}getHeader(e){var t;return null==(t=Object.entries(this.getHeaders()).filter(([t])=>t.toLowerCase()===e.toLowerCase())[0])?void 0:t[1]}setHeaders(e){return Object.entries(e).forEach(e=>this.setHeader(e[0],e[1])),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=true,await e().finally(()=>{this.notifier_handler_disabled=false;})}async initiateRequest(e){var t,a,r;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(h$1({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(r=e.user)?void 0:r.country_code},e.headers||{}));const s=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search),n=i.get("scope"),o=i.get("allocation_type"),l=i.get("allocation_id");if(n&&s&&!Salla.url.is_page("cart")){const e=Salla.storage.get("scope")||{};Salla.storage.set("scope",h$1({},e,{type:s.type,id:n},o&&{allocation_type:o},l&&{allocation_id:l})),s.id=n,Salla.cart.reset();}if((o||l)&&(Salla.url.is_page("cart")||!n||!s)){const e=Salla.storage.get("scope")||{};var u,c;if(null!=e&&e.id||null!=s&&s.id)Salla.storage.set("scope",h$1({},e,{id:null!=(u=null==e?void 0:e.id)?u:null==s?void 0:s.id,type:null!=(c=null==e?void 0:e.type)?c:null==s?void 0:s.type},o&&{allocation_type:o},l&&{allocation_id:l}));}if(s){this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const e=Salla.storage.get("scope")||{};e.allocation_type&&this.setHeader("s-scope-allocation-type",e.allocation_type),e.allocation_id&&this.setHeader("s-scope-allocation-id",e.allocation_id);}const d=Salla.storage.getWithTTL("s-utms");if(d){const e={};Object.entries(d).forEach(([t,a])=>{e[t]="string"==typeof a&&/[^\x00-\x7F]/.test(a)?encodeURIComponent(a):a;}),this.setHeaders(e);}await this.injectTokenToTheRequests(e),Salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",Salla.storage.get("affiliate_code"));}async injectTokenToTheRequests(e){var t,a,r=this;let i,n,o=this.getToken(),l="guest"===(null==(t=e.user)?void 0:t.type),u=parseInt((null==(a=e.user)?void 0:a.id)||0),c=parseInt(salla.storage.get("user.id")||0),d=salla.auth.api.isSessionless(),h=e=>{this.setToken(e),salla.event.emit("api::initiated");},p=async function(){l||d||!u?salla.auth.event.tokenInvalid():(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then(async function(){await salla.profile.info();}).catch(()=>salla.auth.event.tokenInvalid()));};if(!o)return salla.log("Api:: case 1 => current is is guest"),void await p();try{i=jwtDecode(o);}catch(e){return Salla.logger.warn("Failed to decode JWT token",e),void Salla.auth.event.tokenInvalid()}return Date.now()/1e3>i.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await p()):(n=d?parseInt(i.sub)!==c:!c||!u||c!==u||parseInt(i.sub)!==u,n?(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${i.sub} userIdInWeb:${u} userIdInStorage:${c}, isSessionless:${d}`,i.sub,u,c),this.setHeader("Authorization","Bearer "+o),void await salla.profile.info().then(async function(e){!r.inIframe&&!d&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),h(o);}).catch(()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid();})):(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void h(o)))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}cleanupTokenFromUrl(){try{const e=new URL(window.location.href);if(!e.searchParams.has("token"))return;e.searchParams.delete("token"),window.history.replaceState({},document.title,e.toString());}catch(e){Salla.logger.warn("Failed to cleanup token from URL",e);}}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t=void 0,a="get",r={}){let s={endPoint:e,payload:t,method:a,options:r},i="undefined"!=typeof event?event.currentTarget:null,n=false;return "SALLA-BUTTON"===(null==i?void 0:i.tagName)&&(n=true),n&&(null==i||i.load()),this.axios[s.method](s.endPoint,s.payload,s.options).then(e=>(n&&(null==i||i.stop()),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e)).catch(e=>{throw n&&(null==i||i.stop()),salla.event.document.requestFailed(s,e),this.handleErrorResponse(e),e})}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;try{dataLayer&&r&&dataLayer.push(r);}catch(e){salla.logger.error(e.message);}this.fireEventsForResponse(e),this.showAlert(e);}fireEventsForResponse(e){var t,a;let r=(null==e?void 0:e.events)||(null==(t=e.data)?void 0:t.events)||(null==(a=e.error)?void 0:a.events);"string"==typeof r&&(r=JSON.parse(r)),r&&Object.keys(r).forEach(e=>salla.event.dispatch(e,r[e]));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){var t,a;if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&null!=(t=e.data)&&t.message?salla.notify.fire(null==(a=e.data)?void 0:a.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach(e=>{let r=t[e];Array.isArray(r)?r.forEach(e=>a.push(e)):a.push(r);});let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=true){return new Promise((a,r)=>t?a(e):r(e))}errorPromise(e){return this.promise(e,false)}successPromise(e){return this.promise(e,true)}getToken(){if(Salla.storage.get("token"))return Salla.storage.get("token");try{var e;const t=null==(e=new URLSearchParams(window.location.search))?void 0:e.get("token");if(!t)return;if(3!==t.split(".").length)return;return this.cleanupTokenFromUrl(),t}catch(e){Salla.logger.warn("Failed to extract or validate token from URL",e);}}}class P extends g{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}?store_id={store}&lang={lang}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"};}async getMenus(e="header"){return this.request(["getMenus",e,salla.config.get("store.id"),salla.lang.getLocale()]).then(function(e){return salla.event.component.menuFetched(e),e}).catch(function(e){throw salla.event.component.menuFetchFailed(e),e})}async getReviews({per_page:e=5,type:t="all",items:a}){if(!t){const e="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}const r=!a||"string"==typeof a&&"[]"===a||Array.isArray(a)&&!a.length;if(!new Set(["all","store","categories","products","json"]).has(t)){const e="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if("all"!==t&&"store"!==t&&r){const e="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if(new Set(["products","categories"]).has(t)&&!Array.isArray(a)){const e=`Items value must be an array of ${t} id for review type of ${t}.`;return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}return this.request(["reviews"],{params:{per_page:e,type:t,items:a}},"get").then(function(e){return salla.event.component.reviewsFetched(e),e}).catch(function(e){throw salla.event.component.reviewsFetchFailed(e),e})}}class I extends g{constructor(){super(),this.namespace="booking",this.endpoints={fetch:"advertisements"},this.endpointsMethods={fetch:"get"};}async fetch(e=null){const t=e?{page:e}:{};return this.request(["fetch"],{params:t}).then(function(e){return salla.event.advertisement.fetched(e),e}).catch(function(e){throw salla.event.advertisement.fetchFailed(e),e})}}class q extends g{constructor(){super(),this.namespace="navigation",this.endpoints={breadcrumbs:"breadcrumbs"},this.endpointsMethods={breadcrumbs:"get"},this.after_init();}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.single","product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.navigation.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.navigation.breadcrumbFetchFailed(e),e})}}class T extends g{constructor(){super(),this.namespace="metadata",this.endpoints={fetchValues:"https://api.salla.dev/store/v1/metadata/values"},this.endpointsMethods={fetchValues:"get"};}async fetchValues(e,t){if(!e||!t){const e="Please provide entity type and entity ids.";return salla.metadata.event.valueNotFetch(e),salla.api.errorPromise(e)}const a={type:e,entities:Array.isArray(t)?t:[t]};return this.request(this.endpoints.fetchValues,{params:a},"get").then(e=>(salla.metadata.event.valueFetched(e),e)).catch(e=>{throw salla.metadata.event.valueNotFetch(e),e})}}class L{constructor(e){this.config=e,this.configKey="s-twilight-config",this.tempUser=e.user;}async getConfig(){if(Object.entries(this.config.store).length>2)return this.config;let e=await this.getConfigFromSession();return e||(e=await this.getConfigFromApi()),e.user=this.tempUser,e}async getConfigFromSession(){var e;let t=salla.storage.getWithTTL("session",this.configKey);return t&&"object"==typeof t&&null!=(e=t.store)&&e.id?this.config.store.id==t.store.id?t:(salla.storage.session.remove(this.configKey),null):null}getConfigFromApi(){console.log("getting Twilight initiate config using store.id ...");const e=new URL(`${(this.config.store.api||Salla.config.get("store.api")).replace(/\/$/,"")}/store/settings`);return fetch(e,{headers:Salla.api.getHeaders()}).then(e=>e.json()).then(e=>{if(200!==e.status)throw {response:e};return this.setConfigToSession(e.data)}).catch(e=>{throw Salla.api.handleErrorResponse(e),e})}setConfigToSession(e){return Salla.storage.setWithTTL("session",this.configKey,e,1800),e}}class R{constructor(){Salla.event.on("twilight::before.ready",()=>this.renderAll());}async renderAll(){Salla.hooks.renderAutoComponents([{hook:"product:single.description",tag:"salla-delivery-promise",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("delivery-promises")},{hook:"product:single.form.end",tag:"salla-fulfillment-methods",canRender:()=>Salla.url.is_page("product.single")&&!Salla.config.get("store.features",[]).includes("bullet-delivery-v2")},{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}},{hook:"body:end",tag:"salla-bullet-delivery",canRender:()=>{var e;return (null==(e=Salla.config.get("store.features"))?void 0:e.includes("bullet-delivery-v2"))&&true===Salla.config.get("store.settings.bullet_delivery.enabled")}}]),await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.helpers.isIframe()||(this.renderMaintenance(),this.renderThemePreview());}renderMaintenance(){Salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?Salla.logger.warn("salla-maintenance-alert element Existed before!"):document.body.prepend(document.createElement("salla-maintenance-alert")));}renderTemplateStore(){Salla.config.get("store.template")&&(document.body.classList.add("has-bottom-alert"),document.querySelector("salla-bottom-alert")?Salla.logger.warn("salla-bottom-alert element Existed before!"):document.body.append(document.createElement("salla-bottom-alert")));}renderAppInstall(){Salla.config.get("store.app_install_prompt")&&Salla.config.get("store.apps")&&!Salla.storage.get("app_install_prompt_disabled")&&!Salla.config.isMobileApp()&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?Salla.logger.warn("salla-app-install-alert element Existed before!"):document.body.append(document.createElement("salla-app-install-alert")));}renderThemePreview(){if("preview"!==Salla.config.get("theme.mode"))return;if(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar"))return void Salla.logger.warn("#s-theme_preview_bar element Existed before!");let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://cdn.salla.network/images/logo/logo-light.svg">\n <span style="margin:0 10px;">${Salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${Salla.config.get("theme.name")}</span></span>\n </div>\n <a href="${Salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e);}renderEdit(){let e=Salla.config.get("edit");if(!e)return;if(document.querySelector("#s-edit-alert"))return void Salla.logger.warn("#s-edit-alert element Existed before!");let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${Salla.config.get("theme.color.primary","#5cd5c4")}; color:${Salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${Salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t);}applyContentCopyright(){if(!Salla.config.get("store.settings.content_copyright"))return;["contextmenu","selectstart","copy"].forEach(e=>{document.addEventListener(e,e=>{(e=>{var t;if(!e)return false;const a=null==(t=e.tagName)?void 0:t.toLowerCase();return "input"===a||"textarea"===a})(e.target)||e.preventDefault();});}),document.addEventListener("keydown",e=>{const t=e.key.toLowerCase();("f12"===t||e.ctrlKey&&e.shiftKey&&["i","j","c"].includes(t)||e.ctrlKey&&"u"===t)&&(e.preventDefault(),e.stopPropagation());});const e=document.createElement("style");e.textContent="\n body {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n input, textarea {\n -webkit-touch-callout: auto;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n -ms-user-select: auto;\n user-select: auto;\n }\n img {\n pointer-events: none;\n -webkit-user-drag: none;\n }\n ",document.head.appendChild(e);}}class j{constructor(e){this.storeUserKey="s-store-user",Salla.event.on("twilight::initiated",()=>this.embedStoreUser()),this.embedUser(e);}embedUser(e){return e.user||(e.user=this.getUser(),e.user.language_code=Salla.cookie.get("s-lang",e.user.language_code),e.user.currency_code=Salla.cookie.get("s-curr",e.user.currency_code)),e}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return {type:"guest",language_code:Salla.cookie.get("s-lang",Salla.lang.getLocale()),currency_code:Salla.cookie.get("s-curr","SAR")}}async embedStoreUser(){if(Salla.config.isGuest())return;let e=Salla.storage.getWithTTL("session",this.storeUserKey);e||(e=await this.getStoreUserFromApi()),Salla.config.set("user",h$1({},Salla.config.get("user"),e)),Salla.log("Store user is embeded to the user object.");}async getStoreUserFromApi(){let e={};try{const t=await Salla.api.request("profile/notifications/unread");if(e.notification=t.data.count,e.is_notifiable=t.data.is_notifiable,Salla.config.get("store.features",[]).includes("loyalty-system")){const t=await Salla.api.request("profile/loyalty/points");t&&(e.loyalty_points=t.data.points);}}catch(e){Salla.log("Failed to get user services",e);}return Salla.storage.setWithTTL("session",this.storeUserKey,e,300),e}}class U{constructor(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat",sccid:"snapchat"},t=Object.keys(e),a=["utm_source","utm_medium","utm_campaign","utm_term","utm_content",...t],r={},s={};window.location.search.replace("?","").split("&").map(e=>e.split("=")).filter(([e])=>a.includes(e.toLowerCase())).forEach(([e,t])=>{let a=t||"",s=false;try{a=decodeURIComponent(t),s=true;}catch(e){Salla.log("Failed to decode UTM param:",e);}r[e.toLowerCase()]=s?a.replace(/(?:[\0-\x1F!-,\.\/:-@\[-`\{-\xA9\xAB-\xB1\xB4\xB6-\xB8\xBB\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u036F\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482-\u0489\u0530\u0557\u0558\u055A-\u055F\u0589-\u05CF\u05EB-\u05EE\u05F3-\u061F\u064B-\u065F\u066A-\u066D\u0670\u06D4\u06D6-\u06E4\u06E7-\u06ED\u06FD\u06FE\u0700-\u070F\u0711\u0730-\u074C\u07A6-\u07B0\u07B2-\u07BF\u07EB-\u07F3\u07F6-\u07F9\u07FB-\u07FF\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u083F\u0859-\u085F\u086B-\u086F\u0888\u0890-\u089F\u08CA-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962-\u0965\u0970\u0981-\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA-\u09BC\u09BE-\u09CD\u09CF-\u09DB\u09DE\u09E2-\u09E5\u09F2\u09F3\u09FA\u09FB\u09FD-\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A-\u0A58\u0A5D\u0A5F-\u0A65\u0A70\u0A71\u0A75-\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA-\u0ABC\u0ABE-\u0ACF\u0AD1-\u0ADF\u0AE2-\u0AE5\u0AF0-\u0AF8\u0AFA-\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A-\u0B3C\u0B3E-\u0B5B\u0B5E\u0B62-\u0B65\u0B70\u0B78-\u0B82\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BCF\u0BD1-\u0BE5\u0BF3-\u0C04\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C3E-\u0C57\u0C5B\u0C5E\u0C5F\u0C62-\u0C65\u0C70-\u0C77\u0C7F\u0C81-\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA-\u0CBC\u0CBE-\u0CDB\u0CDF\u0CE2-\u0CE5\u0CF0\u0CF3-\u0D03\u0D0D\u0D11\u0D3B\u0D3C\u0D3E-\u0D4D\u0D4F-\u0D53\u0D57\u0D62-\u0D65\u0D79\u0D80-\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DE5\u0DF0-\u0E00\u0E31\u0E34-\u0E3F\u0E47-\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EB1\u0EB4-\u0EBC\u0EBE\u0EBF\u0EC5\u0EC7-\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F1F\u0F34-\u0F3F\u0F48\u0F6D-\u0F87\u0F8D-\u0FFF\u102B-\u103E\u104A-\u104F\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B-\u1368\u137D-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u1712-\u171E\u1732-\u173F\u1752-\u175F\u176D\u1771-\u177F\u17B4-\u17D6\u17D8-\u17DB\u17DD-\u17DF\u17EA-\u17EF\u17FA-\u180F\u181A-\u181F\u1879-\u187F\u1885\u1886\u18A9\u18AB-\u18AF\u18F6-\u18FF\u191F-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19FF\u1A17-\u1A1F\u1A55-\u1A7F\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1B04\u1B34-\u1B44\u1B4D-\u1B4F\u1B5A-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BFF\u1C24-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C8B-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1CFB-\u1CFF\u1DC0-\u1DFF\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u206F\u2072\u2073\u207A-\u207E\u208A-\u208F\u209D-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A-\u245F\u249C-\u24E9\u2500-\u2775\u2794-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF4-\u2CFC\u2CFE\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF-\u2E2E\u2E30-\u3004\u3008-\u3020\u302A-\u3030\u3036\u3037\u303D-\u3040\u3097-\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u3191\u3196-\u319F\u31C0-\u31EF\u3200-\u321F\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA66F-\uA67E\uA69E\uA69F\uA6F0-\uA716\uA720\uA721\uA789\uA78A\uA7DD-\uA7F0\uA802\uA806\uA80B\uA823-\uA82F\uA836-\uA83F\uA874-\uA881\uA8B4-\uA8CF\uA8DA-\uA8F1\uA8F8-\uA8FA\uA8FC\uA8FF\uA926-\uA92F\uA947-\uA95F\uA97D-\uA983\uA9B3-\uA9CE\uA9DA-\uA9DF\uA9E5\uA9FF\uAA29-\uAA3F\uAA43\uAA4C-\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAC3-\uAADA\uAADE\uAADF\uAAEB-\uAAF1\uAAF5-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABE3-\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB1E\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD06\uDD34-\uDD3F\uDD79-\uDD89\uDD8C-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEE0\uDEFC-\uDEFF\uDF24-\uDF2C\uDF4B-\uDF4F\uDF76-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDD6F\uDD7B\uDD8B\uDD93\uDD96\uDDA2\uDDB2\uDDBA\uDDBD-\uDDBF\uDDF4-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDF7F\uDF86\uDFB1\uDFBB-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56\uDC57\uDC77\uDC78\uDC9F-\uDCA6\uDCB0-\uDCDF\uDCF3\uDCF6-\uDCFA\uDD1C-\uDD1F\uDD3A-\uDD3F\uDD5A-\uDD7F\uDDB8-\uDDBB\uDDD0\uDDD1\uDE01-\uDE0F\uDE14\uDE18\uDE36-\uDE3F\uDE49-\uDE5F\uDE7F\uDEA0-\uDEBF\uDEC8\uDEE5-\uDEEA\uDEF0-\uDEFF\uDF36-\uDF3F\uDF56\uDF57\uDF73-\uDF77\uDF92-\uDFA8\uDFB0-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCF9\uDD24-\uDD2F\uDD3A-\uDD3F\uDD66-\uDD6E\uDD86-\uDE5F\uDE7F\uDEAA-\uDEAF\uDEB2-\uDEC1\uDEC8-\uDEFF\uDF28-\uDF2F\uDF46-\uDF50\uDF55-\uDF6F\uDF82-\uDFAF\uDFCC-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC00-\uDC02\uDC38-\uDC51\uDC70\uDC73\uDC74\uDC76-\uDC82\uDCB0-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDD02\uDD27-\uDD35\uDD40-\uDD43\uDD45\uDD46\uDD48-\uDD4F\uDD73-\uDD75\uDD77-\uDD82\uDDB3-\uDDC0\uDDC5-\uDDCF\uDDDB\uDDDD-\uDDE0\uDDF5-\uDDFF\uDE12\uDE2C-\uDE3E\uDE41-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEDF-\uDEEF\uDEFA-\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A-\uDF3C\uDF3E-\uDF4F\uDF51-\uDF5C\uDF62-\uDF7F\uDF8A\uDF8C\uDF8D\uDF8F\uDFB6\uDFB8-\uDFD0\uDFD2\uDFD4-\uDFFF]|\uD805[\uDC35-\uDC46\uDC4B-\uDC4F\uDC5A-\uDC5E\uDC62-\uDC7F\uDCB0-\uDCC3\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDAF-\uDDD7\uDDDC-\uDDFF\uDE30-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEAB-\uDEB7\uDEB9-\uDEBF\uDECA-\uDECF\uDEE4-\uDEFF\uDF1B-\uDF2F\uDF3C-\uDF3F\uDF47-\uDFFF]|\uD806[\uDC2C-\uDC9F\uDCF3-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD30-\uDD3E\uDD40\uDD42-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD1-\uDDE0\uDDE2\uDDE4-\uDDFF\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE4F\uDE51-\uDE5B\uDE8A-\uDE9C\uDE9E-\uDEAF\uDEF9-\uDFBF\uDFE1-\uDFEF\uDFFA-\uDFFF]|\uD807[\uDC09\uDC2F-\uDC3F\uDC41-\uDC4F\uDC6D-\uDC71\uDC90-\uDCFF\uDD07\uDD0A\uDD31-\uDD45\uDD47-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8A-\uDD97\uDD99-\uDD9F\uDDAA-\uDDAF\uDDDC-\uDDDF\uDDEA-\uDEDF\uDEF3-\uDF01\uDF03\uDF11\uDF34-\uDF4F\uDF5A-\uDFAF\uDFB1-\uDFBF\uDFD5-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD812-\uD817\uD819\uD824-\uD82A\uD82D\uD82E\uD830-\uD832\uD836\uD83D\uD83F\uD87C\uD87D\uD87F\uD88E-\uDBFF][\uDC00-\uDFFF]|\uD80B[\uDC00-\uDF8F\uDFF1-\uDFFF]|\uD80D[\uDC30-\uDC40\uDC47-\uDC5F]|\uD810[\uDFFB-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD818[\uDC00-\uDCFF\uDD1E-\uDD2F\uDD3A-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDE6F\uDEBF\uDECA-\uDECF\uDEEE-\uDEFF\uDF30-\uDF3F\uDF44-\uDF4F\uDF5A\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDD3F\uDD6D-\uDD6F\uDD7A-\uDE3F\uDE97-\uDE9F\uDEB9\uDEBA\uDED4-\uDEFF\uDF4B-\uDF4F\uDF51-\uDF92\uDFA0-\uDFDF\uDFE2\uDFE4-\uDFF1\uDFF7-\uDFFF]|\uD823[\uDCD6-\uDCFE\uDD1F-\uDD7F\uDDF3-\uDFFF]|\uD82B[\uDC00-\uDFEF\uDFF4\uDFFC\uDFFF]|\uD82C[\uDD23-\uDD31\uDD33-\uDD4F\uDD53\uDD54\uDD56-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDFFF]|\uD833[\uDC00-\uDCEF\uDCFA-\uDFFF]|\uD834[\uDC00-\uDEBF\uDED4-\uDEDF\uDEF4-\uDF5F\uDF79-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD837[\uDC00-\uDEFF\uDF1F-\uDF24\uDF2B-\uDFFF]|\uD838[\uDC00-\uDC2F\uDC6E-\uDCFF\uDD2D-\uDD36\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDE8F\uDEAE-\uDEBF\uDEEC-\uDEEF\uDEFA-\uDFFF]|\uD839[\uDC00-\uDCCF\uDCEC-\uDCEF\uDCFA-\uDDCF\uDDEE\uDDEF\uDDFB-\uDEBF\uDEDF\uDEE3\uDEE6\uDEEE\uDEEF\uDEF5-\uDEFD\uDF00-\uDFDF\uDFE7\uDFEC\uDFEF\uDFFF]|\uD83A[\uDCC5\uDCC6\uDCD0-\uDCFF\uDD44-\uDD4A\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDC70\uDCAC\uDCB0\uDCB5-\uDD00\uDD2E\uDD3E-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDCFF\uDD0D-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEE0-\uDEFF]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEAE\uDEAF]|\uD87A[\uDFE1-\uDFEF]|\uD87B[\uDE5E-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDF4F]|\uD88D[\uDC7A-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g," ").replace(/ +/g," ").trim():a;});const i=t.find(e=>r[e]);!r.utm_source&&i&&(r.utm_source=e[i],r.utm_campaign=r.utm_campaign||`Using the CLICKID ${i} provided by ${r.utm_source}`,r.utm_term=r.utm_term||`${i}: ${r[i]}`),r.utm_source&&(Object.entries(r).filter(([e])=>!t.includes(e)).forEach(([e,t])=>{s[`s-${e.replace("_","-")}`]=t;}),s["s-utm-referrer"]=document.referrer,Salla.storage.setWithTTL("s-utms",s,129600),this.logUTMVisitData(s));}async logUTMVisitData(e){const t=e["s-utm-source"],a=e["s-utm-medium"],r=e["s-utm-campaign"],s=Salla.config.get("store.id");e&&"affiliate"===t&&a&&r&&fetch(Salla.config.get("affiliate.utm_url"),{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","s-utm-source":t,"s-utm-medium":a,"s-utm-campaign":r,"s-store-id":s}}).then(e=>{if(!e.ok)return;const t=new URL(window.location.href),a=window.history.state;t.searchParams.delete("utm_source"),t.searchParams.delete("utm_medium"),t.searchParams.delete("utm_campaign"),window.history.replaceState(a,"",t);});}}class O{constructor(e){var t,a,r;if("ready"!==Salla.status){if(null==e||null==(t=e.store)||!t.id)return console.error("Trying to init Twilight without store.id!"),void console.log("you can initiate twilight using this line only: Salla.init({store:{id:1234}})");var s;if(Salla.config.merge(e),!["salla.sa","salla.group"].includes(location.hostname)||null!=(a=Salla.config.get("store.url"))&&a.includes(location.hostname)||!Salla.config.get("store.username")||Salla.config.set("store.url",window.location.origin+"/"+Salla.config.get("store.username")),(null==e?void 0:e.events)&&Salla.event.dispatchEvents(null==e?void 0:e.events),new R,new j(e),null!=e&&null!=(r=e.user)&&r.language_code)Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);Salla.storage.get("scope.id")!=Salla.config.get("store.scope.id")&&Salla.storage.set("scope",Salla.config.get("store.scope",Salla.config.get("scope"))),new L(e).getConfig().then(e=>{Salla.config.merge(e),this.setSallaReady(e),this.afterInit();}).catch(e=>console.error("failed to initite twilight😢",e));}else Salla.log("Trying to re-initiate Salla, while its status === 'ready'!");}afterInit(){Salla.url.is_page("product.single")&&Salla.config.isGuest()&&window.addEventListener("mini-checkout::before-init",e=>{e.preventDefault(),Salla.event.emit("login::open");});}setSallaReady(e){new U,Salla.event.emitAsync("twilight::before.ready",e),Salla.status="ready",Salla.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}));}}class N{constructor(e){const t=null==e?void 0:e.nextPage;this.listId=salla.config.get("page.slug"),Salla.config.get("page.id")&&(this.listId+=`_${salla.config.get("page.id")}`),this.sorts=null;try{if(t){const e=new URL(t).searchParams.get("sort");e&&(this.sorts=[{type:"sort",value:e}]);}e.source&&(this.listId=`${this.listId}_${e.source}`),e.sourceValue&&(this.listId=`${this.listId}_${Array.isArray(e.sourceValue)?e.sourceValue.join("_"):e.sourceValue}`);}catch(e){salla.logger.error(e);}this.products=null==e?void 0:e.data;}toSegment(){const e=(salla.config.get("page.title")||"").split("|").map(e=>e.trim()),t=e[0],a=e[1]||null;return {event:"Product List Viewed",properties:{list_id:this.listId,category:t,sub_category:a,sorts:this.sorts,products:this.products.map(e=>{var t,a,r,s,i,n;return {product_id:e.id,category:null==(t=e.category)?void 0:t.name,currency:null==(a=Salla.config.currency())?void 0:a.code,name:e.name,brand:null==(r=e.brand)?void 0:r.name,variant:null==(s=e.variant)?void 0:s.toString(),coupon:null==(i=e.coupon)?void 0:i.toString(),price:e.price,quantity:Number(e.quantity),sku:e.sku,position:0,url:e.url,image_url:null==(n=e.image)?void 0:n.url}})}}}static shouldSend(e){return !((null==e?void 0:e.nextPage)||"").includes("filters")&&!["index","customer.wishlist"].includes(salla.config.get("page.slug"))}}class M{constructor(){this.user=JSON.parse(localStorage.getItem("user"));}toSegment(){var e,t,a,r,s;return {event:"Signed In",properties:{first_name:null==(e=this.user)?void 0:e.first_name,last_name:null==(t=this.user)?void 0:t.last_name,type:null==(a=this.user)?void 0:a.type,mobile:null==(r=this.user)?void 0:r.mobile,email:null==(s=this.user)?void 0:s.email}}}static shouldSend(){return "user"===Salla.config.get("user.type")?!Salla.analytics.history.find(({eventName:e})=>"Signed In"===e):(Salla.profile.event.onInfoFetched(()=>Salla.event.emit("Signed In")),false)}}class ${constructor(e){this.details=null==e?void 0:e.data;}toSegment(){const e=["first_name","last_name","birthday","gender"].filter(e=>{var t,a;return $.user[e]!==(null==(t=this.details)?void 0:t[e])&&(void 0!==$.user[e]||void 0!==(null==(a=this.details)?void 0:a[e]))});return $.setUser(this.details),{event:"User Profile Updated",properties:{updated_fields:e}}}static registerEvent(){Salla.onReady(()=>{salla.url.is_page("customer.profile")&&$.setUser(Salla.config.get("user"));});}static setUser(e){$.user={first_name:null==e?void 0:e.first_name,last_name:null==e?void 0:e.last_name,gender:null==e?void 0:e.gender,birthday:null==e?void 0:e.birthday,avatar:null==e?void 0:e.avatar};}static shouldSend(){return "user"===Salla.config.get("user.type")}}$.user={};class H{static registerEvents(){Object.values(this.events).forEach(e=>{e.forEach(e=>{"function"==typeof e.registerEvent&&e.registerEvent();});});}static transform(e,t){try{const a=this.events[e]||[];for(const e of a){if(!e||"function"==typeof e.shouldSend&&!e.shouldSend(t))continue;const a=new e(t).toSegment();return {event:a.event,properties:a.properties}}return null}catch(e){return console.error("Failed to transform event:",e),null}}}H.events={"Order Completed":[class{constructor(e){this.details=e[0];}toSegment(){return {event:"Order Completed",properties:this.details}}}],"Product Added":[class{constructor(e){var t,a;this.item=e[0],this.source=(null==(t=Salla.cart)||null==(t=t.api)?void 0:t.addToCartSource)||null,null!=(a=Salla.cart)&&a.api&&(Salla.cart.api.addToCartSource=null);}toSegment(){var e,t,a,r,s;return {event:"Product Added",properties:{cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),cart_item_id:null==(t=this.item.cart_item_id)?void 0:t.toString(),product_id:null==(a=this.item.id)?void 0:a.toString(),category:this.item.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:this.item.name,brand:this.item.brand,variant:null==(s=this.item.variant)?void 0:s.toString(),price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url,source:this.source}}}static shouldSend(){return "customer.wishlist"!==salla.config.get("page.slug")}},class{constructor(e){this.item=e[0];}toSegment(){var e,t;return {event:"Wishlist Product Added to Cart",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,name:this.item.name,brand:this.item.brand,variant:this.item.variant,price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}}static shouldSend(){return "customer.wishlist"===salla.config.get("page.slug")}}],"Product Removed":[class{constructor(e){this.item=e[0];}toSegment(){var e,t,a,r,s,i,n,o,l,u,c,d,h,p;return {event:"Product Removed",properties:{cart_id:null==(e=this.item)||null==(e=e.cart_id)?void 0:e.toString(),product_id:null==(t=this.item)||null==(t=t.id)?void 0:t.toString(),category:null==(a=this.item)?void 0:a.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:null==(s=this.item)?void 0:s.name,brand:null==(i=this.item)?void 0:i.brand,variant:null==(n=this.item)?void 0:n.variant,price:null==(o=this.item)?void 0:o.price,quantity:null==(l=this.item)?void 0:l.quantity,sku:null==(u=this.item)?void 0:u.sku,coupon:null==(c=this.item)?void 0:c.coupon,position:null==(d=this.item)?void 0:d.position,url:null==(h=this.item)?void 0:h.url,image_url:null==(p=this.item)?void 0:p.image_url}}}}],"Product Viewed":[class{constructor(e){this.product=e[0];try{this.source=sessionStorage.getItem("s-viewed-source")||null,sessionStorage.removeItem("s-viewed-source");}catch(e){this.source=null;}}toSegment(){var e;return {event:"Product Viewed",properties:{product_id:null==(e=this.product.id)?void 0:e.toString(),category:this.product.category,name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:this.product.quantity,currency:this.product.currency,coupon:this.product.coupon,position:this.product.position,value:this.product.value,sku:this.product.sku,url:this.product.url,image_url:this.product.image_url,source:this.source}}}}],"Product Added to Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Added to Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,position:Number(this.product.position||0),url:this.product.url,image_url:(null==(t=this.product)?void 0:t.image)||null,category:this.product.category,currency:null==(a=Salla.config.currency())?void 0:a.code,brand:this.product.brand}}}}],"Product Removed from Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Removed from Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,coupon:this.product.coupon||null,position:Number(this.product.position||0),currency:null==(t=Salla.config.currency())?void 0:t.code,url:this.product.url,image_url:(null==(a=this.product)?void 0:a.image)||null,category:this.product.category,brand:this.product.brand}}}}],"Cart Viewed":[class{constructor(e){this.cart=e[0];}toSegment(){var e;return {event:"Cart Viewed",properties:{cart_id:null==(e=this.cart.cart_id)?void 0:e.toString(),products:this.cart.products.map(e=>{var t,a,r;return {product_id:null==(t=e.id)?void 0:t.toString(),cart_item_id:null==(a=e.cart_item_id)?void 0:a.toString(),name:e.name,price:e.price,category:e.category,sku:e.sku,position:e.position,url:e.url,image_url:e.image_url,brand:e.brand,currency:null==(r=Salla.config.currency())?void 0:r.code,variant:e.variant,coupon:e.coupon,quantity:e.quantity}})}}}}],"Products Searched":[class{constructor(e){this.query=e;}toSegment(){return {event:"Products Searched",properties:{query:this.query}}}}],"Product List Viewed":[N],"Product List Filtered":[class extends N{constructor(e){super(e);const t=(null==e?void 0:e.nextPage)||"";this.filters=this.extractFilters(t);}extractFilters(e){if(!e)return null;try{const t=new URL(e),a=[];return Array.from(t.searchParams.entries()).forEach(([e,t])=>{if(e.startsWith("filters[")){const r=e.match(/^filters\[(.*?)\]/),s=r?r[1]:e;a.push({type:s,value:t});}}),a.length>0?a:null}catch(e){return console.warn("Error extracting filters from URL:",e),null}}toSegment(){const e=super.toSegment();return {event:"Product List Filtered",properties:h$1({},null==e?void 0:e.properties,{filters:this.filters})}}static shouldSend(e){return ((null==e?void 0:e.nextPage)||"").includes("filters")}}],"Signed Up":[class extends M{toSegment(){const e=super.toSegment();return {event:"Signed Up",properties:null==e?void 0:e.properties}}static shouldSend(){return "user"===Salla.config.get("user.type")||(Salla.profile.event.onInfoFetched(()=>Salla.event.emit("Signed Up")),false)}}],"Signed In":[M],"Signed Out":[class{toSegment(){return {event:"Signed Out",properties:{}}}}],"Product Reviewed":[class{constructor(e){this.details=e;}toSegment(){return {event:"Product Reviewed",properties:this.details}}static registerEvent(){salla.event.rating.onProductsRated(function(e,t){const{products:a,order_id:r}=t;Object.values(a).forEach(e=>{var t;Salla.event.emit("Product Reviewed",{product_id:null==(t=e.product_id)?void 0:t.toString(),review_id:null==r?void 0:r.toString(),review_body:e.comment,rating:e.rating});});});}}],"Product Shared":[class{constructor(e){this.data=e;}toSegment(){var e;const t=(null==(e=Salla.analytics.history.find(({eventName:e})=>"Product Viewed"===e))?void 0:e.payload)||{};return t.share_via=this.data.share_via,{event:"Product Shared",properties:t}}static shouldSend(){return "product.single"===salla.config.get("page.slug")}}],"Promotion Viewed":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Viewed",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Promotion Clicked":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Clicked",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Coupon Applied":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Applied",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Removed":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Removed",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Denied":[class{constructor(e){this.transaction=e;}getCartId(){var e;return "cart"===salla.config.get("page.slug")?null==(e=salla.config.get("page.id"))?void 0:e.toString():""}getCouponCode(){try{var e,t;const a=null==(e=this.transaction.response)||null==(e=e.config)?void 0:e.data;return a?null==(t=JSON.parse(a))?void 0:t.coupon:""}catch(e){return ""}}toSegment(){var e;return {event:"Coupon Denied",properties:{cart_id:this.getCartId(),coupon_name:this.getCouponCode(),reason:(null==(e=this.transaction.response)||null==(e=e.data)||null==(e=e.error)?void 0:e.message)||"Unknown error"}}}}],"User Profile Updated":[$],"Cart Updated":[class{constructor(e){this.cart=e;}toSegment(){var e,t,a,r;return {event:"Cart Updated",properties:{cart_id:null==(e=this.cart.id)?void 0:e.toString(),value:this.cart.total,revenue:this.cart.sub_total,tax:this.cart.tax_amount,discount:this.cart.total_discount,shipping:this.cart.real_shipping_cost,currency:null==(t=Salla.config.currency())?void 0:t.code,affiliation:null==(a=Salla.storage.getWithTTL("s-utms"))?void 0:a["s-utm-source"],products:null==(r=this.cart.items)?void 0:r.map(e=>{var t,a,r,s,i,n;return {product_id:null==(t=e.product_id)?void 0:t.toString(),name:e.product_name,price:e.product_price,category:null==(a=e.category)?void 0:a.toString(),sku:null==(r=e.product_sku)?void 0:r.toString(),position:e.position,url:e.url,image_url:e.product_image,brand:null==(s=e.brand)?void 0:s.toString(),currency:null==(i=Salla.config.currency())?void 0:i.code,variant:null==(n=e.variant)?void 0:n.toString(),coupon:this.cart.coupon,quantity:e.quantity}})}}}static shouldSend(e){return "cart"===salla.config.get("page.slug")&&!(null!=e&&e.fromLatestFetched)}}],"Market Selected":[class{constructor(e){this.scope=e.data;}toSegment(){return {event:"Market Selected",properties:h$1({},this.getScope(this.scope),{prev:this.getScope(Salla.config.get("store.scope"))})}}getScope(e){var t;return {id:null==(t=(e=e||{}).id)?void 0:t.toString(),country:this.getScopeAttribute(e,"countries"),currency:this.getScopeAttribute(e,"currencies"),locale:this.getScopeAttribute(e,"languages")}}getScopeAttribute(e,t){return e=e[t],Array.isArray(e)?e[0]:e}}],"Product Reordered":[class{constructor(e){this.details=e;}toSegment(){var e;return {event:"Product Reordered",properties:{product_id:null==(e=this.details)||null==(e=e.data)||null==(e=e.id)?void 0:e.toString()}}}static shouldSend(e){const t=null==e?void 0:e.data;return (null==t?void 0:t.id)&&!isNaN(null==t?void 0:t.id)&&"reorder"===(null==t?void 0:t.type)}}]};const V="s-session-id";N$3.versions.twilight="2.14.392",N$3.onInitiated=e=>salla.event.once("twilight::initiated",e),N$3.onReady=N$3.onReady||function(t){return new Promise(function(a){return "ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):N$3.onInitiated(e=>a(t?t(e):e))})},N$3.status="loading",N$3.notify=u,N$3.lang=new class extends a$3{constructor(e){e=e||{};const t=salla.cookie.get("s-lang");e.messages=e.messages||window.translations,e.locale=e.locale||(t||window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=false,Salla.event.on("twilight::before.ready",()=>this.loadStoreTranslations());}onLoaded(e){return new Promise(t=>{if(this.translationsLoaded)return t(e?e():null);Salla.event.once("languages::translations.loaded",()=>t(e?e():null));})}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=true)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",false);}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=true;}loadScript(e,t=true){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",false);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}getWithDefault(e,t,a,r){let s=this.get(e,a,r);return s!==e?s:t}get(e,t,a){let r=e;(window.translations||this.translationsLoaded)&&(r="trans."+e);let s=super.get(r,t,a);return s!==r?s:super.get(r,t,"en").replace(r,e)}set(e,t){return salla.helpers.setNested(this.messages[`${this.getLocale()}.trans`],e,t),this}add(e,t){return Object.entries(t).forEach(t=>salla.helpers.setNested(this.messages[t[0]+".trans"],e,t[1])),this}addBulk(e){return Object.entries(e).forEach(([e,t])=>{this.add(e,t);}),this}},N$3.form=new class{async submit(e,t=null){var a;let r=t;if("SubmitEvent"===(null==t||null==(a=t.constructor)?void 0:a.name)||"submit"===(null==t?void 0:t.type)){var s,i;if(t.preventDefault(),"FORM"!==(null==(s=t.target)?void 0:s.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise(()=>{throw "Failed find the target element for submit action. make sure you submit a form element"});"SALLA-BUTTON"===(null==t||null==(i=t.submitter)||null==(i=i.parentElement)?void 0:i.tagName)&&t.submitter.parentElement.load(),r=t.target.getElementSallaData(),salla.log("Data from element",r);}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.request(e,r,"post").finally(()=>{var e;loaderSupported&&(null==t||null==(e=t.submitter)||e.parentElement.stop());});let n=e.split("."),o=n.splice(-1);return await salla.call(n.join("."))[o](r).finally(()=>{var e;return null==t||null==(e=t.submitter)||null==(e=e.parentElement)?void 0:e.stop()}).catch(e=>{throw salla.logger.warn(e),e})}onSubmit(e,t){return salla.form.submit(e,t),false}onChange(e,t){var a;return null!=t&&t.currentTarget?"FORM"!==(null==t||null==(a=t.currentTarget)?void 0:a.tagName)||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),true):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),false):(salla.logger.warn(`Trying to trigger '${e}' without event!`),false)}getPossibleValue(e,t,a=false){if(!e)return;if("object"!=typeof e)return e;let r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},N$3.infiniteScroll=new class extends c{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":true,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[];}initiate(e,a,r,s=false){s?((r=r||{}).fetchOptions=h$1({},this.fetchOptions,r.fetchOptions||{}),r.responseBody="json"):r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),n=r.path;if(!i||!n||"string"==typeof n&&!document.querySelector(n))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let o=new t$1(i,r);return o.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),o.on("request",Salla.infiniteScroll.event.request),o.on("load",Salla.infiniteScroll.event.load),o.on("append",Salla.infiniteScroll.event.append),o.on("error",Salla.infiniteScroll.event.error),o.on("last",Salla.infiniteScroll.event.last),o.on("history",Salla.infiniteScroll.event.history),this.instances.push(o),o}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage();}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy();}}(void 0,salla.event.infiniteScroll),N$3.api=new class extends B{constructor(){super(),this.auth=new D,this.cart=new m,this.loyalty=new f,this.order=new F,this.rating=new A,this.product=new v,this.profile=new y,this.comment=new C,this.currency=new S,this.document=new w,this.wishlist=new E,this.scope=new b,this.booking=new _,this.landing=new k,this.notifications=new x,this.component=new P,this.advertisement=new I,this.navigation=new q,this.metadata=new T;}beaconRequest(e,t={}){var a;if(null==(a=window.navigator)||!a.sendBeacon)return fetch(e,t);const r="string"==typeof(null==t?void 0:t.body)?null==t?void 0:t.body:JSON.stringify((null==t?void 0:t.body)||{}),s=new Blob([r],{type:"application/json"});return Salla.log(`Beacon payload size: ${s.size} bytes (~${(s.size/1024).toFixed(2)} KB)`),navigator.sendBeacon(e,s),Promise.resolve(new Response('{"status":"sent_via_beacon"}',{status:200,headers:{"Content-Type":"application/json"}}))}},N$3.sso=new class{constructor(){Salla.onReady(()=>this.init());}init(){var e;if(salla.config.get("store.features",[]).includes("sso-login")){if(window.location.hostname.includes("salla"))return salla.log("SSO is not supported yet for stores without custom domain.");salla.auth.event.onLoggedOut(()=>new Promise(e=>{const t=document.createElement("iframe");t.style.display="none",t.src=salla.url.get("sso/logout"),document.body.appendChild(t),t.onload=()=>{document.body.removeChild(t),e();};})),null==(e=document.querySelector("salla-login-modal"))||e.remove(),Salla.event.removeAllListeners("login::open"),Salla.event.prependListener("login::open",()=>this.redirect()),window.addEventListener("mini-checkout::before-init",e=>{Salla.config.isUser()||(e.preventDefault(),this.redirect());});}}redirect(){const e=window.location.pathname+window.location.search,t=`${window.location.origin}/sso/login?intended_to=${encodeURIComponent(e)}`;return console.log("Redirecting to:",t),window.location.href=t,true}},N$3.intend=new class{constructor(){Salla.onReady(()=>this.init());}init(){if(Salla.config.isUser())return;const e=new URLSearchParams(window.location.search);if(e.has("intended_to"))try{const t=new URL(e.get("intended_to"));if(t.hostname!==window.location.hostname)return;return this.handleAfterLoginEvent(t)}catch(e){return void console.warn("Invalid URL provided in intended_to parameter")}}handleAfterLoginEvent(e){let t="intend::user.logged.in";Salla.event.on(t,()=>window.location=e),Salla.api.auth.setAfterLoginEvent(t),Salla.api.auth.setCanRedirect(false),Salla.event.on("salla-login::ready",()=>Salla.event.emit("login::open",{withoutReload:true}));}},N$3.hooks=new class{constructor(){this._store=new Map,this._whitelist=new Map([["salla-add-product-button",new Set(["validate","componentDidLoad"])],["salla-product-options",new Set(["componentDidLoad"])],["salla-products-list",new Set(["componentDidLoad"])],["salla-products-slider",new Set(["componentDidLoad"])],["salla-hook",new Set(["componentDidLoad"])],["salla-scopes",new Set(["componentDidLoad"])]]),this._themeSlots=["head","head:start","head:end","body:start","body:end","product:index.items.start","product:index.items.end","product:single.description.start","product:single.description","product:single.description.end","product:single.form.start","product:single.form.end","blog:index.items.start","blog:index.items.end","blog:single.items.start","blog:single.items.end","brands:index.items.start","brands:index.items.end","brands:single.details.start","brands:single.details.end","brands:single.items.start","brands:single.items.end","cart:items.start","cart:items.end","cart:summary.start","cart:summary.end","cart:submit.start","cart:submit.end","customer:notifications.items.start","customer:notifications.items.end","customer:orders.index.items.start","customer:orders.index.items.end","customer:orders.single.details.start","customer:orders.single.details.end","customer:wishlist.items.start","customer:wishlist.items.end","customer:profile.form.start","customer:profile.form.fields.start","customer:profile.form.fields.end","customer:profile.form.submit.start","customer:profile.form.submit.end","customer:profile.form.end","thank-you:start","thank-you:items.start","thank-you:items.end","thank-you:end"];const e=Salla.config.get("page.slug");e&&(this._themeSlots.push(e+":start"),this._themeSlots.push(e+":end")),Salla.onReady(()=>{const e=Salla.config.get("page.slug");e&&(this._themeSlots.includes(e+":start")||this._themeSlots.push(e+":start"),this._themeSlots.includes(e+":end")||this._themeSlots.push(e+":end"));}),this._componentHistory=new Map;}renderAutoComponents(e){Array.isArray(e)&&0!==e.length&&e.forEach(({hook:e,tag:t,canRender:a})=>{a&&!a()||this.mount(e,document.createElement(t));});}registerHook(e,t,a,r={}){if(!this._isAllowed(e,t))return console.warn(`[Hooks] Hook "${e}:${t}" is not allowed`),()=>{};const s=0|r.priority,i=!!r.once,n=this._ensureTag(e),o=n.get(t)||[];return o.push({cb:a,p:s,once:i}),o.sort((e,t)=>t.p-e.p),n.set(t,o),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),()=>this.removeHook(e,t,a)}registerHookOnce(e,t,a,r={}){return this.registerHook(e,t,a,h$1({},r,{once:true}))}async call(e,t,a){const r=this._store.get(e);if(!r)return;const s=r.get(t);if(s&&0!==s.length)for(const r of [...s]){try{await r.cb(a);}catch(a){console.warn(`[Hooks] "${e}:${t}" callback failed:`,a);}r.once&&this.removeHook(e,t,r.cb);}}removeHook(e,t,a){const r=this._store.get(e);if(!r)return false;if(!r.has(t))return false;if(!a)return r.delete(t),0===r.size&&this._store.delete(e),true;const s=r.get(t),i=s.findIndex(e=>e.cb===a);return i>-1&&(s.splice(i,1),0===s.length&&r.delete(t),0===r.size&&this._store.delete(e),true)}clear(e){e?this._store.delete(e):this._store.clear();}get(e,t){var a;const r=this._store.get(e);return r&&(null==(a=r.get(t))?void 0:a.map(e=>e.cb))||[]}_ensureTag(e){let t=this._store.get(e);return t||(t=new Map,this._store.set(e,t)),t}_isAllowed(e,t){const a=this._whitelist.get(e);return a?!!a.has(t)||(console.warn(`[Hooks] Hook "${t}" is not allowed for tag "${e}"`),false):(console.warn(`[Hooks] Tag "${e}" is not in the whitelist`),false)}registerComponent(e,t){this._componentHistory.has(e)||this._componentHistory.set(e,new Set);const a=this._componentHistory.get(e);if(!a.has(t))return a.add(t),this.call(e,"componentDidLoad",t)}async _callForLoadedComponents(e,t){const a=this._componentHistory.get(e);if(a&&0!==a.size)for(const r of a)try{await t(r);}catch(t){console.warn(`[Hooks] "${e.replace(/[^a-zA-Z0-9-_]/g,"")}:componentDidLoad" callback failed:`,t);}}mount(e,t){return this._themeSlots.includes(e)?new Promise(a=>{this.registerHook("salla-hook","componentDidLoad",r=>{r.name===e&&(r.mount(t),a(t));});}):(console.warn(`[Hooks] Hook "${e}" is not allowed`),Promise.reject(t))}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing","metadata"].forEach(t=>N$3[t]=new c(N$3.api[t],N$3.event[t])),N$3.call=t=>{let a=N$3,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},N$3.analytics=new class{constructor(){this.history=[],this.customTrackers=[],this.context={},this._anonymousId=null,this._sessionId=null,this._jitsuConfig=null,this.mappedEvents={"wishlist::added":"Product Added to Wishlist","wishlist::removed":"Product Removed from Wishlist","salla-products-list::products.fetched":["Product List Viewed","Product List Filtered"],"auth::registered":"Signed Up","auth::logged.in":"Signed In","auth::logged.out":"Signed Out","share-element":"Product Shared","promotion::viewed":"Promotion Viewed","promotion::clicked":"Promotion Clicked","salla::offer.promotion.viewed":"Promotion Viewed","salla::offer.promotion.clicked":"Promotion Clicked","cart::coupon.added":"Coupon Applied","cart::coupon.deleted":"Coupon Removed","cart::coupon.addition.failed":"Coupon Denied","profile::updated":"User Profile Updated","cart::updated":"Cart Updated","scope::changed":"Market Selected","order::order.created":"Product Reordered"},Salla.event.onAny((e,t)=>{try{if(Object.keys(this.mappedEvents).includes(e)){const a=this.mappedEvents[e];return void(Array.isArray(a)?a:[a]).forEach(e=>Salla.event.emit(e,t))}if(!Salla.config.get("jitsu.events",[]).includes(e))return;const a=H.transform(e,t);a&&this.track(a.event,a.properties);}catch(e){Salla.log("Error in analytics event handling:",e);}}),Salla.event.on("salla-cookies-bar::accepted",()=>this.setConsent("accepted")),Salla.event.on("salla-cookies-bar::rejected",()=>this.setConsent("rejected")),Salla.event.on("auth::logged.out",()=>this.clearSessionId()),Salla.event.on("twilight::before.ready",e=>{var t,a,r,s,n,o,l;this.debugAnalytics=jitsuAnalytics({host:"https://st.salla.dev",writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p"});const{host:u,key:c}=(null==e?void 0:e.jitsu)||{};if(this.jitsuAnalytics=null,!u||!c)return void salla.log("Jitsu configuration is missing. Analytics will not be tracked.");H.registerEvents(),this._jitsuConfig=h$1({host:this.getAnalyticsHost(e),writeKey:c,cookieCapture:Object.fromEntries(Salla.cookie.getCookieByPrefix("sa_").map(e=>[e,e]))},Salla.helpers.isIframe()&&{fetch:(e,t)=>this.customFetch(e,t)});const d=this.getConsentPolicies();var p;(this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,d)),e.jitsu.anonymous_id&&this.jitsuAnalytics.setAnonymousId(e.jitsu.anonymous_id),this._anonymousId=(null==(t=this.jitsuAnalytics)||null==(t=t.user())?void 0:t.anonymousId)||null,e.jitsu.session_id&&this.setContext("session_id",e.jitsu.session_id),this._sessionId=null==(a=this.jitsuAnalytics)?void 0:a.getContextProperty("session_id"),this.setContext("store_id",null==(r=e.store)?void 0:r.id),this.setContext("version",null==(s=e.jitsu)?void 0:s.version),this.setContext("library",{twilight:Salla.versions}),null!=(n=e.jitsu)&&null!=(n=n.context)&&n.extra&&this.setExtraContext(e.jitsu.context.extra),null!=(o=e.store)&&null!=(o=o.scope)&&o.id)&&this.setContext("scope",null==(p=e.store)?void 0:p.scope);"user"===(null==e||null==(l=e.user)?void 0:l.type)&&this.setContext("traits",this.getFormattedUser(e.user)),this.registerTracker({name:"DefaultSallaTracker",track:(e,t)=>this.jitsuAnalytics.track(e,t),page:e=>this.jitsuAnalytics.page(e)});}),Salla.onReady(()=>{var e;this.initSessionId();const t={name:Salla.config.get("page.slug",""),id:null==(e=Salla.config.get("page.id",""))?void 0:e.toString()};this.setContext("page",t),Salla.config.set("jitsu.anonymous_id",this._anonymousId),Salla.config.set("jitsu.session_id",this._sessionId),this.page(t);});}setExtraContext(e){var t;null!=e&&null!=(t=e.headers)&&t["s-app-os"]&&(this.setContext("app",{version:e.headers["s-app-os-version"],app_release_tag:e.headers["s-app-version"],platform:e.headers["s-app-os"].toLowerCase()}),delete e.headers["s-app-os"],delete e.headers["s-app-os-version"],delete e.headers["s-app-version"],delete e.headers["s-source"]),this.setContext("system",e);}getAnalyticsHost(e){var t;const a="https://salla.cloud/_app/e";var r,s;if(Salla.helpers.isIframe())return null!=(r=null==(s=e.jitsu)?void 0:s.host)?r:a;if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;const i=e.store.url;try{let e="";const t=i;if(/https:\/\/demostore\.salla\.sa/.test(t)){const e=t.match(/demostore\.salla\.sa\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/);if(e&&e[2]){const a=e[2];return `${new URL(t).origin}/${a}/_app/e`}return a}const r=/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/,s=t.match(r);if(s){const r=s[3];if(!r||0===r.trim().length||"ar"===r||"en"===r)return Salla.log("Error: invalid or empty store name in salla.sa URL"),a;e=`${new URL(t).origin}/${r}`;}else {e=new URL(t).origin;}return `${e}/_app/e`}catch(e){return Salla.log("Error getting store url, forwarding to salla.cloud:",e),a}}setContext(e,t){var a,r;null==(a=this.jitsuAnalytics)||a.setContextProperty(e,t),null==(r=this.debugAnalytics)||r.setContextProperty(e,t),this.context[e]=t;}setAppContext(e,t){if(!this.jitsuAnalytics)return void Salla.log("setAppContext: Analytics not initialized yet");if(!e||"string"!=typeof e)return void Salla.log("setAppContext: appId must be a non-empty string");if(!t||"object"!=typeof t)return void Salla.log("setAppContext: payload must be an object");const a=this.context.apps_context||{};a[e]=h$1({},a[e],t),this.setContext("apps_context",a);}withAppScope(e,t){if(!e||"string"!=typeof e)return void Salla.log("withAppScope: appId must be a non-empty string");if("function"!=typeof t)return void Salla.log("withAppScope: callback must be a function");const a=this.context.apps_context?h$1({},this.context.apps_context):void 0,r=this,s={appId:e,setContext(t,a){r.setAppContext(e,{[t]:a});}};try{t(s);}finally{setTimeout(()=>{a?r.setContext("apps_context",a):r.setContext("apps_context",void 0);},0);}}customFetch(e,t){return fetch(e,h$1({},t,{keepalive:true}))}track(e,t={}){t=this.finalPayload(t),this.history.push({action:"track",eventName:e,payload:t}),this.pushEventToCustomTrackers("track",e,t);}log(e,t={}){var a;return null==(a=this.debugAnalytics)?void 0:a.track(e,t).catch(e=>(Salla.log("Error tracking event:",e),Promise.reject(e)))}page(e={}){var t,a;(e=this.finalPayload(e)).id=null==(t=e.id||Salla.config.get("page.id",""))?void 0:t.toString(),e.name=e.name||Salla.config.get("page.slug"),e.keywords=e.keywords||(null==(a=document.querySelector("meta[name=keywords]"))?void 0:a.content),e.referrer=e.referrer||document.referrer,this.history.push({action:"page",payload:e}),this.pushEventToCustomTrackers("page",e);}finalPayload(e={}){return this.attachRealtimeContext(),h$1({},{},e)}attachRealtimeContext(){try{const e=["user.id","cart.id","cart.user_id","cart.count","cart.summary.count","scope.id","branch-choosed-before"].reduce((e,t)=>{const a=Salla.storage.get(t);return a&&(e[t.replace(".","_")]=a),e},{});Object.keys(e).length>0&&this.setContext("localStorage",e);}catch(e){Salla.analytics.log("attachRealtimeContext",{error:e.message}),Salla.log("Error attaching realtime context:",e);}const e=Salla.storage.getWithTTL("s-utms");if(!e)return;const{"s-utm-campaign":t,"s-utm-source":a,"s-utm-medium":r,"s-utm-term":s,"s-utm-content":i,"s-utm-referrer":n}=e;this.setContext("campaign",{name:t,source:a,medium:r,term:s,content:i,referrer:n});}registerTracker(e){"object"==typeof e?"string"==typeof e.name&&e.name?"function"==typeof e.track?"function"==typeof e.page?this.customTrackers.find(t=>t.name===e.name)?Salla.log("tracker with the same name already exists!"):(this.customTrackers.push(e),this.history.forEach(t=>"track"===t.action?e.track(t.eventName,t.payload):"page"===t.action?e.page(t.payload):void 0)):Salla.log("tracker.page most be a function!"):Salla.log("tracker.track most be a function!"):Salla.log("tracker.name most be a string!"):Salla.log('tracker most be an object {name:"tracker name", track: callback, page: callback}!');}pushEventToCustomTrackers(e,t,a={}){const r="page"===e?[t]:[t,a];return Promise.allSettled(this.customTrackers.map(t=>this.pushEventToCustomTracker(t[e],r))).then(t=>t.filter(e=>"rejected"===e.status).map(t=>Salla.log("Error on customTracker to send "+e,t)))}pushEventToCustomTracker(e,t){try{const a=e(...t);return Promise.resolve(a).catch(e=>Promise.reject(e))}catch(e){return Promise.reject(e)}}getConsentState(){return Salla.storage.get("cookies-consent","unknown")}getConsentPolicies(e=null){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return {};const a="accepted"===(e=e||this.getConsentState());return {privacy:{dontSend:false,disableUserIds:!a,ipPolicy:a?"keep":"remove"}}}setConsent(e){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return;if(!["accepted","rejected"].includes(e))return;const a=this.getConsentState();if(this._jitsuConfig&&this.jitsuAnalytics&&a!==e)try{var r;const t=this.getConsentPolicies(e);this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,t)),this._anonymousId=(null==(r=this.jitsuAnalytics)||null==(r=r.user())?void 0:r.anonymousId)||null,Salla.config.set("jitsu.anonymous_id",this._anonymousId),Object.entries(this.context).forEach(([e,t])=>{this.jitsuAnalytics.setContextProperty(e,t);});}catch(e){Salla.log("Error re-initializing Jitsu on consent change:",e);}}getFormattedUser(e){return e.phone=e.mobile,e.country=e.country_code,e.language=e.language_code,e.currency=e.currency_code,e}generateSessionId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)})}initSessionId(){this._sessionId=this._sessionId||Salla.storage.getWithTTL(V)||this.generateSessionId(),Salla.storage.setWithTTL(V,this._sessionId,30),this.setContext("session_id",this._sessionId);}clearSessionId(){this._sessionId=null,Salla.storage.setWithTTL(V,null,0),this.setContext("session_id",null);}getAnonymousId(){try{if(this._anonymousId)return this._anonymousId;if(this.jitsuAnalytics){var e;const t=null==(e=this.jitsuAnalytics.user())?void 0:e.anonymousId;if(t)return this._anonymousId=t,t}return null}catch(e){return Salla.log("Error getting anonymous ID from Jitsu:",e),null}}},N$3.init=e=>new O(e),new class{constructor(e={}){this.config=h$1({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=false,Salla.onReady(()=>this.init());}normalizeUrl(e){try{return new URL(e,location.href)}catch(e){return null}}shouldIgnoreUrl(e){if(!e)return false;const t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some(e=>a.startsWith(e)))return true;try{const e=new URL(t,location.href).hostname.toLowerCase();return ["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some(t=>e===t||e.endsWith("."+t))}catch(e){return false}}isWhitelisted(e){if(!e)return false;const t=e.hostname.toLowerCase();for(const e of this.config.WHITELIST){const a=String(e||"").toLowerCase().trim();if(a&&(t===a||t.endsWith("."+a)))return true}return false}emit(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e);}catch(e){}}catch(e){}}logRedirect(e,t,a){if(this.shouldIgnoreUrl(t))return;const r=this.normalizeUrl(t),s=this.normalizeUrl(location.href),i=this.isWhitelisted(r),n={redirect_source:e,redirect_from:s?s.href:String(location.href),redirect_to:r?r.href:String(t),redirect_host:r?r.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(n);}hookHistoryAPIs(){["pushState","replaceState"].forEach(e=>{try{const t=history[e];"function"==typeof t&&(this.originalMethods[`history.${e}`]=t,history[e]=(...a)=>{try{var r;this.logRedirect(e,null!=(r=a[2])?r:location.href);}catch(e){}return t.apply(history,a)});}catch(e){}}),window.addEventListener("popstate",()=>{this.logRedirect("popstate",location.href);}),window.addEventListener("hashchange",()=>{this.logRedirect("hashchange",location.href);});}hookLocationMethods(){try{const e=location.assign.bind(location);this.originalMethods["location.assign"]=e,location.assign=t=>(this.logRedirect("location.assign",t,{stack:(new Error).stack}),e(t));}catch(e){}try{const e=location.replace.bind(location);this.originalMethods["location.replace"]=e,location.replace=t=>(this.logRedirect("location.replace",t,{stack:(new Error).stack}),e(t));}catch(e){}}hookWindowOpen(){try{const e=window.open;this.originalMethods["window.open"]=e,window.open=(t,...a)=>(t&&this.logRedirect("window.open",t,{stack:(new Error).stack}),e.apply(window,[t,...a]));}catch(e){}}setupEventListeners(){this.handleLinkClick=e=>{const t=e.target&&e.target.closest?e.target.closest("a[href]"):null;if(!t)return;const a=t.getAttribute("href");if(!a||a.startsWith("#"))return;if(this.shouldIgnoreUrl(a))return;const r=t.getAttribute("target")||"_self";setTimeout(()=>{this.logRedirect("link-click",a,{target:r});},0);},document.addEventListener("click",this.handleLinkClick,true),this.handleFormSubmit=e=>{const t=e.target,a=t&&t.getAttribute&&t.getAttribute("action")||location.href,r=(t&&t.method?String(t.method):"GET").toUpperCase();this.logRedirect("form-submit",a,{method:r});},document.addEventListener("submit",this.handleFormSubmit,true);}setupPerformanceObserver(){try{this.performanceObserver=new PerformanceObserver(e=>{for(const t of e.getEntries())"navigation"===t.entryType&&this.logRedirect("performance-navigation",location.href,{type:t.type,redirectCount:t.redirectCount});}),this.performanceObserver.observe({type:"navigation",buffered:true});}catch(e){}}init(){if(this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug")))return;if(this.isInitialized)return;const e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=true;}destroy(){this.isInitialized&&(Object.keys(this.originalMethods).forEach(e=>{const[t,a]=e.split(".");"history"===t&&this.originalMethods[e]?history[a]=this.originalMethods[e]:"location"===t&&this.originalMethods[e]?location[a]=this.originalMethods[e]:"window"===t&&"open"===a&&this.originalMethods[e]&&(window.open=this.originalMethods[e]);}),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,true),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,true),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=false);}},salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",e=>{let t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t);}),N$3.success=N$3.notify.success,N$3.error=N$3.notify.error,window.dispatchEvent(new CustomEvent("salla::created"));
12703
+ let n=function(e,t,a){return alert(e)},o=function(e,t){return n(e,l.error,t)},l={error:"error",success:"success",info:"info"};var u={fire:function(e,t,a){return n(e,t,a)},setNotifier:function(e){n=e,salla.event.emit("twilight::notifier.changed");},error:o,success:function(e,t){return n(e,l.success,t)},info:function(e,t){return n(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",()=>{e.forEach(e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,o(t.innerHTML),salla.event.emit("twilight::error",e);});}));},types:l};class c{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let s=r.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return s.forEach(e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}}),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return false},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach(e=>{e.files.length||e.setAttribute("disabled","");});var a=new FormData(this);return t.forEach(e=>{e.files.length||e.removeAttribute("disabled");}),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||(null==a?void 0:a.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach(r=>{let s=(null==a?void 0:a.dataset[r])||this.dataset[r];if(s){var i=window[s];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${s}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+s+"() not found!");}}),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class d{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach(e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);});}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,async function(...e){return t(...e)})};}getEventName(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,a={}){return Salla.event.addListener(this.getEventName(e),t,a)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function h$1(){return h$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e},h$1.apply(null,arguments)}function p(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=true);}Salla.event.auth=new class extends d{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally(()=>this.dispatch("loggedIn",e))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends d{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},this.after_init();}updated(e,t={}){var a;return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(a=e.cart.free_shipping_bar)&&a.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",h$1({},e.cart,{fromLatestFetched:t.fromLatestFetched}))):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated",{fromLatestFetched:t.fromLatestFetched}))}latestFetched(e){return this.updated(e.data,{fromLatestFetched:true}),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends d{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched",orderEdited:"order.edited",orderNotEdited:"order.not.edited"},this.after_init();}},Salla.event.scope=new class extends d{constructor(){super(),this.namespace="scope",this.events={fetched:"fetched",notFetched:"not.fetched",productAvailabilityFetched:"product-availability.fetched",productAvailabilityNotFetched:"product-availability.not.fetched",changeSucceeded:"changed",changeFailed:"not.changed"},this.after_init();}},Salla.event.rating=new class extends d{constructor(){super(),this.namespace="rating",this.events={orderNotFetched:"order.not.fetched",orderFetched:"order.fetched",storeRated:"store.rated",storeFailed:"store.failed",productsRated:"products.rated",productsFailed:"products.failed",shippingRated:"shipping.rated",shippingFailed:"shipping.failed"},this.after_init();}},Salla.event.booking=new class extends d{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.comment=new class extends d{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed",fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.landing=new class extends d{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.loyalty=new class extends d{constructor(){super(),this.namespace="loyalty",this.events={exchangeSucceeded:"exchange.succeeded",exchangeFailed:"exchange.failed",programFetched:"program.fetched",programNotFetched:"program.not.fetched",resetSucceeded:"exchange-reset.succeeded",resetFailed:"exchange-reset.failed"},this.after_init();}exchangeSucceeded(e,t){return salla.cart.event.updated(e.data),this.dispatch("exchangeSucceeded",e,t)}resetSucceeded(e){return salla.cart.event.updated(e.data),this.dispatch("resetSucceeded",e)}},Salla.event.product=new class extends d{constructor(){super(),this.namespace="product",this.events={priceUpdated:"price.updated",priceUpdateFailed:"price.updated.failed",availabilitySubscribed:"availability.subscribed",availabilitySubscribeFailed:"availability.subscribe.failed",categoriesFetched:"categories.fetched",categoriesFailed:"categories.failed",searchFailed:"search.failed",searchResults:"search.results",offerExisted:"offer.existed",fetchOffersFailed:"fetch.offers.failed",offersFetched:"offers.fetched",sizeGuideFetched:"size-guide.fetched",sizeGuideFetchFailed:"size-guide.failed",giftFetched:"gift.fetched",giftFetchFailed:"gift.failed",detailFetched:"detail.fetched",detailFetchFailed:"detail.failed",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed",productListFetchSucceeded:"fetch.succeeded",productListFetchFailed:"fetch.failed",productOptionsFetched:"options.fetched",productOptionsNotFetched:"options.not.fetched"},this.after_init();}},Salla.event.profile=new class extends d{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends d{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends d{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);});}fireEvent(e,t,...a){return this.fireEventForElements(e,t,false,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,true,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,false,...r));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const s=new CustomEvent(t,...r);return e.dispatchEvent(s)}},Salla.event.wishlist=new class extends d{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed"},this.after_init();}},Salla.event.infiniteScroll=new class extends d{constructor(){super(),this.namespace="infiniteScroll",this.events={scrollThreshold:"scroll.threshold",request:"request",load:"load",append:"append",error:"error",last:"last",history:"history"},this.after_init();}},Salla.event.notifications=new class extends d{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init();}},Salla.event.component=new class extends d{constructor(){super(),this.namespace="component",this.events={menuFetched:"menus.fetched",menuFetchFailed:"menus.fetch.failed",reviewsFetched:"reviews.fetched",reviewsFetchFailed:"reviews.fetch.failed"},this.after_init();}},Salla.event.advertisement=new class extends d{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init();}},Salla.event.navigation=new class extends d{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init();}},Salla.event.metadata=new class extends d{constructor(){super(),this.namespace="metadata",this.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},this.after_init();}},Salla.event.on("twilight::initiated",()=>{Object.keys(Salla).forEach(e=>{"object"==typeof(e=Salla[e])&&(p(e),Object.keys(e).forEach(t=>{p(e[t]);}));});}),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"==="production",token:null,fastRequests:true,canLeave:true,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"https://api.salla.dev/store/v1/"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=false,Salla.config.triedToGetLanguages_=false,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{var e;if(Salla.config.triedToGetLanguages_||Salla.config.get("languages",[]).length>0)return Salla.config.get("languages",[]);Salla.config.triedToGetLanguages_=true;let t=true,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map(e=>{t&&(a=[],t=false),e.code=e.code||e.iso_code,e.url=salla.url.get(e.code),e.is_rtl=e.is_rtl||e.rtl,a.push(e);}),Salla.config.set("languages",a),a},Salla.config.currencies=async()=>{var e;if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=true;let t=true,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map(e=>{t&&(a={},t=false),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e;}),Salla.config.set("currencies",a),a},Salla.config.isMobileApp=()=>{var e;return ["ios","android"].includes(null==(e=Salla.analytics)||null==(e=e.jitsuAnalytics)||null==(e=e.getContextProperty("app"))||null==(e=e.platform)?void 0:e.toLowerCase())};class g{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={};let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase(),this.debounce={request:void 0,time:300,enabled:true,exclude:[]};}after_init(){}normalRequest(e,t=void 0,a=null){let r=Array.isArray(e),s=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach(function(t){e[t[0]]=t[1];}),t={params:e};}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?s=salla.url.get(s):"http"!==s.substring(0,4)&&(s=salla.url.api(s)),Salla.api.request(s,t,a,{headers:i})}request(e,t=void 0,a=null){return !salla.api.isFastRequestsAllowed()&&this.debounce.enabled?(this.debounce.request||(this.debounce.request=salla.helpers.debounce(this.normalRequest.bind(this),this.debounce.time)),this.debounce.request(e,t,a)):this.normalRequest(e,t,a)}getUrl(e){let t=this.endpoints[e]||e;const a=/{[^{}]+}/i;for(let e=1;e<arguments.length;e++)t=t.replace(a,arguments[e]);return t}event(){return salla.event[this.className]}}class m extends g{constructor(){super(),this.addToCartTries=0,this.guestCartAssigned=false,this.namespace="cart",this._pendingCartIdRequest=null,this._pendingAssignRequest=null,this.endpoints={latest:"cart/latest",latestApi:"cart/latest",details:"cart/{cart}",quickAdd:"cart/{cart}/item/{product}/quick-add",addItem:"cart/{cart}/item/{product}/add",deleteItem:"cart/{cart}/item/{item}",updateItem:"cart/{cart}/item/{item}",deleteImage:"cart/{cart}/image/{image}",uploadImage:"cart/{cart}/image",status:"cart/{cart}/status",addCoupon:"cart/{id}/coupon",deleteCoupon:"cart/{id}/coupon",getQuickOrderSettings:"checkout/quick-order",createQuickOrder:"checkout/quick-order",priceQuote:"cart/{cartId}/price-quote",offers:"offers/cart/{cartId}",giftCartDetails:"cart/{cartId}/buy-as-gift",cartGiftToCart:"cart/{cart_id}/buy-as-gift",assign:"cart/{cartId}/assign?merge=1"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",()=>salla.api.cart.getCurrentCartId(false,"api::initiated")),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",async function(){try{await Salla.api.cart.assign();}catch(e){Salla.log("Error on assign after verified",e);}return Salla.api.cart.getCurrentCartId(true,"auth::verified")},{async:true}),salla.event.on("twilight::initiated",()=>salla.api.cart.syncGuestCart()),salla.event.on("profile::info.fetched",()=>this._checkCurrentCart(true)),salla.event.on("twilight::error",e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset());}_checkCurrentCart(e=false){var t,a;let r=salla.storage.get("cart"),s=null==(t=salla.config.get("user"))?void 0:t.id,i=null==(a=salla.config.get("store"))?void 0:a.id;r&&r.id&&!e&&(r.user_id===s&&r.store_id===i||(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log("Api:: case2 => The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),salla.cart.api.reset()),salla.url.is_page("cart")&&r.id!==salla.config.get("page.id")&&(salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:i}),salla.log(`Api:: case2 => The cart is different between storage:${r.id} & session:${salla.config.get("page.id")} !`),salla.cart.api.reset()));}async getCurrentCartId(e=false,t="getCurrentCartId"){if(Salla.cart.api._pendingCartIdRequest)return Salla.cart.api._pendingCartIdRequest;Salla.cart.api._pendingCartIdRequest=async function(){try{if(!e){if(Salla.cart.api.latestCart)return Salla.cart.api.latestCart.cart.id;let e=Salla.storage.get("cart.id");if(e)return e}let a=await Salla.cart.api.latest(t);return Salla.cart.api.latestCart=a.data,Salla.cart.api.latestCart.cart.id}finally{Salla.cart.api._pendingCartIdRequest=null;}}();let a=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,a}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request(salla.auth.api.isSessionless()?"latestApi":"latest",{params:{source:"",callerName:e}}).then(e=>(salla.api.cart.set(e.data.cart),salla.event.cart.latestFetched(e),e)).catch(e=>{throw salla.api.cart.reset(),salla.event.cart.latestFailed(e),e})}async details(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.details"),this.request(["details",e],{params:{with:t}}).then(function(e){return salla.cart.event.detailsFetched(e),e}).catch(function(e){throw salla.cart.event.detailsNotFetched(e),e})}async quickAdd(e,t,a){return this.addItem({id:e,quantity:t,offerType:a,endpoint:"quickAdd"})}async addItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let r=salla.form.getPossibleValue(a.payload,["endpoint"]);r&&["addItem","quickAdd"].includes(r)||(r=salla.form.getPossibleValue(a.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let s=null==(t=a.payload)?void 0:t.source;a.payload&&delete a.payload.source,Salla.cart.api.addToCartSource=s||null;let i=await Salla.api.cart.getCurrentCartId(false,"salla.api.cart.addItem");try{a.payload=Salla.helpers.createFormDataWrapper(a.payload||{}),await Salla.cart.event.beforeAddItem(a);}catch(e){}return this.request([r,i,a.id],a.payload.getRawData()).then(function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,a.id);}catch(e){Salla.log(e);}return e}).catch(function(t){if(!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(t,a.id),t})}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteItem");return this.request(["deleteItem",a,t.id]).then(function(e){return salla.cart.event.itemDeleted(e,t.id),e}).catch(function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e})}async updateItem(e){var t;let a=this.getCartPayload(e);if(!a.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let r=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.updateItem");return "Object"===(null==(t=a.payload.constructor)?void 0:t.name)?a.payload._method="PUT":a.payload.append("_method","PUT"),this.request(["updateItem",r,a.id],a.payload).then(function(e){return salla.cart.event.itemUpdated(e,a.id),e}).catch(function(e){throw salla.cart.event.itemUpdatedFailed(e,a.id),e})}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.deleteImage");return this.request(["deleteImage",t,e]).then(function(t){return salla.cart.event.imageDeleted(t,e),t}).catch(function(t){throw salla.cart.event.imageNotDeleted(t,e),t})}async status(e,t=false){e=e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.status");const a={has_apple_pay:salla.helpers.hasApplePay()};t&&(a.guest_checkout=1);try{await salla.cart.event.submitting();}catch(e){salla.log("Error on: salla.cart.event.submitting()");}return this.request(["status",e],{params:a})}async submit(e=false,t=false){const a=salla.config.get("store.features",[]).includes("embedded-login-checkout");if(salla.config.isGuest()){if(!a&&!t)return salla.cart.loginOnCartPage();try{await salla.api.cart.syncGuestCart();}catch(e){salla.log("Error on syncGuestCart during guest checkout",e);}}let r;if(e)try{var s;const e=await Salla.api.cart.assign();r=null==e||null==(s=e.data)?void 0:s.cart_id;}catch(e){Salla.log("Error on assign after login from submit",e);}const i=salla.config.isGuest()&&(t||a);this.status(null!=r?r:await salla.api.cart.getCurrentCartId(false,"salla.api.cart.submit"),i).then(e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(!a)return window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",false===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload();if(!["checkout","refresh","login"].includes(a)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===a)return salla.cart.loginOnCartPage();if("checkout"===a){var r;let t=null==(r=e.data.next_step)?void 0:r.url;if(!t){let e="Checkout URL is missing from response";throw salla.cart.event.submitFailed(e),e}return salla.helpers.hasApplePay()&&(t+=(t.includes("?")?"&":"?")+"has_apple_pay=true"),window.location.href=t}window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),window.location.reload();}).catch(function(a){var r;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let s=404===(null==a||null==(r=a.response)||null==(r=r.data)?void 0:r.status);if(s&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit(e,t);throw s&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(a),a});}getCartPayload(e){var t;let a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,a="object"==typeof a?a:void 0,{id:e,payload:a}}normalRequest(e,t=void 0,a=null){var r=this;return super.normalRequest(e,t,a).catch(async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e})}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset();}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.addCoupon");return this.request(["addCoupon",t],{coupon:e}).then(function(e){var a;let r=salla.storage.get("cart");return r&&null!=(a=e.data)&&null!=(a=a.cart)&&a.coupon&&(r.coupon=e.data.cart.coupon,salla.storage.set("cart",r)),salla.event.cart.couponAdded(e,t),e}).catch(function(e){throw salla.event.cart.couponAdditionFailed(e,t),e})}async deleteCoupon(){let e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then(function(t){let a=salla.storage.get("cart");return a&&a.coupon&&(delete a.coupon,salla.storage.set("cart",a)),salla.event.cart.couponDeleted(t,e),t}).catch(function(t){throw salla.event.cart.couponDeletionFailed(t,e),t})}getQuickOrderSettings(){return this.request("getQuickOrderSettings").then(e=>(salla.event.cart.quickOrderSettingFetched(e),e)).catch(e=>{throw salla.event.cart.quickOrderSettingFailed(e),e})}createQuickOrder(e){return this.request("createQuickOrder",e).then(e=>(salla.event.cart.quickOrderSucceeded(e),e)).catch(e=>{throw salla.event.cart.quickOrderFailed(e),e})}async priceQuote(e){return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("cart::priceQuote",e),void salla.event.dispatch("login::open")):this.request(["priceQuote",e||await salla.api.cart.getCurrentCartId(false,"salla.api.cart.priceQuote")]).then(e=>(salla.cart.api.reset(),salla.event.cart.priceQuoteSucceeded(e).then(()=>(setTimeout(()=>window.location.href=salla.url.get("/"),1e3),e)))).catch(e=>salla.event.cart.priceQuoteFailed(e).then(()=>{var t;throw 404===(null==(t=e.error)?void 0:t.code)&&window.location.reload(),e}))}loginOnCartPage(){salla.auth.setCanRedirect(false),salla.event.dispatch("login::open",{withoutReload:true,source:"cart-submit"}),salla.auth.event.onLoggedIn(()=>{salla.event.dispatch("login::close"),salla.cart.submit(true);});}set(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart();}async offers(){const e=await salla.cart.api.getCurrentCartId(false,"salla.api.cart.offers");return this.request(["offers",e]).then(e=>(salla.event.cart.offersFetched(e),e)).catch(e=>{throw salla.event.cart.offersFailed(e),e})}async getGiftCartDetails(){let e=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.getGiftCartDetails");return this.request(["giftCartDetails",e]).then(t=>(salla.product.event.giftFetched(t,e),t)).catch(t=>{throw salla.product.event.giftFetchFailed(t,e),t})}async addCartGiftToCart(e,t=false){let a=await salla.api.cart.getCurrentCartId(false,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then(e=>(salla.product.event.addGiftToCartSucceeded(e,a),t&&(window.location.href=e.redirect),e)).catch(e=>{throw salla.product.event.addGiftToCartFailed(e,a),e})}async syncGuestCart(){if(!salla.config.isGuest())return;const e=salla.api.cart.getCartCookiePrefix(),t=salla.cookie.getCookieByPrefix(e),a=salla.storage.get("cart.id");if(!a&&t.length)try{var r;const t=null==(r=(await salla.api.cart.latest()).data)||null==(r=r.cart)?void 0:r.id;t&&salla.api.cart.setCartCookie(e,t);}catch(e){salla.log("Failed to fetch latest cart:",e);}salla.cookie.clearCookieByPrefix(e),a&&(salla.config.set("headers.s-cart-id",a),salla.api.cart.setCartCookie(e,a));}async assign(){var e=this;if(Salla.api.cart._pendingAssignRequest)return Salla.api.cart._pendingAssignRequest;let t=Salla.storage.get("cart.id");return !(!t||Salla.api.cart.guestCartAssigned)&&(Salla.api.cart._pendingAssignRequest=async function(){try{const a=await e.request(["assign",t]);return Salla.api.cart.guestCartAssigned=true,a}catch(e){throw e}finally{Salla.api.cart._pendingAssignRequest=null;}}(),Salla.api.cart._pendingAssignRequest)}setCartCookie(e,t){salla.cookie.set(`${e}-${t}`,t,1);}getCartCookiePrefix(){return "cart-id-"+salla.config.get("store.id")}}class f extends g{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then(e=>(salla.loyalty.event.programFetched(e),e)).catch(e=>{throw salla.loyalty.event.programNotFetched(e),e})}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then(function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t}).catch(function(t){throw salla.loyalty.event.exchangeFailed(t,e),t})}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId(false,"salla.api.loyalty.reset"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then(e=>(salla.loyalty.event.resetSucceeded(e),e)).catch(e=>{throw salla.loyalty.event.resetFailed(e),e})}}class D extends g{constructor(){super(),this.namespace="auth",this.canRedirect_=true,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.inIframe=salla.helpers.isIframe(),Salla.event.on("twilight::init",function(){if(Salla.config.isGuest()&&location.href.includes("force_logout"))return delete Salla.api.axios.defaults.headers.common.Authorization,Salla.api.auth.logout("twilight",false)}),this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){var t;null!=(t=e)&&t.data&&(e=e.data);let a=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(a)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",a],e).then(function(e){return salla.auth.event.codeSent(e,a),e}).catch(function(e){throw salla.auth.event.codeNotSent(e,a),salla.auth.api.trackBlockedError(e,"login"),e})}async verify(e,t=true){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=false!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let r=await salla.auth.api.request(["verify",a],e);return 200!==(null==r?void 0:r.status)?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)}async handlAfterAuthenticatedResponse(e,t){var a;e.data||(e={data:e});let r="authenticated"===(null==(a=e.data)?void 0:a.case);return r&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),r&&await salla.auth.event.loggedIn(e).then(()=>salla.auth.api.afterUserLogin()),await salla.auth.event.verified(e,e.data.verification.type),salla.api.successPromise(e)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then(function(t){return salla.auth.event.codeSent(t,e),t}).catch(function(t){throw salla.auth.event.codeNotSent(t,e),salla.auth.api.trackBlockedError(t,"resend"),t}):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){var t=this;let a;return e.data&&(a=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then(async function(e){var r;return salla.auth.event.registered.call(a,e),"authenticated"===(null==(r=e.data)?void 0:r.case)&&(salla.auth.event.tokenFetched(e.data.token),!t.inIframe&&!t.isSessionless()&&await salla.auth.request("auth/jwt",{callerName:"salla.auth.api.register"}),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e}).catch(function(e){throw salla.auth.event.registrationFailed.call(a,e),salla.auth.api.trackBlockedError(e,"register"),e})}handleIframeReadyAction(e,t){var a;null==(a=e.contentWindow)||a.postMessage({source:"logout",type:"init",data:{id:salla.config.get("store.id"),lang:"ar",appUrl:t,apiUrl:salla.config.get("store.api").replace(/\/+$/,""),settings:salla.config.all(),storage:{}}},"*");}appendIframeAndLogout(){return new Promise(e=>{let t=salla.config.get("login.url","https://accounts.salla.com");const a=document.createElement("iframe");a.style.display="none",a.src=`${t}/logout`;const r=s=>{if("login"!==s.data.source)return;let i=s.data.type.replace("iframe::","");if(salla.log("iframe::logout-iframe message received",s.data),["logged-out","ready"].includes(i)){if("ready"===i)return this.handleIframeReadyAction(a,t);window.removeEventListener("message",r),a.remove(),e();}};window.addEventListener("message",r),document.body.appendChild(a);})}logout(e="twilight",t=true){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then(()=>this.appendIframeAndLogout()).then(()=>{if(!t)return;let a=salla.url.get(`logout?from=${e}`);console.log(`Going to ${a}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=a;}catch(e){salla.log(e);}}).catch(e=>console.error("Error during logout:",e))}refresh(){return this.request("refresh").then(function(e){return salla.auth.event.tokenFetched(e.data.token),e}).catch(function(e){throw salla.auth.event.refreshFailed(e),e})}afterUserLogin(){this.afterLoginEvent.event&&salla.event.emit(this.afterLoginEvent.event,this.afterLoginEvent.payload);}isSessionless(){var e;return "sessionless"===(null!=(e=salla.config.get("auth.mode"))?e:salla.config.get("login.mode"))}trackBlockedError(e,t){var a;void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"])&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message});}}class F extends g{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders",editOrder:"orders/{id}"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get",editOrder:"put"},this.after_init();}show(e){let t=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["url"]);}cancel(e){return e=e||Salla.config.get("page.id"),this.request(["cancel",e],{params:{has_apple_pay:salla.helpers.hasApplePay()}}).then(function(t){return salla.event.order.canceled(t,e),t}).catch(function(t){throw salla.event.order.notCanceled(t,e),t})}createCartFromOrder(e){return e=e||salla.config.get("page.id"),this.request(["createCartFromOrder",e]).then(function(t){return salla.cart.reset(),salla.event.order.orderCreated(t,e),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}reorderProduct(e){return e=e||salla.config.get("page.id"),this.request(["reorderProduct",e]).then(function(t){const a=h$1({},t.data,{type:"reorder",id:e}),r=h$1({},t,{data:a});return salla.event.order.orderCreated(r,t.data.order_id),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then(e=>(salla.event.order.invoiceSent(e,t),e)).catch(e=>{throw salla.event.order.invoiceNotSent(e,t),e})}editOrder(e,t){return e=e||salla.config.get("page.id"),this.request(["editOrder",e],t).then(function(t){return salla.event.order.orderEdited(t,e),t}).catch(function(t){throw salla.event.order.orderNotEdited(t,e),t})}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.order.ordersFetched(e),e}).catch(function(e){throw salla.event.order.ordersNotFetched(e),e})}}class v extends g{constructor(){super(),this.namespace="product",this.previousQuery="",this.endpoints={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",details:"products/{product_id}/details",categories:"products/categories/{?id}",offers:"products/{product_id}/specialoffer",getSizeGuides:"products/{prod_id}/size-guides",giftProductDetails:"products/{product_id}/buy-as-gift",productGiftToCart:"products/{product_id}/buy-as-gift",giftImage:"products/buy-as-gift/image",buyNow:"products/{product_id}/buy-now",fetch:"products",fetchOptions:"products/options"},this.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get"},this.after_init();}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then(function(e){return salla.product.event.priceUpdated(e,a),e}).catch(function(e){throw salla.product.event.priceUpdateFailed(e,a),e})}categories(e){return this.request(["categories",e||""],null,"get").then(function(e){return salla.product.event.categoriesFetched(e),e}).catch(function(e){throw salla.product.event.categoriesFailed(e),e})}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then(function(t){return salla.product.event.availabilitySubscribed(t,e),t}).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}search(e){var t;let a=e.data;if(a||(a={params:"string"==typeof e?{query:e}:e}),!(e=a instanceof FormData?a.get("query"):a.query||(null==(t=a.params)?void 0:t.query))){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",a,"get").then(function(t){return salla.product.event.searchResults(t,e),t}).catch(function(t){throw salla.product.event.searchFailed(t,e),t})}offers(e){var t;if(!(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.product.event.fetchOffersFailed(e),salla.api.errorPromise(e)}return this.request(["offers",e]).then(function(t){return salla.product.event.offersFetched(t,e),t}).catch(function(t){throw salla.product.event.fetchOffersFailed(t,e),t})}getSizeGuides(e){return this.request(`products/${e}/size-guides`,null,"get").then(t=>(salla.product.event.sizeGuideFetched(t,e),t)).catch(t=>{throw salla.product.event.sizeGuideFetchFailed(t,e),t})}getGiftProductDetails(e){return this.request(["giftProductDetails",e]).then(t=>(salla.product.event.giftFetched(t,e),t)).catch(t=>{throw salla.product.event.giftFetchFailed(t,e),t})}getDetails(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.product.event.detailFetchFailed(e),salla.api.errorPromise(e)}return this.request(["details",e],{params:{with:t}}).then(function(t){return salla.product.event.detailFetched(t,e),t}).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}addProductGiftToCart(e,t,a=false){return this.request(["productGiftToCart",e],t).then(t=>(salla.product.event.addGiftToCartSucceeded(t,e),a&&(window.location.href=t.redirect),t)).catch(t=>{throw salla.product.event.addGiftToCartFailed(t,e),t})}uploadGiftImage(e){return this.request("giftImage",e).then(e=>(salla.product.event.giftImageUploadSucceeded(e),e)).catch(e=>{throw salla.product.event.giftImageUploadFailed(e),e})}fetch(e){if(!e.source){const e="Source cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}const t=!e.source_value,a="string"==typeof e.source_value&&"[]"===e.source_value,r=Array.isArray(e.source_value)&&!e.source_value.length;if((t||a||r)&&!["offers","latest","sales","wishlist","top-rated","reorder"].includes(e.source)){const e="Source value cannot be empty. Please provide one.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if(["categories","brands","tags","selected"].includes(e.source)&&!Array.isArray(e.source_value)){const e="SourceValue type error. Expected an array.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("search"===e.source&&"string"!=typeof e.source_value){const e="SourceValue type error. Expected a string.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}if("related"===e.source&&isNaN(e.source_value)){const e="SourceValue type error. Expected a number.";return salla.product.event.productListFetchFailed(e),salla.api.errorPromise(e)}return this.request(this.endpoints.fetch,{params:e},"get").then(async function(e){return salla.product.event.productListFetchSucceeded(e),e}).catch(e=>{throw salla.product.event.productListFetchFailed(e),e})}fetchOptions(e,t={}){if(!e||0===e.length){const e="At least one product ID is required. Please provide a valid list of product IDs.";return salla.product.event.productOptionsNotFetched(e),salla.api.errorPromise(e)}const{with:a=[]}=t,r={selected:e};return a.length>0&&(r.with=a),this.request(this.endpoints.fetchOptions,{params:r},"get").then(e=>(salla.product.event.productOptionsFetched(e),e)).catch(e=>{throw salla.product.event.productOptionsNotFetched(e),e})}}class y extends g{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init();}syncUserData(e){let t={id:e.id,type:"user",email:e.email,mobile:e.phone.code+e.phone.number,country_code:e.phone.country,language_code:e.language,currency_code:e.currency,notifications:e.notifications,pending_orders:e.pending_orders,avatar:e.avatar,first_name:e.first_name,last_name:e.last_name,is_hidden_name:e.is_hidden_name,is_notifiable:e.is_notifiable,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",t),salla.storage.set("user",t);}info(){return this.request("info",null,"get").then(e=>(this.syncUserData(e.data),salla.profile.event.infoFetched(e),e)).catch(e=>{throw salla.profile.event.infoNotFetched(e),e})}update(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("update",e).then(e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateCustomFields(e){if(Salla.config.get("store.features",[]).includes("sso-login")){const e="SSO login is enabled. You cannot update your profile.";return Salla.error(e),Promise.reject(new Error(e))}return this.request("updateCustomFields",e).then(e=>(this.syncUserData(e.data),salla.profile.event.updated(e),e)).catch(e=>{throw salla.event.profile.updateFailed(e),e})}updateContacts(e){return this.request("updateContacts",e).then(e=>(salla.profile.event.verificationCodeSent(e),e)).catch(e=>{throw salla.event.profile.updateContactsFailed(e),e})}verify(e){return this.request("verify",e).then(e=>(salla.profile.event.verified(e),e)).catch(e=>{throw salla.event.profile.unverified(e),e})}updateSettings(e){return this.request("updateSettings",e).then(e=>(salla.event.profile.settingsUpdated(e),e)).catch(e=>{throw salla.event.profile.updateSettingsFailed(e),e})}delete(){return this.request("delete").then(e=>(salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.api.appendIframeAndLogout().then(()=>{salla.event.profile.deleted(e),window.location.href=salla.url.get("logout");}),e)).catch(e=>{throw salla.event.profile.notDeleted(e),e})}}class C extends g{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init();}add(e){var t;if(null!=(t=e)&&t.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,true)))return salla.event.comment.additionFailed(e),salla.api.errorPromise(e);if(!e.comment){let e="can't find comment content!";return salla.event.comment.additionFailed(e),salla.api.errorPromise(e)}return this.request(["addComment","blog"==e.type?"blogs":e.type,e.id],{comment:e.comment}).then(function(t){return salla.event.comment.added(t,e.id),t}).catch(function(t){throw salla.event.comment.additionFailed(t,e.id),t})}getCommentPayload(e,t=false){let a={};if(["id","type","comment","per_page","page","sort"].forEach(t=>{let r=salla.form.getPossibleValue(e,[t]);r&&(a[t]=r);}),!t){let t=e.ids;if(t&&(a.ids=Array.isArray(t)?t:[t]),!a.ids||!a.ids.length)return "Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"}fetchComments(e){const t=e.customerId;if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const a={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(a.sort=e.sort),t&&(a.private_comments=t),this.request(["comments"],{params:a},"get").then(function(t){return salla.event.comment.fetched(t,e),t}).catch(function(t){throw salla.event.comment.fetchFailed(t,e),t})}getComments(e,t,a=1,r=5,s,i=null){const n=Array.isArray(t)?t:[t];return this.fetchComments({ids:n,type:`${e}s`,page:a,per_page:r,sort:s,customerId:i})}}class S extends g{constructor(){super(),this.namespace="currency",this.endpoints={change:"/",list:"currencies"},this.endpointsMethods={change:"get",list:"get"},this.webEndpoints=["change"],this.after_init();}change(e){if(!(e=salla.form.getPossibleValue(e.data||e,["currency","code"]))){let e="Can't find currency code!";return salla.currency.event.failed(e),salla.api.errorPromise(e)}return this.request("change",{params:{change_currency:"",currency:e}}).then(function(t){return salla.cookie.set("fresh_summary",1),salla.storage.set("cart",""),salla.currency.event.changed(t,e),t}).catch(function(t){throw salla.currency.event.failed(t,e),t})}list(){return this.request("list").then(function(e){return salla.currency.event.fetched(e),e}).catch(function(e){throw salla.currency.event.failedToFetch(e),e})}}class w extends g{constructor(){super(),this.namespace="document";}reload(){window.location.reload();}}class A extends g{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}"},this.endpointsMethods={order:"get"},this.after_init();}order(e){let t="object"==typeof e?e:{},a=salla.form.getPossibleValue((null==e?void 0:e.data)||e,["order_id","id"]);if(!a){let e='There is no "order_id"!';return salla.event.rating.orderNotFetched(e),salla.api.errorPromise(e)}return this.request(["order",a],t).then(function(e){return salla.event.rating.orderFetched(e,a),e}).catch(function(e){throw salla.event.rating.orderNotFetched(e,a),e})}store(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.storeFailed(e),salla.api.errorPromise(e)}return this.request("store",e).then(function(t){return salla.event.rating.storeRated(t,e),t}).catch(function(t){throw salla.event.rating.storeFailed(t,e),t})}products(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.productsFailed(e),salla.api.errorPromise(e)}return this.request("products",e).then(function(t){return salla.event.rating.productsRated(t,e),t}).catch(function(t){throw salla.event.rating.productsFailed(t,e),t})}shipping(e){var t;if(!(e=(null==(t=e)?void 0:t.data)||e)){let e='There is no "data"!';return salla.event.rating.shippingFailed(e),salla.api.errorPromise(e)}return this.request("shipping",e).then(function(t){return salla.event.rating.shippingRated(t,e),t}).catch(function(t){throw salla.event.rating.shippingFailed(t,e),t})}}class E extends g{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},Salla.onReady(()=>{var e;"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||this.injectSourceIntoRequest());});}injectSourceIntoRequest(){Salla.api.axios.interceptors.request.use(e=>(e.headers=h$1({},e.headers,{"s-utm-source":"wishlist"}),e),e=>Promise.reject(e));}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["add",e]).then(t=>(this.updateWishlistStorage(e),salla.wishlist.event.added(t,e),t)).catch(function(t){throw salla.wishlist.event.additionFailed(t,e),t}):(salla.wishlist.event.additionFailed(a="Failed to get product id!"),salla.api.errorPromise(a))}remove(e){var t;let a;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]))?this.request(["remove",e]).then(t=>(this.updateWishlistStorage(e,false),salla.wishlist.event.removed(t,e),t)).catch(function(t){throw salla.wishlist.event.removingFailed(t,e),t}):(salla.wishlist.event.removingFailed(a="Failed to get id!"),salla.api.errorPromise(a))}updateWishlistStorage(e,t=true){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a);}}class b extends g{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init();}get(){return this.request("scopes",null,"get").then(e=>(salla.scope.event.fetched(e),e)).catch(e=>{throw salla.scope.event.notFetched(e),e})}change(e){return this.request("scopes",e).then(e=>(salla.scope.event.changeSucceeded(e),e)).catch(e=>{throw salla.scope.event.changeFailed(e),e})}getProductAvailability(e=null){return this.request(`scopes/availability?product_id=${e}`,null,"get").then(t=>(salla.scope.event.productAvailabilityFetched(t,e),t)).catch(e=>{throw salla.scope.event.productAvailabilityNotFetched(e),e})}}class _ extends g{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"};}async add(e,t=true){if(!e){let e="Please provide product id.";return salla.booking.event.additionFailed(e),salla.api.errorPromise(e)}return this.request(["add",e]).then(function(e){return salla.booking.event.added(e),t&&"booking"===e.data.redirect.to&&(window.location.href=e.data.redirect.url),e}).catch(function(e){throw salla.booking.event.additionFailed(e),e})}}class k extends g{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init();}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then(function(t){return salla.event.landing.detailsFetched(t,e),t}).catch(function(t){throw salla.event.landing.getDetailsFailed(t,e),t})}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then(function(t){return salla.event.landing.orderCreated(t,e).then(()=>location.href=t.data.url),t}).catch(function(t){throw salla.event.landing.orderCreationFailed(t,e),t})}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.landing.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e})}}class x extends g{constructor(){super(),this.namespace="notifications",this.endpoints={fetch:"notifications"},this.endpointsMethods={fetch:"get"},this.after_init();}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.notifications.fetched(e),e}).catch(function(e){throw salla.event.notifications.fetchFailed(e),e})}}class B{constructor(){var e,t=this;this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",async function(e){return await t.initiateRequest(e)}),salla.event.on("profile::info.fetched",e=>this.setCurrencyAndLanguage(e)),salla.event.on("auth::token.fetched",e=>{salla.storage.set("token",e),this.inIframe&&salla.log("token fetched iframe"),this.inIframe&&salla.cookie.set("s-token",e,60),this.setToken(e);}),salla.event.on("auth::token.invalid",()=>{salla.storage.remove("user"),salla.storage.remove("token");}),this.notifier_handler_disabled=false,this.axios=axios.create({baseURL:Salla.config.get("store.api",Salla.config.get("store.url")),headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":(null==(e=Salla)||null==(e=e.versions)?void 0:e.twilight)||"2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}}),this.axios.interceptors.request.use(e=>{"preview"===Salla.config.get("theme.mode")&&(e.url=Salla.url.addParamToUrl("use_username_url",1,e.url));try{var t;const a=Salla.config.get("swoole",[]),r=new RegExp(a.join("|"),"i");a.length>0&&r.test(e.url)&&(e.headers["s-store-api-version"]="swoole");const s=null==(t=Salla.analytics)?void 0:t.getAnonymousId();s&&(e.headers["s-anonymous-id"]=s);}catch(e){Salla.log("Error in request interceptor:",e);}return e},e=>Promise.reject(e));}getHeaders(){let e=h$1({},this.axios.defaults.headers.common);return delete e["Content-Type"],e}getHeader(e){var t;return null==(t=Object.entries(this.getHeaders()).filter(([t])=>t.toLowerCase()===e.toLowerCase())[0])?void 0:t[1]}setHeaders(e){return Object.entries(e).forEach(e=>this.setHeader(e[0],e[1])),this}setHeader(e,t){return salla.infiniteScroll.fetchOptions.headers[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_handler_disabled=true,await e().finally(()=>{this.notifier_handler_disabled=false;})}async initiateRequest(e){var t,a,r;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(h$1({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(r=e.user)?void 0:r.country_code},e.headers||{}));const s=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search),n=i.get("scope"),o=i.get("allocation_type"),l=i.get("allocation_id");if(n&&s&&!Salla.url.is_page("cart")){const e=Salla.storage.get("scope")||{};Salla.storage.set("scope",h$1({},e,{type:s.type,id:n},o&&{allocation_type:o},l&&{allocation_id:l})),s.id=n,Salla.cart.reset();}if((o||l)&&(Salla.url.is_page("cart")||!n||!s)){const e=Salla.storage.get("scope")||{};var u,c;if(null!=e&&e.id||null!=s&&s.id)Salla.storage.set("scope",h$1({},e,{id:null!=(u=null==e?void 0:e.id)?u:null==s?void 0:s.id,type:null!=(c=null==e?void 0:e.type)?c:null==s?void 0:s.type},o&&{allocation_type:o},l&&{allocation_id:l}));}if(s){this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const e=Salla.storage.get("scope")||{};e.allocation_type&&this.setHeader("s-scope-allocation-type",e.allocation_type),e.allocation_id&&this.setHeader("s-scope-allocation-id",e.allocation_id);}const d=Salla.storage.getWithTTL("s-utms");if(d){const e={};Object.entries(d).forEach(([t,a])=>{e[t]="string"==typeof a&&/[^\x00-\x7F]/.test(a)?encodeURIComponent(a):a;}),this.setHeaders(e);}await this.injectTokenToTheRequests(e),Salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",Salla.storage.get("affiliate_code"));}async injectTokenToTheRequests(e){var t,a,r=this;let i,n,o=this.getToken(),l="guest"===(null==(t=e.user)?void 0:t.type),u=parseInt((null==(a=e.user)?void 0:a.id)||0),c=parseInt(salla.storage.get("user.id")||0),d=salla.auth.api.isSessionless(),h=e=>{this.setToken(e),salla.event.emit("api::initiated");},p=async function(){l||d||!u?salla.auth.event.tokenInvalid():(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then(async function(){await salla.profile.info();}).catch(()=>salla.auth.event.tokenInvalid()));};if(!o)return salla.log("Api:: case 1 => current is is guest"),void await p();try{i=jwtDecode(o);}catch(e){return Salla.logger.warn("Failed to decode JWT token",e),void Salla.auth.event.tokenInvalid()}return Date.now()/1e3>i.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await p()):(n=d?parseInt(i.sub)!==c:!c||!u||c!==u||parseInt(i.sub)!==u,n?(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${i.sub} userIdInWeb:${u} userIdInStorage:${c}, isSessionless:${d}`,i.sub,u,c),this.setHeader("Authorization","Bearer "+o),void await salla.profile.info().then(async function(e){!r.inIframe&&!d&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),h(o);}).catch(()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid();})):(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void h(o)))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}cleanupTokenFromUrl(){try{const e=new URL(window.location.href);if(!e.searchParams.has("token"))return;e.searchParams.delete("token"),window.history.replaceState({},document.title,e.toString());}catch(e){Salla.logger.warn("Failed to cleanup token from URL",e);}}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t=void 0,a="get",r={}){let s={endPoint:e,payload:t,method:a,options:r},i="undefined"!=typeof event?event.currentTarget:null,n=false;return "SALLA-BUTTON"===(null==i?void 0:i.tagName)&&(n=true),n&&(null==i||i.load()),this.axios[s.method](s.endPoint,s.payload,s.options).then(e=>(n&&(null==i||i.stop()),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e)).catch(e=>{throw n&&(null==i||i.stop()),salla.event.document.requestFailed(s,e),this.handleErrorResponse(e),e})}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;try{dataLayer&&r&&dataLayer.push(r);}catch(e){salla.logger.error(e.message);}this.fireEventsForResponse(e),this.showAlert(e);}fireEventsForResponse(e){var t,a;let r=(null==e?void 0:e.events)||(null==(t=e.data)?void 0:t.events)||(null==(a=e.error)?void 0:a.events);"string"==typeof r&&(r=JSON.parse(r)),r&&Object.keys(r).forEach(e=>salla.event.dispatch(e,r[e]));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){var t,a;if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&null!=(t=e.data)&&t.message?salla.notify.fire(null==(a=e.data)?void 0:a.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach(e=>{let r=t[e];Array.isArray(r)?r.forEach(e=>a.push(e)):a.push(r);});let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=true){return new Promise((a,r)=>t?a(e):r(e))}errorPromise(e){return this.promise(e,false)}successPromise(e){return this.promise(e,true)}getToken(){if(Salla.storage.get("token"))return Salla.storage.get("token");try{var e;const t=null==(e=new URLSearchParams(window.location.search))?void 0:e.get("token");if(!t)return;if(3!==t.split(".").length)return;return this.cleanupTokenFromUrl(),t}catch(e){Salla.logger.warn("Failed to extract or validate token from URL",e);}}}class P extends g{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}?store_id={store}&lang={lang}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"};}async getMenus(e="header"){return this.request(["getMenus",e,salla.config.get("store.id"),salla.lang.getLocale()]).then(function(e){return salla.event.component.menuFetched(e),e}).catch(function(e){throw salla.event.component.menuFetchFailed(e),e})}async getReviews({per_page:e=5,type:t="all",items:a}){if(!t){const e="Review type cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}const r=!a||"string"==typeof a&&"[]"===a||Array.isArray(a)&&!a.length;if(!new Set(["all","store","categories","products","json"]).has(t)){const e="Invalid review type. Please provide a valid type.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if("all"!==t&&"store"!==t&&r){const e="Items cannot be empty. Please provide one.";return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}if(new Set(["products","categories"]).has(t)&&!Array.isArray(a)){const e=`Items value must be an array of ${t} id for review type of ${t}.`;return salla.event.component.reviewsFetchFailed(e),salla.api.errorPromise(e)}return this.request(["reviews"],{params:{per_page:e,type:t,items:a}},"get").then(function(e){return salla.event.component.reviewsFetched(e),e}).catch(function(e){throw salla.event.component.reviewsFetchFailed(e),e})}}class I extends g{constructor(){super(),this.namespace="booking",this.endpoints={fetch:"advertisements"},this.endpointsMethods={fetch:"get"};}async fetch(e=null){const t=e?{page:e}:{};return this.request(["fetch"],{params:t}).then(function(e){return salla.event.advertisement.fetched(e),e}).catch(function(e){throw salla.event.advertisement.fetchFailed(e),e})}}class q extends g{constructor(){super(),this.namespace="navigation",this.endpoints={breadcrumbs:"breadcrumbs"},this.endpointsMethods={breadcrumbs:"get"},this.after_init();}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.navigation.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.single","product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.navigation.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.navigation.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.navigation.breadcrumbFetchFailed(e),e})}}class T extends g{constructor(){super(),this.namespace="metadata",this.endpoints={fetchValues:"https://api.salla.dev/store/v1/metadata/values"},this.endpointsMethods={fetchValues:"get"};}async fetchValues(e,t){if(!e||!t){const e="Please provide entity type and entity ids.";return salla.metadata.event.valueNotFetch(e),salla.api.errorPromise(e)}const a={type:e,entities:Array.isArray(t)?t:[t]};return this.request(this.endpoints.fetchValues,{params:a},"get").then(e=>(salla.metadata.event.valueFetched(e),e)).catch(e=>{throw salla.metadata.event.valueNotFetch(e),e})}}class L{constructor(e){this.config=e,this.configKey="s-twilight-config",this.tempUser=e.user;}async getConfig(){if(Object.entries(this.config.store).length>2)return this.config;let e=await this.getConfigFromSession();return e||(e=await this.getConfigFromApi()),e.user=this.tempUser,e}async getConfigFromSession(){var e;let t=salla.storage.getWithTTL("session",this.configKey);return t&&"object"==typeof t&&null!=(e=t.store)&&e.id?this.config.store.id==t.store.id?t:(salla.storage.session.remove(this.configKey),null):null}getConfigFromApi(){console.log("getting Twilight initiate config using store.id ...");const e=new URL(`${(this.config.store.api||Salla.config.get("store.api")).replace(/\/$/,"")}/store/settings`);return fetch(e,{headers:Salla.api.getHeaders()}).then(e=>e.json()).then(e=>{if(200!==e.status)throw {response:e};return this.setConfigToSession(e.data)}).catch(e=>{throw Salla.api.handleErrorResponse(e),e})}setConfigToSession(e){return Salla.storage.setWithTTL("session",this.configKey,e,1800),e}}class R{constructor(){Salla.event.on("twilight::before.ready",()=>this.renderAll());}async renderAll(){Salla.hooks.renderAutoComponents([{hook:"product:single.description",tag:"salla-delivery-promise",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("delivery-promises")},{hook:"product:single.form.end",tag:"salla-fulfillment-methods",canRender:()=>Salla.url.is_page("product.single")&&!Salla.config.get("store.features",[]).includes("bullet-delivery-v2")},{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}},{hook:"body:end",tag:"salla-bullet-delivery",canRender:()=>{var e;return (null==(e=Salla.config.get("store.features"))?void 0:e.includes("bullet-delivery-v2"))&&true===Salla.config.get("store.settings.bullet_delivery.enabled")}}]),await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.helpers.isIframe()||(this.renderMaintenance(),this.renderThemePreview());}renderMaintenance(){Salla.config.get("maintenance")&&(document.body.classList.add("has-maintenance-bar"),document.querySelector("salla-maintenance-alert")?Salla.logger.warn("salla-maintenance-alert element Existed before!"):document.body.prepend(document.createElement("salla-maintenance-alert")));}renderTemplateStore(){Salla.config.get("store.template")&&(document.body.classList.add("has-bottom-alert"),document.querySelector("salla-bottom-alert")?Salla.logger.warn("salla-bottom-alert element Existed before!"):document.body.append(document.createElement("salla-bottom-alert")));}renderAppInstall(){Salla.config.get("store.app_install_prompt")&&Salla.config.get("store.apps")&&!Salla.storage.get("app_install_prompt_disabled")&&!Salla.config.isMobileApp()&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?Salla.logger.warn("salla-app-install-alert element Existed before!"):document.body.append(document.createElement("salla-app-install-alert")));}renderThemePreview(){if("preview"!==Salla.config.get("theme.mode"))return;if(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar"))return void Salla.logger.warn("#s-theme_preview_bar element Existed before!");let e=document.createElement("div");e.id="s-theme_preview_bar",e.setAttribute("style","display: flex; justify-content: space-between; text-align: center; background-color: #232323; color: #fff; padding: 10px; font-size: 0.875rem; line-height: 1.25rem; position: relative;"),e.innerHTML=`\n <div style="display:flex; align-items:center;">\n <img width="32" src="https://cdn.salla.network/images/logo/logo-light.svg">\n <span style="margin:0 10px;">${Salla.lang.get("blocks.header.preview_mode")}: <span style="background:rgba(255,255,255,0.25);border-radius:15px; padding:2px 15px 4px">${Salla.config.get("theme.name")}</span></span>\n </div>\n <a href="${Salla.url.get("preview_theme/cancel/preview")}" style="line-height:32px; width:32px;"><i class="sicon-cancel"></i></a>\n `,document.body.prepend(e);}renderEdit(){let e=Salla.config.get("edit");if(!e)return;if(document.querySelector("#s-edit-alert"))return void Salla.logger.warn("#s-edit-alert element Existed before!");let t=document.createElement("div");t.id="s-edit-alert",t.innerHTML=`\n <a href="${e}" style="display:block; background-color:${Salla.config.get("theme.color.primary","#5cd5c4")}; color:${Salla.config.get("theme.color.reverse","#fff")}; padding: 10px; text-align:center; font-size: 0.875rem; line-height: 1.25rem;">\n <i class="sicon-edit"></i> \n ${Salla.lang.get("pages.products.quick_edit")}\n </a>\n `,document.body.prepend(t);}applyContentCopyright(){if(!Salla.config.get("store.settings.content_copyright"))return;["contextmenu","selectstart","copy"].forEach(e=>{document.addEventListener(e,e=>{(e=>{var t;if(!e)return false;const a=null==(t=e.tagName)?void 0:t.toLowerCase();return "input"===a||"textarea"===a})(e.target)||e.preventDefault();});}),document.addEventListener("keydown",e=>{const t=e.key.toLowerCase();("f12"===t||e.ctrlKey&&e.shiftKey&&["i","j","c"].includes(t)||e.ctrlKey&&"u"===t)&&(e.preventDefault(),e.stopPropagation());});const e=document.createElement("style");e.textContent="\n body {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n input, textarea {\n -webkit-touch-callout: auto;\n -webkit-user-select: auto;\n -moz-user-select: auto;\n -ms-user-select: auto;\n user-select: auto;\n }\n img {\n pointer-events: none;\n -webkit-user-drag: none;\n }\n ",document.head.appendChild(e);}}class j{constructor(e){this.storeUserKey="s-store-user",Salla.event.on("twilight::initiated",()=>this.embedStoreUser()),this.embedUser(e);}embedUser(e){return e.user||(e.user=this.getUser(),e.user.language_code=Salla.cookie.get("s-lang",e.user.language_code),e.user.currency_code=Salla.cookie.get("s-curr",e.user.currency_code)),e}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return {type:"guest",language_code:Salla.cookie.get("s-lang",Salla.lang.getLocale()),currency_code:Salla.cookie.get("s-curr","SAR")}}async embedStoreUser(){if(Salla.config.isGuest())return;let e=Salla.storage.getWithTTL("session",this.storeUserKey);e||(e=await this.getStoreUserFromApi()),Salla.config.set("user",h$1({},Salla.config.get("user"),e)),Salla.log("Store user is embeded to the user object.");}async getStoreUserFromApi(){let e={};try{const t=await Salla.api.request("profile/notifications/unread");if(e.notification=t.data.count,e.is_notifiable=t.data.is_notifiable,Salla.config.get("store.features",[]).includes("loyalty-system")){const t=await Salla.api.request("profile/loyalty/points");t&&(e.loyalty_points=t.data.points);}}catch(e){Salla.log("Failed to get user services",e);}return Salla.storage.setWithTTL("session",this.storeUserKey,e,300),e}}class U{constructor(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat",sccid:"snapchat"},t=Object.keys(e),a=["utm_source","utm_medium","utm_campaign","utm_term","utm_content",...t],r={},s={};window.location.search.replace("?","").split("&").map(e=>e.split("=")).filter(([e])=>a.includes(e.toLowerCase())).forEach(([e,t])=>{let a=t||"",s=false;try{a=decodeURIComponent(t),s=true;}catch(e){Salla.log("Failed to decode UTM param:",e);}r[e.toLowerCase()]=s?a.replace(/(?:[\0-\x1F!-,\.\/:-@\[-`\{-\xA9\xAB-\xB1\xB4\xB6-\xB8\xBB\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u036F\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482-\u0489\u0530\u0557\u0558\u055A-\u055F\u0589-\u05CF\u05EB-\u05EE\u05F3-\u061F\u064B-\u065F\u066A-\u066D\u0670\u06D4\u06D6-\u06E4\u06E7-\u06ED\u06FD\u06FE\u0700-\u070F\u0711\u0730-\u074C\u07A6-\u07B0\u07B2-\u07BF\u07EB-\u07F3\u07F6-\u07F9\u07FB-\u07FF\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u083F\u0859-\u085F\u086B-\u086F\u0888\u0890-\u089F\u08CA-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962-\u0965\u0970\u0981-\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA-\u09BC\u09BE-\u09CD\u09CF-\u09DB\u09DE\u09E2-\u09E5\u09F2\u09F3\u09FA\u09FB\u09FD-\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A-\u0A58\u0A5D\u0A5F-\u0A65\u0A70\u0A71\u0A75-\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA-\u0ABC\u0ABE-\u0ACF\u0AD1-\u0ADF\u0AE2-\u0AE5\u0AF0-\u0AF8\u0AFA-\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A-\u0B3C\u0B3E-\u0B5B\u0B5E\u0B62-\u0B65\u0B70\u0B78-\u0B82\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BCF\u0BD1-\u0BE5\u0BF3-\u0C04\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C3E-\u0C57\u0C5B\u0C5E\u0C5F\u0C62-\u0C65\u0C70-\u0C77\u0C7F\u0C81-\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA-\u0CBC\u0CBE-\u0CDB\u0CDF\u0CE2-\u0CE5\u0CF0\u0CF3-\u0D03\u0D0D\u0D11\u0D3B\u0D3C\u0D3E-\u0D4D\u0D4F-\u0D53\u0D57\u0D62-\u0D65\u0D79\u0D80-\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DE5\u0DF0-\u0E00\u0E31\u0E34-\u0E3F\u0E47-\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EB1\u0EB4-\u0EBC\u0EBE\u0EBF\u0EC5\u0EC7-\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F1F\u0F34-\u0F3F\u0F48\u0F6D-\u0F87\u0F8D-\u0FFF\u102B-\u103E\u104A-\u104F\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B-\u1368\u137D-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u1712-\u171E\u1732-\u173F\u1752-\u175F\u176D\u1771-\u177F\u17B4-\u17D6\u17D8-\u17DB\u17DD-\u17DF\u17EA-\u17EF\u17FA-\u180F\u181A-\u181F\u1879-\u187F\u1885\u1886\u18A9\u18AB-\u18AF\u18F6-\u18FF\u191F-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19FF\u1A17-\u1A1F\u1A55-\u1A7F\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1B04\u1B34-\u1B44\u1B4D-\u1B4F\u1B5A-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BFF\u1C24-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C8B-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1CFB-\u1CFF\u1DC0-\u1DFF\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u206F\u2072\u2073\u207A-\u207E\u208A-\u208F\u209D-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A-\u245F\u249C-\u24E9\u2500-\u2775\u2794-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF4-\u2CFC\u2CFE\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7F\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF-\u2E2E\u2E30-\u3004\u3008-\u3020\u302A-\u3030\u3036\u3037\u303D-\u3040\u3097-\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u3191\u3196-\u319F\u31C0-\u31EF\u3200-\u321F\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA66F-\uA67E\uA69E\uA69F\uA6F0-\uA716\uA720\uA721\uA789\uA78A\uA7DD-\uA7F0\uA802\uA806\uA80B\uA823-\uA82F\uA836-\uA83F\uA874-\uA881\uA8B4-\uA8CF\uA8DA-\uA8F1\uA8F8-\uA8FA\uA8FC\uA8FF\uA926-\uA92F\uA947-\uA95F\uA97D-\uA983\uA9B3-\uA9CE\uA9DA-\uA9DF\uA9E5\uA9FF\uAA29-\uAA3F\uAA43\uAA4C-\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAC3-\uAADA\uAADE\uAADF\uAAEB-\uAAF1\uAAF5-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABE3-\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB1E\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD06\uDD34-\uDD3F\uDD79-\uDD89\uDD8C-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEE0\uDEFC-\uDEFF\uDF24-\uDF2C\uDF4B-\uDF4F\uDF76-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDD6F\uDD7B\uDD8B\uDD93\uDD96\uDDA2\uDDB2\uDDBA\uDDBD-\uDDBF\uDDF4-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDF7F\uDF86\uDFB1\uDFBB-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56\uDC57\uDC77\uDC78\uDC9F-\uDCA6\uDCB0-\uDCDF\uDCF3\uDCF6-\uDCFA\uDD1C-\uDD1F\uDD3A-\uDD3F\uDD5A-\uDD7F\uDDB8-\uDDBB\uDDD0\uDDD1\uDE01-\uDE0F\uDE14\uDE18\uDE36-\uDE3F\uDE49-\uDE5F\uDE7F\uDEA0-\uDEBF\uDEC8\uDEE5-\uDEEA\uDEF0-\uDEFF\uDF36-\uDF3F\uDF56\uDF57\uDF73-\uDF77\uDF92-\uDFA8\uDFB0-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCF9\uDD24-\uDD2F\uDD3A-\uDD3F\uDD66-\uDD6E\uDD86-\uDE5F\uDE7F\uDEAA-\uDEAF\uDEB2-\uDEC1\uDEC8-\uDEFF\uDF28-\uDF2F\uDF46-\uDF50\uDF55-\uDF6F\uDF82-\uDFAF\uDFCC-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC00-\uDC02\uDC38-\uDC51\uDC70\uDC73\uDC74\uDC76-\uDC82\uDCB0-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDD02\uDD27-\uDD35\uDD40-\uDD43\uDD45\uDD46\uDD48-\uDD4F\uDD73-\uDD75\uDD77-\uDD82\uDDB3-\uDDC0\uDDC5-\uDDCF\uDDDB\uDDDD-\uDDE0\uDDF5-\uDDFF\uDE12\uDE2C-\uDE3E\uDE41-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEDF-\uDEEF\uDEFA-\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A-\uDF3C\uDF3E-\uDF4F\uDF51-\uDF5C\uDF62-\uDF7F\uDF8A\uDF8C\uDF8D\uDF8F\uDFB6\uDFB8-\uDFD0\uDFD2\uDFD4-\uDFFF]|\uD805[\uDC35-\uDC46\uDC4B-\uDC4F\uDC5A-\uDC5E\uDC62-\uDC7F\uDCB0-\uDCC3\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDAF-\uDDD7\uDDDC-\uDDFF\uDE30-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEAB-\uDEB7\uDEB9-\uDEBF\uDECA-\uDECF\uDEE4-\uDEFF\uDF1B-\uDF2F\uDF3C-\uDF3F\uDF47-\uDFFF]|\uD806[\uDC2C-\uDC9F\uDCF3-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD30-\uDD3E\uDD40\uDD42-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD1-\uDDE0\uDDE2\uDDE4-\uDDFF\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE4F\uDE51-\uDE5B\uDE8A-\uDE9C\uDE9E-\uDEAF\uDEF9-\uDFBF\uDFE1-\uDFEF\uDFFA-\uDFFF]|\uD807[\uDC09\uDC2F-\uDC3F\uDC41-\uDC4F\uDC6D-\uDC71\uDC90-\uDCFF\uDD07\uDD0A\uDD31-\uDD45\uDD47-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8A-\uDD97\uDD99-\uDD9F\uDDAA-\uDDAF\uDDDC-\uDDDF\uDDEA-\uDEDF\uDEF3-\uDF01\uDF03\uDF11\uDF34-\uDF4F\uDF5A-\uDFAF\uDFB1-\uDFBF\uDFD5-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD812-\uD817\uD819\uD824-\uD82A\uD82D\uD82E\uD830-\uD832\uD836\uD83D\uD83F\uD87C\uD87D\uD87F\uD88E-\uDBFF][\uDC00-\uDFFF]|\uD80B[\uDC00-\uDF8F\uDFF1-\uDFFF]|\uD80D[\uDC30-\uDC40\uDC47-\uDC5F]|\uD810[\uDFFB-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD818[\uDC00-\uDCFF\uDD1E-\uDD2F\uDD3A-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDE6F\uDEBF\uDECA-\uDECF\uDEEE-\uDEFF\uDF30-\uDF3F\uDF44-\uDF4F\uDF5A\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDD3F\uDD6D-\uDD6F\uDD7A-\uDE3F\uDE97-\uDE9F\uDEB9\uDEBA\uDED4-\uDEFF\uDF4B-\uDF4F\uDF51-\uDF92\uDFA0-\uDFDF\uDFE2\uDFE4-\uDFF1\uDFF7-\uDFFF]|\uD823[\uDCD6-\uDCFE\uDD1F-\uDD7F\uDDF3-\uDFFF]|\uD82B[\uDC00-\uDFEF\uDFF4\uDFFC\uDFFF]|\uD82C[\uDD23-\uDD31\uDD33-\uDD4F\uDD53\uDD54\uDD56-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDFFF]|\uD833[\uDC00-\uDCEF\uDCFA-\uDFFF]|\uD834[\uDC00-\uDEBF\uDED4-\uDEDF\uDEF4-\uDF5F\uDF79-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD837[\uDC00-\uDEFF\uDF1F-\uDF24\uDF2B-\uDFFF]|\uD838[\uDC00-\uDC2F\uDC6E-\uDCFF\uDD2D-\uDD36\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDE8F\uDEAE-\uDEBF\uDEEC-\uDEEF\uDEFA-\uDFFF]|\uD839[\uDC00-\uDCCF\uDCEC-\uDCEF\uDCFA-\uDDCF\uDDEE\uDDEF\uDDFB-\uDEBF\uDEDF\uDEE3\uDEE6\uDEEE\uDEEF\uDEF5-\uDEFD\uDF00-\uDFDF\uDFE7\uDFEC\uDFEF\uDFFF]|\uD83A[\uDCC5\uDCC6\uDCD0-\uDCFF\uDD44-\uDD4A\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDC70\uDCAC\uDCB0\uDCB5-\uDD00\uDD2E\uDD3E-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDCFF\uDD0D-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEE0-\uDEFF]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEAE\uDEAF]|\uD87A[\uDFE1-\uDFEF]|\uD87B[\uDE5E-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDF4F]|\uD88D[\uDC7A-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g," ").replace(/ +/g," ").trim():a;});const i=t.find(e=>r[e]);!r.utm_source&&i&&(r.utm_source=e[i],r.utm_campaign=r.utm_campaign||`Using the CLICKID ${i} provided by ${r.utm_source}`,r.utm_term=r.utm_term||`${i}: ${r[i]}`),r.utm_source&&(Object.entries(r).filter(([e])=>!t.includes(e)).forEach(([e,t])=>{s[`s-${e.replace("_","-")}`]=t;}),s["s-utm-referrer"]=document.referrer,Salla.storage.setWithTTL("s-utms",s,129600),this.logUTMVisitData(s));}async logUTMVisitData(e){const t=e["s-utm-source"],a=e["s-utm-medium"],r=e["s-utm-campaign"],s=Salla.config.get("store.id");e&&"affiliate"===t&&a&&r&&fetch(Salla.config.get("affiliate.utm_url"),{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","s-utm-source":t,"s-utm-medium":a,"s-utm-campaign":r,"s-store-id":s}}).then(e=>{if(!e.ok)return;const t=new URL(window.location.href),a=window.history.state;t.searchParams.delete("utm_source"),t.searchParams.delete("utm_medium"),t.searchParams.delete("utm_campaign"),window.history.replaceState(a,"",t);});}}class O{constructor(e){var t,a,r;if("ready"!==Salla.status){if(null==e||null==(t=e.store)||!t.id)return console.error("Trying to init Twilight without store.id!"),void console.log("you can initiate twilight using this line only: Salla.init({store:{id:1234}})");var s;if(Salla.config.merge(e),!["salla.sa","salla.group"].includes(location.hostname)||null!=(a=Salla.config.get("store.url"))&&a.includes(location.hostname)||!Salla.config.get("store.username")||Salla.config.set("store.url",window.location.origin+"/"+Salla.config.get("store.username")),(null==e?void 0:e.events)&&Salla.event.dispatchEvents(null==e?void 0:e.events),new R,new j(e),null!=e&&null!=(r=e.user)&&r.language_code)Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);Salla.storage.get("scope.id")!=Salla.config.get("store.scope.id")&&Salla.storage.set("scope",Salla.config.get("store.scope",Salla.config.get("scope"))),new L(e).getConfig().then(e=>{Salla.config.merge(e),this.setSallaReady(e),this.afterInit();}).catch(e=>console.error("failed to initite twilight😢",e));}else Salla.log("Trying to re-initiate Salla, while its status === 'ready'!");}afterInit(){Salla.url.is_page("product.single")&&Salla.config.isGuest()&&window.addEventListener("mini-checkout::before-init",e=>{e.preventDefault(),Salla.event.emit("login::open");});}setSallaReady(e){new U,Salla.event.emitAsync("twilight::before.ready",e),Salla.status="ready",Salla.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}));}}class N{constructor(e){const t=null==e?void 0:e.nextPage;this.listId=salla.config.get("page.slug"),Salla.config.get("page.id")&&(this.listId+=`_${salla.config.get("page.id")}`),this.sorts=null;try{if(t){const e=new URL(t).searchParams.get("sort");e&&(this.sorts=[{type:"sort",value:e}]);}e.source&&(this.listId=`${this.listId}_${e.source}`),e.sourceValue&&(this.listId=`${this.listId}_${Array.isArray(e.sourceValue)?e.sourceValue.join("_"):e.sourceValue}`);}catch(e){salla.logger.error(e);}this.products=null==e?void 0:e.data;}toSegment(){const e=(salla.config.get("page.title")||"").split("|").map(e=>e.trim()),t=e[0],a=e[1]||null;return {event:"Product List Viewed",properties:{list_id:this.listId,category:t,sub_category:a,sorts:this.sorts,products:this.products.map(e=>{var t,a,r,s,i,n;return {product_id:e.id,category:null==(t=e.category)?void 0:t.name,currency:null==(a=Salla.config.currency())?void 0:a.code,name:e.name,brand:null==(r=e.brand)?void 0:r.name,variant:null==(s=e.variant)?void 0:s.toString(),coupon:null==(i=e.coupon)?void 0:i.toString(),price:e.price,quantity:Number(e.quantity),sku:e.sku,position:0,url:e.url,image_url:null==(n=e.image)?void 0:n.url}})}}}static shouldSend(e){return !((null==e?void 0:e.nextPage)||"").includes("filters")&&!["index","customer.wishlist"].includes(salla.config.get("page.slug"))}}class M{constructor(){this.user=JSON.parse(localStorage.getItem("user"));}toSegment(){var e,t,a,r,s;return {event:"Signed In",properties:{first_name:null==(e=this.user)?void 0:e.first_name,last_name:null==(t=this.user)?void 0:t.last_name,type:null==(a=this.user)?void 0:a.type,mobile:null==(r=this.user)?void 0:r.mobile,email:null==(s=this.user)?void 0:s.email}}}static shouldSend(){return "user"===Salla.config.get("user.type")?!Salla.analytics.history.find(({eventName:e})=>"Signed In"===e):(Salla.profile.event.onInfoFetched(()=>Salla.event.emit("Signed In")),false)}}class ${constructor(e){this.details=null==e?void 0:e.data;}toSegment(){const e=["first_name","last_name","birthday","gender"].filter(e=>{var t,a;return $.user[e]!==(null==(t=this.details)?void 0:t[e])&&(void 0!==$.user[e]||void 0!==(null==(a=this.details)?void 0:a[e]))});return $.setUser(this.details),{event:"User Profile Updated",properties:{updated_fields:e}}}static registerEvent(){Salla.onReady(()=>{salla.url.is_page("customer.profile")&&$.setUser(Salla.config.get("user"));});}static setUser(e){$.user={first_name:null==e?void 0:e.first_name,last_name:null==e?void 0:e.last_name,gender:null==e?void 0:e.gender,birthday:null==e?void 0:e.birthday,avatar:null==e?void 0:e.avatar};}static shouldSend(){return "user"===Salla.config.get("user.type")}}$.user={};class H{static registerEvents(){Object.values(this.events).forEach(e=>{e.forEach(e=>{"function"==typeof e.registerEvent&&e.registerEvent();});});}static transform(e,t){try{const a=this.events[e]||[];for(const e of a){if(!e||"function"==typeof e.shouldSend&&!e.shouldSend(t))continue;const a=new e(t).toSegment();return {event:a.event,properties:a.properties}}return null}catch(e){return console.error("Failed to transform event:",e),null}}}H.events={"Order Completed":[class{constructor(e){this.details=e[0];}toSegment(){return {event:"Order Completed",properties:this.details}}}],"Product Added":[class{constructor(e){var t,a;this.item=e[0],this.source=(null==(t=Salla.cart)||null==(t=t.api)?void 0:t.addToCartSource)||null,null!=(a=Salla.cart)&&a.api&&(Salla.cart.api.addToCartSource=null);}toSegment(){var e,t,a,r,s;return {event:"Product Added",properties:{cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),cart_item_id:null==(t=this.item.cart_item_id)?void 0:t.toString(),product_id:null==(a=this.item.id)?void 0:a.toString(),category:this.item.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:this.item.name,brand:this.item.brand,variant:null==(s=this.item.variant)?void 0:s.toString(),price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url,source:this.source}}}static shouldSend(){return "customer.wishlist"!==salla.config.get("page.slug")}},class{constructor(e){this.item=e[0];}toSegment(){var e,t;return {event:"Wishlist Product Added to Cart",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),cart_id:null==(e=this.item.cart_id)?void 0:e.toString(),product_id:null==(t=this.item.id)?void 0:t.toString(),category:this.item.category,name:this.item.name,brand:this.item.brand,variant:this.item.variant,price:this.item.price,quantity:this.item.quantity,sku:this.item.sku,coupon:this.item.coupon,position:this.item.position,url:this.item.url,image_url:this.item.image_url}}}static shouldSend(){return "customer.wishlist"===salla.config.get("page.slug")}}],"Product Removed":[class{constructor(e){this.item=e[0];}toSegment(){var e,t,a,r,s,i,n,o,l,u,c,d,h,p;return {event:"Product Removed",properties:{cart_id:null==(e=this.item)||null==(e=e.cart_id)?void 0:e.toString(),product_id:null==(t=this.item)||null==(t=t.id)?void 0:t.toString(),category:null==(a=this.item)?void 0:a.category,currency:null==(r=Salla.config.currency())?void 0:r.code,name:null==(s=this.item)?void 0:s.name,brand:null==(i=this.item)?void 0:i.brand,variant:null==(n=this.item)?void 0:n.variant,price:null==(o=this.item)?void 0:o.price,quantity:null==(l=this.item)?void 0:l.quantity,sku:null==(u=this.item)?void 0:u.sku,coupon:null==(c=this.item)?void 0:c.coupon,position:null==(d=this.item)?void 0:d.position,url:null==(h=this.item)?void 0:h.url,image_url:null==(p=this.item)?void 0:p.image_url}}}}],"Product Viewed":[class{constructor(e){this.product=e[0];try{this.source=sessionStorage.getItem("s-viewed-source")||null,sessionStorage.removeItem("s-viewed-source");}catch(e){this.source=null;}}toSegment(){var e;return {event:"Product Viewed",properties:{product_id:null==(e=this.product.id)?void 0:e.toString(),category:this.product.category,name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:this.product.quantity,currency:this.product.currency,coupon:this.product.coupon,position:this.product.position,value:this.product.value,sku:this.product.sku,url:this.product.url,image_url:this.product.image_url,source:this.source}}}}],"Product Added to Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Added to Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,position:Number(this.product.position||0),url:this.product.url,image_url:(null==(t=this.product)?void 0:t.image)||null,category:this.product.category,currency:null==(a=Salla.config.currency())?void 0:a.code,brand:this.product.brand}}}}],"Product Removed from Wishlist":[class{constructor(e){this.product=e.data.product;}toSegment(){var e,t,a;return {event:"Product Removed from Wishlist",properties:{wishlist_id:salla.config.get("store.id")+"_"+salla.config.get("user.id"),wishlist_name:salla.config.get("store.name"),product_id:null==(e=this.product.id)?void 0:e.toString(),name:this.product.name,brand:this.product.brand,variant:this.product.variant,price:this.product.price,quantity:Math.max(1,Number(this.product.quantity)),sku:this.product.sku||null,coupon:this.product.coupon||null,position:Number(this.product.position||0),currency:null==(t=Salla.config.currency())?void 0:t.code,url:this.product.url,image_url:(null==(a=this.product)?void 0:a.image)||null,category:this.product.category,brand:this.product.brand}}}}],"Cart Viewed":[class{constructor(e){this.cart=e[0];}toSegment(){var e;return {event:"Cart Viewed",properties:{cart_id:null==(e=this.cart.cart_id)?void 0:e.toString(),products:this.cart.products.map(e=>{var t,a,r;return {product_id:null==(t=e.id)?void 0:t.toString(),cart_item_id:null==(a=e.cart_item_id)?void 0:a.toString(),name:e.name,price:e.price,category:e.category,sku:e.sku,position:e.position,url:e.url,image_url:e.image_url,brand:e.brand,currency:null==(r=Salla.config.currency())?void 0:r.code,variant:e.variant,coupon:e.coupon,quantity:e.quantity}})}}}}],"Products Searched":[class{constructor(e){this.query=e;}toSegment(){return {event:"Products Searched",properties:{query:this.query}}}}],"Product List Viewed":[N],"Product List Filtered":[class extends N{constructor(e){super(e);const t=(null==e?void 0:e.nextPage)||"";this.filters=this.extractFilters(t);}extractFilters(e){if(!e)return null;try{const t=new URL(e),a=[];return Array.from(t.searchParams.entries()).forEach(([e,t])=>{if(e.startsWith("filters[")){const r=e.match(/^filters\[(.*?)\]/),s=r?r[1]:e;a.push({type:s,value:t});}}),a.length>0?a:null}catch(e){return console.warn("Error extracting filters from URL:",e),null}}toSegment(){const e=super.toSegment();return {event:"Product List Filtered",properties:h$1({},null==e?void 0:e.properties,{filters:this.filters})}}static shouldSend(e){return ((null==e?void 0:e.nextPage)||"").includes("filters")}}],"Signed Up":[class extends M{toSegment(){const e=super.toSegment();return {event:"Signed Up",properties:null==e?void 0:e.properties}}static shouldSend(){return "user"===Salla.config.get("user.type")||(Salla.profile.event.onInfoFetched(()=>Salla.event.emit("Signed Up")),false)}}],"Signed In":[M],"Signed Out":[class{toSegment(){return {event:"Signed Out",properties:{}}}}],"Product Reviewed":[class{constructor(e){this.details=e;}toSegment(){return {event:"Product Reviewed",properties:this.details}}static registerEvent(){salla.event.rating.onProductsRated(function(e,t){const{products:a,order_id:r}=t;Object.values(a).forEach(e=>{var t;Salla.event.emit("Product Reviewed",{product_id:null==(t=e.product_id)?void 0:t.toString(),review_id:null==r?void 0:r.toString(),review_body:e.comment,rating:e.rating});});});}}],"Product Shared":[class{constructor(e){this.data=e;}toSegment(){var e;const t=(null==(e=Salla.analytics.history.find(({eventName:e})=>"Product Viewed"===e))?void 0:e.payload)||{};return t.share_via=this.data.share_via,{event:"Product Shared",properties:t}}static shouldSend(){return "product.single"===salla.config.get("page.slug")}}],"Promotion Viewed":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Viewed",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Promotion Clicked":[class{constructor(e){this.promotion=e[0];}toSegment(){var e;return {event:"Promotion Clicked",properties:{promotion_id:null==(e=this.promotion.id)?void 0:e.toString(),creative:this.promotion.creative,name:this.promotion.name,position:this.promotion.position}}}}],"Coupon Applied":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Applied",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Removed":[class{constructor(e){this.transaction=e;}getCartId(){var e,t;return "cart"===salla.config.get("page.slug")?null==(t=salla.config.get("page.id"))?void 0:t.toString():(null==(e=this.transaction)||null==(e=e.data)||null==(e=e.cart)||null==(e=e.id)?void 0:e.toString())||""}toSegment(){var e,t;return {event:"Coupon Removed",properties:{cart_id:this.getCartId(),coupon_name:(null==(e=this.transaction)?void 0:e.coupon)||"",discount:(null==(t=this.transaction)||null==(t=t.data)||null==(t=t.cart)?void 0:t.discount)||0,currency:salla.config.get("user.currency")||""}}}}],"Coupon Denied":[class{constructor(e){this.transaction=e;}getCartId(){var e;return "cart"===salla.config.get("page.slug")?null==(e=salla.config.get("page.id"))?void 0:e.toString():""}getCouponCode(){try{var e,t;const a=null==(e=this.transaction.response)||null==(e=e.config)?void 0:e.data;return a?null==(t=JSON.parse(a))?void 0:t.coupon:""}catch(e){return ""}}toSegment(){var e;return {event:"Coupon Denied",properties:{cart_id:this.getCartId(),coupon_name:this.getCouponCode(),reason:(null==(e=this.transaction.response)||null==(e=e.data)||null==(e=e.error)?void 0:e.message)||"Unknown error"}}}}],"User Profile Updated":[$],"Cart Updated":[class{constructor(e){this.cart=e;}toSegment(){var e,t,a,r;return {event:"Cart Updated",properties:{cart_id:null==(e=this.cart.id)?void 0:e.toString(),value:this.cart.total,revenue:this.cart.sub_total,tax:this.cart.tax_amount,discount:this.cart.total_discount,shipping:this.cart.real_shipping_cost,currency:null==(t=Salla.config.currency())?void 0:t.code,affiliation:null==(a=Salla.storage.getWithTTL("s-utms"))?void 0:a["s-utm-source"],products:null==(r=this.cart.items)?void 0:r.map(e=>{var t,a,r,s,i,n;return {product_id:null==(t=e.product_id)?void 0:t.toString(),name:e.product_name,price:e.product_price,category:null==(a=e.category)?void 0:a.toString(),sku:null==(r=e.product_sku)?void 0:r.toString(),position:e.position,url:e.url,image_url:e.product_image,brand:null==(s=e.brand)?void 0:s.toString(),currency:null==(i=Salla.config.currency())?void 0:i.code,variant:null==(n=e.variant)?void 0:n.toString(),coupon:this.cart.coupon,quantity:e.quantity}})}}}static shouldSend(e){return "cart"===salla.config.get("page.slug")&&!(null!=e&&e.fromLatestFetched)}}],"Market Selected":[class{constructor(e){this.scope=e.data;}toSegment(){return {event:"Market Selected",properties:h$1({},this.getScope(this.scope),{prev:this.getScope(Salla.config.get("store.scope"))})}}getScope(e){var t;return {id:null==(t=(e=e||{}).id)?void 0:t.toString(),country:this.getScopeAttribute(e,"countries"),currency:this.getScopeAttribute(e,"currencies"),locale:this.getScopeAttribute(e,"languages")}}getScopeAttribute(e,t){return e=e[t],Array.isArray(e)?e[0]:e}}],"Product Reordered":[class{constructor(e){this.details=e;}toSegment(){var e;return {event:"Product Reordered",properties:{product_id:null==(e=this.details)||null==(e=e.data)||null==(e=e.id)?void 0:e.toString()}}}static shouldSend(e){const t=null==e?void 0:e.data;return (null==t?void 0:t.id)&&!isNaN(null==t?void 0:t.id)&&"reorder"===(null==t?void 0:t.type)}}]};const V="s-session-id";N$3.versions.twilight="2.14.393",N$3.onInitiated=e=>salla.event.once("twilight::initiated",e),N$3.onReady=N$3.onReady||function(t){return new Promise(function(a){return "ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):N$3.onInitiated(e=>a(t?t(e):e))})},N$3.status="loading",N$3.notify=u,N$3.lang=new class extends a$3{constructor(e){e=e||{};const t=salla.cookie.get("s-lang");e.messages=e.messages||window.translations,e.locale=e.locale||(t||window.locale||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=false,Salla.event.on("twilight::before.ready",()=>this.loadStoreTranslations());}onLoaded(e){return new Promise(t=>{if(this.translationsLoaded)return t(e?e():null);Salla.event.once("languages::translations.loaded",()=>t(e?e():null));})}loadStoreTranslations(){if(this.hash=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight")),this.message||(salla.log("try to load translations from localstorage"),this.messages=salla.storage.get(`s_translations.${this.hash}`),this.messages&&(this.translationsLoaded=true)&&super.setMessages(this.messages)),this.messages)return salla.event.dispatch("languages::translations.loaded"),void salla.logger.info("The messages of transactions is already loaded");salla.url.get("")?this.loadScript(salla.url.get(`languages/assets/${this.hash}.js`)):this.loadScript("https://cdn.salla.network/js/translations.js",false);}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=true;}loadScript(e,t=true){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:window.translations}),this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",false);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}getWithDefault(e,t,a,r){let s=this.get(e,a,r);return s!==e?s:t}get(e,t,a){let r=e;(window.translations||this.translationsLoaded)&&(r="trans."+e);let s=super.get(r,t,a);return s!==r?s:super.get(r,t,"en").replace(r,e)}set(e,t){return salla.helpers.setNested(this.messages[`${this.getLocale()}.trans`],e,t),this}add(e,t){return Object.entries(t).forEach(t=>salla.helpers.setNested(this.messages[t[0]+".trans"],e,t[1])),this}addBulk(e){return Object.entries(e).forEach(([e,t])=>{this.add(e,t);}),this}},N$3.form=new class{async submit(e,t=null){var a;let r=t;if("SubmitEvent"===(null==t||null==(a=t.constructor)?void 0:a.name)||"submit"===(null==t?void 0:t.type)){var s,i;if(t.preventDefault(),"FORM"!==(null==(s=t.target)?void 0:s.tagName))return Salla.logger.warn("Failed find the target element for submit action. make sure you submit a form element"),new Promise(()=>{throw "Failed find the target element for submit action. make sure you submit a form element"});"SALLA-BUTTON"===(null==t||null==(i=t.submitter)||null==(i=i.parentElement)?void 0:i.tagName)&&t.submitter.parentElement.load(),r=t.target.getElementSallaData(),salla.log("Data from element",r);}if(/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm.test(e))return salla.api.request(e,r,"post").finally(()=>{var e;loaderSupported&&(null==t||null==(e=t.submitter)||e.parentElement.stop());});let n=e.split("."),o=n.splice(-1);return await salla.call(n.join("."))[o](r).finally(()=>{var e;return null==t||null==(e=t.submitter)||null==(e=e.parentElement)?void 0:e.stop()}).catch(e=>{throw salla.logger.warn(e),e})}onSubmit(e,t){return salla.form.submit(e,t),false}onChange(e,t){var a;return null!=t&&t.currentTarget?"FORM"!==(null==t||null==(a=t.currentTarget)?void 0:a.tagName)||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),true):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),false):(salla.logger.warn(`Trying to trigger '${e}' without event!`),false)}getPossibleValue(e,t,a=false){if(!e)return;if("object"!=typeof e)return e;let r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},N$3.infiniteScroll=new class extends c{constructor(e,t){super(e,t),this.options={path:".infinite-scroll-btn",history:"push",status:".infinite-scroll-status",append:".list-block"},this.fetchOptions={headers:{"S-INFINITE-SCROLL":true,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[];}initiate(e,a,r,s=false){s?((r=r||{}).fetchOptions=h$1({},this.fetchOptions,r.fetchOptions||{}),r.responseBody="json"):r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),n=r.path;if(!i||!n||"string"==typeof n&&!document.querySelector(n))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let o=new t$1(i,r);return o.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),o.on("request",Salla.infiniteScroll.event.request),o.on("load",Salla.infiniteScroll.event.load),o.on("append",Salla.infiniteScroll.event.append),o.on("error",Salla.infiniteScroll.event.error),o.on("last",Salla.infiniteScroll.event.last),o.on("history",Salla.infiniteScroll.event.history),this.instances.push(o),o}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}loadNextPage(e){("string"!=typeof e?e:document.querySelector(e)).loadNextPage();}destroy(e){("string"!=typeof e?e:document.querySelector(e)).destroy();}}(void 0,salla.event.infiniteScroll),N$3.api=new class extends B{constructor(){super(),this.auth=new D,this.cart=new m,this.loyalty=new f,this.order=new F,this.rating=new A,this.product=new v,this.profile=new y,this.comment=new C,this.currency=new S,this.document=new w,this.wishlist=new E,this.scope=new b,this.booking=new _,this.landing=new k,this.notifications=new x,this.component=new P,this.advertisement=new I,this.navigation=new q,this.metadata=new T;}beaconRequest(e,t={}){var a;if(null==(a=window.navigator)||!a.sendBeacon)return fetch(e,t);const r="string"==typeof(null==t?void 0:t.body)?null==t?void 0:t.body:JSON.stringify((null==t?void 0:t.body)||{}),s=new Blob([r],{type:"application/json"});return Salla.log(`Beacon payload size: ${s.size} bytes (~${(s.size/1024).toFixed(2)} KB)`),navigator.sendBeacon(e,s),Promise.resolve(new Response('{"status":"sent_via_beacon"}',{status:200,headers:{"Content-Type":"application/json"}}))}},N$3.sso=new class{constructor(){Salla.onReady(()=>this.init());}init(){var e;if(salla.config.get("store.features",[]).includes("sso-login")){if(window.location.hostname.includes("salla"))return salla.log("SSO is not supported yet for stores without custom domain.");salla.auth.event.onLoggedOut(()=>new Promise(e=>{const t=document.createElement("iframe");t.style.display="none",t.src=salla.url.get("sso/logout"),document.body.appendChild(t),t.onload=()=>{document.body.removeChild(t),e();};})),null==(e=document.querySelector("salla-login-modal"))||e.remove(),Salla.event.removeAllListeners("login::open"),Salla.event.prependListener("login::open",()=>this.redirect()),window.addEventListener("mini-checkout::before-init",e=>{Salla.config.isUser()||(e.preventDefault(),this.redirect());});}}redirect(){const e=window.location.pathname+window.location.search,t=`${window.location.origin}/sso/login?intended_to=${encodeURIComponent(e)}`;return console.log("Redirecting to:",t),window.location.href=t,true}},N$3.intend=new class{constructor(){Salla.onReady(()=>this.init());}init(){if(Salla.config.isUser())return;const e=new URLSearchParams(window.location.search);if(e.has("intended_to"))try{const t=new URL(e.get("intended_to"));if(t.hostname!==window.location.hostname)return;return this.handleAfterLoginEvent(t)}catch(e){return void console.warn("Invalid URL provided in intended_to parameter")}}handleAfterLoginEvent(e){let t="intend::user.logged.in";Salla.event.on(t,()=>window.location=e),Salla.api.auth.setAfterLoginEvent(t),Salla.api.auth.setCanRedirect(false),Salla.event.on("salla-login::ready",()=>Salla.event.emit("login::open",{withoutReload:true}));}},N$3.hooks=new class{constructor(){this._store=new Map,this._whitelist=new Map([["salla-add-product-button",new Set(["validate","componentDidLoad"])],["salla-product-options",new Set(["componentDidLoad"])],["salla-products-list",new Set(["componentDidLoad"])],["salla-products-slider",new Set(["componentDidLoad"])],["salla-hook",new Set(["componentDidLoad"])],["salla-scopes",new Set(["componentDidLoad"])]]),this._themeSlots=["head","head:start","head:end","body:start","body:end","product:index.items.start","product:index.items.end","product:single.description.start","product:single.description","product:single.description.end","product:single.form.start","product:single.form.end","blog:index.items.start","blog:index.items.end","blog:single.items.start","blog:single.items.end","brands:index.items.start","brands:index.items.end","brands:single.details.start","brands:single.details.end","brands:single.items.start","brands:single.items.end","cart:items.start","cart:items.end","cart:summary.start","cart:summary.end","cart:submit.start","cart:submit.end","customer:notifications.items.start","customer:notifications.items.end","customer:orders.index.items.start","customer:orders.index.items.end","customer:orders.single.details.start","customer:orders.single.details.end","customer:wishlist.items.start","customer:wishlist.items.end","customer:profile.form.start","customer:profile.form.fields.start","customer:profile.form.fields.end","customer:profile.form.submit.start","customer:profile.form.submit.end","customer:profile.form.end","thank-you:start","thank-you:items.start","thank-you:items.end","thank-you:end"];const e=Salla.config.get("page.slug");e&&(this._themeSlots.push(e+":start"),this._themeSlots.push(e+":end")),Salla.onReady(()=>{const e=Salla.config.get("page.slug");e&&(this._themeSlots.includes(e+":start")||this._themeSlots.push(e+":start"),this._themeSlots.includes(e+":end")||this._themeSlots.push(e+":end"));}),this._componentHistory=new Map;}renderAutoComponents(e){Array.isArray(e)&&0!==e.length&&e.forEach(({hook:e,tag:t,canRender:a})=>{a&&!a()||this.mount(e,document.createElement(t));});}registerHook(e,t,a,r={}){if(!this._isAllowed(e,t))return console.warn(`[Hooks] Hook "${e}:${t}" is not allowed`),()=>{};const s=0|r.priority,i=!!r.once,n=this._ensureTag(e),o=n.get(t)||[];return o.push({cb:a,p:s,once:i}),o.sort((e,t)=>t.p-e.p),n.set(t,o),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),()=>this.removeHook(e,t,a)}registerHookOnce(e,t,a,r={}){return this.registerHook(e,t,a,h$1({},r,{once:true}))}async call(e,t,a){const r=this._store.get(e);if(!r)return;const s=r.get(t);if(s&&0!==s.length)for(const r of [...s]){try{await r.cb(a);}catch(a){console.warn(`[Hooks] "${e}:${t}" callback failed:`,a);}r.once&&this.removeHook(e,t,r.cb);}}removeHook(e,t,a){const r=this._store.get(e);if(!r)return false;if(!r.has(t))return false;if(!a)return r.delete(t),0===r.size&&this._store.delete(e),true;const s=r.get(t),i=s.findIndex(e=>e.cb===a);return i>-1&&(s.splice(i,1),0===s.length&&r.delete(t),0===r.size&&this._store.delete(e),true)}clear(e){e?this._store.delete(e):this._store.clear();}get(e,t){var a;const r=this._store.get(e);return r&&(null==(a=r.get(t))?void 0:a.map(e=>e.cb))||[]}_ensureTag(e){let t=this._store.get(e);return t||(t=new Map,this._store.set(e,t)),t}_isAllowed(e,t){const a=this._whitelist.get(e);return a?!!a.has(t)||(console.warn(`[Hooks] Hook "${t}" is not allowed for tag "${e}"`),false):(console.warn(`[Hooks] Tag "${e}" is not in the whitelist`),false)}registerComponent(e,t){this._componentHistory.has(e)||this._componentHistory.set(e,new Set);const a=this._componentHistory.get(e);if(!a.has(t))return a.add(t),this.call(e,"componentDidLoad",t)}async _callForLoadedComponents(e,t){const a=this._componentHistory.get(e);if(a&&0!==a.size)for(const r of a)try{await t(r);}catch(t){console.warn(`[Hooks] "${e.replace(/[^a-zA-Z0-9-_]/g,"")}:componentDidLoad" callback failed:`,t);}}mount(e,t){return this._themeSlots.includes(e)?new Promise(a=>{this.registerHook("salla-hook","componentDidLoad",r=>{r.name===e&&(r.mount(t),a(t));});}):(console.warn(`[Hooks] Hook "${e}" is not allowed`),Promise.reject(t))}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing","metadata"].forEach(t=>N$3[t]=new c(N$3.api[t],N$3.event[t])),N$3.call=t=>{let a=N$3,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},N$3.analytics=new class{constructor(){this.history=[],this.customTrackers=[],this.context={},this._anonymousId=null,this._sessionId=null,this._jitsuConfig=null,this.mappedEvents={"wishlist::added":"Product Added to Wishlist","wishlist::removed":"Product Removed from Wishlist","salla-products-list::products.fetched":["Product List Viewed","Product List Filtered"],"auth::registered":"Signed Up","auth::logged.in":"Signed In","auth::logged.out":"Signed Out","share-element":"Product Shared","promotion::viewed":"Promotion Viewed","promotion::clicked":"Promotion Clicked","salla::offer.promotion.viewed":"Promotion Viewed","salla::offer.promotion.clicked":"Promotion Clicked","cart::coupon.added":"Coupon Applied","cart::coupon.deleted":"Coupon Removed","cart::coupon.addition.failed":"Coupon Denied","profile::updated":"User Profile Updated","cart::updated":"Cart Updated","scope::changed":"Market Selected","order::order.created":"Product Reordered"},Salla.event.onAny((e,t)=>{try{if(Object.keys(this.mappedEvents).includes(e)){const a=this.mappedEvents[e];return void(Array.isArray(a)?a:[a]).forEach(e=>Salla.event.emit(e,t))}if(!Salla.config.get("jitsu.events",[]).includes(e))return;const a=H.transform(e,t);a&&this.track(a.event,a.properties);}catch(e){Salla.log("Error in analytics event handling:",e);}}),Salla.event.on("salla-cookies-bar::accepted",()=>this.setConsent("accepted")),Salla.event.on("salla-cookies-bar::rejected",()=>this.setConsent("rejected")),Salla.event.on("auth::logged.out",()=>this.clearSessionId()),Salla.event.on("twilight::before.ready",e=>{var t,a,r,s,n,o,l;this.debugAnalytics=jitsuAnalytics({host:"https://st.salla.dev",writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p"});const{host:u,key:c}=(null==e?void 0:e.jitsu)||{};if(this.jitsuAnalytics=null,!u||!c)return void salla.log("Jitsu configuration is missing. Analytics will not be tracked.");H.registerEvents(),this._jitsuConfig=h$1({host:this.getAnalyticsHost(e),writeKey:c,cookieCapture:Object.fromEntries(Salla.cookie.getCookieByPrefix("sa_").map(e=>[e,e]))},Salla.helpers.isIframe()&&{fetch:(e,t)=>this.customFetch(e,t)});const d=this.getConsentPolicies();var p;(this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,d)),e.jitsu.anonymous_id&&this.jitsuAnalytics.setAnonymousId(e.jitsu.anonymous_id),this._anonymousId=(null==(t=this.jitsuAnalytics)||null==(t=t.user())?void 0:t.anonymousId)||null,e.jitsu.session_id&&this.setContext("session_id",e.jitsu.session_id),this._sessionId=null==(a=this.jitsuAnalytics)?void 0:a.getContextProperty("session_id"),this.setContext("store_id",null==(r=e.store)?void 0:r.id),this.setContext("version",null==(s=e.jitsu)?void 0:s.version),this.setContext("library",{twilight:Salla.versions}),null!=(n=e.jitsu)&&null!=(n=n.context)&&n.extra&&this.setExtraContext(e.jitsu.context.extra),null!=(o=e.store)&&null!=(o=o.scope)&&o.id)&&this.setContext("scope",null==(p=e.store)?void 0:p.scope);"user"===(null==e||null==(l=e.user)?void 0:l.type)&&this.setContext("traits",this.getFormattedUser(e.user)),this.registerTracker({name:"DefaultSallaTracker",track:(e,t)=>this.jitsuAnalytics.track(e,t),page:e=>this.jitsuAnalytics.page(e)});}),Salla.onReady(()=>{var e;this.initSessionId();const t={name:Salla.config.get("page.slug",""),id:null==(e=Salla.config.get("page.id",""))?void 0:e.toString()};this.setContext("page",t),Salla.config.set("jitsu.anonymous_id",this._anonymousId),Salla.config.set("jitsu.session_id",this._sessionId),this.page(t);});}setExtraContext(e){var t;null!=e&&null!=(t=e.headers)&&t["s-app-os"]&&(this.setContext("app",{version:e.headers["s-app-os-version"],app_release_tag:e.headers["s-app-version"],platform:e.headers["s-app-os"].toLowerCase()}),delete e.headers["s-app-os"],delete e.headers["s-app-os-version"],delete e.headers["s-app-version"],delete e.headers["s-source"]),this.setContext("system",e);}getAnalyticsHost(e){var t;const a="https://salla.cloud/_app/e";var r,s;if(Salla.helpers.isIframe())return null!=(r=null==(s=e.jitsu)?void 0:s.host)?r:a;if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;const i=e.store.url;try{let e="";const t=i;if(/https:\/\/demostore\.salla\.sa/.test(t)){const e=t.match(/demostore\.salla\.sa\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/);if(e&&e[2]){const a=e[2];return `${new URL(t).origin}/${a}/_app/e`}return a}const r=/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/,s=t.match(r);if(s){const r=s[3];if(!r||0===r.trim().length||"ar"===r||"en"===r)return Salla.log("Error: invalid or empty store name in salla.sa URL"),a;e=`${new URL(t).origin}/${r}`;}else {e=new URL(t).origin;}return `${e}/_app/e`}catch(e){return Salla.log("Error getting store url, forwarding to salla.cloud:",e),a}}setContext(e,t){var a,r;null==(a=this.jitsuAnalytics)||a.setContextProperty(e,t),null==(r=this.debugAnalytics)||r.setContextProperty(e,t),this.context[e]=t;}setAppContext(e,t){if(!this.jitsuAnalytics)return void Salla.log("setAppContext: Analytics not initialized yet");if(!e||"string"!=typeof e)return void Salla.log("setAppContext: appId must be a non-empty string");if(!t||"object"!=typeof t)return void Salla.log("setAppContext: payload must be an object");const a=this.context.apps_context||{};a[e]=h$1({},a[e],t),this.setContext("apps_context",a);}withAppScope(e,t){if(!e||"string"!=typeof e)return void Salla.log("withAppScope: appId must be a non-empty string");if("function"!=typeof t)return void Salla.log("withAppScope: callback must be a function");const a=this.context.apps_context?h$1({},this.context.apps_context):void 0,r=this,s={appId:e,setContext(t,a){r.setAppContext(e,{[t]:a});}};try{t(s);}finally{setTimeout(()=>{a?r.setContext("apps_context",a):r.setContext("apps_context",void 0);},0);}}customFetch(e,t){return fetch(e,h$1({},t,{keepalive:true}))}track(e,t={}){t=this.finalPayload(t),this.history.push({action:"track",eventName:e,payload:t}),this.pushEventToCustomTrackers("track",e,t);}log(e,t={}){var a;return null==(a=this.debugAnalytics)?void 0:a.track(e,t).catch(e=>(Salla.log("Error tracking event:",e),Promise.reject(e)))}page(e={}){var t,a;(e=this.finalPayload(e)).id=null==(t=e.id||Salla.config.get("page.id",""))?void 0:t.toString(),e.name=e.name||Salla.config.get("page.slug"),e.keywords=e.keywords||(null==(a=document.querySelector("meta[name=keywords]"))?void 0:a.content),e.referrer=e.referrer||document.referrer,this.history.push({action:"page",payload:e}),this.pushEventToCustomTrackers("page",e);}finalPayload(e={}){return this.attachRealtimeContext(),h$1({},{},e)}attachRealtimeContext(){try{const e=["user.id","cart.id","cart.user_id","cart.count","cart.summary.count","scope.id","branch-choosed-before"].reduce((e,t)=>{const a=Salla.storage.get(t);return a&&(e[t.replace(".","_")]=a),e},{});Object.keys(e).length>0&&this.setContext("localStorage",e);}catch(e){Salla.analytics.log("attachRealtimeContext",{error:e.message}),Salla.log("Error attaching realtime context:",e);}const e=Salla.storage.getWithTTL("s-utms");if(!e)return;const{"s-utm-campaign":t,"s-utm-source":a,"s-utm-medium":r,"s-utm-term":s,"s-utm-content":i,"s-utm-referrer":n}=e;this.setContext("campaign",{name:t,source:a,medium:r,term:s,content:i,referrer:n});}registerTracker(e){"object"==typeof e?"string"==typeof e.name&&e.name?"function"==typeof e.track?"function"==typeof e.page?this.customTrackers.find(t=>t.name===e.name)?Salla.log("tracker with the same name already exists!"):(this.customTrackers.push(e),this.history.forEach(t=>"track"===t.action?e.track(t.eventName,t.payload):"page"===t.action?e.page(t.payload):void 0)):Salla.log("tracker.page most be a function!"):Salla.log("tracker.track most be a function!"):Salla.log("tracker.name most be a string!"):Salla.log('tracker most be an object {name:"tracker name", track: callback, page: callback}!');}pushEventToCustomTrackers(e,t,a={}){const r="page"===e?[t]:[t,a];return Promise.allSettled(this.customTrackers.map(t=>this.pushEventToCustomTracker(t[e],r))).then(t=>t.filter(e=>"rejected"===e.status).map(t=>Salla.log("Error on customTracker to send "+e,t)))}pushEventToCustomTracker(e,t){try{const a=e(...t);return Promise.resolve(a).catch(e=>Promise.reject(e))}catch(e){return Promise.reject(e)}}getConsentState(){return Salla.storage.get("cookies-consent","unknown")}getConsentPolicies(e=null){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return {};const a="accepted"===(e=e||this.getConsentState());return {privacy:{dontSend:false,disableUserIds:!a,ipPolicy:a?"keep":"remove"}}}setConsent(e){var t;if(null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies"))return;if(!["accepted","rejected"].includes(e))return;const a=this.getConsentState();if(this._jitsuConfig&&this.jitsuAnalytics&&a!==e)try{var r;const t=this.getConsentPolicies(e);this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,t)),this._anonymousId=(null==(r=this.jitsuAnalytics)||null==(r=r.user())?void 0:r.anonymousId)||null,Salla.config.set("jitsu.anonymous_id",this._anonymousId),Object.entries(this.context).forEach(([e,t])=>{this.jitsuAnalytics.setContextProperty(e,t);});}catch(e){Salla.log("Error re-initializing Jitsu on consent change:",e);}}getFormattedUser(e){return e.phone=e.mobile,e.country=e.country_code,e.language=e.language_code,e.currency=e.currency_code,e}generateSessionId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)})}initSessionId(){this._sessionId=this._sessionId||Salla.storage.getWithTTL(V)||this.generateSessionId(),Salla.storage.setWithTTL(V,this._sessionId,30),this.setContext("session_id",this._sessionId);}clearSessionId(){this._sessionId=null,Salla.storage.setWithTTL(V,null,0),this.setContext("session_id",null);}getAnonymousId(){try{if(this._anonymousId)return this._anonymousId;if(this.jitsuAnalytics){var e;const t=null==(e=this.jitsuAnalytics.user())?void 0:e.anonymousId;if(t)return this._anonymousId=t,t}return null}catch(e){return Salla.log("Error getting anonymous ID from Jitsu:",e),null}}},N$3.init=e=>new O(e),new class{constructor(e={}){this.config=h$1({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=false,Salla.onReady(()=>this.init());}normalizeUrl(e){try{return new URL(e,location.href)}catch(e){return null}}shouldIgnoreUrl(e){if(!e)return false;const t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some(e=>a.startsWith(e)))return true;try{const e=new URL(t,location.href).hostname.toLowerCase();return ["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some(t=>e===t||e.endsWith("."+t))}catch(e){return false}}isWhitelisted(e){if(!e)return false;const t=e.hostname.toLowerCase();for(const e of this.config.WHITELIST){const a=String(e||"").toLowerCase().trim();if(a&&(t===a||t.endsWith("."+a)))return true}return false}emit(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e);}catch(e){}}catch(e){}}logRedirect(e,t,a){if(this.shouldIgnoreUrl(t))return;const r=this.normalizeUrl(t),s=this.normalizeUrl(location.href),i=this.isWhitelisted(r),n={redirect_source:e,redirect_from:s?s.href:String(location.href),redirect_to:r?r.href:String(t),redirect_host:r?r.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(n);}hookHistoryAPIs(){["pushState","replaceState"].forEach(e=>{try{const t=history[e];"function"==typeof t&&(this.originalMethods[`history.${e}`]=t,history[e]=(...a)=>{try{var r;this.logRedirect(e,null!=(r=a[2])?r:location.href);}catch(e){}return t.apply(history,a)});}catch(e){}}),window.addEventListener("popstate",()=>{this.logRedirect("popstate",location.href);}),window.addEventListener("hashchange",()=>{this.logRedirect("hashchange",location.href);});}hookLocationMethods(){try{const e=location.assign.bind(location);this.originalMethods["location.assign"]=e,location.assign=t=>(this.logRedirect("location.assign",t,{stack:(new Error).stack}),e(t));}catch(e){}try{const e=location.replace.bind(location);this.originalMethods["location.replace"]=e,location.replace=t=>(this.logRedirect("location.replace",t,{stack:(new Error).stack}),e(t));}catch(e){}}hookWindowOpen(){try{const e=window.open;this.originalMethods["window.open"]=e,window.open=(t,...a)=>(t&&this.logRedirect("window.open",t,{stack:(new Error).stack}),e.apply(window,[t,...a]));}catch(e){}}setupEventListeners(){this.handleLinkClick=e=>{const t=e.target&&e.target.closest?e.target.closest("a[href]"):null;if(!t)return;const a=t.getAttribute("href");if(!a||a.startsWith("#"))return;if(this.shouldIgnoreUrl(a))return;const r=t.getAttribute("target")||"_self";setTimeout(()=>{this.logRedirect("link-click",a,{target:r});},0);},document.addEventListener("click",this.handleLinkClick,true),this.handleFormSubmit=e=>{const t=e.target,a=t&&t.getAttribute&&t.getAttribute("action")||location.href,r=(t&&t.method?String(t.method):"GET").toUpperCase();this.logRedirect("form-submit",a,{method:r});},document.addEventListener("submit",this.handleFormSubmit,true);}setupPerformanceObserver(){try{this.performanceObserver=new PerformanceObserver(e=>{for(const t of e.getEntries())"navigation"===t.entryType&&this.logRedirect("performance-navigation",location.href,{type:t.type,redirectCount:t.redirectCount});}),this.performanceObserver.observe({type:"navigation",buffered:true});}catch(e){}}init(){if(this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug")))return;if(this.isInitialized)return;const e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=true;}destroy(){this.isInitialized&&(Object.keys(this.originalMethods).forEach(e=>{const[t,a]=e.split(".");"history"===t&&this.originalMethods[e]?history[a]=this.originalMethods[e]:"location"===t&&this.originalMethods[e]?location[a]=this.originalMethods[e]:"window"===t&&"open"===a&&this.originalMethods[e]&&(window.open=this.originalMethods[e]);}),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,true),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,true),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=false);}},salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",e=>{let t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t);}),N$3.success=N$3.notify.success,N$3.error=N$3.notify.error,window.dispatchEvent(new CustomEvent("salla::created"));
12704
12704
 
12705
12705
  var lazyload_min$1 = {exports: {}};
12706
12706
 
@@ -12720,10 +12720,45 @@ function requireLazyload_min () {
12720
12720
  var lazyload_minExports = requireLazyload_min();
12721
12721
  var LazyLoad = /*@__PURE__*/getDefaultExportFromCjs(lazyload_minExports);
12722
12722
 
12723
+ function appGlobalScript () {
12724
+ // Only initialize it one time for the entire application
12725
+ if (!document.lazyLoadInstance) {
12726
+ document.lazyLoadInstance = new LazyLoad({
12727
+ use_native: true, //native not support lazyLoad backgrounds
12728
+ // restore_on_error: true,
12729
+ // Your custom settings go here
12730
+ // callback_finish: () => document.lazyLoadBackgrounds.update(document.querySelectorAll('.lazy[data-bg]:not(.loaded)'))
12731
+ });
12732
+ document.lazyLoadBackgrounds = new LazyLoad({
12733
+ elements_selector: '.lazy[data-bg]:not(.loaded)',
12734
+ });
12735
+ //native way doesn't load backgrounds
12736
+ // document.lazyLoadBackgrounds = new LazyLoad();
12737
+ }
12738
+ //make sure that lazyLoad will be fired after loading the page too.
12739
+ if (document.readyState !== 'complete') {
12740
+ document.addEventListener("DOMContentLoaded", () => document.lazyLoadInstance.update());
12741
+ document.addEventListener("DOMContentLoaded", () => document.lazyLoadBackgrounds.update());
12742
+ }
12743
+ // fire it after each load more request;
12744
+ // @ts-ignore
12745
+ salla.infiniteScroll.event.onAppend(() => {
12746
+ document.lazyLoadInstance.update();
12747
+ document.lazyLoadBackgrounds.update();
12748
+ });
12749
+ }
12750
+
12751
+ const globalScripts = appGlobalScript;
12752
+ const globalStyles = "";
12753
+
12723
12754
  /*
12724
- Stencil Client Platform v4.43.3 | MIT Licensed | https://stenciljs.com
12755
+ Stencil Client Platform v4.35.1 | MIT Licensed | https://stenciljs.com
12725
12756
  */
12726
-
12757
+ var __defProp = Object.defineProperty;
12758
+ var __export = (target, all) => {
12759
+ for (var name in all)
12760
+ __defProp(target, name, { get: all[name], enumerable: true });
12761
+ };
12727
12762
 
12728
12763
  // src/utils/constants.ts
12729
12764
  var SVG_NS = "http://www.w3.org/2000/svg";
@@ -12753,47 +12788,6 @@ var TYPE_CONSTANT = "type";
12753
12788
  var VALUE_CONSTANT = "value";
12754
12789
  var SERIALIZED_PREFIX = "serialized:";
12755
12790
 
12756
- // src/utils/get-prop-descriptor.ts
12757
- function getPropertyDescriptor(obj, memberName, getOnly) {
12758
- const stopAt = typeof HTMLElement !== "undefined" ? HTMLElement.prototype : null;
12759
- while (obj && obj !== stopAt) {
12760
- const desc = Object.getOwnPropertyDescriptor(obj, memberName);
12761
- if (desc && (!getOnly || desc.get)) return desc;
12762
- obj = Object.getPrototypeOf(obj);
12763
- }
12764
- return void 0;
12765
- }
12766
-
12767
- // src/utils/es2022-rewire-class-members.ts
12768
- var reWireGetterSetter = (instance, hostRef) => {
12769
- var _a;
12770
- const cmpMeta = hostRef.$cmpMeta$;
12771
- const members = Object.entries((_a = cmpMeta.$members$) != null ? _a : {});
12772
- members.map(([memberName, [memberFlags]]) => {
12773
- if ((memberFlags & 31 /* Prop */ || memberFlags & 32 /* State */)) {
12774
- const ogValue = instance[memberName];
12775
- const ogDescriptor = getPropertyDescriptor(Object.getPrototypeOf(instance), memberName, true) || Object.getOwnPropertyDescriptor(instance, memberName);
12776
- if (ogDescriptor) {
12777
- Object.defineProperty(instance, memberName, {
12778
- get() {
12779
- return ogDescriptor.get.call(this);
12780
- },
12781
- set(newValue) {
12782
- ogDescriptor.set.call(this, newValue);
12783
- },
12784
- configurable: true,
12785
- enumerable: true
12786
- });
12787
- }
12788
- if (hostRef.$instanceValues$.has(memberName)) {
12789
- instance[memberName] = hostRef.$instanceValues$.get(memberName);
12790
- } else if (ogValue !== void 0) {
12791
- instance[memberName] = ogValue;
12792
- }
12793
- }
12794
- });
12795
- };
12796
-
12797
12791
  // src/client/client-host-ref.ts
12798
12792
  var getHostRef = (ref) => {
12799
12793
  if (ref.__stencil__getHostRef) {
@@ -12802,20 +12796,15 @@ var getHostRef = (ref) => {
12802
12796
  return void 0;
12803
12797
  };
12804
12798
  var registerInstance = (lazyInstance, hostRef) => {
12805
- if (!hostRef) return;
12806
12799
  lazyInstance.__stencil__getHostRef = () => hostRef;
12807
12800
  hostRef.$lazyInstance$ = lazyInstance;
12808
- if (hostRef.$cmpMeta$.$flags$ & 512 /* hasModernPropertyDecls */ && (BUILD.state)) {
12809
- reWireGetterSetter(lazyInstance, hostRef);
12810
- }
12811
12801
  };
12812
12802
  var registerHost = (hostElement, cmpMeta) => {
12813
12803
  const hostRef = {
12814
12804
  $flags$: 0,
12815
12805
  $hostElement$: hostElement,
12816
12806
  $cmpMeta$: cmpMeta,
12817
- $instanceValues$: /* @__PURE__ */ new Map(),
12818
- $serializerValues$: /* @__PURE__ */ new Map()
12807
+ $instanceValues$: /* @__PURE__ */ new Map()
12819
12808
  };
12820
12809
  {
12821
12810
  hostRef.$onInstancePromise$ = new Promise((r) => hostRef.$onInstanceResolve$ = r);
@@ -12825,9 +12814,6 @@ var registerHost = (hostElement, cmpMeta) => {
12825
12814
  hostElement["s-p"] = [];
12826
12815
  hostElement["s-rc"] = [];
12827
12816
  }
12828
- {
12829
- hostRef.$fetchedCbList$ = [];
12830
- }
12831
12817
  const ref = hostRef;
12832
12818
  hostElement.__stencil__getHostRef = () => ref;
12833
12819
  return ref;
@@ -13221,16 +13207,12 @@ var supportsListenerOptions = /* @__PURE__ */ (() => {
13221
13207
  var promiseResolve = (v) => Promise.resolve(v);
13222
13208
  var supportsConstructableStylesheets = /* @__PURE__ */ (() => {
13223
13209
  try {
13224
- if (!win.document.adoptedStyleSheets) {
13225
- return false;
13226
- }
13227
13210
  new CSSStyleSheet();
13228
13211
  return typeof new CSSStyleSheet().replaceSync === "function";
13229
13212
  } catch (e) {
13230
13213
  }
13231
13214
  return false;
13232
13215
  })() ;
13233
- var supportsMutableAdoptedStyleSheets = supportsConstructableStylesheets ? /* @__PURE__ */ (() => !!win.document && Object.getOwnPropertyDescriptor(win.document.adoptedStyleSheets, "length").writable)() : false;
13234
13216
  var queuePending = false;
13235
13217
  var queueDomReads = [];
13236
13218
  var queueDomWrites = [];
@@ -13266,26 +13248,180 @@ var flush = () => {
13266
13248
  };
13267
13249
  var nextTick = (cb) => promiseResolve().then(cb);
13268
13250
  var writeTask = /* @__PURE__ */ queueTask(queueDomWrites, true);
13251
+ var isComplexType = (o) => {
13252
+ o = typeof o;
13253
+ return o === "object" || o === "function";
13254
+ };
13269
13255
 
13270
- // src/utils/style.ts
13271
- function createStyleSheetIfNeededAndSupported(styles2) {
13272
- return void 0;
13256
+ // src/utils/query-nonce-meta-tag-content.ts
13257
+ function queryNonceMetaTagContent(doc) {
13258
+ var _a, _b, _c;
13259
+ return (_c = (_b = (_a = doc.head) == null ? void 0 : _a.querySelector('meta[name="csp-nonce"]')) == null ? void 0 : _b.getAttribute("content")) != null ? _c : void 0;
13273
13260
  }
13274
13261
 
13275
- // src/utils/shadow-root.ts
13276
- var globalStyleSheet;
13277
- function createShadowRoot(cmpMeta) {
13278
- var _a;
13279
- const opts = { mode: "open" };
13280
- const shadowRoot = this.attachShadow(opts);
13281
- if (globalStyleSheet === void 0) globalStyleSheet = (_a = createStyleSheetIfNeededAndSupported()) != null ? _a : null;
13282
- if (globalStyleSheet) {
13283
- if (supportsMutableAdoptedStyleSheets) {
13284
- shadowRoot.adoptedStyleSheets.push(globalStyleSheet);
13262
+ // src/utils/regular-expression.ts
13263
+ var escapeRegExpSpecialCharacters = (text) => {
13264
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13265
+ };
13266
+
13267
+ // src/utils/remote-value.ts
13268
+ var RemoteValue = class _RemoteValue {
13269
+ /**
13270
+ * Deserializes a LocalValue serialized object back to its original JavaScript representation
13271
+ *
13272
+ * @param serialized The serialized LocalValue object
13273
+ * @returns The original JavaScript value/object
13274
+ */
13275
+ static fromLocalValue(serialized) {
13276
+ const type = serialized[TYPE_CONSTANT];
13277
+ const value = VALUE_CONSTANT in serialized ? serialized[VALUE_CONSTANT] : void 0;
13278
+ switch (type) {
13279
+ case "string" /* String */:
13280
+ return value;
13281
+ case "boolean" /* Boolean */:
13282
+ return value;
13283
+ case "bigint" /* BigInt */:
13284
+ return BigInt(value);
13285
+ case "undefined" /* Undefined */:
13286
+ return void 0;
13287
+ case "null" /* Null */:
13288
+ return null;
13289
+ case "number" /* Number */:
13290
+ if (value === "NaN") return NaN;
13291
+ if (value === "-0") return -0;
13292
+ if (value === "Infinity") return Infinity;
13293
+ if (value === "-Infinity") return -Infinity;
13294
+ return value;
13295
+ case "array" /* Array */:
13296
+ return value.map((item) => _RemoteValue.fromLocalValue(item));
13297
+ case "date" /* Date */:
13298
+ return new Date(value);
13299
+ case "map" /* Map */:
13300
+ const map2 = /* @__PURE__ */ new Map();
13301
+ for (const [key, val] of value) {
13302
+ const deserializedKey = typeof key === "object" && key !== null ? _RemoteValue.fromLocalValue(key) : key;
13303
+ const deserializedValue = _RemoteValue.fromLocalValue(val);
13304
+ map2.set(deserializedKey, deserializedValue);
13305
+ }
13306
+ return map2;
13307
+ case "object" /* Object */:
13308
+ const obj = {};
13309
+ for (const [key, val] of value) {
13310
+ obj[key] = _RemoteValue.fromLocalValue(val);
13311
+ }
13312
+ return obj;
13313
+ case "regexp" /* RegularExpression */:
13314
+ const { pattern, flags } = value;
13315
+ return new RegExp(pattern, flags);
13316
+ case "set" /* Set */:
13317
+ const set = /* @__PURE__ */ new Set();
13318
+ for (const item of value) {
13319
+ set.add(_RemoteValue.fromLocalValue(item));
13320
+ }
13321
+ return set;
13322
+ case "symbol" /* Symbol */:
13323
+ return Symbol(value);
13324
+ default:
13325
+ throw new Error(`Unsupported type: ${type}`);
13326
+ }
13327
+ }
13328
+ /**
13329
+ * Utility method to deserialize multiple LocalValues at once
13330
+ *
13331
+ * @param serializedValues Array of serialized LocalValue objects
13332
+ * @returns Array of deserialized JavaScript values
13333
+ */
13334
+ static fromLocalValueArray(serializedValues) {
13335
+ return serializedValues.map((value) => _RemoteValue.fromLocalValue(value));
13336
+ }
13337
+ /**
13338
+ * Verifies if the given object matches the structure of a serialized LocalValue
13339
+ *
13340
+ * @param obj Object to verify
13341
+ * @returns boolean indicating if the object has LocalValue structure
13342
+ */
13343
+ static isLocalValueObject(obj) {
13344
+ if (typeof obj !== "object" || obj === null) {
13345
+ return false;
13346
+ }
13347
+ if (!obj.hasOwnProperty(TYPE_CONSTANT)) {
13348
+ return false;
13349
+ }
13350
+ const type = obj[TYPE_CONSTANT];
13351
+ const hasTypeProperty = Object.values({ ...PrimitiveType, ...NonPrimitiveType }).includes(type);
13352
+ if (!hasTypeProperty) {
13353
+ return false;
13354
+ }
13355
+ if (type !== "null" /* Null */ && type !== "undefined" /* Undefined */) {
13356
+ return obj.hasOwnProperty(VALUE_CONSTANT);
13357
+ }
13358
+ return true;
13359
+ }
13360
+ };
13361
+
13362
+ // src/utils/result.ts
13363
+ var result_exports = {};
13364
+ __export(result_exports, {
13365
+ err: () => err,
13366
+ map: () => map,
13367
+ ok: () => ok,
13368
+ unwrap: () => unwrap,
13369
+ unwrapErr: () => unwrapErr
13370
+ });
13371
+ var ok = (value) => ({
13372
+ isOk: true,
13373
+ isErr: false,
13374
+ value
13375
+ });
13376
+ var err = (value) => ({
13377
+ isOk: false,
13378
+ isErr: true,
13379
+ value
13380
+ });
13381
+ function map(result, fn) {
13382
+ if (result.isOk) {
13383
+ const val = fn(result.value);
13384
+ if (val instanceof Promise) {
13385
+ return val.then((newVal) => ok(newVal));
13285
13386
  } else {
13286
- shadowRoot.adoptedStyleSheets = [...shadowRoot.adoptedStyleSheets, globalStyleSheet];
13387
+ return ok(val);
13287
13388
  }
13288
13389
  }
13390
+ if (result.isErr) {
13391
+ const value = result.value;
13392
+ return err(value);
13393
+ }
13394
+ throw "should never get here";
13395
+ }
13396
+ var unwrap = (result) => {
13397
+ if (result.isOk) {
13398
+ return result.value;
13399
+ } else {
13400
+ throw result.value;
13401
+ }
13402
+ };
13403
+ var unwrapErr = (result) => {
13404
+ if (result.isErr) {
13405
+ return result.value;
13406
+ } else {
13407
+ throw result.value;
13408
+ }
13409
+ };
13410
+
13411
+ // src/utils/serialize.ts
13412
+ function deserializeProperty(value) {
13413
+ if (typeof value !== "string" || !value.startsWith(SERIALIZED_PREFIX)) {
13414
+ return value;
13415
+ }
13416
+ return RemoteValue.fromLocalValue(JSON.parse(atob(value.slice(SERIALIZED_PREFIX.length))));
13417
+ }
13418
+ function createShadowRoot(cmpMeta) {
13419
+ const shadowRoot = this.attachShadow({ mode: "open" });
13420
+ if (supportsConstructableStylesheets) {
13421
+ const sheet = new CSSStyleSheet();
13422
+ sheet.replaceSync(globalStyles);
13423
+ shadowRoot.adoptedStyleSheets.push(sheet);
13424
+ }
13289
13425
  }
13290
13426
  var updateFallbackSlotVisibility = (elm) => {
13291
13427
  const childNodes = internalCall(elm, "childNodes");
@@ -13324,9 +13460,8 @@ function getHostSlotNodes(childNodes, hostName, slotName) {
13324
13460
  let childNode;
13325
13461
  for (; i2 < childNodes.length; i2++) {
13326
13462
  childNode = childNodes[i2];
13327
- if (childNode["s-sr"] && (!hostName || childNode["s-hn"] === hostName) && (slotName === void 0 || getSlotName(childNode) === slotName)) {
13463
+ if (childNode["s-sr"] && (!hostName || childNode["s-hn"] === hostName) && (slotName === void 0)) {
13328
13464
  slottedNodes.push(childNode);
13329
- if (typeof slotName !== "undefined") return slottedNodes;
13330
13465
  }
13331
13466
  slottedNodes = [...slottedNodes, ...getHostSlotNodes(childNode.childNodes, hostName, slotName)];
13332
13467
  }
@@ -13412,18 +13547,6 @@ function patchSlotNode(node) {
13412
13547
  node.assignedElements = assignedFactory(true);
13413
13548
  node.assignedNodes = assignedFactory(false);
13414
13549
  }
13415
- function dispatchSlotChangeEvent(elm) {
13416
- elm.dispatchEvent(new CustomEvent("slotchange", { bubbles: false, cancelable: false, composed: false }));
13417
- }
13418
- function findSlotFromSlottedNode(slottedNode, parentHost) {
13419
- var _a;
13420
- parentHost = parentHost || ((_a = slottedNode["s-ol"]) == null ? void 0 : _a.parentElement);
13421
- if (!parentHost) return { slotNode: null, slotName: "" };
13422
- const slotName = slottedNode["s-sn"] = getSlotName(slottedNode) || "";
13423
- const childNodes = internalCall(parentHost, "childNodes");
13424
- const slotNode = getHostSlotNodes(childNodes, parentHost.tagName, slotName)[0];
13425
- return { slotNode, slotName };
13426
- }
13427
13550
  function internalCall(node, method) {
13428
13551
  if ("__" + method in node) {
13429
13552
  const toReturn = node["__" + method];
@@ -13448,164 +13571,7 @@ var uniqueTime = (key, measureText) => {
13448
13571
  };
13449
13572
  }
13450
13573
  };
13451
-
13452
- // src/utils/query-nonce-meta-tag-content.ts
13453
- function queryNonceMetaTagContent(doc) {
13454
- var _a, _b, _c;
13455
- return (_c = (_b = (_a = doc.head) == null ? void 0 : _a.querySelector('meta[name="csp-nonce"]')) == null ? void 0 : _b.getAttribute("content")) != null ? _c : void 0;
13456
- }
13457
-
13458
- // src/runtime/styles.ts
13459
- var rootAppliedStyles = /* @__PURE__ */ new WeakMap();
13460
- var registerStyle = (scopeId2, cssText, allowCS) => {
13461
- let style = styles.get(scopeId2);
13462
- if (supportsConstructableStylesheets && allowCS) {
13463
- style = style || new CSSStyleSheet();
13464
- if (typeof style === "string") {
13465
- style = cssText;
13466
- } else {
13467
- style.replaceSync(cssText);
13468
- }
13469
- } else {
13470
- style = cssText;
13471
- }
13472
- styles.set(scopeId2, style);
13473
- };
13474
- var addStyle = (styleContainerNode, cmpMeta, mode) => {
13475
- var _a, _b, _c;
13476
- const scopeId2 = getScopeId(cmpMeta);
13477
- const style = styles.get(scopeId2);
13478
- if (!win.document) {
13479
- return scopeId2;
13480
- }
13481
- styleContainerNode = styleContainerNode.nodeType === 11 /* DocumentFragment */ ? styleContainerNode : win.document;
13482
- if (style) {
13483
- if (typeof style === "string") {
13484
- styleContainerNode = styleContainerNode.head || styleContainerNode;
13485
- let appliedStyles = rootAppliedStyles.get(styleContainerNode);
13486
- let styleElm;
13487
- if (!appliedStyles) {
13488
- rootAppliedStyles.set(styleContainerNode, appliedStyles = /* @__PURE__ */ new Set());
13489
- }
13490
- const existingStyleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}="${scopeId2}"]`);
13491
- if (existingStyleElm) {
13492
- existingStyleElm.textContent = style;
13493
- } else if (!appliedStyles.has(scopeId2)) {
13494
- styleElm = win.document.createElement("style");
13495
- styleElm.textContent = style;
13496
- const nonce = (_a = plt.$nonce$) != null ? _a : queryNonceMetaTagContent(win.document);
13497
- if (nonce != null) {
13498
- styleElm.setAttribute("nonce", nonce);
13499
- }
13500
- if (!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */)) {
13501
- if (styleContainerNode.nodeName === "HEAD") {
13502
- const preconnectLinks = styleContainerNode.querySelectorAll("link[rel=preconnect]");
13503
- const referenceNode2 = preconnectLinks.length > 0 ? preconnectLinks[preconnectLinks.length - 1].nextSibling : styleContainerNode.querySelector("style");
13504
- styleContainerNode.insertBefore(
13505
- styleElm,
13506
- (referenceNode2 == null ? void 0 : referenceNode2.parentNode) === styleContainerNode ? referenceNode2 : null
13507
- );
13508
- } else if ("host" in styleContainerNode) {
13509
- if (supportsConstructableStylesheets) {
13510
- const currentWindow = (_b = styleContainerNode.defaultView) != null ? _b : styleContainerNode.ownerDocument.defaultView;
13511
- const stylesheet = new currentWindow.CSSStyleSheet();
13512
- stylesheet.replaceSync(style);
13513
- if (supportsMutableAdoptedStyleSheets) {
13514
- styleContainerNode.adoptedStyleSheets.unshift(stylesheet);
13515
- } else {
13516
- styleContainerNode.adoptedStyleSheets = [stylesheet, ...styleContainerNode.adoptedStyleSheets];
13517
- }
13518
- } else {
13519
- const existingStyleContainer = styleContainerNode.querySelector("style");
13520
- if (existingStyleContainer && true) {
13521
- existingStyleContainer.textContent = style + existingStyleContainer.textContent;
13522
- } else {
13523
- styleContainerNode.prepend(styleElm);
13524
- }
13525
- }
13526
- } else {
13527
- styleContainerNode.append(styleElm);
13528
- }
13529
- }
13530
- if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {
13531
- styleContainerNode.insertBefore(styleElm, null);
13532
- }
13533
- if (cmpMeta.$flags$ & 4 /* hasSlotRelocation */) {
13534
- styleElm.textContent += SLOT_FB_CSS;
13535
- }
13536
- if (appliedStyles) {
13537
- appliedStyles.add(scopeId2);
13538
- }
13539
- }
13540
- } else {
13541
- let appliedStyles = rootAppliedStyles.get(styleContainerNode);
13542
- if (!appliedStyles) {
13543
- rootAppliedStyles.set(styleContainerNode, appliedStyles = /* @__PURE__ */ new Set());
13544
- }
13545
- if (!appliedStyles.has(scopeId2)) {
13546
- const currentWindow = (_c = styleContainerNode.defaultView) != null ? _c : styleContainerNode.ownerDocument.defaultView;
13547
- let stylesheet;
13548
- if (style.constructor === currentWindow.CSSStyleSheet) {
13549
- stylesheet = style;
13550
- } else {
13551
- stylesheet = new currentWindow.CSSStyleSheet();
13552
- for (let i2 = 0; i2 < style.cssRules.length; i2++) {
13553
- stylesheet.insertRule(style.cssRules[i2].cssText, i2);
13554
- }
13555
- }
13556
- if (supportsMutableAdoptedStyleSheets) {
13557
- styleContainerNode.adoptedStyleSheets.push(stylesheet);
13558
- } else {
13559
- styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, stylesheet];
13560
- }
13561
- appliedStyles.add(scopeId2);
13562
- if ("host" in styleContainerNode) {
13563
- const ssrStyleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}="${scopeId2}"]`);
13564
- if (ssrStyleElm) {
13565
- writeTask(() => ssrStyleElm.remove());
13566
- }
13567
- }
13568
- }
13569
- }
13570
- }
13571
- return scopeId2;
13572
- };
13573
- var attachStyles = (hostRef) => {
13574
- const cmpMeta = hostRef.$cmpMeta$;
13575
- const elm = hostRef.$hostElement$;
13576
- const flags = cmpMeta.$flags$;
13577
- const endAttachStyles = createTime("attachStyles", cmpMeta.$tagName$);
13578
- const scopeId2 = addStyle(
13579
- elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(),
13580
- cmpMeta);
13581
- if (flags & 10 /* needsScopedEncapsulation */) {
13582
- elm["s-sc"] = scopeId2;
13583
- elm.classList.add(scopeId2 + "-h");
13584
- }
13585
- endAttachStyles();
13586
- };
13587
- var getScopeId = (cmp, mode) => "sc-" + (cmp.$tagName$);
13588
- var convertScopedToShadow = (css) => css.replace(/\/\*!@([^\/]+)\*\/[^\{]+\{/g, "$1{");
13589
- var hydrateScopedToShadow = () => {
13590
- if (!win.document) {
13591
- return;
13592
- }
13593
- const styles2 = win.document.querySelectorAll(`[${HYDRATED_STYLE_ID}]`);
13594
- let i2 = 0;
13595
- for (; i2 < styles2.length; i2++) {
13596
- registerStyle(styles2[i2].getAttribute(HYDRATED_STYLE_ID), convertScopedToShadow(styles2[i2].innerHTML), true);
13597
- }
13598
- };
13599
- var isComplexType = (o) => {
13600
- o = typeof o;
13601
- return o === "object" || o === "function";
13602
- };
13603
-
13604
- // src/runtime/vdom/h.ts
13605
13574
  var h = (nodeName, vnodeData, ...children) => {
13606
- if (typeof nodeName === "string") {
13607
- nodeName = transformTag(nodeName);
13608
- }
13609
13575
  let child = null;
13610
13576
  let key = null;
13611
13577
  let slotName = null;
@@ -13669,8 +13635,7 @@ var newVNode = (tag, text) => {
13669
13635
  const vnode = {
13670
13636
  $flags$: 0,
13671
13637
  $tag$: tag,
13672
- // Normalize undefined to null to prevent rendering "undefined" as text
13673
- $text$: text != null ? text : null,
13638
+ $text$: text,
13674
13639
  $elm$: null,
13675
13640
  $children$: null
13676
13641
  };
@@ -13720,7 +13685,7 @@ var convertToPrivate = (node) => {
13720
13685
 
13721
13686
  // src/runtime/client-hydrate.ts
13722
13687
  var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13723
- var _a, _b, _c, _d;
13688
+ var _a;
13724
13689
  const endHydrate = createTime("hydrateClient", tagName);
13725
13690
  const shadowRoot = hostElm.shadowRoot;
13726
13691
  const childRenderNodes = [];
@@ -13729,6 +13694,21 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13729
13694
  const shadowRootNodes = shadowRoot ? [] : null;
13730
13695
  const vnode = newVNode(tagName, null);
13731
13696
  vnode.$elm$ = hostElm;
13697
+ const members = Object.entries(((_a = hostRef.$cmpMeta$) == null ? void 0 : _a.$members$) || {});
13698
+ members.forEach(([memberName, [memberFlags, metaAttributeName]]) => {
13699
+ var _b;
13700
+ if (!(memberFlags & 31 /* Prop */)) {
13701
+ return;
13702
+ }
13703
+ const attributeName = metaAttributeName || memberName;
13704
+ const attrVal = hostElm.getAttribute(attributeName);
13705
+ if (attrVal !== null) {
13706
+ const attrPropVal = parsePropertyValue(
13707
+ attrVal,
13708
+ memberFlags);
13709
+ (_b = hostRef == null ? void 0 : hostRef.$instanceValues$) == null ? void 0 : _b.set(memberName, attrPropVal);
13710
+ }
13711
+ });
13732
13712
  if (win.document && (!plt.$orgLocNodes$ || !plt.$orgLocNodes$.size)) {
13733
13713
  initializeDocumentHydrate(win.document.body, plt.$orgLocNodes$ = /* @__PURE__ */ new Map());
13734
13714
  }
@@ -13753,20 +13733,10 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13753
13733
  const orgLocationNode = plt.$orgLocNodes$.get(orgLocationId);
13754
13734
  const node = childRenderNode.$elm$;
13755
13735
  if (!shadowRoot) {
13756
- node["s-hn"] = transformTag(tagName).toUpperCase();
13736
+ node["s-hn"] = tagName.toUpperCase();
13757
13737
  if (childRenderNode.$tag$ === "slot") {
13758
13738
  node["s-cr"] = hostElm["s-cr"];
13759
13739
  }
13760
- } else if (((_a = childRenderNode.$tag$) == null ? void 0 : _a.toString().includes("-")) && childRenderNode.$tag$ !== "slot-fb" && !childRenderNode.$elm$.shadowRoot) {
13761
- const cmpMeta = getHostRef(childRenderNode.$elm$);
13762
- if (cmpMeta) {
13763
- const scopeId3 = getScopeId(
13764
- cmpMeta.$cmpMeta$);
13765
- const styleSheet = win.document.querySelector(`style[sty-id="${scopeId3}"]`);
13766
- if (styleSheet) {
13767
- shadowRootNodes.unshift(styleSheet.cloneNode(true));
13768
- }
13769
- }
13770
13740
  }
13771
13741
  if (childRenderNode.$tag$ === "slot") {
13772
13742
  childRenderNode.$name$ = childRenderNode.$elm$["s-sn"] || childRenderNode.$elm$["name"] || null;
@@ -13782,7 +13752,7 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13782
13752
  }
13783
13753
  }
13784
13754
  if (orgLocationNode && orgLocationNode.isConnected) {
13785
- if (orgLocationNode.parentElement.shadowRoot && orgLocationNode["s-en"] === "") {
13755
+ if (shadowRoot && orgLocationNode["s-en"] === "") {
13786
13756
  orgLocationNode.parentNode.insertBefore(node, orgLocationNode.nextSibling);
13787
13757
  }
13788
13758
  orgLocationNode.parentNode.removeChild(orgLocationNode);
@@ -13790,9 +13760,7 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13790
13760
  node["s-oo"] = parseInt(childRenderNode.$nodeId$);
13791
13761
  }
13792
13762
  }
13793
- if (orgLocationNode && !orgLocationNode["s-id"]) {
13794
- plt.$orgLocNodes$.delete(orgLocationId);
13795
- }
13763
+ plt.$orgLocNodes$.delete(orgLocationId);
13796
13764
  }
13797
13765
  const hosts = [];
13798
13766
  const snLen = slottedNodes.length;
@@ -13801,7 +13769,6 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13801
13769
  let snGroupIdx;
13802
13770
  let snGroupLen;
13803
13771
  let slottedItem;
13804
- let currentPos = 0;
13805
13772
  for (snIndex; snIndex < snLen; snIndex++) {
13806
13773
  slotGroup = slottedNodes[snIndex];
13807
13774
  if (!slotGroup || !slotGroup.length) continue;
@@ -13814,24 +13781,18 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13814
13781
  }
13815
13782
  if (!hosts[slottedItem.hostId]) continue;
13816
13783
  const hostEle = hosts[slottedItem.hostId];
13817
- if (hostEle.shadowRoot && slottedItem.node.parentElement !== hostEle) {
13818
- hostEle.insertBefore(slottedItem.node, (_c = (_b = slotGroup[snGroupIdx - 1]) == null ? void 0 : _b.node) == null ? void 0 : _c.nextSibling);
13819
- }
13820
13784
  if (!hostEle.shadowRoot || !shadowRoot) {
13821
- if (!slottedItem.slot["s-cr"]) {
13822
- slottedItem.slot["s-cr"] = hostEle["s-cr"];
13823
- if (!slottedItem.slot["s-cr"] && hostEle.shadowRoot) {
13824
- slottedItem.slot["s-cr"] = hostEle;
13825
- } else {
13826
- slottedItem.slot["s-cr"] = (hostEle.__childNodes || hostEle.childNodes)[0];
13827
- }
13828
- }
13829
- addSlotRelocateNode(slottedItem.node, slottedItem.slot, false, slottedItem.node["s-oo"] || currentPos);
13830
- if (((_d = slottedItem.node.parentElement) == null ? void 0 : _d.shadowRoot) && slottedItem.node["getAttribute"] && slottedItem.node.getAttribute("slot")) {
13831
- slottedItem.node.removeAttribute("slot");
13785
+ slottedItem.slot["s-cr"] = hostEle["s-cr"];
13786
+ if (!slottedItem.slot["s-cr"] && hostEle.shadowRoot) {
13787
+ slottedItem.slot["s-cr"] = hostEle;
13788
+ } else {
13789
+ slottedItem.slot["s-cr"] = (hostEle.__childNodes || hostEle.childNodes)[0];
13832
13790
  }
13791
+ addSlotRelocateNode(slottedItem.node, slottedItem.slot, false, slottedItem.node["s-oo"]);
13792
+ }
13793
+ if (hostEle.shadowRoot && slottedItem.node.parentElement !== hostEle) {
13794
+ hostEle.appendChild(slottedItem.node);
13833
13795
  }
13834
- currentPos = (slottedItem.node["s-oo"] || currentPos) + 1;
13835
13796
  }
13836
13797
  }
13837
13798
  if (shadowRoot && !shadowRoot.childNodes.length) {
@@ -13839,22 +13800,20 @@ var initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
13839
13800
  const rnLen = shadowRootNodes.length;
13840
13801
  if (rnLen) {
13841
13802
  for (rnIdex; rnIdex < rnLen; rnIdex++) {
13842
- const node = shadowRootNodes[rnIdex];
13843
- if (node) {
13844
- shadowRoot.appendChild(node);
13845
- }
13803
+ shadowRoot.appendChild(shadowRootNodes[rnIdex]);
13846
13804
  }
13847
13805
  Array.from(hostElm.childNodes).forEach((node) => {
13848
13806
  if (typeof node["s-en"] !== "string" && typeof node["s-sn"] !== "string") {
13849
13807
  if (node.nodeType === 1 /* ElementNode */ && node.slot && node.hidden) {
13850
13808
  node.removeAttribute("hidden");
13851
- } else if (node.nodeType === 8 /* CommentNode */ && !node.nodeValue) {
13809
+ } else if (node.nodeType === 8 /* CommentNode */ || node.nodeType === 3 /* TextNode */ && !node.wholeText.trim()) {
13852
13810
  node.parentNode.removeChild(node);
13853
13811
  }
13854
13812
  }
13855
13813
  });
13856
13814
  }
13857
13815
  }
13816
+ plt.$orgLocNodes$.delete(hostElm["s-id"]);
13858
13817
  hostRef.$hostElement$ = hostElm;
13859
13818
  endHydrate();
13860
13819
  };
@@ -14007,6 +13966,10 @@ var clientHydrate = (parentVNode, childRenderNodes, slotNodes, shadowRootNodes,
14007
13966
  vnode.$elm$ = node;
14008
13967
  vnode.$index$ = "0";
14009
13968
  parentVNode.$children$ = [vnode];
13969
+ } else {
13970
+ if (node.nodeType === 3 /* TextNode */ && !node.wholeText.trim()) {
13971
+ node.remove();
13972
+ }
14010
13973
  }
14011
13974
  return parentVNode;
14012
13975
  };
@@ -14062,10 +14025,10 @@ function addSlot(slotName, slotId, childVNode, node, parentVNode, childRenderNod
14062
14025
  if (childVNode.$name$) {
14063
14026
  childVNode.$elm$.setAttribute("name", slotName);
14064
14027
  }
14065
- if (parentVNode.$elm$.shadowRoot && parentNodeId && parentNodeId !== childVNode.$hostId$) {
14066
- internalCall(parentVNode.$elm$, "insertBefore")(slot, internalCall(parentVNode.$elm$, "children")[0]);
14028
+ if (parentNodeId && parentNodeId !== childVNode.$hostId$) {
14029
+ parentVNode.$elm$.insertBefore(slot, parentVNode.$elm$.children[0]);
14067
14030
  } else {
14068
- internalCall(internalCall(node, "parentNode"), "insertBefore")(slot, node);
14031
+ node.parentNode.insertBefore(slot, node);
14069
14032
  }
14070
14033
  addSlottedNodes(slottedNodes, slotId, slotName, node, childVNode.$hostId$);
14071
14034
  node.remove();
@@ -14076,144 +14039,54 @@ function addSlot(slotName, slotId, childVNode, node, parentVNode, childRenderNod
14076
14039
  const slot = childVNode.$elm$;
14077
14040
  const shouldMove = parentNodeId && parentNodeId !== childVNode.$hostId$ && parentVNode.$elm$.shadowRoot;
14078
14041
  addSlottedNodes(slottedNodes, slotId, slotName, node, shouldMove ? parentNodeId : childVNode.$hostId$);
14079
- patchSlotNode(node);
14080
- if (shouldMove) {
14081
- parentVNode.$elm$.insertBefore(slot, parentVNode.$elm$.children[0]);
14082
- }
14083
- }
14084
- childRenderNodes.push(childVNode);
14085
- slotNodes.push(childVNode);
14086
- if (!parentVNode.$children$) {
14087
- parentVNode.$children$ = [];
14088
- }
14089
- parentVNode.$children$[childVNode.$index$] = childVNode;
14090
- }
14091
- var addSlottedNodes = (slottedNodes, slotNodeId, slotName, slotNode, hostId) => {
14092
- var _a, _b;
14093
- let slottedNode = slotNode.nextSibling;
14094
- slottedNodes[slotNodeId] = slottedNodes[slotNodeId] || [];
14095
- if (!slottedNode || ((_a = slottedNode.nodeValue) == null ? void 0 : _a.startsWith(SLOT_NODE_ID + "."))) return;
14096
- do {
14097
- if (slottedNode && ((slottedNode["getAttribute"] && slottedNode.getAttribute("slot") || slottedNode["s-sn"]) === slotName || slotName === "" && !slottedNode["s-sn"] && (!slottedNode["getAttribute"] || !slottedNode.getAttribute("slot")) && (slottedNode.nodeType === 8 /* CommentNode */ || slottedNode.nodeType === 3 /* TextNode */))) {
14098
- slottedNode["s-sn"] = slotName;
14099
- slottedNodes[slotNodeId].push({ slot: slotNode, node: slottedNode, hostId });
14100
- }
14101
- slottedNode = slottedNode == null ? void 0 : slottedNode.nextSibling;
14102
- } while (slottedNode && !((_b = slottedNode.nodeValue) == null ? void 0 : _b.startsWith(SLOT_NODE_ID + ".")));
14103
- };
14104
- var findCorrespondingNode = (node, type) => {
14105
- let sibling = node;
14106
- do {
14107
- sibling = sibling.nextSibling;
14108
- } while (sibling && (sibling.nodeType !== type || !sibling.nodeValue));
14109
- return sibling;
14110
- };
14111
-
14112
- // src/utils/remote-value.ts
14113
- var RemoteValue = class _RemoteValue {
14114
- /**
14115
- * Deserializes a LocalValue serialized object back to its original JavaScript representation
14116
- *
14117
- * @param serialized The serialized LocalValue object
14118
- * @returns The original JavaScript value/object
14119
- */
14120
- static fromLocalValue(serialized) {
14121
- const type = serialized[TYPE_CONSTANT];
14122
- const value = VALUE_CONSTANT in serialized ? serialized[VALUE_CONSTANT] : void 0;
14123
- switch (type) {
14124
- case "string" /* String */:
14125
- return value;
14126
- case "boolean" /* Boolean */:
14127
- return value;
14128
- case "bigint" /* BigInt */:
14129
- return BigInt(value);
14130
- case "undefined" /* Undefined */:
14131
- return void 0;
14132
- case "null" /* Null */:
14133
- return null;
14134
- case "number" /* Number */:
14135
- if (value === "NaN") return NaN;
14136
- if (value === "-0") return -0;
14137
- if (value === "Infinity") return Infinity;
14138
- if (value === "-Infinity") return -Infinity;
14139
- return value;
14140
- case "array" /* Array */:
14141
- return value.map((item) => _RemoteValue.fromLocalValue(item));
14142
- case "date" /* Date */:
14143
- return new Date(value);
14144
- case "map" /* Map */:
14145
- const map = /* @__PURE__ */ new Map();
14146
- for (const [key, val] of value) {
14147
- const deserializedKey = typeof key === "object" && key !== null ? _RemoteValue.fromLocalValue(key) : key;
14148
- const deserializedValue = _RemoteValue.fromLocalValue(val);
14149
- map.set(deserializedKey, deserializedValue);
14150
- }
14151
- return map;
14152
- case "object" /* Object */:
14153
- const obj = {};
14154
- for (const [key, val] of value) {
14155
- obj[key] = _RemoteValue.fromLocalValue(val);
14156
- }
14157
- return obj;
14158
- case "regexp" /* RegularExpression */:
14159
- const { pattern, flags } = value;
14160
- return new RegExp(pattern, flags);
14161
- case "set" /* Set */:
14162
- const set = /* @__PURE__ */ new Set();
14163
- for (const item of value) {
14164
- set.add(_RemoteValue.fromLocalValue(item));
14165
- }
14166
- return set;
14167
- case "symbol" /* Symbol */:
14168
- return Symbol(value);
14169
- default:
14170
- throw new Error(`Unsupported type: ${type}`);
14171
- }
14172
- }
14173
- /**
14174
- * Utility method to deserialize multiple LocalValues at once
14175
- *
14176
- * @param serializedValues Array of serialized LocalValue objects
14177
- * @returns Array of deserialized JavaScript values
14178
- */
14179
- static fromLocalValueArray(serializedValues) {
14180
- return serializedValues.map((value) => _RemoteValue.fromLocalValue(value));
14181
- }
14182
- /**
14183
- * Verifies if the given object matches the structure of a serialized LocalValue
14184
- *
14185
- * @param obj Object to verify
14186
- * @returns boolean indicating if the object has LocalValue structure
14187
- */
14188
- static isLocalValueObject(obj) {
14189
- if (typeof obj !== "object" || obj === null) {
14190
- return false;
14191
- }
14192
- if (!obj.hasOwnProperty(TYPE_CONSTANT)) {
14193
- return false;
14194
- }
14195
- const type = obj[TYPE_CONSTANT];
14196
- const hasTypeProperty = Object.values({ ...PrimitiveType, ...NonPrimitiveType }).includes(type);
14197
- if (!hasTypeProperty) {
14198
- return false;
14199
- }
14200
- if (type !== "null" /* Null */ && type !== "undefined" /* Undefined */) {
14201
- return obj.hasOwnProperty(VALUE_CONSTANT);
14202
- }
14203
- return true;
14204
- }
14205
- };
14206
-
14207
- // src/utils/serialize.ts
14208
- function deserializeProperty(value) {
14209
- if (typeof value !== "string" || !value.startsWith(SERIALIZED_PREFIX)) {
14210
- return value;
14042
+ patchSlotNode(node);
14043
+ if (shouldMove) {
14044
+ parentVNode.$elm$.insertBefore(slot, parentVNode.$elm$.children[0]);
14045
+ }
14211
14046
  }
14212
- return RemoteValue.fromLocalValue(JSON.parse(atob(value.slice(SERIALIZED_PREFIX.length))));
14047
+ childRenderNodes.push(childVNode);
14048
+ slotNodes.push(childVNode);
14049
+ if (!parentVNode.$children$) {
14050
+ parentVNode.$children$ = [];
14051
+ }
14052
+ parentVNode.$children$[childVNode.$index$] = childVNode;
14213
14053
  }
14214
-
14215
- // src/runtime/parse-property-value.ts
14054
+ var addSlottedNodes = (slottedNodes, slotNodeId, slotName, slotNode, hostId) => {
14055
+ let slottedNode = slotNode.nextSibling;
14056
+ slottedNodes[slotNodeId] = slottedNodes[slotNodeId] || [];
14057
+ while (slottedNode && ((slottedNode["getAttribute"] && slottedNode.getAttribute("slot") || slottedNode["s-sn"]) === slotName || slotName === "" && !slottedNode["s-sn"] && (slottedNode.nodeType === 8 /* CommentNode */ && slottedNode.nodeValue.indexOf(".") !== 1 || slottedNode.nodeType === 3 /* TextNode */))) {
14058
+ slottedNode["s-sn"] = slotName;
14059
+ slottedNodes[slotNodeId].push({ slot: slotNode, node: slottedNode, hostId });
14060
+ slottedNode = slottedNode.nextSibling;
14061
+ }
14062
+ };
14063
+ var findCorrespondingNode = (node, type) => {
14064
+ let sibling = node;
14065
+ do {
14066
+ sibling = sibling.nextSibling;
14067
+ } while (sibling && (sibling.nodeType !== type || !sibling.nodeValue));
14068
+ return sibling;
14069
+ };
14070
+ var createSupportsRuleRe = (selector) => {
14071
+ const safeSelector2 = escapeRegExpSpecialCharacters(selector);
14072
+ return new RegExp(
14073
+ // First capture group: match any context before the selector that's not inside @supports selector()
14074
+ // Using negative lookahead to avoid matching inside @supports selector(...) condition
14075
+ `(^|[^@]|@(?!supports\\s+selector\\s*\\([^{]*?${safeSelector2}))(${safeSelector2}\\b)`,
14076
+ "g"
14077
+ );
14078
+ };
14079
+ createSupportsRuleRe("::slotted");
14080
+ createSupportsRuleRe(":host");
14081
+ createSupportsRuleRe(":host-context");
14216
14082
  var parsePropertyValue = (propValue, propType, isFormAssociated) => {
14083
+ if (typeof propValue === "string" && (propValue.startsWith("{") && propValue.endsWith("}") || propValue.startsWith("[") && propValue.endsWith("]"))) {
14084
+ try {
14085
+ propValue = JSON.parse(propValue);
14086
+ return propValue;
14087
+ } catch (e) {
14088
+ }
14089
+ }
14217
14090
  if (typeof propValue === "string" && propValue.startsWith(SERIALIZED_PREFIX)) {
14218
14091
  propValue = deserializeProperty(propValue);
14219
14092
  return propValue;
@@ -14234,10 +14107,7 @@ var parsePropertyValue = (propValue, propType, isFormAssociated) => {
14234
14107
  }
14235
14108
  return propValue;
14236
14109
  };
14237
- var getElement = (ref) => {
14238
- var _a;
14239
- return (_a = getHostRef(ref)) == null ? void 0 : _a.$hostElement$ ;
14240
- };
14110
+ var getElement = (ref) => getHostRef(ref).$hostElement$ ;
14241
14111
 
14242
14112
  // src/runtime/event-emitter.ts
14243
14113
  var createEvent = (ref, name, flags) => {
@@ -14258,6 +14128,115 @@ var emitEvent = (elm, name, opts) => {
14258
14128
  elm.dispatchEvent(ev);
14259
14129
  return ev;
14260
14130
  };
14131
+ var rootAppliedStyles = /* @__PURE__ */ new WeakMap();
14132
+ var registerStyle = (scopeId2, cssText, allowCS) => {
14133
+ let style = styles.get(scopeId2);
14134
+ if (supportsConstructableStylesheets && allowCS) {
14135
+ style = style || new CSSStyleSheet();
14136
+ if (typeof style === "string") {
14137
+ style = cssText;
14138
+ } else {
14139
+ style.replaceSync(cssText);
14140
+ }
14141
+ } else {
14142
+ style = cssText;
14143
+ }
14144
+ styles.set(scopeId2, style);
14145
+ };
14146
+ var addStyle = (styleContainerNode, cmpMeta, mode) => {
14147
+ var _a;
14148
+ const scopeId2 = getScopeId(cmpMeta);
14149
+ const style = styles.get(scopeId2);
14150
+ if (!win.document) {
14151
+ return scopeId2;
14152
+ }
14153
+ styleContainerNode = styleContainerNode.nodeType === 11 /* DocumentFragment */ ? styleContainerNode : win.document;
14154
+ if (style) {
14155
+ if (typeof style === "string") {
14156
+ styleContainerNode = styleContainerNode.head || styleContainerNode;
14157
+ let appliedStyles = rootAppliedStyles.get(styleContainerNode);
14158
+ let styleElm;
14159
+ if (!appliedStyles) {
14160
+ rootAppliedStyles.set(styleContainerNode, appliedStyles = /* @__PURE__ */ new Set());
14161
+ }
14162
+ if (!appliedStyles.has(scopeId2)) {
14163
+ if (styleContainerNode.host && (styleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}="${scopeId2}"]`))) {
14164
+ styleElm.innerHTML = style;
14165
+ } else {
14166
+ styleElm = win.document.createElement("style");
14167
+ styleElm.innerHTML = style;
14168
+ const nonce = (_a = plt.$nonce$) != null ? _a : queryNonceMetaTagContent(win.document);
14169
+ if (nonce != null) {
14170
+ styleElm.setAttribute("nonce", nonce);
14171
+ }
14172
+ if (!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */)) {
14173
+ if (styleContainerNode.nodeName === "HEAD") {
14174
+ const preconnectLinks = styleContainerNode.querySelectorAll("link[rel=preconnect]");
14175
+ const referenceNode2 = preconnectLinks.length > 0 ? preconnectLinks[preconnectLinks.length - 1].nextSibling : styleContainerNode.querySelector("style");
14176
+ styleContainerNode.insertBefore(
14177
+ styleElm,
14178
+ (referenceNode2 == null ? void 0 : referenceNode2.parentNode) === styleContainerNode ? referenceNode2 : null
14179
+ );
14180
+ } else if ("host" in styleContainerNode) {
14181
+ if (supportsConstructableStylesheets) {
14182
+ const stylesheet = new CSSStyleSheet();
14183
+ stylesheet.replaceSync(style);
14184
+ styleContainerNode.adoptedStyleSheets = [stylesheet, ...styleContainerNode.adoptedStyleSheets];
14185
+ } else {
14186
+ const existingStyleContainer = styleContainerNode.querySelector("style");
14187
+ if (existingStyleContainer) {
14188
+ existingStyleContainer.innerHTML = style + existingStyleContainer.innerHTML;
14189
+ } else {
14190
+ styleContainerNode.prepend(styleElm);
14191
+ }
14192
+ }
14193
+ } else {
14194
+ styleContainerNode.append(styleElm);
14195
+ }
14196
+ }
14197
+ if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {
14198
+ styleContainerNode.insertBefore(styleElm, null);
14199
+ }
14200
+ }
14201
+ if (cmpMeta.$flags$ & 4 /* hasSlotRelocation */) {
14202
+ styleElm.innerHTML += SLOT_FB_CSS;
14203
+ }
14204
+ if (appliedStyles) {
14205
+ appliedStyles.add(scopeId2);
14206
+ }
14207
+ }
14208
+ } else if (!styleContainerNode.adoptedStyleSheets.includes(style)) {
14209
+ styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, style];
14210
+ }
14211
+ }
14212
+ return scopeId2;
14213
+ };
14214
+ var attachStyles = (hostRef) => {
14215
+ const cmpMeta = hostRef.$cmpMeta$;
14216
+ const elm = hostRef.$hostElement$;
14217
+ const flags = cmpMeta.$flags$;
14218
+ const endAttachStyles = createTime("attachStyles", cmpMeta.$tagName$);
14219
+ const scopeId2 = addStyle(
14220
+ elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(),
14221
+ cmpMeta);
14222
+ if (flags & 10 /* needsScopedEncapsulation */) {
14223
+ elm["s-sc"] = scopeId2;
14224
+ elm.classList.add(scopeId2 + "-h");
14225
+ }
14226
+ endAttachStyles();
14227
+ };
14228
+ var getScopeId = (cmp, mode) => "sc-" + (cmp.$tagName$);
14229
+ var convertScopedToShadow = (css) => css.replace(/\/\*!@([^\/]+)\*\/[^\{]+\{/g, "$1{");
14230
+ var hydrateScopedToShadow = () => {
14231
+ if (!win.document) {
14232
+ return;
14233
+ }
14234
+ const styles2 = win.document.querySelectorAll(`[${HYDRATED_STYLE_ID}]`);
14235
+ let i2 = 0;
14236
+ for (; i2 < styles2.length; i2++) {
14237
+ registerStyle(styles2[i2].getAttribute(HYDRATED_STYLE_ID), convertScopedToShadow(styles2[i2].innerHTML), true);
14238
+ }
14239
+ };
14261
14240
  var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRender) => {
14262
14241
  if (oldValue === newValue) {
14263
14242
  return;
@@ -14268,13 +14247,12 @@ var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRen
14268
14247
  const classList = elm.classList;
14269
14248
  const oldClasses = parseClassList(oldValue);
14270
14249
  let newClasses = parseClassList(newValue);
14271
- if ((elm["s-si"] || elm["s-sc"]) && initialRender) {
14272
- const scopeId2 = elm["s-sc"] || elm["s-si"];
14273
- newClasses.push(scopeId2);
14250
+ if (elm["s-si"] && initialRender) {
14251
+ newClasses.push(elm["s-si"]);
14274
14252
  oldClasses.forEach((c) => {
14275
- if (c.startsWith(scopeId2)) newClasses.push(c);
14253
+ if (c.startsWith(elm["s-si"])) newClasses.push(c);
14276
14254
  });
14277
- newClasses = [...new Set(newClasses)].filter((c) => c);
14255
+ newClasses = [...new Set(newClasses)];
14278
14256
  classList.add(...newClasses);
14279
14257
  } else {
14280
14258
  classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));
@@ -14303,7 +14281,7 @@ var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRen
14303
14281
  }
14304
14282
  } else if (memberName === "key") ; else if (memberName === "ref") {
14305
14283
  if (newValue) {
14306
- queueRefAttachment(newValue, elm);
14284
+ newValue(elm);
14307
14285
  }
14308
14286
  } else if ((!isProp ) && memberName[0] === "o" && memberName[1] === "n") {
14309
14287
  if (memberName[2] === "-") {
@@ -14323,36 +14301,6 @@ var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRen
14323
14301
  plt.ael(elm, memberName, newValue, capture);
14324
14302
  }
14325
14303
  }
14326
- } else if (memberName[0] === "a" && memberName.startsWith("attr:")) {
14327
- const propName = memberName.slice(5);
14328
- let attrName;
14329
- {
14330
- const hostRef = getHostRef(elm);
14331
- if (hostRef && hostRef.$cmpMeta$ && hostRef.$cmpMeta$.$members$) {
14332
- const memberMeta = hostRef.$cmpMeta$.$members$[propName];
14333
- if (memberMeta && memberMeta[1]) {
14334
- attrName = memberMeta[1];
14335
- }
14336
- }
14337
- }
14338
- if (!attrName) {
14339
- attrName = propName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
14340
- }
14341
- if (newValue == null || newValue === false) {
14342
- if (newValue !== false || elm.getAttribute(attrName) === "") {
14343
- elm.removeAttribute(attrName);
14344
- }
14345
- } else {
14346
- elm.setAttribute(attrName, newValue === true ? "" : newValue);
14347
- }
14348
- return;
14349
- } else if (memberName[0] === "p" && memberName.startsWith("prop:")) {
14350
- const propName = memberName.slice(5);
14351
- try {
14352
- elm[propName] = newValue;
14353
- } catch (e) {
14354
- }
14355
- return;
14356
14304
  } else {
14357
14305
  const isComplex = isComplexType(newValue);
14358
14306
  if ((isProp || isComplex && newValue !== null) && !isSvg) {
@@ -14361,7 +14309,7 @@ var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRen
14361
14309
  const n = newValue == null ? "" : newValue;
14362
14310
  if (memberName === "list") {
14363
14311
  isProp = false;
14364
- } else if (oldValue == null || elm[memberName] !== n) {
14312
+ } else if (oldValue == null || elm[memberName] != n) {
14365
14313
  if (typeof elm.__lookupSetter__(memberName) === "function") {
14366
14314
  elm[memberName] = n;
14367
14315
  } else {
@@ -14459,8 +14407,6 @@ var useNativeShadowDom = false;
14459
14407
  var checkSlotFallbackVisibility = false;
14460
14408
  var checkSlotRelocate = false;
14461
14409
  var isSvgMode = false;
14462
- var refCallbacksToRemove = [];
14463
- var refCallbacksToAttach = [];
14464
14410
  var createElm = (oldParentVNode, newParentVNode, childIndex) => {
14465
14411
  var _a;
14466
14412
  const newVNode2 = newParentVNode.$children$[childIndex];
@@ -14483,7 +14429,7 @@ var createElm = (oldParentVNode, newParentVNode, childIndex) => {
14483
14429
  );
14484
14430
  }
14485
14431
  }
14486
- if (newVNode2.$text$ != null) {
14432
+ if (newVNode2.$text$ !== null) {
14487
14433
  elm = newVNode2.$elm$ = win.document.createTextNode(newVNode2.$text$);
14488
14434
  } else if (newVNode2.$flags$ & 1 /* isSlotReference */) {
14489
14435
  elm = newVNode2.$elm$ = win.document.createTextNode("");
@@ -14495,7 +14441,9 @@ var createElm = (oldParentVNode, newParentVNode, childIndex) => {
14495
14441
  isSvgMode = newVNode2.$tag$ === "svg";
14496
14442
  }
14497
14443
  if (!win.document) {
14498
- throw new Error("You are trying to render a Stencil component in an environment that doesn't support the DOM.");
14444
+ throw new Error(
14445
+ "You are trying to render a Stencil component in an environment that doesn't support the DOM. Make sure to populate the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window) object before rendering a component."
14446
+ );
14499
14447
  }
14500
14448
  elm = newVNode2.$elm$ = win.document.createElementNS(
14501
14449
  isSvgMode ? SVG_NS : HTML_NS,
@@ -14508,11 +14456,10 @@ var createElm = (oldParentVNode, newParentVNode, childIndex) => {
14508
14456
  updateElement(null, newVNode2, isSvgMode);
14509
14457
  }
14510
14458
  if (newVNode2.$children$) {
14511
- const appendTarget = newVNode2.$tag$ === "template" ? elm.content : elm;
14512
14459
  for (i2 = 0; i2 < newVNode2.$children$.length; ++i2) {
14513
14460
  childNode = createElm(oldParentVNode, newVNode2, i2);
14514
14461
  if (childNode) {
14515
- appendTarget.appendChild(childNode);
14462
+ elm.appendChild(childNode);
14516
14463
  }
14517
14464
  }
14518
14465
  }
@@ -14534,43 +14481,17 @@ var createElm = (oldParentVNode, newParentVNode, childIndex) => {
14534
14481
  patchSlotNode(elm);
14535
14482
  oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex];
14536
14483
  if (oldVNode && oldVNode.$tag$ === newVNode2.$tag$ && oldParentVNode.$elm$) {
14537
- relocateToHostRoot(oldParentVNode.$elm$);
14484
+ {
14485
+ putBackInOriginalLocation(oldParentVNode.$elm$, false);
14486
+ }
14538
14487
  }
14539
14488
  }
14540
14489
  }
14541
14490
  return elm;
14542
14491
  };
14543
- var relocateToHostRoot = (parentElm) => {
14544
- plt.$flags$ |= 1 /* isTmpDisconnected */;
14545
- const host = parentElm.closest(hostTagName.toLowerCase());
14546
- if (host != null) {
14547
- const contentRefNode = Array.from(host.__childNodes || host.childNodes).find(
14548
- (ref) => ref["s-cr"]
14549
- );
14550
- const childNodeArray = Array.from(
14551
- parentElm.__childNodes || parentElm.childNodes
14552
- );
14553
- for (const childNode of contentRefNode ? childNodeArray.reverse() : childNodeArray) {
14554
- if (childNode["s-sh"] != null) {
14555
- insertBefore(host, childNode, contentRefNode != null ? contentRefNode : null);
14556
- childNode["s-sh"] = void 0;
14557
- checkSlotRelocate = true;
14558
- }
14559
- }
14560
- }
14561
- plt.$flags$ &= -2 /* isTmpDisconnected */;
14562
- };
14563
14492
  var putBackInOriginalLocation = (parentElm, recursive) => {
14564
14493
  plt.$flags$ |= 1 /* isTmpDisconnected */;
14565
14494
  const oldSlotChildNodes = Array.from(parentElm.__childNodes || parentElm.childNodes);
14566
- if (parentElm["s-sr"]) {
14567
- let node = parentElm;
14568
- while (node = node.nextSibling) {
14569
- if (node && node["s-sn"] === parentElm["s-sn"] && node["s-sh"] === hostTagName) {
14570
- oldSlotChildNodes.push(node);
14571
- }
14572
- }
14573
- }
14574
14495
  for (let i2 = oldSlotChildNodes.length - 1; i2 >= 0; i2--) {
14575
14496
  const childNode = oldSlotChildNodes[i2];
14576
14497
  if (childNode["s-hn"] !== hostTagName && childNode["s-ol"]) {
@@ -14592,9 +14513,6 @@ var addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {
14592
14513
  if (containerElm.shadowRoot && containerElm.tagName === hostTagName) {
14593
14514
  containerElm = containerElm.shadowRoot;
14594
14515
  }
14595
- if (parentVNode.$tag$ === "template") {
14596
- containerElm = containerElm.content;
14597
- }
14598
14516
  for (; startIdx <= endIdx; ++startIdx) {
14599
14517
  if (vnodes[startIdx]) {
14600
14518
  childNode = createElm(null, parentVNode, startIdx);
@@ -14638,7 +14556,6 @@ var updateChildren = (parentElm, oldCh, newVNode2, newCh, isInitialRender = fals
14638
14556
  let newEndVnode = newCh[newEndIdx];
14639
14557
  let node;
14640
14558
  let elmToMove;
14641
- const containerElm = newVNode2.$tag$ === "template" ? parentElm.content : parentElm;
14642
14559
  while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
14643
14560
  if (oldStartVnode == null) {
14644
14561
  oldStartVnode = oldCh[++oldStartIdx];
@@ -14661,7 +14578,7 @@ var updateChildren = (parentElm, oldCh, newVNode2, newCh, isInitialRender = fals
14661
14578
  putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false);
14662
14579
  }
14663
14580
  patch(oldStartVnode, newEndVnode, isInitialRender);
14664
- insertBefore(containerElm, oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);
14581
+ insertBefore(parentElm, oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);
14665
14582
  oldStartVnode = oldCh[++oldStartIdx];
14666
14583
  newEndVnode = newCh[--newEndIdx];
14667
14584
  } else if (isSameVnode(oldEndVnode, newStartVnode, isInitialRender)) {
@@ -14669,7 +14586,7 @@ var updateChildren = (parentElm, oldCh, newVNode2, newCh, isInitialRender = fals
14669
14586
  putBackInOriginalLocation(oldEndVnode.$elm$.parentNode, false);
14670
14587
  }
14671
14588
  patch(oldEndVnode, newStartVnode, isInitialRender);
14672
- insertBefore(containerElm, oldEndVnode.$elm$, oldStartVnode.$elm$);
14589
+ insertBefore(parentElm, oldEndVnode.$elm$, oldStartVnode.$elm$);
14673
14590
  oldEndVnode = oldCh[--oldEndIdx];
14674
14591
  newStartVnode = newCh[++newStartIdx];
14675
14592
  } else {
@@ -14743,17 +14660,11 @@ var patch = (oldVNode, newVNode2, isInitialRender = false) => {
14743
14660
  const tag = newVNode2.$tag$;
14744
14661
  const text = newVNode2.$text$;
14745
14662
  let defaultHolder;
14746
- if (text == null) {
14663
+ if (text === null) {
14747
14664
  {
14748
14665
  isSvgMode = tag === "svg" ? true : tag === "foreignObject" ? false : isSvgMode;
14749
14666
  }
14750
14667
  {
14751
- if (tag === "slot" && !useNativeShadowDom) {
14752
- if (oldVNode.$name$ !== newVNode2.$name$) {
14753
- newVNode2.$elm$["s-sn"] = newVNode2.$name$ || "";
14754
- relocateToHostRoot(newVNode2.$elm$.parentElement);
14755
- }
14756
- }
14757
14668
  updateElement(oldVNode, newVNode2, isSvgMode, isInitialRender);
14758
14669
  }
14759
14670
  if (oldChildren !== null && newChildren !== null) {
@@ -14768,8 +14679,6 @@ var patch = (oldVNode, newVNode2, isInitialRender = false) => {
14768
14679
  !isInitialRender && BUILD.updatable && oldChildren !== null
14769
14680
  ) {
14770
14681
  removeVnodes(oldChildren, 0, oldChildren.length - 1);
14771
- } else if (isInitialRender && BUILD.updatable && oldChildren !== null && newChildren === null) {
14772
- newVNode2.$children$ = oldChildren;
14773
14682
  }
14774
14683
  if (isSvgMode && tag === "svg") {
14775
14684
  isSvgMode = false;
@@ -14792,7 +14701,7 @@ var markSlotContentForRelocation = (elm) => {
14792
14701
  const slotName = childNode["s-sn"];
14793
14702
  for (j = hostContentNodes.length - 1; j >= 0; j--) {
14794
14703
  node = hostContentNodes[j];
14795
- if (!node["s-cn"] && !node["s-nr"] && node["s-hn"] !== childNode["s-hn"] && (!node["s-sh"] || node["s-sh"] !== childNode["s-hn"])) {
14704
+ if (!node["s-cn"] && !node["s-nr"] && node["s-hn"] !== childNode["s-hn"] && (true)) {
14796
14705
  if (isNodeLocatedInSlot(node, slotName)) {
14797
14706
  let relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
14798
14707
  checkSlotFallbackVisibility = true;
@@ -14832,42 +14741,17 @@ var markSlotContentForRelocation = (elm) => {
14832
14741
  };
14833
14742
  var nullifyVNodeRefs = (vNode) => {
14834
14743
  {
14835
- if (vNode.$attrs$ && vNode.$attrs$.ref) {
14836
- refCallbacksToRemove.push(() => vNode.$attrs$.ref(null));
14837
- }
14744
+ vNode.$attrs$ && vNode.$attrs$.ref && vNode.$attrs$.ref(null);
14838
14745
  vNode.$children$ && vNode.$children$.map(nullifyVNodeRefs);
14839
14746
  }
14840
14747
  };
14841
- var queueRefAttachment = (refCallback, elm) => {
14748
+ var insertBefore = (parent, newNode, reference) => {
14842
14749
  {
14843
- refCallbacksToAttach.push(() => refCallback(elm));
14844
- }
14845
- };
14846
- var flushQueuedRefCallbacks = () => {
14847
- {
14848
- refCallbacksToRemove.forEach((cb) => cb());
14849
- refCallbacksToRemove.length = 0;
14850
- refCallbacksToAttach.forEach((cb) => cb());
14851
- refCallbacksToAttach.length = 0;
14852
- }
14853
- };
14854
- var insertBefore = (parent, newNode, reference, isInitialLoad) => {
14855
- {
14856
- if (typeof newNode["s-sn"] === "string") {
14857
- parent.insertBefore(newNode, reference);
14858
- const { slotNode } = findSlotFromSlottedNode(newNode);
14859
- if (slotNode && !isInitialLoad) dispatchSlotChangeEvent(slotNode);
14860
- return newNode;
14861
- }
14862
- }
14863
- if (parent.__insertBefore) {
14864
- return parent.__insertBefore(newNode, reference);
14865
- } else {
14866
14750
  return parent == null ? void 0 : parent.insertBefore(newNode, reference);
14867
14751
  }
14868
14752
  };
14869
14753
  var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
14870
- var _a, _b, _c, _d, _e;
14754
+ var _a, _b, _c, _d;
14871
14755
  const hostElm = hostRef.$hostElement$;
14872
14756
  const cmpMeta = hostRef.$cmpMeta$;
14873
14757
  const oldVNode = hostRef.$vnode$ || newVNode(null, null);
@@ -14876,11 +14760,9 @@ var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
14876
14760
  hostTagName = hostElm.tagName;
14877
14761
  if (cmpMeta.$attrsToReflect$) {
14878
14762
  rootVnode.$attrs$ = rootVnode.$attrs$ || {};
14879
- cmpMeta.$attrsToReflect$.forEach(([propName, attribute]) => {
14880
- {
14881
- rootVnode.$attrs$[attribute] = hostElm[propName];
14882
- }
14883
- });
14763
+ cmpMeta.$attrsToReflect$.map(
14764
+ ([propName, attribute]) => rootVnode.$attrs$[attribute] = hostElm[propName]
14765
+ );
14884
14766
  }
14885
14767
  if (isInitialLoad && rootVnode.$attrs$) {
14886
14768
  for (const key of Object.keys(rootVnode.$attrs$)) {
@@ -14908,27 +14790,19 @@ var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
14908
14790
  if (!nodeToRelocate["s-ol"] && win.document) {
14909
14791
  const orgLocationNode = win.document.createTextNode("");
14910
14792
  orgLocationNode["s-nr"] = nodeToRelocate;
14911
- insertBefore(
14912
- nodeToRelocate.parentNode,
14913
- nodeToRelocate["s-ol"] = orgLocationNode,
14914
- nodeToRelocate,
14915
- isInitialLoad
14916
- );
14793
+ insertBefore(nodeToRelocate.parentNode, nodeToRelocate["s-ol"] = orgLocationNode, nodeToRelocate);
14917
14794
  }
14918
14795
  }
14919
14796
  for (const relocateData of relocateNodes) {
14920
14797
  const nodeToRelocate = relocateData.$nodeToRelocate$;
14921
14798
  const slotRefNode = relocateData.$slotRefNode$;
14922
- if (nodeToRelocate.nodeType === 1 /* ElementNode */ && isInitialLoad) {
14923
- nodeToRelocate["s-ih"] = (_a = nodeToRelocate.hidden) != null ? _a : false;
14924
- }
14925
14799
  if (slotRefNode) {
14926
14800
  const parentNodeRef = slotRefNode.parentNode;
14927
14801
  let insertBeforeNode = slotRefNode.nextSibling;
14928
- if (insertBeforeNode && insertBeforeNode.nodeType === 1 /* ElementNode */) {
14929
- let orgLocationNode = (_b = nodeToRelocate["s-ol"]) == null ? void 0 : _b.previousSibling;
14802
+ {
14803
+ let orgLocationNode = (_a = nodeToRelocate["s-ol"]) == null ? void 0 : _a.previousSibling;
14930
14804
  while (orgLocationNode) {
14931
- let refNode = (_c = orgLocationNode["s-nr"]) != null ? _c : null;
14805
+ let refNode = (_b = orgLocationNode["s-nr"]) != null ? _b : null;
14932
14806
  if (refNode && refNode["s-sn"] === nodeToRelocate["s-sn"] && parentNodeRef === (refNode.__parentNode || refNode.parentNode)) {
14933
14807
  refNode = refNode.nextSibling;
14934
14808
  while (refNode === nodeToRelocate || (refNode == null ? void 0 : refNode["s-sr"])) {
@@ -14946,26 +14820,23 @@ var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
14946
14820
  const nextSibling = nodeToRelocate.__nextSibling || nodeToRelocate.nextSibling;
14947
14821
  if (!insertBeforeNode && parentNodeRef !== parent || nextSibling !== insertBeforeNode) {
14948
14822
  if (nodeToRelocate !== insertBeforeNode) {
14949
- insertBefore(parentNodeRef, nodeToRelocate, insertBeforeNode, isInitialLoad);
14950
- if (nodeToRelocate.nodeType === 8 /* CommentNode */ && nodeToRelocate.nodeValue.startsWith("s-nt-")) {
14951
- const textNode = win.document.createTextNode(nodeToRelocate.nodeValue.replace(/^s-nt-/, ""));
14952
- textNode["s-hn"] = nodeToRelocate["s-hn"];
14953
- textNode["s-sn"] = nodeToRelocate["s-sn"];
14954
- textNode["s-sh"] = nodeToRelocate["s-sh"];
14955
- textNode["s-sr"] = nodeToRelocate["s-sr"];
14956
- textNode["s-ol"] = nodeToRelocate["s-ol"];
14957
- textNode["s-ol"]["s-nr"] = textNode;
14958
- insertBefore(nodeToRelocate.parentNode, textNode, nodeToRelocate, isInitialLoad);
14959
- nodeToRelocate.parentNode.removeChild(nodeToRelocate);
14823
+ if (!nodeToRelocate["s-hn"] && nodeToRelocate["s-ol"]) {
14824
+ nodeToRelocate["s-hn"] = nodeToRelocate["s-ol"].parentNode.nodeName;
14960
14825
  }
14826
+ insertBefore(parentNodeRef, nodeToRelocate, insertBeforeNode);
14961
14827
  if (nodeToRelocate.nodeType === 1 /* ElementNode */ && nodeToRelocate.tagName !== "SLOT-FB") {
14962
- nodeToRelocate.hidden = (_d = nodeToRelocate["s-ih"]) != null ? _d : false;
14828
+ nodeToRelocate.hidden = (_c = nodeToRelocate["s-ih"]) != null ? _c : false;
14963
14829
  }
14964
14830
  }
14965
14831
  }
14966
14832
  nodeToRelocate && typeof slotRefNode["s-rf"] === "function" && slotRefNode["s-rf"](slotRefNode);
14967
- } else if (nodeToRelocate.nodeType === 1 /* ElementNode */) {
14968
- nodeToRelocate.hidden = true;
14833
+ } else {
14834
+ if (nodeToRelocate.nodeType === 1 /* ElementNode */) {
14835
+ if (isInitialLoad) {
14836
+ nodeToRelocate["s-ih"] = (_d = nodeToRelocate.hidden) != null ? _d : false;
14837
+ }
14838
+ nodeToRelocate.hidden = true;
14839
+ }
14969
14840
  }
14970
14841
  }
14971
14842
  }
@@ -14975,26 +14846,7 @@ var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
14975
14846
  plt.$flags$ &= -2 /* isTmpDisconnected */;
14976
14847
  relocateNodes.length = 0;
14977
14848
  }
14978
- if (!useNativeShadowDom && !(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) && hostElm["s-cr"]) {
14979
- const children = rootVnode.$elm$.__childNodes || rootVnode.$elm$.childNodes;
14980
- for (const childNode of children) {
14981
- if (childNode["s-hn"] !== hostTagName && !childNode["s-sh"]) {
14982
- if (isInitialLoad && childNode["s-ih"] == null) {
14983
- childNode["s-ih"] = (_e = childNode.hidden) != null ? _e : false;
14984
- }
14985
- if (childNode.nodeType === 1 /* ElementNode */) {
14986
- childNode.hidden = true;
14987
- } else if (childNode.nodeType === 3 /* TextNode */ && !!childNode.nodeValue.trim()) {
14988
- const textCommentNode = win.document.createComment("s-nt-" + childNode.nodeValue);
14989
- textCommentNode["s-sn"] = childNode["s-sn"];
14990
- insertBefore(childNode.parentNode, textCommentNode, childNode, isInitialLoad);
14991
- childNode.parentNode.removeChild(childNode);
14992
- }
14993
- }
14994
- }
14995
- }
14996
14849
  contentRef = void 0;
14997
- flushQueuedRefCallbacks();
14998
14850
  };
14999
14851
 
15000
14852
  // src/runtime/update-component.ts
@@ -15020,12 +14872,6 @@ var scheduleUpdate = (hostRef, isInitialLoad) => {
15020
14872
  }
15021
14873
  attachToAncestor(hostRef, hostRef.$ancestorComponent$);
15022
14874
  const dispatch = () => dispatchHooks(hostRef, isInitialLoad);
15023
- if (isInitialLoad) {
15024
- queueMicrotask(() => {
15025
- dispatch();
15026
- });
15027
- return;
15028
- }
15029
14875
  return writeTask(dispatch) ;
15030
14876
  };
15031
14877
  var dispatchHooks = (hostRef, isInitialLoad) => {
@@ -15040,19 +14886,10 @@ var dispatchHooks = (hostRef, isInitialLoad) => {
15040
14886
  let maybePromise;
15041
14887
  if (isInitialLoad) {
15042
14888
  {
15043
- if (hostRef.$deferredConnectedCallback$) {
15044
- hostRef.$deferredConnectedCallback$ = false;
15045
- safeCall(instance, "connectedCallback", void 0, elm);
15046
- }
15047
- {
15048
- hostRef.$flags$ |= 256 /* isListenReady */;
15049
- if (hostRef.$queuedListeners$) {
15050
- hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event, elm));
15051
- hostRef.$queuedListeners$ = void 0;
15052
- }
15053
- }
15054
- if (hostRef.$fetchedCbList$.length) {
15055
- hostRef.$fetchedCbList$.forEach((cb) => cb(elm));
14889
+ hostRef.$flags$ |= 256 /* isListenReady */;
14890
+ if (hostRef.$queuedListeners$) {
14891
+ hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event, elm));
14892
+ hostRef.$queuedListeners$ = void 0;
15056
14893
  }
15057
14894
  }
15058
14895
  maybePromise = safeCall(instance, "componentWillLoad", void 0, elm);
@@ -15063,8 +14900,8 @@ var dispatchHooks = (hostRef, isInitialLoad) => {
15063
14900
  endSchedule();
15064
14901
  return enqueue(maybePromise, () => updateComponent(hostRef, instance, isInitialLoad));
15065
14902
  };
15066
- var enqueue = (maybePromise, fn) => isPromisey(maybePromise) ? maybePromise.then(fn).catch((err) => {
15067
- console.error(err);
14903
+ var enqueue = (maybePromise, fn) => isPromisey(maybePromise) ? maybePromise.then(fn).catch((err2) => {
14904
+ console.error(err2);
15068
14905
  fn();
15069
14906
  }) : fn();
15070
14907
  var isPromisey = (maybePromise) => maybePromise instanceof Promise || maybePromise && maybePromise.then && typeof maybePromise.then === "function";
@@ -15092,7 +14929,7 @@ var updateComponent = async (hostRef, instance, isInitialLoad) => {
15092
14929
  if (childrenPromises.length === 0) {
15093
14930
  postUpdate();
15094
14931
  } else {
15095
- Promise.all(childrenPromises).then(postUpdate).catch(postUpdate);
14932
+ Promise.all(childrenPromises).then(postUpdate);
15096
14933
  hostRef.$flags$ |= 4 /* isWaitingForChildren */;
15097
14934
  childrenPromises.length = 0;
15098
14935
  }
@@ -15158,13 +14995,7 @@ var postUpdateComponent = (hostRef) => {
15158
14995
  }
15159
14996
  };
15160
14997
  var appDidLoad = (who) => {
15161
- var _a;
15162
14998
  nextTick(() => emitEvent(win, "appload", { detail: { namespace: NAMESPACE } }));
15163
- {
15164
- if ((_a = plt.$orgLocNodes$) == null ? void 0 : _a.size) {
15165
- plt.$orgLocNodes$.clear();
15166
- }
15167
- }
15168
14999
  };
15169
15000
  var safeCall = (instance, method, arg, elm) => {
15170
15001
  if (instance && instance[method]) {
@@ -15185,9 +15016,6 @@ var addHydratedFlag = (elm) => {
15185
15016
  var getValue = (ref, propName) => getHostRef(ref).$instanceValues$.get(propName);
15186
15017
  var setValue = (ref, propName, newVal, cmpMeta) => {
15187
15018
  const hostRef = getHostRef(ref);
15188
- if (!hostRef) {
15189
- return;
15190
- }
15191
15019
  if (!hostRef) {
15192
15020
  throw new Error(
15193
15021
  `Couldn't find host element for "${cmpMeta.$tagName$}" as it is unknown to this Stencil runtime. This usually happens when integrating a 3rd party Stencil component with another Stencil component or application. Please reach out to the maintainers of the 3rd party Stencil component or report this on the Stencil Discord server (https://chat.stenciljs.com) or comment on this similar [GitHub issue](https://github.com/stenciljs/core/issues/5457).`
@@ -15204,35 +15032,25 @@ var setValue = (ref, propName, newVal, cmpMeta) => {
15204
15032
  const didValueChange = newVal !== oldVal && !areBothNaN;
15205
15033
  if ((!(flags & 8 /* isConstructingInstance */) || oldVal === void 0) && didValueChange) {
15206
15034
  hostRef.$instanceValues$.set(propName, newVal);
15207
- if (cmpMeta.$watchers$) {
15208
- const watchMethods = cmpMeta.$watchers$[propName];
15209
- if (watchMethods) {
15210
- watchMethods.map((watcher) => {
15211
- try {
15212
- const [[watchMethodName, watcherFlags]] = Object.entries(watcher);
15213
- if (flags & 128 /* isWatchReady */ || watcherFlags & 1 /* Immediate */) {
15214
- if (!instance) {
15215
- hostRef.$fetchedCbList$.push(() => {
15216
- hostRef.$lazyInstance$[watchMethodName](newVal, oldVal, propName);
15217
- });
15218
- } else {
15219
- instance[watchMethodName](newVal, oldVal, propName);
15220
- }
15035
+ if (instance) {
15036
+ if (cmpMeta.$watchers$ && flags & 128 /* isWatchReady */) {
15037
+ const watchMethods = cmpMeta.$watchers$[propName];
15038
+ if (watchMethods) {
15039
+ watchMethods.map((watchMethodName) => {
15040
+ try {
15041
+ instance[watchMethodName](newVal, oldVal, propName);
15042
+ } catch (e) {
15043
+ consoleError(e, elm);
15221
15044
  }
15222
- } catch (e) {
15223
- consoleError(e, elm);
15224
- }
15225
- });
15226
- }
15227
- }
15228
- if (flags & 2 /* hasRendered */) {
15229
- if (instance.componentShouldUpdate) {
15230
- const shouldUpdate = instance.componentShouldUpdate(newVal, oldVal, propName);
15231
- if (shouldUpdate === false && !(flags & 16 /* isQueuedForUpdate */)) {
15232
- return;
15045
+ });
15233
15046
  }
15234
15047
  }
15235
- if (!(flags & 16 /* isQueuedForUpdate */)) {
15048
+ if ((flags & (2 /* hasRendered */ | 16 /* isQueuedForUpdate */)) === 2 /* hasRendered */) {
15049
+ if (instance.componentShouldUpdate) {
15050
+ if (instance.componentShouldUpdate(newVal, oldVal, propName) === false) {
15051
+ return;
15052
+ }
15053
+ }
15236
15054
  scheduleUpdate(hostRef, false);
15237
15055
  }
15238
15056
  }
@@ -15243,22 +15061,14 @@ var setValue = (ref, propName, newVal, cmpMeta) => {
15243
15061
  var proxyComponent = (Cstr, cmpMeta, flags) => {
15244
15062
  var _a, _b;
15245
15063
  const prototype = Cstr.prototype;
15246
- if (cmpMeta.$members$ || BUILD.propChangeCallback) {
15247
- {
15248
- if (Cstr.watchers && !cmpMeta.$watchers$) {
15249
- cmpMeta.$watchers$ = Cstr.watchers;
15250
- }
15251
- if (Cstr.deserializers && !cmpMeta.$deserializers$) {
15252
- cmpMeta.$deserializers$ = Cstr.deserializers;
15253
- }
15254
- if (Cstr.serializers && !cmpMeta.$serializers$) {
15255
- cmpMeta.$serializers$ = Cstr.serializers;
15256
- }
15064
+ if (cmpMeta.$members$ || (cmpMeta.$watchers$ || Cstr.watchers)) {
15065
+ if (Cstr.watchers && !cmpMeta.$watchers$) {
15066
+ cmpMeta.$watchers$ = Cstr.watchers;
15257
15067
  }
15258
15068
  const members = Object.entries((_a = cmpMeta.$members$) != null ? _a : {});
15259
15069
  members.map(([memberName, [memberFlags]]) => {
15260
15070
  if ((memberFlags & 31 /* Prop */ || (flags & 2 /* proxyState */) && memberFlags & 32 /* State */)) {
15261
- const { get: origGetter, set: origSetter } = getPropertyDescriptor(prototype, memberName) || {};
15071
+ const { get: origGetter, set: origSetter } = Object.getOwnPropertyDescriptor(prototype, memberName) || {};
15262
15072
  if (origGetter) cmpMeta.$members$[memberName][0] |= 2048 /* Getter */;
15263
15073
  if (origSetter) cmpMeta.$members$[memberName][0] |= 4096 /* Setter */;
15264
15074
  if (flags & 1 /* isElementConstructor */ || !origGetter) {
@@ -15281,13 +15091,12 @@ var proxyComponent = (Cstr, cmpMeta, flags) => {
15281
15091
  Object.defineProperty(prototype, memberName, {
15282
15092
  set(newValue) {
15283
15093
  const ref = getHostRef(this);
15284
- if (!ref) {
15285
- return;
15286
- }
15287
15094
  if (origSetter) {
15288
15095
  const currentValue = memberFlags & 32 /* State */ ? this[memberName] : ref.$hostElement$[memberName];
15289
15096
  if (typeof currentValue === "undefined" && ref.$instanceValues$.get(memberName)) {
15290
15097
  newValue = ref.$instanceValues$.get(memberName);
15098
+ } else if (!ref.$instanceValues$.get(memberName) && currentValue) {
15099
+ ref.$instanceValues$.set(memberName, currentValue);
15291
15100
  }
15292
15101
  origSetter.apply(this, [
15293
15102
  parsePropertyValue(
@@ -15302,7 +15111,7 @@ var proxyComponent = (Cstr, cmpMeta, flags) => {
15302
15111
  if ((flags & 1 /* isElementConstructor */) === 0 || (cmpMeta.$members$[memberName][0] & 4096 /* Setter */) === 0) {
15303
15112
  setValue(this, memberName, newValue, cmpMeta);
15304
15113
  if (flags & 1 /* isElementConstructor */ && !ref.$lazyInstance$) {
15305
- ref.$fetchedCbList$.push(() => {
15114
+ ref.$onReadyPromise$.then(() => {
15306
15115
  if (cmpMeta.$members$[memberName][0] & 4096 /* Setter */ && ref.$lazyInstance$[memberName] !== ref.$instanceValues$.get(memberName)) {
15307
15116
  ref.$lazyInstance$[memberName] = newValue;
15308
15117
  }
@@ -15323,9 +15132,7 @@ var proxyComponent = (Cstr, cmpMeta, flags) => {
15323
15132
  if (ref.$lazyInstance$) {
15324
15133
  setterSetVal();
15325
15134
  } else {
15326
- ref.$fetchedCbList$.push(() => {
15327
- setterSetVal();
15328
- });
15135
+ ref.$onReadyPromise$.then(() => setterSetVal());
15329
15136
  }
15330
15137
  }
15331
15138
  }
@@ -15349,34 +15156,29 @@ var proxyComponent = (Cstr, cmpMeta, flags) => {
15349
15156
  plt.jmp(() => {
15350
15157
  var _a2;
15351
15158
  const propName = attrNameToPropName.get(attrName);
15352
- const hostRef = getHostRef(this);
15353
15159
  if (this.hasOwnProperty(propName) && BUILD.lazyLoad) {
15354
15160
  newValue = this[propName];
15355
15161
  delete this[propName];
15356
- }
15357
- if (prototype.hasOwnProperty(propName) && typeof this[propName] === "number" && // cast type to number to avoid TS compiler issues
15162
+ } else if (prototype.hasOwnProperty(propName) && typeof this[propName] === "number" && // cast type to number to avoid TS compiler issues
15358
15163
  this[propName] == newValue) {
15359
15164
  return;
15360
15165
  } else if (propName == null) {
15166
+ const hostRef = getHostRef(this);
15361
15167
  const flags2 = hostRef == null ? void 0 : hostRef.$flags$;
15362
- if (hostRef && flags2 && !(flags2 & 8 /* isConstructingInstance */) && newValue !== oldValue) {
15168
+ if (flags2 && !(flags2 & 8 /* isConstructingInstance */) && flags2 & 128 /* isWatchReady */ && newValue !== oldValue) {
15363
15169
  const instance = hostRef.$lazyInstance$ ;
15364
15170
  const entry = (_a2 = cmpMeta.$watchers$) == null ? void 0 : _a2[attrName];
15365
- entry == null ? void 0 : entry.forEach((watcher) => {
15366
- const [[watchMethodName, watcherFlags]] = Object.entries(watcher);
15367
- if (instance[watchMethodName] != null && (flags2 & 128 /* isWatchReady */ || watcherFlags & 1 /* Immediate */)) {
15368
- instance[watchMethodName].call(instance, newValue, oldValue, attrName);
15171
+ entry == null ? void 0 : entry.forEach((callbackName) => {
15172
+ if (instance[callbackName] != null) {
15173
+ instance[callbackName].call(instance, newValue, oldValue, attrName);
15369
15174
  }
15370
15175
  });
15371
15176
  }
15372
15177
  return;
15373
15178
  }
15374
- const propFlags = members.find(([m]) => m === propName);
15375
- if (propFlags && propFlags[1][0] & 4 /* Boolean */) {
15376
- newValue = newValue === null || newValue === "false" ? false : true;
15377
- }
15378
15179
  const propDesc = Object.getOwnPropertyDescriptor(prototype, propName);
15379
- if (newValue != this[propName] && (!propDesc.get || !!propDesc.set)) {
15180
+ newValue = newValue === null && typeof this[propName] === "boolean" ? false : newValue;
15181
+ if (newValue !== this[propName] && (!propDesc.get || !!propDesc.set)) {
15380
15182
  this[propName] = newValue;
15381
15183
  }
15382
15184
  });
@@ -15384,7 +15186,7 @@ var proxyComponent = (Cstr, cmpMeta, flags) => {
15384
15186
  Cstr.observedAttributes = Array.from(
15385
15187
  /* @__PURE__ */ new Set([
15386
15188
  ...Object.keys((_b = cmpMeta.$watchers$) != null ? _b : {}),
15387
- ...members.filter(([_, m]) => m[0] & 31 /* HasAttribute */).map(([propName, m]) => {
15189
+ ...members.filter(([_, m]) => m[0] & 15 /* HasAttribute */).map(([propName, m]) => {
15388
15190
  var _a2;
15389
15191
  const attrName = m[1] || propName;
15390
15192
  attrNameToPropName.set(attrName, propName);
@@ -15403,88 +15205,70 @@ var proxyComponent = (Cstr, cmpMeta, flags) => {
15403
15205
  // src/runtime/initialize-component.ts
15404
15206
  var initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId) => {
15405
15207
  let Cstr;
15406
- try {
15407
- if ((hostRef.$flags$ & 32 /* hasInitializedComponent */) === 0) {
15408
- hostRef.$flags$ |= 32 /* hasInitializedComponent */;
15409
- const bundleId = cmpMeta.$lazyBundleId$;
15410
- if (bundleId) {
15411
- const CstrImport = loadModule(cmpMeta, hostRef);
15412
- if (CstrImport && "then" in CstrImport) {
15413
- const endLoad = uniqueTime();
15414
- Cstr = await CstrImport;
15415
- endLoad();
15416
- } else {
15417
- Cstr = CstrImport;
15418
- }
15419
- if (!Cstr) {
15420
- throw new Error(`Constructor for "${cmpMeta.$tagName$}#${hostRef.$modeName$}" was not found`);
15421
- }
15422
- if (!Cstr.isProxied) {
15423
- {
15424
- cmpMeta.$watchers$ = Cstr.watchers;
15425
- cmpMeta.$serializers$ = Cstr.serializers;
15426
- cmpMeta.$deserializers$ = Cstr.deserializers;
15427
- }
15428
- proxyComponent(Cstr, cmpMeta, 2 /* proxyState */);
15429
- Cstr.isProxied = true;
15430
- }
15431
- const endNewInstance = createTime("createInstance", cmpMeta.$tagName$);
15432
- {
15433
- hostRef.$flags$ |= 8 /* isConstructingInstance */;
15434
- }
15435
- try {
15436
- new Cstr(hostRef);
15437
- } catch (e) {
15438
- consoleError(e, elm);
15439
- }
15440
- {
15441
- hostRef.$flags$ &= -9 /* isConstructingInstance */;
15442
- }
15443
- {
15444
- hostRef.$flags$ |= 128 /* isWatchReady */;
15445
- }
15446
- endNewInstance();
15447
- const needsDeferredCallback = cmpMeta.$flags$ & 4 /* hasSlotRelocation */;
15448
- if (!needsDeferredCallback) {
15449
- fireConnectedCallback(hostRef.$lazyInstance$, elm);
15450
- } else {
15451
- hostRef.$deferredConnectedCallback$ = true;
15452
- }
15208
+ if ((hostRef.$flags$ & 32 /* hasInitializedComponent */) === 0) {
15209
+ hostRef.$flags$ |= 32 /* hasInitializedComponent */;
15210
+ const bundleId = cmpMeta.$lazyBundleId$;
15211
+ if (bundleId) {
15212
+ const CstrImport = loadModule(cmpMeta, hostRef);
15213
+ if (CstrImport && "then" in CstrImport) {
15214
+ const endLoad = uniqueTime();
15215
+ Cstr = await CstrImport;
15216
+ endLoad();
15453
15217
  } else {
15454
- Cstr = elm.constructor;
15455
- const cmpTag = elm.localName;
15456
- customElements.whenDefined(cmpTag).then(() => hostRef.$flags$ |= 128 /* isWatchReady */);
15218
+ Cstr = CstrImport;
15457
15219
  }
15458
- if (Cstr && Cstr.style) {
15459
- let style;
15460
- if (typeof Cstr.style === "string") {
15461
- style = Cstr.style;
15462
- }
15463
- const scopeId2 = getScopeId(cmpMeta);
15464
- if (!styles.has(scopeId2) || BUILD.hotModuleReplacement) {
15465
- const endRegisterStyles = createTime("registerStyles", cmpMeta.$tagName$);
15466
- registerStyle(scopeId2, style, !!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */));
15467
- endRegisterStyles();
15220
+ if (!Cstr) {
15221
+ throw new Error(`Constructor for "${cmpMeta.$tagName$}#${hostRef.$modeName$}" was not found`);
15222
+ }
15223
+ if (!Cstr.isProxied) {
15224
+ {
15225
+ cmpMeta.$watchers$ = Cstr.watchers;
15468
15226
  }
15227
+ proxyComponent(Cstr, cmpMeta, 2 /* proxyState */);
15228
+ Cstr.isProxied = true;
15469
15229
  }
15470
- }
15471
- const ancestorComponent = hostRef.$ancestorComponent$;
15472
- const schedule = () => scheduleUpdate(hostRef, true);
15473
- if (ancestorComponent && ancestorComponent["s-rc"]) {
15474
- ancestorComponent["s-rc"].push(schedule);
15230
+ const endNewInstance = createTime("createInstance", cmpMeta.$tagName$);
15231
+ {
15232
+ hostRef.$flags$ |= 8 /* isConstructingInstance */;
15233
+ }
15234
+ try {
15235
+ new Cstr(hostRef);
15236
+ } catch (e) {
15237
+ consoleError(e, elm);
15238
+ }
15239
+ {
15240
+ hostRef.$flags$ &= -9 /* isConstructingInstance */;
15241
+ }
15242
+ {
15243
+ hostRef.$flags$ |= 128 /* isWatchReady */;
15244
+ }
15245
+ endNewInstance();
15246
+ fireConnectedCallback(hostRef.$lazyInstance$, elm);
15475
15247
  } else {
15476
- schedule();
15477
- }
15478
- } catch (e) {
15479
- consoleError(e, elm);
15480
- if (hostRef.$onRenderResolve$) {
15481
- hostRef.$onRenderResolve$();
15482
- hostRef.$onRenderResolve$ = void 0;
15483
- }
15484
- if (hostRef.$onReadyResolve$) {
15485
- hostRef.$onReadyResolve$(elm);
15248
+ Cstr = elm.constructor;
15249
+ const cmpTag = elm.localName;
15250
+ customElements.whenDefined(cmpTag).then(() => hostRef.$flags$ |= 128 /* isWatchReady */);
15251
+ }
15252
+ if (Cstr && Cstr.style) {
15253
+ let style;
15254
+ if (typeof Cstr.style === "string") {
15255
+ style = Cstr.style;
15256
+ }
15257
+ const scopeId2 = getScopeId(cmpMeta);
15258
+ if (!styles.has(scopeId2)) {
15259
+ const endRegisterStyles = createTime("registerStyles", cmpMeta.$tagName$);
15260
+ registerStyle(scopeId2, style, !!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */));
15261
+ endRegisterStyles();
15262
+ }
15486
15263
  }
15487
15264
  }
15265
+ const ancestorComponent = hostRef.$ancestorComponent$;
15266
+ const schedule = () => scheduleUpdate(hostRef, true);
15267
+ if (ancestorComponent && ancestorComponent["s-rc"]) {
15268
+ ancestorComponent["s-rc"].push(schedule);
15269
+ } else {
15270
+ schedule();
15271
+ }
15488
15272
  };
15489
15273
  var fireConnectedCallback = (instance, elm) => {
15490
15274
  {
@@ -15496,9 +15280,6 @@ var fireConnectedCallback = (instance, elm) => {
15496
15280
  var connectedCallback = (elm) => {
15497
15281
  if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) {
15498
15282
  const hostRef = getHostRef(elm);
15499
- if (!hostRef) {
15500
- return;
15501
- }
15502
15283
  const cmpMeta = hostRef.$cmpMeta$;
15503
15284
  const endConnected = createTime("connectedCallback", cmpMeta.$tagName$);
15504
15285
  if (!(hostRef.$flags$ & 1 /* hasConnected */)) {
@@ -15531,7 +15312,7 @@ var connectedCallback = (elm) => {
15531
15312
  }
15532
15313
  if (cmpMeta.$members$) {
15533
15314
  Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => {
15534
- if (memberFlags & 31 /* Prop */ && Object.prototype.hasOwnProperty.call(elm, memberName)) {
15315
+ if (memberFlags & 31 /* Prop */ && elm.hasOwnProperty(memberName)) {
15535
15316
  const value = elm[memberName];
15536
15317
  delete elm[memberName];
15537
15318
  elm[memberName] = value;
@@ -15571,7 +15352,7 @@ var disconnectedCallback = async (elm) => {
15571
15352
  if ((plt.$flags$ & 1 /* isTmpDisconnected */) === 0) {
15572
15353
  const hostRef = getHostRef(elm);
15573
15354
  {
15574
- if (hostRef == null ? void 0 : hostRef.$rmListeners$) {
15355
+ if (hostRef.$rmListeners$) {
15575
15356
  hostRef.$rmListeners$.map((rmListener) => rmListener());
15576
15357
  hostRef.$rmListeners$ = void 0;
15577
15358
  }
@@ -15618,7 +15399,7 @@ var bootstrapLazy = (lazyBundles, options = {}) => {
15618
15399
  let hasSlotRelocation = false;
15619
15400
  lazyBundles.map((lazyBundle) => {
15620
15401
  lazyBundle[1].map((compactMeta) => {
15621
- var _a2, _b, _c;
15402
+ var _a2;
15622
15403
  const cmpMeta = {
15623
15404
  $flags$: compactMeta[0],
15624
15405
  $tagName$: compactMeta[1],
@@ -15639,17 +15420,13 @@ var bootstrapLazy = (lazyBundles, options = {}) => {
15639
15420
  }
15640
15421
  {
15641
15422
  cmpMeta.$watchers$ = (_a2 = compactMeta[4]) != null ? _a2 : {};
15642
- cmpMeta.$serializers$ = (_b = compactMeta[5]) != null ? _b : {};
15643
- cmpMeta.$deserializers$ = (_c = compactMeta[6]) != null ? _c : {};
15644
15423
  }
15645
- const tagName = transformTag(cmpMeta.$tagName$);
15424
+ const tagName = cmpMeta.$tagName$;
15646
15425
  const HostElement = class extends HTMLElement {
15647
- ["s-p"];
15648
- ["s-rc"];
15649
- hasRegisteredEventListeners = false;
15650
15426
  // StencilLazyHost
15651
15427
  constructor(self) {
15652
15428
  super(self);
15429
+ this.hasRegisteredEventListeners = false;
15653
15430
  self = this;
15654
15431
  registerHost(self, cmpMeta);
15655
15432
  if (cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) {
@@ -15668,9 +15445,6 @@ var bootstrapLazy = (lazyBundles, options = {}) => {
15668
15445
  }
15669
15446
  connectedCallback() {
15670
15447
  const hostRef = getHostRef(this);
15671
- if (!hostRef) {
15672
- return;
15673
- }
15674
15448
  if (!this.hasRegisteredEventListeners) {
15675
15449
  this.hasRegisteredEventListeners = true;
15676
15450
  addHostEventListeners(this, hostRef, cmpMeta.$listeners$);
@@ -15690,9 +15464,6 @@ var bootstrapLazy = (lazyBundles, options = {}) => {
15690
15464
  plt.raf(() => {
15691
15465
  var _a3;
15692
15466
  const hostRef = getHostRef(this);
15693
- if (!hostRef) {
15694
- return;
15695
- }
15696
15467
  const i2 = deferredConnectedCallbacks.findIndex((host) => host === this);
15697
15468
  if (i2 > -1) {
15698
15469
  deferredConnectedCallbacks.splice(i2, 1);
@@ -15703,8 +15474,7 @@ var bootstrapLazy = (lazyBundles, options = {}) => {
15703
15474
  });
15704
15475
  }
15705
15476
  componentOnReady() {
15706
- var _a3;
15707
- return (_a3 = getHostRef(this)) == null ? void 0 : _a3.$onReadyPromise$;
15477
+ return getHostRef(this).$onReadyPromise$;
15708
15478
  }
15709
15479
  };
15710
15480
  cmpMeta.$lazyBundleId$ = lazyBundle[0];
@@ -15787,8 +15557,5 @@ var hostListenerOpts = (flags) => supportsListenerOptions ? {
15787
15557
 
15788
15558
  // src/runtime/nonce.ts
15789
15559
  var setNonce = (nonce) => plt.$nonce$ = nonce;
15790
- function transformTag(tag) {
15791
- return tag;
15792
- }
15793
15560
 
15794
- export { Fragment as F, Host as H, LazyLoad as L, getDefaultExportFromCjs as a, bootstrapLazy as b, createEvent as c, axios as d, require_root as e, requireIsObject as f, getElement as g, h, requireIsSymbol as i, promiseResolve as p, registerInstance as r, setNonce as s };
15561
+ export { Fragment as F, Host as H, getElement as a, bootstrapLazy as b, createEvent as c, getDefaultExportFromCjs as d, axios as e, require_root as f, globalScripts as g, h, requireIsObject as i, requireIsSymbol as j, promiseResolve as p, registerInstance as r, setNonce as s };