@salla.sa/twilight 2.7.15 → 2.7.16

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.
@@ -23,5 +23,5 @@
23
23
  * @license MIT https://github.com/rmariuzzo/Lang.js/blob/master/LICENSE
24
24
  * @site https://github.com/rmariuzzo/Lang.js
25
25
  * @author Rubens Mariuzzo <rubens@mariuzzo.com>
26
- */!function(e,t){e.exports=function(){function e(){if("undefined"!=typeof document&&document.documentElement)return document.documentElement.lang}function t(e){return"-Inf"===e?-1/0:"+Inf"===e||"Inf"===e||"*"===e?1/0:parseInt(e,10)}var r=/^({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])$/,n=/({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])/,i={locale:"en"},s=function(t){t=t||{},this.locale=t.locale||e()||i.locale,this.fallback=t.fallback,this.messages=t.messages};return s.prototype.setMessages=function(e){this.messages=e},s.prototype.getLocale=function(){return this.locale||this.fallback},s.prototype.setLocale=function(e){this.locale=e},s.prototype.getFallback=function(){return this.fallback},s.prototype.setFallback=function(e){this.fallback=e},s.prototype.has=function(e,t){return!("string"!=typeof e||!this.messages)&&null!==this._getMessage(e,t)},s.prototype.get=function(e,t,r){if(!this.has(e,r))return e;var n=this._getMessage(e,r);return null===n?e:(t&&(n=this._applyReplacements(n,t)),n)},s.prototype.trans=function(e,t){return this.get(e,t)},s.prototype.choice=function(e,t,r,i){(r=void 0!==r?r:{}).count=t;var s=this.get(e,r,i);if(null==s)return s;for(var a=s.split("|"),o=[],l=0;l<a.length;l++)if(a[l]=a[l].trim(),n.test(a[l])){var c=a[l].split(/\s/);o.push(c.shift()),a[l]=c.join(" ")}if(1===a.length)return s;for(var u=0;u<o.length;u++)if(this._testInterval(t,o[u]))return a[u];return i=i||this._getLocale(e),a[this._getPluralForm(t,i)]},s.prototype.transChoice=function(e,t,r){return this.choice(e,t,r)},s.prototype._parseKey=function(e,t){if("string"!=typeof e||"string"!=typeof t)return null;var r=e.split("."),n=r[0].replace(/\//g,".");return{source:t+"."+n,sourceFallback:this.getFallback()+"."+n,entries:r.slice(1)}},s.prototype._getMessage=function(e,t){if(t=t||this.getLocale(),e=this._parseKey(e,t),void 0===this.messages[e.source]&&void 0===this.messages[e.sourceFallback])return null;var r=this.messages[e.source],n=e.entries.slice(),i=n.join(".");if("string"!=typeof(r=void 0!==r?this._getValueInKey(r,i):void 0)&&this.messages[e.sourceFallback])for(r=this.messages[e.sourceFallback],n=e.entries.slice(),i="";n.length&&void 0!==r;)r[i=i?i.concat(".",n.shift()):n.shift()]&&(r=r[i],i="");return"string"!=typeof r?null:r},s.prototype._getValueInKey=function(e,t){if("string"==typeof e[t])return e[t];for(var r=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),n=0,i=r.length;n<i;++n){var s=r.slice(0,n+1).join("."),a=r.slice(n+1,r.length).join(".");if(e[s])return this._getValueInKey(e[s],a)}return e},s.prototype._getLocale=function(e){return e=this._parseKey(e,this.locale),this.messages[e.source]?this.locale:this.messages[e.sourceFallback]?this.fallback:null},s.prototype._findMessageInTree=function(e,t){for(;e.length&&void 0!==t;){var r=e.join(".");if(t[r]){t=t[r];break}t=t[e.shift()]}return t},s.prototype._sortReplacementKeys=function(e,t){return t.length-e.length},s.prototype._applyReplacements=function(e,t){return Object.keys(t).sort(this._sortReplacementKeys).forEach((function(r){e=e.replace(new RegExp(":"+r,"gi"),(function(e){var n=t[r];return e===e.toUpperCase()?n.toUpperCase():e===e.replace(/\w/i,(function(e){return e.toUpperCase()}))?n.charAt(0).toUpperCase()+n.slice(1):n}))})),e},s.prototype._testInterval=function(e,n){if("string"!=typeof n)throw"Invalid interval: should be a string.";var i=(n=n.trim()).match(r);if(!i)throw"Invalid interval: "+n;if(!i[2]){var s=(i=i.filter((function(e){return!!e})))[1],a=t(i[2]);a===1/0&&(a=-1/0);var o=t(i[3]),l=i[4];return("["===s?e>=a:e>a)&&("]"===l?e<=o:e<o)}for(var c=i[2].split(","),u=0;u<c.length;u++)if(parseInt(c[u],10)===e)return!0;return!1},s.prototype._getPluralForm=function(e,t){switch(t){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":default:return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return 1==e?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return 0===e||1===e?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2;case"cs":case"sk":return 1==e?0:e>=2&&e<=4?1:2;case"ga":return 1==e?0:2==e?1:2;case"lt":return e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2;case"sl":return e%100==1?0:e%100==2?1:e%100==3||e%100==4?2:3;case"mk":return e%10==1?0:1;case"mt":return 1==e?0:0===e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3;case"lv":return 0===e?0:e%10==1&&e%100!=11?1:2;case"pl":return 1==e?0:e%10>=2&&e%10<=4&&(e%100<12||e%100>14)?1:2;case"cy":return 1==e?0:2==e?1:8==e||11==e?2:3;case"ro":return 1==e?0:0===e||e%100>0&&e%100<20?1:2;case"ar":return 0===e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11&&e%100<=99?4:5}},s}()}(Vi);var Wi=Vi.exports;var Ji=Object.assign?Object.assign:function(e,t,r,n){for(var i=1;i<arguments.length;i++)es(Object(arguments[i]),(function(t,r){e[r]=t}));return e},Qi=function(){if(Object.create)return function(e,t,r,n){var i=Yi(arguments,1);return Ji.apply(this,[Object.create(e)].concat(i))};{function e(){}return function(t,r,n,i){var s=Yi(arguments,1);return e.prototype=t,Ji.apply(this,[new e].concat(s))}}}(),Ki=String.prototype.trim?function(e){return String.prototype.trim.call(e)}:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},Zi="undefined"!=typeof window?window:w,Xi={assign:Ji,create:Qi,trim:Ki,bind:function(e,t){return function(){return t.apply(e,Array.prototype.slice.call(arguments,0))}},slice:Yi,each:es,map:function(e,t){var r=rs(e)?[]:{};return ts(e,(function(e,n){return r[n]=t(e,n),!1})),r},pluck:ts,isList:rs,isFunction:function(e){return e&&"[object Function]"==={}.toString.call(e)},isObject:function(e){return e&&"[object Object]"==={}.toString.call(e)},Global:Zi};function Yi(e,t){return Array.prototype.slice.call(e,t||0)}function es(e,t){ts(e,(function(e,r){return t(e,r),!1}))}function ts(e,t){if(rs(e)){for(var r=0;r<e.length;r++)if(t(e[r],r))return e[r]}else for(var n in e)if(e.hasOwnProperty(n)&&t(e[n],n))return e[n]}function rs(e){return null!=e&&"function"!=typeof e&&"number"==typeof e.length}var ns=Xi.slice,is=Xi.pluck,ss=Xi.each,as=Xi.bind,os=Xi.create,ls=Xi.isList,cs=Xi.isFunction,us=Xi.isObject,hs={createStore:fs},ds={version:"2.0.12",enabled:!1,get:function(e,t){var r=this.storage.read(this._namespacePrefix+e);return this._deserialize(r,t)},set:function(e,t){return void 0===t?this.remove(e):(this.storage.write(this._namespacePrefix+e,this._serialize(t)),t)},remove:function(e){this.storage.remove(this._namespacePrefix+e)},each:function(e){var t=this;this.storage.each((function(r,n){e.call(t,t._deserialize(r),(n||"").replace(t._namespaceRegexp,""))}))},clearAll:function(){this.storage.clearAll()},hasNamespace:function(e){return this._namespacePrefix=="__storejs_"+e+"_"},createStore:function(){return fs.apply(this,arguments)},addPlugin:function(e){this._addPlugin(e)},namespace:function(e){return fs(this.storage,this.plugins,e)}};function fs(e,t,r){r||(r=""),e&&!ls(e)&&(e=[e]),t&&!ls(t)&&(t=[t]);var n=r?"__storejs_"+r+"_":"",i=r?new RegExp("^"+n):null;if(!/^[a-zA-Z0-9_\-]*$/.test(r))throw new Error("store.js namespaces can only have alphanumerics + underscores and dashes");var s={_namespacePrefix:n,_namespaceRegexp:i,_testStorage:function(e){try{var t="__storejs__test__";e.write(t,t);var r=e.read(t)===t;return e.remove(t),r}catch(e){return!1}},_assignPluginFnProp:function(e,t){var r=this[t];this[t]=function(){var t=ns(arguments,0),n=this;function i(){if(r)return ss(arguments,(function(e,r){t[r]=e})),r.apply(n,t)}var s=[i].concat(t);return e.apply(n,s)}},_serialize:function(e){return JSON.stringify(e)},_deserialize:function(e,t){if(!e)return t;var r="";try{r=JSON.parse(e)}catch(t){r=e}return void 0!==r?r:t},_addStorage:function(e){this.enabled||this._testStorage(e)&&(this.storage=e,this.enabled=!0)},_addPlugin:function(e){var t=this;if(ls(e))ss(e,(function(e){t._addPlugin(e)}));else if(!is(this.plugins,(function(t){return e===t}))){if(this.plugins.push(e),!cs(e))throw new Error("Plugins must be function values that return objects");var r=e.call(this);if(!us(r))throw new Error("Plugins must return an object of function properties");ss(r,(function(r,n){if(!cs(r))throw new Error("Bad plugin property: "+n+" from plugin "+e.name+". Plugins should only return functions.");t._assignPluginFnProp(r,n)}))}},addStorage:function(e){!function(){var e="undefined"==typeof console?null:console;if(e){(e.warn?e.warn:e.log).apply(e,arguments)}}("store.addStorage(storage) is deprecated. Use createStore([storages])"),this._addStorage(e)}},a=os(s,ds,{plugins:[]});return a.raw={},ss(a,(function(e,t){cs(e)&&(a.raw[t]=as(a,e))})),ss(e,(function(e){a._addStorage(e)})),ss(t,(function(e){a._addPlugin(e)})),a}var ps=Xi.Global,gs={name:"localStorage",read:vs,write:function(e,t){return ms().setItem(e,t)},each:function(e){for(var t=ms().length-1;t>=0;t--){var r=ms().key(t);e(vs(r),r)}},remove:function(e){return ms().removeItem(e)},clearAll:function(){return ms().clear()}};function ms(){return ps.localStorage}function vs(e){return ms().getItem(e)}var ys=Xi.Global,bs={name:"sessionStorage",read:_s,write:function(e,t){return ws().setItem(e,t)},each:function(e){for(var t=ws().length-1;t>=0;t--){var r=ws().key(t);e(_s(r),r)}},remove:function(e){return ws().removeItem(e)},clearAll:function(){return ws().clear()}};function ws(){return ys.sessionStorage}function _s(e){return ws().getItem(e)}var Es=Xi.trim,Ss={name:"cookieStorage",read:function(e){if(!e||!Fs(e))return null;var t="(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(xs.cookie.replace(new RegExp(t),"$1"))},write:function(e,t){if(!e)return;xs.cookie=escape(e)+"="+escape(t)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:As,remove:Ps,clearAll:function(){As((function(e,t){Ps(t)}))}},xs=Xi.Global.document;function As(e){for(var t=xs.cookie.split(/; ?/g),r=t.length-1;r>=0;r--)if(Es(t[r])){var n=t[r].split("="),i=unescape(n[0]);e(unescape(n[1]),i)}}function Ps(e){e&&Fs(e)&&(xs.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Fs(e){return new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(xs.cookie)}var Ls={name:"memoryStorage",read:function(e){return Os[e]},write:function(e,t){Os[e]=t},each:function(e){for(var t in Os)Os.hasOwnProperty(t)&&e(Os[t],t)},remove:function(e){delete Os[e]},clearAll:function(e){Os={}}},Os={};const ks=hs.createStore([gs,bs,Ss,Ls],[]);let Ts=new class extends S{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.auth=new o(this),this.cart=new l(this),this.order=new c(this),this.scope=new u(this),this.rating=new h(this),this.comment=new d(this),this.loyalty=new f(this),this.product=new g(this),this.profile=new p(this),this.currency=new y(this),this.document=new m(this),this.twilight=new b(this),this.wishlist=new v(this),this.infiniteScroll=new x(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.noneFireableActions=["document.request"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let e=this;Object.keys(salla).forEach((t=>{"object"==typeof(t=salla[t])&&(e.callSallaInitiate(t),Object.keys(t).forEach((r=>{e.callSallaInitiate(t[r])})))}))}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&"function"==typeof salla.call(r))return salla.log(`'salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);this.emit(e,...t),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:e},...t.values())),this.ingoreLogEvents.includes(e)||!salla.config.get("debug")&&!this.logableEvents.includes(e)||salla.logger.event(e,...t);let n=this;Object.keys(this.globalListners).forEach((function(r){n.globalListners[r](e,...t)})),this.dispatchMobileEvent(e,{...t.values()})}dispatchEvents(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))this.dispatch(t,r);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){salla.logger.warn(e,"The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){salla.logger.warn(e,"The native context does not exist yet")}}},js=new class extends class{constructor(e){return e.on("twilight::initiated",(()=>this.initiateRequest())),e.on("profile::info.fetched",this.setCurrencyAndLanguage),e.on("auth::token.fetched",(e=>this.handleToken(e))),e.on("document::request.failed",((e,t)=>{salla.logger.warn(t,e)})),Vt.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}})}initiateRequest(){salla.api.defaults.baseURL=salla.config.get("store.api",salla.config.get("store.url")),salla.api.defaults.headers.common["Store-Identifier"]=salla.config.get("store.id"),salla.api.defaults.headers.common.currency=salla.config.get("user.currency_code","SAR"),salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=salla.api.defaults.headers.common["accept-language"]=salla.lang.getLocale(),salla.api.defaults.headers.common["s-user-id"]=salla.config.get("user.id");let e=salla.storage.get("scope");e&&(salla.api.defaults.headers.common["s-scope-type"]=e.type,salla.api.defaults.headers.common["s-scope-id"]=e.id),this.injectTokenToTheRequests()}injectTokenToTheRequests(){let e=salla.storage.get("token"),t=salla.config.isGuest(),r=salla.storage.get("cart");if(r&&(r.user_id!==salla.config.get("user.id")||r.store_id!==salla.config.get("store.id")))return salla.log("Auth:: The cart is not belong to current "+(r.user_id!==salla.config.get("user.id")?"user":"store")+"!"),void salla.cart.api.reset();if(t&&!e)return;if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();let n=function(e,t){if("string"!=typeof e)throw new Kt("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(Qt(e.split(".")[r]))}catch(e){throw new Kt("Invalid token specified: "+e.message)}}(e);return Date.now()/1e3>n.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):n.sub!==salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}handleToken(e){salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()}setToken(e){salla.api.defaults.headers.common.Authorization="Bearer "+e}setCurrencyAndLanguage(e){salla.api.defaults.headers.common.currency=e.data.currency,salla.api.defaults.headers.common["accept-language"]=e.data.language,salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=e.data.language}}{constructor(e){super(e),this.apis={auth:new L(this),cart:new P(this),loyalty:new F(this),order:new O(this),rating:new I(this),product:new k(this),profile:new T(this),comment:new j(this),currency:new C(this),document:new R(this),twilight:new N(this),wishlist:new D(this),scope:new U(this),withoutNotifier:async e=>(salla.config.set("sdk.notifier_handler_disabled",!0),await e().finally((()=>{salla.config.set("sdk.notifier_handler_disabled",!1)})))},Object.assign(this,this.apis),this.getHeaders=()=>this.defaults.headers.common}}(Ts);window.Salla=window.salla={notify:i,api:js,event:Ts,helpers:Gi,config:new class{constructor(e={}){this.triedToGetCurrencies_=!1,this.languages_=[],this.triedToGetLanguages_=!1,this.currencies_={},this.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"}}},this.properties_={...this.default_properties,...e}}merge(e){return Object.assign(this.properties_,e),this.properties_.store={...this.default_properties.store,...this.properties_.store},this}set(e,t){return e.includes(".")?(salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)}get(e,t=null){return e.includes(".")?salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0}isUser(){return"user"===this.get("user.type")}isGuest(){return!this.isUser()}async languages(){if(this.triedToGetLanguages_)return this.languages_;this.triedToGetLanguages_=!0;let e=!0;return(await salla.document.api.request("languages",null,"get"))?.data?.map((t=>{e&&(this.languages_=[],e=!1),t.code=t.code||t.iso_code,t.url=salla.url.get(t.code),t.is_rtl=t.is_rtl||t.rtl,this.languages_.push(t)})),this.set("languages",this.languages_),this.languages_}async currencies(){if(this.triedToGetCurrencies_)return this.currencies_;this.triedToGetCurrencies_=!0;let e=!0;return(await salla.currency.api.list())?.data?.map((t=>{e&&(this.currencies_={},e=!1),t.country_code=t.code.substr(0,2).toLowerCase(),this.currencies_[t.code]=t})),this.set("currencies",this.currencies_),this.currencies_}currency(e){return e=e||this.get("user.currency_code"),this.get("currencies."+e)||Object.values(this.get("currencies"))[0]}},storage:new class{constructor(e){e.on("storage::item.remove",(e=>this.remove(e))),e.on("storage::item.set",((e,t)=>this.set(e,t))),this.store=ks}set(e,t){if(e.includes(".")){let r=e.split(".")[0],n={[r]:ks.get(r)};return n=salla.helpers.setNested(n,e,t),ks.set(r,n[r])}return ks.set(e,t)}remove(e){return ks.remove(e)}get(e,t){if(e.includes(".")){let t=e.split(".")[0];return salla.helpers.getNested({[t]:ks.get(t)},e)}return ks.get(e,t)}}(Ts),cookie:new class{constructor(e){e.on("cookies::remove",(e=>this.remove(e))),e.on("cookies::add",((e,t)=>this.set(e,t)))}get(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]}set(e,t="",r=10){let n="";if(r){let e=new Date;e.setTime(e.getTime()+24*r*60*60*1e3),n="; expires="+e.toUTCString()}return document.cookie=`${e}=${t}${n}"; path=/; secure; SameSite=Lax"`,this}remove(e){return document.cookie=`${e}=; Max-Age=0; path=/;`,this}}(Ts),lang:new class extends Wi{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){if(this.translationsLoaded)return e();salla.event.once("languages::translations.loaded",e)}loadStoreTranslations(){if(this.messages)return void window.addEventListener("load",(e=>{salla.event.dispatch("languages::translations.loaded"),salla.logger.info("The messages of transactions is already loaded")}));if(!salla.url.get(""))return void this.loadScript("https://cdn.salla.network/js/translations.js",!1);let e=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight"));this.loadScript(salla.url.get(`languages/assets/${e}.js`))}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0}loadScript(e,t=!0){let r=document.createElement("script");r.src=e,r.onload=()=>window.translations?this.setMessages(window.translations):t?(salla.logger.info("Failed to load Translations for store, lets try load it from cdn"),this.loadScript("https://cdn.salla.network/js/translations.js",!1)):void salla.logger.warn("Failed to load Translations from the cdn\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's."),document.head.appendChild(r)}get(e,t,r){return window.translations&&(e="trans."+e),super.get(e,t,r)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},form:new class{async submit(e,t=null){let r=t;if("SubmitEvent"===t?.constructor?.name){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(),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.twilight.request(e,r,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop()}));let n=e.split("."),i=n.splice(-1);return await salla.call(n.join("."))[i](r).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)}},cart:new Zt(js.cart,Ts.cart),auth:new Zt(js.auth,Ts.auth),gift:new Zt(js.gift,Ts.gift),order:new Zt(js.order,Ts.order),scope:new Zt(js.scope,Ts.scope),rating:new Zt(js.rating,Ts.rating),comment:new Zt(js.comment,Ts.comment),loyalty:new Zt(js.loyalty,Ts.loyalty),product:new Zt(js.product,Ts.product),profile:new Zt(js.profile,Ts.profile),currency:new Zt(js.currency,Ts.currency),document:new Zt(js.document,Ts.document),twilight:new Zt(js.twilight,Ts.twilight),wishlist:new Zt(js.wishlist,Ts.wishlist),logger:s,log:s.log,success:i.success,error:i.error,onReady:e=>salla.isInitiated?e():salla.event.once("twilight::initiated",e),isInitiated:!1,AppHelpers:class{toggleClassIf(e,t,r,n){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,r,n))),this}toggleElementClassIf(e,t,r,n){t=Array.isArray(t)?t:t.split(" "),r=Array.isArray(r)?r:r.split(" ");let i=n(e);return e?.classList.remove(...i?r:t),e?.classList.add(...i?t:r),this}isValidEmail(e){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return"object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach((e=>this.watchElement(e[0],e[1]))),this}on(e,t,r,n={}){return"object"==typeof t?(this.element(t).addEventListener(e,r,n),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,r,n))),this)}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,(e=>13===e.keyCode&&t(e))),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e,...t){return this.debounce_||(this.debounce_=salla.helpers.debounce(((e,...t)=>e(...t)),500)),this.debounce_(e,...t)}},infiniteScroll:new class extends Zt{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}},this.instances=[]}initiate(e,t,r){r=this.getCustomOptions(t,r);let n="string"!=typeof e?e:document.querySelector(e),i=r.path;if(!n||!i||"string"==typeof i&&!document.querySelector(i))return void salla.logger.warn(n?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let s=new Sr(n,r);return s.on("scrollThreshold",salla.infiniteScroll.event.scrollThreshold),s.on("request",salla.infiniteScroll.event.request),s.on("load",salla.infiniteScroll.event.load),s.on("append",salla.infiniteScroll.event.append),s.on("error",salla.infiniteScroll.event.error),s.on("last",salla.infiniteScroll.event.last),s.on("history",salla.infiniteScroll.event.history),this.instances.push(s),s}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}}(void 0,Ts.infiniteScroll),money:Gi.money,url:Gi.url,init:e=>js.twilight.init(e),call:e=>{let t=salla,r=e.split(".");for(;r.length&&(t=t[r.shift()]););return t}};var Cs=salla;e.default=Cs,Object.defineProperty(e,"__esModule",{value:!0})}));
26
+ */!function(e,t){e.exports=function(){function e(){if("undefined"!=typeof document&&document.documentElement)return document.documentElement.lang}function t(e){return"-Inf"===e?-1/0:"+Inf"===e||"Inf"===e||"*"===e?1/0:parseInt(e,10)}var r=/^({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])$/,n=/({\s*(\-?\d+(\.\d+)?[\s*,\s*\-?\d+(\.\d+)?]*)\s*})|([\[\]])\s*(-Inf|\*|\-?\d+(\.\d+)?)\s*,\s*(\+?Inf|\*|\-?\d+(\.\d+)?)\s*([\[\]])/,i={locale:"en"},s=function(t){t=t||{},this.locale=t.locale||e()||i.locale,this.fallback=t.fallback,this.messages=t.messages};return s.prototype.setMessages=function(e){this.messages=e},s.prototype.getLocale=function(){return this.locale||this.fallback},s.prototype.setLocale=function(e){this.locale=e},s.prototype.getFallback=function(){return this.fallback},s.prototype.setFallback=function(e){this.fallback=e},s.prototype.has=function(e,t){return!("string"!=typeof e||!this.messages)&&null!==this._getMessage(e,t)},s.prototype.get=function(e,t,r){if(!this.has(e,r))return e;var n=this._getMessage(e,r);return null===n?e:(t&&(n=this._applyReplacements(n,t)),n)},s.prototype.trans=function(e,t){return this.get(e,t)},s.prototype.choice=function(e,t,r,i){(r=void 0!==r?r:{}).count=t;var s=this.get(e,r,i);if(null==s)return s;for(var a=s.split("|"),o=[],l=0;l<a.length;l++)if(a[l]=a[l].trim(),n.test(a[l])){var c=a[l].split(/\s/);o.push(c.shift()),a[l]=c.join(" ")}if(1===a.length)return s;for(var u=0;u<o.length;u++)if(this._testInterval(t,o[u]))return a[u];return i=i||this._getLocale(e),a[this._getPluralForm(t,i)]},s.prototype.transChoice=function(e,t,r){return this.choice(e,t,r)},s.prototype._parseKey=function(e,t){if("string"!=typeof e||"string"!=typeof t)return null;var r=e.split("."),n=r[0].replace(/\//g,".");return{source:t+"."+n,sourceFallback:this.getFallback()+"."+n,entries:r.slice(1)}},s.prototype._getMessage=function(e,t){if(t=t||this.getLocale(),e=this._parseKey(e,t),void 0===this.messages[e.source]&&void 0===this.messages[e.sourceFallback])return null;var r=this.messages[e.source],n=e.entries.slice(),i=n.join(".");if("string"!=typeof(r=void 0!==r?this._getValueInKey(r,i):void 0)&&this.messages[e.sourceFallback])for(r=this.messages[e.sourceFallback],n=e.entries.slice(),i="";n.length&&void 0!==r;)r[i=i?i.concat(".",n.shift()):n.shift()]&&(r=r[i],i="");return"string"!=typeof r?null:r},s.prototype._getValueInKey=function(e,t){if("string"==typeof e[t])return e[t];for(var r=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split("."),n=0,i=r.length;n<i;++n){var s=r.slice(0,n+1).join("."),a=r.slice(n+1,r.length).join(".");if(e[s])return this._getValueInKey(e[s],a)}return e},s.prototype._getLocale=function(e){return e=this._parseKey(e,this.locale),this.messages[e.source]?this.locale:this.messages[e.sourceFallback]?this.fallback:null},s.prototype._findMessageInTree=function(e,t){for(;e.length&&void 0!==t;){var r=e.join(".");if(t[r]){t=t[r];break}t=t[e.shift()]}return t},s.prototype._sortReplacementKeys=function(e,t){return t.length-e.length},s.prototype._applyReplacements=function(e,t){return Object.keys(t).sort(this._sortReplacementKeys).forEach((function(r){e=e.replace(new RegExp(":"+r,"gi"),(function(e){var n=t[r];return e===e.toUpperCase()?n.toUpperCase():e===e.replace(/\w/i,(function(e){return e.toUpperCase()}))?n.charAt(0).toUpperCase()+n.slice(1):n}))})),e},s.prototype._testInterval=function(e,n){if("string"!=typeof n)throw"Invalid interval: should be a string.";var i=(n=n.trim()).match(r);if(!i)throw"Invalid interval: "+n;if(!i[2]){var s=(i=i.filter((function(e){return!!e})))[1],a=t(i[2]);a===1/0&&(a=-1/0);var o=t(i[3]),l=i[4];return("["===s?e>=a:e>a)&&("]"===l?e<=o:e<o)}for(var c=i[2].split(","),u=0;u<c.length;u++)if(parseInt(c[u],10)===e)return!0;return!1},s.prototype._getPluralForm=function(e,t){switch(t){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":default:return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return 1==e?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return 0===e||1===e?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2;case"cs":case"sk":return 1==e?0:e>=2&&e<=4?1:2;case"ga":return 1==e?0:2==e?1:2;case"lt":return e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2;case"sl":return e%100==1?0:e%100==2?1:e%100==3||e%100==4?2:3;case"mk":return e%10==1?0:1;case"mt":return 1==e?0:0===e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3;case"lv":return 0===e?0:e%10==1&&e%100!=11?1:2;case"pl":return 1==e?0:e%10>=2&&e%10<=4&&(e%100<12||e%100>14)?1:2;case"cy":return 1==e?0:2==e?1:8==e||11==e?2:3;case"ro":return 1==e?0:0===e||e%100>0&&e%100<20?1:2;case"ar":return 0===e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11&&e%100<=99?4:5}},s}()}(Vi);var Wi=Vi.exports;var Ji=Object.assign?Object.assign:function(e,t,r,n){for(var i=1;i<arguments.length;i++)es(Object(arguments[i]),(function(t,r){e[r]=t}));return e},Qi=function(){if(Object.create)return function(e,t,r,n){var i=Yi(arguments,1);return Ji.apply(this,[Object.create(e)].concat(i))};{function e(){}return function(t,r,n,i){var s=Yi(arguments,1);return e.prototype=t,Ji.apply(this,[new e].concat(s))}}}(),Ki=String.prototype.trim?function(e){return String.prototype.trim.call(e)}:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},Zi="undefined"!=typeof window?window:w,Xi={assign:Ji,create:Qi,trim:Ki,bind:function(e,t){return function(){return t.apply(e,Array.prototype.slice.call(arguments,0))}},slice:Yi,each:es,map:function(e,t){var r=rs(e)?[]:{};return ts(e,(function(e,n){return r[n]=t(e,n),!1})),r},pluck:ts,isList:rs,isFunction:function(e){return e&&"[object Function]"==={}.toString.call(e)},isObject:function(e){return e&&"[object Object]"==={}.toString.call(e)},Global:Zi};function Yi(e,t){return Array.prototype.slice.call(e,t||0)}function es(e,t){ts(e,(function(e,r){return t(e,r),!1}))}function ts(e,t){if(rs(e)){for(var r=0;r<e.length;r++)if(t(e[r],r))return e[r]}else for(var n in e)if(e.hasOwnProperty(n)&&t(e[n],n))return e[n]}function rs(e){return null!=e&&"function"!=typeof e&&"number"==typeof e.length}var ns=Xi.slice,is=Xi.pluck,ss=Xi.each,as=Xi.bind,os=Xi.create,ls=Xi.isList,cs=Xi.isFunction,us=Xi.isObject,hs={createStore:fs},ds={version:"2.0.12",enabled:!1,get:function(e,t){var r=this.storage.read(this._namespacePrefix+e);return this._deserialize(r,t)},set:function(e,t){return void 0===t?this.remove(e):(this.storage.write(this._namespacePrefix+e,this._serialize(t)),t)},remove:function(e){this.storage.remove(this._namespacePrefix+e)},each:function(e){var t=this;this.storage.each((function(r,n){e.call(t,t._deserialize(r),(n||"").replace(t._namespaceRegexp,""))}))},clearAll:function(){this.storage.clearAll()},hasNamespace:function(e){return this._namespacePrefix=="__storejs_"+e+"_"},createStore:function(){return fs.apply(this,arguments)},addPlugin:function(e){this._addPlugin(e)},namespace:function(e){return fs(this.storage,this.plugins,e)}};function fs(e,t,r){r||(r=""),e&&!ls(e)&&(e=[e]),t&&!ls(t)&&(t=[t]);var n=r?"__storejs_"+r+"_":"",i=r?new RegExp("^"+n):null;if(!/^[a-zA-Z0-9_\-]*$/.test(r))throw new Error("store.js namespaces can only have alphanumerics + underscores and dashes");var s={_namespacePrefix:n,_namespaceRegexp:i,_testStorage:function(e){try{var t="__storejs__test__";e.write(t,t);var r=e.read(t)===t;return e.remove(t),r}catch(e){return!1}},_assignPluginFnProp:function(e,t){var r=this[t];this[t]=function(){var t=ns(arguments,0),n=this;function i(){if(r)return ss(arguments,(function(e,r){t[r]=e})),r.apply(n,t)}var s=[i].concat(t);return e.apply(n,s)}},_serialize:function(e){return JSON.stringify(e)},_deserialize:function(e,t){if(!e)return t;var r="";try{r=JSON.parse(e)}catch(t){r=e}return void 0!==r?r:t},_addStorage:function(e){this.enabled||this._testStorage(e)&&(this.storage=e,this.enabled=!0)},_addPlugin:function(e){var t=this;if(ls(e))ss(e,(function(e){t._addPlugin(e)}));else if(!is(this.plugins,(function(t){return e===t}))){if(this.plugins.push(e),!cs(e))throw new Error("Plugins must be function values that return objects");var r=e.call(this);if(!us(r))throw new Error("Plugins must return an object of function properties");ss(r,(function(r,n){if(!cs(r))throw new Error("Bad plugin property: "+n+" from plugin "+e.name+". Plugins should only return functions.");t._assignPluginFnProp(r,n)}))}},addStorage:function(e){!function(){var e="undefined"==typeof console?null:console;if(e){(e.warn?e.warn:e.log).apply(e,arguments)}}("store.addStorage(storage) is deprecated. Use createStore([storages])"),this._addStorage(e)}},a=os(s,ds,{plugins:[]});return a.raw={},ss(a,(function(e,t){cs(e)&&(a.raw[t]=as(a,e))})),ss(e,(function(e){a._addStorage(e)})),ss(t,(function(e){a._addPlugin(e)})),a}var ps=Xi.Global,gs={name:"localStorage",read:vs,write:function(e,t){return ms().setItem(e,t)},each:function(e){for(var t=ms().length-1;t>=0;t--){var r=ms().key(t);e(vs(r),r)}},remove:function(e){return ms().removeItem(e)},clearAll:function(){return ms().clear()}};function ms(){return ps.localStorage}function vs(e){return ms().getItem(e)}var ys=Xi.Global,bs={name:"sessionStorage",read:_s,write:function(e,t){return ws().setItem(e,t)},each:function(e){for(var t=ws().length-1;t>=0;t--){var r=ws().key(t);e(_s(r),r)}},remove:function(e){return ws().removeItem(e)},clearAll:function(){return ws().clear()}};function ws(){return ys.sessionStorage}function _s(e){return ws().getItem(e)}var Es=Xi.trim,Ss={name:"cookieStorage",read:function(e){if(!e||!Fs(e))return null;var t="(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";return unescape(xs.cookie.replace(new RegExp(t),"$1"))},write:function(e,t){if(!e)return;xs.cookie=escape(e)+"="+escape(t)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},each:As,remove:Ps,clearAll:function(){As((function(e,t){Ps(t)}))}},xs=Xi.Global.document;function As(e){for(var t=xs.cookie.split(/; ?/g),r=t.length-1;r>=0;r--)if(Es(t[r])){var n=t[r].split("="),i=unescape(n[0]);e(unescape(n[1]),i)}}function Ps(e){e&&Fs(e)&&(xs.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")}function Fs(e){return new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(xs.cookie)}var Ls={name:"memoryStorage",read:function(e){return Os[e]},write:function(e,t){Os[e]=t},each:function(e){for(var t in Os)Os.hasOwnProperty(t)&&e(Os[t],t)},remove:function(e){delete Os[e]},clearAll:function(e){Os={}}},Os={};const ks=hs.createStore([gs,bs,Ss,Ls],[]);let Ts=new class extends S{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.globalListners={},this.delimiter="::",this.auth=new o(this),this.cart=new l(this),this.order=new c(this),this.scope=new u(this),this.rating=new h(this),this.comment=new d(this),this.loyalty=new f(this),this.product=new g(this),this.profile=new p(this),this.currency=new y(this),this.document=new m(this),this.twilight=new b(this),this.wishlist=new v(this),this.infiniteScroll=new x(this),this.body=document.querySelector("body"),this.logableEvents=["cart::item.added.failed","cart::item.deleted.failed"],this.ingoreLogEvents=["document::click","document::keyup","document::change"],this.noneFireableActions=["document.request"],this.on("twilight::initiated",this.initiateSallaInAllClasses)}initiateSallaInAllClasses(){let e=this;Object.keys(salla).forEach((t=>{"object"==typeof(t=salla[t])&&(e.callSallaInitiate(t),Object.keys(t).forEach((r=>{e.callSallaInitiate(t[r])})))}))}callSallaInitiate(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0)}createAndDispatch(e,...t){this.dispatch(e,...t)}dispatch(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&"function"==typeof salla.call(r))return salla.log(`'salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);this.emit(e,...t),window.dataLayer=window.dataLayer||[],window.dataLayer.push(Object.assign({event:e},...t.values())),this.ingoreLogEvents.includes(e)||!salla.config.get("debug")&&!this.logableEvents.includes(e)||salla.logger.event(e,...t);let n=this;Object.keys(this.globalListners).forEach((function(r){n.globalListners[r](e,...t)})),this.dispatchMobileEvent(e,{...t.values()})}dispatchEvents(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))this.dispatch(t,r);else salla.log("No Events To Dispatch!",e)}addListener(e,t){this.on(e,t)}addEventListener(e,t){this.addListener(e,t)}listen(e,t){this.addListener(e,t)}registerGlobalListener(e,t){this.globalListners[e]=t}dispatchMobileEvent(e,t={}){if(!(window.dataLayer&&dataLayer[0]&&dataLayer[0].page&&dataLayer[0].page.mobileApp))return"";if(window.webkit)try{window.webkit.messageHandlers.callbackHandler.postMessage(JSON.stringify({event:e,details:t}))}catch(e){salla.logger.warn(e,"The native context does not exist yet")}else if(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}))}catch(e){salla.logger.warn(e,"The native context does not exist yet")}}},js=new class extends class{constructor(e){return e.on("twilight::initiated",(()=>this.initiateRequest())),e.on("profile::info.fetched",this.setCurrencyAndLanguage),e.on("auth::token.fetched",(e=>this.handleToken(e))),e.on("document::request.failed",((e,t)=>{salla.logger.warn(t,e)})),Vt.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}})}initiateRequest(){salla.api.defaults.baseURL=salla.config.get("store.api",salla.config.get("store.url")),salla.api.defaults.headers.common["Store-Identifier"]=salla.config.get("store.id"),salla.api.defaults.headers.common.currency=salla.config.get("user.currency_code","SAR"),salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=salla.api.defaults.headers.common["accept-language"]=salla.lang.getLocale(),salla.api.defaults.headers.common["s-user-id"]=salla.config.get("user.id");let e=salla.storage.get("scope");e&&(salla.api.defaults.headers.common["s-scope-type"]=e.type,salla.api.defaults.headers.common["s-scope-id"]=e.id),this.injectTokenToTheRequests()}injectTokenToTheRequests(){let e=salla.storage.get("token"),t=salla.config.isGuest(),r=salla.storage.get("cart");if(r&&(r.user_id!==salla.config.get("user.id")||r.store_id!==salla.config.get("store.id")))return salla.log("Auth:: The cart is not belong to current "+(r.user_id!==salla.config.get("user.id")?"user":"store")+"!"),void salla.cart.api.reset();if(t&&!e)return;if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();let n=function(e,t){if("string"!=typeof e)throw new Kt("Invalid token specified");var r=!0===(t=t||{}).header?0:1;try{return JSON.parse(Qt(e.split(".")[r]))}catch(e){throw new Kt("Invalid token specified: "+e.message)}}(e);return Date.now()/1e3>n.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):n.sub!==salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}handleToken(e){salla.storage.set("token",e),this.setToken(e),salla.cart.api.reset()}setToken(e){salla.api.defaults.headers.common.Authorization="Bearer "+e}setCurrencyAndLanguage(e){salla.api.defaults.headers.common.currency=e.data.currency,salla.api.defaults.headers.common["accept-language"]=e.data.language,salla.infiniteScroll.fetchOptions.headers["Accept-Language"]=e.data.language}}{constructor(e){super(e),this.apis={auth:new L(this),cart:new P(this),loyalty:new F(this),order:new O(this),rating:new I(this),product:new k(this),profile:new T(this),comment:new j(this),currency:new C(this),document:new R(this),twilight:new N(this),wishlist:new D(this),scope:new U(this),withoutNotifier:async e=>(salla.config.set("sdk.notifier_handler_disabled",!0),await e().finally((()=>{salla.config.set("sdk.notifier_handler_disabled",!1)})))},Object.assign(this,this.apis),this.getHeaders=()=>this.defaults.headers.common}}(Ts);window.Salla=window.salla={notify:i,api:js,event:Ts,helpers:Gi,config:new class{constructor(e={}){this.triedToGetCurrencies_=!1,this.languages_=[],this.triedToGetLanguages_=!1,this.currencies_={},this.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"}}},this.properties_={...this.default_properties,...e}}merge(e){return Object.assign(this.properties_,e),this.properties_.store={...this.default_properties.store,...this.properties_.store},this}set(e,t){return e.includes(".")?(salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)}get(e,t=null){return e.includes(".")?salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0}isUser(){return"user"===this.get("user.type")}isGuest(){return!this.isUser()}async languages(){if(this.triedToGetLanguages_)return this.languages_;this.triedToGetLanguages_=!0;let e=!0;return(await salla.document.api.request("languages",null,"get"))?.data?.map((t=>{e&&(this.languages_=[],e=!1),t.code=t.code||t.iso_code,t.url=salla.url.get(t.code),t.is_rtl=t.is_rtl||t.rtl,this.languages_.push(t)})),this.set("languages",this.languages_),this.languages_}async currencies(){if(this.triedToGetCurrencies_)return this.currencies_;this.triedToGetCurrencies_=!0;let e=!0;return(await salla.currency.api.list())?.data?.map((t=>{e&&(this.currencies_={},e=!1),t.country_code=t.code.substr(0,2).toLowerCase(),this.currencies_[t.code]=t})),this.set("currencies",this.currencies_),this.currencies_}currency(e){return e=e||this.get("user.currency_code"),this.get("currencies."+e)||Object.values(this.get("currencies"))[0]}},storage:new class{constructor(e){e.on("storage::item.remove",(e=>this.remove(e))),e.on("storage::item.set",((e,t)=>this.set(e,t))),this.store=ks}set(e,t){if(e.includes(".")){let r=e.split(".")[0],n={[r]:ks.get(r)};return n=salla.helpers.setNested(n,e,t),ks.set(r,n[r])}return ks.set(e,t)}remove(e){return ks.remove(e)}get(e,t){if(e.includes(".")){let t=e.split(".")[0];return salla.helpers.getNested({[t]:ks.get(t)},e)}return ks.get(e,t)}}(Ts),cookie:new class{constructor(e){e.on("cookies::remove",(e=>this.remove(e))),e.on("cookies::add",((e,t)=>this.set(e,t)))}get(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]}set(e,t="",r=10){let n="";if(r){let e=new Date;e.setTime(e.getTime()+24*r*60*60*1e3),n="; expires="+e.toUTCString()}return document.cookie=`${e}=${t}${n}"; path=/; secure; SameSite=Lax"`,this}remove(e){return document.cookie=`${e}=; Max-Age=0; path=/;`,this}}(Ts),lang:new class extends Wi{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){if(this.translationsLoaded)return e();salla.event.once("languages::translations.loaded",e)}loadStoreTranslations(){if(this.messages)return void window.addEventListener("load",(e=>{salla.event.dispatch("languages::translations.loaded"),salla.logger.info("The messages of transactions is already loaded")}));if(!salla.url.get(""))return void this.loadScript("https://cdn.salla.network/js/translations.js",!1);let e=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight"));this.loadScript(salla.url.get(`languages/assets/${e}.js`))}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0}loadScript(e,t=!0){let r=document.createElement("script");r.src=e,r.onload=()=>window.translations?this.setMessages(window.translations):t?(salla.logger.info("Failed to load Translations for store, lets try load it from cdn"),this.loadScript("https://cdn.salla.network/js/translations.js",!1)):void salla.logger.warn("Failed to load Translations from the cdn\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's."),document.head.appendChild(r)}get(e,t,r){return window.translations&&(e="trans."+e),super.get(e,t,r)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},form:new class{async submit(e,t=null){let r=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(),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.twilight.request(e,r,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop()}));let n=e.split("."),i=n.splice(-1);return await salla.call(n.join("."))[i](r).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)}},cart:new Zt(js.cart,Ts.cart),auth:new Zt(js.auth,Ts.auth),gift:new Zt(js.gift,Ts.gift),order:new Zt(js.order,Ts.order),scope:new Zt(js.scope,Ts.scope),rating:new Zt(js.rating,Ts.rating),comment:new Zt(js.comment,Ts.comment),loyalty:new Zt(js.loyalty,Ts.loyalty),product:new Zt(js.product,Ts.product),profile:new Zt(js.profile,Ts.profile),currency:new Zt(js.currency,Ts.currency),document:new Zt(js.document,Ts.document),twilight:new Zt(js.twilight,Ts.twilight),wishlist:new Zt(js.wishlist,Ts.wishlist),logger:s,log:s.log,success:i.success,error:i.error,onReady:e=>salla.isInitiated?e():salla.event.once("twilight::initiated",e),isInitiated:!1,AppHelpers:class{toggleClassIf(e,t,r,n){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,r,n))),this}toggleElementClassIf(e,t,r,n){t=Array.isArray(t)?t:t.split(" "),r=Array.isArray(r)?r:r.split(" ");let i=n(e);return e?.classList.remove(...i?r:t),e?.classList.add(...i?t:r),this}isValidEmail(e){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return"object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach((e=>this.watchElement(e[0],e[1]))),this}on(e,t,r,n={}){return"object"==typeof t?(this.element(t).addEventListener(e,r,n),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,r,n))),this)}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,(e=>13===e.keyCode&&t(e))),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e,...t){return this.debounce_||(this.debounce_=salla.helpers.debounce(((e,...t)=>e(...t)),500)),this.debounce_(e,...t)}},infiniteScroll:new class extends Zt{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}},this.instances=[]}initiate(e,t,r){r=this.getCustomOptions(t,r);let n="string"!=typeof e?e:document.querySelector(e),i=r.path;if(!n||!i||"string"==typeof i&&!document.querySelector(i))return void salla.logger.warn(n?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let s=new Sr(n,r);return s.on("scrollThreshold",salla.infiniteScroll.event.scrollThreshold),s.on("request",salla.infiniteScroll.event.request),s.on("load",salla.infiniteScroll.event.load),s.on("append",salla.infiniteScroll.event.append),s.on("error",salla.infiniteScroll.event.error),s.on("last",salla.infiniteScroll.event.last),s.on("history",salla.infiniteScroll.event.history),this.instances.push(s),s}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}}(void 0,Ts.infiniteScroll),money:Gi.money,url:Gi.url,init:e=>js.twilight.init(e),call:e=>{let t=salla,r=e.split(".");for(;r.length&&(t=t[r.shift()]););return t}};var Cs=salla;e.default=Cs,Object.defineProperty(e,"__esModule",{value:!0})}));
27
27
  //# sourceMappingURL=twilight.min.js.map