@salla.sa/twilight-components 2.14.367 → 2.14.368
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.
- package/dist/cjs/{filepond-Dc4v9nRQ.js → filepond-BFZbLcs9.js} +1 -1
- package/dist/cjs/{filepond-plugin-file-poster-D580mHPz.js → filepond-plugin-file-poster-j5N_wxed.js} +1 -1
- package/dist/cjs/{filepond-plugin-file-validate-size-CirPDkJ5.js → filepond-plugin-file-validate-size-C4fE0LiJ.js} +1 -1
- package/dist/cjs/{filepond-plugin-file-validate-type-DlzM2hzF.js → filepond-plugin-file-validate-type-K4KCyB8B.js} +1 -1
- package/dist/cjs/{filepond-plugin-image-edit-C-V0_34D.js → filepond-plugin-image-edit-BPQKyMc5.js} +1 -1
- package/dist/cjs/{filepond-plugin-image-exif-orientation-BzOSGmgz.js → filepond-plugin-image-exif-orientation-Bqc0A8tM.js} +1 -1
- package/dist/cjs/{filepond-plugin-image-preview-DPPccyO8.js → filepond-plugin-image-preview-CWUeJfUC.js} +1 -1
- package/dist/cjs/{index-B-3J2UiO.js → index-57tdmUta.js} +1 -1
- package/dist/cjs/{index-C4FIMuo-.js → index-BbnigMiZ.js} +2 -2
- package/dist/cjs/loader.cjs.js +1 -1
- package/dist/cjs/salla-accordion-body_3.cjs.entry.js +1 -1
- package/dist/cjs/salla-accordion_6.cjs.entry.js +1 -1
- package/dist/cjs/salla-add-product-button_4.cjs.entry.js +1 -1
- package/dist/cjs/salla-advertisement.cjs.entry.js +1 -1
- package/dist/cjs/salla-alert_2.cjs.entry.js +1 -1
- package/dist/cjs/salla-app-install-alert.cjs.entry.js +1 -1
- package/dist/cjs/salla-apps-icons.cjs.entry.js +1 -1
- package/dist/cjs/salla-booking-field_7.cjs.entry.js +10 -10
- package/dist/cjs/salla-cart-item-offers_2.cjs.entry.js +1 -1
- package/dist/cjs/salla-comment-form_8.cjs.entry.js +1 -1
- package/dist/cjs/salla-conditional-offer.cjs.entry.js +1 -1
- package/dist/cjs/salla-contacts.cjs.entry.js +1 -1
- package/dist/cjs/salla-cookies-bar.cjs.entry.js +2 -2
- package/dist/cjs/salla-count-down_2.cjs.entry.js +1 -1
- package/dist/cjs/salla-custom-fields.cjs.entry.js +1 -1
- package/dist/cjs/salla-filters-widget.cjs.entry.js +1 -1
- package/dist/cjs/salla-filters.cjs.entry.js +1 -1
- package/dist/cjs/salla-gifting.cjs.entry.js +1 -1
- package/dist/cjs/salla-hook.cjs.entry.js +1 -1
- package/dist/cjs/salla-infinite-scroll.cjs.entry.js +1 -1
- package/dist/cjs/salla-installment.cjs.entry.js +1 -1
- package/dist/cjs/salla-list-tile.cjs.entry.js +1 -1
- package/dist/cjs/salla-localization-modal.cjs.entry.js +1 -1
- package/dist/cjs/salla-login-modal.cjs.entry.js +1 -1
- package/dist/cjs/salla-loyalty-prize-item.cjs.entry.js +1 -1
- package/dist/cjs/salla-loyalty-program.cjs.entry.js +1 -1
- package/dist/cjs/salla-loyalty.cjs.entry.js +1 -1
- package/dist/cjs/salla-maintenance-alert.cjs.entry.js +1 -1
- package/dist/cjs/salla-menu.cjs.entry.js +1 -1
- package/dist/cjs/salla-metadata.cjs.entry.js +1 -1
- package/dist/cjs/salla-multiple-bundle-product-cart_2.cjs.entry.js +1 -1
- package/dist/cjs/salla-multiple-bundle-product-options-modal_2.cjs.entry.js +1 -1
- package/dist/cjs/salla-multiple-bundle-product.cjs.entry.js +1 -1
- package/dist/cjs/salla-notification-item.cjs.entry.js +1 -1
- package/dist/cjs/salla-notifications.cjs.entry.js +1 -1
- package/dist/cjs/salla-offer-modal.cjs.entry.js +1 -1
- package/dist/cjs/salla-offer.cjs.entry.js +1 -1
- package/dist/cjs/salla-order-details-multiple-bundle-product.cjs.entry.js +1 -1
- package/dist/cjs/salla-order-details-options.cjs.entry.js +1 -1
- package/dist/cjs/salla-order-details.cjs.entry.js +1 -1
- package/dist/cjs/salla-order-summary.cjs.entry.js +1 -1
- package/dist/cjs/salla-order-totals-card.cjs.entry.js +1 -1
- package/dist/cjs/salla-orders.cjs.entry.js +1 -1
- package/dist/cjs/salla-payments.cjs.entry.js +1 -1
- package/dist/cjs/salla-placeholder.cjs.entry.js +1 -1
- package/dist/cjs/salla-price-range.cjs.entry.js +1 -1
- package/dist/cjs/salla-product-size-guide.cjs.entry.js +1 -1
- package/dist/cjs/salla-products-list.cjs.entry.js +1 -1
- package/dist/cjs/salla-products-slider.cjs.entry.js +1 -1
- package/dist/cjs/salla-progress-bar.cjs.entry.js +1 -1
- package/dist/cjs/salla-quick-order.cjs.entry.js +1 -1
- package/dist/cjs/salla-rating-modal.cjs.entry.js +1 -1
- package/dist/cjs/salla-scopes.cjs.entry.js +1 -1
- package/dist/cjs/salla-search.cjs.entry.js +1 -1
- package/dist/cjs/salla-skeleton.cjs.entry.js +1 -1
- package/dist/cjs/salla-slider.cjs.entry.js +1 -1
- package/dist/cjs/salla-social-share.cjs.entry.js +1 -1
- package/dist/cjs/salla-social.cjs.entry.js +1 -1
- package/dist/cjs/salla-tab-content_3.cjs.entry.js +1 -1
- package/dist/cjs/salla-tiered-offer.cjs.entry.js +1 -1
- package/dist/cjs/salla-tooltip.cjs.entry.js +1 -1
- package/dist/cjs/salla-trust-badges.cjs.entry.js +1 -1
- package/dist/cjs/salla-user-menu.cjs.entry.js +1 -1
- package/dist/cjs/salla-user-profile.cjs.entry.js +1 -1
- package/dist/cjs/salla-user-settings.cjs.entry.js +1 -1
- package/dist/cjs/salla-verify.cjs.entry.js +1 -1
- package/dist/cjs/salla-wallet.cjs.entry.js +1 -1
- package/dist/cjs/twilight.cjs.js +1 -1
- package/dist/cjs/{vanilla-picker-wB5YeUXb.js → vanilla-picker-DVyFh2bj.js} +1 -1
- package/dist/collection/components/salla-cookies-bar/salla-cookies-bar.js +1 -1
- package/dist/components/index.js +2 -2
- package/dist/components/salla-cookies-bar.js +1 -1
- package/dist/esm/{filepond-Pk5LWGeG.js → filepond-13fnFppb.js} +1 -1
- package/dist/esm/{filepond-plugin-file-poster-BtFMoeoX.js → filepond-plugin-file-poster-BpvS4tvR.js} +1 -1
- package/dist/esm/{filepond-plugin-file-validate-size-BxrR9h6P.js → filepond-plugin-file-validate-size-D5_uYEwO.js} +1 -1
- package/dist/esm/{filepond-plugin-file-validate-type-BwgatLbq.js → filepond-plugin-file-validate-type-BL4ft-S-.js} +1 -1
- package/dist/esm/{filepond-plugin-image-edit-D5zXSV7g.js → filepond-plugin-image-edit-B1N2m-gK.js} +1 -1
- package/dist/esm/{filepond-plugin-image-exif-orientation-DCrpf9GE.js → filepond-plugin-image-exif-orientation-3XnkO1Od.js} +1 -1
- package/dist/esm/{filepond-plugin-image-preview-B67SPp2M.js → filepond-plugin-image-preview-B5KuY0qu.js} +1 -1
- package/dist/esm/{index-MNn-Ef4U.js → index-Cb4vp5Dk.js} +1 -1
- package/dist/esm/{index-ea1dIZhh.js → index-Y6CiunLU.js} +2 -2
- package/dist/esm/loader.js +2 -2
- package/dist/esm/salla-accordion-body_3.entry.js +1 -1
- package/dist/esm/salla-accordion_6.entry.js +1 -1
- package/dist/esm/salla-add-product-button_4.entry.js +1 -1
- package/dist/esm/salla-advertisement.entry.js +1 -1
- package/dist/esm/salla-alert_2.entry.js +1 -1
- package/dist/esm/salla-app-install-alert.entry.js +1 -1
- package/dist/esm/salla-apps-icons.entry.js +1 -1
- package/dist/esm/salla-booking-field_7.entry.js +10 -10
- package/dist/esm/salla-cart-item-offers_2.entry.js +1 -1
- package/dist/esm/salla-comment-form_8.entry.js +1 -1
- package/dist/esm/salla-conditional-offer.entry.js +1 -1
- package/dist/esm/salla-contacts.entry.js +1 -1
- package/dist/esm/salla-cookies-bar.entry.js +2 -2
- package/dist/esm/salla-count-down_2.entry.js +1 -1
- package/dist/esm/salla-custom-fields.entry.js +1 -1
- package/dist/esm/salla-filters-widget.entry.js +1 -1
- package/dist/esm/salla-filters.entry.js +1 -1
- package/dist/esm/salla-gifting.entry.js +1 -1
- package/dist/esm/salla-hook.entry.js +1 -1
- package/dist/esm/salla-infinite-scroll.entry.js +1 -1
- package/dist/esm/salla-installment.entry.js +1 -1
- package/dist/esm/salla-list-tile.entry.js +1 -1
- package/dist/esm/salla-localization-modal.entry.js +1 -1
- package/dist/esm/salla-login-modal.entry.js +1 -1
- package/dist/esm/salla-loyalty-prize-item.entry.js +1 -1
- package/dist/esm/salla-loyalty-program.entry.js +1 -1
- package/dist/esm/salla-loyalty.entry.js +1 -1
- package/dist/esm/salla-maintenance-alert.entry.js +1 -1
- package/dist/esm/salla-menu.entry.js +1 -1
- package/dist/esm/salla-metadata.entry.js +1 -1
- package/dist/esm/salla-multiple-bundle-product-cart_2.entry.js +1 -1
- package/dist/esm/salla-multiple-bundle-product-options-modal_2.entry.js +1 -1
- package/dist/esm/salla-multiple-bundle-product.entry.js +1 -1
- package/dist/esm/salla-notification-item.entry.js +1 -1
- package/dist/esm/salla-notifications.entry.js +1 -1
- package/dist/esm/salla-offer-modal.entry.js +1 -1
- package/dist/esm/salla-offer.entry.js +1 -1
- package/dist/esm/salla-order-details-multiple-bundle-product.entry.js +1 -1
- package/dist/esm/salla-order-details-options.entry.js +1 -1
- package/dist/esm/salla-order-details.entry.js +1 -1
- package/dist/esm/salla-order-summary.entry.js +1 -1
- package/dist/esm/salla-order-totals-card.entry.js +1 -1
- package/dist/esm/salla-orders.entry.js +1 -1
- package/dist/esm/salla-payments.entry.js +1 -1
- package/dist/esm/salla-placeholder.entry.js +1 -1
- package/dist/esm/salla-price-range.entry.js +1 -1
- package/dist/esm/salla-product-size-guide.entry.js +1 -1
- package/dist/esm/salla-products-list.entry.js +1 -1
- package/dist/esm/salla-products-slider.entry.js +1 -1
- package/dist/esm/salla-progress-bar.entry.js +1 -1
- package/dist/esm/salla-quick-order.entry.js +1 -1
- package/dist/esm/salla-rating-modal.entry.js +1 -1
- package/dist/esm/salla-scopes.entry.js +1 -1
- package/dist/esm/salla-search.entry.js +1 -1
- package/dist/esm/salla-skeleton.entry.js +1 -1
- package/dist/esm/salla-slider.entry.js +1 -1
- package/dist/esm/salla-social-share.entry.js +1 -1
- package/dist/esm/salla-social.entry.js +1 -1
- package/dist/esm/salla-tab-content_3.entry.js +1 -1
- package/dist/esm/salla-tiered-offer.entry.js +1 -1
- package/dist/esm/salla-tooltip.entry.js +1 -1
- package/dist/esm/salla-trust-badges.entry.js +1 -1
- package/dist/esm/salla-user-menu.entry.js +1 -1
- package/dist/esm/salla-user-profile.entry.js +1 -1
- package/dist/esm/salla-user-settings.entry.js +1 -1
- package/dist/esm/salla-verify.entry.js +1 -1
- package/dist/esm/salla-wallet.entry.js +1 -1
- package/dist/esm/twilight.js +2 -2
- package/dist/esm/{vanilla-picker-DyzYo4Sm.js → vanilla-picker-B7piONfC.js} +1 -1
- package/dist/twilight/{p-50ddd8ae.entry.js → p-00265d7c.entry.js} +1 -1
- package/dist/twilight/{p-3f39afe0.entry.js → p-072f71c3.entry.js} +1 -1
- package/dist/twilight/{p-3240a1fe.entry.js → p-0862caad.entry.js} +1 -1
- package/dist/twilight/{p-0b51caa0.entry.js → p-0a074662.entry.js} +1 -1
- package/dist/twilight/{p-36566eca.entry.js → p-0a9a6df5.entry.js} +1 -1
- package/dist/twilight/{p-fb93477b.entry.js → p-0d4b87c7.entry.js} +1 -1
- package/dist/twilight/{p-57b7835d.entry.js → p-133743ba.entry.js} +1 -1
- package/dist/twilight/{p-28faa620.entry.js → p-13ad1a43.entry.js} +1 -1
- package/dist/twilight/{p-47521f54.entry.js → p-17011d71.entry.js} +1 -1
- package/dist/twilight/{p-d3b0bd92.entry.js → p-1e59d6df.entry.js} +1 -1
- package/dist/twilight/{p-25787405.entry.js → p-2038c995.entry.js} +1 -1
- package/dist/twilight/{p-b06335bd.entry.js → p-25daa921.entry.js} +1 -1
- package/dist/twilight/{p-0f2acbdc.entry.js → p-274b59eb.entry.js} +1 -1
- package/dist/twilight/{p-99addee2.entry.js → p-29fd4524.entry.js} +1 -1
- package/dist/twilight/{p-48cf39b8.entry.js → p-2a26fb24.entry.js} +1 -1
- package/dist/twilight/{p-4db7b9b8.entry.js → p-2f6f0743.entry.js} +1 -1
- package/dist/twilight/{p-39b426d2.entry.js → p-33d68882.entry.js} +1 -1
- package/dist/twilight/{p-74fec1e4.entry.js → p-38fcc532.entry.js} +1 -1
- package/dist/twilight/{p-584a2bcc.entry.js → p-3e24955a.entry.js} +1 -1
- package/dist/twilight/{p-ee2501d9.entry.js → p-46a1466d.entry.js} +1 -1
- package/dist/twilight/{p-93441a3d.entry.js → p-4dc533c9.entry.js} +1 -1
- package/dist/twilight/{p-4964523f.entry.js → p-4f36d6a1.entry.js} +1 -1
- package/dist/twilight/{p-d9741316.entry.js → p-5073fed9.entry.js} +1 -1
- package/dist/twilight/{p-2ff31dfc.entry.js → p-50ec770f.entry.js} +1 -1
- package/dist/twilight/{p-bad606d7.entry.js → p-51679569.entry.js} +1 -1
- package/dist/twilight/{p-afb766ef.entry.js → p-52f4eb31.entry.js} +1 -1
- package/dist/twilight/{p-a92b3c77.entry.js → p-540f44e1.entry.js} +1 -1
- package/dist/twilight/{p-b3152bd4.entry.js → p-56b5e580.entry.js} +1 -1
- package/dist/twilight/{p-ea41c97a.entry.js → p-59677d68.entry.js} +1 -1
- package/dist/twilight/{p-034d8a67.entry.js → p-5ba1da41.entry.js} +1 -1
- package/dist/twilight/{p-0eb1f375.entry.js → p-5bb6b939.entry.js} +1 -1
- package/dist/twilight/{p-25589361.entry.js → p-5fa668d1.entry.js} +1 -1
- package/dist/twilight/{p-0b3261ac.entry.js → p-6066a33d.entry.js} +1 -1
- package/dist/twilight/{p-f66c013f.entry.js → p-69884c12.entry.js} +1 -1
- package/dist/twilight/{p-c481f4a2.entry.js → p-6eb3185b.entry.js} +1 -1
- package/dist/twilight/{p-dbf28d24.entry.js → p-72c6ea67.entry.js} +1 -1
- package/dist/twilight/{p-645c1083.entry.js → p-7389553b.entry.js} +1 -1
- package/dist/twilight/{p-a591946d.entry.js → p-7a197371.entry.js} +1 -1
- package/dist/twilight/{p-7cbebd14.entry.js → p-85229513.entry.js} +1 -1
- package/dist/twilight/{p-c5b4e65a.entry.js → p-87756e85.entry.js} +1 -1
- package/dist/twilight/{p-cb605a9e.entry.js → p-8a287dfe.entry.js} +1 -1
- package/dist/twilight/{p-eef758b0.entry.js → p-8cd21001.entry.js} +1 -1
- package/dist/twilight/p-9272011d.entry.js +4 -0
- package/dist/twilight/{p-99bcb8d4.entry.js → p-9b8ab958.entry.js} +1 -1
- package/dist/twilight/{p-Cd7SQKFA.js → p-BCiXbXPf.js} +1 -1
- package/dist/twilight/{p-DMwKr6kA.js → p-BET_97_b.js} +1 -1
- package/dist/twilight/{p-BTSNi4-Y.js → p-Bcx5sYnZ.js} +1 -1
- package/dist/twilight/{p-LocYOzht.js → p-C0K8EiG4.js} +1 -1
- package/dist/twilight/{p-yvU70SQX.js → p-DcT7j_au.js} +1 -1
- package/dist/twilight/{p-Bv6jrsv_.js → p-Dwd0nl0N.js} +1 -1
- package/dist/twilight/p-E4Drg2mm.js +9 -0
- package/dist/twilight/{p-ea1dIZhh.js → p-Y6CiunLU.js} +1 -1
- package/dist/twilight/{p-064c2b11.entry.js → p-a396686e.entry.js} +1 -1
- package/dist/twilight/{p-49eedd45.entry.js → p-a5341e29.entry.js} +1 -1
- package/dist/twilight/{p-e7cd6030.entry.js → p-a5ed9268.entry.js} +1 -1
- package/dist/twilight/{p-a7a6c8ad.entry.js → p-a767c83d.entry.js} +1 -1
- package/dist/twilight/{p-74445a67.entry.js → p-af6d37b9.entry.js} +1 -1
- package/dist/twilight/{p-7b4b2370.entry.js → p-b10a5dc1.entry.js} +1 -1
- package/dist/twilight/{p-b870e878.entry.js → p-b1cd84e9.entry.js} +1 -1
- package/dist/twilight/{p-d56efab2.entry.js → p-b323bd9c.entry.js} +1 -1
- package/dist/twilight/{p-3a82f07b.entry.js → p-b5aecb9b.entry.js} +1 -1
- package/dist/twilight/{p-c48d8192.entry.js → p-ba808f52.entry.js} +1 -1
- package/dist/twilight/{p-c045c6b1.entry.js → p-badcbdcf.entry.js} +1 -1
- package/dist/twilight/{p-b053fe1e.entry.js → p-cfa0b892.entry.js} +1 -1
- package/dist/twilight/{p-7d9e3567.entry.js → p-d1fe1003.entry.js} +1 -1
- package/dist/twilight/{p-bf3ffab6.entry.js → p-da81ede0.entry.js} +1 -1
- package/dist/twilight/{p-9aaa0b02.entry.js → p-db9eaba1.entry.js} +1 -1
- package/dist/twilight/{p-c3b046bc.entry.js → p-e7ceddca.entry.js} +1 -1
- package/dist/twilight/{p-089a72be.entry.js → p-ea031fc5.entry.js} +1 -1
- package/dist/twilight/{p-fcebbb86.entry.js → p-ecdc4cd6.entry.js} +1 -1
- package/dist/twilight/{p-BpRlzPzg.js → p-edeim4q7.js} +1 -1
- package/dist/twilight/{p-4719199c.entry.js → p-ee25eb47.entry.js} +1 -1
- package/dist/twilight/{p-c3351b4c.entry.js → p-f1964ad5.entry.js} +1 -1
- package/dist/twilight/{p-d2ce1566.entry.js → p-f49e71c7.entry.js} +1 -1
- package/dist/twilight/{p-443034a4.entry.js → p-f75d4e9b.entry.js} +1 -1
- package/dist/twilight/{p-a6c6f400.entry.js → p-fc6cf914.entry.js} +1 -1
- package/dist/twilight/{p-CDyCpF-q.js → p-zW4iqu6h.js} +1 -1
- package/dist/twilight/twilight.esm.js +1 -1
- package/package.json +5 -5
- package/dist/twilight/p-9a20af32.entry.js +0 -4
- package/dist/twilight/p-C_5WDzkV.js +0 -9
|
@@ -4021,7 +4021,7 @@ var a$4 = /*#__PURE__*/_mergeNamespaces({
|
|
|
4021
4021
|
default: memoryStorage
|
|
4022
4022
|
}, [memoryStorageExports]);
|
|
4023
4023
|
|
|
4024
|
-
function s$1(t,e){ void 0===e&&(e=false),t+="";for(var r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],o=["0","1","2","3","4","5","6","7","8","9"],i=(e=e||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:o,a=e?o:n,s=0;s<i.length;s++)r=new RegExp(i[s],"g"),t=t.replace(r,a[s]);return t.replace(e?"٫":".",e?".":"٫")}function l$2(t){var e=("".concat(t).match(/\./g)||[]).length;return e&&1!==e?l$2(t.replace(/\.(.+)\./g,".$1")):t}function c$3(t){return "".concat(t).startsWith("https://")||"".concat(t).startsWith("http://")}function u$3(t){if(c$3(t))return t;var e=Salla.config.get("store.url");return e||(e=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",e)),e.rtrim("/")+"/"+(null==t?void 0:t.ltrim("/"))}function p$1(t,e,r){if(r=r||window.location.href,!e||!t)return r;var n=new RegExp("([?&])"+t+"=[^&]+[&]?","g");return (r=r.replace(n,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+t+"="+encodeURIComponent(e)).replace(/&$|\?$/,"")}function f$2(t){return window.location.origin+"/"+(null==t?void 0:t.ltrim("/"))}function d$3(t){return c$3(t)?t:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==t?void 0:t.ltrim("/")):f$2("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:d$3,base:function(t){return c$3(t)?t:"https://"+new URL(u$3("/")).hostname+"/"+(null==t?void 0:t.ltrim("/"))},baseUrl:f$2,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 d$3(salla.config.get("theme.settings.placeholder"))===d$3(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 y$3=function(){return y$3=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},y$3.apply(this,arguments)};function v$2(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 y$3({},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}}},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,v$2([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,v$2([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_=y$3(y$3({},this.default_properties),t);}return t.prototype.merge=function(t){var e;return this.properties_=y$3(y$3({},this.properties_),t),this.properties_.store=y$3(y$3({},(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,v$2([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,v$2([e],n,false)),this.trackEvents.apply(this,v$2([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,v$2([e],r,false));try{this.trackEvents.apply(this,v$2([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=y$3(y$3({},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,v$2([t],r,false)),this.dispatchMobileEvent.apply(this,v$2([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,v$2([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),D$2=storeEngineExports.createStore([n$4,o$3,i$3,a$4],[]),W$2=storeEngineExports.createStore([o$3],[]),F$3=storeEngineExports.createStore([i$3],[]),C$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=D$2,this.session=W$2,this.cookie=F$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 C$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.366"};var N$3=Salla;
|
|
4024
|
+
function s$1(t,e){ void 0===e&&(e=false),t+="";for(var r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],o=["0","1","2","3","4","5","6","7","8","9"],i=(e=e||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:o,a=e?o:n,s=0;s<i.length;s++)r=new RegExp(i[s],"g"),t=t.replace(r,a[s]);return t.replace(e?"٫":".",e?".":"٫")}function l$2(t){var e=("".concat(t).match(/\./g)||[]).length;return e&&1!==e?l$2(t.replace(/\.(.+)\./g,".$1")):t}function c$3(t){return "".concat(t).startsWith("https://")||"".concat(t).startsWith("http://")}function u$3(t){if(c$3(t))return t;var e=Salla.config.get("store.url");return e||(e=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",e)),e.rtrim("/")+"/"+(null==t?void 0:t.ltrim("/"))}function p$1(t,e,r){if(r=r||window.location.href,!e||!t)return r;var n=new RegExp("([?&])"+t+"=[^&]+[&]?","g");return (r=r.replace(n,"$1").split("#")[0].replace(/&$|\?$/,"")).includes("?")?r+="&":r+=(r.endsWith("/")?"":"/")+"?",(r+t+"="+encodeURIComponent(e)).replace(/&$|\?$/,"")}function f$2(t){return window.location.origin+"/"+(null==t?void 0:t.ltrim("/"))}function d$3(t){return c$3(t)?t:Salla.config.get("theme.assets")?Salla.config.get("theme.assets").replace(":path",null==t?void 0:t.ltrim("/")):f$2("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:d$3,base:function(t){return c$3(t)?t:"https://"+new URL(u$3("/")).hostname+"/"+(null==t?void 0:t.ltrim("/"))},baseUrl:f$2,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 d$3(salla.config.get("theme.settings.placeholder"))===d$3(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 y$3=function(){return y$3=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},y$3.apply(this,arguments)};function v$2(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 y$3({},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}}},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,v$2([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,v$2([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_=y$3(y$3({},this.default_properties),t);}return t.prototype.merge=function(t){var e;return this.properties_=y$3(y$3({},this.properties_),t),this.properties_.store=y$3(y$3({},(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,v$2([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,v$2([e],n,false)),this.trackEvents.apply(this,v$2([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,v$2([e],r,false));try{this.trackEvents.apply(this,v$2([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=y$3(y$3({},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,v$2([t],r,false)),this.dispatchMobileEvent.apply(this,v$2([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,v$2([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),D$2=storeEngineExports.createStore([n$4,o$3,i$3,a$4],[]),W$2=storeEngineExports.createStore([o$3],[]),F$3=storeEngineExports.createStore([i$3],[]),C$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=D$2,this.session=W$2,this.cookie=F$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 C$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.367"};var N$3=Salla;
|
|
4025
4025
|
|
|
4026
4026
|
var js = {exports: {}};
|
|
4027
4027
|
|
|
@@ -12331,7 +12331,7 @@ function jitsuAnalytics(_opts) {
|
|
|
12331
12331
|
// }
|
|
12332
12332
|
}
|
|
12333
12333
|
|
|
12334
|
-
let n=function(e,t,a){return alert(e)},o=function(e,t){return n(e,l.error,t)},l={error:"error",success:"success",info:"info"};var u={fire:function(e,t,a){return n(e,t,a)},setNotifier:function(e){n=e,salla.event.emit("twilight::notifier.changed");},error:o,success:function(e,t){return n(e,l.success,t)},info:function(e,t){return n(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,o(t.innerHTML),salla.event.emit("twilight::error",e);}));})));},types:l};class c{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let s=r.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return s.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return false},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||(null==a?void 0:a.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let s=(null==a?void 0:a.dataset[r])||this.dataset[r];if(s){var i=window[s];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${s}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+s+"() not found!");}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class d{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);}));}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,(async function(...e){return t(...e)}))};}getEventName(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,a={}){return Salla.event.addListener(this.getEventName(e),t,a)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function h$1(){return h$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e},h$1.apply(null,arguments)}function p(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=true);}Salla.event.auth=new class extends d{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends d{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},this.after_init();}updated(e,t={}){var a;return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(a=e.cart.free_shipping_bar)&&a.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",h$1({},e.cart,{fromLatestFetched:t.fromLatestFetched}))):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated",{fromLatestFetched:t.fromLatestFetched}))}latestFetched(e){return this.updated(e.data,{fromLatestFetched:true}),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends d{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched"},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_)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){if(console.log("salla.cart.api.submit",{isGuestCheckout:e}),salla.config.isGuest()&&!e)return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();let a;if(t)try{var r;const e=await Salla.api.cart.assign();a=null==e||null==(r=e.data)?void 0:r.cart_id;}catch(e){Salla.log("Error on assign after login from submit",e);}this.status(null!=a?a:await salla.api.cart.getCurrentCartId(false,"salla.api.cart.submit"),e).then((e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(a||(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()),!["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){let t=e.data.next_step.url;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(e){var t;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let a=404===(null==e||null==(t=e.response)||null==(t=t.data)?void 0:t.status);if(a&&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();throw a&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}));}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(false,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(){return "sessionless"===salla.config.get("auth.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"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get"},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}))}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){if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const t={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(t.sort=e.sort),this.request(["comments"],{params:t},"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){const i=Array.isArray(t)?t:[t];return this.fetchComments({ids:i,type:`${e}s`,page:a,per_page:r,sort:s})}}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 B 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 P{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).get("scope");i&&s&&!Salla.url.is_page("cart")&&(s.id=i,Salla.storage.set("scope",s),Salla.cart.reset()),s&&this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const n=Salla.storage.getWithTTL("s-utms");if(n){const e={};Object.entries(n).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 x 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 q 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 I 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(){await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.hooks.renderAutoComponents([{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}}]),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 U{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}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return {type:"guest",language_code:Salla.lang.getLocale(),currency_code:"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 j{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 U(e),null!=e&&null!=(r=e.user)&&r.language_code)Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);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 j,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)}}]};N$3.versions.twilight="2.14.366",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||{}).messages=e.messages||window.translations,e.locale=e.locale||(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 P{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 B,this.component=new x,this.advertisement=new q,this.navigation=new I,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()||customElements.get(t)||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._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("twilight::before.ready",(e=>{var t,a,r,s,n,o;this.debugAnalytics=jitsuAnalytics({host:"https://st.salla.dev",writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p"});const{host:l,key:u}=(null==e?void 0:e.jitsu)||{};if(this.jitsuAnalytics=null,!l||!u)return void salla.log("Jitsu configuration is missing. Analytics will not be tracked.");H.registerEvents(),this._jitsuConfig={host:this.getAnalyticsHost(e),writeKey:u,cookieCapture:Object.fromEntries(Salla.cookie.getCookieByPrefix("sa_").map((e=>[e,e])))};const c=this.getConsentPolicies();var d;(this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,c)),this._anonymousId=(null==(t=this.jitsuAnalytics)||null==(t=t.user())?void 0:t.anonymousId)||null,this.setContext("store_id",null==(a=e.store)?void 0:a.id),this.setContext("version",null==(r=e.jitsu)?void 0:r.version),this.setContext("library",{twilight:Salla.versions}),null!=(s=e.jitsu)&&null!=(s=s.context)&&s.extra&&this.setExtraContext(e.jitsu.context.extra),null!=(n=e.store)&&null!=(n=n.scope)&&n.id)&&this.setContext("scope",null==(d=e.store)?void 0:d.scope);"user"===(null==e||null==(o=e.user)?void 0:o.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;const t={name:Salla.config.get("page.slug",""),id:null==(e=Salla.config.get("page.id",""))?void 0:e.toString()};this.setContext("page",t),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";if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;const r=e.store.url;try{let e="";const t=r;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 s=/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/,i=t.match(s);if(i){const r=i[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);}customFetch(e,t){var a;return Salla.api.beaconRequest(`${e}?writekey=${null==t||null==(a=t.headers)?void 0:a["X-Write-Key"]}`,t)}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,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}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"));
|
|
12334
|
+
let n=function(e,t,a){return alert(e)},o=function(e,t){return n(e,l.error,t)},l={error:"error",success:"success",info:"info"};var u={fire:function(e,t,a){return n(e,t,a)},setNotifier:function(e){n=e,salla.event.emit("twilight::notifier.changed");},error:o,success:function(e,t){return n(e,l.success,t)},info:function(e,t){return n(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&(window.history.replaceState(null,document.title,window.location.pathname),salla.event.once("twilight::notifier.changed",(()=>{e.forEach((e=>{e=decodeURI(e.replace("?danger=","").replace("&danger=",""));let t=document.createElement("div");t.innerText=e,o(t.innerHTML),salla.event.emit("twilight::error",e);}));})));},types:l};class c{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let s=r.querySelectorAll("[name]");if(!s.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return s.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return false},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||(null==a?void 0:a.dataset)||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let s=(null==a?void 0:a.dataset[r])||this.dataset[r];if(s){var i=window[s];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${s}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+s+"() not found!");}})),e},HTMLAnchorElement.prototype.getAjaxFormData=function(e){return {formData:this.getFilteredData(null,e),url:this.getAttribute("href"),method:this.dataset.type||"get",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}};class d{constructor(){this.events={},this.namespace="";let e=/function (.{1,})\(/.exec(this.constructor.toString());this.className=(e&&e.length>1?e[1]:"").toLowerCase();}after_init(){this.createDynamicFunctions();}createDynamicFunctions(){Object.keys(this.events).forEach((e=>{this.createDynamicEventFuns(e),this.createDynamicListenerFuns(e);}));}createDynamicEventFuns(e){if(this[e])return;let t=this;this[e]=function(...a){return t.dispatch(e,...a)};}createDynamicListenerFuns(e){let t="on"+e.charAt(0).toUpperCase()+e.slice(1);if(this[t])return;let a=this;this[t]=function(t){return a.on(e,(async function(...e){return t(...e)}))};}getEventName(e){return e=this.events[e]||e||"unknown-event",!this.namespace||e.includes("::")?e:this.namespace+Salla.event.delimiter+e}dispatch(e,...t){return Salla.event.emitAsync(this.getEventName(e),...t)}on(e,t,a={}){return Salla.event.addListener(this.getEventName(e),t,a)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function h$1(){return h$1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r]);}return e},h$1.apply(null,arguments)}function p(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=true);}Salla.event.auth=new class extends d{constructor(){super(),this.namespace="auth",this.events={login:"login",logout:"logout",codeSent:"code.sent",codeNotSent:"code.not-sent",verified:"verified",verificationFailed:"verification.failed",loggedIn:"logged.in",registered:"registered",registrationFailed:"registration.failed",loggedOut:"logged.out",failedLogout:"failed.logout",refreshFailed:"refresh.failed",tokenFetched:"token.fetched",tokenInvalid:"token.invalid"},this.after_init();}login(e){return e?(e.type&&this.setTypeActionOnVerified(e.type),this.next_event=e.next_event||null,this.dispatch("login",...arguments)):(this.next_event=null,this.dispatch("login",...arguments))}async loggedIn(e){return Salla.profile.info().finally((()=>this.dispatch("loggedIn",e)))}setTypeActionOnVerified(e){this.type_action_on_verified=e;}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends d{constructor(){super(),this.namespace="cart",this.events={latestFetched:"latest.fetched",latestFailed:"latest.failed",updated:"updated",itemUpdated:"item.updated",itemUpdatedFailed:"item.updated.failed",itemAdded:"item.added",beforeAddItem:"before.add.item",itemAddedFailed:"item.added.failed",itemDeleted:"item.deleted",itemDeletedFailed:"item.deleted.failed",submitted:"submitted",submitFailed:"submit.failed",imageDeleted:"image.deleted",imageNotDeleted:"image.not.deleted",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",successReset:"success.reset",priceQuoteSucceeded:"price-quote.succeeded",priceQuoteFailed:"price-quote.failed",offersFetched:"offers.fetched",offersFailed:"offers.failed",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.failed",quickOrderSettingFetched:"quick-order.fetched",quickOrderSettingFailed:"quick-order.failed",quickOrderSucceeded:"quick-order.succeeded",quickOrderFailed:"quick-order.failed",beforeStartFastCheckout:"before.start.fast-checkout",submitting:"submitting"},this.after_init();}updated(e,t={}){var a;return Salla.cookie.set("fresh_summary",1),e&&"object"==typeof e?(e.offer&&salla.product.event.offerExisted(e.offer),e.redirect&&(salla.log("The current cart is purchased!"),salla.cart.api.reset()),e.cart?(salla.storage.set("cart.summary",{total:e.cart.total,sub_total:e.cart.sub_total,discount:e.cart.discount,tax_amount:e.cart.tax_amount,total_discount:e.cart.total_discount,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:null!=(a=e.cart.free_shipping_bar)&&a.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",h$1({},e.cart,{fromLatestFetched:t.fromLatestFetched}))):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated",{fromLatestFetched:t.fromLatestFetched}))}latestFetched(e){return this.updated(e.data,{fromLatestFetched:true}),this.dispatch("latestFetched",e)}itemAdded(e,t){return this.updated(e.data),this.dispatch("itemAdded",e,t)}itemDeleted(e,t){return this.updated(e.data),this.dispatch("itemDeleted",e,t)}itemUpdated(e,t){return this.updated(e.data),this.dispatch("itemUpdated",e,t)}couponAdded(e,t){return this.updated(e.data),this.dispatch("couponAdded",e,t)}couponDeleted(e,t){return this.updated(e.data),this.dispatch("couponDeleted",e,t)}},Salla.event.order=new class extends d{constructor(){super(),this.namespace="order",this.events={canceled:"canceled",notCanceled:"not.canceled",orderCreated:"order.created",orderCreationFailed:"order.creation.failed",invoiceSent:"invoice.sent",invoiceNotSent:"invoice.not.sent",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched"},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_)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){if(console.log("salla.cart.api.submit",{isGuestCheckout:e}),salla.config.isGuest()&&!e)return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();let a;if(t)try{var r;const e=await Salla.api.cart.assign();a=null==e||null==(r=e.data)?void 0:r.cart_id;}catch(e){Salla.log("Error on assign after login from submit",e);}this.status(null!=a?a:await salla.api.cart.getCurrentCartId(false,"salla.api.cart.submit"),e).then((e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(a||(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()),!["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){let t=e.data.next_step.url;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(e){var t;salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let a=404===(null==e||null==(t=e.response)||null==(t=t.data)?void 0:t.status);if(a&&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();throw a&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}));}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(false,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(){return "sessionless"===salla.config.get("auth.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"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get"},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}))}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){if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const t={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(t.sort=e.sort),this.request(["comments"],{params:t},"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){const i=Array.isArray(t)?t:[t];return this.fetchComments({ids:i,type:`${e}s`,page:a,per_page:r,sort:s})}}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 B 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 P{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).get("scope");i&&s&&!Salla.url.is_page("cart")&&(s.id=i,Salla.storage.set("scope",s),Salla.cart.reset()),s&&this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const n=Salla.storage.getWithTTL("s-utms");if(n){const e={};Object.entries(n).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 x 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 q 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 I 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(){await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.hooks.renderAutoComponents([{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}}]),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 U{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}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return {type:"guest",language_code:Salla.lang.getLocale(),currency_code:"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 j{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 U(e),null!=e&&null!=(r=e.user)&&r.language_code)Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);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 j,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)}}]};N$3.versions.twilight="2.14.367",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||{}).messages=e.messages||window.translations,e.locale=e.locale||(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 P{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 B,this.component=new x,this.advertisement=new q,this.navigation=new I,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()||customElements.get(t)||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._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("twilight::before.ready",(e=>{var t,a,r,s,n,o;this.debugAnalytics=jitsuAnalytics({host:"https://st.salla.dev",writeKey:"bbLD6Xqr1OKsDJfxZBCy7SJN1RIsrkBp:WEa99iY220v9qX7KiuAlML9ldSFJKW2p"});const{host:l,key:u}=(null==e?void 0:e.jitsu)||{};if(this.jitsuAnalytics=null,!l||!u)return void salla.log("Jitsu configuration is missing. Analytics will not be tracked.");H.registerEvents(),this._jitsuConfig={host:this.getAnalyticsHost(e),writeKey:u,cookieCapture:Object.fromEntries(Salla.cookie.getCookieByPrefix("sa_").map((e=>[e,e])))};const c=this.getConsentPolicies();var d;(this.jitsuAnalytics=jitsuAnalytics(h$1({},this._jitsuConfig,c)),this._anonymousId=(null==(t=this.jitsuAnalytics)||null==(t=t.user())?void 0:t.anonymousId)||null,this.setContext("store_id",null==(a=e.store)?void 0:a.id),this.setContext("version",null==(r=e.jitsu)?void 0:r.version),this.setContext("library",{twilight:Salla.versions}),null!=(s=e.jitsu)&&null!=(s=s.context)&&s.extra&&this.setExtraContext(e.jitsu.context.extra),null!=(n=e.store)&&null!=(n=n.scope)&&n.id)&&this.setContext("scope",null==(d=e.store)?void 0:d.scope);"user"===(null==e||null==(o=e.user)?void 0:o.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;const t={name:Salla.config.get("page.slug",""),id:null==(e=Salla.config.get("page.id",""))?void 0:e.toString()};this.setContext("page",t),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";if(null==e||null==(t=e.store)||!t.url)return Salla.log("Error getting store url - no config or store URL provided"),a;const r=e.store.url;try{let e="";const t=r;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 s=/(salla\.sa)\/(?:(ar|en)\/)?((?!ar$|en$)[a-zA-Z0-9.-]+)/,i=t.match(s);if(i){const r=i[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);}customFetch(e,t){var a;return Salla.api.beaconRequest(`${e}?writekey=${null==t||null==(a=t.headers)?void 0:a["X-Write-Key"]}`,t)}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,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}getAnonymousId(){try{if(this._anonymousId)return this._anonymousId;if(this.jitsuAnalytics){var e;const t=null==(e=this.jitsuAnalytics.user())?void 0:e.anonymousId;if(t)return this._anonymousId=t,t}return null}catch(e){return Salla.log("Error getting anonymous ID from Jitsu:",e),null}}},N$3.init=e=>new O(e),new class{constructor(e={}){this.config=h$1({WHITELIST:[location.hostname,"salla.com","salla.sa","salla.dev","salla.network","salla.group","mtjr.at"],POLL_INTERVAL_MS:500,WHITELIST_PAGES:["customer.orders.single","page-single","blog.single","blog.index"]},e),this.originalMethods={},this.isInitialized=false,Salla.onReady((()=>this.init()));}normalizeUrl(e){try{return new URL(e,location.href)}catch(e){return null}}shouldIgnoreUrl(e){if(!e)return false;const t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some((e=>a.startsWith(e))))return true;try{const e=new URL(t,location.href).hostname.toLowerCase();return ["facebook.com","fb.com","twitter.com","x.com","instagram.com","linkedin.com","youtube.com","youtu.be","tiktok.com","snapchat.com","pinterest.com","whatsapp.com","wa.me","iwtsp.com","telegram.org","t.me","discord.com","discord.gg","reddit.com","tumblr.com","google.com","forms.gle","maps.app.goo.gl","goo.gl","apple.com","smsaexpress.com","aramex.com","aj-ex.com","redboxsa.com","fastcoo-tech.com","express.dhl","najizxpress.net","jtexpress.me","jtexpress-sa.com","tamex.com.sa","aymakan.com.sa","fastlo.com","sls-express.com","logestechs.com","massuul.com","tamara.co","gov.sa","org.sa","stc.com.sa","sa","addtoany.com","wchat.freshchat.com","getbutton.io","heyzine.com","linktr.ee"].some((t=>e===t||e.endsWith("."+t)))}catch(e){return false}}isWhitelisted(e){if(!e)return false;const t=e.hostname.toLowerCase();for(const e of this.config.WHITELIST){const a=String(e||"").toLowerCase().trim();if(a&&(t===a||t.endsWith("."+a)))return true}return false}emit(e){try{window.__redirectLogs||(window.__redirectLogs=[]),window.__redirectLogs.push(e);try{Salla.analytics.log("redirect",e);}catch(e){}}catch(e){}}logRedirect(e,t,a){if(this.shouldIgnoreUrl(t))return;const r=this.normalizeUrl(t),s=this.normalizeUrl(location.href),i=this.isWhitelisted(r),n={redirect_source:e,redirect_from:s?s.href:String(location.href),redirect_to:r?r.href:String(t),redirect_host:r?r.hostname:null,redirect_referrer:document.referrer||null,page_slug:Salla.config.get("page.slug"),whitelisted:i,stack:a&&a.stack?String(a.stack):void 0,meta:a||void 0};i||this.emit(n);}hookHistoryAPIs(){["pushState","replaceState"].forEach((e=>{try{const t=history[e];"function"==typeof t&&(this.originalMethods[`history.${e}`]=t,history[e]=(...a)=>{try{var r;this.logRedirect(e,null!=(r=a[2])?r:location.href);}catch(e){}return t.apply(history,a)});}catch(e){}})),window.addEventListener("popstate",(()=>{this.logRedirect("popstate",location.href);})),window.addEventListener("hashchange",(()=>{this.logRedirect("hashchange",location.href);}));}hookLocationMethods(){try{const e=location.assign.bind(location);this.originalMethods["location.assign"]=e,location.assign=t=>(this.logRedirect("location.assign",t,{stack:(new Error).stack}),e(t));}catch(e){}try{const e=location.replace.bind(location);this.originalMethods["location.replace"]=e,location.replace=t=>(this.logRedirect("location.replace",t,{stack:(new Error).stack}),e(t));}catch(e){}}hookWindowOpen(){try{const e=window.open;this.originalMethods["window.open"]=e,window.open=(t,...a)=>(t&&this.logRedirect("window.open",t,{stack:(new Error).stack}),e.apply(window,[t,...a]));}catch(e){}}setupEventListeners(){this.handleLinkClick=e=>{const t=e.target&&e.target.closest?e.target.closest("a[href]"):null;if(!t)return;const a=t.getAttribute("href");if(!a||a.startsWith("#"))return;if(this.shouldIgnoreUrl(a))return;const r=t.getAttribute("target")||"_self";setTimeout((()=>{this.logRedirect("link-click",a,{target:r});}),0);},document.addEventListener("click",this.handleLinkClick,true),this.handleFormSubmit=e=>{const t=e.target,a=t&&t.getAttribute&&t.getAttribute("action")||location.href,r=(t&&t.method?String(t.method):"GET").toUpperCase();this.logRedirect("form-submit",a,{method:r});},document.addEventListener("submit",this.handleFormSubmit,true);}setupPerformanceObserver(){try{this.performanceObserver=new PerformanceObserver((e=>{for(const t of e.getEntries())"navigation"===t.entryType&&this.logRedirect("performance-navigation",location.href,{type:t.type,redirectCount:t.redirectCount});})),this.performanceObserver.observe({type:"navigation",buffered:true});}catch(e){}}init(){if(this.config.WHITELIST_PAGES.includes(Salla.config.get("page.slug")))return;if(this.isInitialized)return;const e=new URL(Salla.config.get("store.url")).hostname.split(".").slice(-2).join(".");this.config.WHITELIST.includes(e)||this.config.WHITELIST.push(e),this.hookHistoryAPIs(),this.hookLocationMethods(),this.hookWindowOpen(),this.setupEventListeners(),this.setupPerformanceObserver(),this.isInitialized=true;}destroy(){this.isInitialized&&(Object.keys(this.originalMethods).forEach((e=>{const[t,a]=e.split(".");"history"===t&&this.originalMethods[e]?history[a]=this.originalMethods[e]:"location"===t&&this.originalMethods[e]?location[a]=this.originalMethods[e]:"window"===t&&"open"===a&&this.originalMethods[e]&&(window.open=this.originalMethods[e]);})),this.handleLinkClick&&document.removeEventListener("click",this.handleLinkClick,true),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,true),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=false);}},salla.event.once("twilight::init",salla.init),salla.event.on("twilight::api",(e=>{let t=null==e?void 0:e.events;t&&salla.event.dispatchEvents(t);})),N$3.success=N$3.notify.success,N$3.error=N$3.notify.error,window.dispatchEvent(new CustomEvent("salla::created"));
|
|
12335
12335
|
|
|
12336
12336
|
var lazyload_min$1 = {exports: {}};
|
|
12337
12337
|
|