@salla.sa/twilight-components 2.11.85 → 2.11.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/_commonjsHelpers-f57e29ee.js +256 -0
- package/dist/cjs/{app-globals-08c1c2af.js → app-globals-bf20263f.js} +2007 -40
- package/dist/cjs/loader.cjs.js +2 -2
- package/dist/cjs/salla-button_37.cjs.entry.js +7 -3
- package/dist/cjs/twilight.cjs.js +2 -2
- package/dist/collection/components/salla-localization-modal/salla-localization-modal.js +5 -1
- package/dist/components/index.js +2006 -38
- package/dist/components/salla-localization-modal.js +5 -1
- package/dist/components/salla-quick-buy2.js +228 -2
- package/dist/esm/_commonjsHelpers-a7c4abac.js +250 -0
- package/dist/esm/{app-globals-3e9f7127.js → app-globals-30874674.js} +2006 -39
- package/dist/esm/loader.js +2 -2
- package/dist/esm/salla-button_37.entry.js +7 -3
- package/dist/esm/twilight.js +2 -2
- package/dist/esm-es5/_commonjsHelpers-a7c4abac.js +4 -0
- package/dist/esm-es5/app-globals-30874674.js +30 -0
- package/dist/esm-es5/loader.js +1 -1
- package/dist/esm-es5/salla-button_37.entry.js +2 -2
- package/dist/esm-es5/twilight.js +1 -1
- package/dist/twilight/{p-20bef15d.system.entry.js → p-0d221d45.system.entry.js} +9 -9
- package/dist/twilight/p-71b1ddca.js +24 -0
- package/dist/twilight/{p-7ea02f41.system.js → p-7f520307.system.js} +1 -1
- package/dist/twilight/p-854e2c89.system.js +30 -0
- package/dist/twilight/p-99ed8fff.system.js +4 -0
- package/dist/twilight/p-ce54db8d.js +4 -0
- package/dist/twilight/p-df0e0ea8.entry.js +36 -0
- package/dist/twilight/twilight.esm.js +1 -1
- package/dist/twilight/twilight.js +1 -1
- package/package.json +5 -5
- package/dist/cjs/_commonjsHelpers-691dd63b.js +0 -28
- package/dist/esm/_commonjsHelpers-1415ffd3.js +0 -24
- package/dist/esm-es5/_commonjsHelpers-1415ffd3.js +0 -4
- package/dist/esm-es5/app-globals-3e9f7127.js +0 -24
- package/dist/twilight/p-45b4a309.entry.js +0 -36
- package/dist/twilight/p-63b59f65.js +0 -24
- package/dist/twilight/p-9beb6b7b.system.js +0 -4
- package/dist/twilight/p-b87e4299.system.js +0 -24
- package/dist/twilight/p-f84bae34.js +0 -4
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
'use strict';
|
|
5
5
|
|
|
6
|
-
const _commonjsHelpers = require('./_commonjsHelpers-
|
|
6
|
+
const _commonjsHelpers = require('./_commonjsHelpers-f57e29ee.js');
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Checks if `value` is classified as an `Array` object.
|
|
@@ -28,9 +28,9 @@ const _commonjsHelpers = require('./_commonjsHelpers-691dd63b.js');
|
|
|
28
28
|
* _.isArray(_.noop);
|
|
29
29
|
* // => false
|
|
30
30
|
*/
|
|
31
|
-
var isArray$
|
|
31
|
+
var isArray$2 = Array.isArray;
|
|
32
32
|
|
|
33
|
-
var isArray_1 = isArray$
|
|
33
|
+
var isArray_1 = isArray$2;
|
|
34
34
|
|
|
35
35
|
/** Detect free variable `global` from Node.js. */
|
|
36
36
|
var freeGlobal = typeof _commonjsHelpers.commonjsGlobal == 'object' && _commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.Object === Object && _commonjsHelpers.commonjsGlobal;
|
|
@@ -1095,11 +1095,11 @@ var _baseToString = baseToString;
|
|
|
1095
1095
|
* _.toString([1, 2, 3]);
|
|
1096
1096
|
* // => '1,2,3'
|
|
1097
1097
|
*/
|
|
1098
|
-
function toString$
|
|
1098
|
+
function toString$2(value) {
|
|
1099
1099
|
return value == null ? '' : _baseToString(value);
|
|
1100
1100
|
}
|
|
1101
1101
|
|
|
1102
|
-
var toString_1 = toString$
|
|
1102
|
+
var toString_1 = toString$2;
|
|
1103
1103
|
|
|
1104
1104
|
/**
|
|
1105
1105
|
* Casts `value` to a path array if it's not one.
|
|
@@ -1199,7 +1199,7 @@ var eventemitter2 = _commonjsHelpers.createCommonjsModule(function (module, expo
|
|
|
1199
1199
|
return Object.prototype.toString.call(obj) === "[object Array]";
|
|
1200
1200
|
};
|
|
1201
1201
|
var defaultMaxListeners = 10;
|
|
1202
|
-
var nextTickSupported= typeof
|
|
1202
|
+
var nextTickSupported= typeof _commonjsHelpers.browser$1=='object' && typeof _commonjsHelpers.browser$1.nextTick=='function';
|
|
1203
1203
|
var symbolsSupported= typeof Symbol==='function';
|
|
1204
1204
|
var reflectSupported= typeof Reflect === 'object';
|
|
1205
1205
|
var setImmediateSupported= typeof setImmediate === 'function';
|
|
@@ -1248,12 +1248,12 @@ var eventemitter2 = _commonjsHelpers.createCommonjsModule(function (module, expo
|
|
|
1248
1248
|
errorMsg += ' Event name: ' + eventName + '.';
|
|
1249
1249
|
}
|
|
1250
1250
|
|
|
1251
|
-
if(typeof
|
|
1251
|
+
if(typeof _commonjsHelpers.browser$1 !== 'undefined' && _commonjsHelpers.browser$1.emitWarning){
|
|
1252
1252
|
var e = new Error(errorMsg);
|
|
1253
1253
|
e.name = 'MaxListenersExceededWarning';
|
|
1254
1254
|
e.emitter = this;
|
|
1255
1255
|
e.count = count;
|
|
1256
|
-
|
|
1256
|
+
_commonjsHelpers.browser$1.emitWarning(e);
|
|
1257
1257
|
} else {
|
|
1258
1258
|
console.error(errorMsg);
|
|
1259
1259
|
|
|
@@ -1959,7 +1959,7 @@ var eventemitter2 = _commonjsHelpers.createCommonjsModule(function (module, expo
|
|
|
1959
1959
|
}).then(function () {
|
|
1960
1960
|
context.event = event;
|
|
1961
1961
|
return _listener.apply(context, args)
|
|
1962
|
-
})) : (nextTick ?
|
|
1962
|
+
})) : (nextTick ? _commonjsHelpers.browser$1.nextTick : _setImmediate)(function () {
|
|
1963
1963
|
context.event = event;
|
|
1964
1964
|
_listener.apply(context, args);
|
|
1965
1965
|
});
|
|
@@ -3172,8 +3172,8 @@ var Global$2 = util.Global;
|
|
|
3172
3172
|
|
|
3173
3173
|
var localStorage_1 = {
|
|
3174
3174
|
name: 'localStorage',
|
|
3175
|
-
read: read$
|
|
3176
|
-
write: write$
|
|
3175
|
+
read: read$4,
|
|
3176
|
+
write: write$4,
|
|
3177
3177
|
each: each$3,
|
|
3178
3178
|
remove: remove$3,
|
|
3179
3179
|
clearAll: clearAll$3,
|
|
@@ -3183,18 +3183,18 @@ function localStorage() {
|
|
|
3183
3183
|
return Global$2.localStorage
|
|
3184
3184
|
}
|
|
3185
3185
|
|
|
3186
|
-
function read$
|
|
3186
|
+
function read$4(key) {
|
|
3187
3187
|
return localStorage().getItem(key)
|
|
3188
3188
|
}
|
|
3189
3189
|
|
|
3190
|
-
function write$
|
|
3190
|
+
function write$4(key, data) {
|
|
3191
3191
|
return localStorage().setItem(key, data)
|
|
3192
3192
|
}
|
|
3193
3193
|
|
|
3194
3194
|
function each$3(fn) {
|
|
3195
3195
|
for (var i = localStorage().length - 1; i >= 0; i--) {
|
|
3196
3196
|
var key = localStorage().key(i);
|
|
3197
|
-
fn(read$
|
|
3197
|
+
fn(read$4(key), key);
|
|
3198
3198
|
}
|
|
3199
3199
|
}
|
|
3200
3200
|
|
|
@@ -3210,8 +3210,8 @@ var Global$1 = util.Global;
|
|
|
3210
3210
|
|
|
3211
3211
|
var sessionStorage_1 = {
|
|
3212
3212
|
name: 'sessionStorage',
|
|
3213
|
-
read: read$
|
|
3214
|
-
write: write$
|
|
3213
|
+
read: read$3,
|
|
3214
|
+
write: write$3,
|
|
3215
3215
|
each: each$2,
|
|
3216
3216
|
remove: remove$2,
|
|
3217
3217
|
clearAll: clearAll$2
|
|
@@ -3221,18 +3221,18 @@ function sessionStorage() {
|
|
|
3221
3221
|
return Global$1.sessionStorage
|
|
3222
3222
|
}
|
|
3223
3223
|
|
|
3224
|
-
function read$
|
|
3224
|
+
function read$3(key) {
|
|
3225
3225
|
return sessionStorage().getItem(key)
|
|
3226
3226
|
}
|
|
3227
3227
|
|
|
3228
|
-
function write$
|
|
3228
|
+
function write$3(key, data) {
|
|
3229
3229
|
return sessionStorage().setItem(key, data)
|
|
3230
3230
|
}
|
|
3231
3231
|
|
|
3232
3232
|
function each$2(fn) {
|
|
3233
3233
|
for (var i = sessionStorage().length - 1; i >= 0; i--) {
|
|
3234
3234
|
var key = sessionStorage().key(i);
|
|
3235
|
-
fn(read$
|
|
3235
|
+
fn(read$3(key), key);
|
|
3236
3236
|
}
|
|
3237
3237
|
}
|
|
3238
3238
|
|
|
@@ -3254,8 +3254,8 @@ var trim$1 = util.trim;
|
|
|
3254
3254
|
|
|
3255
3255
|
var cookieStorage = {
|
|
3256
3256
|
name: 'cookieStorage',
|
|
3257
|
-
read: read$
|
|
3258
|
-
write: write$
|
|
3257
|
+
read: read$2,
|
|
3258
|
+
write: write$2,
|
|
3259
3259
|
each: each$1,
|
|
3260
3260
|
remove: remove$1,
|
|
3261
3261
|
clearAll: clearAll$1,
|
|
@@ -3263,7 +3263,7 @@ var cookieStorage = {
|
|
|
3263
3263
|
|
|
3264
3264
|
var doc = Global.document;
|
|
3265
3265
|
|
|
3266
|
-
function read$
|
|
3266
|
+
function read$2(key) {
|
|
3267
3267
|
if (!key || !_has(key)) { return null }
|
|
3268
3268
|
var regexpStr = "(?:^|.*;\\s*)" +
|
|
3269
3269
|
escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
|
|
@@ -3284,7 +3284,7 @@ function each$1(callback) {
|
|
|
3284
3284
|
}
|
|
3285
3285
|
}
|
|
3286
3286
|
|
|
3287
|
-
function write$
|
|
3287
|
+
function write$2(key, data) {
|
|
3288
3288
|
if(!key) { return }
|
|
3289
3289
|
doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
|
|
3290
3290
|
}
|
|
@@ -3313,8 +3313,8 @@ function _has(key) {
|
|
|
3313
3313
|
|
|
3314
3314
|
var memoryStorage_1 = {
|
|
3315
3315
|
name: 'memoryStorage',
|
|
3316
|
-
read: read,
|
|
3317
|
-
write: write,
|
|
3316
|
+
read: read$1,
|
|
3317
|
+
write: write$1,
|
|
3318
3318
|
each: each,
|
|
3319
3319
|
remove: remove,
|
|
3320
3320
|
clearAll: clearAll,
|
|
@@ -3322,11 +3322,11 @@ var memoryStorage_1 = {
|
|
|
3322
3322
|
|
|
3323
3323
|
var memoryStorage = {};
|
|
3324
3324
|
|
|
3325
|
-
function read(key) {
|
|
3325
|
+
function read$1(key) {
|
|
3326
3326
|
return memoryStorage[key]
|
|
3327
3327
|
}
|
|
3328
3328
|
|
|
3329
|
-
function write(key, data) {
|
|
3329
|
+
function write$1(key, data) {
|
|
3330
3330
|
memoryStorage[key] = data;
|
|
3331
3331
|
}
|
|
3332
3332
|
|
|
@@ -3346,7 +3346,7 @@ function clearAll(key) {
|
|
|
3346
3346
|
memoryStorage = {};
|
|
3347
3347
|
}
|
|
3348
3348
|
|
|
3349
|
-
function a(e,t=!1){e+="";let r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],i=["0","1","2","3","4","5","6","7","8","9"],o=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:i,l=t?i:n;for(let t=0;t<o.length;t++)r=new RegExp(o[t],"g"),e=e.replace(r,l[t]);return e}function s(e){let t=(`${e}`.match(/\./g)||[]).length;return t&&1!==t?s(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e){return `${e}`.startsWith("https://")||`${e}`.startsWith("http://")}function u$1(e){if(c$1(e))return e;let t=Salla.config.get("store.url");return t||(t=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",t)),t.rtrim("/")+"/"+e?.ltrim("/")}function d$1(e,t){if(!t||!e)return window.location.href;let r=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),n=window.location.href.replace(r,"$1").split("#")[0].replace(/&$|\?$/,"");return n.includes("?")?n+="&":n+=(n.endsWith("/")?"":"/")+"?",(n+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")}function g$1(e){return window.location.origin+"/"+e?.ltrim("/")}function p$1(e){return c$1(e)?e:g$1("themes/"+Salla.config.get("theme.name")+"/"+e?.ltrim("/"))}function h$1(e,t,r){let n=e[0];return r&&0==e.length?Array.isArray(r)?(r.push(t),r):[r,t]:Array.isArray(r)?(r.push(t),r):"string"==typeof r?[r,t]:r?(r[n]=h$1(e.slice(1),t,r[n]),r):n?{[n]:h$1(e.slice(1),t)}:""===n?[t]:t}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this:"#"+this},String.prototype.replaceArray=function(e,t){for(var r,n=this,i=0;i<e.length;i++)r=new RegExp(e[i],"g"),n=n.replace(r,t[i]);return n},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var f$1={digitsOnly:function(e){return a(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function e(t,r=!1){if("string"==typeof t)return document.querySelectorAll(t).forEach((t=>e(t,r)));if(!t)return void Salla.logger.warn("Can't find Object With Id: "+t);let n=Salla.helpers.digitsOnly(t.value);return t.min&&n<parseInt(t.min)?t.value=t.min:t.max&&n>parseInt(t.max)?t.value=t.max:t.maxLength>=1&&n.toString().length>t.maxLength?t.value=n.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?s(n):n.replace(/\D/g,"")},number:a,money:function(e){let t=Salla.config.currency(e?.currency).symbol;return a(e="object"==typeof e?e.amount:e)+" "+t},setNested:function(e,t,r){let n=e,i=t.split("."),o=i.length;for(let e=0;e<o-1;e++){let t=i[e];n[t]||(n[t]={}),n=n[t];}return n[i[o-1]]=r,e},getNested:function(t,r,n){let i=get_1(t,r);return void 0!==i?i:n},inputData:function(e,t,r={}){if(e.includes("[")){let n=e.split("]").join("").split("[");return {name:n[0],value:h$1(n.slice(1),t,r[n[0]])}}return {name:e,value:t}},url:Object.freeze({__proto__:null,is_full_url:c$1,base:function(e){if(c$1(e))return e;const{hostname:t}=new URL(u$1("/"));return "https://"+t+"/"+e?.ltrim("/")},get:u$1,domain:function(e){return c$1(e)?e:Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/")+"/"+e?.ltrim("/")},addParamToUrl:d$1,baseUrl:g$1,asset:p$1,cdn:function(e){return "https://cdn.salla.network/"+e?.ltrim("/")},api:function(e){return Salla.config.get("store.api",u$1(""))?.rtrim("/")+"/"+e?.ltrim("/")},is_page:function(e){return e&&Salla.config.get("page.slug")===e},is_placeholder:function(e){return p$1(salla.config.get("theme.settings.placeholder"))===p$1(e)}}),addParamToUrl:d$1,debounce:function(e,t){t=t||100;let r,n=[];return function(...i){return clearTimeout(r),r=setTimeout((()=>{let t=e(...i);n.forEach((e=>e(t))),n=[];}),t),new Promise((e=>n.push(e)))}}},m$1=function(e){let t={log:function(t,r){if(!e)return;if(!salla.config.isDebug())return;"trace"===salla.config.get("debug")&&(r="trace");let n=e.log,i=void 0===r?n:this.__dict__[r]||n,o=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(o[0]+="%c"+r[0].toUpperCase()+r.substring(1),o.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),i.call(e,...o.concat(...t));},__dict__:{trace:e.trace,debug:e.debug,info:e.info,warn:e.warn,error:e.error}};return {event:function(){t.log(arguments,"event");},trace:function(){t.log(arguments,"trace");},debug:function(){t.log(arguments,"debug");},info:function(){t.log(arguments,"info");},warn:function(){t.log(arguments,"warn");},error:function(){t.log(arguments,"error");},log:function(){t.log(arguments,void 0);},backend:function(){t.log(arguments,"backend");},logs:function(e){[e].flat().forEach((e=>e&&t.log([e].flat(),"backend")));}}}(console);const S$1=storeEngine.createStore([localStorage_1,sessionStorage_1,cookieStorage,memoryStorage_1],[]);"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),"undefined"!=typeof global&&(global.salla=global.salla||global.Salla||{},global.Salla=global.salla),Salla.status="base",Salla.config=new class{constructor(e={},t={}){this.default_properties=t,this.properties_={...this.default_properties,...e};}merge(e){return this.properties_={...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)}currency(e){return e=e||this.get("user.currency_code"),this.get("currencies."+e)||Object.values(this.get("currencies"))[0]}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}all(){return this.properties_}isDebug(){return this.get("debug")||Salla.storage.get("debug")}},Salla.logger=m$1,Salla.event=new class extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.delimiter="::","undefined"!=typeof document&&(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"];}createAndDispatch(e,...t){this.dispatch(e,...t);}emit(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&Salla.call&&"function"==typeof Salla.call(r))return Salla.log(`'Salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),Array.isArray(t[0])&&(t=t[0]),void salla[r[0]][r[1]](...t);super.emit(e,...t),this.trackEvents(e,...t);}emitAsync(e,...t){let r=super.emitAsync(e,...t);try{this.trackEvents(e,...t);}catch(r){Salla.logger.warn(`error on tracking event (${e})`,t,r);}return r}trackEvents(e,...t){if("undefined"!=typeof window){window.dataLayer=window.dataLayer||[];let r={event:e};t.map((e=>"object"==typeof e&&(r={...r,...e}))),window.dataLayer.push(r);}Salla.logger&&!this.ingoreLogEvents.includes(e)&&Salla.logger.event(e,...t),this.dispatchMobileEvent(e,...t);}dispatch(e,...t){return this.emit(e,...t)}dispatchEvents(e){if(e)if("object"!=typeof e||Array.isArray(e))Salla.log("Events object is wrong, it should be object of {event:payload}",e);else for(const[t,r]of Object.entries(e))this.dispatch(t,r);else Salla.log("No Events To Dispatch!",e);}addListener(e,t){return this.on(e,t)}addEventListener(e,t){return this.on(e,t)}listen(e,t){return this.on(e,t)}registerGlobalListener(e,t){return this.onAny(t)}dispatchMobileEvent(e,t={}){if(!("undefined"!=typeof window&&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.log(e,"The native context does not exist yet");}else if("undefined"!=typeof Android)try{Android.customEventWithData(e,JSON.stringify({details:t}));}catch(e){Salla.log(e,"The native context does not exist yet");}}},Salla.helpers=f$1,Salla.storage=new class{constructor(){Salla.event.on("storage::item.remove",(e=>this.remove(e))),Salla.event.on("storage::item.set",((e,t)=>this.set(e,t))),this.store=S$1;}set(e,t){if(e.includes(".")){let r=e.split(".")[0],n={[r]:this.store.get(r)};return n=Salla.helpers.setNested(n,e,t),this.store.set(r,n[r])}return this.store.set(e,t)}remove(e){return this.store.remove(e)}clearAll(){return this.store.clearAll()}get(e,t){if(e.includes(".")){let t=e.split(".")[0];return Salla.helpers.getNested({[t]:this.store.get(t)},e)}return this.store.get(e,t)}},Salla.cookie=new class{constructor(){Salla.event.on("cookies::remove",(e=>this.remove(e))),Salla.event.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}clearAll(){let e=document.cookie.split(";");for(let t=0;t<e.length;t++){let r=e[t],n=r.indexOf("="),i=n>-1?r.substr(0,n):r;this.remove(i);}}},Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"[VI]{version}[/VI]"};var y$1=Salla;
|
|
3349
|
+
function a(e,t=!1){e+="";let r,n=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],i=["0","1","2","3","4","5","6","7","8","9"],o=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?n:i,l=t?i:n;for(let t=0;t<o.length;t++)r=new RegExp(o[t],"g"),e=e.replace(r,l[t]);return e}function s(e){let t=(`${e}`.match(/\./g)||[]).length;return t&&1!==t?s(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e){return `${e}`.startsWith("https://")||`${e}`.startsWith("http://")}function u$1(e){if(c$1(e))return e;let t=Salla.config.get("store.url");return t||(t=window.location.href.split("/").slice(0,-1).join("/"),Salla.config.set("store.url",t)),t.rtrim("/")+"/"+e?.ltrim("/")}function d$1(e,t){if(!t||!e)return window.location.href;let r=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),n=window.location.href.replace(r,"$1").split("#")[0].replace(/&$|\?$/,"");return n.includes("?")?n+="&":n+=(n.endsWith("/")?"":"/")+"?",(n+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")}function g$1(e){return window.location.origin+"/"+e?.ltrim("/")}function p$1(e){return c$1(e)?e:g$1("themes/"+Salla.config.get("theme.name")+"/"+e?.ltrim("/"))}function h$1(e,t,r){let n=e[0];return r&&0==e.length?Array.isArray(r)?(r.push(t),r):[r,t]:Array.isArray(r)?(r.push(t),r):"string"==typeof r?[r,t]:r?(r[n]=h$1(e.slice(1),t,r[n]),r):n?{[n]:h$1(e.slice(1),t)}:""===n?[t]:t}String.prototype.toStudlyCase=function(){return this.trim().replace(/([^a-zA-Z\d].)/g,(function(e){return e.toUpperCase().replace(/[^a-zA-Z\d]/g,"")}))},String.prototype.toDatasetName=function(){return this.startsWith("data-")?this.substr(5).toStudlyCase():this.toStudlyCase()},String.prototype.toSelector=function(){return this.trim().startsWith(".")||this.trim().startsWith("#")?this:"#"+this},String.prototype.replaceArray=function(e,t){for(var r,n=this,i=0;i<e.length;i++)r=new RegExp(e[i],"g"),n=n.replace(r,t[i]);return n},String.prototype.rtrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("["+e+"]*$"),"")},String.prototype.ltrim=function(e){return void 0===e&&(e="\\s"),this.replace(new RegExp("^["+e+"]*"),"")},String.prototype.digitsOnly=function(){return Salla.helpers.digitsOnly(this)};var f$1={digitsOnly:function(e){return a(e,!0).replace(/[^0-9.]/g,"").replace("..",".").rtrim(".")},inputDigitsOnly:function e(t,r=!1){if("string"==typeof t)return document.querySelectorAll(t).forEach((t=>e(t,r)));if(!t)return void Salla.logger.warn("Can't find Object With Id: "+t);let n=Salla.helpers.digitsOnly(t.value);return t.min&&n<parseInt(t.min)?t.value=t.min:t.max&&n>parseInt(t.max)?t.value=t.max:t.maxLength>=1&&n.toString().length>t.maxLength?t.value=n.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?s(n):n.replace(/\D/g,"")},number:a,money:function(e){let t=Salla.config.currency(e?.currency).symbol;return a(e="object"==typeof e?e.amount:e)+" "+t},setNested:function(e,t,r){let n=e,i=t.split("."),o=i.length;for(let e=0;e<o-1;e++){let t=i[e];n[t]||(n[t]={}),n=n[t];}return n[i[o-1]]=r,e},getNested:function(t,r,n){let i=get_1(t,r);return void 0!==i?i:n},inputData:function(e,t,r={}){if(e.includes("[")){let n=e.split("]").join("").split("[");return {name:n[0],value:h$1(n.slice(1),t,r[n[0]])}}return {name:e,value:t}},url:Object.freeze({__proto__:null,is_full_url:c$1,base:function(e){if(c$1(e))return e;const{hostname:t}=new URL(u$1("/"));return "https://"+t+"/"+e?.ltrim("/")},get:u$1,domain:function(e){return c$1(e)?e:Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/")+"/"+e?.ltrim("/")},addParamToUrl:d$1,baseUrl:g$1,asset:p$1,cdn:function(e){return "https://cdn.salla.network/"+e?.ltrim("/")},api:function(e){return Salla.config.get("store.api",u$1(""))?.rtrim("/")+"/"+e?.ltrim("/")},is_page:function(e){return e&&Salla.config.get("page.slug")===e},is_placeholder:function(e){return p$1(salla.config.get("theme.settings.placeholder"))===p$1(e)}}),addParamToUrl:d$1,debounce:function(e,t){t=t||100;let r,n=[];return function(...i){return clearTimeout(r),r=setTimeout((()=>{let t=e(...i);n.forEach((e=>e(t))),n=[];}),t),new Promise((e=>n.push(e)))}}},m$1=function(e){let t={log:function(t,r){if(!e)return;if(!salla.config.isDebug())return;"trace"===salla.config.get("debug")&&(r="trace");let n=e.log,i=void 0===r?n:this.__dict__[r]||n,o=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(o[0]+="%c"+r[0].toUpperCase()+r.substring(1),o.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),i.call(e,...o.concat(...t));},__dict__:{trace:e.trace,debug:e.debug,info:e.info,warn:e.warn,error:e.error}};return {event:function(){t.log(arguments,"event");},trace:function(){t.log(arguments,"trace");},debug:function(){t.log(arguments,"debug");},info:function(){t.log(arguments,"info");},warn:function(){t.log(arguments,"warn");},error:function(){t.log(arguments,"error");},log:function(){t.log(arguments,void 0);},backend:function(){t.log(arguments,"backend");},logs:function(e){[e].flat().forEach((e=>e&&t.log([e].flat(),"backend")));}}}(console);const S$1=storeEngine.createStore([localStorage_1,sessionStorage_1,cookieStorage,memoryStorage_1],[]);"undefined"!=typeof window&&(window.salla=window.salla||window.Salla||{},window.Salla=window.salla),"undefined"!=typeof _commonjsHelpers.global&&(_commonjsHelpers.global.salla=_commonjsHelpers.global.salla||_commonjsHelpers.global.Salla||{},_commonjsHelpers.global.Salla=_commonjsHelpers.global.salla),Salla.status="base",Salla.config=new class{constructor(e={},t={}){this.default_properties=t,this.properties_={...this.default_properties,...e};}merge(e){return this.properties_={...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)}currency(e){return e=e||this.get("user.currency_code"),this.get("currencies."+e)||Object.values(this.get("currencies"))[0]}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}all(){return this.properties_}isDebug(){return this.get("debug")||Salla.storage.get("debug")}},Salla.logger=m$1,Salla.event=new class extends eventemitter2{constructor(){super({wildcard:!0,delimiter:"::",newListener:!1,removeListener:!1,maxListeners:10,verboseMemoryLeak:!1,ignoreErrors:!1}),this.delimiter="::","undefined"!=typeof document&&(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"];}createAndDispatch(e,...t){this.dispatch(e,...t);}emit(e,...t){let r=e.replace("::",".");if(!this.noneFireableActions.includes(r)&&Salla.call&&"function"==typeof Salla.call(r))return Salla.log(`'Salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),Array.isArray(t[0])&&(t=t[0]),void salla[r[0]][r[1]](...t);super.emit(e,...t),this.trackEvents(e,...t);}emitAsync(e,...t){let r=super.emitAsync(e,...t);try{this.trackEvents(e,...t);}catch(r){Salla.logger.warn(`error on tracking event (${e})`,t,r);}return r}trackEvents(e,...t){if("undefined"!=typeof window){window.dataLayer=window.dataLayer||[];let r={event:e};t.map((e=>"object"==typeof e&&(r={...r,...e}))),window.dataLayer.push(r);}Salla.logger&&!this.ingoreLogEvents.includes(e)&&Salla.logger.event(e,...t),this.dispatchMobileEvent(e,...t);}dispatch(e,...t){return this.emit(e,...t)}dispatchEvents(e){if(e)if("object"!=typeof e||Array.isArray(e))Salla.log("Events object is wrong, it should be object of {event:payload}",e);else for(const[t,r]of Object.entries(e))this.dispatch(t,r);else Salla.log("No Events To Dispatch!",e);}addListener(e,t){return this.on(e,t)}addEventListener(e,t){return this.on(e,t)}listen(e,t){return this.on(e,t)}registerGlobalListener(e,t){return this.onAny(t)}dispatchMobileEvent(e,t={}){if(!("undefined"!=typeof window&&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.log(e,"The native context does not exist yet");}else if("undefined"!=typeof Android)try{Android.customEventWithData(e,JSON.stringify({details:t}));}catch(e){Salla.log(e,"The native context does not exist yet");}}},Salla.helpers=f$1,Salla.storage=new class{constructor(){Salla.event.on("storage::item.remove",(e=>this.remove(e))),Salla.event.on("storage::item.set",((e,t)=>this.set(e,t))),this.store=S$1;}set(e,t){if(e.includes(".")){let r=e.split(".")[0],n={[r]:this.store.get(r)};return n=Salla.helpers.setNested(n,e,t),this.store.set(r,n[r])}return this.store.set(e,t)}remove(e){return this.store.remove(e)}clearAll(){return this.store.clearAll()}get(e,t){if(e.includes(".")){let t=e.split(".")[0];return Salla.helpers.getNested({[t]:this.store.get(t)},e)}return this.store.get(e,t)}},Salla.cookie=new class{constructor(){Salla.event.on("cookies::remove",(e=>this.remove(e))),Salla.event.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}clearAll(){let e=document.cookie.split(";");for(let t=0;t<e.length;t++){let r=e[t],n=r.indexOf("="),i=n>-1?r.substr(0,n):r;this.remove(i);}}},Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"[VI]{version}[/VI]"};var y$1=Salla;
|
|
3350
3350
|
|
|
3351
3351
|
var evEmitter = _commonjsHelpers.createCommonjsModule(function (module) {
|
|
3352
3352
|
/**
|
|
@@ -5507,13 +5507,13 @@ var bind = function bind(fn, thisArg) {
|
|
|
5507
5507
|
|
|
5508
5508
|
// utils is a library of generic helper functions non-specific to axios
|
|
5509
5509
|
|
|
5510
|
-
var toString = Object.prototype.toString;
|
|
5510
|
+
var toString$1 = Object.prototype.toString;
|
|
5511
5511
|
|
|
5512
5512
|
// eslint-disable-next-line func-names
|
|
5513
5513
|
var kindOf = (function(cache) {
|
|
5514
5514
|
// eslint-disable-next-line func-names
|
|
5515
5515
|
return function(thing) {
|
|
5516
|
-
var str = toString.call(thing);
|
|
5516
|
+
var str = toString$1.call(thing);
|
|
5517
5517
|
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
|
|
5518
5518
|
};
|
|
5519
5519
|
})(Object.create(null));
|
|
@@ -5531,7 +5531,7 @@ function kindOfTest(type) {
|
|
|
5531
5531
|
* @param {Object} val The value to test
|
|
5532
5532
|
* @returns {boolean} True if value is an Array, otherwise false
|
|
5533
5533
|
*/
|
|
5534
|
-
function isArray(val) {
|
|
5534
|
+
function isArray$1(val) {
|
|
5535
5535
|
return Array.isArray(val);
|
|
5536
5536
|
}
|
|
5537
5537
|
|
|
@@ -5551,7 +5551,7 @@ function isUndefined(val) {
|
|
|
5551
5551
|
* @param {Object} val The value to test
|
|
5552
5552
|
* @returns {boolean} True if value is a Buffer, otherwise false
|
|
5553
5553
|
*/
|
|
5554
|
-
function isBuffer(val) {
|
|
5554
|
+
function isBuffer$1(val) {
|
|
5555
5555
|
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
|
|
5556
5556
|
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
|
|
5557
5557
|
}
|
|
@@ -5670,7 +5670,7 @@ var isFileList = kindOfTest('FileList');
|
|
|
5670
5670
|
* @returns {boolean} True if value is a Function, otherwise false
|
|
5671
5671
|
*/
|
|
5672
5672
|
function isFunction(val) {
|
|
5673
|
-
return toString.call(val) === '[object Function]';
|
|
5673
|
+
return toString$1.call(val) === '[object Function]';
|
|
5674
5674
|
}
|
|
5675
5675
|
|
|
5676
5676
|
/**
|
|
@@ -5693,7 +5693,7 @@ function isFormData(thing) {
|
|
|
5693
5693
|
var pattern = '[object FormData]';
|
|
5694
5694
|
return thing && (
|
|
5695
5695
|
(typeof FormData === 'function' && thing instanceof FormData) ||
|
|
5696
|
-
toString.call(thing) === pattern ||
|
|
5696
|
+
toString$1.call(thing) === pattern ||
|
|
5697
5697
|
(isFunction(thing.toString) && thing.toString() === pattern)
|
|
5698
5698
|
);
|
|
5699
5699
|
}
|
|
@@ -5767,7 +5767,7 @@ function forEach(obj, fn) {
|
|
|
5767
5767
|
obj = [obj];
|
|
5768
5768
|
}
|
|
5769
5769
|
|
|
5770
|
-
if (isArray(obj)) {
|
|
5770
|
+
if (isArray$1(obj)) {
|
|
5771
5771
|
// Iterate over array values
|
|
5772
5772
|
for (var i = 0, l = obj.length; i < l; i++) {
|
|
5773
5773
|
fn.call(null, obj[i], i, obj);
|
|
@@ -5806,7 +5806,7 @@ function merge(/* obj1, obj2, obj3, ... */) {
|
|
|
5806
5806
|
result[key] = merge(result[key], val);
|
|
5807
5807
|
} else if (isPlainObject(val)) {
|
|
5808
5808
|
result[key] = merge({}, val);
|
|
5809
|
-
} else if (isArray(val)) {
|
|
5809
|
+
} else if (isArray$1(val)) {
|
|
5810
5810
|
result[key] = val.slice();
|
|
5811
5811
|
} else {
|
|
5812
5812
|
result[key] = val;
|
|
@@ -5940,9 +5940,9 @@ var isTypedArray = (function(TypedArray) {
|
|
|
5940
5940
|
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
|
|
5941
5941
|
|
|
5942
5942
|
var utils = {
|
|
5943
|
-
isArray: isArray,
|
|
5943
|
+
isArray: isArray$1,
|
|
5944
5944
|
isArrayBuffer: isArrayBuffer,
|
|
5945
|
-
isBuffer: isBuffer,
|
|
5945
|
+
isBuffer: isBuffer$1,
|
|
5946
5946
|
isFormData: isFormData,
|
|
5947
5947
|
isArrayBufferView: isArrayBufferView,
|
|
5948
5948
|
isString: isString,
|
|
@@ -6188,6 +6188,1973 @@ var transitional = {
|
|
|
6188
6188
|
clarifyTimeoutError: false
|
|
6189
6189
|
};
|
|
6190
6190
|
|
|
6191
|
+
var lookup = [];
|
|
6192
|
+
var revLookup = [];
|
|
6193
|
+
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
|
|
6194
|
+
var inited = false;
|
|
6195
|
+
function init () {
|
|
6196
|
+
inited = true;
|
|
6197
|
+
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
6198
|
+
for (var i = 0, len = code.length; i < len; ++i) {
|
|
6199
|
+
lookup[i] = code[i];
|
|
6200
|
+
revLookup[code.charCodeAt(i)] = i;
|
|
6201
|
+
}
|
|
6202
|
+
|
|
6203
|
+
revLookup['-'.charCodeAt(0)] = 62;
|
|
6204
|
+
revLookup['_'.charCodeAt(0)] = 63;
|
|
6205
|
+
}
|
|
6206
|
+
|
|
6207
|
+
function toByteArray (b64) {
|
|
6208
|
+
if (!inited) {
|
|
6209
|
+
init();
|
|
6210
|
+
}
|
|
6211
|
+
var i, j, l, tmp, placeHolders, arr;
|
|
6212
|
+
var len = b64.length;
|
|
6213
|
+
|
|
6214
|
+
if (len % 4 > 0) {
|
|
6215
|
+
throw new Error('Invalid string. Length must be a multiple of 4')
|
|
6216
|
+
}
|
|
6217
|
+
|
|
6218
|
+
// the number of equal signs (place holders)
|
|
6219
|
+
// if there are two placeholders, than the two characters before it
|
|
6220
|
+
// represent one byte
|
|
6221
|
+
// if there is only one, then the three characters before it represent 2 bytes
|
|
6222
|
+
// this is just a cheap hack to not do indexOf twice
|
|
6223
|
+
placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
|
|
6224
|
+
|
|
6225
|
+
// base64 is 4/3 + up to two characters of the original data
|
|
6226
|
+
arr = new Arr(len * 3 / 4 - placeHolders);
|
|
6227
|
+
|
|
6228
|
+
// if there are placeholders, only get up to the last complete 4 chars
|
|
6229
|
+
l = placeHolders > 0 ? len - 4 : len;
|
|
6230
|
+
|
|
6231
|
+
var L = 0;
|
|
6232
|
+
|
|
6233
|
+
for (i = 0, j = 0; i < l; i += 4, j += 3) {
|
|
6234
|
+
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
|
|
6235
|
+
arr[L++] = (tmp >> 16) & 0xFF;
|
|
6236
|
+
arr[L++] = (tmp >> 8) & 0xFF;
|
|
6237
|
+
arr[L++] = tmp & 0xFF;
|
|
6238
|
+
}
|
|
6239
|
+
|
|
6240
|
+
if (placeHolders === 2) {
|
|
6241
|
+
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
|
|
6242
|
+
arr[L++] = tmp & 0xFF;
|
|
6243
|
+
} else if (placeHolders === 1) {
|
|
6244
|
+
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
|
|
6245
|
+
arr[L++] = (tmp >> 8) & 0xFF;
|
|
6246
|
+
arr[L++] = tmp & 0xFF;
|
|
6247
|
+
}
|
|
6248
|
+
|
|
6249
|
+
return arr
|
|
6250
|
+
}
|
|
6251
|
+
|
|
6252
|
+
function tripletToBase64 (num) {
|
|
6253
|
+
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
|
|
6254
|
+
}
|
|
6255
|
+
|
|
6256
|
+
function encodeChunk (uint8, start, end) {
|
|
6257
|
+
var tmp;
|
|
6258
|
+
var output = [];
|
|
6259
|
+
for (var i = start; i < end; i += 3) {
|
|
6260
|
+
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
|
|
6261
|
+
output.push(tripletToBase64(tmp));
|
|
6262
|
+
}
|
|
6263
|
+
return output.join('')
|
|
6264
|
+
}
|
|
6265
|
+
|
|
6266
|
+
function fromByteArray (uint8) {
|
|
6267
|
+
if (!inited) {
|
|
6268
|
+
init();
|
|
6269
|
+
}
|
|
6270
|
+
var tmp;
|
|
6271
|
+
var len = uint8.length;
|
|
6272
|
+
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
|
|
6273
|
+
var output = '';
|
|
6274
|
+
var parts = [];
|
|
6275
|
+
var maxChunkLength = 16383; // must be multiple of 3
|
|
6276
|
+
|
|
6277
|
+
// go through the array every three bytes, we'll deal with trailing stuff later
|
|
6278
|
+
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
|
|
6279
|
+
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
|
|
6280
|
+
}
|
|
6281
|
+
|
|
6282
|
+
// pad the end with zeros, but make sure to not forget the extra bytes
|
|
6283
|
+
if (extraBytes === 1) {
|
|
6284
|
+
tmp = uint8[len - 1];
|
|
6285
|
+
output += lookup[tmp >> 2];
|
|
6286
|
+
output += lookup[(tmp << 4) & 0x3F];
|
|
6287
|
+
output += '==';
|
|
6288
|
+
} else if (extraBytes === 2) {
|
|
6289
|
+
tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
|
|
6290
|
+
output += lookup[tmp >> 10];
|
|
6291
|
+
output += lookup[(tmp >> 4) & 0x3F];
|
|
6292
|
+
output += lookup[(tmp << 2) & 0x3F];
|
|
6293
|
+
output += '=';
|
|
6294
|
+
}
|
|
6295
|
+
|
|
6296
|
+
parts.push(output);
|
|
6297
|
+
|
|
6298
|
+
return parts.join('')
|
|
6299
|
+
}
|
|
6300
|
+
|
|
6301
|
+
function read (buffer, offset, isLE, mLen, nBytes) {
|
|
6302
|
+
var e, m;
|
|
6303
|
+
var eLen = nBytes * 8 - mLen - 1;
|
|
6304
|
+
var eMax = (1 << eLen) - 1;
|
|
6305
|
+
var eBias = eMax >> 1;
|
|
6306
|
+
var nBits = -7;
|
|
6307
|
+
var i = isLE ? (nBytes - 1) : 0;
|
|
6308
|
+
var d = isLE ? -1 : 1;
|
|
6309
|
+
var s = buffer[offset + i];
|
|
6310
|
+
|
|
6311
|
+
i += d;
|
|
6312
|
+
|
|
6313
|
+
e = s & ((1 << (-nBits)) - 1);
|
|
6314
|
+
s >>= (-nBits);
|
|
6315
|
+
nBits += eLen;
|
|
6316
|
+
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
|
|
6317
|
+
|
|
6318
|
+
m = e & ((1 << (-nBits)) - 1);
|
|
6319
|
+
e >>= (-nBits);
|
|
6320
|
+
nBits += mLen;
|
|
6321
|
+
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
|
|
6322
|
+
|
|
6323
|
+
if (e === 0) {
|
|
6324
|
+
e = 1 - eBias;
|
|
6325
|
+
} else if (e === eMax) {
|
|
6326
|
+
return m ? NaN : ((s ? -1 : 1) * Infinity)
|
|
6327
|
+
} else {
|
|
6328
|
+
m = m + Math.pow(2, mLen);
|
|
6329
|
+
e = e - eBias;
|
|
6330
|
+
}
|
|
6331
|
+
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
|
|
6332
|
+
}
|
|
6333
|
+
|
|
6334
|
+
function write (buffer, value, offset, isLE, mLen, nBytes) {
|
|
6335
|
+
var e, m, c;
|
|
6336
|
+
var eLen = nBytes * 8 - mLen - 1;
|
|
6337
|
+
var eMax = (1 << eLen) - 1;
|
|
6338
|
+
var eBias = eMax >> 1;
|
|
6339
|
+
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
|
|
6340
|
+
var i = isLE ? 0 : (nBytes - 1);
|
|
6341
|
+
var d = isLE ? 1 : -1;
|
|
6342
|
+
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
|
|
6343
|
+
|
|
6344
|
+
value = Math.abs(value);
|
|
6345
|
+
|
|
6346
|
+
if (isNaN(value) || value === Infinity) {
|
|
6347
|
+
m = isNaN(value) ? 1 : 0;
|
|
6348
|
+
e = eMax;
|
|
6349
|
+
} else {
|
|
6350
|
+
e = Math.floor(Math.log(value) / Math.LN2);
|
|
6351
|
+
if (value * (c = Math.pow(2, -e)) < 1) {
|
|
6352
|
+
e--;
|
|
6353
|
+
c *= 2;
|
|
6354
|
+
}
|
|
6355
|
+
if (e + eBias >= 1) {
|
|
6356
|
+
value += rt / c;
|
|
6357
|
+
} else {
|
|
6358
|
+
value += rt * Math.pow(2, 1 - eBias);
|
|
6359
|
+
}
|
|
6360
|
+
if (value * c >= 2) {
|
|
6361
|
+
e++;
|
|
6362
|
+
c /= 2;
|
|
6363
|
+
}
|
|
6364
|
+
|
|
6365
|
+
if (e + eBias >= eMax) {
|
|
6366
|
+
m = 0;
|
|
6367
|
+
e = eMax;
|
|
6368
|
+
} else if (e + eBias >= 1) {
|
|
6369
|
+
m = (value * c - 1) * Math.pow(2, mLen);
|
|
6370
|
+
e = e + eBias;
|
|
6371
|
+
} else {
|
|
6372
|
+
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
|
|
6373
|
+
e = 0;
|
|
6374
|
+
}
|
|
6375
|
+
}
|
|
6376
|
+
|
|
6377
|
+
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
|
|
6378
|
+
|
|
6379
|
+
e = (e << mLen) | m;
|
|
6380
|
+
eLen += mLen;
|
|
6381
|
+
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
|
|
6382
|
+
|
|
6383
|
+
buffer[offset + i - d] |= s * 128;
|
|
6384
|
+
}
|
|
6385
|
+
|
|
6386
|
+
var toString = {}.toString;
|
|
6387
|
+
|
|
6388
|
+
var isArray = Array.isArray || function (arr) {
|
|
6389
|
+
return toString.call(arr) == '[object Array]';
|
|
6390
|
+
};
|
|
6391
|
+
|
|
6392
|
+
/*!
|
|
6393
|
+
* The buffer module from node.js, for the browser.
|
|
6394
|
+
*
|
|
6395
|
+
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
|
|
6396
|
+
* @license MIT
|
|
6397
|
+
*/
|
|
6398
|
+
|
|
6399
|
+
var INSPECT_MAX_BYTES = 50;
|
|
6400
|
+
|
|
6401
|
+
/**
|
|
6402
|
+
* If `Buffer.TYPED_ARRAY_SUPPORT`:
|
|
6403
|
+
* === true Use Uint8Array implementation (fastest)
|
|
6404
|
+
* === false Use Object implementation (most compatible, even IE6)
|
|
6405
|
+
*
|
|
6406
|
+
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
|
|
6407
|
+
* Opera 11.6+, iOS 4.2+.
|
|
6408
|
+
*
|
|
6409
|
+
* Due to various browser bugs, sometimes the Object implementation will be used even
|
|
6410
|
+
* when the browser supports typed arrays.
|
|
6411
|
+
*
|
|
6412
|
+
* Note:
|
|
6413
|
+
*
|
|
6414
|
+
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
|
|
6415
|
+
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
|
|
6416
|
+
*
|
|
6417
|
+
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
|
|
6418
|
+
*
|
|
6419
|
+
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
|
|
6420
|
+
* incorrect length in some situations.
|
|
6421
|
+
|
|
6422
|
+
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
|
|
6423
|
+
* get the Object implementation, which is slower but behaves correctly.
|
|
6424
|
+
*/
|
|
6425
|
+
Buffer.TYPED_ARRAY_SUPPORT = _commonjsHelpers.global.TYPED_ARRAY_SUPPORT !== undefined
|
|
6426
|
+
? _commonjsHelpers.global.TYPED_ARRAY_SUPPORT
|
|
6427
|
+
: true;
|
|
6428
|
+
|
|
6429
|
+
function kMaxLength () {
|
|
6430
|
+
return Buffer.TYPED_ARRAY_SUPPORT
|
|
6431
|
+
? 0x7fffffff
|
|
6432
|
+
: 0x3fffffff
|
|
6433
|
+
}
|
|
6434
|
+
|
|
6435
|
+
function createBuffer (that, length) {
|
|
6436
|
+
if (kMaxLength() < length) {
|
|
6437
|
+
throw new RangeError('Invalid typed array length')
|
|
6438
|
+
}
|
|
6439
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
6440
|
+
// Return an augmented `Uint8Array` instance, for best performance
|
|
6441
|
+
that = new Uint8Array(length);
|
|
6442
|
+
that.__proto__ = Buffer.prototype;
|
|
6443
|
+
} else {
|
|
6444
|
+
// Fallback: Return an object instance of the Buffer class
|
|
6445
|
+
if (that === null) {
|
|
6446
|
+
that = new Buffer(length);
|
|
6447
|
+
}
|
|
6448
|
+
that.length = length;
|
|
6449
|
+
}
|
|
6450
|
+
|
|
6451
|
+
return that
|
|
6452
|
+
}
|
|
6453
|
+
|
|
6454
|
+
/**
|
|
6455
|
+
* The Buffer constructor returns instances of `Uint8Array` that have their
|
|
6456
|
+
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
|
|
6457
|
+
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
|
|
6458
|
+
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
|
|
6459
|
+
* returns a single octet.
|
|
6460
|
+
*
|
|
6461
|
+
* The `Uint8Array` prototype remains unmodified.
|
|
6462
|
+
*/
|
|
6463
|
+
|
|
6464
|
+
function Buffer (arg, encodingOrOffset, length) {
|
|
6465
|
+
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
|
|
6466
|
+
return new Buffer(arg, encodingOrOffset, length)
|
|
6467
|
+
}
|
|
6468
|
+
|
|
6469
|
+
// Common case.
|
|
6470
|
+
if (typeof arg === 'number') {
|
|
6471
|
+
if (typeof encodingOrOffset === 'string') {
|
|
6472
|
+
throw new Error(
|
|
6473
|
+
'If encoding is specified then the first argument must be a string'
|
|
6474
|
+
)
|
|
6475
|
+
}
|
|
6476
|
+
return allocUnsafe(this, arg)
|
|
6477
|
+
}
|
|
6478
|
+
return from(this, arg, encodingOrOffset, length)
|
|
6479
|
+
}
|
|
6480
|
+
|
|
6481
|
+
Buffer.poolSize = 8192; // not used by this implementation
|
|
6482
|
+
|
|
6483
|
+
// TODO: Legacy, not needed anymore. Remove in next major version.
|
|
6484
|
+
Buffer._augment = function (arr) {
|
|
6485
|
+
arr.__proto__ = Buffer.prototype;
|
|
6486
|
+
return arr
|
|
6487
|
+
};
|
|
6488
|
+
|
|
6489
|
+
function from (that, value, encodingOrOffset, length) {
|
|
6490
|
+
if (typeof value === 'number') {
|
|
6491
|
+
throw new TypeError('"value" argument must not be a number')
|
|
6492
|
+
}
|
|
6493
|
+
|
|
6494
|
+
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
|
|
6495
|
+
return fromArrayBuffer(that, value, encodingOrOffset, length)
|
|
6496
|
+
}
|
|
6497
|
+
|
|
6498
|
+
if (typeof value === 'string') {
|
|
6499
|
+
return fromString(that, value, encodingOrOffset)
|
|
6500
|
+
}
|
|
6501
|
+
|
|
6502
|
+
return fromObject(that, value)
|
|
6503
|
+
}
|
|
6504
|
+
|
|
6505
|
+
/**
|
|
6506
|
+
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
|
|
6507
|
+
* if value is a number.
|
|
6508
|
+
* Buffer.from(str[, encoding])
|
|
6509
|
+
* Buffer.from(array)
|
|
6510
|
+
* Buffer.from(buffer)
|
|
6511
|
+
* Buffer.from(arrayBuffer[, byteOffset[, length]])
|
|
6512
|
+
**/
|
|
6513
|
+
Buffer.from = function (value, encodingOrOffset, length) {
|
|
6514
|
+
return from(null, value, encodingOrOffset, length)
|
|
6515
|
+
};
|
|
6516
|
+
|
|
6517
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
6518
|
+
Buffer.prototype.__proto__ = Uint8Array.prototype;
|
|
6519
|
+
Buffer.__proto__ = Uint8Array;
|
|
6520
|
+
}
|
|
6521
|
+
|
|
6522
|
+
function assertSize (size) {
|
|
6523
|
+
if (typeof size !== 'number') {
|
|
6524
|
+
throw new TypeError('"size" argument must be a number')
|
|
6525
|
+
} else if (size < 0) {
|
|
6526
|
+
throw new RangeError('"size" argument must not be negative')
|
|
6527
|
+
}
|
|
6528
|
+
}
|
|
6529
|
+
|
|
6530
|
+
function alloc (that, size, fill, encoding) {
|
|
6531
|
+
assertSize(size);
|
|
6532
|
+
if (size <= 0) {
|
|
6533
|
+
return createBuffer(that, size)
|
|
6534
|
+
}
|
|
6535
|
+
if (fill !== undefined) {
|
|
6536
|
+
// Only pay attention to encoding if it's a string. This
|
|
6537
|
+
// prevents accidentally sending in a number that would
|
|
6538
|
+
// be interpretted as a start offset.
|
|
6539
|
+
return typeof encoding === 'string'
|
|
6540
|
+
? createBuffer(that, size).fill(fill, encoding)
|
|
6541
|
+
: createBuffer(that, size).fill(fill)
|
|
6542
|
+
}
|
|
6543
|
+
return createBuffer(that, size)
|
|
6544
|
+
}
|
|
6545
|
+
|
|
6546
|
+
/**
|
|
6547
|
+
* Creates a new filled Buffer instance.
|
|
6548
|
+
* alloc(size[, fill[, encoding]])
|
|
6549
|
+
**/
|
|
6550
|
+
Buffer.alloc = function (size, fill, encoding) {
|
|
6551
|
+
return alloc(null, size, fill, encoding)
|
|
6552
|
+
};
|
|
6553
|
+
|
|
6554
|
+
function allocUnsafe (that, size) {
|
|
6555
|
+
assertSize(size);
|
|
6556
|
+
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
|
|
6557
|
+
if (!Buffer.TYPED_ARRAY_SUPPORT) {
|
|
6558
|
+
for (var i = 0; i < size; ++i) {
|
|
6559
|
+
that[i] = 0;
|
|
6560
|
+
}
|
|
6561
|
+
}
|
|
6562
|
+
return that
|
|
6563
|
+
}
|
|
6564
|
+
|
|
6565
|
+
/**
|
|
6566
|
+
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
|
|
6567
|
+
* */
|
|
6568
|
+
Buffer.allocUnsafe = function (size) {
|
|
6569
|
+
return allocUnsafe(null, size)
|
|
6570
|
+
};
|
|
6571
|
+
/**
|
|
6572
|
+
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
|
|
6573
|
+
*/
|
|
6574
|
+
Buffer.allocUnsafeSlow = function (size) {
|
|
6575
|
+
return allocUnsafe(null, size)
|
|
6576
|
+
};
|
|
6577
|
+
|
|
6578
|
+
function fromString (that, string, encoding) {
|
|
6579
|
+
if (typeof encoding !== 'string' || encoding === '') {
|
|
6580
|
+
encoding = 'utf8';
|
|
6581
|
+
}
|
|
6582
|
+
|
|
6583
|
+
if (!Buffer.isEncoding(encoding)) {
|
|
6584
|
+
throw new TypeError('"encoding" must be a valid string encoding')
|
|
6585
|
+
}
|
|
6586
|
+
|
|
6587
|
+
var length = byteLength(string, encoding) | 0;
|
|
6588
|
+
that = createBuffer(that, length);
|
|
6589
|
+
|
|
6590
|
+
var actual = that.write(string, encoding);
|
|
6591
|
+
|
|
6592
|
+
if (actual !== length) {
|
|
6593
|
+
// Writing a hex string, for example, that contains invalid characters will
|
|
6594
|
+
// cause everything after the first invalid character to be ignored. (e.g.
|
|
6595
|
+
// 'abxxcd' will be treated as 'ab')
|
|
6596
|
+
that = that.slice(0, actual);
|
|
6597
|
+
}
|
|
6598
|
+
|
|
6599
|
+
return that
|
|
6600
|
+
}
|
|
6601
|
+
|
|
6602
|
+
function fromArrayLike (that, array) {
|
|
6603
|
+
var length = array.length < 0 ? 0 : checked(array.length) | 0;
|
|
6604
|
+
that = createBuffer(that, length);
|
|
6605
|
+
for (var i = 0; i < length; i += 1) {
|
|
6606
|
+
that[i] = array[i] & 255;
|
|
6607
|
+
}
|
|
6608
|
+
return that
|
|
6609
|
+
}
|
|
6610
|
+
|
|
6611
|
+
function fromArrayBuffer (that, array, byteOffset, length) {
|
|
6612
|
+
|
|
6613
|
+
if (byteOffset < 0 || array.byteLength < byteOffset) {
|
|
6614
|
+
throw new RangeError('\'offset\' is out of bounds')
|
|
6615
|
+
}
|
|
6616
|
+
|
|
6617
|
+
if (array.byteLength < byteOffset + (length || 0)) {
|
|
6618
|
+
throw new RangeError('\'length\' is out of bounds')
|
|
6619
|
+
}
|
|
6620
|
+
|
|
6621
|
+
if (byteOffset === undefined && length === undefined) {
|
|
6622
|
+
array = new Uint8Array(array);
|
|
6623
|
+
} else if (length === undefined) {
|
|
6624
|
+
array = new Uint8Array(array, byteOffset);
|
|
6625
|
+
} else {
|
|
6626
|
+
array = new Uint8Array(array, byteOffset, length);
|
|
6627
|
+
}
|
|
6628
|
+
|
|
6629
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
6630
|
+
// Return an augmented `Uint8Array` instance, for best performance
|
|
6631
|
+
that = array;
|
|
6632
|
+
that.__proto__ = Buffer.prototype;
|
|
6633
|
+
} else {
|
|
6634
|
+
// Fallback: Return an object instance of the Buffer class
|
|
6635
|
+
that = fromArrayLike(that, array);
|
|
6636
|
+
}
|
|
6637
|
+
return that
|
|
6638
|
+
}
|
|
6639
|
+
|
|
6640
|
+
function fromObject (that, obj) {
|
|
6641
|
+
if (internalIsBuffer(obj)) {
|
|
6642
|
+
var len = checked(obj.length) | 0;
|
|
6643
|
+
that = createBuffer(that, len);
|
|
6644
|
+
|
|
6645
|
+
if (that.length === 0) {
|
|
6646
|
+
return that
|
|
6647
|
+
}
|
|
6648
|
+
|
|
6649
|
+
obj.copy(that, 0, 0, len);
|
|
6650
|
+
return that
|
|
6651
|
+
}
|
|
6652
|
+
|
|
6653
|
+
if (obj) {
|
|
6654
|
+
if ((typeof ArrayBuffer !== 'undefined' &&
|
|
6655
|
+
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
|
|
6656
|
+
if (typeof obj.length !== 'number' || isnan(obj.length)) {
|
|
6657
|
+
return createBuffer(that, 0)
|
|
6658
|
+
}
|
|
6659
|
+
return fromArrayLike(that, obj)
|
|
6660
|
+
}
|
|
6661
|
+
|
|
6662
|
+
if (obj.type === 'Buffer' && isArray(obj.data)) {
|
|
6663
|
+
return fromArrayLike(that, obj.data)
|
|
6664
|
+
}
|
|
6665
|
+
}
|
|
6666
|
+
|
|
6667
|
+
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
|
|
6668
|
+
}
|
|
6669
|
+
|
|
6670
|
+
function checked (length) {
|
|
6671
|
+
// Note: cannot use `length < kMaxLength()` here because that fails when
|
|
6672
|
+
// length is NaN (which is otherwise coerced to zero.)
|
|
6673
|
+
if (length >= kMaxLength()) {
|
|
6674
|
+
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
|
|
6675
|
+
'size: 0x' + kMaxLength().toString(16) + ' bytes')
|
|
6676
|
+
}
|
|
6677
|
+
return length | 0
|
|
6678
|
+
}
|
|
6679
|
+
Buffer.isBuffer = isBuffer;
|
|
6680
|
+
function internalIsBuffer (b) {
|
|
6681
|
+
return !!(b != null && b._isBuffer)
|
|
6682
|
+
}
|
|
6683
|
+
|
|
6684
|
+
Buffer.compare = function compare (a, b) {
|
|
6685
|
+
if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
|
|
6686
|
+
throw new TypeError('Arguments must be Buffers')
|
|
6687
|
+
}
|
|
6688
|
+
|
|
6689
|
+
if (a === b) return 0
|
|
6690
|
+
|
|
6691
|
+
var x = a.length;
|
|
6692
|
+
var y = b.length;
|
|
6693
|
+
|
|
6694
|
+
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
|
|
6695
|
+
if (a[i] !== b[i]) {
|
|
6696
|
+
x = a[i];
|
|
6697
|
+
y = b[i];
|
|
6698
|
+
break
|
|
6699
|
+
}
|
|
6700
|
+
}
|
|
6701
|
+
|
|
6702
|
+
if (x < y) return -1
|
|
6703
|
+
if (y < x) return 1
|
|
6704
|
+
return 0
|
|
6705
|
+
};
|
|
6706
|
+
|
|
6707
|
+
Buffer.isEncoding = function isEncoding (encoding) {
|
|
6708
|
+
switch (String(encoding).toLowerCase()) {
|
|
6709
|
+
case 'hex':
|
|
6710
|
+
case 'utf8':
|
|
6711
|
+
case 'utf-8':
|
|
6712
|
+
case 'ascii':
|
|
6713
|
+
case 'latin1':
|
|
6714
|
+
case 'binary':
|
|
6715
|
+
case 'base64':
|
|
6716
|
+
case 'ucs2':
|
|
6717
|
+
case 'ucs-2':
|
|
6718
|
+
case 'utf16le':
|
|
6719
|
+
case 'utf-16le':
|
|
6720
|
+
return true
|
|
6721
|
+
default:
|
|
6722
|
+
return false
|
|
6723
|
+
}
|
|
6724
|
+
};
|
|
6725
|
+
|
|
6726
|
+
Buffer.concat = function concat (list, length) {
|
|
6727
|
+
if (!isArray(list)) {
|
|
6728
|
+
throw new TypeError('"list" argument must be an Array of Buffers')
|
|
6729
|
+
}
|
|
6730
|
+
|
|
6731
|
+
if (list.length === 0) {
|
|
6732
|
+
return Buffer.alloc(0)
|
|
6733
|
+
}
|
|
6734
|
+
|
|
6735
|
+
var i;
|
|
6736
|
+
if (length === undefined) {
|
|
6737
|
+
length = 0;
|
|
6738
|
+
for (i = 0; i < list.length; ++i) {
|
|
6739
|
+
length += list[i].length;
|
|
6740
|
+
}
|
|
6741
|
+
}
|
|
6742
|
+
|
|
6743
|
+
var buffer = Buffer.allocUnsafe(length);
|
|
6744
|
+
var pos = 0;
|
|
6745
|
+
for (i = 0; i < list.length; ++i) {
|
|
6746
|
+
var buf = list[i];
|
|
6747
|
+
if (!internalIsBuffer(buf)) {
|
|
6748
|
+
throw new TypeError('"list" argument must be an Array of Buffers')
|
|
6749
|
+
}
|
|
6750
|
+
buf.copy(buffer, pos);
|
|
6751
|
+
pos += buf.length;
|
|
6752
|
+
}
|
|
6753
|
+
return buffer
|
|
6754
|
+
};
|
|
6755
|
+
|
|
6756
|
+
function byteLength (string, encoding) {
|
|
6757
|
+
if (internalIsBuffer(string)) {
|
|
6758
|
+
return string.length
|
|
6759
|
+
}
|
|
6760
|
+
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
|
|
6761
|
+
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
|
|
6762
|
+
return string.byteLength
|
|
6763
|
+
}
|
|
6764
|
+
if (typeof string !== 'string') {
|
|
6765
|
+
string = '' + string;
|
|
6766
|
+
}
|
|
6767
|
+
|
|
6768
|
+
var len = string.length;
|
|
6769
|
+
if (len === 0) return 0
|
|
6770
|
+
|
|
6771
|
+
// Use a for loop to avoid recursion
|
|
6772
|
+
var loweredCase = false;
|
|
6773
|
+
for (;;) {
|
|
6774
|
+
switch (encoding) {
|
|
6775
|
+
case 'ascii':
|
|
6776
|
+
case 'latin1':
|
|
6777
|
+
case 'binary':
|
|
6778
|
+
return len
|
|
6779
|
+
case 'utf8':
|
|
6780
|
+
case 'utf-8':
|
|
6781
|
+
case undefined:
|
|
6782
|
+
return utf8ToBytes(string).length
|
|
6783
|
+
case 'ucs2':
|
|
6784
|
+
case 'ucs-2':
|
|
6785
|
+
case 'utf16le':
|
|
6786
|
+
case 'utf-16le':
|
|
6787
|
+
return len * 2
|
|
6788
|
+
case 'hex':
|
|
6789
|
+
return len >>> 1
|
|
6790
|
+
case 'base64':
|
|
6791
|
+
return base64ToBytes(string).length
|
|
6792
|
+
default:
|
|
6793
|
+
if (loweredCase) return utf8ToBytes(string).length // assume utf8
|
|
6794
|
+
encoding = ('' + encoding).toLowerCase();
|
|
6795
|
+
loweredCase = true;
|
|
6796
|
+
}
|
|
6797
|
+
}
|
|
6798
|
+
}
|
|
6799
|
+
Buffer.byteLength = byteLength;
|
|
6800
|
+
|
|
6801
|
+
function slowToString (encoding, start, end) {
|
|
6802
|
+
var loweredCase = false;
|
|
6803
|
+
|
|
6804
|
+
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
|
|
6805
|
+
// property of a typed array.
|
|
6806
|
+
|
|
6807
|
+
// This behaves neither like String nor Uint8Array in that we set start/end
|
|
6808
|
+
// to their upper/lower bounds if the value passed is out of range.
|
|
6809
|
+
// undefined is handled specially as per ECMA-262 6th Edition,
|
|
6810
|
+
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
|
|
6811
|
+
if (start === undefined || start < 0) {
|
|
6812
|
+
start = 0;
|
|
6813
|
+
}
|
|
6814
|
+
// Return early if start > this.length. Done here to prevent potential uint32
|
|
6815
|
+
// coercion fail below.
|
|
6816
|
+
if (start > this.length) {
|
|
6817
|
+
return ''
|
|
6818
|
+
}
|
|
6819
|
+
|
|
6820
|
+
if (end === undefined || end > this.length) {
|
|
6821
|
+
end = this.length;
|
|
6822
|
+
}
|
|
6823
|
+
|
|
6824
|
+
if (end <= 0) {
|
|
6825
|
+
return ''
|
|
6826
|
+
}
|
|
6827
|
+
|
|
6828
|
+
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
|
|
6829
|
+
end >>>= 0;
|
|
6830
|
+
start >>>= 0;
|
|
6831
|
+
|
|
6832
|
+
if (end <= start) {
|
|
6833
|
+
return ''
|
|
6834
|
+
}
|
|
6835
|
+
|
|
6836
|
+
if (!encoding) encoding = 'utf8';
|
|
6837
|
+
|
|
6838
|
+
while (true) {
|
|
6839
|
+
switch (encoding) {
|
|
6840
|
+
case 'hex':
|
|
6841
|
+
return hexSlice(this, start, end)
|
|
6842
|
+
|
|
6843
|
+
case 'utf8':
|
|
6844
|
+
case 'utf-8':
|
|
6845
|
+
return utf8Slice(this, start, end)
|
|
6846
|
+
|
|
6847
|
+
case 'ascii':
|
|
6848
|
+
return asciiSlice(this, start, end)
|
|
6849
|
+
|
|
6850
|
+
case 'latin1':
|
|
6851
|
+
case 'binary':
|
|
6852
|
+
return latin1Slice(this, start, end)
|
|
6853
|
+
|
|
6854
|
+
case 'base64':
|
|
6855
|
+
return base64Slice(this, start, end)
|
|
6856
|
+
|
|
6857
|
+
case 'ucs2':
|
|
6858
|
+
case 'ucs-2':
|
|
6859
|
+
case 'utf16le':
|
|
6860
|
+
case 'utf-16le':
|
|
6861
|
+
return utf16leSlice(this, start, end)
|
|
6862
|
+
|
|
6863
|
+
default:
|
|
6864
|
+
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
|
|
6865
|
+
encoding = (encoding + '').toLowerCase();
|
|
6866
|
+
loweredCase = true;
|
|
6867
|
+
}
|
|
6868
|
+
}
|
|
6869
|
+
}
|
|
6870
|
+
|
|
6871
|
+
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
|
|
6872
|
+
// Buffer instances.
|
|
6873
|
+
Buffer.prototype._isBuffer = true;
|
|
6874
|
+
|
|
6875
|
+
function swap (b, n, m) {
|
|
6876
|
+
var i = b[n];
|
|
6877
|
+
b[n] = b[m];
|
|
6878
|
+
b[m] = i;
|
|
6879
|
+
}
|
|
6880
|
+
|
|
6881
|
+
Buffer.prototype.swap16 = function swap16 () {
|
|
6882
|
+
var len = this.length;
|
|
6883
|
+
if (len % 2 !== 0) {
|
|
6884
|
+
throw new RangeError('Buffer size must be a multiple of 16-bits')
|
|
6885
|
+
}
|
|
6886
|
+
for (var i = 0; i < len; i += 2) {
|
|
6887
|
+
swap(this, i, i + 1);
|
|
6888
|
+
}
|
|
6889
|
+
return this
|
|
6890
|
+
};
|
|
6891
|
+
|
|
6892
|
+
Buffer.prototype.swap32 = function swap32 () {
|
|
6893
|
+
var len = this.length;
|
|
6894
|
+
if (len % 4 !== 0) {
|
|
6895
|
+
throw new RangeError('Buffer size must be a multiple of 32-bits')
|
|
6896
|
+
}
|
|
6897
|
+
for (var i = 0; i < len; i += 4) {
|
|
6898
|
+
swap(this, i, i + 3);
|
|
6899
|
+
swap(this, i + 1, i + 2);
|
|
6900
|
+
}
|
|
6901
|
+
return this
|
|
6902
|
+
};
|
|
6903
|
+
|
|
6904
|
+
Buffer.prototype.swap64 = function swap64 () {
|
|
6905
|
+
var len = this.length;
|
|
6906
|
+
if (len % 8 !== 0) {
|
|
6907
|
+
throw new RangeError('Buffer size must be a multiple of 64-bits')
|
|
6908
|
+
}
|
|
6909
|
+
for (var i = 0; i < len; i += 8) {
|
|
6910
|
+
swap(this, i, i + 7);
|
|
6911
|
+
swap(this, i + 1, i + 6);
|
|
6912
|
+
swap(this, i + 2, i + 5);
|
|
6913
|
+
swap(this, i + 3, i + 4);
|
|
6914
|
+
}
|
|
6915
|
+
return this
|
|
6916
|
+
};
|
|
6917
|
+
|
|
6918
|
+
Buffer.prototype.toString = function toString () {
|
|
6919
|
+
var length = this.length | 0;
|
|
6920
|
+
if (length === 0) return ''
|
|
6921
|
+
if (arguments.length === 0) return utf8Slice(this, 0, length)
|
|
6922
|
+
return slowToString.apply(this, arguments)
|
|
6923
|
+
};
|
|
6924
|
+
|
|
6925
|
+
Buffer.prototype.equals = function equals (b) {
|
|
6926
|
+
if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
|
|
6927
|
+
if (this === b) return true
|
|
6928
|
+
return Buffer.compare(this, b) === 0
|
|
6929
|
+
};
|
|
6930
|
+
|
|
6931
|
+
Buffer.prototype.inspect = function inspect () {
|
|
6932
|
+
var str = '';
|
|
6933
|
+
var max = INSPECT_MAX_BYTES;
|
|
6934
|
+
if (this.length > 0) {
|
|
6935
|
+
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
|
|
6936
|
+
if (this.length > max) str += ' ... ';
|
|
6937
|
+
}
|
|
6938
|
+
return '<Buffer ' + str + '>'
|
|
6939
|
+
};
|
|
6940
|
+
|
|
6941
|
+
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
|
|
6942
|
+
if (!internalIsBuffer(target)) {
|
|
6943
|
+
throw new TypeError('Argument must be a Buffer')
|
|
6944
|
+
}
|
|
6945
|
+
|
|
6946
|
+
if (start === undefined) {
|
|
6947
|
+
start = 0;
|
|
6948
|
+
}
|
|
6949
|
+
if (end === undefined) {
|
|
6950
|
+
end = target ? target.length : 0;
|
|
6951
|
+
}
|
|
6952
|
+
if (thisStart === undefined) {
|
|
6953
|
+
thisStart = 0;
|
|
6954
|
+
}
|
|
6955
|
+
if (thisEnd === undefined) {
|
|
6956
|
+
thisEnd = this.length;
|
|
6957
|
+
}
|
|
6958
|
+
|
|
6959
|
+
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
|
|
6960
|
+
throw new RangeError('out of range index')
|
|
6961
|
+
}
|
|
6962
|
+
|
|
6963
|
+
if (thisStart >= thisEnd && start >= end) {
|
|
6964
|
+
return 0
|
|
6965
|
+
}
|
|
6966
|
+
if (thisStart >= thisEnd) {
|
|
6967
|
+
return -1
|
|
6968
|
+
}
|
|
6969
|
+
if (start >= end) {
|
|
6970
|
+
return 1
|
|
6971
|
+
}
|
|
6972
|
+
|
|
6973
|
+
start >>>= 0;
|
|
6974
|
+
end >>>= 0;
|
|
6975
|
+
thisStart >>>= 0;
|
|
6976
|
+
thisEnd >>>= 0;
|
|
6977
|
+
|
|
6978
|
+
if (this === target) return 0
|
|
6979
|
+
|
|
6980
|
+
var x = thisEnd - thisStart;
|
|
6981
|
+
var y = end - start;
|
|
6982
|
+
var len = Math.min(x, y);
|
|
6983
|
+
|
|
6984
|
+
var thisCopy = this.slice(thisStart, thisEnd);
|
|
6985
|
+
var targetCopy = target.slice(start, end);
|
|
6986
|
+
|
|
6987
|
+
for (var i = 0; i < len; ++i) {
|
|
6988
|
+
if (thisCopy[i] !== targetCopy[i]) {
|
|
6989
|
+
x = thisCopy[i];
|
|
6990
|
+
y = targetCopy[i];
|
|
6991
|
+
break
|
|
6992
|
+
}
|
|
6993
|
+
}
|
|
6994
|
+
|
|
6995
|
+
if (x < y) return -1
|
|
6996
|
+
if (y < x) return 1
|
|
6997
|
+
return 0
|
|
6998
|
+
};
|
|
6999
|
+
|
|
7000
|
+
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
|
|
7001
|
+
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
|
|
7002
|
+
//
|
|
7003
|
+
// Arguments:
|
|
7004
|
+
// - buffer - a Buffer to search
|
|
7005
|
+
// - val - a string, Buffer, or number
|
|
7006
|
+
// - byteOffset - an index into `buffer`; will be clamped to an int32
|
|
7007
|
+
// - encoding - an optional encoding, relevant is val is a string
|
|
7008
|
+
// - dir - true for indexOf, false for lastIndexOf
|
|
7009
|
+
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
|
|
7010
|
+
// Empty buffer means no match
|
|
7011
|
+
if (buffer.length === 0) return -1
|
|
7012
|
+
|
|
7013
|
+
// Normalize byteOffset
|
|
7014
|
+
if (typeof byteOffset === 'string') {
|
|
7015
|
+
encoding = byteOffset;
|
|
7016
|
+
byteOffset = 0;
|
|
7017
|
+
} else if (byteOffset > 0x7fffffff) {
|
|
7018
|
+
byteOffset = 0x7fffffff;
|
|
7019
|
+
} else if (byteOffset < -0x80000000) {
|
|
7020
|
+
byteOffset = -0x80000000;
|
|
7021
|
+
}
|
|
7022
|
+
byteOffset = +byteOffset; // Coerce to Number.
|
|
7023
|
+
if (isNaN(byteOffset)) {
|
|
7024
|
+
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
|
|
7025
|
+
byteOffset = dir ? 0 : (buffer.length - 1);
|
|
7026
|
+
}
|
|
7027
|
+
|
|
7028
|
+
// Normalize byteOffset: negative offsets start from the end of the buffer
|
|
7029
|
+
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
|
|
7030
|
+
if (byteOffset >= buffer.length) {
|
|
7031
|
+
if (dir) return -1
|
|
7032
|
+
else byteOffset = buffer.length - 1;
|
|
7033
|
+
} else if (byteOffset < 0) {
|
|
7034
|
+
if (dir) byteOffset = 0;
|
|
7035
|
+
else return -1
|
|
7036
|
+
}
|
|
7037
|
+
|
|
7038
|
+
// Normalize val
|
|
7039
|
+
if (typeof val === 'string') {
|
|
7040
|
+
val = Buffer.from(val, encoding);
|
|
7041
|
+
}
|
|
7042
|
+
|
|
7043
|
+
// Finally, search either indexOf (if dir is true) or lastIndexOf
|
|
7044
|
+
if (internalIsBuffer(val)) {
|
|
7045
|
+
// Special case: looking for empty string/buffer always fails
|
|
7046
|
+
if (val.length === 0) {
|
|
7047
|
+
return -1
|
|
7048
|
+
}
|
|
7049
|
+
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
|
|
7050
|
+
} else if (typeof val === 'number') {
|
|
7051
|
+
val = val & 0xFF; // Search for a byte value [0-255]
|
|
7052
|
+
if (Buffer.TYPED_ARRAY_SUPPORT &&
|
|
7053
|
+
typeof Uint8Array.prototype.indexOf === 'function') {
|
|
7054
|
+
if (dir) {
|
|
7055
|
+
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
|
|
7056
|
+
} else {
|
|
7057
|
+
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
|
|
7058
|
+
}
|
|
7059
|
+
}
|
|
7060
|
+
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
|
|
7061
|
+
}
|
|
7062
|
+
|
|
7063
|
+
throw new TypeError('val must be string, number or Buffer')
|
|
7064
|
+
}
|
|
7065
|
+
|
|
7066
|
+
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
|
|
7067
|
+
var indexSize = 1;
|
|
7068
|
+
var arrLength = arr.length;
|
|
7069
|
+
var valLength = val.length;
|
|
7070
|
+
|
|
7071
|
+
if (encoding !== undefined) {
|
|
7072
|
+
encoding = String(encoding).toLowerCase();
|
|
7073
|
+
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
|
|
7074
|
+
encoding === 'utf16le' || encoding === 'utf-16le') {
|
|
7075
|
+
if (arr.length < 2 || val.length < 2) {
|
|
7076
|
+
return -1
|
|
7077
|
+
}
|
|
7078
|
+
indexSize = 2;
|
|
7079
|
+
arrLength /= 2;
|
|
7080
|
+
valLength /= 2;
|
|
7081
|
+
byteOffset /= 2;
|
|
7082
|
+
}
|
|
7083
|
+
}
|
|
7084
|
+
|
|
7085
|
+
function read (buf, i) {
|
|
7086
|
+
if (indexSize === 1) {
|
|
7087
|
+
return buf[i]
|
|
7088
|
+
} else {
|
|
7089
|
+
return buf.readUInt16BE(i * indexSize)
|
|
7090
|
+
}
|
|
7091
|
+
}
|
|
7092
|
+
|
|
7093
|
+
var i;
|
|
7094
|
+
if (dir) {
|
|
7095
|
+
var foundIndex = -1;
|
|
7096
|
+
for (i = byteOffset; i < arrLength; i++) {
|
|
7097
|
+
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
|
|
7098
|
+
if (foundIndex === -1) foundIndex = i;
|
|
7099
|
+
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
|
|
7100
|
+
} else {
|
|
7101
|
+
if (foundIndex !== -1) i -= i - foundIndex;
|
|
7102
|
+
foundIndex = -1;
|
|
7103
|
+
}
|
|
7104
|
+
}
|
|
7105
|
+
} else {
|
|
7106
|
+
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
|
|
7107
|
+
for (i = byteOffset; i >= 0; i--) {
|
|
7108
|
+
var found = true;
|
|
7109
|
+
for (var j = 0; j < valLength; j++) {
|
|
7110
|
+
if (read(arr, i + j) !== read(val, j)) {
|
|
7111
|
+
found = false;
|
|
7112
|
+
break
|
|
7113
|
+
}
|
|
7114
|
+
}
|
|
7115
|
+
if (found) return i
|
|
7116
|
+
}
|
|
7117
|
+
}
|
|
7118
|
+
|
|
7119
|
+
return -1
|
|
7120
|
+
}
|
|
7121
|
+
|
|
7122
|
+
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
|
|
7123
|
+
return this.indexOf(val, byteOffset, encoding) !== -1
|
|
7124
|
+
};
|
|
7125
|
+
|
|
7126
|
+
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
|
|
7127
|
+
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
|
|
7128
|
+
};
|
|
7129
|
+
|
|
7130
|
+
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
|
|
7131
|
+
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
|
|
7132
|
+
};
|
|
7133
|
+
|
|
7134
|
+
function hexWrite (buf, string, offset, length) {
|
|
7135
|
+
offset = Number(offset) || 0;
|
|
7136
|
+
var remaining = buf.length - offset;
|
|
7137
|
+
if (!length) {
|
|
7138
|
+
length = remaining;
|
|
7139
|
+
} else {
|
|
7140
|
+
length = Number(length);
|
|
7141
|
+
if (length > remaining) {
|
|
7142
|
+
length = remaining;
|
|
7143
|
+
}
|
|
7144
|
+
}
|
|
7145
|
+
|
|
7146
|
+
// must be an even number of digits
|
|
7147
|
+
var strLen = string.length;
|
|
7148
|
+
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
|
|
7149
|
+
|
|
7150
|
+
if (length > strLen / 2) {
|
|
7151
|
+
length = strLen / 2;
|
|
7152
|
+
}
|
|
7153
|
+
for (var i = 0; i < length; ++i) {
|
|
7154
|
+
var parsed = parseInt(string.substr(i * 2, 2), 16);
|
|
7155
|
+
if (isNaN(parsed)) return i
|
|
7156
|
+
buf[offset + i] = parsed;
|
|
7157
|
+
}
|
|
7158
|
+
return i
|
|
7159
|
+
}
|
|
7160
|
+
|
|
7161
|
+
function utf8Write (buf, string, offset, length) {
|
|
7162
|
+
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
|
|
7163
|
+
}
|
|
7164
|
+
|
|
7165
|
+
function asciiWrite (buf, string, offset, length) {
|
|
7166
|
+
return blitBuffer(asciiToBytes(string), buf, offset, length)
|
|
7167
|
+
}
|
|
7168
|
+
|
|
7169
|
+
function latin1Write (buf, string, offset, length) {
|
|
7170
|
+
return asciiWrite(buf, string, offset, length)
|
|
7171
|
+
}
|
|
7172
|
+
|
|
7173
|
+
function base64Write (buf, string, offset, length) {
|
|
7174
|
+
return blitBuffer(base64ToBytes(string), buf, offset, length)
|
|
7175
|
+
}
|
|
7176
|
+
|
|
7177
|
+
function ucs2Write (buf, string, offset, length) {
|
|
7178
|
+
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
|
|
7179
|
+
}
|
|
7180
|
+
|
|
7181
|
+
Buffer.prototype.write = function write (string, offset, length, encoding) {
|
|
7182
|
+
// Buffer#write(string)
|
|
7183
|
+
if (offset === undefined) {
|
|
7184
|
+
encoding = 'utf8';
|
|
7185
|
+
length = this.length;
|
|
7186
|
+
offset = 0;
|
|
7187
|
+
// Buffer#write(string, encoding)
|
|
7188
|
+
} else if (length === undefined && typeof offset === 'string') {
|
|
7189
|
+
encoding = offset;
|
|
7190
|
+
length = this.length;
|
|
7191
|
+
offset = 0;
|
|
7192
|
+
// Buffer#write(string, offset[, length][, encoding])
|
|
7193
|
+
} else if (isFinite(offset)) {
|
|
7194
|
+
offset = offset | 0;
|
|
7195
|
+
if (isFinite(length)) {
|
|
7196
|
+
length = length | 0;
|
|
7197
|
+
if (encoding === undefined) encoding = 'utf8';
|
|
7198
|
+
} else {
|
|
7199
|
+
encoding = length;
|
|
7200
|
+
length = undefined;
|
|
7201
|
+
}
|
|
7202
|
+
// legacy write(string, encoding, offset, length) - remove in v0.13
|
|
7203
|
+
} else {
|
|
7204
|
+
throw new Error(
|
|
7205
|
+
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
|
|
7206
|
+
)
|
|
7207
|
+
}
|
|
7208
|
+
|
|
7209
|
+
var remaining = this.length - offset;
|
|
7210
|
+
if (length === undefined || length > remaining) length = remaining;
|
|
7211
|
+
|
|
7212
|
+
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
|
|
7213
|
+
throw new RangeError('Attempt to write outside buffer bounds')
|
|
7214
|
+
}
|
|
7215
|
+
|
|
7216
|
+
if (!encoding) encoding = 'utf8';
|
|
7217
|
+
|
|
7218
|
+
var loweredCase = false;
|
|
7219
|
+
for (;;) {
|
|
7220
|
+
switch (encoding) {
|
|
7221
|
+
case 'hex':
|
|
7222
|
+
return hexWrite(this, string, offset, length)
|
|
7223
|
+
|
|
7224
|
+
case 'utf8':
|
|
7225
|
+
case 'utf-8':
|
|
7226
|
+
return utf8Write(this, string, offset, length)
|
|
7227
|
+
|
|
7228
|
+
case 'ascii':
|
|
7229
|
+
return asciiWrite(this, string, offset, length)
|
|
7230
|
+
|
|
7231
|
+
case 'latin1':
|
|
7232
|
+
case 'binary':
|
|
7233
|
+
return latin1Write(this, string, offset, length)
|
|
7234
|
+
|
|
7235
|
+
case 'base64':
|
|
7236
|
+
// Warning: maxLength not taken into account in base64Write
|
|
7237
|
+
return base64Write(this, string, offset, length)
|
|
7238
|
+
|
|
7239
|
+
case 'ucs2':
|
|
7240
|
+
case 'ucs-2':
|
|
7241
|
+
case 'utf16le':
|
|
7242
|
+
case 'utf-16le':
|
|
7243
|
+
return ucs2Write(this, string, offset, length)
|
|
7244
|
+
|
|
7245
|
+
default:
|
|
7246
|
+
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
|
|
7247
|
+
encoding = ('' + encoding).toLowerCase();
|
|
7248
|
+
loweredCase = true;
|
|
7249
|
+
}
|
|
7250
|
+
}
|
|
7251
|
+
};
|
|
7252
|
+
|
|
7253
|
+
Buffer.prototype.toJSON = function toJSON () {
|
|
7254
|
+
return {
|
|
7255
|
+
type: 'Buffer',
|
|
7256
|
+
data: Array.prototype.slice.call(this._arr || this, 0)
|
|
7257
|
+
}
|
|
7258
|
+
};
|
|
7259
|
+
|
|
7260
|
+
function base64Slice (buf, start, end) {
|
|
7261
|
+
if (start === 0 && end === buf.length) {
|
|
7262
|
+
return fromByteArray(buf)
|
|
7263
|
+
} else {
|
|
7264
|
+
return fromByteArray(buf.slice(start, end))
|
|
7265
|
+
}
|
|
7266
|
+
}
|
|
7267
|
+
|
|
7268
|
+
function utf8Slice (buf, start, end) {
|
|
7269
|
+
end = Math.min(buf.length, end);
|
|
7270
|
+
var res = [];
|
|
7271
|
+
|
|
7272
|
+
var i = start;
|
|
7273
|
+
while (i < end) {
|
|
7274
|
+
var firstByte = buf[i];
|
|
7275
|
+
var codePoint = null;
|
|
7276
|
+
var bytesPerSequence = (firstByte > 0xEF) ? 4
|
|
7277
|
+
: (firstByte > 0xDF) ? 3
|
|
7278
|
+
: (firstByte > 0xBF) ? 2
|
|
7279
|
+
: 1;
|
|
7280
|
+
|
|
7281
|
+
if (i + bytesPerSequence <= end) {
|
|
7282
|
+
var secondByte, thirdByte, fourthByte, tempCodePoint;
|
|
7283
|
+
|
|
7284
|
+
switch (bytesPerSequence) {
|
|
7285
|
+
case 1:
|
|
7286
|
+
if (firstByte < 0x80) {
|
|
7287
|
+
codePoint = firstByte;
|
|
7288
|
+
}
|
|
7289
|
+
break
|
|
7290
|
+
case 2:
|
|
7291
|
+
secondByte = buf[i + 1];
|
|
7292
|
+
if ((secondByte & 0xC0) === 0x80) {
|
|
7293
|
+
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
|
|
7294
|
+
if (tempCodePoint > 0x7F) {
|
|
7295
|
+
codePoint = tempCodePoint;
|
|
7296
|
+
}
|
|
7297
|
+
}
|
|
7298
|
+
break
|
|
7299
|
+
case 3:
|
|
7300
|
+
secondByte = buf[i + 1];
|
|
7301
|
+
thirdByte = buf[i + 2];
|
|
7302
|
+
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
|
|
7303
|
+
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
|
|
7304
|
+
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
|
|
7305
|
+
codePoint = tempCodePoint;
|
|
7306
|
+
}
|
|
7307
|
+
}
|
|
7308
|
+
break
|
|
7309
|
+
case 4:
|
|
7310
|
+
secondByte = buf[i + 1];
|
|
7311
|
+
thirdByte = buf[i + 2];
|
|
7312
|
+
fourthByte = buf[i + 3];
|
|
7313
|
+
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
|
|
7314
|
+
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
|
|
7315
|
+
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
|
|
7316
|
+
codePoint = tempCodePoint;
|
|
7317
|
+
}
|
|
7318
|
+
}
|
|
7319
|
+
}
|
|
7320
|
+
}
|
|
7321
|
+
|
|
7322
|
+
if (codePoint === null) {
|
|
7323
|
+
// we did not generate a valid codePoint so insert a
|
|
7324
|
+
// replacement char (U+FFFD) and advance only 1 byte
|
|
7325
|
+
codePoint = 0xFFFD;
|
|
7326
|
+
bytesPerSequence = 1;
|
|
7327
|
+
} else if (codePoint > 0xFFFF) {
|
|
7328
|
+
// encode to utf16 (surrogate pair dance)
|
|
7329
|
+
codePoint -= 0x10000;
|
|
7330
|
+
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
|
|
7331
|
+
codePoint = 0xDC00 | codePoint & 0x3FF;
|
|
7332
|
+
}
|
|
7333
|
+
|
|
7334
|
+
res.push(codePoint);
|
|
7335
|
+
i += bytesPerSequence;
|
|
7336
|
+
}
|
|
7337
|
+
|
|
7338
|
+
return decodeCodePointsArray(res)
|
|
7339
|
+
}
|
|
7340
|
+
|
|
7341
|
+
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
|
|
7342
|
+
// the lowest limit is Chrome, with 0x10000 args.
|
|
7343
|
+
// We go 1 magnitude less, for safety
|
|
7344
|
+
var MAX_ARGUMENTS_LENGTH = 0x1000;
|
|
7345
|
+
|
|
7346
|
+
function decodeCodePointsArray (codePoints) {
|
|
7347
|
+
var len = codePoints.length;
|
|
7348
|
+
if (len <= MAX_ARGUMENTS_LENGTH) {
|
|
7349
|
+
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
|
|
7350
|
+
}
|
|
7351
|
+
|
|
7352
|
+
// Decode in chunks to avoid "call stack size exceeded".
|
|
7353
|
+
var res = '';
|
|
7354
|
+
var i = 0;
|
|
7355
|
+
while (i < len) {
|
|
7356
|
+
res += String.fromCharCode.apply(
|
|
7357
|
+
String,
|
|
7358
|
+
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
|
|
7359
|
+
);
|
|
7360
|
+
}
|
|
7361
|
+
return res
|
|
7362
|
+
}
|
|
7363
|
+
|
|
7364
|
+
function asciiSlice (buf, start, end) {
|
|
7365
|
+
var ret = '';
|
|
7366
|
+
end = Math.min(buf.length, end);
|
|
7367
|
+
|
|
7368
|
+
for (var i = start; i < end; ++i) {
|
|
7369
|
+
ret += String.fromCharCode(buf[i] & 0x7F);
|
|
7370
|
+
}
|
|
7371
|
+
return ret
|
|
7372
|
+
}
|
|
7373
|
+
|
|
7374
|
+
function latin1Slice (buf, start, end) {
|
|
7375
|
+
var ret = '';
|
|
7376
|
+
end = Math.min(buf.length, end);
|
|
7377
|
+
|
|
7378
|
+
for (var i = start; i < end; ++i) {
|
|
7379
|
+
ret += String.fromCharCode(buf[i]);
|
|
7380
|
+
}
|
|
7381
|
+
return ret
|
|
7382
|
+
}
|
|
7383
|
+
|
|
7384
|
+
function hexSlice (buf, start, end) {
|
|
7385
|
+
var len = buf.length;
|
|
7386
|
+
|
|
7387
|
+
if (!start || start < 0) start = 0;
|
|
7388
|
+
if (!end || end < 0 || end > len) end = len;
|
|
7389
|
+
|
|
7390
|
+
var out = '';
|
|
7391
|
+
for (var i = start; i < end; ++i) {
|
|
7392
|
+
out += toHex(buf[i]);
|
|
7393
|
+
}
|
|
7394
|
+
return out
|
|
7395
|
+
}
|
|
7396
|
+
|
|
7397
|
+
function utf16leSlice (buf, start, end) {
|
|
7398
|
+
var bytes = buf.slice(start, end);
|
|
7399
|
+
var res = '';
|
|
7400
|
+
for (var i = 0; i < bytes.length; i += 2) {
|
|
7401
|
+
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
|
|
7402
|
+
}
|
|
7403
|
+
return res
|
|
7404
|
+
}
|
|
7405
|
+
|
|
7406
|
+
Buffer.prototype.slice = function slice (start, end) {
|
|
7407
|
+
var len = this.length;
|
|
7408
|
+
start = ~~start;
|
|
7409
|
+
end = end === undefined ? len : ~~end;
|
|
7410
|
+
|
|
7411
|
+
if (start < 0) {
|
|
7412
|
+
start += len;
|
|
7413
|
+
if (start < 0) start = 0;
|
|
7414
|
+
} else if (start > len) {
|
|
7415
|
+
start = len;
|
|
7416
|
+
}
|
|
7417
|
+
|
|
7418
|
+
if (end < 0) {
|
|
7419
|
+
end += len;
|
|
7420
|
+
if (end < 0) end = 0;
|
|
7421
|
+
} else if (end > len) {
|
|
7422
|
+
end = len;
|
|
7423
|
+
}
|
|
7424
|
+
|
|
7425
|
+
if (end < start) end = start;
|
|
7426
|
+
|
|
7427
|
+
var newBuf;
|
|
7428
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7429
|
+
newBuf = this.subarray(start, end);
|
|
7430
|
+
newBuf.__proto__ = Buffer.prototype;
|
|
7431
|
+
} else {
|
|
7432
|
+
var sliceLen = end - start;
|
|
7433
|
+
newBuf = new Buffer(sliceLen, undefined);
|
|
7434
|
+
for (var i = 0; i < sliceLen; ++i) {
|
|
7435
|
+
newBuf[i] = this[i + start];
|
|
7436
|
+
}
|
|
7437
|
+
}
|
|
7438
|
+
|
|
7439
|
+
return newBuf
|
|
7440
|
+
};
|
|
7441
|
+
|
|
7442
|
+
/*
|
|
7443
|
+
* Need to make sure that buffer isn't trying to write out of bounds.
|
|
7444
|
+
*/
|
|
7445
|
+
function checkOffset (offset, ext, length) {
|
|
7446
|
+
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
|
|
7447
|
+
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
|
|
7448
|
+
}
|
|
7449
|
+
|
|
7450
|
+
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
|
|
7451
|
+
offset = offset | 0;
|
|
7452
|
+
byteLength = byteLength | 0;
|
|
7453
|
+
if (!noAssert) checkOffset(offset, byteLength, this.length);
|
|
7454
|
+
|
|
7455
|
+
var val = this[offset];
|
|
7456
|
+
var mul = 1;
|
|
7457
|
+
var i = 0;
|
|
7458
|
+
while (++i < byteLength && (mul *= 0x100)) {
|
|
7459
|
+
val += this[offset + i] * mul;
|
|
7460
|
+
}
|
|
7461
|
+
|
|
7462
|
+
return val
|
|
7463
|
+
};
|
|
7464
|
+
|
|
7465
|
+
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
|
|
7466
|
+
offset = offset | 0;
|
|
7467
|
+
byteLength = byteLength | 0;
|
|
7468
|
+
if (!noAssert) {
|
|
7469
|
+
checkOffset(offset, byteLength, this.length);
|
|
7470
|
+
}
|
|
7471
|
+
|
|
7472
|
+
var val = this[offset + --byteLength];
|
|
7473
|
+
var mul = 1;
|
|
7474
|
+
while (byteLength > 0 && (mul *= 0x100)) {
|
|
7475
|
+
val += this[offset + --byteLength] * mul;
|
|
7476
|
+
}
|
|
7477
|
+
|
|
7478
|
+
return val
|
|
7479
|
+
};
|
|
7480
|
+
|
|
7481
|
+
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
|
|
7482
|
+
if (!noAssert) checkOffset(offset, 1, this.length);
|
|
7483
|
+
return this[offset]
|
|
7484
|
+
};
|
|
7485
|
+
|
|
7486
|
+
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
|
|
7487
|
+
if (!noAssert) checkOffset(offset, 2, this.length);
|
|
7488
|
+
return this[offset] | (this[offset + 1] << 8)
|
|
7489
|
+
};
|
|
7490
|
+
|
|
7491
|
+
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
|
|
7492
|
+
if (!noAssert) checkOffset(offset, 2, this.length);
|
|
7493
|
+
return (this[offset] << 8) | this[offset + 1]
|
|
7494
|
+
};
|
|
7495
|
+
|
|
7496
|
+
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
|
|
7497
|
+
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
7498
|
+
|
|
7499
|
+
return ((this[offset]) |
|
|
7500
|
+
(this[offset + 1] << 8) |
|
|
7501
|
+
(this[offset + 2] << 16)) +
|
|
7502
|
+
(this[offset + 3] * 0x1000000)
|
|
7503
|
+
};
|
|
7504
|
+
|
|
7505
|
+
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
|
|
7506
|
+
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
7507
|
+
|
|
7508
|
+
return (this[offset] * 0x1000000) +
|
|
7509
|
+
((this[offset + 1] << 16) |
|
|
7510
|
+
(this[offset + 2] << 8) |
|
|
7511
|
+
this[offset + 3])
|
|
7512
|
+
};
|
|
7513
|
+
|
|
7514
|
+
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
|
|
7515
|
+
offset = offset | 0;
|
|
7516
|
+
byteLength = byteLength | 0;
|
|
7517
|
+
if (!noAssert) checkOffset(offset, byteLength, this.length);
|
|
7518
|
+
|
|
7519
|
+
var val = this[offset];
|
|
7520
|
+
var mul = 1;
|
|
7521
|
+
var i = 0;
|
|
7522
|
+
while (++i < byteLength && (mul *= 0x100)) {
|
|
7523
|
+
val += this[offset + i] * mul;
|
|
7524
|
+
}
|
|
7525
|
+
mul *= 0x80;
|
|
7526
|
+
|
|
7527
|
+
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
|
|
7528
|
+
|
|
7529
|
+
return val
|
|
7530
|
+
};
|
|
7531
|
+
|
|
7532
|
+
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
|
|
7533
|
+
offset = offset | 0;
|
|
7534
|
+
byteLength = byteLength | 0;
|
|
7535
|
+
if (!noAssert) checkOffset(offset, byteLength, this.length);
|
|
7536
|
+
|
|
7537
|
+
var i = byteLength;
|
|
7538
|
+
var mul = 1;
|
|
7539
|
+
var val = this[offset + --i];
|
|
7540
|
+
while (i > 0 && (mul *= 0x100)) {
|
|
7541
|
+
val += this[offset + --i] * mul;
|
|
7542
|
+
}
|
|
7543
|
+
mul *= 0x80;
|
|
7544
|
+
|
|
7545
|
+
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
|
|
7546
|
+
|
|
7547
|
+
return val
|
|
7548
|
+
};
|
|
7549
|
+
|
|
7550
|
+
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
|
|
7551
|
+
if (!noAssert) checkOffset(offset, 1, this.length);
|
|
7552
|
+
if (!(this[offset] & 0x80)) return (this[offset])
|
|
7553
|
+
return ((0xff - this[offset] + 1) * -1)
|
|
7554
|
+
};
|
|
7555
|
+
|
|
7556
|
+
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
|
|
7557
|
+
if (!noAssert) checkOffset(offset, 2, this.length);
|
|
7558
|
+
var val = this[offset] | (this[offset + 1] << 8);
|
|
7559
|
+
return (val & 0x8000) ? val | 0xFFFF0000 : val
|
|
7560
|
+
};
|
|
7561
|
+
|
|
7562
|
+
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
|
|
7563
|
+
if (!noAssert) checkOffset(offset, 2, this.length);
|
|
7564
|
+
var val = this[offset + 1] | (this[offset] << 8);
|
|
7565
|
+
return (val & 0x8000) ? val | 0xFFFF0000 : val
|
|
7566
|
+
};
|
|
7567
|
+
|
|
7568
|
+
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
|
|
7569
|
+
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
7570
|
+
|
|
7571
|
+
return (this[offset]) |
|
|
7572
|
+
(this[offset + 1] << 8) |
|
|
7573
|
+
(this[offset + 2] << 16) |
|
|
7574
|
+
(this[offset + 3] << 24)
|
|
7575
|
+
};
|
|
7576
|
+
|
|
7577
|
+
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
|
|
7578
|
+
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
7579
|
+
|
|
7580
|
+
return (this[offset] << 24) |
|
|
7581
|
+
(this[offset + 1] << 16) |
|
|
7582
|
+
(this[offset + 2] << 8) |
|
|
7583
|
+
(this[offset + 3])
|
|
7584
|
+
};
|
|
7585
|
+
|
|
7586
|
+
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
|
|
7587
|
+
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
7588
|
+
return read(this, offset, true, 23, 4)
|
|
7589
|
+
};
|
|
7590
|
+
|
|
7591
|
+
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
|
|
7592
|
+
if (!noAssert) checkOffset(offset, 4, this.length);
|
|
7593
|
+
return read(this, offset, false, 23, 4)
|
|
7594
|
+
};
|
|
7595
|
+
|
|
7596
|
+
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
|
|
7597
|
+
if (!noAssert) checkOffset(offset, 8, this.length);
|
|
7598
|
+
return read(this, offset, true, 52, 8)
|
|
7599
|
+
};
|
|
7600
|
+
|
|
7601
|
+
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
|
|
7602
|
+
if (!noAssert) checkOffset(offset, 8, this.length);
|
|
7603
|
+
return read(this, offset, false, 52, 8)
|
|
7604
|
+
};
|
|
7605
|
+
|
|
7606
|
+
function checkInt (buf, value, offset, ext, max, min) {
|
|
7607
|
+
if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
|
|
7608
|
+
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
|
|
7609
|
+
if (offset + ext > buf.length) throw new RangeError('Index out of range')
|
|
7610
|
+
}
|
|
7611
|
+
|
|
7612
|
+
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
|
|
7613
|
+
value = +value;
|
|
7614
|
+
offset = offset | 0;
|
|
7615
|
+
byteLength = byteLength | 0;
|
|
7616
|
+
if (!noAssert) {
|
|
7617
|
+
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
|
|
7618
|
+
checkInt(this, value, offset, byteLength, maxBytes, 0);
|
|
7619
|
+
}
|
|
7620
|
+
|
|
7621
|
+
var mul = 1;
|
|
7622
|
+
var i = 0;
|
|
7623
|
+
this[offset] = value & 0xFF;
|
|
7624
|
+
while (++i < byteLength && (mul *= 0x100)) {
|
|
7625
|
+
this[offset + i] = (value / mul) & 0xFF;
|
|
7626
|
+
}
|
|
7627
|
+
|
|
7628
|
+
return offset + byteLength
|
|
7629
|
+
};
|
|
7630
|
+
|
|
7631
|
+
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
|
|
7632
|
+
value = +value;
|
|
7633
|
+
offset = offset | 0;
|
|
7634
|
+
byteLength = byteLength | 0;
|
|
7635
|
+
if (!noAssert) {
|
|
7636
|
+
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
|
|
7637
|
+
checkInt(this, value, offset, byteLength, maxBytes, 0);
|
|
7638
|
+
}
|
|
7639
|
+
|
|
7640
|
+
var i = byteLength - 1;
|
|
7641
|
+
var mul = 1;
|
|
7642
|
+
this[offset + i] = value & 0xFF;
|
|
7643
|
+
while (--i >= 0 && (mul *= 0x100)) {
|
|
7644
|
+
this[offset + i] = (value / mul) & 0xFF;
|
|
7645
|
+
}
|
|
7646
|
+
|
|
7647
|
+
return offset + byteLength
|
|
7648
|
+
};
|
|
7649
|
+
|
|
7650
|
+
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
|
|
7651
|
+
value = +value;
|
|
7652
|
+
offset = offset | 0;
|
|
7653
|
+
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
|
|
7654
|
+
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
|
|
7655
|
+
this[offset] = (value & 0xff);
|
|
7656
|
+
return offset + 1
|
|
7657
|
+
};
|
|
7658
|
+
|
|
7659
|
+
function objectWriteUInt16 (buf, value, offset, littleEndian) {
|
|
7660
|
+
if (value < 0) value = 0xffff + value + 1;
|
|
7661
|
+
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
|
|
7662
|
+
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
|
|
7663
|
+
(littleEndian ? i : 1 - i) * 8;
|
|
7664
|
+
}
|
|
7665
|
+
}
|
|
7666
|
+
|
|
7667
|
+
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
|
|
7668
|
+
value = +value;
|
|
7669
|
+
offset = offset | 0;
|
|
7670
|
+
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
|
|
7671
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7672
|
+
this[offset] = (value & 0xff);
|
|
7673
|
+
this[offset + 1] = (value >>> 8);
|
|
7674
|
+
} else {
|
|
7675
|
+
objectWriteUInt16(this, value, offset, true);
|
|
7676
|
+
}
|
|
7677
|
+
return offset + 2
|
|
7678
|
+
};
|
|
7679
|
+
|
|
7680
|
+
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
|
|
7681
|
+
value = +value;
|
|
7682
|
+
offset = offset | 0;
|
|
7683
|
+
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
|
|
7684
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7685
|
+
this[offset] = (value >>> 8);
|
|
7686
|
+
this[offset + 1] = (value & 0xff);
|
|
7687
|
+
} else {
|
|
7688
|
+
objectWriteUInt16(this, value, offset, false);
|
|
7689
|
+
}
|
|
7690
|
+
return offset + 2
|
|
7691
|
+
};
|
|
7692
|
+
|
|
7693
|
+
function objectWriteUInt32 (buf, value, offset, littleEndian) {
|
|
7694
|
+
if (value < 0) value = 0xffffffff + value + 1;
|
|
7695
|
+
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
|
|
7696
|
+
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
|
|
7697
|
+
}
|
|
7698
|
+
}
|
|
7699
|
+
|
|
7700
|
+
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
|
|
7701
|
+
value = +value;
|
|
7702
|
+
offset = offset | 0;
|
|
7703
|
+
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
|
|
7704
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7705
|
+
this[offset + 3] = (value >>> 24);
|
|
7706
|
+
this[offset + 2] = (value >>> 16);
|
|
7707
|
+
this[offset + 1] = (value >>> 8);
|
|
7708
|
+
this[offset] = (value & 0xff);
|
|
7709
|
+
} else {
|
|
7710
|
+
objectWriteUInt32(this, value, offset, true);
|
|
7711
|
+
}
|
|
7712
|
+
return offset + 4
|
|
7713
|
+
};
|
|
7714
|
+
|
|
7715
|
+
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
|
|
7716
|
+
value = +value;
|
|
7717
|
+
offset = offset | 0;
|
|
7718
|
+
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
|
|
7719
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7720
|
+
this[offset] = (value >>> 24);
|
|
7721
|
+
this[offset + 1] = (value >>> 16);
|
|
7722
|
+
this[offset + 2] = (value >>> 8);
|
|
7723
|
+
this[offset + 3] = (value & 0xff);
|
|
7724
|
+
} else {
|
|
7725
|
+
objectWriteUInt32(this, value, offset, false);
|
|
7726
|
+
}
|
|
7727
|
+
return offset + 4
|
|
7728
|
+
};
|
|
7729
|
+
|
|
7730
|
+
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
|
|
7731
|
+
value = +value;
|
|
7732
|
+
offset = offset | 0;
|
|
7733
|
+
if (!noAssert) {
|
|
7734
|
+
var limit = Math.pow(2, 8 * byteLength - 1);
|
|
7735
|
+
|
|
7736
|
+
checkInt(this, value, offset, byteLength, limit - 1, -limit);
|
|
7737
|
+
}
|
|
7738
|
+
|
|
7739
|
+
var i = 0;
|
|
7740
|
+
var mul = 1;
|
|
7741
|
+
var sub = 0;
|
|
7742
|
+
this[offset] = value & 0xFF;
|
|
7743
|
+
while (++i < byteLength && (mul *= 0x100)) {
|
|
7744
|
+
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
|
|
7745
|
+
sub = 1;
|
|
7746
|
+
}
|
|
7747
|
+
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
|
|
7748
|
+
}
|
|
7749
|
+
|
|
7750
|
+
return offset + byteLength
|
|
7751
|
+
};
|
|
7752
|
+
|
|
7753
|
+
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
|
|
7754
|
+
value = +value;
|
|
7755
|
+
offset = offset | 0;
|
|
7756
|
+
if (!noAssert) {
|
|
7757
|
+
var limit = Math.pow(2, 8 * byteLength - 1);
|
|
7758
|
+
|
|
7759
|
+
checkInt(this, value, offset, byteLength, limit - 1, -limit);
|
|
7760
|
+
}
|
|
7761
|
+
|
|
7762
|
+
var i = byteLength - 1;
|
|
7763
|
+
var mul = 1;
|
|
7764
|
+
var sub = 0;
|
|
7765
|
+
this[offset + i] = value & 0xFF;
|
|
7766
|
+
while (--i >= 0 && (mul *= 0x100)) {
|
|
7767
|
+
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
|
|
7768
|
+
sub = 1;
|
|
7769
|
+
}
|
|
7770
|
+
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
|
|
7771
|
+
}
|
|
7772
|
+
|
|
7773
|
+
return offset + byteLength
|
|
7774
|
+
};
|
|
7775
|
+
|
|
7776
|
+
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
|
|
7777
|
+
value = +value;
|
|
7778
|
+
offset = offset | 0;
|
|
7779
|
+
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
|
|
7780
|
+
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
|
|
7781
|
+
if (value < 0) value = 0xff + value + 1;
|
|
7782
|
+
this[offset] = (value & 0xff);
|
|
7783
|
+
return offset + 1
|
|
7784
|
+
};
|
|
7785
|
+
|
|
7786
|
+
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
|
|
7787
|
+
value = +value;
|
|
7788
|
+
offset = offset | 0;
|
|
7789
|
+
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
|
|
7790
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7791
|
+
this[offset] = (value & 0xff);
|
|
7792
|
+
this[offset + 1] = (value >>> 8);
|
|
7793
|
+
} else {
|
|
7794
|
+
objectWriteUInt16(this, value, offset, true);
|
|
7795
|
+
}
|
|
7796
|
+
return offset + 2
|
|
7797
|
+
};
|
|
7798
|
+
|
|
7799
|
+
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
|
|
7800
|
+
value = +value;
|
|
7801
|
+
offset = offset | 0;
|
|
7802
|
+
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
|
|
7803
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7804
|
+
this[offset] = (value >>> 8);
|
|
7805
|
+
this[offset + 1] = (value & 0xff);
|
|
7806
|
+
} else {
|
|
7807
|
+
objectWriteUInt16(this, value, offset, false);
|
|
7808
|
+
}
|
|
7809
|
+
return offset + 2
|
|
7810
|
+
};
|
|
7811
|
+
|
|
7812
|
+
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
|
|
7813
|
+
value = +value;
|
|
7814
|
+
offset = offset | 0;
|
|
7815
|
+
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
|
|
7816
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7817
|
+
this[offset] = (value & 0xff);
|
|
7818
|
+
this[offset + 1] = (value >>> 8);
|
|
7819
|
+
this[offset + 2] = (value >>> 16);
|
|
7820
|
+
this[offset + 3] = (value >>> 24);
|
|
7821
|
+
} else {
|
|
7822
|
+
objectWriteUInt32(this, value, offset, true);
|
|
7823
|
+
}
|
|
7824
|
+
return offset + 4
|
|
7825
|
+
};
|
|
7826
|
+
|
|
7827
|
+
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
|
|
7828
|
+
value = +value;
|
|
7829
|
+
offset = offset | 0;
|
|
7830
|
+
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
|
|
7831
|
+
if (value < 0) value = 0xffffffff + value + 1;
|
|
7832
|
+
if (Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7833
|
+
this[offset] = (value >>> 24);
|
|
7834
|
+
this[offset + 1] = (value >>> 16);
|
|
7835
|
+
this[offset + 2] = (value >>> 8);
|
|
7836
|
+
this[offset + 3] = (value & 0xff);
|
|
7837
|
+
} else {
|
|
7838
|
+
objectWriteUInt32(this, value, offset, false);
|
|
7839
|
+
}
|
|
7840
|
+
return offset + 4
|
|
7841
|
+
};
|
|
7842
|
+
|
|
7843
|
+
function checkIEEE754 (buf, value, offset, ext, max, min) {
|
|
7844
|
+
if (offset + ext > buf.length) throw new RangeError('Index out of range')
|
|
7845
|
+
if (offset < 0) throw new RangeError('Index out of range')
|
|
7846
|
+
}
|
|
7847
|
+
|
|
7848
|
+
function writeFloat (buf, value, offset, littleEndian, noAssert) {
|
|
7849
|
+
if (!noAssert) {
|
|
7850
|
+
checkIEEE754(buf, value, offset, 4);
|
|
7851
|
+
}
|
|
7852
|
+
write(buf, value, offset, littleEndian, 23, 4);
|
|
7853
|
+
return offset + 4
|
|
7854
|
+
}
|
|
7855
|
+
|
|
7856
|
+
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
|
|
7857
|
+
return writeFloat(this, value, offset, true, noAssert)
|
|
7858
|
+
};
|
|
7859
|
+
|
|
7860
|
+
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
|
|
7861
|
+
return writeFloat(this, value, offset, false, noAssert)
|
|
7862
|
+
};
|
|
7863
|
+
|
|
7864
|
+
function writeDouble (buf, value, offset, littleEndian, noAssert) {
|
|
7865
|
+
if (!noAssert) {
|
|
7866
|
+
checkIEEE754(buf, value, offset, 8);
|
|
7867
|
+
}
|
|
7868
|
+
write(buf, value, offset, littleEndian, 52, 8);
|
|
7869
|
+
return offset + 8
|
|
7870
|
+
}
|
|
7871
|
+
|
|
7872
|
+
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
|
|
7873
|
+
return writeDouble(this, value, offset, true, noAssert)
|
|
7874
|
+
};
|
|
7875
|
+
|
|
7876
|
+
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
|
|
7877
|
+
return writeDouble(this, value, offset, false, noAssert)
|
|
7878
|
+
};
|
|
7879
|
+
|
|
7880
|
+
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
|
|
7881
|
+
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
|
|
7882
|
+
if (!start) start = 0;
|
|
7883
|
+
if (!end && end !== 0) end = this.length;
|
|
7884
|
+
if (targetStart >= target.length) targetStart = target.length;
|
|
7885
|
+
if (!targetStart) targetStart = 0;
|
|
7886
|
+
if (end > 0 && end < start) end = start;
|
|
7887
|
+
|
|
7888
|
+
// Copy 0 bytes; we're done
|
|
7889
|
+
if (end === start) return 0
|
|
7890
|
+
if (target.length === 0 || this.length === 0) return 0
|
|
7891
|
+
|
|
7892
|
+
// Fatal error conditions
|
|
7893
|
+
if (targetStart < 0) {
|
|
7894
|
+
throw new RangeError('targetStart out of bounds')
|
|
7895
|
+
}
|
|
7896
|
+
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
|
|
7897
|
+
if (end < 0) throw new RangeError('sourceEnd out of bounds')
|
|
7898
|
+
|
|
7899
|
+
// Are we oob?
|
|
7900
|
+
if (end > this.length) end = this.length;
|
|
7901
|
+
if (target.length - targetStart < end - start) {
|
|
7902
|
+
end = target.length - targetStart + start;
|
|
7903
|
+
}
|
|
7904
|
+
|
|
7905
|
+
var len = end - start;
|
|
7906
|
+
var i;
|
|
7907
|
+
|
|
7908
|
+
if (this === target && start < targetStart && targetStart < end) {
|
|
7909
|
+
// descending copy from end
|
|
7910
|
+
for (i = len - 1; i >= 0; --i) {
|
|
7911
|
+
target[i + targetStart] = this[i + start];
|
|
7912
|
+
}
|
|
7913
|
+
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
|
|
7914
|
+
// ascending copy from start
|
|
7915
|
+
for (i = 0; i < len; ++i) {
|
|
7916
|
+
target[i + targetStart] = this[i + start];
|
|
7917
|
+
}
|
|
7918
|
+
} else {
|
|
7919
|
+
Uint8Array.prototype.set.call(
|
|
7920
|
+
target,
|
|
7921
|
+
this.subarray(start, start + len),
|
|
7922
|
+
targetStart
|
|
7923
|
+
);
|
|
7924
|
+
}
|
|
7925
|
+
|
|
7926
|
+
return len
|
|
7927
|
+
};
|
|
7928
|
+
|
|
7929
|
+
// Usage:
|
|
7930
|
+
// buffer.fill(number[, offset[, end]])
|
|
7931
|
+
// buffer.fill(buffer[, offset[, end]])
|
|
7932
|
+
// buffer.fill(string[, offset[, end]][, encoding])
|
|
7933
|
+
Buffer.prototype.fill = function fill (val, start, end, encoding) {
|
|
7934
|
+
// Handle string cases:
|
|
7935
|
+
if (typeof val === 'string') {
|
|
7936
|
+
if (typeof start === 'string') {
|
|
7937
|
+
encoding = start;
|
|
7938
|
+
start = 0;
|
|
7939
|
+
end = this.length;
|
|
7940
|
+
} else if (typeof end === 'string') {
|
|
7941
|
+
encoding = end;
|
|
7942
|
+
end = this.length;
|
|
7943
|
+
}
|
|
7944
|
+
if (val.length === 1) {
|
|
7945
|
+
var code = val.charCodeAt(0);
|
|
7946
|
+
if (code < 256) {
|
|
7947
|
+
val = code;
|
|
7948
|
+
}
|
|
7949
|
+
}
|
|
7950
|
+
if (encoding !== undefined && typeof encoding !== 'string') {
|
|
7951
|
+
throw new TypeError('encoding must be a string')
|
|
7952
|
+
}
|
|
7953
|
+
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
|
|
7954
|
+
throw new TypeError('Unknown encoding: ' + encoding)
|
|
7955
|
+
}
|
|
7956
|
+
} else if (typeof val === 'number') {
|
|
7957
|
+
val = val & 255;
|
|
7958
|
+
}
|
|
7959
|
+
|
|
7960
|
+
// Invalid ranges are not set to a default, so can range check early.
|
|
7961
|
+
if (start < 0 || this.length < start || this.length < end) {
|
|
7962
|
+
throw new RangeError('Out of range index')
|
|
7963
|
+
}
|
|
7964
|
+
|
|
7965
|
+
if (end <= start) {
|
|
7966
|
+
return this
|
|
7967
|
+
}
|
|
7968
|
+
|
|
7969
|
+
start = start >>> 0;
|
|
7970
|
+
end = end === undefined ? this.length : end >>> 0;
|
|
7971
|
+
|
|
7972
|
+
if (!val) val = 0;
|
|
7973
|
+
|
|
7974
|
+
var i;
|
|
7975
|
+
if (typeof val === 'number') {
|
|
7976
|
+
for (i = start; i < end; ++i) {
|
|
7977
|
+
this[i] = val;
|
|
7978
|
+
}
|
|
7979
|
+
} else {
|
|
7980
|
+
var bytes = internalIsBuffer(val)
|
|
7981
|
+
? val
|
|
7982
|
+
: utf8ToBytes(new Buffer(val, encoding).toString());
|
|
7983
|
+
var len = bytes.length;
|
|
7984
|
+
for (i = 0; i < end - start; ++i) {
|
|
7985
|
+
this[i + start] = bytes[i % len];
|
|
7986
|
+
}
|
|
7987
|
+
}
|
|
7988
|
+
|
|
7989
|
+
return this
|
|
7990
|
+
};
|
|
7991
|
+
|
|
7992
|
+
// HELPER FUNCTIONS
|
|
7993
|
+
// ================
|
|
7994
|
+
|
|
7995
|
+
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
|
|
7996
|
+
|
|
7997
|
+
function base64clean (str) {
|
|
7998
|
+
// Node strips out invalid characters like \n and \t from the string, base64-js does not
|
|
7999
|
+
str = stringtrim(str).replace(INVALID_BASE64_RE, '');
|
|
8000
|
+
// Node converts strings with length < 2 to ''
|
|
8001
|
+
if (str.length < 2) return ''
|
|
8002
|
+
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
|
|
8003
|
+
while (str.length % 4 !== 0) {
|
|
8004
|
+
str = str + '=';
|
|
8005
|
+
}
|
|
8006
|
+
return str
|
|
8007
|
+
}
|
|
8008
|
+
|
|
8009
|
+
function stringtrim (str) {
|
|
8010
|
+
if (str.trim) return str.trim()
|
|
8011
|
+
return str.replace(/^\s+|\s+$/g, '')
|
|
8012
|
+
}
|
|
8013
|
+
|
|
8014
|
+
function toHex (n) {
|
|
8015
|
+
if (n < 16) return '0' + n.toString(16)
|
|
8016
|
+
return n.toString(16)
|
|
8017
|
+
}
|
|
8018
|
+
|
|
8019
|
+
function utf8ToBytes (string, units) {
|
|
8020
|
+
units = units || Infinity;
|
|
8021
|
+
var codePoint;
|
|
8022
|
+
var length = string.length;
|
|
8023
|
+
var leadSurrogate = null;
|
|
8024
|
+
var bytes = [];
|
|
8025
|
+
|
|
8026
|
+
for (var i = 0; i < length; ++i) {
|
|
8027
|
+
codePoint = string.charCodeAt(i);
|
|
8028
|
+
|
|
8029
|
+
// is surrogate component
|
|
8030
|
+
if (codePoint > 0xD7FF && codePoint < 0xE000) {
|
|
8031
|
+
// last char was a lead
|
|
8032
|
+
if (!leadSurrogate) {
|
|
8033
|
+
// no lead yet
|
|
8034
|
+
if (codePoint > 0xDBFF) {
|
|
8035
|
+
// unexpected trail
|
|
8036
|
+
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
|
|
8037
|
+
continue
|
|
8038
|
+
} else if (i + 1 === length) {
|
|
8039
|
+
// unpaired lead
|
|
8040
|
+
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
|
|
8041
|
+
continue
|
|
8042
|
+
}
|
|
8043
|
+
|
|
8044
|
+
// valid lead
|
|
8045
|
+
leadSurrogate = codePoint;
|
|
8046
|
+
|
|
8047
|
+
continue
|
|
8048
|
+
}
|
|
8049
|
+
|
|
8050
|
+
// 2 leads in a row
|
|
8051
|
+
if (codePoint < 0xDC00) {
|
|
8052
|
+
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
|
|
8053
|
+
leadSurrogate = codePoint;
|
|
8054
|
+
continue
|
|
8055
|
+
}
|
|
8056
|
+
|
|
8057
|
+
// valid surrogate pair
|
|
8058
|
+
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
|
|
8059
|
+
} else if (leadSurrogate) {
|
|
8060
|
+
// valid bmp char, but last char was a lead
|
|
8061
|
+
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
|
|
8062
|
+
}
|
|
8063
|
+
|
|
8064
|
+
leadSurrogate = null;
|
|
8065
|
+
|
|
8066
|
+
// encode utf8
|
|
8067
|
+
if (codePoint < 0x80) {
|
|
8068
|
+
if ((units -= 1) < 0) break
|
|
8069
|
+
bytes.push(codePoint);
|
|
8070
|
+
} else if (codePoint < 0x800) {
|
|
8071
|
+
if ((units -= 2) < 0) break
|
|
8072
|
+
bytes.push(
|
|
8073
|
+
codePoint >> 0x6 | 0xC0,
|
|
8074
|
+
codePoint & 0x3F | 0x80
|
|
8075
|
+
);
|
|
8076
|
+
} else if (codePoint < 0x10000) {
|
|
8077
|
+
if ((units -= 3) < 0) break
|
|
8078
|
+
bytes.push(
|
|
8079
|
+
codePoint >> 0xC | 0xE0,
|
|
8080
|
+
codePoint >> 0x6 & 0x3F | 0x80,
|
|
8081
|
+
codePoint & 0x3F | 0x80
|
|
8082
|
+
);
|
|
8083
|
+
} else if (codePoint < 0x110000) {
|
|
8084
|
+
if ((units -= 4) < 0) break
|
|
8085
|
+
bytes.push(
|
|
8086
|
+
codePoint >> 0x12 | 0xF0,
|
|
8087
|
+
codePoint >> 0xC & 0x3F | 0x80,
|
|
8088
|
+
codePoint >> 0x6 & 0x3F | 0x80,
|
|
8089
|
+
codePoint & 0x3F | 0x80
|
|
8090
|
+
);
|
|
8091
|
+
} else {
|
|
8092
|
+
throw new Error('Invalid code point')
|
|
8093
|
+
}
|
|
8094
|
+
}
|
|
8095
|
+
|
|
8096
|
+
return bytes
|
|
8097
|
+
}
|
|
8098
|
+
|
|
8099
|
+
function asciiToBytes (str) {
|
|
8100
|
+
var byteArray = [];
|
|
8101
|
+
for (var i = 0; i < str.length; ++i) {
|
|
8102
|
+
// Node's code seems to be doing this and not & 0x7F..
|
|
8103
|
+
byteArray.push(str.charCodeAt(i) & 0xFF);
|
|
8104
|
+
}
|
|
8105
|
+
return byteArray
|
|
8106
|
+
}
|
|
8107
|
+
|
|
8108
|
+
function utf16leToBytes (str, units) {
|
|
8109
|
+
var c, hi, lo;
|
|
8110
|
+
var byteArray = [];
|
|
8111
|
+
for (var i = 0; i < str.length; ++i) {
|
|
8112
|
+
if ((units -= 2) < 0) break
|
|
8113
|
+
|
|
8114
|
+
c = str.charCodeAt(i);
|
|
8115
|
+
hi = c >> 8;
|
|
8116
|
+
lo = c % 256;
|
|
8117
|
+
byteArray.push(lo);
|
|
8118
|
+
byteArray.push(hi);
|
|
8119
|
+
}
|
|
8120
|
+
|
|
8121
|
+
return byteArray
|
|
8122
|
+
}
|
|
8123
|
+
|
|
8124
|
+
|
|
8125
|
+
function base64ToBytes (str) {
|
|
8126
|
+
return toByteArray(base64clean(str))
|
|
8127
|
+
}
|
|
8128
|
+
|
|
8129
|
+
function blitBuffer (src, dst, offset, length) {
|
|
8130
|
+
for (var i = 0; i < length; ++i) {
|
|
8131
|
+
if ((i + offset >= dst.length) || (i >= src.length)) break
|
|
8132
|
+
dst[i + offset] = src[i];
|
|
8133
|
+
}
|
|
8134
|
+
return i
|
|
8135
|
+
}
|
|
8136
|
+
|
|
8137
|
+
function isnan (val) {
|
|
8138
|
+
return val !== val // eslint-disable-line no-self-compare
|
|
8139
|
+
}
|
|
8140
|
+
|
|
8141
|
+
|
|
8142
|
+
// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
|
|
8143
|
+
// The _isBuffer check is for Safari 5-7 support, because it's missing
|
|
8144
|
+
// Object.prototype.constructor. Remove this eventually
|
|
8145
|
+
function isBuffer(obj) {
|
|
8146
|
+
return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
|
|
8147
|
+
}
|
|
8148
|
+
|
|
8149
|
+
function isFastBuffer (obj) {
|
|
8150
|
+
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
|
|
8151
|
+
}
|
|
8152
|
+
|
|
8153
|
+
// For Node v0.10 support. Remove this eventually.
|
|
8154
|
+
function isSlowBuffer (obj) {
|
|
8155
|
+
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
|
|
8156
|
+
}
|
|
8157
|
+
|
|
6191
8158
|
/**
|
|
6192
8159
|
* Convert a data object to FormData
|
|
6193
8160
|
* @param {Object} obj
|
|
@@ -6736,7 +8703,7 @@ function getDefaultAdapter() {
|
|
|
6736
8703
|
if (typeof XMLHttpRequest !== 'undefined') {
|
|
6737
8704
|
// For browsers use XHR adapter
|
|
6738
8705
|
adapter = xhr;
|
|
6739
|
-
} else if (typeof
|
|
8706
|
+
} else if (typeof _commonjsHelpers.browser$1 !== 'undefined' && Object.prototype.toString.call(_commonjsHelpers.browser$1) === '[object process]') {
|
|
6740
8707
|
// For node use HTTP adapter
|
|
6741
8708
|
adapter = xhr;
|
|
6742
8709
|
}
|
|
@@ -7513,7 +9480,7 @@ var axios = axios_1;
|
|
|
7513
9480
|
|
|
7514
9481
|
function e(e){this.message=e;}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r$1="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw "Illegal base64url string!"}try{return function(e){return decodeURIComponent(r$1(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r$1(t)}}function n$1(e){this.message=e;}function o$1(e,r){if("string"!=typeof e)throw new n$1("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n$1("Invalid token specified: "+e.message)}}n$1.prototype=new Error,n$1.prototype.name="InvalidTokenError";
|
|
7515
9482
|
|
|
7516
|
-
let r=function(e,t,a){return alert(e)},n=function(e,t){return r(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return r(e,t,a)},setNotifier:function(e){r=e,salla.event.emit("twilight::notifier.changed");},error:n,success:function(e,t){return r(e,l.success,t)},info:function(e,t){return r(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=>{n(decodeURI(e.replace("?danger=","").replace("&danger=","")));}));})));},types:l};class d{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,s){return "event"===s?t:"api"===s?e:e&&e[s]||a[s]}})}}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 s=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(s="FORM"===this.tagName?this:s||this.closest("form")||this.closest("[salla-form-data]")||this,s&&"FORM"===s.tagName)return this.getFilteredData(new FormData(s),null,s);let i=s.querySelectorAll("[name]");if(!i.length)return this.getFilteredData();let r=Object.assign({},this.dataset);return i.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,r);r[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(r)},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 s=this.attributes[a].name.toLowerCase();if(0===s.indexOf(e))return !t||s}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((s=>{let i=a?.dataset[s]||this.dataset[s];if(i){var r=window[i];if("function"==typeof r){if(!r(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${i}(formData, element, event)!`;return r(e,a||this,t)}Salla.log("window."+i+"() 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 c{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){return Salla.event.addListener(this.getEventName(e),t)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function u(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0);}Salla.event.auth=new class extends c{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"},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 c{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",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 c{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"},this.after_init();}},Salla.event.scope=new class extends c{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 c{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 c{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.comment=new class extends c{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.landing=new class extends c{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed"},this.after_init();}},Salla.event.loyalty=new class extends c{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 c{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"},this.after_init();}},Salla.event.profile=new class extends c{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 c{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 c{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,...s){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...s)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const i=new CustomEvent(t,...s);return e.dispatchEvent(i)}},Salla.event.wishlist=new class extends c{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 c{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.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(u(e),Object.keys(e).forEach((t=>{u(e[t]);})));}));})),Salla.config.default_properties={debug:"undefined"!=typeof process&&"development"==="production",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 h{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,a=null){let s=Array.isArray(e),i=s?this.getUrl(...e):this.getUrl(e);e=s?e[0]:e,a=a||this.endpointsMethods[e]||"post";let r=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 r&&"get"===a&&(t=t?Object.assign(t,r):r),this.webEndpoints.includes(e)?i=salla.url.get(i):"http"!==i.substring(0,4)&&(i=salla.url.api(i)),Salla.api.request(i,t,a,{headers:r})}request(e,t,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 p extends h{constructor(){super(),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"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>this.getCurrentCartId()));}async getCurrentCartId(){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e;let t=await this.latest();return salla.cart.api.latestCart=t.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(){return this.request("latest",{params:{source:""}}).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 this.getCurrentCartId(),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 s=await this.getCurrentCartId();return this.request([a,s,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}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 this.getCurrentCartId();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 this.getCurrentCartId();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 this.getCurrentCartId();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){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit();}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload();})).catch((function(e){throw 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,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.cart.api.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();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();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 this.getCurrentCartId()]).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}))))}}class g extends h{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())){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())){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 f extends h{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.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 s=await salla.auth.api.request(["verify",a],e);if(200!==s?.status)return salla.auth.event.verificationFailed(s,a),salla.api.errorPromise(s);let i="authenticated"===s.data?.case;return i&&salla.auth.event.tokenFetched(s.data.token),t&&await salla.auth.api.request("auth/jwt"),i&&salla.auth.event.loggedIn(s).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(s,a),salla.api.successPromise(s)}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 function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),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}))}logout(){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut().then((()=>{let e=salla.url.get("logout");console.log(`Going to ${e}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=e;}catch(e){salla.log(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 m extends h{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"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:!!window.ApplePaySession}}).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}))}}class v extends h{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"},this.endpointsMethods={details:"get",giftDetail:"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.availabilitySubscribedFailed(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}))}}class y extends h{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 w extends h{constructor(){super(),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init();}add(e){e?.data&&(e=e.data);let t,a=salla.form.getPossibleValue(e,["id"]),s=salla.form.getPossibleValue(e,["type"]),i=salla.form.getPossibleValue(e,["comment"]);return a?s&&["products","pages","product","page"].includes(s)?i?(s+=["product","page"].includes(s)?"s":"",this.request(["add",s,a],{comment:i}).then((function(e){return salla.event.comment.added(e,a),e})).catch((function(e){throw salla.event.comment.additionFailed(e,a),e}))):(salla.event.comment.additionFailed(t="can't find comment content!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),salla.api.errorPromise(t))}}class F extends h{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 h{constructor(){super(),this.namespace="document";}}class S extends h{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 _ extends h{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 q extends h{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 A extends h{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 C extends h{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}"},this.endpointsMethods={getDetails:"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}))}}class x{constructor(){salla.event.on("twilight::initiated",(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.setToken(e),salla.cart.api.reset();})),this.notifier_handler_disabled=!1,this.axios=axios.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}});}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;}))}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});let t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id}),this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"));}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a="guest"===e.user.type,s=salla.storage.get("cart"),r=e.user?.id,n=salla.storage.get("user.id");if(n&&n!==r&&(salla.log("Api:: case1 = >user in localStorage is not same as user in the config"),salla.storage.remove("user")),s&&(s.user_id!==r||s.store_id!==e.store?.id))return salla.log("cart",{user_id:s.user_id,store_id:s.store_id}),salla.log("current",{user_id:r,store_id:e.store?.id}),salla.log("Api:: case2 => The cart is not belong to current "+(s.user_id!==r?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return void salla.log("Api:: case3 => current user is a guest and there is no token");if(a&&t)return salla.log("Api:: case4 => there is a token and current user is guest"),salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.log("Api:: case5 => current user is logged-in but there is no token"),salla.cart.api.reset(),void salla.auth.api.refresh();let l=o$1(t);return Date.now()/1e3>l.exp?(salla.log("Api:: case6 => current user is logged-in and there is a token, but it's expired"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):l.sub!==r?(salla.log("Api:: case7 => The user id is not match the token details"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):(this.setToken(t),salla.log("Api:: case8 => current user is logged-in and there is a token, and it's not expired"),void salla.event.emit("api::initiated"))}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,a="get",s={}){let i={endPoint:e,payload:t,method:a,options:s},r="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===r?.tagName&&(n=!0),n&&r?.load(),this.axios[i.method](i.endPoint,i.payload,i.options).then((e=>(n&&r?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&r?.stop(),salla.event.document.requestFailed(i,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,s=t&&t.googleTags?t.googleTags:a;dataLayer&&s&&dataLayer.push(s),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 s=t[e];Array.isArray(s)?s.forEach((e=>a.push(e))):a.push(s);}));let s=(a.length>1?"* ":"")+a.join("\n* ");salla.error(s,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,s)=>t?a(e):s(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class k{constructor(t){"ready"!==y$1.status?t?(y$1.config.merge(t),t?.events&&y$1.event.dispatchEvents(t?.events),t._token&&salla.api.setHeader("X-CSRF-TOKEN",t._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),t?.user?.language_code&&salla.lang.setLocale(t?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(t)):this.setSallaReady(t):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(".store-notify")?salla.logger.warn(".store-notify element Existed before!"):salla.lang.onLoaded((()=>{const e=document.createElement("div");e.classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e);})));}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://assets.salla.sa/cp/assets/images/logo-new.png">\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),s=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,s).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(t){y$1.status="ready",y$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}));}}y$1.status="loading",y$1.notify=o,y$1.lang=new class extends lang{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.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);}get(e,t,a){let s=e;(window.translations||this.translationsLoaded)&&(s="trans."+e);let i=super.get(s,t,a);return i!==s?i:super.get(s,t,"en").replace(s,e)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},y$1.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 s=e.split("."),i=s.splice(-1);return await salla.call(s.join("."))[i](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 s;for(let a=0;a<t.length&&!(s=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(s=e.get(t[a])));a++);return s=s||e,"object"!=typeof s||a?s:void 0}},y$1.infiniteScroll=new class extends d{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,a,s){s=this.getCustomOptions(a,s);let i="string"!=typeof e?e:document.querySelector(e),r=s.path;if(!i||!r||"string"==typeof r&&!document.querySelector(r))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new js(i,s);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}}(void 0,salla.event.infiniteScroll),y$1.api=new class extends x{constructor(){super(),this.auth=new f,this.cart=new p,this.loyalty=new g,this.order=new m,this.rating=new S,this.product=new v,this.profile=new y,this.comment=new w,this.currency=new F,this.document=new b,this.wishlist=new _,this.scope=new q,this.booking=new A,this.landing=new C;}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((t=>y$1[t]=new d(y$1.api[t],y$1.event[t]))),y$1.call=t=>{let a=y$1,s=t.split(".");for(;s.length&&(a=a[s.shift()]););return a},y$1.init=e=>new k(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t);})),y$1.success=y$1.notify.success,y$1.error=y$1.notify.error,y$1.versions.twilight="[VI]{version}[/VI]",y$1.onInitiated=e=>salla.event.once("twilight::initiated",e),y$1.onReady=y$1.onReady||function(t){"ready"!==salla.status?y$1.onInitiated(t):t(salla.config.all());},window.dispatchEvent(new CustomEvent("salla::created"));
|
|
9483
|
+
let r=function(e,t,a){return alert(e)},n=function(e,t){return r(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return r(e,t,a)},setNotifier:function(e){r=e,salla.event.emit("twilight::notifier.changed");},error:n,success:function(e,t){return r(e,l.success,t)},info:function(e,t){return r(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=>{n(decodeURI(e.replace("?danger=","").replace("&danger=","")));}));})));},types:l};class d{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,s){return "event"===s?t:"api"===s?e:e&&e[s]||a[s]}})}}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 s=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(s="FORM"===this.tagName?this:s||this.closest("form")||this.closest("[salla-form-data]")||this,s&&"FORM"===s.tagName)return this.getFilteredData(new FormData(s),null,s);let i=s.querySelectorAll("[name]");if(!i.length)return this.getFilteredData();let r=Object.assign({},this.dataset);return i.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,r);r[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(r)},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 s=this.attributes[a].name.toLowerCase();if(0===s.indexOf(e))return !t||s}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((s=>{let i=a?.dataset[s]||this.dataset[s];if(i){var r=window[i];if("function"==typeof r){if(!r(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${i}(formData, element, event)!`;return r(e,a||this,t)}Salla.log("window."+i+"() 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 c{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){return Salla.event.addListener(this.getEventName(e),t)}once(e,t){return Salla.event.once(this.getEventName(e),t)}}function u(e){e&&e.sallaInitiated&&!e.initiated&&(e.sallaInitiated(),e.initiated=!0);}Salla.event.auth=new class extends c{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"},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 c{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",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 c{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"},this.after_init();}},Salla.event.scope=new class extends c{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 c{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 c{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.comment=new class extends c{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.failed"},this.after_init();}},Salla.event.landing=new class extends c{constructor(){super(),this.namespace="landing",this.events={detailsFetched:"order.fetched",getDetailsFailed:"get.details.failed",orderCreated:"order.created",orderCreationFailed:"order.creation.failed"},this.after_init();}},Salla.event.loyalty=new class extends c{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 c{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"},this.after_init();}},Salla.event.profile=new class extends c{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 c{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 c{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,...s){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...s)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const i=new CustomEvent(t,...s);return e.dispatchEvent(i)}},Salla.event.wishlist=new class extends c{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 c{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.on("twilight::initiated",(()=>{Object.keys(Salla).forEach((e=>{"object"==typeof(e=Salla[e])&&(u(e),Object.keys(e).forEach((t=>{u(e[t]);})));}));})),Salla.config.default_properties={debug:"undefined"!=typeof _commonjsHelpers.browser$1&&"development"==="production",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 h{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,a=null){let s=Array.isArray(e),i=s?this.getUrl(...e):this.getUrl(e);e=s?e[0]:e,a=a||this.endpointsMethods[e]||"post";let r=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 r&&"get"===a&&(t=t?Object.assign(t,r):r),this.webEndpoints.includes(e)?i=salla.url.get(i):"http"!==i.substring(0,4)&&(i=salla.url.api(i)),Salla.api.request(i,t,a,{headers:r})}request(e,t,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 p extends h{constructor(){super(),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"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put",getQuickOrderSettings:"get"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init(),salla.event.on("api::initiated",(()=>this.getCurrentCartId()));}async getCurrentCartId(){if(salla.cart.api.latestCart)return salla.cart.api.latestCart.cart.id;let e=salla.storage.get("cart.id");if(e)return e;let t=await this.latest();return salla.cart.api.latestCart=t.data,salla.cart.api.latestCart.cart.id}getUploadImageEndpoint(e){return salla.url.api(this.getUrl("uploadImage",e||salla.storage.get("cart.id")))}latest(){return this.request("latest",{params:{source:""}}).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 this.getCurrentCartId(),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 s=await this.getCurrentCartId();return this.request([a,s,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}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 this.getCurrentCartId();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 this.getCurrentCartId();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 this.getCurrentCartId();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){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit();}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload();})).catch((function(e){throw 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,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.cart.api.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();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();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 this.getCurrentCartId()]).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}))))}}class g extends h{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())){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())){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 f extends h{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.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 s=await salla.auth.api.request(["verify",a],e);if(200!==s?.status)return salla.auth.event.verificationFailed(s,a),salla.api.errorPromise(s);let i="authenticated"===s.data?.case;return i&&salla.auth.event.tokenFetched(s.data.token),t&&await salla.auth.api.request("auth/jwt"),i&&salla.auth.event.loggedIn(s).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(s,a),salla.api.successPromise(s)}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 function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),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}))}logout(){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut().then((()=>{let e=salla.url.get("logout");console.log(`Going to ${e}, to do any thing before this action use: salla.auth.even.onLoggedOut(()=>{...})`);try{location.href=e;}catch(e){salla.log(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 m extends h{constructor(){super(),this.namespace="order",this.endpoints={cancel:"orders/cancel/{id}",createCartFromOrder:"reorder/{id}",sendInvoice:"orders/send/{id}"},this.endpointsMethods={createCartFromOrder:"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:!!window.ApplePaySession}}).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}))}}class v extends h{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"},this.endpointsMethods={details:"get",giftDetail:"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.availabilitySubscribedFailed(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}))}}class y extends h{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 w extends h{constructor(){super(),this.namespace="comment",this.endpoints={add:"{type}/{id}/comments"},this.after_init();}add(e){e?.data&&(e=e.data);let t,a=salla.form.getPossibleValue(e,["id"]),s=salla.form.getPossibleValue(e,["type"]),i=salla.form.getPossibleValue(e,["comment"]);return a?s&&["products","pages","product","page"].includes(s)?i?(s+=["product","page"].includes(s)?"s":"",this.request(["add",s,a],{comment:i}).then((function(e){return salla.event.comment.added(e,a),e})).catch((function(e){throw salla.event.comment.additionFailed(e,a),e}))):(salla.event.comment.additionFailed(t="can't find comment content!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get type one of:(products, product, page, pages)!"),salla.api.errorPromise(t)):(salla.event.comment.additionFailed(t="Failed to get id!"),salla.api.errorPromise(t))}}class F extends h{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 h{constructor(){super(),this.namespace="document";}}class S extends h{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 _ extends h{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 q extends h{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 A extends h{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 C extends h{constructor(){super(),this.namespace="landing",this.endpoints={getDetails:"landing/{landing_page_id}",createCartFromPage:"landing/{landing_page_id}"},this.endpointsMethods={getDetails:"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}))}}class x{constructor(){salla.event.on("twilight::initiated",(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.setToken(e),salla.cart.api.reset();})),this.notifier_handler_disabled=!1,this.axios=axios.create({headers:{common:{"X-Requested-With":"XMLHttpRequest","S-SOURCE":"twilight","S-APP-VERSION":"v2.0.0","S-APP-OS":"browser"}}});}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;}))}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});let t=salla.storage.get("scope");t&&this.setHeaders({"s-scope-type":t.type,"s-scope-id":t.id}),this.injectTokenToTheRequests(e),salla.storage.get("affiliate_code")&&this.setHeader("s-affiliate-code",salla.storage.get("affiliate_code"));}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a="guest"===e.user.type,s=salla.storage.get("cart"),r=e.user?.id,n=salla.storage.get("user.id");if(n&&n!==r&&(salla.log("Api:: case1 = >user in localStorage is not same as user in the config"),salla.storage.remove("user")),s&&(s.user_id!==r||s.store_id!==e.store?.id))return salla.log("cart",{user_id:s.user_id,store_id:s.store_id}),salla.log("current",{user_id:r,store_id:e.store?.id}),salla.log("Api:: case2 => The cart is not belong to current "+(s.user_id!==r?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return void salla.log("Api:: case3 => current user is a guest and there is no token");if(a&&t)return salla.log("Api:: case4 => there is a token and current user is guest"),salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.log("Api:: case5 => current user is logged-in but there is no token"),salla.cart.api.reset(),void salla.auth.api.refresh();let l=o$1(t);return Date.now()/1e3>l.exp?(salla.log("Api:: case6 => current user is logged-in and there is a token, but it's expired"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):l.sub!==r?(salla.log("Api:: case7 => The user id is not match the token details"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):(this.setToken(t),salla.log("Api:: case8 => current user is logged-in and there is a token, and it's not expired"),void salla.event.emit("api::initiated"))}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,a="get",s={}){let i={endPoint:e,payload:t,method:a,options:s},r="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===r?.tagName&&(n=!0),n&&r?.load(),this.axios[i.method](i.endPoint,i.payload,i.options).then((e=>(n&&r?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&r?.stop(),salla.event.document.requestFailed(i,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,s=t&&t.googleTags?t.googleTags:a;dataLayer&&s&&dataLayer.push(s),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 s=t[e];Array.isArray(s)?s.forEach((e=>a.push(e))):a.push(s);}));let s=(a.length>1?"* ":"")+a.join("\n* ");salla.error(s,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,s)=>t?a(e):s(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}}class k{constructor(t){"ready"!==y$1.status?t?(y$1.config.merge(t),t?.events&&y$1.event.dispatchEvents(t?.events),t._token&&salla.api.setHeader("X-CSRF-TOKEN",t._token),this.injectMaintenanceAlert(),this.injectThemePreviewAlert(),this.injectEditAlert(),t?.user?.language_code&&salla.lang.setLocale(t?.user?.language_code),salla.lang.loadStoreTranslations(),this.setSallaReady(t)):this.setSallaReady(t):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(".store-notify")?salla.logger.warn(".store-notify element Existed before!"):salla.lang.onLoaded((()=>{const e=document.createElement("div");e.classList.add("store-notify"),e.style="background-color: #d63031; color: #fff; padding: 10px 15px; text-align: center; font-size: 17px;",e.innerHTML=`<p style="margin:0 !important;">${salla.lang.get("blocks.header.maintenance_alert")}</p>`,document.body.prepend(e);})));}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://assets.salla.sa/cp/assets/images/logo-new.png">\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),s=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,s).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(t){y$1.status="ready",y$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}));}}y$1.status="loading",y$1.notify=o,y$1.lang=new class extends lang{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.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);}get(e,t,a){let s=e;(window.translations||this.translationsLoaded)&&(s="trans."+e);let i=super.get(s,t,a);return i!==s?i:super.get(s,t,"en").replace(s,e)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},y$1.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 s=e.split("."),i=s.splice(-1);return await salla.call(s.join("."))[i](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 s;for(let a=0;a<t.length&&!(s=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(s=e.get(t[a])));a++);return s=s||e,"object"!=typeof s||a?s:void 0}},y$1.infiniteScroll=new class extends d{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,a,s){s=this.getCustomOptions(a,s);let i="string"!=typeof e?e:document.querySelector(e),r=s.path;if(!i||!r||"string"==typeof r&&!document.querySelector(r))return void Salla.logger.warn(i?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new js(i,s);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}}(void 0,salla.event.infiniteScroll),y$1.api=new class extends x{constructor(){super(),this.auth=new f,this.cart=new p,this.loyalty=new g,this.order=new m,this.rating=new S,this.product=new v,this.profile=new y,this.comment=new w,this.currency=new F,this.document=new b,this.wishlist=new _,this.scope=new q,this.booking=new A,this.landing=new C;}},["cart","auth","order","scope","rating","comment","loyalty","product","profile","currency","document","wishlist","booking","landing"].forEach((t=>y$1[t]=new d(y$1.api[t],y$1.event[t]))),y$1.call=t=>{let a=y$1,s=t.split(".");for(;s.length&&(a=a[s.shift()]););return a},y$1.init=e=>new k(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t);})),y$1.success=y$1.notify.success,y$1.error=y$1.notify.error,y$1.versions.twilight="[VI]{version}[/VI]",y$1.onInitiated=e=>salla.event.once("twilight::initiated",e),y$1.onReady=y$1.onReady||function(t){"ready"!==salla.status?y$1.onInitiated(t):t(salla.config.all());},window.dispatchEvent(new CustomEvent("salla::created"));
|
|
7517
9484
|
|
|
7518
9485
|
var lazyload_min = _commonjsHelpers.createCommonjsModule(function (module, exports) {
|
|
7519
9486
|
!function(n,t){module.exports=t();}(_commonjsHelpers.commonjsGlobal,(function(){function n(){return n=Object.assign||function(n){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);}return n},n.apply(this,arguments)}var t="undefined"!=typeof window,e=t&&!("onscroll"in window)||"undefined"!=typeof navigator&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),i=t&&"IntersectionObserver"in window,o=t&&"classList"in document.createElement("p"),a=t&&window.devicePixelRatio>1,r={elements_selector:".lazy",container:e||t?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_bg_set:"bg-set",data_poster:"poster",class_applied:"applied",class_loading:"loading",class_loaded:"loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1,restore_on_error:!1},c=function(t){return n({},r,t)},l=function(n,t){var e,i="LazyLoad::Initialized",o=new n(t);try{e=new CustomEvent(i,{detail:{instance:o}});}catch(n){(e=document.createEvent("CustomEvent")).initCustomEvent(i,!1,!1,{instance:o});}window.dispatchEvent(e);},u="src",s="srcset",d="sizes",f="poster",_="llOriginalAttrs",g="data",v="loading",b="loaded",m="applied",p="error",h="native",E="data-",I="ll-status",y=function(n,t){return n.getAttribute(E+t)},k=function(n){return y(n,I)},w=function(n,t){return function(n,t,e){var i="data-ll-status";null!==e?n.setAttribute(i,e):n.removeAttribute(i);}(n,0,t)},A=function(n){return w(n,null)},L=function(n){return null===k(n)},O=function(n){return k(n)===h},x=[v,b,m,p],C=function(n,t,e,i){n&&(void 0===i?void 0===e?n(t):n(t,e):n(t,e,i));},N=function(n,t){o?n.classList.add(t):n.className+=(n.className?" ":"")+t;},M=function(n,t){o?n.classList.remove(t):n.className=n.className.replace(new RegExp("(^|\\s+)"+t+"(\\s+|$)")," ").replace(/^\s+/,"").replace(/\s+$/,"");},z=function(n){return n.llTempImage},T=function(n,t){if(t){var e=t._observer;e&&e.unobserve(n);}},R=function(n,t){n&&(n.loadingCount+=t);},G=function(n,t){n&&(n.toLoadCount=t);},j=function(n){for(var t,e=[],i=0;t=n.children[i];i+=1)"SOURCE"===t.tagName&&e.push(t);return e},D=function(n,t){var e=n.parentNode;e&&"PICTURE"===e.tagName&&j(e).forEach(t);},H=function(n,t){j(n).forEach(t);},V=[u],F=[u,f],B=[u,s,d],J=[g],P=function(n){return !!n[_]},S=function(n){return n[_]},U=function(n){return delete n[_]},$=function(n,t){if(!P(n)){var e={};t.forEach((function(t){e[t]=n.getAttribute(t);})),n[_]=e;}},q=function(n,t){if(P(n)){var e=S(n);t.forEach((function(t){!function(n,t,e){e?n.setAttribute(t,e):n.removeAttribute(t);}(n,t,e[t]);}));}},K=function(n,t,e){N(n,t.class_applied),w(n,m),e&&(t.unobserve_completed&&T(n,t),C(t.callback_applied,n,e));},Q=function(n,t,e){N(n,t.class_loading),w(n,v),e&&(R(e,1),C(t.callback_loading,n,e));},W=function(n,t,e){e&&n.setAttribute(t,e);},X=function(n,t){W(n,d,y(n,t.data_sizes)),W(n,s,y(n,t.data_srcset)),W(n,u,y(n,t.data_src));},Y={IMG:function(n,t){D(n,(function(n){$(n,B),X(n,t);})),$(n,B),X(n,t);},IFRAME:function(n,t){$(n,V),W(n,u,y(n,t.data_src));},VIDEO:function(n,t){H(n,(function(n){$(n,V),W(n,u,y(n,t.data_src));})),$(n,F),W(n,f,y(n,t.data_poster)),W(n,u,y(n,t.data_src)),n.load();},OBJECT:function(n,t){$(n,J),W(n,g,y(n,t.data_src));}},Z=["IMG","IFRAME","VIDEO","OBJECT"],nn=function(n,t){!t||function(n){return n.loadingCount>0}(t)||function(n){return n.toLoadCount>0}(t)||C(n.callback_finish,t);},tn=function(n,t,e){n.addEventListener(t,e),n.llEvLisnrs[t]=e;},en=function(n,t,e){n.removeEventListener(t,e);},on=function(n){return !!n.llEvLisnrs},an=function(n){if(on(n)){var t=n.llEvLisnrs;for(var e in t){var i=t[e];en(n,e,i);}delete n.llEvLisnrs;}},rn=function(n,t,e){!function(n){delete n.llTempImage;}(n),R(e,-1),function(n){n&&(n.toLoadCount-=1);}(e),M(n,t.class_loading),t.unobserve_completed&&T(n,e);},cn=function(n,t,e){var i=z(n)||n;on(i)||function(n,t,e){on(n)||(n.llEvLisnrs={});var i="VIDEO"===n.tagName?"loadeddata":"load";tn(n,i,t),tn(n,"error",e);}(i,(function(o){!function(n,t,e,i){var o=O(t);rn(t,e,i),N(t,e.class_loaded),w(t,b),C(e.callback_loaded,t,i),o||nn(e,i);}(0,n,t,e),an(i);}),(function(o){!function(n,t,e,i){var o=O(t);rn(t,e,i),N(t,e.class_error),w(t,p),C(e.callback_error,t,i),e.restore_on_error&&q(t,B),o||nn(e,i);}(0,n,t,e),an(i);}));},ln=function(n,t,e){!function(n){return Z.indexOf(n.tagName)>-1}(n)?function(n,t,e){!function(n){n.llTempImage=document.createElement("IMG");}(n),cn(n,t,e),function(n){P(n)||(n[_]={backgroundImage:n.style.backgroundImage});}(n),function(n,t,e){var i=y(n,t.data_bg),o=y(n,t.data_bg_hidpi),r=a&&o?o:i;r&&(n.style.backgroundImage='url("'.concat(r,'")'),z(n).setAttribute(u,r),Q(n,t,e));}(n,t,e),function(n,t,e){var i=y(n,t.data_bg_multi),o=y(n,t.data_bg_multi_hidpi),r=a&&o?o:i;r&&(n.style.backgroundImage=r,K(n,t,e));}(n,t,e),function(n,t,e){var i=y(n,t.data_bg_set);if(i){var o=i.split("|"),a=o.map((function(n){return "image-set(".concat(n,")")}));n.style.backgroundImage=a.join(),""===n.style.backgroundImage&&(a=o.map((function(n){return "-webkit-image-set(".concat(n,")")})),n.style.backgroundImage=a.join()),K(n,t,e);}}(n,t,e);}(n,t,e):function(n,t,e){cn(n,t,e),function(n,t,e){var i=Y[n.tagName];i&&(i(n,t),Q(n,t,e));}(n,t,e);}(n,t,e);},un=function(n){n.removeAttribute(u),n.removeAttribute(s),n.removeAttribute(d);},sn=function(n){D(n,(function(n){q(n,B);})),q(n,B);},dn={IMG:sn,IFRAME:function(n){q(n,V);},VIDEO:function(n){H(n,(function(n){q(n,V);})),q(n,F),n.load();},OBJECT:function(n){q(n,J);}},fn=function(n,t){(function(n){var t=dn[n.tagName];t?t(n):function(n){if(P(n)){var t=S(n);n.style.backgroundImage=t.backgroundImage;}}(n);})(n),function(n,t){L(n)||O(n)||(M(n,t.class_entered),M(n,t.class_exited),M(n,t.class_applied),M(n,t.class_loading),M(n,t.class_loaded),M(n,t.class_error));}(n,t),A(n),U(n);},_n=["IMG","IFRAME","VIDEO"],gn=function(n){return n.use_native&&"loading"in HTMLImageElement.prototype},vn=function(n,t,e){n.forEach((function(n){return function(n){return n.isIntersecting||n.intersectionRatio>0}(n)?function(n,t,e,i){var o=function(n){return x.indexOf(k(n))>=0}(n);w(n,"entered"),N(n,e.class_entered),M(n,e.class_exited),function(n,t,e){t.unobserve_entered&&T(n,e);}(n,e,i),C(e.callback_enter,n,t,i),o||ln(n,e,i);}(n.target,n,t,e):function(n,t,e,i){L(n)||(N(n,e.class_exited),function(n,t,e,i){e.cancel_on_exit&&function(n){return k(n)===v}(n)&&"IMG"===n.tagName&&(an(n),function(n){D(n,(function(n){un(n);})),un(n);}(n),sn(n),M(n,e.class_loading),R(i,-1),A(n),C(e.callback_cancel,n,t,i));}(n,t,e,i),C(e.callback_exit,n,t,i));}(n.target,n,t,e)}));},bn=function(n){return Array.prototype.slice.call(n)},mn=function(n){return n.container.querySelectorAll(n.elements_selector)},pn=function(n){return function(n){return k(n)===p}(n)},hn=function(n,t){return function(n){return bn(n).filter(L)}(n||mn(t))},En=function(n,e){var o=c(n);this._settings=o,this.loadingCount=0,function(n,t){i&&!gn(n)&&(t._observer=new IntersectionObserver((function(e){vn(e,n,t);}),function(n){return {root:n.container===document?null:n.container,rootMargin:n.thresholds||n.threshold+"px"}}(n)));}(o,this),function(n,e){t&&(e._onlineHandler=function(){!function(n,t){var e;(e=mn(n),bn(e).filter(pn)).forEach((function(t){M(t,n.class_error),A(t);})),t.update();}(n,e);},window.addEventListener("online",e._onlineHandler));}(o,this),this.update(e);};return En.prototype={update:function(n){var t,o,a=this._settings,r=hn(n,a);G(this,r.length),!e&&i?gn(a)?function(n,t,e){n.forEach((function(n){-1!==_n.indexOf(n.tagName)&&function(n,t,e){n.setAttribute("loading","lazy"),cn(n,t,e),function(n,t){var e=Y[n.tagName];e&&e(n,t);}(n,t),w(n,h);}(n,t,e);})),G(e,0);}(r,a,this):(o=r,function(n){n.disconnect();}(t=this._observer),function(n,t){t.forEach((function(t){n.observe(t);}));}(t,o)):this.loadAll(r);},destroy:function(){this._observer&&this._observer.disconnect(),t&&window.removeEventListener("online",this._onlineHandler),mn(this._settings).forEach((function(n){U(n);})),delete this._observer,delete this._settings,delete this._onlineHandler,delete this.loadingCount,delete this.toLoadCount;},loadAll:function(n){var t=this,e=this._settings;hn(n,e).forEach((function(n){T(n,t),ln(n,e,t);}));},restoreAll:function(){var n=this._settings;mn(n).forEach((function(t){fn(t,n);}));}},En.load=function(n,t){var e=c(t);ln(n,e);},En.resetStatus=function(n){A(n);},t&&function(n,t){if(t)if(t.length)for(var e,i=0;e=t[i];i+=1)l(n,e);else l(n,t);}(En,window.lazyLoadOptions),En}));
|