@salla.sa/twilight 3.0.0-alpha.0 → 3.0.0
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/README.md +66 -3
- package/dist/@salla.sa/twilight.min.js +1 -19
- package/dist/@salla.sa/twilight.min.js.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/package.json +29 -24
- package/types/api/cart/index.d.ts +1 -1
- package/types/api/index.d.ts +7 -1
- package/types/api/loyalty.d.ts +10 -1
- package/types/api/metadata.d.ts +33 -0
- package/types/api/order.d.ts +18 -2
- package/types/api/product/request.d.ts +2 -1
- package/types/api/profile.d.ts +5 -0
- package/types/common.d.ts +20 -1
- package/types/event/auth.d.ts +5 -1
- package/types/event/index.d.ts +3 -0
- package/types/event/loyalty.d.ts +5 -1
- package/types/event/metadata.d.ts +7 -0
- package/types/event/product.d.ts +1 -1
- package/types/index.d.ts +2 -0
- package/types/lib/error-monitor.d.ts +7 -0
- package/types/lib/lang.d.ts +2 -1
- package/types/tiwlight-config.d.ts +229 -18
- package/watcher.js +2 -2
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("@salla.sa/base"),t=require("infinite-scroll"),a=require("lang.js"),r=require("axios"),s=require("jwt-decode");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=i(e),l=i(t),o=i(a),d=i(r),c=i(s);let u=function(e,t,a){return alert(e)},h=function(e,t){return u(e,p.error,t)},p={error:"error",success:"success",info:"info"};var g={fire:function(e,t,a){return u(e,t,a)},setNotifier:function(e){u=e,salla.event.emit("twilight::notifier.changed")},error:h,success:function(e,t){return u(e,p.success,t)},info:function(e,t){return u(e,p.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,h(t.innerHTML),salla.event.emit("twilight::error",e)}))})))},types:p};class f{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!1},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||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=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 m{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(...e)=>t(...e)))}}getEventName(e){return e=this.events[e]||e,!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 v(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new class extends m{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))}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 m{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",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"},this.after_init()}updated(e){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,real_shipping_cost:e.cart.real_shipping_cost,count:e.cart.count,shipping_cost:e.cart.free_shipping_bar?.has_free_shipping?0:e.cart.real_shipping_cost}),this.dispatch("updated",e.cart)):void salla.log("Failed to get the cart summary!")):(Salla.logger.info("Cart summary not an object!",e),this.dispatch("updated"))}latestFetched(e){return this.updated(e.data),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 m{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 m{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 m{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 m{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}},Salla.event.comment=new class extends m{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 m{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 m{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 m{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 m{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 m{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 m{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,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...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 m{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 m{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 m{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.component=new class extends m{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 m{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init()}},Salla.event.navigation=new class extends m{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init()}},Salla.event.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(v(e),Object.keys(e).forEach((t=>{v(e[t])})))}))})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:"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_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{if(Salla.config.triedToGetLanguages_)return Salla.config.get("languages");Salla.config.triedToGetLanguages_=!0;let e=!0,t=[];return(await salla.document.api.request("languages",null,"get"))?.data?.map((a=>{e&&(t=[],e=!1),a.code=a.code||a.iso_code,a.url=salla.url.get(a.code),a.is_rtl=a.is_rtl||a.rtl,t.push(a)})),Salla.config.set("languages",t),t},Salla.config.currencies=async()=>{if(Salla.config.triedToGetCurrencies_)return Salla.config.get("currencies");Salla.config.triedToGetCurrencies_=!0;let e=!0,t={};return(await salla.currency.api.list())?.data?.map((a=>{e&&(t={},e=!1),a.country_code=a.code.substr(0,2).toLowerCase(),t[a.code]=a})),Salla.config.set("currencies",t),t};class y extends o.default{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=!1}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=!0)&&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",!1)}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0}loadScript(e,t=!0){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",!1);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}}class w{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:!0,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 b extends w{constructor(){super(),this.addToCartTries=0,this.namespace="cart",this.endpoints={latest:"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}"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get",offers:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>salla.api.cart.getCurrentCartId(!1,"api::initiated"))),salla.event.on("auth::token.fetched",this._checkCurrentCart),salla.event.on("auth::token.invalid",this._checkCurrentCart),salla.event.on("auth::verified",(()=>salla.api.cart.getCurrentCartId(!0,"auth::verified")),{async:!0}),salla.event.on("profile::info.fetched",this._checkCurrentCart),salla.event.on("twilight::error",(e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()))}_checkCurrentCart(){let e=salla.storage.get("cart"),t=salla.config.get("user")?.id,a=salla.config.get("store")?.id;e&&e.id&&(e.user_id!==t||e.store_id!==a)&&(salla.log("cart",{user_id:e.user_id,store_id:e.store_id}),salla.log("current",{user_id:t,store_id:a}),salla.log("Api:: case2 => The cart is not belong to current "+(e.user_id!==t?"user":"store")+"!"),salla.cart.api.reset())}async getCurrentCartId(e=!1,t="getCurrentCartId"){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}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(e="direct"){return this.request("latest",{params:{source:"",callerName:e}}).then((e=>(salla.storage.set("cart",e.data.cart),salla.event.cart.latestFetched(e),e))).catch((e=>{throw salla.storage.set("cart",""),salla.event.cart.latestFailed(e),e}))}async details(e,t=[]){return e=e||await salla.api.cart.getCurrentCartId(!1,"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){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let a=salla.form.getPossibleValue(t.payload,["endpoint"]);a&&["addItem","quickAdd"].includes(a)||(a=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let r=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addItem");return this.request([a,r,t.id],t.payload).then((function(e){return salla.cart.api.addToCartTries=0,salla.cart.event.itemAdded(e,t.id),e})).catch((function(a){if(!salla.cart.api.addToCartTries)return salla.cart.api.addToCartTries++,salla.cart.reset(),salla.cart.api.addItem(e);throw salla.cart.event.itemAddedFailed(a,t.id),a}))}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(!1,"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){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.updateItem");return"Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",a,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.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(!1,"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){const t=(new Date).getTime(),a=Math.random().toString(36).substring(2,15);return this.request(["status",e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status")],{params:{has_apple_pay:salla.helpers.hasApplePay(),"s-hash":`${a}_${t}`}})}async submit(){if(salla.config.isGuest())return salla.log("it looks that the current user is not logged-in, lets login then submit"),salla.cart.loginOnCartPage();this.status(await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.submit")).then((e=>{let t=e.data.next_step?.to;if(t||(window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",!1===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload()),!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}return salla.cart.event.submitted(e),"login"===t?salla.cart.loginOnCartPage():"checkout"===t?window.location.href=e.data.next_step.url+(salla.helpers.hasApplePay()?"?has_apple_pay=true":""):(window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),void window.location.reload())})).catch((function(e){salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let t=404===e?.response?.data?.status;if(t&&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 t&&salla.error(salla.lang.get("pages.checkout.try_again")),salla.cart.event.submitFailed(e),e}))}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t=void 0,a=null){return super.normalRequest(e,t,a).catch((async e=>{throw 403===e?.response?.status&&(this.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),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(!1,"salla.api.cart.addCoupon");return this.request(["addCoupon",t],{coupon:e}).then((function(e){return 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(!1,"salla.api.cart.deleteCoupon");return this.request(["deleteCoupon",e],{}).then((function(t){return 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(!1,"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((()=>{throw 404===e.error?.code&&window.location.reload(),e}))))}loginOnCartPage(){salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),salla.cart.submit()}))}async offers(){const e=await salla.cart.api.getCurrentCartId(!1,"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}))}}class F extends w{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(!1,"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(!1,"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 _ extends w{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,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(),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){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){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=!1!==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!==r?.status?(salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r)):salla.auth.api.handlAfterAuthenticatedResponse(r,t)}async handlAfterAuthenticatedResponse(e,t){e.data||(e={data:e});let a="authenticated"===e.data?.case;return a&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&await salla.auth.api.request("auth/jwt"),a&&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),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){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async e=>(salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),!this.inIframe&&await salla.auth.request("auth/jwt"),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e))).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}handleIframeReadyAction(e,t){e.contentWindow?.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()}},"*")}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"){return salla.storage.clearAll(),salla.cookie.clearAll(),e=encodeURI(e),salla.auth.event.loggedOut().then((()=>this.appendIframeAndLogout())).then((()=>{let t=salla.url.get(`logout?from=${e}`);console.log(`Going to ${t}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=t}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)}}class S extends w{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}",fetch:"orders"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get"},this.after_init()}show(e){let t=salla.form.getPossibleValue(e?.data||e,["id","order_id"]);salla.event.dispatch("mobile::order.placed",{order_id:t}),location.href=salla.form.getPossibleValue(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}))}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t||isNaN(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 q extends w{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",giftDetail:"products/{product_id}/buy-as-gift",giftToCart:"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",giftDetail:"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){let t=e.data;if(t||(t={params:"string"==typeof e?{query:e}:e}),!(e=t instanceof FormData?t.get("query"):t.query||t.params?.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",t,"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){if(!(e=salla.form.getPossibleValue(e?.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}))}getGiftDetails(e){return this.request(["giftDetail",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}))}addGiftToCart(e,t,a=!1){return this.request(["giftToCart",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"].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 t=>{if(salla.product.event.productListFetchSucceeded(t),e.includes&&e.includes.includes("options")&&t.data){const e=t.data.map((e=>e.id)),a=await this.fetchOptions(e);this.updateProductOptions(t.data,a.data)}return t})).catch((e=>{throw salla.product.event.productListFetchFailed(e),e}))}updateProductOptions(e,t){const a=new Map(t.map((e=>[e.id,e.options])));for(const t of e)t.options=a.get(t.id)}fetchOptions(e){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 t={selected:e};return this.request(this.endpoints.fetchOptions,{params:t},"get").then((e=>(salla.product.event.productOptionsFetched(e),e))).catch((e=>{throw salla.product.event.productOptionsNotFetched(e),e}))}}class C extends w{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",update:"profile/update",updateContacts:"profile/contacts/update",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile"},this.endpointsMethods={delete:"delete"},this.after_init()}info(){return this.request("info",null,"get").then((e=>{let t={id:e.data.id,type:"user",email:e.data.email,mobile:e.data.phone.code+e.data.phone.number,country_code:e.data.phone.country,language_code:e.data.language,currency_code:e.data.currency,notifications:e.data.notifications,pending_orders:e.data.pending_orders,avatar:e.data.avatar,first_name:e.data.first_name,last_name:e.data.last_name,fetched_at:Date.now()};return salla.config.set("user",t),salla.storage.set("user",t),salla.profile.event.infoFetched(e),e})).catch((e=>{throw salla.profile.event.infoNotFetched(e),e}))}update(e){return this.request("update",e).then((e=>(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.event.profile.deleted(e),window.location.href=salla.url.get("logout"),e))).catch((e=>{throw salla.event.profile.notDeleted(e),e}))}}class P extends w{constructor(){super(),this.namespace="comment",this.endpoints={addComment:"{type}/{id}/comments",comments:"/comments"},this.after_init()}add(e){if(e?.data&&(e=e.data),"string"==typeof(e=this.getCommentPayload(e,!0)))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",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=!1){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"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages)!"}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}))}getPageComments(e,t=1,a=5,r){return this.fetchComments({ids:[e],type:"pages",page:t,per_page:a,sort:r})}getProductComments(e,t=1,a=5,r){return this.fetchComments({ids:[e],type:"products",page:t,per_page:a,sort:r})}}class A extends w{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 x extends w{constructor(){super(),this.namespace="document"}}class k extends w{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(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){if(!(e=e?.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){if(!(e=e?.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){if(!(e=e?.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 w{constructor(){super(),this.namespace="wishlist",this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}"},this.endpointsMethods={remove:"delete"},this.after_init()}toggle(e){return salla.storage.get("salla::wishlist",[]).includes(e)?this.remove(e):this.add(e)}add(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.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(t="Failed to get product id!"),salla.api.errorPromise(t))}remove(e){let t;return salla.config.isGuest()?(salla.wishlist.event.additionFailed(t=salla.lang.get("common.messages.must_login")),salla.error(t),salla.api.errorPromise(t)):(e=salla.form.getPossibleValue(e?.data||e,["product_id","id"]))?this.request(["remove",e]).then((t=>(this.updateWishlistStorage(e,!1),salla.wishlist.event.removed(t,e),t))).catch((function(t){throw salla.wishlist.event.removingFailed(t,e),t})):(salla.wishlist.event.removingFailed(t="Failed to get id!"),salla.api.errorPromise(t))}updateWishlistStorage(e,t=!0){let a=salla.storage.get("salla::wishlist",[]);t?a.push(e):a.splice(a.indexOf(e),1),salla.storage.set("salla::wishlist",a)}}class I extends w{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 T extends w{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"}}async add(e,t=!0){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 O extends w{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 D extends w{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 L{constructor(){this.inIframe=salla.helpers.isIframe(),salla.event.on("twilight::before.ready",(e=>this.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),this.setToken(e)})),salla.event.on("auth::token.invalid",(()=>{salla.storage.remove("user"),salla.storage.remove("token")})),this.notifier_handler_disabled=!1,this.axios=d.default.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser","cache-control":"no-cache"}}})}getHeaders(){return this.axios.defaults.headers.common}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=!0,await e().finally((()=>{this.notifier_handler_disabled=!1}))}async initiateRequest(e){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:e.user?.currency_code||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":e.user?.id,...e.headers||{}});const t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id});const a=salla.storage.session.get("s-utms");a&&this.setHeaders(a),await this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"))}async injectTokenToTheRequests(e){let t=salla.storage.get("token"),a="guest"===e.user.type,r=e.user?.id,s=salla.storage.get("user.id"),i=e=>{this.setToken(e),salla.event.emit("api::initiated")},n=async()=>{!a&&r?(salla.log("Api:: case 1 => current is is guest & web session available"),await salla.auth.api.refresh().then((async()=>{await salla.profile.info()})).catch((()=>salla.auth.event.tokenInvalid()))):salla.auth.event.tokenInvalid()};if(!t)return salla.log("Api:: case 1 => current is is guest"),void await n();let l=c.default(t);return Date.now()/1e3>l.exp?(salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await n()):l.sub===r&&s===r&&s&&r?(salla.log("Api:: case 4 => current user is logged-in and there is a token, and it's not expired"),void i(t)):(salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${l.sub} userIdInWeb:${r} userIdInStorage:${s}`),this.setHeader("Authorization","Bearer "+t),void await salla.profile.info().then((async e=>{!this.inIframe&&await salla.auth.api.request("auth/jwt"),i(t)})).catch((()=>{salla.log("Api:: case 3 => failed get fresh profile"),this.setHeader("Authorization",null),salla.auth.event.tokenInvalid()})))}setToken(e){return this.setHeader("Authorization","Bearer "+e),salla.event.emit("api::token.injected",e),this.token=e,this}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=!1;return"SALLA-BUTTON"===i?.tagName&&(n=!0),n&&i?.load(),this.axios[s.method](s.endPoint,s.payload,s.options).then((e=>(n&&i?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&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){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[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){if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.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=!0){return new Promise(((a,r)=>t?a(e):r(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class R extends w{constructor(){super(),this.namespace="component",this.endpoints={getMenus:"menus/{headOrFoot}",reviews:"reviews"},this.endpointsMethods={getMenus:"get",reviews:"get"}}async getMenus(e="header"){return this.request(["getMenus",e]).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 N extends w{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 j extends w{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 U{constructor(e){"ready"!==n.default.status?e?(n.default.config.merge(e),e?.events&&n.default.event.dispatchEvents(e?.events),e._token&&salla.api.setHeader("X-CSRF-TOKEN",e._token),this.injectMaintenanceAlert(),this.injectTemplateStoreAlert(),this.injectThemePreviewAlert(),this.injectAppInstallAlert(),this.injectEditAlert(),e?.user?.language_code&&salla.lang.setLocale(e?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(e)):this.setSallaReady(e):salla.log("Trying to re-initiate Salla, while its status === 'ready'!")}injectMaintenanceAlert(){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!"):salla.lang.onLoaded((()=>document.body.prepend(document.createElement("salla-maintenance-alert")))))}injectTemplateStoreAlert(){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!"):salla.lang.onLoaded((()=>document.body.append(document.createElement("salla-bottom-alert")))))}injectAppInstallAlert(){salla.config.get("store.app_install_prompt")&&salla.config.get("store.apps")&&!salla.storage.get("app_install_prompt_disabled")&&(document.body.classList.add("has-app-install-alert"),document.querySelector("salla-app-install-alert")?salla.logger.warn("salla-app-install-alert element Existed before!"):salla.lang.onLoaded((()=>document.body.append(document.createElement("salla-app-install-alert")))))}injectThemePreviewAlert(){"preview"===salla.config.get("theme.mode")&&(document.body.classList.add("has-preview-bar"),document.querySelector("#s-theme_preview_bar")?salla.logger.warn("#s-theme_preview_bar element Existed before!"):salla.lang.onLoaded((()=>{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)})))}injectEditAlert(){let e=salla.config.get("edit");e&&(document.querySelector("#s-edit-alert")?salla.logger.warn("#s-edit-alert element Existed before!"):salla.lang.onLoaded((()=>{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)})))}handleElementAjaxRequest(e,t){if(!(t instanceof HTMLFormElement||t instanceof HTMLAnchorElement))return salla.logger.warn("trying to call ajax from non Element!!"),!1;e.preventDefault();let a=t.getAjaxFormData(e),r=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,r).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}))}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1]})),a=e}window[e]?window[e](t,a):salla.event.dispatch(e,t,a)}}setSallaReady(e){this.storeUTMs(),n.default.event.dispatch("twilight::before.ready",e),n.default.status="ready",n.default.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}))}storeUTMs(){const e={fbclid:"facebook",gad_source:"google",ttclid:"tiktok",twclid:"twitter",scid:"snapchat"},t=["fbclid","gad_source","ttclid","twclid","scid"],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])=>r[e.toLowerCase()]=t));const i=t.some((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)),salla.storage.session.set("s-utms",s))}}n.default.status="loading",n.default.notify=g,n.default.lang=new y,n.default.form=new class{async submit(e,t=null){let a=t;if("SubmitEvent"===t?.constructor?.name||"submit"===t?.type){if(t.preventDefault(),"FORM"!==t.target?.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"===t?.submitter?.parentElement?.tagName&&t.submitter.parentElement.load(),a=t.target.getElementSallaData(),salla.log("Data from element",a)}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,a,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop()}));let r=e.split("."),s=r.splice(-1);return await salla.call(r.join("."))[s](a).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){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.default.infiniteScroll=new class extends f{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":!0,"S-Source":"twilight","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[]}initiate(e,t,a,r=!1){r?((a=a||{}).fetchOptions={...this.fetchOptions,...a.fetchOptions||{}},a.responseBody="json"):a=this.getCustomOptions(t,a);let s="string"!=typeof e?e:document.querySelector(e),i=a.path;if(!s||!i||"string"==typeof i&&!document.querySelector(i))return void Salla.logger.warn(s?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new l.default(s,a);return n.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),n.on("request",Salla.infiniteScroll.event.request),n.on("load",Salla.infiniteScroll.event.load),n.on("append",Salla.infiniteScroll.event.append),n.on("error",Salla.infiniteScroll.event.error),n.on("last",Salla.infiniteScroll.event.last),n.on("history",Salla.infiniteScroll.event.history),this.instances.push(n),n}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.default.api=new class extends L{constructor(){super(),this.auth=new _,this.cart=new b,this.loyalty=new F,this.order=new S,this.rating=new k,this.product=new q,this.profile=new C,this.comment=new P,this.currency=new A,this.document=new x,this.wishlist=new E,this.scope=new I,this.booking=new T,this.landing=new O,this.notifications=new D,this.component=new R,this.advertisement=new N,this.navigation=new j}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((e=>n.default[e]=new f(n.default.api[e],n.default.event[e]))),n.default.call=e=>{let t=n.default,a=e.split(".");for(;a.length&&(t=t[a.shift()]););return t},n.default.init=e=>new U(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t)})),n.default.success=n.default.notify.success,n.default.error=n.default.notify.error,n.default.versions.twilight="[VI]{version}[/VI]",n.default.onInitiated=e=>salla.event.once("twilight::initiated",e),n.default.onReady=n.default.onReady||function(e){return new Promise((function(t){return"ready"===salla.status?t(e?e(salla.config.all()):salla.config.all()):n.default.onInitiated((a=>t(e?e(a):a)))}))},window.dispatchEvent(new CustomEvent("salla::created")),module.exports=n.default;
|
|
1
|
+
"use strict";var e=require("@salla.sa/base"),t=require("infinite-scroll"),a=require("lang.js"),r=require("axios"),s=require("jwt-decode"),i=require("@salla.sa/analytics/storefront");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]}})}}function d(){return d=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},d.apply(null,arguments)}function h(e,t){if(null==e)return{};var a={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;a[r]=e[r]}return a}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!1},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 p{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=e.charAt(0).toUpperCase()+e.slice(1),a="on"+t,r="off"+t,s=this;this._asyncWrappers||(this._asyncWrappers=new Map),this[a]||(this[a]=function(t){let a=s._asyncWrappers.get(t);a||(a=new Map,s._asyncWrappers.set(t,a));let r=a.get(e);return r||(r=async function(...e){return t(...e)},a.set(e,r),s.on(e,r))}),this[r]||(this[r]=function(t){let a=s._asyncWrappers.get(t),r=a&&a.get(e)||t;return a&&(a.delete(e),0===a.size&&s._asyncWrappers.delete(t)),Salla.event.off(s.getEventName(e),r)})}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 g(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}Salla.event.auth=new class extends p{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",mobileLogin:"mobile.login"},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().catch(()=>{}).finally(()=>this.dispatch("loggedIn",e))}async mobileLogin(e,t){if(e="string"==typeof e?e.trim().replace(/^"|"$/g,""):"",t="string"==typeof t?t.trim():"",e&&3===e.split(".").length){if(Salla.storage.get("token")!==e||Salla.config.isGuest())return this.pending_mobile_login?(Salla.log("mobileLogin: already running, joined the flow in progress"),this.pending_mobile_login):(this.pending_mobile_login=this.runMobileLogin(e,t).finally(()=>{this.pending_mobile_login=null}),this.pending_mobile_login);Salla.log("mobileLogin: skipped, already authenticated with this token")}else Salla.logger.warn("mobileLogin: ignored, token is not a JWT")}async runMobileLogin(e,t){try{Salla.log("mobileLogin: start",{cart_id:t||null}),this.tokenFetched(e),t&&!Salla.storage.get("cart.id")&&Salla.storage.set("cart",d({},Salla.storage.get("cart")||{},{id:t})),await Salla.api.cart.assign().catch(e=>Salla.log("mobileLogin: cart assign failed",e)),Salla.auth.api.isSessionless()||Salla.helpers.isIframe()||await Salla.auth.api.request("auth/jwt",{callerName:"salla.auth.event.mobileLogin"}).catch(e=>Salla.log("mobileLogin: auth/jwt (web session) failed",e)),await this.loggedIn({data:{token:e}}),Salla.auth.api.afterUserLogin();let a=Salla.config.get("user")||{},r=!Salla.config.isGuest()&&!!a.id;r&&(Salla.api.setHeader("s-user-id",a.id),a.country_code&&Salla.api.setHeader("s-country",a.country_code),a.currency_code&&Salla.api.setHeader("currency",a.currency_code)),await this.verified({data:{token:e}}),Salla.log("mobileLogin: done",{user_id:r?a.id:null}),this.dispatch("mobileLogin")}catch(e){Salla.logger.warn("mobileLogin failed",e)}}setTypeActionOnVerified(e){this.type_action_on_verified=e}getTypeActionOnVerified(){return this.type_action_on_verified||"redirect"}},Salla.event.cart=new class extends p{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",d({},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:!0}),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 p{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",editSessionCanceled:"edit.session.canceled",editSessionNotCanceled:"edit.session.not.canceled",detailsFetched:"details.fetched",detailsNotFetched:"details.not.fetched",branchDetailsFetched:"branch.details.fetched",branchDetailsNotFetched:"branch.details.not.fetched",ordersFetched:"order.fetched",ordersNotFetched:"order.not.fetched",orderEdited:"order.edited",orderNotEdited:"order.not.edited"},this.after_init()}},Salla.event.scope=new class extends p{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 p{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 p{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init()}},Salla.event.comment=new class extends p{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 p{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 p{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",loyaltyPointsFetched:"points.fetched",loyaltyPointsNotFetched:"points.not.fetched"},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 p{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 p{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 p{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 p{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,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach(e=>this.fireEventForElements(e,t,!1,...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 p{constructor(){super(),this.namespace="wishlist",this.events={added:"added",removed:"removed",additionFailed:"addition.failed",removingFailed:"removing.failed",beforeRemoveItem:"before.remove.item",beforeAddItem:"before.add.item",beforeShare:"before.share",shared:"shared",sharingFailed:"sharing.failed"},this.after_init()}},Salla.event.infiniteScroll=new class extends p{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 p{constructor(){super(),this.namespace="notifications",this.events={fetched:"fetched",fetchFailed:"fetch.failed"},this.after_init()}},Salla.event.component=new class extends p{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 p{constructor(){super(),this.namespace="advertisement",this.events={fetched:"advertisement.fetched",fetchFailed:"advertisement.not.fetched"},this.after_init()}},Salla.event.navigation=new class extends p{constructor(){super(),this.namespace="navigation",this.events={breadcrumbFetched:"breadcrumb.fetched",breadcrumbFetchFailed:"breadcrumb.fetch.failed"},this.after_init()}},Salla.event.metadata=new class extends p{constructor(){super(),this.namespace="metadata",this.events={valueFetched:"value.fetched",valueNotFetch:"value.not.fetched"},this.after_init()}},Salla.event.recommendations=new class extends p{constructor(){super(),this.namespace="recommendations",this.events={customersAlsoBoughtFetched:"customers-also-bought.fetched",customersAlsoBoughtFailed:"customers-also-bought.failed",similarProductsFetched:"similar-products.fetched",similarProductsFailed:"similar-products.failed",customersAlsoViewedFetched:"customers-also-viewed.fetched",customersAlsoViewedFailed:"customers-also-viewed.failed",buyAgainFetched:"buy-again.fetched",buyAgainFailed:"buy-again.failed",personalizedShoppersWhoBoughtFetched:"personalized-shoppers-who-bought.fetched",personalizedShoppersWhoBoughtFailed:"personalized-shoppers-who-bought.failed",boughtTogetherFetched:"bought-together.fetched",boughtTogetherFailed:"bought-together.failed"},this.after_init()}},Salla.event.search=new class extends p{constructor(){super(),this.namespace="search",this.events={popularFetched:"popular.fetched",popularFailed:"popular.failed"},this.after_init()}},Salla.event.on("twilight::initiated",()=>{Object.keys(Salla).forEach(e=>{"object"==typeof(e=Salla[e])&&(g(e),Object.keys(e).forEach(t=>{g(e[t])}))})}),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"===process.env.NODE_ENV,token:null,fastRequests:!0,canLeave:!0,store:{api:["group","test"].includes(window.location.hostname.split(".").pop())?window.location.origin+"/api/v1/":"https://api.salla.dev/store/v1/"},recommendations:{api:"https://api.salla.dev/recommendations/v1"},currencies:{SAR:{code:"SAR",name:"ريال سعودي",symbol:"ر.س",amount:1,country_code:"sa"}}},Salla.config.merge(Salla.config.default_properties),Salla.config.triedToGetCurrencies_=!1,Salla.config.triedToGetLanguages_=!1,Salla.config.isUser=()=>"user"===Salla.config.get("user.type"),Salla.config.isGuest=()=>!Salla.config.isUser(),Salla.config.languages=async()=>{var e;if(Salla.config.triedToGetLanguages_||Salla.config.get("languages",[]).length>0)return Salla.config.get("languages",[]);Salla.config.triedToGetLanguages_=!0;let t=!0,a=[];return null==(e=await salla.document.api.request("languages",null,"get"))||null==(e=e.data)||e.map(e=>{t&&(a=[],t=!1),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_=!0;let t=!0,a={};return null==(e=await salla.currency.api.list())||null==(e=e.data)||e.map(e=>{t&&(a={},t=!1),e.country_code=e.code.substr(0,2).toLowerCase(),a[e.code]=e}),t?Salla.config.get("currencies",{}):(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())||Salla.config.get("theme.is_spa_webview")};const f=Object.freeze(["ar","bg","cs","da","de","el","en","es","et","fa","fi","fr","ga","he","hi","hr","hu","hy","ind","it","ja","ko","lv","ms","mt","nl","pl","pt","ro","ru","sl","sq","sv","tl","tr","uk","ur","zh","bn"]);function m(){var e;const t=["undefined"!=typeof window?window.locale:null,"undefined"!=typeof document?null==(e=document.documentElement)?void 0:e.lang:null];for(const e of t){const t=String(e||"").trim().toLowerCase().split(/[-_]/)[0];if(f.includes(t))return t}return null}class F{constructor(){this.endpoints={},this.webEndpoints=[],this.namespace="BaseApi",this.endpointsMethods={},this.endpointsHeaders={},this.headersAllowlist={};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:!0,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}}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));let n={headers:i};return Array.isArray(this.headersAllowlist)&&this.headersAllowlist.length&&("get"===a?t=Object.assign({},t,{headersAllowlist:this.headersAllowlist}):n.headersAllowlist=this.headersAllowlist),Salla.api.request(s,t,a,n)}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]}}const D=["skip_page_options"];function v(e){var t;const a=null!=(t=null==e?void 0:e.payload)?t:e;return"undefined"!=typeof FormData&&a instanceof FormData||"undefined"!=typeof HTMLFormElement&&a instanceof HTMLFormElement}class y extends F{constructor(){super(),this.addToCartTries=0,this.guestCartAssigned=!1,this.namespace="cart",this._pendingCartIdRequest=null,this._pendingAssignRequest=null,this._pendingOffersRequest=null,this._pendingItemUpdates={},this._itemUpdateQueues={},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",deleteCouponByCode:"cart/{id}/coupon/{code}",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",latestApi:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",deleteCouponByCode:"delete",getQuickOrderSettings:"get",offers:"get",giftCartDetails:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",()=>{salla.config.isGuest()&&!salla.api.cart.getStoredCartId()||salla.api.cart.getCurrentCartId(!1,"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(!0,"auth::verified")},{async:!0}),salla.event.on("twilight::initiated",()=>salla.api.cart.syncGuestCart()),salla.event.on("profile::info.fetched",()=>this._checkCurrentCart(!0)),salla.event.on("twilight::error",e=>(e.includes("Cart not available")||e.includes("السلة غير متاحة"))&&salla.cart.api.reset()),salla.event.on("cart::updated",()=>{Salla.api.cart._pendingOffersRequest=null})}_checkCurrentCart(e=!1){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,n=Salla.url.is_page("cart");r&&r.id&&!e&&(!n&&(r.store_id!==i||s&&r.user_id!==s)&&(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()),n&&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()))}getStoredCartId(){var e;return(null==(e=Salla.cart.api.latestCart)||null==(e=e.cart)?void 0:e.id)||Salla.storage.get("cart.id")||null}async getCurrentCartId(e=!1,t="getCurrentCartId",a=!0){if(!e&&!a&&salla.config.isGuest()&&!Salla.cart.api.getStoredCartId())return null;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 r=Salla.cart.api._pendingCartIdRequest;return Salla.cart.api._pendingCartIdRequest=null,r}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=[]){if(!(e=e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.details",!1))){const e=new Error("Cart not created yet");return e.name="CartNotCreated",salla.cart.event.detailsNotFetched(e),Promise.reject(e)}return 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"})}reportPageOptionsValidity(e){var t;if("undefined"==typeof document||!Salla.url.is_page("product.single")||String(e)!==String(Salla.config.get("page.id")))return!0;let a=null==(t=document.querySelector(`salla-product-options[product-id="${e}"]`))?void 0:t.closest("form");return"function"!=typeof(null==a?void 0:a.reportValidity)||a.reportValidity()}async addItem(e){var t,a;let r=this.getCartPayload(e);if(!r.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let s=salla.form.getPossibleValue(r.payload,["endpoint"]);s&&["addItem","quickAdd"].includes(s)||(s=salla.form.getPossibleValue(r.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let i=salla.form.getPossibleValue(r.payload,["skip_page_options"]);if(i&&"Object"===(null==(t=r.payload)||null==(t=t.constructor)?void 0:t.name)){let e=h(r.payload,D);r.payload=e}if("addItem"===s&&!i&&!Salla.cart.api.reportPageOptionsValidity(r.id)){let e="The product options are not valid!";return salla.cart.event.itemAddedFailed(e,r.id),salla.api.errorPromise(e)}let n=null==(a=r.payload)?void 0:a.source;r.payload&&delete r.payload.source,Salla.cart.api.addToCartSource=n||null;let o=await Salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addItem");try{r.payload=Salla.helpers.createFormDataWrapper(r.payload||{}),await Salla.cart.event.beforeAddItem(r)}catch(e){}return this.request([s,o,r.id],r.payload.getRawData()).then(function(e){Salla.cart.api.addToCartTries=0;try{Salla.cart.event.itemAdded(e,r.id)}catch(e){Salla.log(e)}return e}).catch(function(t){var a;if(422!==(null==t||null==(a=t.response)?void 0:a.status)&&!Salla.cart.api.addToCartTries)return Salla.cart.api.addToCartTries++,Salla.cart.reset(),Salla.cart.api.addItem(e);throw Salla.cart.event.itemAddedFailed(t,r.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(!1,"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){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}const a=String(t.id);return new Promise((e,r)=>{this._itemUpdateQueues[a]||(this._itemUpdateQueues[a]=[]);const s=this._itemUpdateQueues[a],i=s[s.length-1],n={resolve:e,reject:r};i&&!i.sending&&v(i.data)&&v(t)?(i.data=t,i.waiters.push(n)):s.push({data:t,waiters:[n],sending:!1}),this._queueItemUpdate(a)})}_queueItemUpdate(e){if(this._pendingItemUpdates[e])return;const t=this._flushItemUpdates(e).finally(()=>{var a;this._pendingItemUpdates[e]===t&&delete this._pendingItemUpdates[e],null!=(a=this._itemUpdateQueues[e])&&a.length&&this._queueItemUpdate(e)});this._pendingItemUpdates[e]=t}async _flushItemUpdates(e){await Promise.resolve();const t=this._itemUpdateQueues[e];if(t){for(;t.length;){const e=t[0];e.sending=!0;try{const t=await this._sendUpdateItem(e.data);e.waiters.forEach(e=>e.resolve(t))}catch(t){e.waiters.forEach(e=>e.reject(t))}t[0]===e&&t.shift()}t.length||delete this._itemUpdateQueues[e]}}async _sendUpdateItem(e){var t;let a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.updateItem"),r=Salla.url.is_page("cart");return"Object"===(null==(t=e.payload.constructor)?void 0:t.name)?(e.payload._method="PUT",r&&(e.payload.refresh_page=1)):(e.payload.append("_method","PUT"),r&&e.payload.set("refresh_page",1)),this.request(["updateItem",a,e.id],e.payload).then(function(t){return salla.cart.event.itemUpdated(t,e.id),t}).catch(function(t){throw salla.cart.event.itemUpdatedFailed(t,e.id),t})}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(!1,"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=!1){e=e||await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status");try{await salla.cart.event.submitting()}catch(e){salla.log("Error on: salla.cart.event.submitting()")}const a=salla.config.isGuest();t&&!a&&(e=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.status"));const r={has_apple_pay:salla.helpers.hasApplePay()};return t&&a&&(r.guest_checkout=1),this.request(["status",e],{params:r})}async submit(e=!1,t=!1){const a=salla.config.get("store.features",[]).includes("embedded-login-checkout");if(salla.config.isGuest()){if(!(salla.config.get("store.features",[]).includes("cross-store-login")&&await salla.cart.tryCrossStoreLogin())&&salla.config.isGuest()){if(!a&&!t)return salla.cart.loginOnCartPage();try{await salla.api.cart.syncGuestCart()}catch(e){salla.log("Error on syncGuestCart during guest checkout",e)}}}let r;if(e)try{var s;const e=await Salla.api.cart.assign();r=null==e||null==(s=e.data)?void 0:s.cart_id}catch(e){Salla.log("Error on assign after login from submit",e)}const i=salla.config.isGuest()&&(t||a),n=null!=r?r:await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.submit");return this.status(n,i).then(e=>{var t;let a=null==(t=e.data.next_step)?void 0:t.to;if(!a)return window.history.pushState({},"",salla.url.addParamToUrl("reload","empty_next_step")),window.history.pushState({},"",salla.url.addParamToUrl("acitve",!1===e.data.active?"false":"true_or_undfined")),salla.cart.reset(),window.location.reload();if(!["checkout","refresh","login"].includes(a)){let e="Can't find next_step );";throw salla.cart.reset(),salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===a)return salla.cart.loginOnCartPage();if("checkout"===a){var r,s;let t=null==(r=e.data.next_step)?void 0:r.url;if(!t){let e="Checkout URL is missing from response";throw salla.cart.event.submitFailed(e),e}return salla.helpers.hasApplePay()&&(t+=(t.includes("?")?"&":"?")+"has_apple_pay=true"),null!=(s=salla.mobile)&&null!=s.isSpaWebview&&s.isSpaWebview()&&salla.mobile.openCheckout?salla.mobile.openCheckout(t):window.location.href=t}window.history.pushState({},"",salla.url.addParamToUrl("reload","refresh")),window.location.reload()}).catch(function(a){var r;if((e=>{var t,a,r;const s=null==e||null==(t=e.response)?void 0:t.data,i=null!=(a=null==s?void 0:s.fields)?a:null==s||null==(r=s.error)?void 0:r.fields;return Array.isArray(null==i?void 0:i.options)&&i.options.length>0})(a)){var s;const e=salla.url.get("cart");return null!=(s=salla.mobile)&&null!=s.isSpaWebview&&s.isSpaWebview()&&salla.mobile.openCheckout?(salla.cart.event.submitFailed(a),salla.mobile.openCheckout(e)):window.location.href=e}salla.cart.api.tries=salla.cart.api.tries||0,salla.cart.reset();let o=404===(null==a||null==(r=a.response)||null==(r=r.data)?void 0:r.status);if(o&&0===salla.cart.api.tries)return salla.cart.api.tries++,salla.log("we recived that the current cart is not found, we will try to re-submit one more time"),salla.cart.submit(e,t);if(o){try{var l,u;salla.analytics.log("CartNotFound",{cart_id:n,tries:salla.cart.api.tries,with_assign:e,skip_login:t,is_guest_checkout:i,status:null==a||null==(l=a.response)?void 0:l.status,message:(null==a||null==(u=a.response)||null==(u=u.data)||null==(u=u.error)?void 0:u.message)||(null==a?void 0:a.message),url:window.location.href})}catch(e){}salla.error(salla.lang.get("pages.checkout.try_again"))}throw salla.cart.event.submitFailed(a),a})}getCartPayload(e){var t;let a=(null==(t=e)?void 0:t.data)||("object"==typeof e?e:void 0);return e=a?salla.form.getPossibleValue(a,["prod_id","product_id","item_id","id"]):e,a="object"==typeof a?a:void 0,{id:e,payload:a}}normalRequest(e,t=void 0,a=null){var r=this;return super.normalRequest(e,t,a).catch(async function(e){var t;throw 403===(null==e||null==(t=e.response)?void 0:t.status)&&(r.reset(),salla.error(salla.lang.get("pages.checkout.try_again"))),e})}reset(){salla.api.cart.latestCart=null,salla.storage.remove("cart"),salla.cookie.clearCookieByPrefix(salla.api.cart.getCartCookiePrefix()),salla.cart.event.successReset()}async addCoupon(e){if(e=e.data||e,!(e=salla.form.getPossibleValue(e,["coupon"]))){let e=new Error('There is no "Coupon Code"!');return e.name="EmptyCoupon",salla.event.cart.couponAdditionFailed(e),salla.api.errorPromise(e)}let t=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.addCoupon");return this.request(["addCoupon",t],{coupon:e}).then(function(e){var a;let r=salla.storage.get("cart");if(r&&null!=(a=e.data)&&a.cart){let t=e.data.cart;t.coupon&&(r.coupon=t.coupon),Array.isArray(t.coupons)&&(r.coupons=t.coupons),void 0!==t.multi_coupon&&(r.multi_coupon=t.multi_coupon),salla.storage.set("cart",r)}return salla.event.cart.couponAdded(e,t),e}).catch(function(e){throw salla.event.cart.couponAdditionFailed(e,t),e})}async deleteCoupon(e=null){let t=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.deleteCoupon");return(e?this.request(["deleteCouponByCode",t,encodeURIComponent(e)],{}):this.request(["deleteCoupon",t],{})).then(function(a){let r=salla.storage.get("cart");if(r){var s;let t=null==(s=a.data)?void 0:s.cart;var i;if(t&&Array.isArray(t.coupons))r.coupons=t.coupons,r.coupon=t.coupon||(null!=(i=t.coupons[0])?i:void 0),r.coupon||delete r.coupon;else e&&Array.isArray(r.coupons)?(r.coupons=r.coupons.filter(function(t){return t!==e}),r.coupon=r.coupons[0]||void 0,r.coupon||delete r.coupon):r.coupon&&delete r.coupon;salla.storage.set("cart",r)}return salla.event.cart.couponDeleted(a,t),a}).catch(function(e){throw salla.event.cart.couponDeletionFailed(e,t),e})}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(!1,"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(!1),salla.event.dispatch("login::open",{withoutReload:!0,source:"cart-submit",pendingCartSubmit:!0}),salla.auth.event.onLoggedIn(()=>{salla.event.dispatch("login::close"),salla.cart.submit(!0)})}tryCrossStoreLogin(e=1500){return salla.config.isGuest()?salla.config.get("store.features",[]).includes("sso-login")?Promise.resolve(!1):new Promise(t=>{const a=salla.config.get("login.url","https://accounts.salla.com");let r;try{r=new URL(a).origin}catch(e){r="https://accounts.salla.com"}const s=document.createElement("iframe");s.style.display="none",s.src=a;let i=!1,n=!1,o=!1;const l=e=>{i||(i=!0,clearTimeout(u),window.removeEventListener("message",c),s.remove(),!e&&o&&(salla.storage.remove("token"),salla.api.setHeader("Authorization",null)),t(e))};let u=setTimeout(()=>l(!1),e);const c=async function(t){var a,c;if(t.origin!==r||t.source!==s.contentWindow||"login"!==(null==(a=t.data)?void 0:a.source))return;const h=null==(c=t.data.type)?void 0:c.replace("iframe::","");var p;if("ready"===h)return clearTimeout(u),u=setTimeout(()=>l(!1),e),s.contentWindow.postMessage({source:"login",type:"init",data:{id:salla.config.get("store.id"),lang:salla.lang.locale,apiUrl:null==(p=salla.config.get("store.api"))?void 0:p.replace(/\/+$/,"")}},r);if("storage"===h){var g;if(i||n)return;const e=null==(g=t.data.message)?void 0:g.token,a="string"==typeof e?e.replace(/^"|"$/g,""):e;if(!a)return l(!1);n=!0,clearTimeout(u),u=setTimeout(()=>l(!1),8e3);try{var f;salla.auth.event.tokenFetched(a),o=!0;const e=await salla.api.cart.assign().catch(e=>(salla.log("cross-store login: cart assign failed",e),null));if(i)return;if(!salla.auth.api.isSessionless()&&(await salla.auth.api.request("auth/jwt").catch(e=>salla.log("cross-store login: auth/jwt (web session) failed",e)),i))return;if(await salla.auth.event.loggedIn({data:{token:a}}),i)return;if(salla.config.isGuest())return l(!1);const t=salla.config.get("user")||{};t.id&&(salla.api.setHeader("s-user-id",t.id),t.country_code&&salla.api.setHeader("s-country",t.country_code),t.currency_code&&salla.api.setHeader("currency",t.currency_code));const r=null==e||null==(f=e.data)?void 0:f.cart_id;r?(salla.api.cart.latestCart=null,salla.storage.set("cart",d({},salla.storage.get("cart")||{},{id:r}))):await salla.api.cart.getCurrentCartId(!0,"cross-store-login").catch(e=>salla.log("cross-store login: cart id refresh failed",e)),l(!0)}catch(e){salla.log("Silent cross-store login failed",e),l(!1)}}};window.addEventListener("message",c),document.body.appendChild(s)}):Promise.resolve(!0)}set(e){salla.storage.set("cart",e),salla.api.cart.syncGuestCart()}async offers(){var e=this;return Salla.api.cart._pendingOffersRequest||(Salla.api.cart._pendingOffersRequest=async function(){try{const t=await salla.cart.api.getCurrentCartId(!1,"salla.api.cart.offers",!1);if(!t){const e=new Error("Cart not created yet");throw e.name="CartNotCreated",salla.event.cart.offersFailed(e),e}return await e.request(["offers",t]).then(e=>(salla.event.cart.offersFetched(e),e)).catch(e=>{throw salla.event.cart.offersFailed(e),e})}finally{Salla.api.cart._pendingOffersRequest=null}}()),Salla.api.cart._pendingOffersRequest}async getGiftCartDetails(){let e=await salla.api.cart.getCurrentCartId(!1,"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=!1){let a=await salla.api.cart.getCurrentCartId(!1,"salla.api.cart.addCartGiftToCart");return this.request(["cartGiftToCart",a],e).then(e=>(salla.cart.api.reset(),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=!0,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 w extends F{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange",loyaltyPoints:"profile/loyalty/points"},this.endpointsMethods={getProgram:"get",reset:"put",loyaltyPoints:"get"},this.after_init()}getPoints(){if(salla.config.isGuest()){let e="Can't get points for guest user, please login to get points";return salla.loyalty.event.loyaltyPointsNotFetched(e),salla.api.errorPromise(e)}if(!this.isFeatureEnabled()){let e="Unable to get loyalty points";return salla.loyalty.event.loyaltyPointsNotFetched(e),salla.api.errorPromise(e)}return this.request("loyaltyPoints").then(e=>(salla.loyalty.event.loyaltyPointsFetched(e),e)).catch(e=>{throw salla.loyalty.event.loyaltyPointsNotFetched(e),e})}isFeatureEnabled(){return(salla.config.get("store.features")||[]).includes("loyalty-system")}getProgram(){if(!this.isFeatureEnabled()){let e="Unable to get loyalty program";return salla.loyalty.event.programNotFetched(e),salla.api.errorPromise(e)}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,a=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find prize id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId(!1,"salla.api.loyalty.exchange"))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}const r={loyalty_prize_id:e,cart_id:t};return a&&(r.selected_product_id=a),this.request("exchange",r).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(!1,"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})}}const S="salla::login-resume";class b extends F{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,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",!1)}),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=!0){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=!1!==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,r;e.data||(e={data:e});let s="authenticated"===(null==(a=e.data)?void 0:a.case);return s&&salla.auth.event.tokenFetched(e.data.token),t&&!this.inIframe&&!this.isSessionless()&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.api.handlAfterAuthenticatedResponse"}),s&&await salla.auth.event.loggedIn(e).then(()=>salla.auth.api.afterUserLogin()),await salla.auth.event.verified(e,null==(r=e.data.verification)?void 0:r.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=!0){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})}requireLoginThen(e,t,a=null){var r;if(!salla.config.isGuest())return t();this.pendingAfterLogin_=this.pendingAfterLogin_||{},null==(r=this.pendingAfterLogin_[e])||r.cancel();const s=()=>{salla.event.off(e,i),salla.event.off("salla-login::dismissed",s),delete this.pendingAfterLogin_[e],this.afterLoginEvent.event===e&&(this.afterLoginEvent={event:null,payload:null},this.pendingResume_=null)},i=()=>{s(),t()};i.cancel=s,this.pendingAfterLogin_[e]=i,salla.event.on(e,i),salla.event.on("salla-login::dismissed",s),salla.api.auth.setAfterLoginEvent(e),this.pendingResume_=a,salla.auth.event.dispatch("login::open",{withoutReload:!0})}rememberPendingForRedirect(){var e;null!=(e=this.pendingResume_)&&e.action&&salla.storage.setWithTTL(S,d({},this.pendingResume_,{path:window.location.pathname+window.location.search}),10,"session")}takeResume(e,t){if(salla.config.isGuest())return null;const a=salla.storage.getWithTTL(S,null,"session");return a&&a.action===e?void 0!==t&&String(a.payload)!==String(t)?null:(salla.storage.setWithTTL(S,null,0,"session"),a.path===window.location.pathname+window.location.search?a:null):null}afterUserLogin(){if(!this.afterLoginEvent.event)return;const{event:e,payload:t}=this.afterLoginEvent;this.afterLoginEvent={event:null,payload:null},salla.event.emit(e,t)}isSessionless(){var e;return"sessionless"===(null!=(e=salla.config.get("auth.mode"))?e:salla.config.get("login.mode"))}trackBlockedError(e,t){var a;void 0===(null==e||null==(a=e.response)||null==(a=a.headers)?void 0:a["s-ray"])&&salla.analytics.track("BlockedByProxy",{class:"auth",function:t,reason:"non-server-request",message:e.message})}}class _ extends F{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",reorderProduct:"reorder/product/{id}",sendInvoice:"orders/send/{id}",fetch:"orders",details:"orders/{id}",editOrder:"orders/{id}",cancelEditSession:"orders/cancel-edit-session",getBranchDetails:"orders/{id}/pickup",getShipments:"orders/{id}/shipments"},this.endpointsMethods={createCartFromOrder:"get",fetch:"get",details:"get",editOrder:"put",cancel:"post",cancelEditSession:"post",getBranchDetails:"get",getShipments:"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,t){var a;e=e||Salla.config.get("page.id");const r={params:{has_apple_pay:salla.helpers.hasApplePay()}},s=null==t||null==(a=t.reasons)?void 0:a.filter(e=>null!=e&&""!==e);if(null!=s&&s.length){var i;r.reasons=s.map(String);const e=null==(i=t.reason_note)?void 0:i.trim();e&&(r.reason_note=e)}return this.request(["cancel",e],r).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=d({},t.data,{type:"reorder",id:e}),r=d({},t,{data:a});return salla.event.order.orderCreated(r,t.data.order_id),window.location.href=t.data.url,t}).catch(function(t){throw salla.event.order.orderCreationFailed(t,e),t})}sendInvoice(e){let t=salla.form.getPossibleValue(e,["id"])||salla.config.get("page.id");if(!t){let e="There is no id!";return salla.order.event.invoiceNotSent(e),salla.api.errorPromise(e)}return this.request(["sendInvoice",t],e).then(e=>(salla.event.order.invoiceSent(e,t),e)).catch(e=>{throw salla.event.order.invoiceNotSent(e,t),e})}editOrder(e,t){return e=e||salla.config.get("page.id"),this.request(["editOrder",e],t).then(function(t){return salla.event.order.orderEdited(t,e),t}).catch(function(t){throw salla.event.order.orderNotEdited(t,e),t})}cancelEditSession(e){return this.request(["cancelEditSession"],{order_id:e}).then(function(t){return salla.event.order.editSessionCanceled(t,e),t}).catch(function(t){throw salla.event.order.editSessionNotCanceled(t,e),t})}fetch(e){return this.request(["fetch"],{params:e}).then(function(e){return salla.event.order.ordersFetched(e),e}).catch(function(e){throw salla.event.order.ordersNotFetched(e),e})}getDetails(e){if(!(e=e||salla.config.get("page.id"))){let e="There is no order id!";return salla.event.order.detailsNotFetched(e),salla.api.errorPromise(e)}return this.request(["details",e],null,"get").then(function(t){return salla.event.order.detailsFetched(t,e),t}).catch(function(t){throw salla.event.order.detailsNotFetched(t,e),t})}getBranchDetails(e){if(!(e=e||salla.config.get("page.id"))){let e="There is no order id!";return salla.event.order.branchDetailsNotFetched(e),salla.api.errorPromise(e)}return this.request(["getBranchDetails",e],null,"get").then(function(t){return salla.event.order.branchDetailsFetched(t,e),t}).catch(function(t){throw salla.event.order.branchDetailsNotFetched(t,e),t})}getShipments(e,t=void 0){return(e=e||salla.config.get("page.id"))?this.request(["getShipments",e],{params:{with_products:1},signal:t},"get"):salla.api.errorPromise("There is no order id!")}}class C extends F{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",getOptions:"product/options",getOrderOptions:"product/options"},this.endpointsMethods={details:"get",giftProductDetails:"get",fetch:"get",offers:"get",fetchOptions:"get",getOptions:"get",getOrderOptions:"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(t=>(this.updateAvailabilityStorage(e),salla.product.event.availabilitySubscribed(t,e),t)).catch(function(t){throw salla.product.event.availabilitySubscribeFailed(t,e),t})}updateAvailabilityStorage(e){let t=salla.storage.get("salla::availability",[]);t.includes(Number(e))||(t.push(Number(e)),salla.storage.set("salla::availability",t))}isSubscribedToAvailability(e){return salla.storage.get("salla::availability",[]).includes(Number(e))||!!salla.storage.get(`product-${e}-subscribed`)}getAvailabilityChannels(){let e=salla.config.get("store.settings.product.availability_notify");if(!e)return"";let t=[];return e.email&&t.push("email"),(e.sms||e.mobile||e.whatsapp)&&t.push("sms"),t.join(",")}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=!1){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 Salla.api.withoutNotifier(()=>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}))}getOptions(e){return this.request(this.endpoints.getOptions,{params:{products:e}},"get")}getOrderOptions(e){return this.getOptions(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 A extends F{constructor(){super(),this.namespace="profile",this.endpoints={info:"auth/user",fields:"profile/fields",update:"profile/update",updateContacts:"profile/contacts/update",updateCustomFields:"profile/fields",updateSettings:"profile/settings",verify:"profile/verify",delete:"profile",deleteRequestInitiate:"account/data-request",deleteRequestVerify:"account/data-request/verify",deleteRequestGet:"account/data-request",deleteRequestCancel:"account/data-request/cancel"},this.endpointsMethods={delete:"delete",deleteRequestGet:"get",deleteRequestCancel:"post"},this.after_init()}syncUserData(e){if(!e||!e.phone)return;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,preferences:e.preferences,can_comment:salla.config.get("user.can_comment"),fetched_at:Date.now()};salla.config.set("user",d({},t,{language_code:m()||t.language_code})),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})}getFields(){return this.request("fields",null,"get").then(e=>e.data).catch(()=>(salla.logger.warn("[profile.getFields] failed"),[]))}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})}initiateDeleteRequest(e){return salla.api.withoutNotifier(()=>this.normalRequest("deleteRequestInitiate",{request_type:"delete_account",type:e}))}verifyDeleteRequest(e){return salla.api.withoutNotifier(()=>this.normalRequest("deleteRequestVerify",{request_type:"delete_account",type:e.type,code:e.code}))}getDeleteRequest(){return salla.api.withoutNotifier(()=>this.normalRequest("deleteRequestGet",{params:{request_type:"delete_account"}},"get"))}cancelDeleteRequest(){return salla.api.withoutNotifier(()=>this.normalRequest("deleteRequestCancel",{request_type:"delete_account"}))}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 E extends F{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,!0)))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","blogs"].includes(e.type)?"blog/articles":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=!1){let a={};if(["id","type","comment","per_page","page","sort"].forEach(t=>{let r=salla.form.getPossibleValue(e,[t]);r&&(a[t]=r)}),!t){let t=e.ids;if(t&&(a.ids=Array.isArray(t)?t:[t]),!a.ids||!a.ids.length)return"Failed to get ids!"}return a.type&&["products","pages","product","page","blogs","blog"].includes(a.type)?(a.type+=["product","page"].includes(a.type)?"s":"",a):"Failed to get type one of:(products, product, page, pages, blog, blogs)!"}fetchComments(e){const t=e.customerId;if("string"==typeof(e=this.getCommentPayload(e)))return salla.event.comment.fetchFailed(e),salla.api.errorPromise(e);const a={per_page:e.per_page||5,page:e.page||1,type:e.type,ids:e.ids};return e.sort&&(a.sort=e.sort),t&&(a.private_comments=t),this.request(["comments"],{params:a},"get").then(function(t){return salla.event.comment.fetched(t,e),t}).catch(function(t){throw salla.event.comment.fetchFailed(t,e),t})}getComments(e,t,a=1,r=5,s,i=null){const n=Array.isArray(t)?t:[t];return this.fetchComments({ids:n,type:`${e}s`,page:a,per_page:r,sort:s,customerId:i})}}class k extends F{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 B extends F{constructor(){super(),this.namespace="document"}reload(){window.location.reload()}}class P extends F{constructor(){super(),this.namespace="rating",this.endpoints={store:"rating/store",products:"rating/products",shipping:"rating/shipping",order:"rating/{order_id}",productEligibility:"rating/products/{product_id}/eligibility"},this.endpointsMethods={order:"get",productEligibility:"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})}productEligibility(e){return e?this.request(["productEligibility",e]):salla.api.errorPromise('There is no "product_id"!')}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})}}const q="salla::wishlist-hydrated-user";class L extends F{constructor(){super(),this.namespace="wishlist",this.syncStorageFromServerPromise=null,this.endpoints={add:"products/favorites/{id}",remove:"products/favorites/{id}",share:"products/favorites/share"},this.endpointsMethods={remove:"delete"},Salla.onReady(()=>{var e;const t=salla.auth.api.takeResume("wishlist.add"),a=!t&&salla.auth.api.takeResume("wishlist.remove");t&&this.resumeAfterLogin(t.payload,!0),a&&this.resumeAfterLogin(a.payload,!1),"customer.wishlist"===Salla.config.get("page.slug")&&(null!=(e=Salla.storage.getWithTTL("s-utms"))&&e["s-utm-source"]||this.injectSourceIntoRequest())}),salla.event.on("api::initiated",()=>this.syncStorageFromServer())}injectSourceIntoRequest(){Salla.api.axios.interceptors.request.use(e=>(e.headers=d({},e.headers,{"s-utm-source":"wishlist"}),e),e=>Promise.reject(e))}getWishlistIds(){const e=salla.storage.get("salla::wishlist",[]);return Array.isArray(e)?e.filter(e=>"number"==typeof e):[]}has(e){return this.getWishlistIds().includes(Number(e))}async syncStorageFromServer(){const e=salla.config.get("user.id")||salla.storage.get("user.id"),t=salla.config.get("store.id"),a=e&&null!=t&&""!==t?`${t}--${e}`:null;return salla.config.isGuest()||!a?Promise.resolve():salla.storage.get(q)===a?this.notifyStorageSynced():(this.syncStorageFromServerPromise||(this.syncStorageFromServerPromise=this.request("products/favorites",void 0,"get").then(e=>{var t,r,s;const i=null!=(t=null!=(r=null==e||null==(s=e.data)?void 0:s.data)?r:null==e?void 0:e.data)?t:e,n=[...new Set((Array.isArray(i)?i:[]).map(e=>{var t,a;return null!=(t=null==e||null==(a=e.product)?void 0:a.id)?t:null==e?void 0:e.id}).filter(e=>"number"==typeof e))];return salla.storage.set("salla::wishlist",n),salla.storage.set(q,a),this.notifyStorageSynced()}).catch(e=>{const t=(null==e?void 0:e.code)||(null==e?void 0:e.name)||"";["ERR_CANCELED","CanceledError","AbortError"].includes(t)||salla.log("Wishlist hydration failed",e)}).finally(()=>{this.syncStorageFromServerPromise=null})),this.syncStorageFromServerPromise)}notifyStorageSynced(){return new Promise(e=>{queueMicrotask(()=>{salla.event.emit("wishlist::storage.synced"),e()})})}toggle(e){return this.has(e)?this.remove(e):this.add(e)}resumeAfterLogin(e,t){return this.syncStorageFromServer().catch(()=>{}).then(()=>{if(this.has(e)!==t)return t?this.add(e):this.remove(e)}).catch(()=>{})}async add(e){var t;try{const t={preventDefault:!1,product_id:e};if(await Salla.wishlist.event.beforeAddItem(t),t.preventDefault)return}catch(a){}let a;return e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]),salla.config.isGuest()?(e&&salla.api.auth.requireLoginThen(`wishlist::add.after-login.${e}`,()=>this.resumeAfterLogin(e,!0),{action:"wishlist.add",payload:e}),salla.api.errorPromise(salla.lang.get("common.messages.must_login"))):e?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("Failed to get product id!"))}async remove(e){var t;try{const t={preventDefault:!1,product_id:e};if(await Salla.wishlist.event.beforeRemoveItem(t),t.preventDefault)return}catch(a){}let a;return e=salla.form.getPossibleValue((null==(t=e)?void 0:t.data)||e,["product_id","id"]),salla.config.isGuest()?(e&&salla.api.auth.requireLoginThen(`wishlist::remove.after-login.${e}`,()=>this.resumeAfterLogin(e,!1),{action:"wishlist.remove",payload:e}),salla.api.errorPromise(salla.lang.get("common.messages.must_login"))):e?this.request(["remove",e]).then(t=>(this.updateWishlistStorage(e,!1),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("Failed to get id!"))}async share(e,t=!1){try{const a={preventDefault:!1,select_all:t,product_ids:e};if(await Salla.wishlist.event.beforeShare(a),a.preventDefault)return;t=a.select_all,e=a.product_ids}catch(a){}let a;return salla.config.isGuest()?(salla.wishlist.event.sharingFailed(a=salla.lang.get("common.messages.must_login")),salla.error(a),salla.api.errorPromise(a)):(Array.isArray(e)||(e=[]),t||e.length?this.request("share",{select_all:t,product_ids:e}).then(t=>(salla.wishlist.event.shared(t,e),t)).catch(function(t){throw salla.wishlist.event.sharingFailed(t,e),t}):(salla.wishlist.event.sharingFailed(a="No products selected to share!"),salla.api.errorPromise(a)))}updateWishlistStorage(e,t=!0){let a=this.getWishlistIds();t?a.includes(Number(e))||a.push(Number(e)):a=a.filter(t=>Number(t)!==Number(e)),salla.storage.set("salla::wishlist",a)}}class R extends F{constructor(){super(),this.namespace="scopes",this.endpoints={get:"scopes",change:"scopes",getProductAvailability:"scopes/availability?product_id={id}"},this.after_init()}get(){return salla.config.get("store.scope")?this.request("scopes",null,"get").then(e=>(salla.scope.event.fetched(e),e)).catch(e=>{throw salla.scope.event.notFetched(e),e}):(salla.log("Scope:: skipped /scopes request, store has no scope configured."),Promise.reject(new Error("scope is not configured for this store")))}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 T extends F{constructor(){super(),this.namespace="booking",this.endpoints={add:"cart/booking/product/{id}"},this.endpointsMethods={add:"get"}}async add(e,t=!0){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 I extends F{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}",breadcrumbs:"breadcrumbs"},this.endpointsMethods={getDetails:"get",breadcrumbs:"get"},this.after_init()}getDetails(e){if(!e){let e="page landing id not passed";return salla.event.landing.getDetailsFailed(e),salla.api.errorPromise(e)}return this.request(["getDetails",e]).then(function(t){return salla.event.landing.detailsFetched(t,e),t}).catch(function(t){throw salla.event.landing.getDetailsFailed(t,e),t})}createCartFromPage(e){if(!e){let e="page landing id not passed";return salla.event.landing.orderCreationFailed(e),salla.api.errorPromise(e)}return salla.config.isGuest()?(salla.auth.api.setAfterLoginEvent("landing::createCartFromPage",e),salla.event.dispatch("login::open"),salla.api.successPromise("")):this.request(["createCartFromPage",e]).then(function(t){return salla.event.landing.orderCreated(t,e).then(()=>location.href=t.data.url),t}).catch(function(t){throw salla.event.landing.orderCreationFailed(t,e),t})}fetchBreadcrumbs(e){if(!e.page){let e="The 'page' parameter is required for the Breadcrumb API. Please provide a valid 'page' parameter.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if("product.single"===e.page&&!e.id&&!e.parent_id){let e="The 'id' and 'parent_id' parameters are required when the 'page' parameter is set to 'product.single'. Please provide valid values for both parameters.";return salla.event.landing.breadcrumbFetchFailed(e),salla.api.errorPromise(e)}if(["product.index","customer.orders.single","product.index.tag","page-single","landing-page","brands.single","blog.single","blog.index.author","blog.index.category","blog.index.tag"].includes(e.page)&&!e.id){let t=`The 'id' parameter is required when the 'page' parameter is set to ${e.page}. Please provide valid value for the 'ID' parameter.`;return salla.event.landing.breadcrumbFetchFailed(t),salla.api.errorPromise(t)}return this.request("breadcrumbs",{params:e}).then(function(e){return salla.event.landing.breadcrumbFetched(e),e}).catch(function(e){throw salla.event.landing.breadcrumbFetchFailed(e),e})}}class x extends F{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})}}const O={fbclid:{key:"fbclid",platform:"meta"},ttclid:{key:"ttclid",platform:"tiktok"},sccid:{key:"sccid",platform:"snapchat"},gclid:{key:"gclid",platform:"google"},gbraid:{key:"gbraid",platform:"google"},wbraid:{key:"wbraid",platform:"google"},gad_source:{key:"gad_source",platform:"google"},twclid:{key:"twclid",platform:"x"}},N={_fbp:"fbp",_fbc:"fbc",_ttp:"_ttp",_scid:"_scid",_scid_r:"_scid_r",_gcl_aw:"_gcl_aw",_gcl_au:"_gcl_au"},U=/^[A-Za-z0-9._-]{1,150}$/,M="s-client-ids",j=["gclid","gbraid","wbraid","gad_source","_gcl_aw","_gcl_au"],H=/(^|\/)(cart|checkout|orders)(\/|$)/i;function $(){var e;return!0===(null==(e=Salla.config.get("store.features",[]))?void 0:e.includes("utm-client-ids"))}function z(e=null){var t;return null==(t=Salla.config.get("store.features"))||!t.includes("website-cookies")||"accepted"===(null!=e?e:Salla.storage.get("cookies-consent"))&&"true"===Salla.cookie.get("advertising_cookies")}class W{constructor(){this.collect(),Salla.event.on("salla-cookies-bar::accepted",()=>this.collect("accepted")),Salla.event.on("salla-cookies-bar::rejected",()=>this.clear())}collect(e=null){if($())if(this.hasConsent(e))try{const e=Salla.storage.getWithTTL(M)||{},t=d({},e.client_ids||{}),a=[...e.touches||[]],r=this.readClickIds(),s=this.readCookies();Object.entries(r).forEach(([e,{value:r,platform:s}])=>{t[e]=r,this.addTouch(a,s,r)});const i=Q(t,s);if(!Object.keys(i).length)return;Salla.storage.setWithTTL(M,{client_ids:i,touches:a},129600)}catch(e){Salla.log("Error collecting client ids:",e)}else this.clear();else this.clear()}clear(){Salla.storage.remove(`${M}_${Salla.config.get("store.id")}`)}hasConsent(e=null){return z(e)}readClickIds(){const e={};try{new URLSearchParams(window.location.search).forEach((t,a)=>{const r=O[a.toLowerCase()];r&&this.isValid(t)&&(e[r.key]={value:t,platform:r.platform})})}catch(e){Salla.log("Error reading click ids:",e)}return e}readCookies(){return V()}addTouch(e,t,a){if(!e.some(e=>e.id===a))for(e.push({platform:t,id:a,at:(new Date).toISOString()});e.length>5;)e.shift()}isValid(e){return G(e)}}function G(e){return"string"==typeof e&&U.test(e)}function V(){const e={};return document.cookie.split(";").forEach(t=>{const a=t.trim(),r=a.indexOf("=");if(-1===r)return;const s=N[a.slice(0,r)];if(!s)return;const i=function(e){try{return decodeURIComponent(e)}catch(t){return e}}(a.slice(r+1));G(i)&&(e[s]=i)}),e}function Q(e,t){const a=d({},e,t),r=e.fbclid,s=e=>String(e||"").endsWith(`.${r}`);return r&&!s(a.fbc)&&(a.fbc=s(e.fbc)?e.fbc:`fb.1.${Date.now()}.${r}`),a}const K=["post","put","patch"];function J(e){const t=function(e){try{return new URL((null==e?void 0:e.url)||"",(null==e?void 0:e.baseURL)||window.location.origin)}catch(e){return null}}(e);return!!t&&(a=t.origin,[Salla.config.get("store.api"),Salla.config.get("store.url")].filter(Boolean).some(e=>{try{return new URL(e,window.location.origin).origin===a}catch(e){return!1}}))&&H.test(t.pathname);var a}function X(e){if(!function(e){const t=String((null==e?void 0:e.method)||"").toLowerCase();return K.includes(t)&&J(e)}(e))return e;const t=function(){if(!$()||!z())return null;try{const e=Salla.storage.getWithTTL(M),t=Q(d({},(null==e?void 0:e.client_ids)||{}),V()),a=[...(null==e?void 0:e.touches)||[]].slice(-5);return Object.keys(t).length?{clientIds:t,touches:a}:null}catch(e){return Salla.log("Error reading client ids for payload:",e),null}}();if(!t)return e;const a=e.data instanceof FormData,{clientIds:r,touches:s}=function(e,t,a=0){let r=d({},e),s=[...t];const i=()=>JSON.stringify({client_ids:r,client_touches:s}).length+a*(Object.keys(r).length+3*s.length);for(;i()>2048&&s.length;)s.shift();for(const e of j){if(i()<=2048)break;delete r[e]}return{clientIds:r,touches:s}}(t.clientIds,t.touches,a?120:0);if(!Object.keys(r).length)return e;if(a)return function(e,t,a){Object.entries(t).forEach(([t,a])=>e.append(`client_ids[${t}]`,a)),a.forEach((t,a)=>{e.append(`client_touches[${a}][platform]`,t.platform),e.append(`client_touches[${a}][id]`,t.id),e.append(`client_touches[${a}][at]`,t.at)})}(e.data,r,s),e;if("string"==typeof e.data){try{const t=JSON.parse(e.data);t&&"object"==typeof t&&!Array.isArray(t)&&(t.client_ids=r,t.client_touches=s,e.data=JSON.stringify(t))}catch(e){}return e}return e.data&&"object"==typeof e.data?(e.data.client_ids=r,e.data.client_touches=s,e):(e.data={client_ids:r,client_touches:s},e)}class Z{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"),salla.config.set("user.type","guest")}),this.notifier_handler_disabled=!1,this.notifier_suppression_count=0,this.axios=r.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{const a=Salla.config.get("swoole",[]),r=new RegExp(a.join("|"),"i");if(a.length>0&&r.test(e.url)&&(e.headers["s-store-api-version"]="swoole"),J(e)||this.declaresHeader(e,"s-anonymous-id")){var t;const a=null==(t=Salla.analytics)?void 0:t.getAnonymousId();a&&(e.headers["s-anonymous-id"]=a)}X(e)}catch(e){Salla.log("Error in request interceptor:",e)}return this.applyHeadersAllowlist(e),e},e=>Promise.reject(e)),this.axios.interceptors.response.use(e=>{try{var t;if(/\/products\/?$/.test((null==(t=e.config)?void 0:t.url)||"")){var a,r;const t=(null==(a=e.headers)?void 0:a["s-request-id"])||(null==(r=e.data)?void 0:r.request_id);t&&e.data&&(e.data._requestId=t)}}catch(e){}return e})}declaresHeader(e,t){const a=null==e?void 0:e.headersAllowlist;return Array.isArray(a)&&a.some(e=>String(e).toLowerCase()===t)}applyHeadersAllowlist(e){const t=null==e?void 0:e.headersAllowlist;if(!Array.isArray(t)||!t.length||!e.headers)return;const a=new Set(t.map(e=>String(e).toLowerCase())),r="function"==typeof e.headers.toJSON?e.headers.toJSON():e.headers;Object.keys(r).forEach(t=>{a.has(t.toLowerCase())||(e.headers[t]=null)}),delete e.headersAllowlist}getHeaders(){let e=d({},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){const a=salla.infiniteScroll.fetchOptions.headers,r=String(e).toLowerCase();return Object.keys(a).forEach(t=>{t!==e&&t.toLowerCase()===r&&delete a[t]}),a[e]=this.axios.defaults.headers.common[e]=t,this}async withoutNotifier(e){return this.notifier_suppression_count++,this.notifier_handler_disabled=!0,await e().finally(()=>{this.notifier_suppression_count=Math.max(0,this.notifier_suppression_count-1),0===this.notifier_suppression_count&&(this.notifier_handler_disabled=!1)})}async initiateRequest(e){var t,a,r;this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders(d({"Store-Identifier":Salla.config.get("store.id"),currency:(null==(t=e.user)?void 0:t.currency_code)||"SAR","accept-language":salla.lang.getLocale(),"s-user-id":null==(a=e.user)?void 0:a.id,"s-country":null==(r=e.user)?void 0:r.country_code},e.headers||{}));const s=Salla.config.get("store.scope",Salla.storage.get("scope")),i=new URLSearchParams(window.location.search),n=i.get("scope"),o=i.get("allocation_type"),l=i.get("allocation_id");if(n&&s&&!Salla.url.is_page("cart")){const e=Salla.storage.get("scope")||{};Salla.storage.set("scope",d({},e,{type:s.type,id:n},o&&{allocation_type:o},l&&{allocation_id:l})),String(n)!==String(s.id)&&Salla.cart.reset(),s.id=n}if((o||l)&&(Salla.url.is_page("cart")||!n||!s)){const e=Salla.storage.get("scope")||{};var u,c;if(null!=e&&e.id||null!=s&&s.id)Salla.storage.set("scope",d({},e,{id:null!=(u=null==e?void 0:e.id)?u:null==s?void 0:s.id,type:null!=(c=null==e?void 0:e.type)?c:null==s?void 0:s.type},o&&{allocation_type:o},l&&{allocation_id:l}))}if(s){this.setHeaders({"s-scope-type":s.type,"s-scope-id":s.id});const e=Salla.storage.get("scope")||{};e.allocation_type&&this.setHeader("s-scope-allocation-type",e.allocation_type),e.allocation_id&&this.setHeader("s-scope-allocation-id",e.allocation_id)}const h=Salla.storage.getWithTTL("s-utms");if(h){const e={};Object.entries(h).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=this.getToken(),o="guest"===(null==(t=e.user)?void 0:t.type),l=parseInt((null==(a=e.user)?void 0:a.id)||0),u=parseInt(salla.storage.get("user.id")||0),c=salla.auth.api.isSessionless(),d=e=>{this.setToken(e),salla.event.emit("api::initiated")},h=async function(){o||c||!l?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(!n)return salla.log("Api:: case 1 => current is is guest"),void await h();try{i=s.jwtDecode(n)}catch(e){return Salla.logger.warn("Failed to decode JWT token",e),void Salla.auth.event.tokenInvalid()}if(Date.now()/1e3>i.exp)return salla.log("Api:: case 2 => current user is logged-in and there is a token, but it's expired"),void await h();const p=salla.storage.get("user");if(o&&"user"===(null==p?void 0:p.type)&&parseInt(i.sub)===u){salla.log("Api:: case 2.5 => guest web but a matching logged-in user is in storage, trust it"),salla.config.set("user",p),this.setHeader("Authorization","Bearer "+n);try{!this.inIframe&&!c&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests.storageLogin"}),d(n)}catch(e){this.setHeader("Authorization",null),salla.auth.event.tokenInvalid()}return}let g;if(g=c?parseInt(i.sub)!==u:!u||!l||u!==l||parseInt(i.sub)!==l,g)return salla.log("Api:: case 3 => there is a token and user in session/local missing or mismatch"),salla.log(`sub:${i.sub} userIdInWeb:${l} userIdInStorage:${u}, isSessionless:${c}`,i.sub,l,u),this.setHeader("Authorization","Bearer "+n),void await salla.profile.info().then(async function(e){!r.inIframe&&!c&&await salla.auth.api.request("auth/jwt",{callerName:"salla.auth.request.injectTokenToTheRequests"}),d(n)}).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"),d(n)}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":m()||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=!1;return"SALLA-BUTTON"===(null==i?void 0:i.tagName)&&(n=!0),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=!0){return new Promise((a,r)=>t?a(e):r(e))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}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 Y extends F{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 ee extends F{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 te extends F{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 ae extends F{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})}}const re=["limit","max_recommendations"];class se extends F{constructor(){super(),this.namespace="recommendations",this.endpoints={customersAlsoBought:"products/customers-also-bought",similarProducts:"products/similar-products",customersAlsoViewed:"products/customers-also-viewed",buyAgain:"customers/buy-again",personalizedShoppersWhoBought:"customers/personalized-shoppers-who-bought",boughtTogether:"carts/bought-together"},this.endpointsMethods={customersAlsoBought:"get",similarProducts:"get",customersAlsoViewed:"get",buyAgain:"get",personalizedShoppersWhoBought:"get",boughtTogether:"get"},this.headersAllowlist=["Authorization","Content-Type","Accept-Language","lang","s-store-id","s-scope-id","s-app-name","s-app-version","s-app-os","s-source","s-request-id","s-anonymous-id","s-user-id"]}getBaseUrl(){return Salla.config.get("recommendations.api").replace(/\/$/,"")}getRecommendationHeaders(){return{"s-store-id":Salla.config.get("store.id"),"s-source":"twilight"}}getUrl(e){const t=super.getUrl(...arguments);return`${this.getBaseUrl()}/${t}`}customersAlsoBought(e,t={}){return this.requestProductRecommendations("customersAlsoBought",e,t,{fetched:"customersAlsoBoughtFetched",failed:"customersAlsoBoughtFailed"},"Product id is required for customers-also-bought recommendations.")}similarProducts(e,t={}){return this.requestProductRecommendations("similarProducts",e,t,{fetched:"similarProductsFetched",failed:"similarProductsFailed"},"Product id is required for similar-products recommendations.")}customersAlsoViewed(e,t={}){return this.requestProductRecommendations("customersAlsoViewed",e,t,{fetched:"customersAlsoViewedFetched",failed:"customersAlsoViewedFailed"},"Product id is required for customers-also-viewed recommendations.")}buyAgain(e={}){return this.requestCustomerRecommendations("buyAgain",e,{fetched:"buyAgainFetched",failed:"buyAgainFailed"})}personalizedShoppersWhoBought(e={}){return this.requestCustomerRecommendations("personalizedShoppersWhoBought",e,{fetched:"personalizedShoppersWhoBoughtFetched",failed:"personalizedShoppersWhoBoughtFailed"})}boughtTogether(e,t={}){const a=this.normalizeProductIdsList(e);if(!a.length){const e="Product ids are required for bought-together recommendations.";return salla.event.recommendations.boughtTogetherFailed(e),this.wrapRecommendationResponse(salla.api.errorPromise(e))}return this.requestCartRecommendations("boughtTogether",d({product_ids:a},this.normalizeRecommendationParams(t)),{fetched:"boughtTogetherFetched",failed:"boughtTogetherFailed"},a)}requestProductRecommendations(e,t,a,r,s){return t?this.wrapRecommendationResponse(this.request(e,{params:d({product_id:t},this.normalizeRecommendationParams(a)),headers:this.getRecommendationHeaders()},"get").then(e=>(salla.event.recommendations[r.fetched](e,t),e)).catch(e=>{throw salla.event.recommendations[r.failed](e,t),e})):(salla.event.recommendations[r.failed](s),this.wrapRecommendationResponse(salla.api.errorPromise(s)))}requestCustomerRecommendations(e,t,a){return this.wrapRecommendationResponse(this.request(e,{params:this.normalizeRecommendationParams(t),headers:this.getRecommendationHeaders()},"get").then(e=>(salla.event.recommendations[a.fetched](e),e)).catch(e=>{throw salla.event.recommendations[a.failed](e),e}))}requestCartRecommendations(e,t,a,r=null){return this.wrapRecommendationResponse(this.request(e,{params:t,paramsSerializer:this.serializeRepeatedQueryParams,headers:this.getRecommendationHeaders()},"get").then(e=>(salla.event.recommendations[a.fetched](e,r),e)).catch(e=>{throw salla.event.recommendations[a.failed](e,r),e}))}normalizeRecommendationParams(e={}){const{limit:t,max_recommendations:a}=e,r=d({},h(e,re));return r.max_recommendations=null!=t?t:null!=a?a:5,r}serializeRepeatedQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([e,a])=>{Array.isArray(a)?a.forEach(a=>t.append(e,String(a))):null!=a&&t.append(e,String(a))}),t.toString()}normalizeProductIdsList(e){if(!e)return[];return(Array.isArray(e)?e:[e]).map(e=>this.parseProductId(e)).filter(e=>null!==e)}wrapRecommendationResponse(e){return e.extractProductIds=()=>e.then(e=>this.extractProductIds(e)),e}extractProductIds(e){var t,a,r;if(!e)return[];return(Array.isArray(e)?e:Array.isArray(e.data)?e.data:null!=(t=null!=(a=null!=(r=e.products)?r:e.items)?a:e.recommendations)?t:[]).map(e=>this.parseProductId(e)).filter(e=>null!==e)}parseProductId(e){if("number"==typeof e)return e;if("string"==typeof e){const t=Number(e);return Number.isNaN(t)?null:t}if(e&&"object"==typeof e){var t,a;const r=null!=(t=null!=(a=e.id)?a:e.product_id)?t:e.objectID;if(null==r||""===r)return null;const s=Number(r);return Number.isNaN(s)?null:s}return null}}class ie extends F{constructor(){super(),this.namespace="search",this.endpoints={popular:"products/recommendations"},this.endpointsMethods={popular:"get"},this.after_init()}popular(){return this.request("popular",null,"get").then(e=>(salla.search.event.popularFetched(e),e)).catch(e=>{throw salla.search.event.popularFailed(e),e})}}class ne{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(this.configKey,null,"session");return t&&"object"==typeof t&&null!=(e=t.store)&&e.id&&this.config.store.id==t.store.id?t: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(this.configKey,e,30,"session"),e}}class oe{constructor(){Salla.event.on("twilight::before.ready",()=>this.renderAll())}async renderAll(){this.registerOrderSingleRatingPopupTrigger(),this.registerWishlistNavIconMount(),this.registerFreeShippingBannerMount(),this.registerFreeShippingTagMount(),Salla.hooks.renderAutoComponents([{hook:"product:single.description",tag:"salla-delivery-promise",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("delivery-promises")},{hook:"product:single.description",tag:"salla-loyalty-banner",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("loyalty-system")},{hook:"product:single.description",tag:"salla-loyalty-points-banner",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("loyalty-system")},{hook:"product:single.description",tag:"salla-cashback-banner",canRender:()=>Salla.url.is_page("product.single")},{hook:"product:single.form.end",tag:"salla-fulfillment-methods",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.features",[]).includes("delivery-promises")},{hook:"body:end",tag:"salla-cookies-bar",canRender:()=>{var e;return null==(e=Salla.config.get("store.features"))?void 0:e.includes("website-cookies")}},{hook:"body:end",tag:"salla-bullet-delivery",canRender:()=>{var e;return(null==(e=Salla.config.get("store.features"))?void 0:e.includes("bullet-delivery-v2"))&&!0===Salla.config.get("store.settings.bullet_delivery.enabled")}},{hook:"product:single.description.end",tag:"salla-bought-together",canRender:()=>Salla.url.is_page("product.single")&&Salla.config.get("store.settings.product.bought_together")},{hook:"product:single.description.end",tag:"salla-verified-review",canRender:()=>Salla.url.is_page("product.single")},{hook:"cart:items.end",tag:"salla-basket-gap",canRender:()=>Salla.url.is_page("cart")&&Salla.config.get("store.settings.cart.basket_gap")},{hook:"customer:wishlist.items.start",tag:"salla-wishlist-actions",canRender:()=>Salla.url.is_page("customer.wishlist")},{hook:"product:index.items.start",tag:"salla-applied-filters",canRender:()=>Salla.url.is_page("product.index")&&Salla.config.get("store.settings.product.filters")},{hook:"customer:orders.single.details.start",tag:"salla-order-cancel",canRender:()=>Salla.url.is_page("customer.orders.single")}]),await Salla.lang.onLoaded(),this.renderAppInstall(),this.renderEdit(),this.applyContentCopyright(),this.renderTemplateStore(),Salla.helpers.isIframe()||(this.renderMaintenance(),this.renderThemePreview())}registerOrderSingleRatingPopupTrigger(){this._orderSingleRatingPopupTriggerRegistered||(this._orderSingleRatingPopupTriggerRegistered=!0,Salla.hooks.registerHook("salla-hook","componentDidLoad",e=>{if("customer:orders.single.details.start"!==e.name)return;if(!Salla.url.is_page("customer.orders.single"))return;"true"===new URLSearchParams(window.location.search).get("show-rating-popup")&&Salla.event.once("rating::ready",()=>{Salla.event.dispatch("rating::open");const e=new URL(window.location.href);e.searchParams.delete("show-rating-popup"),window.history.replaceState(window.history.state,"",e.toString())})}))}registerFreeShippingBannerMount(){if(this._freeShippingBannerMountRegistered)return;this._freeShippingBannerMountRegistered=!0;const e={"index:start":"home","product.single:start":"product"};Salla.hooks.registerHook("salla-hook","componentDidLoad",t=>{const a=e[t.name];if(!a)return;const r=document.createElement("salla-free-shipping-banner");r.setAttribute("placement",a),t.mount(r)})}registerFreeShippingTagMount(){this._freeShippingTagMountRegistered||(this._freeShippingTagMountRegistered=!0,Salla.hooks.registerHook("salla-hook","componentDidLoad",e=>{if("product:single.description"!==e.name||!Salla.url.is_page("product.single"))return;const t=Salla.config.get("page.id");if(!t)return;const a=document.createElement("salla-free-shipping-tag");a.setAttribute("product-id",t),e.mount(a)}))}registerWishlistNavIconMount(){if(this._wishlistNavIconMountRegistered)return;this._wishlistNavIconMountRegistered=!0;const e=e=>{var t;e&&(e.hasAttribute("inline")||"SALLA-WISHLIST-SUMMARY"!==(null==(t=e.nextElementSibling)?void 0:t.tagName)&&(salla.config.isGuest()||e.insertAdjacentElement("afterend",document.createElement("salla-wishlist-summary"))))};Salla.hooks.registerHook("salla-user-menu","componentDidLoad",t=>{e(null==t?void 0:t.host)}),Salla.event.on("auth::logged.in",()=>{document.querySelectorAll("salla-user-menu").forEach(e)})}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!1;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 le{constructor(e){this.storeUserKey="s-store-user",Salla.event.on("twilight::initiated",()=>this.embedStoreUser()),this.embedUser(e),this.rememberPageLanguage()}rememberPageLanguage(){const e=m();e&&Salla.cookie.get("s-lang")!==e&&Salla.cookie.set("s-lang",e)}embedUser(e){return e.user||(e.user=this.getUser(),e.user.language_code=m()||Salla.cookie.get("s-lang")||e.user.language_code,e.user.currency_code=Salla.cookie.get("s-curr",e.user.currency_code)),e}getUser(){return Salla.storage.get("user",this.getDefaultUser())}getDefaultUser(){return{type:"guest",language_code:m()||Salla.cookie.get("s-lang")||Salla.lang.getLocale(),currency_code:Salla.cookie.get("s-curr","SAR")}}async embedStoreUser(){if(Salla.config.isGuest())return;const e=this.storeUserCacheKey();let t=e&&Salla.storage.getWithTTL(e,null,"session");t||(t=await this.getStoreUserFromApi(e)),e===this.storeUserCacheKey()&&(Salla.config.set("user",d({},Salla.config.get("user"),t)),Salla.log("Store user is embeded to the user object."))}storeUserCacheKey(){const e=Salla.config.get("user.id");return e?`${this.storeUserKey}_${e}`:null}async getStoreUserFromApi(e=this.storeUserCacheKey()){let t={};try{const a=await Salla.api.request("profile/notifications/unread");if(t.notification=a.data.count,t.is_notifiable=a.data.is_notifiable,Salla.config.get("store.features",[]).includes("loyalty-system")){if(this.storeUserCacheKey()!==e)return t;const a=await Salla.api.request("profile/loyalty/points");a&&(t.loyalty_points=a.data.points)}}catch(e){return Salla.log("Failed to get user services",e),t}return e&&Salla.storage.setWithTTL(e,t,5,"session"),t}}class ue{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={};this.extractQueryPairs(window.location.search).filter(([e])=>a.includes(e.toLowerCase())).forEach(([e,t])=>{r[e.toLowerCase()]=this.sanitizeValue(t||"")});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))}extractQueryPairs(e){if(!e)return[];try{if("undefined"!=typeof URLSearchParams)return Array.from(new URLSearchParams(e).entries()).map(([e,t])=>[e,this.decodeQueryValue(t)])}catch(e){Salla.log("Error parsing UTM params:",e)}return e.replace(/^\?/,"").split("&").filter(Boolean).map(e=>{const t=e.indexOf("=");return(-1===t?[e,""]:[e.slice(0,t),e.slice(t+1)]).map(e=>this.decodeMalformedURIComponent(e||"").decoded||"")})}decodeQueryValue(e){return e&&e.includes("%")?this.decodeMalformedURIComponent(e).decoded||"":e}decodeMalformedURIComponent(e){const t={raw:e,decoded:null,status:"valid",issues:[]};if(!/[+%]/.test(e))return t.decoded=e,t;const a=[];let r="";const s=()=>{if(!r.length)return;const e=this.encodeText(r);for(const t of e)a.push(t);r=""};for(let i=0;i<e.length;i++){const n=e[i];if("%"===n){const n=e.slice(i+1,i+3);if(/^[0-9A-Fa-f]{2}$/.test(n)){s(),a.push(parseInt(n,16)),i+=2;continue}t.issues.push(`invalid_percent_at_${i}`),r+="%"}else r+="+"===n?" ":n}return s(),t.decoded=this.decodeText(a),t.decoded.includes("�")&&t.issues.push("invalid_or_incomplete_utf8_sequence"),t.issues.length&&(t.status="repaired"),t}encodeText(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=[];for(let a=0;a<e.length;a++){const r=e.codePointAt(a);r>65535&&(a+=1),r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<65536?t.push(224|r>>12,128|r>>6&63,128|63&r):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r)}return t}decodeText(e){if("undefined"!=typeof TextDecoder)return new TextDecoder("utf-8",{fatal:!1}).decode(new Uint8Array(e));let t="";const a=e=>128==(192&e);for(let r=0;r<e.length;r++){const s=e[r];s<128?t+=String.fromCharCode(s):s>=194&&s<=223&&a(e[r+1])?(t+=String.fromCharCode((31&s)<<6|63&e[r+1]),r+=1):s>=224&&s<=239&&a(e[r+1])&&a(e[r+2])?(t+=String.fromCharCode((15&s)<<12|(63&e[r+1])<<6|63&e[r+2]),r+=2):s>=240&&s<=244&&a(e[r+1])&&a(e[r+2])&&a(e[r+3])?(t+=String.fromCodePoint((7&s)<<18|(63&e[r+1])<<12|(63&e[r+2])<<6|63&e[r+3]),r+=3):t+="�"}return t}sanitizeValue(e){return e.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()}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 ce{constructor(e){var t,a,r,s;if("ready"===Salla.status)return void Salla.log("Trying to re-initiate Salla, while its status === 'ready'!");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}})");(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 oe,new le(e),null!=e&&null!=(r=e.user)&&r.language_code)&&Salla.lang.setLocale(null==e||null==(s=e.user)?void 0:s.language_code);Salla.storage.get("scope.id")!=Salla.config.get("store.scope.id")&&Salla.storage.set("scope",Salla.config.get("store.scope",Salla.config.get("scope")));const i=Salla.storage.get("cart");null!=i&&i.id&&"string"!=typeof i.id&&String(i.id).length>15&&Salla.cart.reset(),new ne(e).getConfig().then(e=>{Salla.config.merge(e),this.setSallaReady(e),this.afterInit()}).catch(e=>console.error("failed to initite twilight😢",e))}afterInit(){Salla.url.is_page("product.single")&&Salla.config.isGuest()&&window.addEventListener("mini-checkout::before-init",e=>{Salla.config.isGuest()&&(e.preventDefault(),Salla.event.emit("login::open"))})}setSallaReady(e){new ue,new W,Salla.event.emitAsync("twilight::before.ready",e),Salla.status="ready",Salla.event.dispatch("twilight::initiated",e),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:e}))}}const de=/^Constructor for ".+#.*" was not found$/;const he="mobile",pe=()=>({}),ge=[{event:"modal::close",action:"modal.close",method:"closeModal",wrap:pe},{action:"scope.open",method:"openScopes"},{event:"language::open",action:"language.open",method:"openLanguages"},{event:"currency::open",action:"currency.open",method:"openCurrencies"},{event:"checkout::open",action:"checkout.open",method:"openCheckout",wrap:e=>{const t="string"==typeof e?e:e&&e.url;return null==t?{}:{url:t}}},{event:"browser::open",action:"browser.open",method:"openBrowser",wrap:e=>"string"==typeof e?{url:e}:e||{}},{event:"ui::alert",action:"ui.alert",method:"alert"},{event:"ui::title",action:"ui.title",method:"setTitle",wrap:e=>"string"==typeof e?{title:e}:e||{}},{event:"ui::print",action:"ui.print",method:"print",wrap:e=>"string"==typeof e?{url:e}:e||{}}];const fe=e=>{if("string"==typeof e)return e;try{var t;return null!=(t=JSON.stringify(e))?t:String(e)}catch(t){try{return String(e)}catch(e){return JSON.stringify({status:"unreadable_result"})}}},me=e=>({content:[{type:"text",text:fe(e)}]}),Fe=e=>{let t;try{var a,r;t=(null==e||null==(a=e.response)||null==(a=a.data)||null==(a=a.error)?void 0:a.message)||(null==e||null==(r=e.response)||null==(r=r.data)?void 0:r.message)||(null==e?void 0:e.message)||String(e)}catch(e){t={status:"unknown_error"}}return d({isError:!0},me(t))},De=e=>async(t={})=>{try{return me(await e(t))}catch(e){return Fe(e)}},ve=e=>{var t,a,r,s;const i=null!=(t=null!=(a=null==e||null==(r=e.data)?void 0:r.cart)?a:null==e?void 0:e.data)?t:e;return{id:null==i?void 0:i.id,total:null==i?void 0:i.total,sub_total:null==i?void 0:i.sub_total,discount:null==i?void 0:i.discount,coupon:null==i?void 0:i.coupon,items_count:null!=(s=null==i?void 0:i.items_count)?s:null==i?void 0:i.count,items:(Array.isArray(null==i?void 0:i.items)?i.items:[]).filter(Boolean).map(e=>({id:e.id,product_id:e.product_id,name:e.product_name||e.name,quantity:e.quantity,price:e.price,total:e.total}))}},ye=e=>({type:["string","number"],description:e}),we=()=>[{name:"search_products",description:"Search this store's products by keyword.",inputSchema:{type:"object",properties:{query:{type:"string"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]},annotations:{readOnlyHint:!0},execute:De(async({query:e,limit:t=10})=>{const{data:a}=await salla.product.fetch({source:"search",source_value:String(e),limit:t})||{};return Array.isArray(a)?a.slice(0,t):a})},{name:"get_product",description:"Get the details of one product by id.",inputSchema:{type:"object",properties:{product_id:ye("Product id")},required:["product_id"]},annotations:{readOnlyHint:!0},execute:De(async({product_id:e})=>{var t;return null==(t=await salla.product.getDetails(e,["options"]))?void 0:t.data})},{name:"get_cart",description:"Get the shopper's current cart: items, totals and coupon.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0},execute:De(async()=>{try{return ve(await salla.cart.details())}catch(e){if("CartNotCreated"===(null==e?void 0:e.name))return ve({items:[],items_count:0});throw e}})},{name:"add_to_cart",description:"Add a product to the shopper's cart. Products with required options must pass them in `options` as { optionId: value }, with option ids from get_product (`options[].id`). The value depends on the option type: for choice options (single-option, multiple-options, color, ...) it is the id of a choice (`options[].details[].id`); for free-input options (text, textarea, number, date, time) it is the value the shopper wants.",inputSchema:{type:"object",properties:{product_id:ye("Product id"),quantity:{type:"number",description:"Defaults to 1"},options:{type:"object",description:"Selected options keyed by option id (get_product: options[].id). Choice options (single-option, multiple-options, color, ...): the id of a choice (options[].details[].id). Free-input options (text, textarea, number, date, time): the shopper's own value."}},required:["product_id"]},execute:De(async({product_id:e,quantity:t=1,options:a})=>{const r={id:e,quantity:t,skip_page_options:!0};return a&&Object.keys(a).length&&(r.options=a),ve(await salla.cart.addItem(r))})},{name:"update_cart_item",description:"Change the quantity of a cart item (use the cart item id from get_cart).",inputSchema:{type:"object",properties:{item_id:ye("Cart item id"),quantity:{type:"number"}},required:["item_id","quantity"]},execute:De(async({item_id:e,quantity:t})=>ve(await salla.cart.updateItem({id:e,quantity:t})))},{name:"remove_cart_item",description:"Remove an item from the cart (use the cart item id from get_cart).",inputSchema:{type:"object",properties:{item_id:ye("Cart item id")},required:["item_id"]},annotations:{destructiveHint:!0},execute:De(async({item_id:e})=>ve(await salla.cart.deleteItem(e)))},{name:"apply_coupon",description:"Apply a coupon code to the cart.",inputSchema:{type:"object",properties:{coupon:{type:"string"}},required:["coupon"]},execute:De(async({coupon:e})=>ve(await salla.cart.addCoupon(e)))},{name:"go_to_checkout",description:"Send the shopper to checkout. Guests are sent to login first. The shopper completes payment themselves.",inputSchema:{type:"object",properties:{}},execute:async()=>{try{let e=0;try{e=ve(await salla.cart.details()).items_count||0}catch(e){if("CartNotCreated"!==(null==e?void 0:e.name))throw e}return e?(await salla.cart.submit(),me({status:"navigating",destination:"checkout"})):d({isError:!0},me({status:"empty_cart",destination:"checkout"}))}catch(e){return Fe(e)}}}],Se=new Map;class be{constructor(){this.controller=null}static get owners(){return Se}static tools(){return we()}static getModelContext(){if("undefined"==typeof document)return null;try{var e,t;return null!=(e=null!=(t=document.modelContext)?t:"undefined"!=typeof navigator?navigator.modelContext:null)?e:null}catch(e){return null}}static isSupported(){var e;return!1!==window.isSecureContext&&"https:"===location.protocol&&"function"==typeof(null==(e=be.getModelContext())?void 0:e.registerTool)&&"function"==typeof AbortController}static isEnabled(){const e=Salla.config.get("webmcp.enabled");return!0===e||"true"===e||1===e||"1"===e}static onRegisterError(e,t){"InvalidStateError"!==(null==t?void 0:t.name)?Salla.log("WebMCP: failed to register "+e.name,t):Salla.log("WebMCP: "+e.name+" is already registered, skipping")}enable(){if(this.controller||!be.isSupported())return!1;const e=be.getModelContext(),t=this.controller=new AbortController,{signal:a}=t,r=t=>{a.aborted?(e=>{const t=Se.get(e);return!!t&&!t.signal.aborted})(t.name)||(this.controller?Se.set(t.name,{signal:this.controller.signal}):(Se.delete(t.name),(t=>{try{null==e.unregisterTool||e.unregisterTool(t)}catch(e){}})(t.name))):Se.set(t.name,{signal:a})};return we().forEach(t=>{try{const s=e.registerTool(t,{signal:a});"function"==typeof(null==s?void 0:s.then)?s.then(()=>r(t),e=>be.onRegisterError(t,e)).catch(e=>Salla.log("WebMCP: failed to settle "+t.name,e)):r(t)}catch(e){be.onRegisterError(t,e)}}),!0}disable(){if(!this.controller)return;const e=be.getModelContext(),{signal:t}=this.controller;this.controller.abort(),this.controller=null,Se.forEach((a,r)=>{if(a.signal===t){Se.delete(r);try{null==e||null==e.unregisterTool||e.unregisterTool(r)}catch(e){}}})}init(){try{be.isEnabled()&&this.enable()}catch(e){Salla.log("WebMCP: init failed",e)}}}e.versions.twilight="2.14.612",e.onInitiated=e=>salla.event.once("twilight::initiated",e),e.onReady=e.onReady||function(t){return new Promise(function(a){return"ready"===salla.status?a(t?t(salla.config.all()):salla.config.all()):e.onInitiated(e=>a(t?t(e):e))})},e.status="loading",e.notify=u,e.lang=new class extends a{constructor(e){e=e||{};const t=salla.cookie.get("s-lang");e.messages=e.messages||window.translations,e.locale=e.locale||m()||(t||navigator.language||navigator.userLanguage||"ar").split("-")[0],e.fallback=e.fallback||e.locale,super(e),this.translationsLoaded=!1,this._subscribers=new Set,Salla.event.on("twilight::before.ready",()=>this.loadStoreTranslations())}subscribe(e){return this._subscribers.add(e),this.translationsLoaded&&e(),()=>this._subscribers.delete(e)}_notifySubscribers(){this._subscribers.forEach(e=>e())}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");const e=this.getLocale()+".trans",t=salla.storage.get(`s_translations.${this.hash}`);this.messages=t&&(t[e]?{[e]:t[e]}:Object.keys(t).some(e=>e.endsWith(".trans"))?null:t),this.messages&&(this.translationsLoaded=!0,super.setMessages(this.messages),this.messages=this.wrapMessages(this.messages))}if(this.messages)return salla.event.dispatch("languages::translations.loaded"),this._notifySubscribers(),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",!1)}setMessages(e){super.setMessages(e),this.messages=this.wrapMessages(this.messages),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0,this._notifySubscribers()}wrapMessages(e){return e&&"object"==typeof e&&"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("string"==typeof t&&t.endsWith(".trans")&&!(t in e)&&(e[t]={}),e[t])}):e}loadScript(e,t=!0){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations){const e=this.getLocale()+".trans",t=window.translations[e],a=t?{[e]:t}:window.translations;try{salla.storage.remove("s_translations"),salla.storage.set("s_translations",{[this.hash]:a})}catch(e){salla.logger.warn("Could not cache translations in storage",e)}return 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",!1);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.getLocaleMessages(this.getLocale()),e,t),this}getLocaleMessages(e){const t=`${e}.trans`;return this.messages=this.messages||{},this.messages[t]=this.messages[t]||{},this.messages[t]}add(e,t){return Object.entries(t).forEach(t=>salla.helpers.setNested(this.getLocaleMessages(t[0]),e,t[1])),this}addBulk(e){return Object.entries(e).forEach(([e,t])=>{this.add(e,t)}),this}},e.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;"undefined"!=typeof loaderSupported&&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),!1}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()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){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}},e.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":!0,"S-Source":"twilight","X-Requested-With":"XMLHttpRequest","cache-control":"no-cache",pragma:"no-cache"}},this.instances=[]}initiate(e,a,r,s=!1){s?((r=r||{}).fetchOptions=d({},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(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),e.api=new class extends Z{constructor(){super(),this.auth=new b,this.cart=new y,this.loyalty=new w,this.order=new _,this.rating=new P,this.product=new C,this.profile=new A,this.comment=new E,this.currency=new k,this.document=new B,this.wishlist=new L,this.scope=new R,this.booking=new T,this.landing=new I,this.notifications=new x,this.component=new Y,this.advertisement=new ee,this.navigation=new te,this.metadata=new ae,this.recommendations=new se,this.search=new ie}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"}}))}},e.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(){null==salla.auth.api.rememberPendingForRedirect||salla.auth.api.rememberPendingForRedirect();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,!0}},e.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(!1),Salla.event.on("salla-login::ready",()=>Salla.event.emit("login::open",{withoutReload:!0}))}},e.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","beforeBuildListUrl","beforeAppendItems"])],["salla-products-slider",new Set(["componentDidLoad","beforeAppendItems"])],["salla-hook",new Set(["componentDidLoad"])],["salla-scopes",new Set(["componentDidLoad"])],["salla-user-menu",new Set(["componentDidLoad"])],["salla-menu",new Set(["afterFetchMenuItems"])]]),this._themeSlots=["head","head:start","head:end","body:start","body:end","index:start","product:index.items.start","product:index.items.end","product:single.description.start","product:single.description","product:single.description.end","product:single.form.start","product:single.form.end","blog:index.items.start","blog:index.items.end","blog:single.items.start","blog:single.items.end","brands:index.items.start","brands:index.items.end","brands:single.details.start","brands:single.details.end","brands:single.items.start","brands:single.items.end","cart:items.start","cart:items.end","cart:summary.start","cart:summary.end","cart:submit.start","cart:submit.end","customer:notifications.items.start","customer:notifications.items.end","customer:orders.index.items.start","customer:orders.index.items.end","customer:orders.single.details.start","customer:orders.single.details.end","customer:wishlist.items.start","customer:wishlist.items.end","customer:profile.form.start","customer:profile.form.fields.start","customer:profile.form.fields.end","customer:profile.form.submit.start","customer:profile.form.submit.end","customer:profile.form.end","thank-you:start","thank-you:items.start","thank-you:items.end","thank-you:end"];const e=Salla.config.get("page.slug");e&&(this._themeSlots.push(e+":start"),this._themeSlots.push(e+":end")),Salla.onReady(()=>{const e=Salla.config.get("page.slug");e&&(this._themeSlots.includes(e+":start")||this._themeSlots.push(e+":start"),this._themeSlots.includes(e+":end")||this._themeSlots.push(e+":end"))}),this._componentHistory=new Map}renderAutoComponents(e){Array.isArray(e)&&0!==e.length&&e.forEach(({hook:e,tag:t,canRender:a})=>{a&&!a()||this.mount(e,document.createElement(t))})}registerHook(e,t,a,r={}){if(!this._isAllowed(e,t))return console.warn(`[Hooks] Hook "${e}:${t}" is not allowed`),()=>{};const s=0|r.priority,i=!!r.once,n=this._ensureTag(e),o=n.get(t)||[];return o.push({cb:a,p:s,once:i}),o.sort((e,t)=>t.p-e.p),n.set(t,o),"componentDidLoad"===t&&this._callForLoadedComponents(e,a),()=>this.removeHook(e,t,a)}registerHookOnce(e,t,a,r={}){return this.registerHook(e,t,a,d({},r,{once:!0}))}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!1;if(!r.has(t))return!1;if(!a)return r.delete(t),0===r.size&&this._store.delete(e),!0;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),!0)}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}"`),!1):(console.warn(`[Hooks] Tag "${e}" is not in the whitelist`),!1)}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","recommendations","search"].forEach(t=>e[t]=new c(e.api[t],e.event[t])),e.call=t=>{let a=e,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},e.analytics=new i,e.mobile=new class{constructor(){this._last={},this._tick=0,this._tickScheduled=!1,this.rows=[{on:"cart::updated",action:"cart.changed",map:this._cart},{on:"cart::latest.fetched",action:"cart.changed",pick:"data.cart",map:this._cart},{on:"cart::item.updated",action:"cart.changed",pick:"data.cart",map:this._cart},{on:"cart::details.fetched",action:"cart.changed",pick:"data.cart",map:this._cart},{on:"auth::verified",action:"auth.changed",pick:"data",map:this._auth},{on:"auth::registered",action:"auth.changed",pick:"data",map:this._auth},{on:"auth::logged.in",action:"auth.changed",pick:"data",map:this._auth},{on:"auth::logged.out",action:"auth.changed",map:()=>({token:null,refresh_token:null,expires_at:null})},{on:"scope::changed",action:"scope.changed",map:this._scope},{on:"currency::changed",action:"currency.changed",map:this._currency},{on:"salla::bullet-delivery.allocation.confirmed",action:"delivery.confirmed",map:this._pass},{on:"salla::bullet-delivery.open-sheet",action:"delivery.open",map:this._pass},{on:"modal::open",action:"modal.open",map:pe},{on:"share-element",action:"share.element",map:this._pass},{on:"booking::open",action:"booking.open",map:this._pass},{on:"booking::added",action:"booking.added",pick:"data",map:this._pass},{on:"booking::addition.failed",action:"booking.failed",map:this._error},{on:"login::open",action:"login.open",map:()=>this.isNativeLoginEnabled()?{}:null}],ge.forEach(e=>{const t=e.wrap||(e=>null==e?{}:e);e.event&&this.rows.push({on:e.event,action:e.action,map:e=>t(e)}),this[e.method]=a=>this.action(e.action,t(a))}),this.route("twilight.loaded",{}),Salla.onReady(e=>{if(!this.isEnabled())return void(Salla.log&&Salla.log("Salla.mobile: not a native webview, bridge is a no-op"));this.rows.forEach(e=>this._subscribe(e)),this.route("twilight.ready",{});const t=Salla.helpers.getNested(e,"page.title");t&&this.setTitle(t)})}isEnabled(){if("undefined"==typeof window)return!1;try{var e,t;return!!(null!=(e=Salla.helpers)&&null!=e.isWebView&&e.isWebView()||null!=(t=Salla.config)&&null!=t.isMobileApp&&t.isMobileApp())}catch(e){return!1}}isSpaWebview(){try{var e;return this.isEnabled()&&!(null==(e=Salla.config)||null==e.get||!e.get("theme.is_spa_webview"))}catch(e){return!1}}isNativeLoginEnabled(){return!!this.isEnabled()&&(null==this._appHeader("s-app-version")?this.isSpaWebview():this._appVersionAtLeast("5.0.38"))}_appVersionAtLeast(e){const t=this._get(()=>Salla.api.getHeaders()["s-app-version"]);return"string"==typeof t&&t.localeCompare(e,void 0,{numeric:!0})>=0}openGallery(e,t){if(!this.isEnabled())return!1;if(!(null==this._appHeader("s-app-full-version")?this.isSpaWebview():this._appFullVersionAtLeast("5.0.38-275")))return!1;const a={images:this._galleryMedia(e)},[r]=this._galleryMedia(t);return r&&(a.selected_Image=r),this.route("gallery.open",a)}_appHeader(e){return this._get(()=>Salla.api.getHeaders()[e])}_versionAtLeast(e,t){if("string"!=typeof e)return!1;const a=e=>e.split(/\D+/).filter(Boolean).map(Number),[r,s]=[a(e),a(t)];for(let e=0;e<Math.max(r.length,s.length);e++)if(r[e]!==s[e])return void 0!==r[e]&&(void 0===s[e]||r[e]>s[e]);return!0}_appFullVersionAtLeast(e){return this._versionAtLeast(this._appHeader("s-app-full-version"),e)}_galleryMedia(e){const t=["cdn.salla.sa","cdn.salla.network","cdn.assets.salla.network","cdn-gnl.salla.sa","s3.eu-central-1.amazonaws.com/cdn.salla.sa","s3.eu-central-1.amazonaws.com/cdn-gnl.salla.sa"],a=e=>"string"==typeof e&&e?e:null,r=e=>void 0===e?null:e;return(null==e?[]:Array.isArray(e)?e:[e]).reduce((e,s)=>{const i="string"==typeof s?(e=>{const a=e.split(/[?#]/)[0].replace(/^https?:\/\//i,"").toLowerCase();return t.some(e=>a.startsWith(`${e}/`))&&/\.[a-z0-9]+$/.test(a)})(s)?{url:s}:null:s;if(!i)return e;const n=a(i.three_d_image_url),o=a(i.video_url),l=a(i.url);return n||o||l?(e.push({id:r(i.id),url:l,main:r(i.main),three_d_image_url:n,alt:r(i.alt),video_url:o,type:n?"3d-image":o?"video":"image",sort:r(i.sort)}),e):e},[])}register(e){return this.rows.push(e),this.isEnabled()&&this._subscribe(e),this}action(e,t={}){return this.route(e,t),this}on(e,t){return Salla.event.on(`${he}::${e}`,t),this}off(e,t){return Salla.event.off(`${he}::${e}`,t),this}_subscribe(e){Salla.event.on(e.on,(...t)=>this.route(e.action,this._safeMap(e,t)))}_safeMap(e,t){try{const a=e.pick?Salla.helpers.getNested(t[0],e.pick):t[0];return e.map.call(this,a,t)}catch(t){return Salla.logger&&Salla.logger.warn&&Salla.logger.warn(`Salla.mobile: mapper failed for '${e.on}'`,t),null}}route(e,t){if(null==t||!this.isEnabled())return!1;if(!this._assertSafeAction(e))return!1;const a=this._fingerprint(t),r=this._currentTick(),s=this._last[e];return(!s||s.tick!==r||s.sig!==a)&&(this._last[e]={sig:a,tick:r},Salla.event.emit(`${he}::${e}`,t),!0)}_assertSafeAction(e){if("string"!=typeof e||-1===e.indexOf("."))return Salla.logger&&Salla.logger.warn&&Salla.logger.warn(`Salla.mobile: action '${e}' rejected — must contain a '.' (e.g. 'cart.changed').`),!1;try{if("function"==typeof(Salla.call&&Salla.call(`${he}.${e}`)))return Salla.logger&&Salla.logger.warn&&Salla.logger.warn(`Salla.mobile: action '${e}' collides with a real Salla.mobile member and would be hijacked by emit(); rejected.`),!1}catch(e){}return!0}_currentTick(){return this._tickScheduled||(this._tickScheduled=!0,Promise.resolve().then(()=>{this._tick++,this._tickScheduled=!1})),this._tick}_fingerprint(e){try{return JSON.stringify(e)}catch(t){return String(e)}}_cart(e){let t=(e=e||{}).id;null==t&&(t=this._get(()=>Salla.cart.api.latestCart.cart.id)),null==t&&(t=this._get(()=>Salla.storage.get("cart.id")));let a=e.count;return null==a&&(a=this._get(()=>Salla.storage.get("cart.summary.count"))),{cartId:null==t?null:t,count:Number(a)||0}}_auth(e){const t=(e=e||{}).token,a="string"==typeof t?t:t&&(t.access_token||t.token)||null;if(!a)return null;const r=e.refresh_token||t&&"object"==typeof t&&t.refresh_token||null;let i=null;try{var n;i=null!=(n=(s.jwtDecode(a)||{}).exp)?n:null}catch(e){}return{token:a,refresh_token:r,expires_at:i}}_scope(e){let t=Salla.helpers.getNested(e,"data.id");return null==t&&(t=this._get(()=>Salla.config.get("scope.id"))),null==t&&(t=this._get(()=>Salla.storage.get("scope.id"))),{id:null==t?null:t}}_currency(e,t){let a=t&&t[1];return null==a&&(a=this._get(()=>Salla.config.get("user.currency_code"))),{code:null==a?null:a}}_pass(e){return null==e?{}:e}_error(e){return{message:"string"==typeof e?e:Salla.helpers.getNested(e,"response.data.error.message")||e&&e.message||null}}_get(e){try{const t=e();return null==t?null:t}catch(e){return null}}},e.webmcp=new be,e.event.once("twilight::initiated",()=>e.webmcp.init()),e.init=e=>new ce(e),new class{constructor(e={}){this.config=d({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=!1,Salla.onReady(()=>this.init())}normalizeUrl(e){try{return new URL(e,location.href)}catch(e){return null}}shouldIgnoreUrl(e){if(!e)return!1;const t="string"==typeof e?e:e.href||String(e),a=t.toLowerCase();if(["tel:","mailto:","javascript:"].some(e=>a.startsWith(e)))return!0;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!1}}isWhitelisted(e){if(!e)return!1;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!0}return!1}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,!0),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,!0)}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:!0})}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=!0}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,!0),this.handleFormSubmit&&document.removeEventListener("submit",this.handleFormSubmit,!0),this.performanceObserver&&this.performanceObserver.disconnect(),this.isInitialized=!1)}},e.errorMonitor=new class{constructor(e={}){this.config=d({LABEL:"salla::frontend.error",SAMPLE_RATE:.1,MAX_PER_MINUTE:20,MAX_PER_SIGNATURE:3,MESSAGE_MAX:500,STACK_MAX:2e3,STALE_CHUNK_RELOAD_FLAG:"salla::stale-chunk-reloaded",SENSITIVE_PARAMS:["token","jwt","access_token","id_token","refresh_token","auth","authorization","api_key","apikey","key","secret","password","signature","sig"],BOT_PATTERN:/bot|crawler|spider|externalagent|webindexer|headlesschrome|lighthouse|slurp|facebookexternalhit/i,CHUNK_ERROR_PATTERN:/dynamically imported module|importing a module script failed/i},e),this.recentSends=[],this.seen=new Map,this.pending=[],this.isReady=!1,this.isInitialized=!1,this.pageHidden=!1,this.init(),Salla.onReady(()=>{this.isReady=!0;this.pending.splice(0).forEach(e=>this.emit(e))})}init(){this.isInitialized||(this.handleError=e=>{try{const t=e.error;this.capture({error_type:"error",name:(null==t?void 0:t.name)||"Error",message:e.message||(null==t?void 0:t.message),stack:null==t?void 0:t.stack,filename:e.filename,lineno:e.lineno,colno:e.colno})}catch(e){}},this.handleRejection=e=>{try{const t=e.reason,a=t instanceof Error,r=a?t.message:this.safeStringify(t);this.capture({error_type:"unhandledrejection",name:a?t.name:typeof t,message:r,stack:a?t.stack:void 0}),this.maybeRecoverFromStaleChunk(r)}catch(e){}},this.handlePageHide=()=>{this.pageHidden=!0},this.handlePageShow=()=>{this.pageHidden=!1},window.addEventListener("error",this.handleError),window.addEventListener("unhandledrejection",this.handleRejection),window.addEventListener("pagehide",this.handlePageHide),window.addEventListener("pageshow",this.handlePageShow),this.isInitialized=!0)}captureChunkError(e,t){try{var a,r;const s=(null==e?void 0:e.message)||this.safeStringify(e);if(!this.config.CHUNK_ERROR_PATTERN.test(s||""))return;const i=null==(a=s.match(/https?:\/\/[^\s'"]+\.js/))?void 0:a[0];this.capture({error_type:"chunk_load",name:(null==e?void 0:e.name)||"Error",message:s,stack:null==e?void 0:e.stack,extra:d({component:null==t||null==(r=t.tagName)?void 0:r.toLowerCase(),chunk_url:i},this.chunkTiming(i))})}catch(e){}}chunkTiming(e){var t;if(!e)return{};const a=null==(t=window.performance)||null==t.getEntriesByName||null==(t=t.getEntriesByName(e,"resource"))?void 0:t.slice(-1)[0];return a?{chunk_timing:"found",chunk_status:a.responseStatus,chunk_duration_ms:Math.round(a.duration)}:{chunk_timing:"none"}}environment(){var e,t,a;const r=navigator.userAgent||"",s=navigator.connection;return{build:null==(e=Salla.versions)?void 0:e.twilight,is_bot:this.config.BOT_PATTERN.test(r)||!0===navigator.webdriver,online:navigator.onLine,visibility:document.visibilityState,page_hidden:this.pageHidden,page_age_ms:Math.round(null!=(t=null==(a=window.performance)||null==a.now?void 0:a.now())?t:0),effective_type:null==s?void 0:s.effectiveType,save_data:null==s?void 0:s.saveData}}maybeRecoverFromStaleChunk(e){if(de.test(e||"")&&!1!==navigator.onLine){try{if(sessionStorage.getItem(this.config.STALE_CHUNK_RELOAD_FLAG))return;sessionStorage.setItem(this.config.STALE_CHUNK_RELOAD_FLAG,"1")}catch(e){return}this.reload()}}reload(){window.location.reload()}signature(e){var t;const a=(null==(t=(e.stack||"").split("\n")[1])?void 0:t.trim())||"";return[e.error_type,e.name,e.message,a,e.filename,e.lineno].filter(Boolean).join("|").slice(0,300)}capture(e){if(!e.message&&!e.stack)return;const t=this.signature(e),a=this.seen.get(t)||0;if(a>=this.config.MAX_PER_SIGNATURE)return;if(Math.random()>this.config.SAMPLE_RATE)return;const r=d({error_type:e.error_type,name:e.name,message:(e.message||"").toString().slice(0,this.config.MESSAGE_MAX),stack:e.stack?String(e.stack).slice(0,this.config.STACK_MAX):void 0,filename:e.filename,lineno:e.lineno,colno:e.colno,url:this.sanitizeUrl(window.location.href),referrer:this.sanitizeUrl(document.referrer)},this.environment(),e.extra);this.seen.set(t,a+1),this.isReady?this.emit(r):this.pending.length<this.config.MAX_PER_MINUTE&&this.pending.push(r)}emit(e){var t,a;const r=null!=(t=null==(a=window.performance)||null==a.now?void 0:a.now())?t:Date.now();if(this.recentSends=this.recentSends.filter(e=>r-e<6e4),!(this.recentSends.length>=this.config.MAX_PER_MINUTE)){this.recentSends.push(r);try{Salla.analytics.log(this.config.LABEL,e)}catch(e){}}}sanitizeUrl(e,t=0){if(e)try{const a=new URL(e,window.location.href);return this.redactParams(a.searchParams,t),a.hash&&this.hashHasSensitive(a.hash)&&(a.hash=""),a.toString()}catch(e){return}}redactParams(e,t=0){const a=this.config.SENSITIVE_PARAMS;for(const r of Array.from(e.keys())){if(a.includes(r.toLowerCase())){e.delete(r);continue}if(t>=3)continue;const s=e.get(r);s&&this.hasSensitiveParam(s)&&e.set(r,this.sanitizeNested(s,t+1))}}sanitizeNested(e,t){if(!e.includes("://")&&!e.includes("?")){const a=new URLSearchParams(e);return this.redactParams(a,t),a.toString()}const a=this.sanitizeUrl(e,t);return null!=a?a:e}hasSensitiveParam(e){const t=e.toLowerCase();return this.config.SENSITIVE_PARAMS.some(e=>{const a=t.indexOf(e+"=");if(a<0)return!1;const r=0===a?"":t[a-1];return""===r||"?"===r||"&"===r||"#"===r||"/"===r})}hashHasSensitive(e){return this.hasSensitiveParam(e)}safeStringify(e){try{return"string"==typeof e?e:JSON.stringify(e)}catch(t){return String(e)}}destroy(){this.isInitialized&&(window.removeEventListener("error",this.handleError),window.removeEventListener("unhandledrejection",this.handleRejection),window.removeEventListener("pagehide",this.handlePageHide),window.removeEventListener("pageshow",this.handlePageShow),this.isInitialized=!1)}},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)}),e.success=e.notify.success,e.error=e.notify.error,window.dispatchEvent(new CustomEvent("salla::created")),module.exports=e;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|