@salla.sa/twilight-components 2.11.20 → 2.11.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/cjs/{app-globals-f18513f9.js → app-globals-7253a431.js} +2232 -39
  2. package/dist/cjs/loader.cjs.js +2 -2
  3. package/dist/cjs/salla-button_37.cjs.entry.js +2 -3
  4. package/dist/cjs/twilight.cjs.js +2 -2
  5. package/dist/collection/components/salla-file-upload/salla-file-upload.js +4 -5
  6. package/dist/collection/components/salla-slider/salla-slider.js +2 -2
  7. package/dist/components/index.js +2232 -39
  8. package/dist/components/salla-file-upload2.js +2 -3
  9. package/dist/components/salla-slider2.js +1 -1
  10. package/dist/esm/{app-globals-9127a6ae.js → app-globals-a043cc09.js} +2232 -39
  11. package/dist/esm/loader.js +2 -2
  12. package/dist/esm/salla-button_37.entry.js +2 -3
  13. package/dist/esm/twilight.js +2 -2
  14. package/dist/esm-es5/app-globals-a043cc09.js +30 -0
  15. package/dist/esm-es5/loader.js +1 -1
  16. package/dist/esm-es5/salla-button_37.entry.js +1 -1
  17. package/dist/esm-es5/twilight.js +1 -1
  18. package/dist/twilight/p-11ec9d06.system.js +30 -0
  19. package/dist/twilight/{p-5fc3f873.system.js → p-1b87ab66.system.js} +1 -1
  20. package/dist/twilight/p-2c5db3b4.js +24 -0
  21. package/dist/twilight/p-5f625abf.entry.js +36 -0
  22. package/dist/twilight/{p-c46d9ddb.system.entry.js → p-a55496d9.system.entry.js} +1 -1
  23. package/dist/twilight/twilight.esm.js +1 -1
  24. package/dist/twilight/twilight.js +1 -1
  25. package/package.json +4 -4
  26. package/dist/esm-es5/app-globals-9127a6ae.js +0 -24
  27. package/dist/twilight/p-7182281b.entry.js +0 -36
  28. package/dist/twilight/p-a6b1a735.js +0 -24
  29. package/dist/twilight/p-dddd2139.system.js +0 -24
@@ -5,6 +5,232 @@
5
5
 
6
6
  const _commonjsHelpers = require('./_commonjsHelpers-691dd63b.js');
7
7
 
8
+ const global$1 = (typeof global !== "undefined" ? global :
9
+ typeof self !== "undefined" ? self :
10
+ typeof window !== "undefined" ? window : {});
11
+
12
+ // shim for using process in browser
13
+ // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
14
+
15
+ function defaultSetTimout() {
16
+ throw new Error('setTimeout has not been defined');
17
+ }
18
+ function defaultClearTimeout () {
19
+ throw new Error('clearTimeout has not been defined');
20
+ }
21
+ var cachedSetTimeout = defaultSetTimout;
22
+ var cachedClearTimeout = defaultClearTimeout;
23
+ if (typeof global$1.setTimeout === 'function') {
24
+ cachedSetTimeout = setTimeout;
25
+ }
26
+ if (typeof global$1.clearTimeout === 'function') {
27
+ cachedClearTimeout = clearTimeout;
28
+ }
29
+
30
+ function runTimeout(fun) {
31
+ if (cachedSetTimeout === setTimeout) {
32
+ //normal enviroments in sane situations
33
+ return setTimeout(fun, 0);
34
+ }
35
+ // if setTimeout wasn't available but was latter defined
36
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
37
+ cachedSetTimeout = setTimeout;
38
+ return setTimeout(fun, 0);
39
+ }
40
+ try {
41
+ // when when somebody has screwed with setTimeout but no I.E. maddness
42
+ return cachedSetTimeout(fun, 0);
43
+ } catch(e){
44
+ try {
45
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
46
+ return cachedSetTimeout.call(null, fun, 0);
47
+ } catch(e){
48
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
49
+ return cachedSetTimeout.call(this, fun, 0);
50
+ }
51
+ }
52
+
53
+
54
+ }
55
+ function runClearTimeout(marker) {
56
+ if (cachedClearTimeout === clearTimeout) {
57
+ //normal enviroments in sane situations
58
+ return clearTimeout(marker);
59
+ }
60
+ // if clearTimeout wasn't available but was latter defined
61
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
62
+ cachedClearTimeout = clearTimeout;
63
+ return clearTimeout(marker);
64
+ }
65
+ try {
66
+ // when when somebody has screwed with setTimeout but no I.E. maddness
67
+ return cachedClearTimeout(marker);
68
+ } catch (e){
69
+ try {
70
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
71
+ return cachedClearTimeout.call(null, marker);
72
+ } catch (e){
73
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
74
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
75
+ return cachedClearTimeout.call(this, marker);
76
+ }
77
+ }
78
+
79
+
80
+
81
+ }
82
+ var queue = [];
83
+ var draining = false;
84
+ var currentQueue;
85
+ var queueIndex = -1;
86
+
87
+ function cleanUpNextTick() {
88
+ if (!draining || !currentQueue) {
89
+ return;
90
+ }
91
+ draining = false;
92
+ if (currentQueue.length) {
93
+ queue = currentQueue.concat(queue);
94
+ } else {
95
+ queueIndex = -1;
96
+ }
97
+ if (queue.length) {
98
+ drainQueue();
99
+ }
100
+ }
101
+
102
+ function drainQueue() {
103
+ if (draining) {
104
+ return;
105
+ }
106
+ var timeout = runTimeout(cleanUpNextTick);
107
+ draining = true;
108
+
109
+ var len = queue.length;
110
+ while(len) {
111
+ currentQueue = queue;
112
+ queue = [];
113
+ while (++queueIndex < len) {
114
+ if (currentQueue) {
115
+ currentQueue[queueIndex].run();
116
+ }
117
+ }
118
+ queueIndex = -1;
119
+ len = queue.length;
120
+ }
121
+ currentQueue = null;
122
+ draining = false;
123
+ runClearTimeout(timeout);
124
+ }
125
+ function nextTick(fun) {
126
+ var args = new Array(arguments.length - 1);
127
+ if (arguments.length > 1) {
128
+ for (var i = 1; i < arguments.length; i++) {
129
+ args[i - 1] = arguments[i];
130
+ }
131
+ }
132
+ queue.push(new Item(fun, args));
133
+ if (queue.length === 1 && !draining) {
134
+ runTimeout(drainQueue);
135
+ }
136
+ }
137
+ // v8 likes predictible objects
138
+ function Item(fun, array) {
139
+ this.fun = fun;
140
+ this.array = array;
141
+ }
142
+ Item.prototype.run = function () {
143
+ this.fun.apply(null, this.array);
144
+ };
145
+ var title = 'browser';
146
+ var platform = 'browser';
147
+ var browser = true;
148
+ var env = {};
149
+ var argv = [];
150
+ var version = ''; // empty string to avoid regexp issues
151
+ var versions = {};
152
+ var release = {};
153
+ var config = {};
154
+
155
+ function noop() {}
156
+
157
+ var on = noop;
158
+ var addListener = noop;
159
+ var once = noop;
160
+ var off = noop;
161
+ var removeListener = noop;
162
+ var removeAllListeners = noop;
163
+ var emit = noop;
164
+
165
+ function binding(name) {
166
+ throw new Error('process.binding is not supported');
167
+ }
168
+
169
+ function cwd () { return '/' }
170
+ function chdir (dir) {
171
+ throw new Error('process.chdir is not supported');
172
+ }function umask() { return 0; }
173
+
174
+ // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
175
+ var performance = global$1.performance || {};
176
+ var performanceNow =
177
+ performance.now ||
178
+ performance.mozNow ||
179
+ performance.msNow ||
180
+ performance.oNow ||
181
+ performance.webkitNow ||
182
+ function(){ return (new Date()).getTime() };
183
+
184
+ // generate timestamp or delta
185
+ // see http://nodejs.org/api/process.html#process_process_hrtime
186
+ function hrtime(previousTimestamp){
187
+ var clocktime = performanceNow.call(performance)*1e-3;
188
+ var seconds = Math.floor(clocktime);
189
+ var nanoseconds = Math.floor((clocktime%1)*1e9);
190
+ if (previousTimestamp) {
191
+ seconds = seconds - previousTimestamp[0];
192
+ nanoseconds = nanoseconds - previousTimestamp[1];
193
+ if (nanoseconds<0) {
194
+ seconds--;
195
+ nanoseconds += 1e9;
196
+ }
197
+ }
198
+ return [seconds,nanoseconds]
199
+ }
200
+
201
+ var startTime = new Date();
202
+ function uptime() {
203
+ var currentTime = new Date();
204
+ var dif = currentTime - startTime;
205
+ return dif / 1000;
206
+ }
207
+
208
+ var browser$1 = {
209
+ nextTick: nextTick,
210
+ title: title,
211
+ browser: browser,
212
+ env: env,
213
+ argv: argv,
214
+ version: version,
215
+ versions: versions,
216
+ on: on,
217
+ addListener: addListener,
218
+ once: once,
219
+ off: off,
220
+ removeListener: removeListener,
221
+ removeAllListeners: removeAllListeners,
222
+ emit: emit,
223
+ binding: binding,
224
+ cwd: cwd,
225
+ chdir: chdir,
226
+ umask: umask,
227
+ hrtime: hrtime,
228
+ platform: platform,
229
+ release: release,
230
+ config: config,
231
+ uptime: uptime
232
+ };
233
+
8
234
  /**
9
235
  * Checks if `value` is classified as an `Array` object.
10
236
  *
@@ -28,9 +254,9 @@ const _commonjsHelpers = require('./_commonjsHelpers-691dd63b.js');
28
254
  * _.isArray(_.noop);
29
255
  * // => false
30
256
  */
31
- var isArray$1 = Array.isArray;
257
+ var isArray$2 = Array.isArray;
32
258
 
33
- var isArray_1 = isArray$1;
259
+ var isArray_1 = isArray$2;
34
260
 
35
261
  /** Detect free variable `global` from Node.js. */
36
262
  var freeGlobal = typeof _commonjsHelpers.commonjsGlobal == 'object' && _commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.Object === Object && _commonjsHelpers.commonjsGlobal;
@@ -1095,11 +1321,11 @@ var _baseToString = baseToString;
1095
1321
  * _.toString([1, 2, 3]);
1096
1322
  * // => '1,2,3'
1097
1323
  */
1098
- function toString$1(value) {
1324
+ function toString$2(value) {
1099
1325
  return value == null ? '' : _baseToString(value);
1100
1326
  }
1101
1327
 
1102
- var toString_1 = toString$1;
1328
+ var toString_1 = toString$2;
1103
1329
 
1104
1330
  /**
1105
1331
  * Casts `value` to a path array if it's not one.
@@ -1199,7 +1425,7 @@ var eventemitter2 = _commonjsHelpers.createCommonjsModule(function (module, expo
1199
1425
  return Object.prototype.toString.call(obj) === "[object Array]";
1200
1426
  };
1201
1427
  var defaultMaxListeners = 10;
1202
- var nextTickSupported= typeof process=='object' && typeof process.nextTick=='function';
1428
+ var nextTickSupported= typeof browser$1=='object' && typeof browser$1.nextTick=='function';
1203
1429
  var symbolsSupported= typeof Symbol==='function';
1204
1430
  var reflectSupported= typeof Reflect === 'object';
1205
1431
  var setImmediateSupported= typeof setImmediate === 'function';
@@ -1248,12 +1474,12 @@ var eventemitter2 = _commonjsHelpers.createCommonjsModule(function (module, expo
1248
1474
  errorMsg += ' Event name: ' + eventName + '.';
1249
1475
  }
1250
1476
 
1251
- if(typeof process !== 'undefined' && process.emitWarning){
1477
+ if(typeof browser$1 !== 'undefined' && browser$1.emitWarning){
1252
1478
  var e = new Error(errorMsg);
1253
1479
  e.name = 'MaxListenersExceededWarning';
1254
1480
  e.emitter = this;
1255
1481
  e.count = count;
1256
- process.emitWarning(e);
1482
+ browser$1.emitWarning(e);
1257
1483
  } else {
1258
1484
  console.error(errorMsg);
1259
1485
 
@@ -1959,7 +2185,7 @@ var eventemitter2 = _commonjsHelpers.createCommonjsModule(function (module, expo
1959
2185
  }).then(function () {
1960
2186
  context.event = event;
1961
2187
  return _listener.apply(context, args)
1962
- })) : (nextTick ? process.nextTick : _setImmediate)(function () {
2188
+ })) : (nextTick ? browser$1.nextTick : _setImmediate)(function () {
1963
2189
  context.event = event;
1964
2190
  _listener.apply(context, args);
1965
2191
  });
@@ -3172,8 +3398,8 @@ var Global$2 = util.Global;
3172
3398
 
3173
3399
  var localStorage_1 = {
3174
3400
  name: 'localStorage',
3175
- read: read$3,
3176
- write: write$3,
3401
+ read: read$4,
3402
+ write: write$4,
3177
3403
  each: each$3,
3178
3404
  remove: remove$3,
3179
3405
  clearAll: clearAll$3,
@@ -3183,18 +3409,18 @@ function localStorage() {
3183
3409
  return Global$2.localStorage
3184
3410
  }
3185
3411
 
3186
- function read$3(key) {
3412
+ function read$4(key) {
3187
3413
  return localStorage().getItem(key)
3188
3414
  }
3189
3415
 
3190
- function write$3(key, data) {
3416
+ function write$4(key, data) {
3191
3417
  return localStorage().setItem(key, data)
3192
3418
  }
3193
3419
 
3194
3420
  function each$3(fn) {
3195
3421
  for (var i = localStorage().length - 1; i >= 0; i--) {
3196
3422
  var key = localStorage().key(i);
3197
- fn(read$3(key), key);
3423
+ fn(read$4(key), key);
3198
3424
  }
3199
3425
  }
3200
3426
 
@@ -3210,8 +3436,8 @@ var Global$1 = util.Global;
3210
3436
 
3211
3437
  var sessionStorage_1 = {
3212
3438
  name: 'sessionStorage',
3213
- read: read$2,
3214
- write: write$2,
3439
+ read: read$3,
3440
+ write: write$3,
3215
3441
  each: each$2,
3216
3442
  remove: remove$2,
3217
3443
  clearAll: clearAll$2
@@ -3221,18 +3447,18 @@ function sessionStorage() {
3221
3447
  return Global$1.sessionStorage
3222
3448
  }
3223
3449
 
3224
- function read$2(key) {
3450
+ function read$3(key) {
3225
3451
  return sessionStorage().getItem(key)
3226
3452
  }
3227
3453
 
3228
- function write$2(key, data) {
3454
+ function write$3(key, data) {
3229
3455
  return sessionStorage().setItem(key, data)
3230
3456
  }
3231
3457
 
3232
3458
  function each$2(fn) {
3233
3459
  for (var i = sessionStorage().length - 1; i >= 0; i--) {
3234
3460
  var key = sessionStorage().key(i);
3235
- fn(read$2(key), key);
3461
+ fn(read$3(key), key);
3236
3462
  }
3237
3463
  }
3238
3464
 
@@ -3254,8 +3480,8 @@ var trim$1 = util.trim;
3254
3480
 
3255
3481
  var cookieStorage = {
3256
3482
  name: 'cookieStorage',
3257
- read: read$1,
3258
- write: write$1,
3483
+ read: read$2,
3484
+ write: write$2,
3259
3485
  each: each$1,
3260
3486
  remove: remove$1,
3261
3487
  clearAll: clearAll$1,
@@ -3263,7 +3489,7 @@ var cookieStorage = {
3263
3489
 
3264
3490
  var doc = Global.document;
3265
3491
 
3266
- function read$1(key) {
3492
+ function read$2(key) {
3267
3493
  if (!key || !_has(key)) { return null }
3268
3494
  var regexpStr = "(?:^|.*;\\s*)" +
3269
3495
  escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
@@ -3284,7 +3510,7 @@ function each$1(callback) {
3284
3510
  }
3285
3511
  }
3286
3512
 
3287
- function write$1(key, data) {
3513
+ function write$2(key, data) {
3288
3514
  if(!key) { return }
3289
3515
  doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
3290
3516
  }
@@ -3313,8 +3539,8 @@ function _has(key) {
3313
3539
 
3314
3540
  var memoryStorage_1 = {
3315
3541
  name: 'memoryStorage',
3316
- read: read,
3317
- write: write,
3542
+ read: read$1,
3543
+ write: write$1,
3318
3544
  each: each,
3319
3545
  remove: remove,
3320
3546
  clearAll: clearAll,
@@ -3322,11 +3548,11 @@ var memoryStorage_1 = {
3322
3548
 
3323
3549
  var memoryStorage = {};
3324
3550
 
3325
- function read(key) {
3551
+ function read$1(key) {
3326
3552
  return memoryStorage[key]
3327
3553
  }
3328
3554
 
3329
- function write(key, data) {
3555
+ function write$1(key, data) {
3330
3556
  memoryStorage[key] = data;
3331
3557
  }
3332
3558
 
@@ -3346,7 +3572,7 @@ function clearAll(key) {
3346
3572
  memoryStorage = {};
3347
3573
  }
3348
3574
 
3349
- function a(e,t=!1){e+="";let r,o=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],n=["0","1","2","3","4","5","6","7","8","9"],i=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?o:n,l=t?n:o;for(let t=0;t<i.length;t++)r=new RegExp(i[t],"g"),e=e.replace(r,l[t]);return e}function s$1(e){let t=(e.match(/\./g)||[]).length;return t&&1!==t?s$1(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e,t,r){let o=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[o]=c$1(e.slice(1),t,r[o]),r):o?{[o]:c$1(e.slice(1),t)}:""===o?[t]:t}function u$1(e){return Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/")+"/"+e.ltrim("/")}var d$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 o=Salla.helpers.digitsOnly(t.value);return t.min&&o<t.min?t.value=t.min:t.max&&o>t.max?t.value=t.max:t.maxLength>=1&&o.toString().length>t.maxLength?t.value=o.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?s$1(o):o.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 o=e,n=t.split("."),i=n.length;for(let e=0;e<i-1;e++){let t=n[e];o[t]||(o[t]={}),o=o[t];}return o[n[i-1]]=r,e},getNested:function(t,r,o){let n=get_1(t,r);return void 0!==n?n:o},inputData:function(e,t,r={}){if(e.includes("[")){let o=e.split("]").join("").split("[");return {name:o[0],value:c$1(o.slice(1),t,r[o[0]])}}return {name:e,value:t}},url:{get:u$1,asset:function(e){return function(e){return window.location.origin+"/"+e.ltrim("/")}("themes/"+Salla.config.get("theme.name")+"/"+e.ltrim("/"))},cdn:function(e){return "https://cdn.salla.network/"+e.ltrim("/")},is_page:function(e){return e&&Salla.config.get("page.slug")===e},api:function(e){return Salla.config.get("store.api",u$1("")).rtrim("/")+"/"+e.ltrim("/")}},addParamToUrl:function(e,t){if(!t||!e)return window.location.href;let r=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),o=window.location.href.replace(r,"$1").replace(/&$|\?$/,"");return o+=(o.includes("?")?"&":"?")+e+"="+encodeURIComponent(t),o.replace(/&$|\?$/,"")},debounce:function(e,t){t=t||100;let r,o=[];return function(...n){return clearTimeout(r),r=setTimeout((()=>{let t=e(...n);o.forEach((e=>e(t))),o=[];}),t),new Promise((e=>o.push(e)))}}},g$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 o=e.log,n=void 0===r?o:this.__dict__[r]||o,i=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(i[0]+="%c"+r[0].toUpperCase()+r.substring(1),i.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),n.call(e,...i.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 p$1=storeEngine.createStore([localStorage_1,sessionStorage_1,cookieStorage,memoryStorage_1],[]);"undefined"==typeof global?(window.salla=window.salla||window.Salla||{},window.Salla=window.salla):(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 Object.assign(this.properties_,e),this.properties_.store={...this.default_properties.store,...this.properties_.store},this}set(e,t){return e.includes(".")?(Salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)}get(e,t=null){return e.includes(".")?Salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0}all(){return this.properties_}isDebug(){return this.get("debug")||Salla.storage.get("debug")}},Salla.logger=g$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)&&void 0!==Salla.call&&"function"==typeof Salla.call(r))return Salla.log(`'Salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);if(super.emit(e,...t),"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.values()});}dispatch(e,...t){return this.emit(e,...t)}dispatchEvents(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))this.dispatch(t,r);else Salla.log("No Events To Dispatch!",e);}addListener(e,t){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(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}));}catch(e){Salla.log(e,"The native context does not exist yet");}}},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=p$1;}set(e,t){if(e.includes(".")){let r=e.split(".")[0],o={[r]:this.store.get(r)};return o=Salla.helpers.setNested(o,e,t),this.store.set(r,o[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 o="";if(r){let e=new Date;e.setTime(e.getTime()+24*r*60*60*1e3),o="; expires="+e.toUTCString();}return document.cookie=`${e}=${t}${o}"; 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],o=r.indexOf("="),n=o>-1?r.substr(0,o):r;this.remove(n);}}},Salla.helpers=d$1,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"[VI]{version}[/VI]"};var f$1=Salla;
3575
+ function a(e,t=!1){e+="";let r,o=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],n=["0","1","2","3","4","5","6","7","8","9"],i=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?o:n,l=t?n:o;for(let t=0;t<i.length;t++)r=new RegExp(i[t],"g"),e=e.replace(r,l[t]);return e}function s$1(e){let t=(e.match(/\./g)||[]).length;return t&&1!==t?s$1(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e,t,r){let o=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[o]=c$1(e.slice(1),t,r[o]),r):o?{[o]:c$1(e.slice(1),t)}:""===o?[t]:t}function u$1(e){return Salla.config.get("store.url",window.location.href.split("/").slice(0,-1).join("/")).rtrim("/")+"/"+e.ltrim("/")}var d$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 o=Salla.helpers.digitsOnly(t.value);return t.min&&o<t.min?t.value=t.min:t.max&&o>t.max?t.value=t.max:t.maxLength>=1&&o.toString().length>t.maxLength?t.value=o.toString().substring(0,t.maxLength):t.value=r||t.dataset.hasOwnProperty("digitsWithDecimal")?s$1(o):o.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 o=e,n=t.split("."),i=n.length;for(let e=0;e<i-1;e++){let t=n[e];o[t]||(o[t]={}),o=o[t];}return o[n[i-1]]=r,e},getNested:function(t,r,o){let n=get_1(t,r);return void 0!==n?n:o},inputData:function(e,t,r={}){if(e.includes("[")){let o=e.split("]").join("").split("[");return {name:o[0],value:c$1(o.slice(1),t,r[o[0]])}}return {name:e,value:t}},url:{get:u$1,asset:function(e){return function(e){return window.location.origin+"/"+e.ltrim("/")}("themes/"+Salla.config.get("theme.name")+"/"+e.ltrim("/"))},cdn:function(e){return "https://cdn.salla.network/"+e.ltrim("/")},is_page:function(e){return e&&Salla.config.get("page.slug")===e},api:function(e){return Salla.config.get("store.api",u$1("")).rtrim("/")+"/"+e.ltrim("/")}},addParamToUrl:function(e,t){if(!t||!e)return window.location.href;let r=new RegExp("([?&])"+e+"=[^&]+[&]?","g"),o=window.location.href.replace(r,"$1").replace(/&$|\?$/,"");return o.includes("?")?o+="&":o+=(o.endsWith("/")?"":"/")+"?",(o+e+"="+encodeURIComponent(t)).replace(/&$|\?$/,"")},debounce:function(e,t){t=t||100;let r,o=[];return function(...n){return clearTimeout(r),r=setTimeout((()=>{let t=e(...n);o.forEach((e=>e(t))),o=[];}),t),new Promise((e=>o.push(e)))}}},g$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 o=e.log,n=void 0===r?o:this.__dict__[r]||o,i=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(i[0]+="%c"+r[0].toUpperCase()+r.substring(1),i.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),n.call(e,...i.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 p$1=storeEngine.createStore([localStorage_1,sessionStorage_1,cookieStorage,memoryStorage_1],[]);"undefined"==typeof global$1?(window.salla=window.salla||window.Salla||{},window.Salla=window.salla):(global$1.salla=global$1.salla||global$1.Salla||{},global$1.Salla=global$1.salla),Salla.status="base",Salla.config=new class{constructor(e={},t={}){this.default_properties=t,this.properties_={...this.default_properties,...e};}merge(e){return Object.assign(this.properties_,e),this.properties_.store={...this.default_properties.store,...this.properties_.store},this}set(e,t){return e.includes(".")?(Salla.helpers.setNested(this.properties_,e,t),this):(this.properties_[e]=t,this)}get(e,t=null){return e.includes(".")?Salla.helpers.getNested(this.properties_,e,t):this.properties_.hasOwnProperty(e)?this.properties_[e]||t:t||void 0}all(){return this.properties_}isDebug(){return this.get("debug")||Salla.storage.get("debug")}},Salla.logger=g$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)&&void 0!==Salla.call&&"function"==typeof Salla.call(r))return Salla.log(`'Salla.${r}(...)' triggered using event '${e}'`),r=r.split("."),void salla[r[0]][r[1]](...t);if(super.emit(e,...t),"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.values()});}dispatch(e,...t){return this.emit(e,...t)}dispatchEvents(e){if(e&&"object"==typeof e)for(const[t,r]of Object.entries(e))this.dispatch(t,r);else Salla.log("No Events To Dispatch!",e);}addListener(e,t){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(Android)try{Android.customEventWithData(e,JSON.stringify({details:t}));}catch(e){Salla.log(e,"The native context does not exist yet");}}},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=p$1;}set(e,t){if(e.includes(".")){let r=e.split(".")[0],o={[r]:this.store.get(r)};return o=Salla.helpers.setNested(o,e,t),this.store.set(r,o[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 o="";if(r){let e=new Date;e.setTime(e.getTime()+24*r*60*60*1e3),o="; expires="+e.toUTCString();}return document.cookie=`${e}=${t}${o}"; 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],o=r.indexOf("="),n=o>-1?r.substr(0,o):r;this.remove(n);}}},Salla.helpers=d$1,Salla.log=Salla.logger.log,Salla.money=Salla.helpers.money,Salla.url=Salla.helpers.url,Salla.versions={base:"[VI]{version}[/VI]"};var f$1=Salla;
3350
3576
 
3351
3577
  var evEmitter = _commonjsHelpers.createCommonjsModule(function (module) {
3352
3578
  /**
@@ -5507,13 +5733,13 @@ var bind = function bind(fn, thisArg) {
5507
5733
 
5508
5734
  // utils is a library of generic helper functions non-specific to axios
5509
5735
 
5510
- var toString = Object.prototype.toString;
5736
+ var toString$1 = Object.prototype.toString;
5511
5737
 
5512
5738
  // eslint-disable-next-line func-names
5513
5739
  var kindOf = (function(cache) {
5514
5740
  // eslint-disable-next-line func-names
5515
5741
  return function(thing) {
5516
- var str = toString.call(thing);
5742
+ var str = toString$1.call(thing);
5517
5743
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
5518
5744
  };
5519
5745
  })(Object.create(null));
@@ -5531,7 +5757,7 @@ function kindOfTest(type) {
5531
5757
  * @param {Object} val The value to test
5532
5758
  * @returns {boolean} True if value is an Array, otherwise false
5533
5759
  */
5534
- function isArray(val) {
5760
+ function isArray$1(val) {
5535
5761
  return Array.isArray(val);
5536
5762
  }
5537
5763
 
@@ -5551,7 +5777,7 @@ function isUndefined(val) {
5551
5777
  * @param {Object} val The value to test
5552
5778
  * @returns {boolean} True if value is a Buffer, otherwise false
5553
5779
  */
5554
- function isBuffer(val) {
5780
+ function isBuffer$1(val) {
5555
5781
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
5556
5782
  && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
5557
5783
  }
@@ -5670,7 +5896,7 @@ var isFileList = kindOfTest('FileList');
5670
5896
  * @returns {boolean} True if value is a Function, otherwise false
5671
5897
  */
5672
5898
  function isFunction(val) {
5673
- return toString.call(val) === '[object Function]';
5899
+ return toString$1.call(val) === '[object Function]';
5674
5900
  }
5675
5901
 
5676
5902
  /**
@@ -5693,7 +5919,7 @@ function isFormData(thing) {
5693
5919
  var pattern = '[object FormData]';
5694
5920
  return thing && (
5695
5921
  (typeof FormData === 'function' && thing instanceof FormData) ||
5696
- toString.call(thing) === pattern ||
5922
+ toString$1.call(thing) === pattern ||
5697
5923
  (isFunction(thing.toString) && thing.toString() === pattern)
5698
5924
  );
5699
5925
  }
@@ -5767,7 +5993,7 @@ function forEach(obj, fn) {
5767
5993
  obj = [obj];
5768
5994
  }
5769
5995
 
5770
- if (isArray(obj)) {
5996
+ if (isArray$1(obj)) {
5771
5997
  // Iterate over array values
5772
5998
  for (var i = 0, l = obj.length; i < l; i++) {
5773
5999
  fn.call(null, obj[i], i, obj);
@@ -5806,7 +6032,7 @@ function merge(/* obj1, obj2, obj3, ... */) {
5806
6032
  result[key] = merge(result[key], val);
5807
6033
  } else if (isPlainObject(val)) {
5808
6034
  result[key] = merge({}, val);
5809
- } else if (isArray(val)) {
6035
+ } else if (isArray$1(val)) {
5810
6036
  result[key] = val.slice();
5811
6037
  } else {
5812
6038
  result[key] = val;
@@ -5940,9 +6166,9 @@ var isTypedArray = (function(TypedArray) {
5940
6166
  })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
5941
6167
 
5942
6168
  var utils = {
5943
- isArray: isArray,
6169
+ isArray: isArray$1,
5944
6170
  isArrayBuffer: isArrayBuffer,
5945
- isBuffer: isBuffer,
6171
+ isBuffer: isBuffer$1,
5946
6172
  isFormData: isFormData,
5947
6173
  isArrayBufferView: isArrayBufferView,
5948
6174
  isString: isString,
@@ -6188,6 +6414,1973 @@ var transitional = {
6188
6414
  clarifyTimeoutError: false
6189
6415
  };
6190
6416
 
6417
+ var lookup = [];
6418
+ var revLookup = [];
6419
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
6420
+ var inited = false;
6421
+ function init () {
6422
+ inited = true;
6423
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6424
+ for (var i = 0, len = code.length; i < len; ++i) {
6425
+ lookup[i] = code[i];
6426
+ revLookup[code.charCodeAt(i)] = i;
6427
+ }
6428
+
6429
+ revLookup['-'.charCodeAt(0)] = 62;
6430
+ revLookup['_'.charCodeAt(0)] = 63;
6431
+ }
6432
+
6433
+ function toByteArray (b64) {
6434
+ if (!inited) {
6435
+ init();
6436
+ }
6437
+ var i, j, l, tmp, placeHolders, arr;
6438
+ var len = b64.length;
6439
+
6440
+ if (len % 4 > 0) {
6441
+ throw new Error('Invalid string. Length must be a multiple of 4')
6442
+ }
6443
+
6444
+ // the number of equal signs (place holders)
6445
+ // if there are two placeholders, than the two characters before it
6446
+ // represent one byte
6447
+ // if there is only one, then the three characters before it represent 2 bytes
6448
+ // this is just a cheap hack to not do indexOf twice
6449
+ placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
6450
+
6451
+ // base64 is 4/3 + up to two characters of the original data
6452
+ arr = new Arr(len * 3 / 4 - placeHolders);
6453
+
6454
+ // if there are placeholders, only get up to the last complete 4 chars
6455
+ l = placeHolders > 0 ? len - 4 : len;
6456
+
6457
+ var L = 0;
6458
+
6459
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
6460
+ tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
6461
+ arr[L++] = (tmp >> 16) & 0xFF;
6462
+ arr[L++] = (tmp >> 8) & 0xFF;
6463
+ arr[L++] = tmp & 0xFF;
6464
+ }
6465
+
6466
+ if (placeHolders === 2) {
6467
+ tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
6468
+ arr[L++] = tmp & 0xFF;
6469
+ } else if (placeHolders === 1) {
6470
+ tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
6471
+ arr[L++] = (tmp >> 8) & 0xFF;
6472
+ arr[L++] = tmp & 0xFF;
6473
+ }
6474
+
6475
+ return arr
6476
+ }
6477
+
6478
+ function tripletToBase64 (num) {
6479
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
6480
+ }
6481
+
6482
+ function encodeChunk (uint8, start, end) {
6483
+ var tmp;
6484
+ var output = [];
6485
+ for (var i = start; i < end; i += 3) {
6486
+ tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
6487
+ output.push(tripletToBase64(tmp));
6488
+ }
6489
+ return output.join('')
6490
+ }
6491
+
6492
+ function fromByteArray (uint8) {
6493
+ if (!inited) {
6494
+ init();
6495
+ }
6496
+ var tmp;
6497
+ var len = uint8.length;
6498
+ var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
6499
+ var output = '';
6500
+ var parts = [];
6501
+ var maxChunkLength = 16383; // must be multiple of 3
6502
+
6503
+ // go through the array every three bytes, we'll deal with trailing stuff later
6504
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
6505
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
6506
+ }
6507
+
6508
+ // pad the end with zeros, but make sure to not forget the extra bytes
6509
+ if (extraBytes === 1) {
6510
+ tmp = uint8[len - 1];
6511
+ output += lookup[tmp >> 2];
6512
+ output += lookup[(tmp << 4) & 0x3F];
6513
+ output += '==';
6514
+ } else if (extraBytes === 2) {
6515
+ tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
6516
+ output += lookup[tmp >> 10];
6517
+ output += lookup[(tmp >> 4) & 0x3F];
6518
+ output += lookup[(tmp << 2) & 0x3F];
6519
+ output += '=';
6520
+ }
6521
+
6522
+ parts.push(output);
6523
+
6524
+ return parts.join('')
6525
+ }
6526
+
6527
+ function read (buffer, offset, isLE, mLen, nBytes) {
6528
+ var e, m;
6529
+ var eLen = nBytes * 8 - mLen - 1;
6530
+ var eMax = (1 << eLen) - 1;
6531
+ var eBias = eMax >> 1;
6532
+ var nBits = -7;
6533
+ var i = isLE ? (nBytes - 1) : 0;
6534
+ var d = isLE ? -1 : 1;
6535
+ var s = buffer[offset + i];
6536
+
6537
+ i += d;
6538
+
6539
+ e = s & ((1 << (-nBits)) - 1);
6540
+ s >>= (-nBits);
6541
+ nBits += eLen;
6542
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6543
+
6544
+ m = e & ((1 << (-nBits)) - 1);
6545
+ e >>= (-nBits);
6546
+ nBits += mLen;
6547
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6548
+
6549
+ if (e === 0) {
6550
+ e = 1 - eBias;
6551
+ } else if (e === eMax) {
6552
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
6553
+ } else {
6554
+ m = m + Math.pow(2, mLen);
6555
+ e = e - eBias;
6556
+ }
6557
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6558
+ }
6559
+
6560
+ function write (buffer, value, offset, isLE, mLen, nBytes) {
6561
+ var e, m, c;
6562
+ var eLen = nBytes * 8 - mLen - 1;
6563
+ var eMax = (1 << eLen) - 1;
6564
+ var eBias = eMax >> 1;
6565
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
6566
+ var i = isLE ? 0 : (nBytes - 1);
6567
+ var d = isLE ? 1 : -1;
6568
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
6569
+
6570
+ value = Math.abs(value);
6571
+
6572
+ if (isNaN(value) || value === Infinity) {
6573
+ m = isNaN(value) ? 1 : 0;
6574
+ e = eMax;
6575
+ } else {
6576
+ e = Math.floor(Math.log(value) / Math.LN2);
6577
+ if (value * (c = Math.pow(2, -e)) < 1) {
6578
+ e--;
6579
+ c *= 2;
6580
+ }
6581
+ if (e + eBias >= 1) {
6582
+ value += rt / c;
6583
+ } else {
6584
+ value += rt * Math.pow(2, 1 - eBias);
6585
+ }
6586
+ if (value * c >= 2) {
6587
+ e++;
6588
+ c /= 2;
6589
+ }
6590
+
6591
+ if (e + eBias >= eMax) {
6592
+ m = 0;
6593
+ e = eMax;
6594
+ } else if (e + eBias >= 1) {
6595
+ m = (value * c - 1) * Math.pow(2, mLen);
6596
+ e = e + eBias;
6597
+ } else {
6598
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
6599
+ e = 0;
6600
+ }
6601
+ }
6602
+
6603
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6604
+
6605
+ e = (e << mLen) | m;
6606
+ eLen += mLen;
6607
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6608
+
6609
+ buffer[offset + i - d] |= s * 128;
6610
+ }
6611
+
6612
+ var toString = {}.toString;
6613
+
6614
+ var isArray = Array.isArray || function (arr) {
6615
+ return toString.call(arr) == '[object Array]';
6616
+ };
6617
+
6618
+ /*!
6619
+ * The buffer module from node.js, for the browser.
6620
+ *
6621
+ * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
6622
+ * @license MIT
6623
+ */
6624
+
6625
+ var INSPECT_MAX_BYTES = 50;
6626
+
6627
+ /**
6628
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
6629
+ * === true Use Uint8Array implementation (fastest)
6630
+ * === false Use Object implementation (most compatible, even IE6)
6631
+ *
6632
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6633
+ * Opera 11.6+, iOS 4.2+.
6634
+ *
6635
+ * Due to various browser bugs, sometimes the Object implementation will be used even
6636
+ * when the browser supports typed arrays.
6637
+ *
6638
+ * Note:
6639
+ *
6640
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
6641
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
6642
+ *
6643
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
6644
+ *
6645
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
6646
+ * incorrect length in some situations.
6647
+
6648
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
6649
+ * get the Object implementation, which is slower but behaves correctly.
6650
+ */
6651
+ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
6652
+ ? global$1.TYPED_ARRAY_SUPPORT
6653
+ : true;
6654
+
6655
+ function kMaxLength () {
6656
+ return Buffer.TYPED_ARRAY_SUPPORT
6657
+ ? 0x7fffffff
6658
+ : 0x3fffffff
6659
+ }
6660
+
6661
+ function createBuffer (that, length) {
6662
+ if (kMaxLength() < length) {
6663
+ throw new RangeError('Invalid typed array length')
6664
+ }
6665
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6666
+ // Return an augmented `Uint8Array` instance, for best performance
6667
+ that = new Uint8Array(length);
6668
+ that.__proto__ = Buffer.prototype;
6669
+ } else {
6670
+ // Fallback: Return an object instance of the Buffer class
6671
+ if (that === null) {
6672
+ that = new Buffer(length);
6673
+ }
6674
+ that.length = length;
6675
+ }
6676
+
6677
+ return that
6678
+ }
6679
+
6680
+ /**
6681
+ * The Buffer constructor returns instances of `Uint8Array` that have their
6682
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
6683
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
6684
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
6685
+ * returns a single octet.
6686
+ *
6687
+ * The `Uint8Array` prototype remains unmodified.
6688
+ */
6689
+
6690
+ function Buffer (arg, encodingOrOffset, length) {
6691
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
6692
+ return new Buffer(arg, encodingOrOffset, length)
6693
+ }
6694
+
6695
+ // Common case.
6696
+ if (typeof arg === 'number') {
6697
+ if (typeof encodingOrOffset === 'string') {
6698
+ throw new Error(
6699
+ 'If encoding is specified then the first argument must be a string'
6700
+ )
6701
+ }
6702
+ return allocUnsafe(this, arg)
6703
+ }
6704
+ return from(this, arg, encodingOrOffset, length)
6705
+ }
6706
+
6707
+ Buffer.poolSize = 8192; // not used by this implementation
6708
+
6709
+ // TODO: Legacy, not needed anymore. Remove in next major version.
6710
+ Buffer._augment = function (arr) {
6711
+ arr.__proto__ = Buffer.prototype;
6712
+ return arr
6713
+ };
6714
+
6715
+ function from (that, value, encodingOrOffset, length) {
6716
+ if (typeof value === 'number') {
6717
+ throw new TypeError('"value" argument must not be a number')
6718
+ }
6719
+
6720
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
6721
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
6722
+ }
6723
+
6724
+ if (typeof value === 'string') {
6725
+ return fromString(that, value, encodingOrOffset)
6726
+ }
6727
+
6728
+ return fromObject(that, value)
6729
+ }
6730
+
6731
+ /**
6732
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
6733
+ * if value is a number.
6734
+ * Buffer.from(str[, encoding])
6735
+ * Buffer.from(array)
6736
+ * Buffer.from(buffer)
6737
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
6738
+ **/
6739
+ Buffer.from = function (value, encodingOrOffset, length) {
6740
+ return from(null, value, encodingOrOffset, length)
6741
+ };
6742
+
6743
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6744
+ Buffer.prototype.__proto__ = Uint8Array.prototype;
6745
+ Buffer.__proto__ = Uint8Array;
6746
+ }
6747
+
6748
+ function assertSize (size) {
6749
+ if (typeof size !== 'number') {
6750
+ throw new TypeError('"size" argument must be a number')
6751
+ } else if (size < 0) {
6752
+ throw new RangeError('"size" argument must not be negative')
6753
+ }
6754
+ }
6755
+
6756
+ function alloc (that, size, fill, encoding) {
6757
+ assertSize(size);
6758
+ if (size <= 0) {
6759
+ return createBuffer(that, size)
6760
+ }
6761
+ if (fill !== undefined) {
6762
+ // Only pay attention to encoding if it's a string. This
6763
+ // prevents accidentally sending in a number that would
6764
+ // be interpretted as a start offset.
6765
+ return typeof encoding === 'string'
6766
+ ? createBuffer(that, size).fill(fill, encoding)
6767
+ : createBuffer(that, size).fill(fill)
6768
+ }
6769
+ return createBuffer(that, size)
6770
+ }
6771
+
6772
+ /**
6773
+ * Creates a new filled Buffer instance.
6774
+ * alloc(size[, fill[, encoding]])
6775
+ **/
6776
+ Buffer.alloc = function (size, fill, encoding) {
6777
+ return alloc(null, size, fill, encoding)
6778
+ };
6779
+
6780
+ function allocUnsafe (that, size) {
6781
+ assertSize(size);
6782
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
6783
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
6784
+ for (var i = 0; i < size; ++i) {
6785
+ that[i] = 0;
6786
+ }
6787
+ }
6788
+ return that
6789
+ }
6790
+
6791
+ /**
6792
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
6793
+ * */
6794
+ Buffer.allocUnsafe = function (size) {
6795
+ return allocUnsafe(null, size)
6796
+ };
6797
+ /**
6798
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
6799
+ */
6800
+ Buffer.allocUnsafeSlow = function (size) {
6801
+ return allocUnsafe(null, size)
6802
+ };
6803
+
6804
+ function fromString (that, string, encoding) {
6805
+ if (typeof encoding !== 'string' || encoding === '') {
6806
+ encoding = 'utf8';
6807
+ }
6808
+
6809
+ if (!Buffer.isEncoding(encoding)) {
6810
+ throw new TypeError('"encoding" must be a valid string encoding')
6811
+ }
6812
+
6813
+ var length = byteLength(string, encoding) | 0;
6814
+ that = createBuffer(that, length);
6815
+
6816
+ var actual = that.write(string, encoding);
6817
+
6818
+ if (actual !== length) {
6819
+ // Writing a hex string, for example, that contains invalid characters will
6820
+ // cause everything after the first invalid character to be ignored. (e.g.
6821
+ // 'abxxcd' will be treated as 'ab')
6822
+ that = that.slice(0, actual);
6823
+ }
6824
+
6825
+ return that
6826
+ }
6827
+
6828
+ function fromArrayLike (that, array) {
6829
+ var length = array.length < 0 ? 0 : checked(array.length) | 0;
6830
+ that = createBuffer(that, length);
6831
+ for (var i = 0; i < length; i += 1) {
6832
+ that[i] = array[i] & 255;
6833
+ }
6834
+ return that
6835
+ }
6836
+
6837
+ function fromArrayBuffer (that, array, byteOffset, length) {
6838
+
6839
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
6840
+ throw new RangeError('\'offset\' is out of bounds')
6841
+ }
6842
+
6843
+ if (array.byteLength < byteOffset + (length || 0)) {
6844
+ throw new RangeError('\'length\' is out of bounds')
6845
+ }
6846
+
6847
+ if (byteOffset === undefined && length === undefined) {
6848
+ array = new Uint8Array(array);
6849
+ } else if (length === undefined) {
6850
+ array = new Uint8Array(array, byteOffset);
6851
+ } else {
6852
+ array = new Uint8Array(array, byteOffset, length);
6853
+ }
6854
+
6855
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6856
+ // Return an augmented `Uint8Array` instance, for best performance
6857
+ that = array;
6858
+ that.__proto__ = Buffer.prototype;
6859
+ } else {
6860
+ // Fallback: Return an object instance of the Buffer class
6861
+ that = fromArrayLike(that, array);
6862
+ }
6863
+ return that
6864
+ }
6865
+
6866
+ function fromObject (that, obj) {
6867
+ if (internalIsBuffer(obj)) {
6868
+ var len = checked(obj.length) | 0;
6869
+ that = createBuffer(that, len);
6870
+
6871
+ if (that.length === 0) {
6872
+ return that
6873
+ }
6874
+
6875
+ obj.copy(that, 0, 0, len);
6876
+ return that
6877
+ }
6878
+
6879
+ if (obj) {
6880
+ if ((typeof ArrayBuffer !== 'undefined' &&
6881
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
6882
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
6883
+ return createBuffer(that, 0)
6884
+ }
6885
+ return fromArrayLike(that, obj)
6886
+ }
6887
+
6888
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
6889
+ return fromArrayLike(that, obj.data)
6890
+ }
6891
+ }
6892
+
6893
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
6894
+ }
6895
+
6896
+ function checked (length) {
6897
+ // Note: cannot use `length < kMaxLength()` here because that fails when
6898
+ // length is NaN (which is otherwise coerced to zero.)
6899
+ if (length >= kMaxLength()) {
6900
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
6901
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
6902
+ }
6903
+ return length | 0
6904
+ }
6905
+ Buffer.isBuffer = isBuffer;
6906
+ function internalIsBuffer (b) {
6907
+ return !!(b != null && b._isBuffer)
6908
+ }
6909
+
6910
+ Buffer.compare = function compare (a, b) {
6911
+ if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
6912
+ throw new TypeError('Arguments must be Buffers')
6913
+ }
6914
+
6915
+ if (a === b) return 0
6916
+
6917
+ var x = a.length;
6918
+ var y = b.length;
6919
+
6920
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
6921
+ if (a[i] !== b[i]) {
6922
+ x = a[i];
6923
+ y = b[i];
6924
+ break
6925
+ }
6926
+ }
6927
+
6928
+ if (x < y) return -1
6929
+ if (y < x) return 1
6930
+ return 0
6931
+ };
6932
+
6933
+ Buffer.isEncoding = function isEncoding (encoding) {
6934
+ switch (String(encoding).toLowerCase()) {
6935
+ case 'hex':
6936
+ case 'utf8':
6937
+ case 'utf-8':
6938
+ case 'ascii':
6939
+ case 'latin1':
6940
+ case 'binary':
6941
+ case 'base64':
6942
+ case 'ucs2':
6943
+ case 'ucs-2':
6944
+ case 'utf16le':
6945
+ case 'utf-16le':
6946
+ return true
6947
+ default:
6948
+ return false
6949
+ }
6950
+ };
6951
+
6952
+ Buffer.concat = function concat (list, length) {
6953
+ if (!isArray(list)) {
6954
+ throw new TypeError('"list" argument must be an Array of Buffers')
6955
+ }
6956
+
6957
+ if (list.length === 0) {
6958
+ return Buffer.alloc(0)
6959
+ }
6960
+
6961
+ var i;
6962
+ if (length === undefined) {
6963
+ length = 0;
6964
+ for (i = 0; i < list.length; ++i) {
6965
+ length += list[i].length;
6966
+ }
6967
+ }
6968
+
6969
+ var buffer = Buffer.allocUnsafe(length);
6970
+ var pos = 0;
6971
+ for (i = 0; i < list.length; ++i) {
6972
+ var buf = list[i];
6973
+ if (!internalIsBuffer(buf)) {
6974
+ throw new TypeError('"list" argument must be an Array of Buffers')
6975
+ }
6976
+ buf.copy(buffer, pos);
6977
+ pos += buf.length;
6978
+ }
6979
+ return buffer
6980
+ };
6981
+
6982
+ function byteLength (string, encoding) {
6983
+ if (internalIsBuffer(string)) {
6984
+ return string.length
6985
+ }
6986
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
6987
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
6988
+ return string.byteLength
6989
+ }
6990
+ if (typeof string !== 'string') {
6991
+ string = '' + string;
6992
+ }
6993
+
6994
+ var len = string.length;
6995
+ if (len === 0) return 0
6996
+
6997
+ // Use a for loop to avoid recursion
6998
+ var loweredCase = false;
6999
+ for (;;) {
7000
+ switch (encoding) {
7001
+ case 'ascii':
7002
+ case 'latin1':
7003
+ case 'binary':
7004
+ return len
7005
+ case 'utf8':
7006
+ case 'utf-8':
7007
+ case undefined:
7008
+ return utf8ToBytes(string).length
7009
+ case 'ucs2':
7010
+ case 'ucs-2':
7011
+ case 'utf16le':
7012
+ case 'utf-16le':
7013
+ return len * 2
7014
+ case 'hex':
7015
+ return len >>> 1
7016
+ case 'base64':
7017
+ return base64ToBytes(string).length
7018
+ default:
7019
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
7020
+ encoding = ('' + encoding).toLowerCase();
7021
+ loweredCase = true;
7022
+ }
7023
+ }
7024
+ }
7025
+ Buffer.byteLength = byteLength;
7026
+
7027
+ function slowToString (encoding, start, end) {
7028
+ var loweredCase = false;
7029
+
7030
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7031
+ // property of a typed array.
7032
+
7033
+ // This behaves neither like String nor Uint8Array in that we set start/end
7034
+ // to their upper/lower bounds if the value passed is out of range.
7035
+ // undefined is handled specially as per ECMA-262 6th Edition,
7036
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7037
+ if (start === undefined || start < 0) {
7038
+ start = 0;
7039
+ }
7040
+ // Return early if start > this.length. Done here to prevent potential uint32
7041
+ // coercion fail below.
7042
+ if (start > this.length) {
7043
+ return ''
7044
+ }
7045
+
7046
+ if (end === undefined || end > this.length) {
7047
+ end = this.length;
7048
+ }
7049
+
7050
+ if (end <= 0) {
7051
+ return ''
7052
+ }
7053
+
7054
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
7055
+ end >>>= 0;
7056
+ start >>>= 0;
7057
+
7058
+ if (end <= start) {
7059
+ return ''
7060
+ }
7061
+
7062
+ if (!encoding) encoding = 'utf8';
7063
+
7064
+ while (true) {
7065
+ switch (encoding) {
7066
+ case 'hex':
7067
+ return hexSlice(this, start, end)
7068
+
7069
+ case 'utf8':
7070
+ case 'utf-8':
7071
+ return utf8Slice(this, start, end)
7072
+
7073
+ case 'ascii':
7074
+ return asciiSlice(this, start, end)
7075
+
7076
+ case 'latin1':
7077
+ case 'binary':
7078
+ return latin1Slice(this, start, end)
7079
+
7080
+ case 'base64':
7081
+ return base64Slice(this, start, end)
7082
+
7083
+ case 'ucs2':
7084
+ case 'ucs-2':
7085
+ case 'utf16le':
7086
+ case 'utf-16le':
7087
+ return utf16leSlice(this, start, end)
7088
+
7089
+ default:
7090
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7091
+ encoding = (encoding + '').toLowerCase();
7092
+ loweredCase = true;
7093
+ }
7094
+ }
7095
+ }
7096
+
7097
+ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
7098
+ // Buffer instances.
7099
+ Buffer.prototype._isBuffer = true;
7100
+
7101
+ function swap (b, n, m) {
7102
+ var i = b[n];
7103
+ b[n] = b[m];
7104
+ b[m] = i;
7105
+ }
7106
+
7107
+ Buffer.prototype.swap16 = function swap16 () {
7108
+ var len = this.length;
7109
+ if (len % 2 !== 0) {
7110
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
7111
+ }
7112
+ for (var i = 0; i < len; i += 2) {
7113
+ swap(this, i, i + 1);
7114
+ }
7115
+ return this
7116
+ };
7117
+
7118
+ Buffer.prototype.swap32 = function swap32 () {
7119
+ var len = this.length;
7120
+ if (len % 4 !== 0) {
7121
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
7122
+ }
7123
+ for (var i = 0; i < len; i += 4) {
7124
+ swap(this, i, i + 3);
7125
+ swap(this, i + 1, i + 2);
7126
+ }
7127
+ return this
7128
+ };
7129
+
7130
+ Buffer.prototype.swap64 = function swap64 () {
7131
+ var len = this.length;
7132
+ if (len % 8 !== 0) {
7133
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
7134
+ }
7135
+ for (var i = 0; i < len; i += 8) {
7136
+ swap(this, i, i + 7);
7137
+ swap(this, i + 1, i + 6);
7138
+ swap(this, i + 2, i + 5);
7139
+ swap(this, i + 3, i + 4);
7140
+ }
7141
+ return this
7142
+ };
7143
+
7144
+ Buffer.prototype.toString = function toString () {
7145
+ var length = this.length | 0;
7146
+ if (length === 0) return ''
7147
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
7148
+ return slowToString.apply(this, arguments)
7149
+ };
7150
+
7151
+ Buffer.prototype.equals = function equals (b) {
7152
+ if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
7153
+ if (this === b) return true
7154
+ return Buffer.compare(this, b) === 0
7155
+ };
7156
+
7157
+ Buffer.prototype.inspect = function inspect () {
7158
+ var str = '';
7159
+ var max = INSPECT_MAX_BYTES;
7160
+ if (this.length > 0) {
7161
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
7162
+ if (this.length > max) str += ' ... ';
7163
+ }
7164
+ return '<Buffer ' + str + '>'
7165
+ };
7166
+
7167
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
7168
+ if (!internalIsBuffer(target)) {
7169
+ throw new TypeError('Argument must be a Buffer')
7170
+ }
7171
+
7172
+ if (start === undefined) {
7173
+ start = 0;
7174
+ }
7175
+ if (end === undefined) {
7176
+ end = target ? target.length : 0;
7177
+ }
7178
+ if (thisStart === undefined) {
7179
+ thisStart = 0;
7180
+ }
7181
+ if (thisEnd === undefined) {
7182
+ thisEnd = this.length;
7183
+ }
7184
+
7185
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
7186
+ throw new RangeError('out of range index')
7187
+ }
7188
+
7189
+ if (thisStart >= thisEnd && start >= end) {
7190
+ return 0
7191
+ }
7192
+ if (thisStart >= thisEnd) {
7193
+ return -1
7194
+ }
7195
+ if (start >= end) {
7196
+ return 1
7197
+ }
7198
+
7199
+ start >>>= 0;
7200
+ end >>>= 0;
7201
+ thisStart >>>= 0;
7202
+ thisEnd >>>= 0;
7203
+
7204
+ if (this === target) return 0
7205
+
7206
+ var x = thisEnd - thisStart;
7207
+ var y = end - start;
7208
+ var len = Math.min(x, y);
7209
+
7210
+ var thisCopy = this.slice(thisStart, thisEnd);
7211
+ var targetCopy = target.slice(start, end);
7212
+
7213
+ for (var i = 0; i < len; ++i) {
7214
+ if (thisCopy[i] !== targetCopy[i]) {
7215
+ x = thisCopy[i];
7216
+ y = targetCopy[i];
7217
+ break
7218
+ }
7219
+ }
7220
+
7221
+ if (x < y) return -1
7222
+ if (y < x) return 1
7223
+ return 0
7224
+ };
7225
+
7226
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7227
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7228
+ //
7229
+ // Arguments:
7230
+ // - buffer - a Buffer to search
7231
+ // - val - a string, Buffer, or number
7232
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
7233
+ // - encoding - an optional encoding, relevant is val is a string
7234
+ // - dir - true for indexOf, false for lastIndexOf
7235
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7236
+ // Empty buffer means no match
7237
+ if (buffer.length === 0) return -1
7238
+
7239
+ // Normalize byteOffset
7240
+ if (typeof byteOffset === 'string') {
7241
+ encoding = byteOffset;
7242
+ byteOffset = 0;
7243
+ } else if (byteOffset > 0x7fffffff) {
7244
+ byteOffset = 0x7fffffff;
7245
+ } else if (byteOffset < -0x80000000) {
7246
+ byteOffset = -0x80000000;
7247
+ }
7248
+ byteOffset = +byteOffset; // Coerce to Number.
7249
+ if (isNaN(byteOffset)) {
7250
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7251
+ byteOffset = dir ? 0 : (buffer.length - 1);
7252
+ }
7253
+
7254
+ // Normalize byteOffset: negative offsets start from the end of the buffer
7255
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
7256
+ if (byteOffset >= buffer.length) {
7257
+ if (dir) return -1
7258
+ else byteOffset = buffer.length - 1;
7259
+ } else if (byteOffset < 0) {
7260
+ if (dir) byteOffset = 0;
7261
+ else return -1
7262
+ }
7263
+
7264
+ // Normalize val
7265
+ if (typeof val === 'string') {
7266
+ val = Buffer.from(val, encoding);
7267
+ }
7268
+
7269
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
7270
+ if (internalIsBuffer(val)) {
7271
+ // Special case: looking for empty string/buffer always fails
7272
+ if (val.length === 0) {
7273
+ return -1
7274
+ }
7275
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7276
+ } else if (typeof val === 'number') {
7277
+ val = val & 0xFF; // Search for a byte value [0-255]
7278
+ if (Buffer.TYPED_ARRAY_SUPPORT &&
7279
+ typeof Uint8Array.prototype.indexOf === 'function') {
7280
+ if (dir) {
7281
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7282
+ } else {
7283
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7284
+ }
7285
+ }
7286
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
7287
+ }
7288
+
7289
+ throw new TypeError('val must be string, number or Buffer')
7290
+ }
7291
+
7292
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7293
+ var indexSize = 1;
7294
+ var arrLength = arr.length;
7295
+ var valLength = val.length;
7296
+
7297
+ if (encoding !== undefined) {
7298
+ encoding = String(encoding).toLowerCase();
7299
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7300
+ encoding === 'utf16le' || encoding === 'utf-16le') {
7301
+ if (arr.length < 2 || val.length < 2) {
7302
+ return -1
7303
+ }
7304
+ indexSize = 2;
7305
+ arrLength /= 2;
7306
+ valLength /= 2;
7307
+ byteOffset /= 2;
7308
+ }
7309
+ }
7310
+
7311
+ function read (buf, i) {
7312
+ if (indexSize === 1) {
7313
+ return buf[i]
7314
+ } else {
7315
+ return buf.readUInt16BE(i * indexSize)
7316
+ }
7317
+ }
7318
+
7319
+ var i;
7320
+ if (dir) {
7321
+ var foundIndex = -1;
7322
+ for (i = byteOffset; i < arrLength; i++) {
7323
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7324
+ if (foundIndex === -1) foundIndex = i;
7325
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7326
+ } else {
7327
+ if (foundIndex !== -1) i -= i - foundIndex;
7328
+ foundIndex = -1;
7329
+ }
7330
+ }
7331
+ } else {
7332
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
7333
+ for (i = byteOffset; i >= 0; i--) {
7334
+ var found = true;
7335
+ for (var j = 0; j < valLength; j++) {
7336
+ if (read(arr, i + j) !== read(val, j)) {
7337
+ found = false;
7338
+ break
7339
+ }
7340
+ }
7341
+ if (found) return i
7342
+ }
7343
+ }
7344
+
7345
+ return -1
7346
+ }
7347
+
7348
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7349
+ return this.indexOf(val, byteOffset, encoding) !== -1
7350
+ };
7351
+
7352
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7353
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7354
+ };
7355
+
7356
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7357
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7358
+ };
7359
+
7360
+ function hexWrite (buf, string, offset, length) {
7361
+ offset = Number(offset) || 0;
7362
+ var remaining = buf.length - offset;
7363
+ if (!length) {
7364
+ length = remaining;
7365
+ } else {
7366
+ length = Number(length);
7367
+ if (length > remaining) {
7368
+ length = remaining;
7369
+ }
7370
+ }
7371
+
7372
+ // must be an even number of digits
7373
+ var strLen = string.length;
7374
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
7375
+
7376
+ if (length > strLen / 2) {
7377
+ length = strLen / 2;
7378
+ }
7379
+ for (var i = 0; i < length; ++i) {
7380
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
7381
+ if (isNaN(parsed)) return i
7382
+ buf[offset + i] = parsed;
7383
+ }
7384
+ return i
7385
+ }
7386
+
7387
+ function utf8Write (buf, string, offset, length) {
7388
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7389
+ }
7390
+
7391
+ function asciiWrite (buf, string, offset, length) {
7392
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
7393
+ }
7394
+
7395
+ function latin1Write (buf, string, offset, length) {
7396
+ return asciiWrite(buf, string, offset, length)
7397
+ }
7398
+
7399
+ function base64Write (buf, string, offset, length) {
7400
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
7401
+ }
7402
+
7403
+ function ucs2Write (buf, string, offset, length) {
7404
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7405
+ }
7406
+
7407
+ Buffer.prototype.write = function write (string, offset, length, encoding) {
7408
+ // Buffer#write(string)
7409
+ if (offset === undefined) {
7410
+ encoding = 'utf8';
7411
+ length = this.length;
7412
+ offset = 0;
7413
+ // Buffer#write(string, encoding)
7414
+ } else if (length === undefined && typeof offset === 'string') {
7415
+ encoding = offset;
7416
+ length = this.length;
7417
+ offset = 0;
7418
+ // Buffer#write(string, offset[, length][, encoding])
7419
+ } else if (isFinite(offset)) {
7420
+ offset = offset | 0;
7421
+ if (isFinite(length)) {
7422
+ length = length | 0;
7423
+ if (encoding === undefined) encoding = 'utf8';
7424
+ } else {
7425
+ encoding = length;
7426
+ length = undefined;
7427
+ }
7428
+ // legacy write(string, encoding, offset, length) - remove in v0.13
7429
+ } else {
7430
+ throw new Error(
7431
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7432
+ )
7433
+ }
7434
+
7435
+ var remaining = this.length - offset;
7436
+ if (length === undefined || length > remaining) length = remaining;
7437
+
7438
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7439
+ throw new RangeError('Attempt to write outside buffer bounds')
7440
+ }
7441
+
7442
+ if (!encoding) encoding = 'utf8';
7443
+
7444
+ var loweredCase = false;
7445
+ for (;;) {
7446
+ switch (encoding) {
7447
+ case 'hex':
7448
+ return hexWrite(this, string, offset, length)
7449
+
7450
+ case 'utf8':
7451
+ case 'utf-8':
7452
+ return utf8Write(this, string, offset, length)
7453
+
7454
+ case 'ascii':
7455
+ return asciiWrite(this, string, offset, length)
7456
+
7457
+ case 'latin1':
7458
+ case 'binary':
7459
+ return latin1Write(this, string, offset, length)
7460
+
7461
+ case 'base64':
7462
+ // Warning: maxLength not taken into account in base64Write
7463
+ return base64Write(this, string, offset, length)
7464
+
7465
+ case 'ucs2':
7466
+ case 'ucs-2':
7467
+ case 'utf16le':
7468
+ case 'utf-16le':
7469
+ return ucs2Write(this, string, offset, length)
7470
+
7471
+ default:
7472
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7473
+ encoding = ('' + encoding).toLowerCase();
7474
+ loweredCase = true;
7475
+ }
7476
+ }
7477
+ };
7478
+
7479
+ Buffer.prototype.toJSON = function toJSON () {
7480
+ return {
7481
+ type: 'Buffer',
7482
+ data: Array.prototype.slice.call(this._arr || this, 0)
7483
+ }
7484
+ };
7485
+
7486
+ function base64Slice (buf, start, end) {
7487
+ if (start === 0 && end === buf.length) {
7488
+ return fromByteArray(buf)
7489
+ } else {
7490
+ return fromByteArray(buf.slice(start, end))
7491
+ }
7492
+ }
7493
+
7494
+ function utf8Slice (buf, start, end) {
7495
+ end = Math.min(buf.length, end);
7496
+ var res = [];
7497
+
7498
+ var i = start;
7499
+ while (i < end) {
7500
+ var firstByte = buf[i];
7501
+ var codePoint = null;
7502
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
7503
+ : (firstByte > 0xDF) ? 3
7504
+ : (firstByte > 0xBF) ? 2
7505
+ : 1;
7506
+
7507
+ if (i + bytesPerSequence <= end) {
7508
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
7509
+
7510
+ switch (bytesPerSequence) {
7511
+ case 1:
7512
+ if (firstByte < 0x80) {
7513
+ codePoint = firstByte;
7514
+ }
7515
+ break
7516
+ case 2:
7517
+ secondByte = buf[i + 1];
7518
+ if ((secondByte & 0xC0) === 0x80) {
7519
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
7520
+ if (tempCodePoint > 0x7F) {
7521
+ codePoint = tempCodePoint;
7522
+ }
7523
+ }
7524
+ break
7525
+ case 3:
7526
+ secondByte = buf[i + 1];
7527
+ thirdByte = buf[i + 2];
7528
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7529
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
7530
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7531
+ codePoint = tempCodePoint;
7532
+ }
7533
+ }
7534
+ break
7535
+ case 4:
7536
+ secondByte = buf[i + 1];
7537
+ thirdByte = buf[i + 2];
7538
+ fourthByte = buf[i + 3];
7539
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7540
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
7541
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7542
+ codePoint = tempCodePoint;
7543
+ }
7544
+ }
7545
+ }
7546
+ }
7547
+
7548
+ if (codePoint === null) {
7549
+ // we did not generate a valid codePoint so insert a
7550
+ // replacement char (U+FFFD) and advance only 1 byte
7551
+ codePoint = 0xFFFD;
7552
+ bytesPerSequence = 1;
7553
+ } else if (codePoint > 0xFFFF) {
7554
+ // encode to utf16 (surrogate pair dance)
7555
+ codePoint -= 0x10000;
7556
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
7557
+ codePoint = 0xDC00 | codePoint & 0x3FF;
7558
+ }
7559
+
7560
+ res.push(codePoint);
7561
+ i += bytesPerSequence;
7562
+ }
7563
+
7564
+ return decodeCodePointsArray(res)
7565
+ }
7566
+
7567
+ // Based on http://stackoverflow.com/a/22747272/680742, the browser with
7568
+ // the lowest limit is Chrome, with 0x10000 args.
7569
+ // We go 1 magnitude less, for safety
7570
+ var MAX_ARGUMENTS_LENGTH = 0x1000;
7571
+
7572
+ function decodeCodePointsArray (codePoints) {
7573
+ var len = codePoints.length;
7574
+ if (len <= MAX_ARGUMENTS_LENGTH) {
7575
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
7576
+ }
7577
+
7578
+ // Decode in chunks to avoid "call stack size exceeded".
7579
+ var res = '';
7580
+ var i = 0;
7581
+ while (i < len) {
7582
+ res += String.fromCharCode.apply(
7583
+ String,
7584
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
7585
+ );
7586
+ }
7587
+ return res
7588
+ }
7589
+
7590
+ function asciiSlice (buf, start, end) {
7591
+ var ret = '';
7592
+ end = Math.min(buf.length, end);
7593
+
7594
+ for (var i = start; i < end; ++i) {
7595
+ ret += String.fromCharCode(buf[i] & 0x7F);
7596
+ }
7597
+ return ret
7598
+ }
7599
+
7600
+ function latin1Slice (buf, start, end) {
7601
+ var ret = '';
7602
+ end = Math.min(buf.length, end);
7603
+
7604
+ for (var i = start; i < end; ++i) {
7605
+ ret += String.fromCharCode(buf[i]);
7606
+ }
7607
+ return ret
7608
+ }
7609
+
7610
+ function hexSlice (buf, start, end) {
7611
+ var len = buf.length;
7612
+
7613
+ if (!start || start < 0) start = 0;
7614
+ if (!end || end < 0 || end > len) end = len;
7615
+
7616
+ var out = '';
7617
+ for (var i = start; i < end; ++i) {
7618
+ out += toHex(buf[i]);
7619
+ }
7620
+ return out
7621
+ }
7622
+
7623
+ function utf16leSlice (buf, start, end) {
7624
+ var bytes = buf.slice(start, end);
7625
+ var res = '';
7626
+ for (var i = 0; i < bytes.length; i += 2) {
7627
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
7628
+ }
7629
+ return res
7630
+ }
7631
+
7632
+ Buffer.prototype.slice = function slice (start, end) {
7633
+ var len = this.length;
7634
+ start = ~~start;
7635
+ end = end === undefined ? len : ~~end;
7636
+
7637
+ if (start < 0) {
7638
+ start += len;
7639
+ if (start < 0) start = 0;
7640
+ } else if (start > len) {
7641
+ start = len;
7642
+ }
7643
+
7644
+ if (end < 0) {
7645
+ end += len;
7646
+ if (end < 0) end = 0;
7647
+ } else if (end > len) {
7648
+ end = len;
7649
+ }
7650
+
7651
+ if (end < start) end = start;
7652
+
7653
+ var newBuf;
7654
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7655
+ newBuf = this.subarray(start, end);
7656
+ newBuf.__proto__ = Buffer.prototype;
7657
+ } else {
7658
+ var sliceLen = end - start;
7659
+ newBuf = new Buffer(sliceLen, undefined);
7660
+ for (var i = 0; i < sliceLen; ++i) {
7661
+ newBuf[i] = this[i + start];
7662
+ }
7663
+ }
7664
+
7665
+ return newBuf
7666
+ };
7667
+
7668
+ /*
7669
+ * Need to make sure that buffer isn't trying to write out of bounds.
7670
+ */
7671
+ function checkOffset (offset, ext, length) {
7672
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
7673
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
7674
+ }
7675
+
7676
+ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
7677
+ offset = offset | 0;
7678
+ byteLength = byteLength | 0;
7679
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7680
+
7681
+ var val = this[offset];
7682
+ var mul = 1;
7683
+ var i = 0;
7684
+ while (++i < byteLength && (mul *= 0x100)) {
7685
+ val += this[offset + i] * mul;
7686
+ }
7687
+
7688
+ return val
7689
+ };
7690
+
7691
+ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
7692
+ offset = offset | 0;
7693
+ byteLength = byteLength | 0;
7694
+ if (!noAssert) {
7695
+ checkOffset(offset, byteLength, this.length);
7696
+ }
7697
+
7698
+ var val = this[offset + --byteLength];
7699
+ var mul = 1;
7700
+ while (byteLength > 0 && (mul *= 0x100)) {
7701
+ val += this[offset + --byteLength] * mul;
7702
+ }
7703
+
7704
+ return val
7705
+ };
7706
+
7707
+ Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
7708
+ if (!noAssert) checkOffset(offset, 1, this.length);
7709
+ return this[offset]
7710
+ };
7711
+
7712
+ Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
7713
+ if (!noAssert) checkOffset(offset, 2, this.length);
7714
+ return this[offset] | (this[offset + 1] << 8)
7715
+ };
7716
+
7717
+ Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
7718
+ if (!noAssert) checkOffset(offset, 2, this.length);
7719
+ return (this[offset] << 8) | this[offset + 1]
7720
+ };
7721
+
7722
+ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
7723
+ if (!noAssert) checkOffset(offset, 4, this.length);
7724
+
7725
+ return ((this[offset]) |
7726
+ (this[offset + 1] << 8) |
7727
+ (this[offset + 2] << 16)) +
7728
+ (this[offset + 3] * 0x1000000)
7729
+ };
7730
+
7731
+ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
7732
+ if (!noAssert) checkOffset(offset, 4, this.length);
7733
+
7734
+ return (this[offset] * 0x1000000) +
7735
+ ((this[offset + 1] << 16) |
7736
+ (this[offset + 2] << 8) |
7737
+ this[offset + 3])
7738
+ };
7739
+
7740
+ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
7741
+ offset = offset | 0;
7742
+ byteLength = byteLength | 0;
7743
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7744
+
7745
+ var val = this[offset];
7746
+ var mul = 1;
7747
+ var i = 0;
7748
+ while (++i < byteLength && (mul *= 0x100)) {
7749
+ val += this[offset + i] * mul;
7750
+ }
7751
+ mul *= 0x80;
7752
+
7753
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
7754
+
7755
+ return val
7756
+ };
7757
+
7758
+ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
7759
+ offset = offset | 0;
7760
+ byteLength = byteLength | 0;
7761
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7762
+
7763
+ var i = byteLength;
7764
+ var mul = 1;
7765
+ var val = this[offset + --i];
7766
+ while (i > 0 && (mul *= 0x100)) {
7767
+ val += this[offset + --i] * mul;
7768
+ }
7769
+ mul *= 0x80;
7770
+
7771
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
7772
+
7773
+ return val
7774
+ };
7775
+
7776
+ Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
7777
+ if (!noAssert) checkOffset(offset, 1, this.length);
7778
+ if (!(this[offset] & 0x80)) return (this[offset])
7779
+ return ((0xff - this[offset] + 1) * -1)
7780
+ };
7781
+
7782
+ Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
7783
+ if (!noAssert) checkOffset(offset, 2, this.length);
7784
+ var val = this[offset] | (this[offset + 1] << 8);
7785
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
7786
+ };
7787
+
7788
+ Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
7789
+ if (!noAssert) checkOffset(offset, 2, this.length);
7790
+ var val = this[offset + 1] | (this[offset] << 8);
7791
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
7792
+ };
7793
+
7794
+ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
7795
+ if (!noAssert) checkOffset(offset, 4, this.length);
7796
+
7797
+ return (this[offset]) |
7798
+ (this[offset + 1] << 8) |
7799
+ (this[offset + 2] << 16) |
7800
+ (this[offset + 3] << 24)
7801
+ };
7802
+
7803
+ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
7804
+ if (!noAssert) checkOffset(offset, 4, this.length);
7805
+
7806
+ return (this[offset] << 24) |
7807
+ (this[offset + 1] << 16) |
7808
+ (this[offset + 2] << 8) |
7809
+ (this[offset + 3])
7810
+ };
7811
+
7812
+ Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
7813
+ if (!noAssert) checkOffset(offset, 4, this.length);
7814
+ return read(this, offset, true, 23, 4)
7815
+ };
7816
+
7817
+ Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
7818
+ if (!noAssert) checkOffset(offset, 4, this.length);
7819
+ return read(this, offset, false, 23, 4)
7820
+ };
7821
+
7822
+ Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
7823
+ if (!noAssert) checkOffset(offset, 8, this.length);
7824
+ return read(this, offset, true, 52, 8)
7825
+ };
7826
+
7827
+ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
7828
+ if (!noAssert) checkOffset(offset, 8, this.length);
7829
+ return read(this, offset, false, 52, 8)
7830
+ };
7831
+
7832
+ function checkInt (buf, value, offset, ext, max, min) {
7833
+ if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
7834
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
7835
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
7836
+ }
7837
+
7838
+ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
7839
+ value = +value;
7840
+ offset = offset | 0;
7841
+ byteLength = byteLength | 0;
7842
+ if (!noAssert) {
7843
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
7844
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
7845
+ }
7846
+
7847
+ var mul = 1;
7848
+ var i = 0;
7849
+ this[offset] = value & 0xFF;
7850
+ while (++i < byteLength && (mul *= 0x100)) {
7851
+ this[offset + i] = (value / mul) & 0xFF;
7852
+ }
7853
+
7854
+ return offset + byteLength
7855
+ };
7856
+
7857
+ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
7858
+ value = +value;
7859
+ offset = offset | 0;
7860
+ byteLength = byteLength | 0;
7861
+ if (!noAssert) {
7862
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
7863
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
7864
+ }
7865
+
7866
+ var i = byteLength - 1;
7867
+ var mul = 1;
7868
+ this[offset + i] = value & 0xFF;
7869
+ while (--i >= 0 && (mul *= 0x100)) {
7870
+ this[offset + i] = (value / mul) & 0xFF;
7871
+ }
7872
+
7873
+ return offset + byteLength
7874
+ };
7875
+
7876
+ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
7877
+ value = +value;
7878
+ offset = offset | 0;
7879
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
7880
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
7881
+ this[offset] = (value & 0xff);
7882
+ return offset + 1
7883
+ };
7884
+
7885
+ function objectWriteUInt16 (buf, value, offset, littleEndian) {
7886
+ if (value < 0) value = 0xffff + value + 1;
7887
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
7888
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
7889
+ (littleEndian ? i : 1 - i) * 8;
7890
+ }
7891
+ }
7892
+
7893
+ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
7894
+ value = +value;
7895
+ offset = offset | 0;
7896
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
7897
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7898
+ this[offset] = (value & 0xff);
7899
+ this[offset + 1] = (value >>> 8);
7900
+ } else {
7901
+ objectWriteUInt16(this, value, offset, true);
7902
+ }
7903
+ return offset + 2
7904
+ };
7905
+
7906
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
7907
+ value = +value;
7908
+ offset = offset | 0;
7909
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
7910
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7911
+ this[offset] = (value >>> 8);
7912
+ this[offset + 1] = (value & 0xff);
7913
+ } else {
7914
+ objectWriteUInt16(this, value, offset, false);
7915
+ }
7916
+ return offset + 2
7917
+ };
7918
+
7919
+ function objectWriteUInt32 (buf, value, offset, littleEndian) {
7920
+ if (value < 0) value = 0xffffffff + value + 1;
7921
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
7922
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
7923
+ }
7924
+ }
7925
+
7926
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
7927
+ value = +value;
7928
+ offset = offset | 0;
7929
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
7930
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7931
+ this[offset + 3] = (value >>> 24);
7932
+ this[offset + 2] = (value >>> 16);
7933
+ this[offset + 1] = (value >>> 8);
7934
+ this[offset] = (value & 0xff);
7935
+ } else {
7936
+ objectWriteUInt32(this, value, offset, true);
7937
+ }
7938
+ return offset + 4
7939
+ };
7940
+
7941
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
7942
+ value = +value;
7943
+ offset = offset | 0;
7944
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
7945
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7946
+ this[offset] = (value >>> 24);
7947
+ this[offset + 1] = (value >>> 16);
7948
+ this[offset + 2] = (value >>> 8);
7949
+ this[offset + 3] = (value & 0xff);
7950
+ } else {
7951
+ objectWriteUInt32(this, value, offset, false);
7952
+ }
7953
+ return offset + 4
7954
+ };
7955
+
7956
+ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
7957
+ value = +value;
7958
+ offset = offset | 0;
7959
+ if (!noAssert) {
7960
+ var limit = Math.pow(2, 8 * byteLength - 1);
7961
+
7962
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
7963
+ }
7964
+
7965
+ var i = 0;
7966
+ var mul = 1;
7967
+ var sub = 0;
7968
+ this[offset] = value & 0xFF;
7969
+ while (++i < byteLength && (mul *= 0x100)) {
7970
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
7971
+ sub = 1;
7972
+ }
7973
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
7974
+ }
7975
+
7976
+ return offset + byteLength
7977
+ };
7978
+
7979
+ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
7980
+ value = +value;
7981
+ offset = offset | 0;
7982
+ if (!noAssert) {
7983
+ var limit = Math.pow(2, 8 * byteLength - 1);
7984
+
7985
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
7986
+ }
7987
+
7988
+ var i = byteLength - 1;
7989
+ var mul = 1;
7990
+ var sub = 0;
7991
+ this[offset + i] = value & 0xFF;
7992
+ while (--i >= 0 && (mul *= 0x100)) {
7993
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
7994
+ sub = 1;
7995
+ }
7996
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
7997
+ }
7998
+
7999
+ return offset + byteLength
8000
+ };
8001
+
8002
+ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8003
+ value = +value;
8004
+ offset = offset | 0;
8005
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
8006
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
8007
+ if (value < 0) value = 0xff + value + 1;
8008
+ this[offset] = (value & 0xff);
8009
+ return offset + 1
8010
+ };
8011
+
8012
+ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8013
+ value = +value;
8014
+ offset = offset | 0;
8015
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
8016
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8017
+ this[offset] = (value & 0xff);
8018
+ this[offset + 1] = (value >>> 8);
8019
+ } else {
8020
+ objectWriteUInt16(this, value, offset, true);
8021
+ }
8022
+ return offset + 2
8023
+ };
8024
+
8025
+ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8026
+ value = +value;
8027
+ offset = offset | 0;
8028
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
8029
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8030
+ this[offset] = (value >>> 8);
8031
+ this[offset + 1] = (value & 0xff);
8032
+ } else {
8033
+ objectWriteUInt16(this, value, offset, false);
8034
+ }
8035
+ return offset + 2
8036
+ };
8037
+
8038
+ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8039
+ value = +value;
8040
+ offset = offset | 0;
8041
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
8042
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8043
+ this[offset] = (value & 0xff);
8044
+ this[offset + 1] = (value >>> 8);
8045
+ this[offset + 2] = (value >>> 16);
8046
+ this[offset + 3] = (value >>> 24);
8047
+ } else {
8048
+ objectWriteUInt32(this, value, offset, true);
8049
+ }
8050
+ return offset + 4
8051
+ };
8052
+
8053
+ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8054
+ value = +value;
8055
+ offset = offset | 0;
8056
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
8057
+ if (value < 0) value = 0xffffffff + value + 1;
8058
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8059
+ this[offset] = (value >>> 24);
8060
+ this[offset + 1] = (value >>> 16);
8061
+ this[offset + 2] = (value >>> 8);
8062
+ this[offset + 3] = (value & 0xff);
8063
+ } else {
8064
+ objectWriteUInt32(this, value, offset, false);
8065
+ }
8066
+ return offset + 4
8067
+ };
8068
+
8069
+ function checkIEEE754 (buf, value, offset, ext, max, min) {
8070
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
8071
+ if (offset < 0) throw new RangeError('Index out of range')
8072
+ }
8073
+
8074
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
8075
+ if (!noAssert) {
8076
+ checkIEEE754(buf, value, offset, 4);
8077
+ }
8078
+ write(buf, value, offset, littleEndian, 23, 4);
8079
+ return offset + 4
8080
+ }
8081
+
8082
+ Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8083
+ return writeFloat(this, value, offset, true, noAssert)
8084
+ };
8085
+
8086
+ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8087
+ return writeFloat(this, value, offset, false, noAssert)
8088
+ };
8089
+
8090
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
8091
+ if (!noAssert) {
8092
+ checkIEEE754(buf, value, offset, 8);
8093
+ }
8094
+ write(buf, value, offset, littleEndian, 52, 8);
8095
+ return offset + 8
8096
+ }
8097
+
8098
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
8099
+ return writeDouble(this, value, offset, true, noAssert)
8100
+ };
8101
+
8102
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
8103
+ return writeDouble(this, value, offset, false, noAssert)
8104
+ };
8105
+
8106
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8107
+ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8108
+ if (!start) start = 0;
8109
+ if (!end && end !== 0) end = this.length;
8110
+ if (targetStart >= target.length) targetStart = target.length;
8111
+ if (!targetStart) targetStart = 0;
8112
+ if (end > 0 && end < start) end = start;
8113
+
8114
+ // Copy 0 bytes; we're done
8115
+ if (end === start) return 0
8116
+ if (target.length === 0 || this.length === 0) return 0
8117
+
8118
+ // Fatal error conditions
8119
+ if (targetStart < 0) {
8120
+ throw new RangeError('targetStart out of bounds')
8121
+ }
8122
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
8123
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
8124
+
8125
+ // Are we oob?
8126
+ if (end > this.length) end = this.length;
8127
+ if (target.length - targetStart < end - start) {
8128
+ end = target.length - targetStart + start;
8129
+ }
8130
+
8131
+ var len = end - start;
8132
+ var i;
8133
+
8134
+ if (this === target && start < targetStart && targetStart < end) {
8135
+ // descending copy from end
8136
+ for (i = len - 1; i >= 0; --i) {
8137
+ target[i + targetStart] = this[i + start];
8138
+ }
8139
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
8140
+ // ascending copy from start
8141
+ for (i = 0; i < len; ++i) {
8142
+ target[i + targetStart] = this[i + start];
8143
+ }
8144
+ } else {
8145
+ Uint8Array.prototype.set.call(
8146
+ target,
8147
+ this.subarray(start, start + len),
8148
+ targetStart
8149
+ );
8150
+ }
8151
+
8152
+ return len
8153
+ };
8154
+
8155
+ // Usage:
8156
+ // buffer.fill(number[, offset[, end]])
8157
+ // buffer.fill(buffer[, offset[, end]])
8158
+ // buffer.fill(string[, offset[, end]][, encoding])
8159
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
8160
+ // Handle string cases:
8161
+ if (typeof val === 'string') {
8162
+ if (typeof start === 'string') {
8163
+ encoding = start;
8164
+ start = 0;
8165
+ end = this.length;
8166
+ } else if (typeof end === 'string') {
8167
+ encoding = end;
8168
+ end = this.length;
8169
+ }
8170
+ if (val.length === 1) {
8171
+ var code = val.charCodeAt(0);
8172
+ if (code < 256) {
8173
+ val = code;
8174
+ }
8175
+ }
8176
+ if (encoding !== undefined && typeof encoding !== 'string') {
8177
+ throw new TypeError('encoding must be a string')
8178
+ }
8179
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8180
+ throw new TypeError('Unknown encoding: ' + encoding)
8181
+ }
8182
+ } else if (typeof val === 'number') {
8183
+ val = val & 255;
8184
+ }
8185
+
8186
+ // Invalid ranges are not set to a default, so can range check early.
8187
+ if (start < 0 || this.length < start || this.length < end) {
8188
+ throw new RangeError('Out of range index')
8189
+ }
8190
+
8191
+ if (end <= start) {
8192
+ return this
8193
+ }
8194
+
8195
+ start = start >>> 0;
8196
+ end = end === undefined ? this.length : end >>> 0;
8197
+
8198
+ if (!val) val = 0;
8199
+
8200
+ var i;
8201
+ if (typeof val === 'number') {
8202
+ for (i = start; i < end; ++i) {
8203
+ this[i] = val;
8204
+ }
8205
+ } else {
8206
+ var bytes = internalIsBuffer(val)
8207
+ ? val
8208
+ : utf8ToBytes(new Buffer(val, encoding).toString());
8209
+ var len = bytes.length;
8210
+ for (i = 0; i < end - start; ++i) {
8211
+ this[i + start] = bytes[i % len];
8212
+ }
8213
+ }
8214
+
8215
+ return this
8216
+ };
8217
+
8218
+ // HELPER FUNCTIONS
8219
+ // ================
8220
+
8221
+ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
8222
+
8223
+ function base64clean (str) {
8224
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
8225
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '');
8226
+ // Node converts strings with length < 2 to ''
8227
+ if (str.length < 2) return ''
8228
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
8229
+ while (str.length % 4 !== 0) {
8230
+ str = str + '=';
8231
+ }
8232
+ return str
8233
+ }
8234
+
8235
+ function stringtrim (str) {
8236
+ if (str.trim) return str.trim()
8237
+ return str.replace(/^\s+|\s+$/g, '')
8238
+ }
8239
+
8240
+ function toHex (n) {
8241
+ if (n < 16) return '0' + n.toString(16)
8242
+ return n.toString(16)
8243
+ }
8244
+
8245
+ function utf8ToBytes (string, units) {
8246
+ units = units || Infinity;
8247
+ var codePoint;
8248
+ var length = string.length;
8249
+ var leadSurrogate = null;
8250
+ var bytes = [];
8251
+
8252
+ for (var i = 0; i < length; ++i) {
8253
+ codePoint = string.charCodeAt(i);
8254
+
8255
+ // is surrogate component
8256
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
8257
+ // last char was a lead
8258
+ if (!leadSurrogate) {
8259
+ // no lead yet
8260
+ if (codePoint > 0xDBFF) {
8261
+ // unexpected trail
8262
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8263
+ continue
8264
+ } else if (i + 1 === length) {
8265
+ // unpaired lead
8266
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8267
+ continue
8268
+ }
8269
+
8270
+ // valid lead
8271
+ leadSurrogate = codePoint;
8272
+
8273
+ continue
8274
+ }
8275
+
8276
+ // 2 leads in a row
8277
+ if (codePoint < 0xDC00) {
8278
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8279
+ leadSurrogate = codePoint;
8280
+ continue
8281
+ }
8282
+
8283
+ // valid surrogate pair
8284
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
8285
+ } else if (leadSurrogate) {
8286
+ // valid bmp char, but last char was a lead
8287
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8288
+ }
8289
+
8290
+ leadSurrogate = null;
8291
+
8292
+ // encode utf8
8293
+ if (codePoint < 0x80) {
8294
+ if ((units -= 1) < 0) break
8295
+ bytes.push(codePoint);
8296
+ } else if (codePoint < 0x800) {
8297
+ if ((units -= 2) < 0) break
8298
+ bytes.push(
8299
+ codePoint >> 0x6 | 0xC0,
8300
+ codePoint & 0x3F | 0x80
8301
+ );
8302
+ } else if (codePoint < 0x10000) {
8303
+ if ((units -= 3) < 0) break
8304
+ bytes.push(
8305
+ codePoint >> 0xC | 0xE0,
8306
+ codePoint >> 0x6 & 0x3F | 0x80,
8307
+ codePoint & 0x3F | 0x80
8308
+ );
8309
+ } else if (codePoint < 0x110000) {
8310
+ if ((units -= 4) < 0) break
8311
+ bytes.push(
8312
+ codePoint >> 0x12 | 0xF0,
8313
+ codePoint >> 0xC & 0x3F | 0x80,
8314
+ codePoint >> 0x6 & 0x3F | 0x80,
8315
+ codePoint & 0x3F | 0x80
8316
+ );
8317
+ } else {
8318
+ throw new Error('Invalid code point')
8319
+ }
8320
+ }
8321
+
8322
+ return bytes
8323
+ }
8324
+
8325
+ function asciiToBytes (str) {
8326
+ var byteArray = [];
8327
+ for (var i = 0; i < str.length; ++i) {
8328
+ // Node's code seems to be doing this and not & 0x7F..
8329
+ byteArray.push(str.charCodeAt(i) & 0xFF);
8330
+ }
8331
+ return byteArray
8332
+ }
8333
+
8334
+ function utf16leToBytes (str, units) {
8335
+ var c, hi, lo;
8336
+ var byteArray = [];
8337
+ for (var i = 0; i < str.length; ++i) {
8338
+ if ((units -= 2) < 0) break
8339
+
8340
+ c = str.charCodeAt(i);
8341
+ hi = c >> 8;
8342
+ lo = c % 256;
8343
+ byteArray.push(lo);
8344
+ byteArray.push(hi);
8345
+ }
8346
+
8347
+ return byteArray
8348
+ }
8349
+
8350
+
8351
+ function base64ToBytes (str) {
8352
+ return toByteArray(base64clean(str))
8353
+ }
8354
+
8355
+ function blitBuffer (src, dst, offset, length) {
8356
+ for (var i = 0; i < length; ++i) {
8357
+ if ((i + offset >= dst.length) || (i >= src.length)) break
8358
+ dst[i + offset] = src[i];
8359
+ }
8360
+ return i
8361
+ }
8362
+
8363
+ function isnan (val) {
8364
+ return val !== val // eslint-disable-line no-self-compare
8365
+ }
8366
+
8367
+
8368
+ // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
8369
+ // The _isBuffer check is for Safari 5-7 support, because it's missing
8370
+ // Object.prototype.constructor. Remove this eventually
8371
+ function isBuffer(obj) {
8372
+ return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
8373
+ }
8374
+
8375
+ function isFastBuffer (obj) {
8376
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
8377
+ }
8378
+
8379
+ // For Node v0.10 support. Remove this eventually.
8380
+ function isSlowBuffer (obj) {
8381
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
8382
+ }
8383
+
6191
8384
  /**
6192
8385
  * Convert a data object to FormData
6193
8386
  * @param {Object} obj
@@ -6736,7 +8929,7 @@ function getDefaultAdapter() {
6736
8929
  if (typeof XMLHttpRequest !== 'undefined') {
6737
8930
  // For browsers use XHR adapter
6738
8931
  adapter = xhr;
6739
- } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
8932
+ } else if (typeof browser$1 !== 'undefined' && Object.prototype.toString.call(browser$1) === '[object process]') {
6740
8933
  // For node use HTTP adapter
6741
8934
  adapter = xhr;
6742
8935
  }
@@ -7513,7 +9706,7 @@ var axios = axios_1;
7513
9706
 
7514
9707
  function e(e){this.message=e;}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="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(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(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
9708
 
7516
- let s=function(e,t,a){return alert(e)},n=function(e,t){return s(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return s(e,t,a)},setNotifier:function(e){s=e,salla.event.emit("twilight::notifier.changed");},error:n,success:function(e,t){return s(e,l.success,t)},info:function(e,t){return s(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,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}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 a,r=this,i=0;i<e.length;i++)a=new RegExp(e[i],"g"),r=r.replace(a,t[i]);return r},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)},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let i=r.querySelectorAll("[name]");if(!i.length)return this.getFilteredData();let s=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,s);s[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(s)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return !1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||a?.dataset||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let i=a?.dataset[r]||this.dataset[r];if(i){var s=window[i];if("function"==typeof s){if(!s(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${i}(formData, element, event)!`;return s(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.comment=new class extends c{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.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();}},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,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...r)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const i=new CustomEvent(t,...r);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.booking=new class extends c{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},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},Salla.config.currency=e=>(e=e||Salla.config.get("user.currency_code"),Salla.config.get("currencies."+e)||Object.values(Salla.config.get("currencies"))[0]);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 r=Array.isArray(e),i=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let s=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 s&&"get"===a&&(t=t?Object.assign(t,s):s),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:s})}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-checkout",createQuickOrder:"checkout/quick-checkout",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("request::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(){let e=await this.getCurrentCartId();return this.request(["details",e]).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let a=salla.form.getPossibleValue(t.payload,["endpoint"]);a&&["addItem","quickAdd"].includes(a)||(a=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let r=await this.getCurrentCartId();return this.request([a,r,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 r=await salla.auth.api.request(["verify",a],e);if(200!==r?.status)return salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r);let i="authenticated"===r.data?.case;return i&&salla.auth.event.tokenFetched(r.data.token),t&&await salla.auth.api.request("auth/jwt"),i&&salla.auth.event.loggedIn(r).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(r,a),salla.api.successPromise(r)}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(()=>{...})`),location.href=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.storage.set("cart",{id:t.data.cart_id,user_id:salla.config.get("user.id")}),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={get:"products/{id}/details",getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",detail:"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"},this.endpointsMethods={detail:"get",giftDetail:"get"},this.after_init();}get(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.api.errorPromise(e)}return this.request(["get",e],{params:{with:t}}).then((function(e){return e})).catch((function(e){throw e}))}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.offer.event.fetchDetailsFailed(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(["detail",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.detailFetchFailed(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),response))).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"]),r=salla.form.getPossibleValue(e,["type"]),i=salla.form.getPossibleValue(e,["comment"]);return a?r&&["products","pages","product","page"].includes(r)?i?(r+=["product","page"].includes(r)?"s":"",this.request(["add",r,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 b 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 F 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),resp}))}}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 E{constructor(t){"ready"!==f$1.status?t?(f$1.config.merge(t),t?.events&&f$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.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.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),r=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,r).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}));}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1];})),a=e;}window[e]?window[e](t,a):salla.event.dispatch(e,t,a);}}setSallaReady(t){f$1.status="ready",f$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}));}}f$1.status="loading",f$1.notify=o,f$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.messages)return void window.addEventListener("load",(e=>{salla.event.dispatch("languages::translations.loaded"),salla.logger.info("The messages of transactions is already loaded");}));if(!salla.url.get(""))return void this.loadScript("https://cdn.salla.network/js/translations.js",!1);let e=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight"));this.loadScript(salla.url.get(`languages/assets/${e}.js`));}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0;}loadScript(e,t=!0){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}get(e,t,a){return window.translations&&(e="trans."+e),super.get(e,t,a)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},f$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.normalRequest(e,a,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop();}));let r=e.split("."),i=r.splice(-1);return await salla.call(r.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 r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},f$1.helpers.app=new class{toggleClassIf(e,t,a,r){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,a,r))),this}toggleElementClassIf(e,t,a,r){t=Array.isArray(t)?t:t.split(" "),a=Array.isArray(a)?a:a.split(" ");let i=r(e);return e?.classList.remove(...i?a:t),e?.classList.add(...i?t:a),this}isValidEmail(e){return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return "object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach((e=>this.watchElement(e[0],e[1]))),this}on(e,t,a,r={}){return "object"==typeof t?(this.element(t).addEventListener(e,a,r),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,a,r))),this)}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,(e=>13===e.keyCode&&t(e))),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e,...t){return this.debounce_||(this.debounce_=Salla.helpers.debounce(((e,...t)=>e(...t)),500)),this.debounce_(e,...t)}},f$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,r){r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),s=r.path;if(!i||!s||"string"==typeof s&&!document.querySelector(s))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,r);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),f$1.api=new class extends class{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);}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a=Salla.config.isGuest(),r=salla.storage.get("cart"),s=e.user?.id,n=salla.storage.get("user.id");if(n&&n!==s&&salla.storage.remove("user"),r&&(r.user_id!==s||r.store_id!==e.store?.id))return salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:e.store?.id}),salla.log("Auth:: The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return;if(a&&t)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.cart.api.reset(),void salla.auth.api.refresh();let l=o$1(t);return Date.now()/1e3>l.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):l.sub!==s?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):(this.setToken(t),void salla.event.emit("request::initiated"))}setToken(e){return this.setHeader("Authorization","Bearer "+e)}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t,a="get",r={}){let i={endPoint:e,payload:t,method:a,options:r},s="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===s?.tagName&&(n=!0),n&&s?.load(),this.axios[i.method](i.endPoint,i.payload,i.options).then((e=>(n&&s?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&s?.stop(),salla.event.document.requestFailed(i,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;dataLayer&&r&&dataLayer.push(r),this.fireEventsForResponse(e),this.showAlert(e),this.renderSections(e);}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach((e=>{let r=t[e];Array.isArray(r)?r.forEach((e=>a.push(e))):a.push(r);}));let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,r)=>t?a(e):r(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}renderSections(e){e.sections&&Object.keys(e.sections).forEach((t=>{document.querySelectorAll(t.toSelector()).forEach((function(a){a.innerHTML=e.sections[t];}));}));}}{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 b,this.document=new F,this.wishlist=new _,this.scope=new q,this.booking=new A;}},f$1.cart=new d(f$1.api.cart,f$1.event.cart),f$1.auth=new d(f$1.api.auth,f$1.event.auth),f$1.order=new d(f$1.api.order,f$1.event.order),f$1.scope=new d(f$1.api.scope,f$1.event.scope),f$1.rating=new d(f$1.api.rating,f$1.event.rating),f$1.comment=new d(f$1.api.comment,f$1.event.comment),f$1.loyalty=new d(f$1.api.loyalty,f$1.event.loyalty),f$1.product=new d(f$1.api.product,f$1.event.product),f$1.profile=new d(f$1.api.profile,f$1.event.profile),f$1.currency=new d(f$1.api.currency,f$1.event.currency),f$1.document=new d(f$1.api.document,f$1.event.document),f$1.wishlist=new d(f$1.api.wishlist,f$1.event.wishlist),f$1.booking=new d(f$1.api.booking,f$1.event.booking),f$1.call=t=>{let a=f$1,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},f$1.init=e=>new E(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t);})),f$1.success=f$1.notify.success,f$1.error=f$1.notify.error,f$1.versions.twilight="[VI]{version}[/VI]",f$1.onInitiated=e=>salla.event.once("twilight::initiated",e),f$1.onReady=f$1.onReady||function(t){"ready"!==salla.status?f$1.onInitiated(t):t(salla.config.all());},window.dispatchEvent(new CustomEvent("salla::created"));
9709
+ let s=function(e,t,a){return alert(e)},n=function(e,t){return s(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return s(e,t,a)},setNotifier:function(e){s=e,salla.event.emit("twilight::notifier.changed");},error:n,success:function(e,t){return s(e,l.success,t)},info:function(e,t){return s(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,r){return "event"===r?t:"api"===r?e:e&&e[r]||a[r]}})}}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 a,r=this,i=0;i<e.length;i++)a=new RegExp(e[i],"g"),r=r.replace(a,t[i]);return r},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)},Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(e){for(var t=this;t;){if(t.matches(e))return t;t=t.parentElement;}}),Element.prototype.getElementSallaData=function(e,...t){if(!this.getAttribute)return;if(this.hasAttribute("data-json"))try{return JSON.parse(this.getAttribute("data-json"))}catch(e){}let a=this.getAttribute("data-function");if(a&&window[a])return "function"==typeof window[a]?this.getFilteredData(window[a].call(this,...t)):this.getFilteredData(window[a]);let r=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(r="FORM"===this.tagName?this:r||this.closest("form")||this.closest("[salla-form-data]")||this,r&&"FORM"===r.tagName)return this.getFilteredData(new FormData(r),null,r);let i=r.querySelectorAll("[name]");if(!i.length)return this.getFilteredData();let s=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,s);s[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(s)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let r=this.attributes[a].name.toLowerCase();if(0===r.indexOf(e))return !t||r}return !1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||a?.dataset||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((r=>{let i=a?.dataset[r]||this.dataset[r];if(i){var s=window[i];if("function"==typeof s){if(!s(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${i}(formData, element, event)!`;return s(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.comment=new class extends c{constructor(){super(),this.namespace="comment",this.events={added:"added",additionFailed:"addition.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();}},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,...r){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...r)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const i=new CustomEvent(t,...r);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.booking=new class extends c{constructor(){super(),this.namespace="booking",this.events={added:"added",additionFailed:"addition.failed"},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 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},Salla.config.currency=e=>(e=e||Salla.config.get("user.currency_code"),Salla.config.get("currencies."+e)||Object.values(Salla.config.get("currencies"))[0]);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 r=Array.isArray(e),i=r?this.getUrl(...e):this.getUrl(e);e=r?e[0]:e,a=a||this.endpointsMethods[e]||"post";let s=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 s&&"get"===a&&(t=t?Object.assign(t,s):s),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:s})}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-checkout",createQuickOrder:"checkout/quick-checkout",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("request::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(){let e=await this.getCurrentCartId();return this.request(["details",e]).then((function(e){return salla.cart.event.detailsFetched(e),e})).catch((function(e){throw salla.cart.event.detailsNotFetched(e),e}))}async quickAdd(e,t){return this.addItem({id:e,quantity:t,endpoint:"quickAdd"})}async addItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no product "id"!';return salla.cart.event.itemAddedFailed(e),salla.api.errorPromise(e)}let a=salla.form.getPossibleValue(t.payload,["endpoint"]);a&&["addItem","quickAdd"].includes(a)||(a=salla.form.getPossibleValue(t.payload,["quantity","donating_amount"])?"addItem":"quickAdd");let r=await this.getCurrentCartId();return this.request([a,r,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 r=await salla.auth.api.request(["verify",a],e);if(200!==r?.status)return salla.auth.event.verificationFailed(r,a),salla.api.errorPromise(r);let i="authenticated"===r.data?.case;return i&&salla.auth.event.tokenFetched(r.data.token),t&&await salla.auth.api.request("auth/jwt"),i&&salla.auth.event.loggedIn(r).then((()=>salla.auth.api.afterUserLogin())),salla.auth.event.verified(r,a),salla.api.successPromise(r)}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(()=>{...})`),location.href=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.storage.set("cart",{id:t.data.cart_id,user_id:salla.config.get("user.id")}),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={get:"products/{id}/details",getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",detail:"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"},this.endpointsMethods={detail:"get",giftDetail:"get"},this.after_init();}get(e,t=[]){if(!Array.isArray(t)){let e="withItems should be array.";return salla.api.errorPromise(e)}if(!e){let e="productId is not passed.";return salla.api.errorPromise(e)}return this.request(["get",e],{params:{with:t}}).then((function(e){return e})).catch((function(e){throw e}))}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.offer.event.fetchDetailsFailed(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(["detail",e],{params:{with:t}}).then((function(t){return salla.product.event.detailFetched(t,e),t})).catch((function(t){throw salla.product.event.detailFetchFailed(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),response))).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"]),r=salla.form.getPossibleValue(e,["type"]),i=salla.form.getPossibleValue(e,["comment"]);return a?r&&["products","pages","product","page"].includes(r)?i?(r+=["product","page"].includes(r)?"s":"",this.request(["add",r,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 b 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 F 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),resp}))}}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 E{constructor(t){"ready"!==f$1.status?t?(f$1.config.merge(t),t?.events&&f$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.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.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),r=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,r).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}));}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1];})),a=e;}window[e]?window[e](t,a):salla.event.dispatch(e,t,a);}}setSallaReady(t){f$1.status="ready",f$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("twilight::initiated",{detail:t}));}}f$1.status="loading",f$1.notify=o,f$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.messages)return void window.addEventListener("load",(e=>{salla.event.dispatch("languages::translations.loaded"),salla.logger.info("The messages of transactions is already loaded");}));if(!salla.url.get(""))return void this.loadScript("https://cdn.salla.network/js/translations.js",!1);let e=salla.config.get("theme.translations_hash",salla.config.get("store.id","twilight"));this.loadScript(salla.url.get(`languages/assets/${e}.js`));}setMessages(e){super.setMessages(e),salla.event.dispatch("languages::translations.loaded"),this.translationsLoaded=!0;}loadScript(e,t=!0){let a=document.createElement("script");a.src=e,a.onload=()=>{if(window.translations)return this.setMessages(window.translations);a.onerror();},a.onerror=()=>{if(t)return salla.logger.warn("Failed to load Translations for store, lets try load it from CDN"),this.loadScript("https://cdn.salla.network/js/translations.js",!1);salla.logger.error("Failed to load Translations, check your network logs for more details\nor: salla.lang.setMessages({....}), see https://docs.salla.dev for more information's.");},document.head.appendChild(a);}get(e,t,a){return window.translations&&(e="trans."+e),super.get(e,t,a)}set(e,t){return salla.helpers.setNested(this.messages[this.getLocale()+".trans"],e,t),this}},f$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.normalRequest(e,a,"post").finally((()=>{loaderSupported&&t?.submitter?.parentElement.stop();}));let r=e.split("."),i=r.splice(-1);return await salla.call(r.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 r;for(let a=0;a<t.length&&!(r=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(r=e.get(t[a])));a++);return r=r||e,"object"!=typeof r||a?r:void 0}},f$1.helpers.app=new class{toggleClassIf(e,t,a,r){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,a,r))),this}toggleElementClassIf(e,t,a,r){t=Array.isArray(t)?t:t.split(" "),a=Array.isArray(a)?a:a.split(" ");let i=r(e);return e?.classList.remove(...i?a:t),e?.classList.add(...i?t:a),this}isValidEmail(e){return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())}element(e){return "object"==typeof e?e:document.querySelector(e)}watchElement(e,t){return this[e]=this.element(t),this}watchElements(e){return Object.entries(e).forEach((e=>this.watchElement(e[0],e[1]))),this}on(e,t,a,r={}){return "object"==typeof t?(this.element(t).addEventListener(e,a,r),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,a,r))),this)}onClick(e,t){return this.on("click",e,t)}onKeyUp(e,t){return this.on("keyup",e,t)}onEnter(e,t){return this.onKeyUp(e,(e=>13===e.keyCode&&t(e))),this}all(e,t){return document.querySelectorAll(e).forEach(t),this}hideElement(e){return this.element(e).style.display="none",this}showElement(e,t="block"){return this.element(e).style.display=t,this}removeClass(e,t){return this.element(e).classList.remove(...Array.from(arguments).slice(1)),this}addClass(e,t){return this.element(e).classList.add(...Array.from(arguments).slice(1)),this}debounce(e,...t){return this.debounce_||(this.debounce_=Salla.helpers.debounce(((e,...t)=>e(...t)),500)),this.debounce_(e,...t)}},f$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,r){r=this.getCustomOptions(a,r);let i="string"!=typeof e?e:document.querySelector(e),s=r.path;if(!i||!s||"string"==typeof s&&!document.querySelector(s))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,r);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),f$1.api=new class extends class{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);}injectTokenToTheRequests(e){let t=salla.storage.get("token"),a=Salla.config.isGuest(),r=salla.storage.get("cart"),s=e.user?.id,n=salla.storage.get("user.id");if(n&&n!==s&&salla.storage.remove("user"),r&&(r.user_id!==s||r.store_id!==e.store?.id))return salla.log("cart",{user_id:r.user_id,store_id:r.store_id}),salla.log("current",{user_id:s,store_id:e.store?.id}),salla.log("Auth:: The cart is not belong to current "+(r.user_id!==s?"user":"store")+"!"),void salla.cart.api.reset();if(a&&!t)return;if(a&&t)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!t)return salla.cart.api.reset(),void salla.auth.api.refresh();let l=o$1(t);return Date.now()/1e3>l.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):l.sub!==s?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):(this.setToken(t),void salla.event.emit("request::initiated"))}setToken(e){return this.setHeader("Authorization","Bearer "+e)}setCurrencyAndLanguage(e){return this.setHeaders({currency:e.data.currency,"accept-language":e.data.language})}request(e,t,a="get",r={}){let i={endPoint:e,payload:t,method:a,options:r},s="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===s?.tagName&&(n=!0),n&&s?.load(),this.axios[i.method](i.endPoint,i.payload,i.options).then((e=>(n&&s?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&s?.stop(),salla.event.document.requestFailed(i,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,r=t&&t.googleTags?t.googleTags:a;dataLayer&&r&&dataLayer.push(r),this.fireEventsForResponse(e),this.showAlert(e),this.renderSections(e);}fireEventsForResponse(e){let t=e?.events||e.data?.events||e.error?.events;"string"==typeof t&&(t=JSON.parse(t)),t&&Object.keys(t).forEach((e=>salla.event.dispatch(e,t[e])));}handleErrorResponse(e){if(e.response&&e.response.data)return e.response.data.error&&e.response.data.error.fields&&!this.notifier_handler_disabled?this.handleInvalidFields(e):this.handleAfterResponseActions(e.response.data)}showAlert(e){if(e&&!this.notifier_handler_disabled)return e.case&&e.msg?salla.notify.fire(e.msg,e.case,e):e.hasOwnProperty("success")&&e.data?.message?salla.notify.fire(e.data?.message,e.success?salla.notify.types.success:salla.notify.types.error,e):e.error&&e.error.message&&"FORBIDDEN"!==e.error.message?salla.error(e.error.message,e):void 0}handleInvalidFields(e){let t=e.response.data.error.fields,a=[];Object.keys(t).forEach((e=>{let r=t[e];Array.isArray(r)?r.forEach((e=>a.push(e))):a.push(r);}));let r=(a.length>1?"* ":"")+a.join("\n* ");salla.error(r,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,r)=>t?a(e):r(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}renderSections(e){e.sections&&Object.keys(e.sections).forEach((t=>{document.querySelectorAll(t.toSelector()).forEach((function(a){a.innerHTML=e.sections[t];}));}));}}{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 b,this.document=new F,this.wishlist=new _,this.scope=new q,this.booking=new A;}},f$1.cart=new d(f$1.api.cart,f$1.event.cart),f$1.auth=new d(f$1.api.auth,f$1.event.auth),f$1.order=new d(f$1.api.order,f$1.event.order),f$1.scope=new d(f$1.api.scope,f$1.event.scope),f$1.rating=new d(f$1.api.rating,f$1.event.rating),f$1.comment=new d(f$1.api.comment,f$1.event.comment),f$1.loyalty=new d(f$1.api.loyalty,f$1.event.loyalty),f$1.product=new d(f$1.api.product,f$1.event.product),f$1.profile=new d(f$1.api.profile,f$1.event.profile),f$1.currency=new d(f$1.api.currency,f$1.event.currency),f$1.document=new d(f$1.api.document,f$1.event.document),f$1.wishlist=new d(f$1.api.wishlist,f$1.event.wishlist),f$1.booking=new d(f$1.api.booking,f$1.event.booking),f$1.call=t=>{let a=f$1,r=t.split(".");for(;r.length&&(a=a[r.shift()]););return a},f$1.init=e=>new E(e),salla.event.once("twilight::init",salla.init),salla.event.once("twilight::api",(e=>{let t=e?.events;t&&salla.event.dispatchEvents(t);})),f$1.success=f$1.notify.success,f$1.error=f$1.notify.error,f$1.versions.twilight="[VI]{version}[/VI]",f$1.onInitiated=e=>salla.event.once("twilight::initiated",e),f$1.onReady=f$1.onReady||function(t){"ready"!==salla.status?f$1.onInitiated(t):t(salla.config.all());},window.dispatchEvent(new CustomEvent("salla::created"));
7517
9710
 
7518
9711
  var lazyload_min = _commonjsHelpers.createCommonjsModule(function (module, exports) {
7519
9712
  !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}));