@salla.sa/twilight-components 2.9.41 → 2.9.42

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 (39) hide show
  1. package/dist/cjs/index-1d2b3370.js +2 -2
  2. package/dist/cjs/{index-8abe1667.js → index-53c1e9f1.js} +2232 -39
  3. package/dist/cjs/loader.cjs.js +2 -2
  4. package/dist/cjs/{salla-button_33.cjs.entry.js → salla-button_34.cjs.entry.js} +614 -0
  5. package/dist/cjs/twilight.cjs.js +2 -2
  6. package/dist/collection/assets/svg/location-marker.svg +4 -0
  7. package/dist/collection/collection-manifest.json +1 -0
  8. package/dist/collection/components/salla-map/map-styles.js +345 -0
  9. package/dist/collection/components/salla-map/salla-map.css +59 -0
  10. package/dist/collection/components/salla-map/salla-map.js +393 -0
  11. package/dist/components/index.d.ts +1 -0
  12. package/dist/components/index.js +2233 -39
  13. package/dist/components/salla-map.d.ts +11 -0
  14. package/dist/components/salla-map.js +670 -0
  15. package/dist/esm/{index-fa058d0e.js → index-dc279949.js} +2232 -39
  16. package/dist/esm/index-f1d446ac.js +2 -2
  17. package/dist/esm/loader.js +2 -2
  18. package/dist/esm/{salla-button_33.entry.js → salla-button_34.entry.js} +614 -1
  19. package/dist/esm/twilight.js +2 -2
  20. package/dist/esm-es5/index-dc279949.js +30 -0
  21. package/dist/esm-es5/index-f1d446ac.js +1 -1
  22. package/dist/esm-es5/loader.js +1 -1
  23. package/dist/esm-es5/{salla-button_33.entry.js → salla-button_34.entry.js} +4 -4
  24. package/dist/esm-es5/twilight.js +1 -1
  25. package/dist/twilight/p-19ce7aa8.js +24 -0
  26. package/dist/twilight/{p-6f94dcce.entry.js → p-382b121a.entry.js} +4 -4
  27. package/dist/twilight/p-4733b689.system.js +4 -0
  28. package/dist/twilight/p-6b59d89a.system.js +30 -0
  29. package/dist/twilight/{p-79eae6ae.system.entry.js → p-b45e1ab3.system.entry.js} +5 -5
  30. package/dist/twilight/twilight.esm.js +1 -1
  31. package/dist/twilight/twilight.js +1 -1
  32. package/dist/types/components/salla-map/map-styles.d.ts +6 -0
  33. package/dist/types/components/salla-map/salla-map.d.ts +57 -0
  34. package/dist/types/components.d.ts +75 -0
  35. package/package.json +4 -3
  36. package/dist/esm-es5/index-fa058d0e.js +0 -24
  37. package/dist/twilight/p-175df7e0.system.js +0 -24
  38. package/dist/twilight/p-9e980a1a.js +0 -24
  39. package/dist/twilight/p-cb28d2ec.system.js +0 -4
@@ -19,6 +19,7 @@ export { SallaLocalizationModal, defineCustomElement as defineCustomElementSalla
19
19
  export { SallaLoginModal, defineCustomElement as defineCustomElementSallaLoginModal } from './salla-login-modal.js';
20
20
  export { SallaLoyalty, defineCustomElement as defineCustomElementSallaLoyalty } from './salla-loyalty.js';
21
21
  export { SallaLoyaltyPrizeItem, defineCustomElement as defineCustomElementSallaLoyaltyPrizeItem } from './salla-loyalty-prize-item.js';
22
+ export { SallaMap, defineCustomElement as defineCustomElementSallaMap } from './salla-map.js';
22
23
  export { SallaModal, defineCustomElement as defineCustomElementSallaModal } from './salla-modal.js';
23
24
  export { SallaOfferModal, defineCustomElement as defineCustomElementSallaOfferModal } from './salla-offer-modal.js';
24
25
  export { SallaPlaceholder, defineCustomElement as defineCustomElementSallaPlaceholder } from './salla-placeholder.js';
@@ -43,6 +44,232 @@ export { SallaUserMenu, defineCustomElement as defineCustomElementSallaUserMenu
43
44
  export { SallaUserSettings, defineCustomElement as defineCustomElementSallaUserSettings } from './salla-user-settings.js';
44
45
  export { SallaVerify, defineCustomElement as defineCustomElementSallaVerify } from './salla-verify.js';
45
46
 
47
+ const global$1 = (typeof global !== "undefined" ? global :
48
+ typeof self !== "undefined" ? self :
49
+ typeof window !== "undefined" ? window : {});
50
+
51
+ // shim for using process in browser
52
+ // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
53
+
54
+ function defaultSetTimout() {
55
+ throw new Error('setTimeout has not been defined');
56
+ }
57
+ function defaultClearTimeout () {
58
+ throw new Error('clearTimeout has not been defined');
59
+ }
60
+ var cachedSetTimeout = defaultSetTimout;
61
+ var cachedClearTimeout = defaultClearTimeout;
62
+ if (typeof global$1.setTimeout === 'function') {
63
+ cachedSetTimeout = setTimeout;
64
+ }
65
+ if (typeof global$1.clearTimeout === 'function') {
66
+ cachedClearTimeout = clearTimeout;
67
+ }
68
+
69
+ function runTimeout(fun) {
70
+ if (cachedSetTimeout === setTimeout) {
71
+ //normal enviroments in sane situations
72
+ return setTimeout(fun, 0);
73
+ }
74
+ // if setTimeout wasn't available but was latter defined
75
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
76
+ cachedSetTimeout = setTimeout;
77
+ return setTimeout(fun, 0);
78
+ }
79
+ try {
80
+ // when when somebody has screwed with setTimeout but no I.E. maddness
81
+ return cachedSetTimeout(fun, 0);
82
+ } catch(e){
83
+ try {
84
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
85
+ return cachedSetTimeout.call(null, fun, 0);
86
+ } catch(e){
87
+ // 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
88
+ return cachedSetTimeout.call(this, fun, 0);
89
+ }
90
+ }
91
+
92
+
93
+ }
94
+ function runClearTimeout(marker) {
95
+ if (cachedClearTimeout === clearTimeout) {
96
+ //normal enviroments in sane situations
97
+ return clearTimeout(marker);
98
+ }
99
+ // if clearTimeout wasn't available but was latter defined
100
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
101
+ cachedClearTimeout = clearTimeout;
102
+ return clearTimeout(marker);
103
+ }
104
+ try {
105
+ // when when somebody has screwed with setTimeout but no I.E. maddness
106
+ return cachedClearTimeout(marker);
107
+ } catch (e){
108
+ try {
109
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
110
+ return cachedClearTimeout.call(null, marker);
111
+ } catch (e){
112
+ // 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.
113
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
114
+ return cachedClearTimeout.call(this, marker);
115
+ }
116
+ }
117
+
118
+
119
+
120
+ }
121
+ var queue = [];
122
+ var draining = false;
123
+ var currentQueue;
124
+ var queueIndex = -1;
125
+
126
+ function cleanUpNextTick() {
127
+ if (!draining || !currentQueue) {
128
+ return;
129
+ }
130
+ draining = false;
131
+ if (currentQueue.length) {
132
+ queue = currentQueue.concat(queue);
133
+ } else {
134
+ queueIndex = -1;
135
+ }
136
+ if (queue.length) {
137
+ drainQueue();
138
+ }
139
+ }
140
+
141
+ function drainQueue() {
142
+ if (draining) {
143
+ return;
144
+ }
145
+ var timeout = runTimeout(cleanUpNextTick);
146
+ draining = true;
147
+
148
+ var len = queue.length;
149
+ while(len) {
150
+ currentQueue = queue;
151
+ queue = [];
152
+ while (++queueIndex < len) {
153
+ if (currentQueue) {
154
+ currentQueue[queueIndex].run();
155
+ }
156
+ }
157
+ queueIndex = -1;
158
+ len = queue.length;
159
+ }
160
+ currentQueue = null;
161
+ draining = false;
162
+ runClearTimeout(timeout);
163
+ }
164
+ function nextTick(fun) {
165
+ var args = new Array(arguments.length - 1);
166
+ if (arguments.length > 1) {
167
+ for (var i = 1; i < arguments.length; i++) {
168
+ args[i - 1] = arguments[i];
169
+ }
170
+ }
171
+ queue.push(new Item(fun, args));
172
+ if (queue.length === 1 && !draining) {
173
+ runTimeout(drainQueue);
174
+ }
175
+ }
176
+ // v8 likes predictible objects
177
+ function Item(fun, array) {
178
+ this.fun = fun;
179
+ this.array = array;
180
+ }
181
+ Item.prototype.run = function () {
182
+ this.fun.apply(null, this.array);
183
+ };
184
+ var title = 'browser';
185
+ var platform = 'browser';
186
+ var browser = true;
187
+ var env = {};
188
+ var argv = [];
189
+ var version = ''; // empty string to avoid regexp issues
190
+ var versions = {};
191
+ var release = {};
192
+ var config = {};
193
+
194
+ function noop() {}
195
+
196
+ var on = noop;
197
+ var addListener = noop;
198
+ var once = noop;
199
+ var off = noop;
200
+ var removeListener = noop;
201
+ var removeAllListeners = noop;
202
+ var emit = noop;
203
+
204
+ function binding(name) {
205
+ throw new Error('process.binding is not supported');
206
+ }
207
+
208
+ function cwd () { return '/' }
209
+ function chdir (dir) {
210
+ throw new Error('process.chdir is not supported');
211
+ }function umask() { return 0; }
212
+
213
+ // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
214
+ var performance = global$1.performance || {};
215
+ var performanceNow =
216
+ performance.now ||
217
+ performance.mozNow ||
218
+ performance.msNow ||
219
+ performance.oNow ||
220
+ performance.webkitNow ||
221
+ function(){ return (new Date()).getTime() };
222
+
223
+ // generate timestamp or delta
224
+ // see http://nodejs.org/api/process.html#process_process_hrtime
225
+ function hrtime(previousTimestamp){
226
+ var clocktime = performanceNow.call(performance)*1e-3;
227
+ var seconds = Math.floor(clocktime);
228
+ var nanoseconds = Math.floor((clocktime%1)*1e9);
229
+ if (previousTimestamp) {
230
+ seconds = seconds - previousTimestamp[0];
231
+ nanoseconds = nanoseconds - previousTimestamp[1];
232
+ if (nanoseconds<0) {
233
+ seconds--;
234
+ nanoseconds += 1e9;
235
+ }
236
+ }
237
+ return [seconds,nanoseconds]
238
+ }
239
+
240
+ var startTime = new Date();
241
+ function uptime() {
242
+ var currentTime = new Date();
243
+ var dif = currentTime - startTime;
244
+ return dif / 1000;
245
+ }
246
+
247
+ var browser$1 = {
248
+ nextTick: nextTick,
249
+ title: title,
250
+ browser: browser,
251
+ env: env,
252
+ argv: argv,
253
+ version: version,
254
+ versions: versions,
255
+ on: on,
256
+ addListener: addListener,
257
+ once: once,
258
+ off: off,
259
+ removeListener: removeListener,
260
+ removeAllListeners: removeAllListeners,
261
+ emit: emit,
262
+ binding: binding,
263
+ cwd: cwd,
264
+ chdir: chdir,
265
+ umask: umask,
266
+ hrtime: hrtime,
267
+ platform: platform,
268
+ release: release,
269
+ config: config,
270
+ uptime: uptime
271
+ };
272
+
46
273
  /**
47
274
  * Checks if `value` is classified as an `Array` object.
48
275
  *
@@ -66,9 +293,9 @@ export { SallaVerify, defineCustomElement as defineCustomElementSallaVerify } fr
66
293
  * _.isArray(_.noop);
67
294
  * // => false
68
295
  */
69
- var isArray$1 = Array.isArray;
296
+ var isArray$2 = Array.isArray;
70
297
 
71
- var isArray_1 = isArray$1;
298
+ var isArray_1 = isArray$2;
72
299
 
73
300
  /** Detect free variable `global` from Node.js. */
74
301
  var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
@@ -1133,11 +1360,11 @@ var _baseToString = baseToString;
1133
1360
  * _.toString([1, 2, 3]);
1134
1361
  * // => '1,2,3'
1135
1362
  */
1136
- function toString$1(value) {
1363
+ function toString$2(value) {
1137
1364
  return value == null ? '' : _baseToString(value);
1138
1365
  }
1139
1366
 
1140
- var toString_1 = toString$1;
1367
+ var toString_1 = toString$2;
1141
1368
 
1142
1369
  /**
1143
1370
  * Casts `value` to a path array if it's not one.
@@ -1237,7 +1464,7 @@ var eventemitter2 = createCommonjsModule(function (module, exports) {
1237
1464
  return Object.prototype.toString.call(obj) === "[object Array]";
1238
1465
  };
1239
1466
  var defaultMaxListeners = 10;
1240
- var nextTickSupported= typeof process=='object' && typeof process.nextTick=='function';
1467
+ var nextTickSupported= typeof browser$1=='object' && typeof browser$1.nextTick=='function';
1241
1468
  var symbolsSupported= typeof Symbol==='function';
1242
1469
  var reflectSupported= typeof Reflect === 'object';
1243
1470
  var setImmediateSupported= typeof setImmediate === 'function';
@@ -1286,12 +1513,12 @@ var eventemitter2 = createCommonjsModule(function (module, exports) {
1286
1513
  errorMsg += ' Event name: ' + eventName + '.';
1287
1514
  }
1288
1515
 
1289
- if(typeof process !== 'undefined' && process.emitWarning){
1516
+ if(typeof browser$1 !== 'undefined' && browser$1.emitWarning){
1290
1517
  var e = new Error(errorMsg);
1291
1518
  e.name = 'MaxListenersExceededWarning';
1292
1519
  e.emitter = this;
1293
1520
  e.count = count;
1294
- process.emitWarning(e);
1521
+ browser$1.emitWarning(e);
1295
1522
  } else {
1296
1523
  console.error(errorMsg);
1297
1524
 
@@ -1997,7 +2224,7 @@ var eventemitter2 = createCommonjsModule(function (module, exports) {
1997
2224
  }).then(function () {
1998
2225
  context.event = event;
1999
2226
  return _listener.apply(context, args)
2000
- })) : (nextTick ? process.nextTick : _setImmediate)(function () {
2227
+ })) : (nextTick ? browser$1.nextTick : _setImmediate)(function () {
2001
2228
  context.event = event;
2002
2229
  _listener.apply(context, args);
2003
2230
  });
@@ -3210,8 +3437,8 @@ var Global$2 = util.Global;
3210
3437
 
3211
3438
  var localStorage_1 = {
3212
3439
  name: 'localStorage',
3213
- read: read$3,
3214
- write: write$3,
3440
+ read: read$4,
3441
+ write: write$4,
3215
3442
  each: each$3,
3216
3443
  remove: remove$3,
3217
3444
  clearAll: clearAll$3,
@@ -3221,18 +3448,18 @@ function localStorage() {
3221
3448
  return Global$2.localStorage
3222
3449
  }
3223
3450
 
3224
- function read$3(key) {
3451
+ function read$4(key) {
3225
3452
  return localStorage().getItem(key)
3226
3453
  }
3227
3454
 
3228
- function write$3(key, data) {
3455
+ function write$4(key, data) {
3229
3456
  return localStorage().setItem(key, data)
3230
3457
  }
3231
3458
 
3232
3459
  function each$3(fn) {
3233
3460
  for (var i = localStorage().length - 1; i >= 0; i--) {
3234
3461
  var key = localStorage().key(i);
3235
- fn(read$3(key), key);
3462
+ fn(read$4(key), key);
3236
3463
  }
3237
3464
  }
3238
3465
 
@@ -3248,8 +3475,8 @@ var Global$1 = util.Global;
3248
3475
 
3249
3476
  var sessionStorage_1 = {
3250
3477
  name: 'sessionStorage',
3251
- read: read$2,
3252
- write: write$2,
3478
+ read: read$3,
3479
+ write: write$3,
3253
3480
  each: each$2,
3254
3481
  remove: remove$2,
3255
3482
  clearAll: clearAll$2
@@ -3259,18 +3486,18 @@ function sessionStorage() {
3259
3486
  return Global$1.sessionStorage
3260
3487
  }
3261
3488
 
3262
- function read$2(key) {
3489
+ function read$3(key) {
3263
3490
  return sessionStorage().getItem(key)
3264
3491
  }
3265
3492
 
3266
- function write$2(key, data) {
3493
+ function write$3(key, data) {
3267
3494
  return sessionStorage().setItem(key, data)
3268
3495
  }
3269
3496
 
3270
3497
  function each$2(fn) {
3271
3498
  for (var i = sessionStorage().length - 1; i >= 0; i--) {
3272
3499
  var key = sessionStorage().key(i);
3273
- fn(read$2(key), key);
3500
+ fn(read$3(key), key);
3274
3501
  }
3275
3502
  }
3276
3503
 
@@ -3292,8 +3519,8 @@ var trim$1 = util.trim;
3292
3519
 
3293
3520
  var cookieStorage = {
3294
3521
  name: 'cookieStorage',
3295
- read: read$1,
3296
- write: write$1,
3522
+ read: read$2,
3523
+ write: write$2,
3297
3524
  each: each$1,
3298
3525
  remove: remove$1,
3299
3526
  clearAll: clearAll$1,
@@ -3301,7 +3528,7 @@ var cookieStorage = {
3301
3528
 
3302
3529
  var doc = Global.document;
3303
3530
 
3304
- function read$1(key) {
3531
+ function read$2(key) {
3305
3532
  if (!key || !_has(key)) { return null }
3306
3533
  var regexpStr = "(?:^|.*;\\s*)" +
3307
3534
  escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
@@ -3322,7 +3549,7 @@ function each$1(callback) {
3322
3549
  }
3323
3550
  }
3324
3551
 
3325
- function write$1(key, data) {
3552
+ function write$2(key, data) {
3326
3553
  if(!key) { return }
3327
3554
  doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
3328
3555
  }
@@ -3351,8 +3578,8 @@ function _has(key) {
3351
3578
 
3352
3579
  var memoryStorage_1 = {
3353
3580
  name: 'memoryStorage',
3354
- read: read,
3355
- write: write,
3581
+ read: read$1,
3582
+ write: write$1,
3356
3583
  each: each,
3357
3584
  remove: remove,
3358
3585
  clearAll: clearAll,
@@ -3360,11 +3587,11 @@ var memoryStorage_1 = {
3360
3587
 
3361
3588
  var memoryStorage = {};
3362
3589
 
3363
- function read(key) {
3590
+ function read$1(key) {
3364
3591
  return memoryStorage[key]
3365
3592
  }
3366
3593
 
3367
- function write(key, data) {
3594
+ function write$1(key, data) {
3368
3595
  memoryStorage[key] = data;
3369
3596
  }
3370
3597
 
@@ -3384,7 +3611,7 @@ function clearAll(key) {
3384
3611
  memoryStorage = {};
3385
3612
  }
3386
3613
 
3387
- function a(e,t=!1){e+="";let r,o=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],i=["0","1","2","3","4","5","6","7","8","9"],n=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?o:i,l=t?i:o;for(let t=0;t<n.length;t++)r=new RegExp(n[t],"g"),e=e.replace(r,l[t]);return e}function s(e){let t=(e.match(/\./g)||[]).length;return t&&1!==t?s(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e,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(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,i=t.split("."),n=i.length;for(let e=0;e<n-1;e++){let t=i[e];o[t]||(o[t]={}),o=o[t];}return o[i[n-1]]=r,e},getNested:function(t,r,o){let i=get_1(t,r);return void 0!==i?i: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(...i){return clearTimeout(r),r=setTimeout((()=>{let t=e(...i);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,i=void 0===r?o:this.__dict__[r]||o,n=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(n[0]+="%c"+r[0].toUpperCase()+r.substring(1),n.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),i.call(e,...n.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}:salla.log(`Skipped to add item (${e}) to the dataLayerObject, because it's not an object.`);})),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("="),i=o>-1?r.substr(0,o):r;this.remove(i);}}},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;
3614
+ function a(e,t=!1){e+="";let r,o=["٠","١","٢","٣","٤","٥","٦","٧","٨","٩"],i=["0","1","2","3","4","5","6","7","8","9"],n=(t=t||!Salla.config.get("store.settings.arabic_numbers_enabled"))?o:i,l=t?i:o;for(let t=0;t<n.length;t++)r=new RegExp(n[t],"g"),e=e.replace(r,l[t]);return e}function s(e){let t=(e.match(/\./g)||[]).length;return t&&1!==t?s(e.replace(/\.(.+)\./g,".$1")):e}function c$1(e,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(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,i=t.split("."),n=i.length;for(let e=0;e<n-1;e++){let t=i[e];o[t]||(o[t]={}),o=o[t];}return o[i[n-1]]=r,e},getNested:function(t,r,o){let i=get_1(t,r);return void 0!==i?i: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(...i){return clearTimeout(r),r=setTimeout((()=>{let t=e(...i);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,i=void 0===r?o:this.__dict__[r]||o,n=["%cTwilight","color: #5cd5c4;font-weight:bold; border:1px solid #5cd5c4; padding: 2px 6px; border-radius: 5px;"],l={event:"#CFF680",backend:"#7b68ee"}[r];l&&(n[0]+="%c"+r[0].toUpperCase()+r.substring(1),n.push(`margin-left: 5px;color: ${l};font-weight:bold; border:1px solid ${l}; padding: 2px 6px; border-radius: 5px;`)),i.call(e,...n.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}:salla.log(`Skipped to add item (${e}) to the dataLayerObject, because it's not an object.`);})),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("="),i=o>-1?r.substr(0,o):r;this.remove(i);}}},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;
3388
3615
 
3389
3616
  var evEmitter = createCommonjsModule(function (module) {
3390
3617
  /**
@@ -5545,13 +5772,13 @@ var bind = function bind(fn, thisArg) {
5545
5772
 
5546
5773
  // utils is a library of generic helper functions non-specific to axios
5547
5774
 
5548
- var toString = Object.prototype.toString;
5775
+ var toString$1 = Object.prototype.toString;
5549
5776
 
5550
5777
  // eslint-disable-next-line func-names
5551
5778
  var kindOf = (function(cache) {
5552
5779
  // eslint-disable-next-line func-names
5553
5780
  return function(thing) {
5554
- var str = toString.call(thing);
5781
+ var str = toString$1.call(thing);
5555
5782
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
5556
5783
  };
5557
5784
  })(Object.create(null));
@@ -5569,7 +5796,7 @@ function kindOfTest(type) {
5569
5796
  * @param {Object} val The value to test
5570
5797
  * @returns {boolean} True if value is an Array, otherwise false
5571
5798
  */
5572
- function isArray(val) {
5799
+ function isArray$1(val) {
5573
5800
  return Array.isArray(val);
5574
5801
  }
5575
5802
 
@@ -5589,7 +5816,7 @@ function isUndefined(val) {
5589
5816
  * @param {Object} val The value to test
5590
5817
  * @returns {boolean} True if value is a Buffer, otherwise false
5591
5818
  */
5592
- function isBuffer(val) {
5819
+ function isBuffer$1(val) {
5593
5820
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
5594
5821
  && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
5595
5822
  }
@@ -5708,7 +5935,7 @@ var isFileList = kindOfTest('FileList');
5708
5935
  * @returns {boolean} True if value is a Function, otherwise false
5709
5936
  */
5710
5937
  function isFunction(val) {
5711
- return toString.call(val) === '[object Function]';
5938
+ return toString$1.call(val) === '[object Function]';
5712
5939
  }
5713
5940
 
5714
5941
  /**
@@ -5731,7 +5958,7 @@ function isFormData(thing) {
5731
5958
  var pattern = '[object FormData]';
5732
5959
  return thing && (
5733
5960
  (typeof FormData === 'function' && thing instanceof FormData) ||
5734
- toString.call(thing) === pattern ||
5961
+ toString$1.call(thing) === pattern ||
5735
5962
  (isFunction(thing.toString) && thing.toString() === pattern)
5736
5963
  );
5737
5964
  }
@@ -5805,7 +6032,7 @@ function forEach(obj, fn) {
5805
6032
  obj = [obj];
5806
6033
  }
5807
6034
 
5808
- if (isArray(obj)) {
6035
+ if (isArray$1(obj)) {
5809
6036
  // Iterate over array values
5810
6037
  for (var i = 0, l = obj.length; i < l; i++) {
5811
6038
  fn.call(null, obj[i], i, obj);
@@ -5844,7 +6071,7 @@ function merge(/* obj1, obj2, obj3, ... */) {
5844
6071
  result[key] = merge(result[key], val);
5845
6072
  } else if (isPlainObject(val)) {
5846
6073
  result[key] = merge({}, val);
5847
- } else if (isArray(val)) {
6074
+ } else if (isArray$1(val)) {
5848
6075
  result[key] = val.slice();
5849
6076
  } else {
5850
6077
  result[key] = val;
@@ -5978,9 +6205,9 @@ var isTypedArray = (function(TypedArray) {
5978
6205
  })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
5979
6206
 
5980
6207
  var utils = {
5981
- isArray: isArray,
6208
+ isArray: isArray$1,
5982
6209
  isArrayBuffer: isArrayBuffer,
5983
- isBuffer: isBuffer,
6210
+ isBuffer: isBuffer$1,
5984
6211
  isFormData: isFormData,
5985
6212
  isArrayBufferView: isArrayBufferView,
5986
6213
  isString: isString,
@@ -6226,6 +6453,1973 @@ var transitional = {
6226
6453
  clarifyTimeoutError: false
6227
6454
  };
6228
6455
 
6456
+ var lookup = [];
6457
+ var revLookup = [];
6458
+ var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
6459
+ var inited = false;
6460
+ function init () {
6461
+ inited = true;
6462
+ var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6463
+ for (var i = 0, len = code.length; i < len; ++i) {
6464
+ lookup[i] = code[i];
6465
+ revLookup[code.charCodeAt(i)] = i;
6466
+ }
6467
+
6468
+ revLookup['-'.charCodeAt(0)] = 62;
6469
+ revLookup['_'.charCodeAt(0)] = 63;
6470
+ }
6471
+
6472
+ function toByteArray (b64) {
6473
+ if (!inited) {
6474
+ init();
6475
+ }
6476
+ var i, j, l, tmp, placeHolders, arr;
6477
+ var len = b64.length;
6478
+
6479
+ if (len % 4 > 0) {
6480
+ throw new Error('Invalid string. Length must be a multiple of 4')
6481
+ }
6482
+
6483
+ // the number of equal signs (place holders)
6484
+ // if there are two placeholders, than the two characters before it
6485
+ // represent one byte
6486
+ // if there is only one, then the three characters before it represent 2 bytes
6487
+ // this is just a cheap hack to not do indexOf twice
6488
+ placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
6489
+
6490
+ // base64 is 4/3 + up to two characters of the original data
6491
+ arr = new Arr(len * 3 / 4 - placeHolders);
6492
+
6493
+ // if there are placeholders, only get up to the last complete 4 chars
6494
+ l = placeHolders > 0 ? len - 4 : len;
6495
+
6496
+ var L = 0;
6497
+
6498
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
6499
+ tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
6500
+ arr[L++] = (tmp >> 16) & 0xFF;
6501
+ arr[L++] = (tmp >> 8) & 0xFF;
6502
+ arr[L++] = tmp & 0xFF;
6503
+ }
6504
+
6505
+ if (placeHolders === 2) {
6506
+ tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
6507
+ arr[L++] = tmp & 0xFF;
6508
+ } else if (placeHolders === 1) {
6509
+ tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
6510
+ arr[L++] = (tmp >> 8) & 0xFF;
6511
+ arr[L++] = tmp & 0xFF;
6512
+ }
6513
+
6514
+ return arr
6515
+ }
6516
+
6517
+ function tripletToBase64 (num) {
6518
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
6519
+ }
6520
+
6521
+ function encodeChunk (uint8, start, end) {
6522
+ var tmp;
6523
+ var output = [];
6524
+ for (var i = start; i < end; i += 3) {
6525
+ tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
6526
+ output.push(tripletToBase64(tmp));
6527
+ }
6528
+ return output.join('')
6529
+ }
6530
+
6531
+ function fromByteArray (uint8) {
6532
+ if (!inited) {
6533
+ init();
6534
+ }
6535
+ var tmp;
6536
+ var len = uint8.length;
6537
+ var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
6538
+ var output = '';
6539
+ var parts = [];
6540
+ var maxChunkLength = 16383; // must be multiple of 3
6541
+
6542
+ // go through the array every three bytes, we'll deal with trailing stuff later
6543
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
6544
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
6545
+ }
6546
+
6547
+ // pad the end with zeros, but make sure to not forget the extra bytes
6548
+ if (extraBytes === 1) {
6549
+ tmp = uint8[len - 1];
6550
+ output += lookup[tmp >> 2];
6551
+ output += lookup[(tmp << 4) & 0x3F];
6552
+ output += '==';
6553
+ } else if (extraBytes === 2) {
6554
+ tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
6555
+ output += lookup[tmp >> 10];
6556
+ output += lookup[(tmp >> 4) & 0x3F];
6557
+ output += lookup[(tmp << 2) & 0x3F];
6558
+ output += '=';
6559
+ }
6560
+
6561
+ parts.push(output);
6562
+
6563
+ return parts.join('')
6564
+ }
6565
+
6566
+ function read (buffer, offset, isLE, mLen, nBytes) {
6567
+ var e, m;
6568
+ var eLen = nBytes * 8 - mLen - 1;
6569
+ var eMax = (1 << eLen) - 1;
6570
+ var eBias = eMax >> 1;
6571
+ var nBits = -7;
6572
+ var i = isLE ? (nBytes - 1) : 0;
6573
+ var d = isLE ? -1 : 1;
6574
+ var s = buffer[offset + i];
6575
+
6576
+ i += d;
6577
+
6578
+ e = s & ((1 << (-nBits)) - 1);
6579
+ s >>= (-nBits);
6580
+ nBits += eLen;
6581
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6582
+
6583
+ m = e & ((1 << (-nBits)) - 1);
6584
+ e >>= (-nBits);
6585
+ nBits += mLen;
6586
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
6587
+
6588
+ if (e === 0) {
6589
+ e = 1 - eBias;
6590
+ } else if (e === eMax) {
6591
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
6592
+ } else {
6593
+ m = m + Math.pow(2, mLen);
6594
+ e = e - eBias;
6595
+ }
6596
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6597
+ }
6598
+
6599
+ function write (buffer, value, offset, isLE, mLen, nBytes) {
6600
+ var e, m, c;
6601
+ var eLen = nBytes * 8 - mLen - 1;
6602
+ var eMax = (1 << eLen) - 1;
6603
+ var eBias = eMax >> 1;
6604
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
6605
+ var i = isLE ? 0 : (nBytes - 1);
6606
+ var d = isLE ? 1 : -1;
6607
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
6608
+
6609
+ value = Math.abs(value);
6610
+
6611
+ if (isNaN(value) || value === Infinity) {
6612
+ m = isNaN(value) ? 1 : 0;
6613
+ e = eMax;
6614
+ } else {
6615
+ e = Math.floor(Math.log(value) / Math.LN2);
6616
+ if (value * (c = Math.pow(2, -e)) < 1) {
6617
+ e--;
6618
+ c *= 2;
6619
+ }
6620
+ if (e + eBias >= 1) {
6621
+ value += rt / c;
6622
+ } else {
6623
+ value += rt * Math.pow(2, 1 - eBias);
6624
+ }
6625
+ if (value * c >= 2) {
6626
+ e++;
6627
+ c /= 2;
6628
+ }
6629
+
6630
+ if (e + eBias >= eMax) {
6631
+ m = 0;
6632
+ e = eMax;
6633
+ } else if (e + eBias >= 1) {
6634
+ m = (value * c - 1) * Math.pow(2, mLen);
6635
+ e = e + eBias;
6636
+ } else {
6637
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
6638
+ e = 0;
6639
+ }
6640
+ }
6641
+
6642
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6643
+
6644
+ e = (e << mLen) | m;
6645
+ eLen += mLen;
6646
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6647
+
6648
+ buffer[offset + i - d] |= s * 128;
6649
+ }
6650
+
6651
+ var toString = {}.toString;
6652
+
6653
+ var isArray = Array.isArray || function (arr) {
6654
+ return toString.call(arr) == '[object Array]';
6655
+ };
6656
+
6657
+ /*!
6658
+ * The buffer module from node.js, for the browser.
6659
+ *
6660
+ * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
6661
+ * @license MIT
6662
+ */
6663
+
6664
+ var INSPECT_MAX_BYTES = 50;
6665
+
6666
+ /**
6667
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
6668
+ * === true Use Uint8Array implementation (fastest)
6669
+ * === false Use Object implementation (most compatible, even IE6)
6670
+ *
6671
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6672
+ * Opera 11.6+, iOS 4.2+.
6673
+ *
6674
+ * Due to various browser bugs, sometimes the Object implementation will be used even
6675
+ * when the browser supports typed arrays.
6676
+ *
6677
+ * Note:
6678
+ *
6679
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
6680
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
6681
+ *
6682
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
6683
+ *
6684
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
6685
+ * incorrect length in some situations.
6686
+
6687
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
6688
+ * get the Object implementation, which is slower but behaves correctly.
6689
+ */
6690
+ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
6691
+ ? global$1.TYPED_ARRAY_SUPPORT
6692
+ : true;
6693
+
6694
+ function kMaxLength () {
6695
+ return Buffer.TYPED_ARRAY_SUPPORT
6696
+ ? 0x7fffffff
6697
+ : 0x3fffffff
6698
+ }
6699
+
6700
+ function createBuffer (that, length) {
6701
+ if (kMaxLength() < length) {
6702
+ throw new RangeError('Invalid typed array length')
6703
+ }
6704
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6705
+ // Return an augmented `Uint8Array` instance, for best performance
6706
+ that = new Uint8Array(length);
6707
+ that.__proto__ = Buffer.prototype;
6708
+ } else {
6709
+ // Fallback: Return an object instance of the Buffer class
6710
+ if (that === null) {
6711
+ that = new Buffer(length);
6712
+ }
6713
+ that.length = length;
6714
+ }
6715
+
6716
+ return that
6717
+ }
6718
+
6719
+ /**
6720
+ * The Buffer constructor returns instances of `Uint8Array` that have their
6721
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
6722
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
6723
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
6724
+ * returns a single octet.
6725
+ *
6726
+ * The `Uint8Array` prototype remains unmodified.
6727
+ */
6728
+
6729
+ function Buffer (arg, encodingOrOffset, length) {
6730
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
6731
+ return new Buffer(arg, encodingOrOffset, length)
6732
+ }
6733
+
6734
+ // Common case.
6735
+ if (typeof arg === 'number') {
6736
+ if (typeof encodingOrOffset === 'string') {
6737
+ throw new Error(
6738
+ 'If encoding is specified then the first argument must be a string'
6739
+ )
6740
+ }
6741
+ return allocUnsafe(this, arg)
6742
+ }
6743
+ return from(this, arg, encodingOrOffset, length)
6744
+ }
6745
+
6746
+ Buffer.poolSize = 8192; // not used by this implementation
6747
+
6748
+ // TODO: Legacy, not needed anymore. Remove in next major version.
6749
+ Buffer._augment = function (arr) {
6750
+ arr.__proto__ = Buffer.prototype;
6751
+ return arr
6752
+ };
6753
+
6754
+ function from (that, value, encodingOrOffset, length) {
6755
+ if (typeof value === 'number') {
6756
+ throw new TypeError('"value" argument must not be a number')
6757
+ }
6758
+
6759
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
6760
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
6761
+ }
6762
+
6763
+ if (typeof value === 'string') {
6764
+ return fromString(that, value, encodingOrOffset)
6765
+ }
6766
+
6767
+ return fromObject(that, value)
6768
+ }
6769
+
6770
+ /**
6771
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
6772
+ * if value is a number.
6773
+ * Buffer.from(str[, encoding])
6774
+ * Buffer.from(array)
6775
+ * Buffer.from(buffer)
6776
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
6777
+ **/
6778
+ Buffer.from = function (value, encodingOrOffset, length) {
6779
+ return from(null, value, encodingOrOffset, length)
6780
+ };
6781
+
6782
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6783
+ Buffer.prototype.__proto__ = Uint8Array.prototype;
6784
+ Buffer.__proto__ = Uint8Array;
6785
+ }
6786
+
6787
+ function assertSize (size) {
6788
+ if (typeof size !== 'number') {
6789
+ throw new TypeError('"size" argument must be a number')
6790
+ } else if (size < 0) {
6791
+ throw new RangeError('"size" argument must not be negative')
6792
+ }
6793
+ }
6794
+
6795
+ function alloc (that, size, fill, encoding) {
6796
+ assertSize(size);
6797
+ if (size <= 0) {
6798
+ return createBuffer(that, size)
6799
+ }
6800
+ if (fill !== undefined) {
6801
+ // Only pay attention to encoding if it's a string. This
6802
+ // prevents accidentally sending in a number that would
6803
+ // be interpretted as a start offset.
6804
+ return typeof encoding === 'string'
6805
+ ? createBuffer(that, size).fill(fill, encoding)
6806
+ : createBuffer(that, size).fill(fill)
6807
+ }
6808
+ return createBuffer(that, size)
6809
+ }
6810
+
6811
+ /**
6812
+ * Creates a new filled Buffer instance.
6813
+ * alloc(size[, fill[, encoding]])
6814
+ **/
6815
+ Buffer.alloc = function (size, fill, encoding) {
6816
+ return alloc(null, size, fill, encoding)
6817
+ };
6818
+
6819
+ function allocUnsafe (that, size) {
6820
+ assertSize(size);
6821
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
6822
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
6823
+ for (var i = 0; i < size; ++i) {
6824
+ that[i] = 0;
6825
+ }
6826
+ }
6827
+ return that
6828
+ }
6829
+
6830
+ /**
6831
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
6832
+ * */
6833
+ Buffer.allocUnsafe = function (size) {
6834
+ return allocUnsafe(null, size)
6835
+ };
6836
+ /**
6837
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
6838
+ */
6839
+ Buffer.allocUnsafeSlow = function (size) {
6840
+ return allocUnsafe(null, size)
6841
+ };
6842
+
6843
+ function fromString (that, string, encoding) {
6844
+ if (typeof encoding !== 'string' || encoding === '') {
6845
+ encoding = 'utf8';
6846
+ }
6847
+
6848
+ if (!Buffer.isEncoding(encoding)) {
6849
+ throw new TypeError('"encoding" must be a valid string encoding')
6850
+ }
6851
+
6852
+ var length = byteLength(string, encoding) | 0;
6853
+ that = createBuffer(that, length);
6854
+
6855
+ var actual = that.write(string, encoding);
6856
+
6857
+ if (actual !== length) {
6858
+ // Writing a hex string, for example, that contains invalid characters will
6859
+ // cause everything after the first invalid character to be ignored. (e.g.
6860
+ // 'abxxcd' will be treated as 'ab')
6861
+ that = that.slice(0, actual);
6862
+ }
6863
+
6864
+ return that
6865
+ }
6866
+
6867
+ function fromArrayLike (that, array) {
6868
+ var length = array.length < 0 ? 0 : checked(array.length) | 0;
6869
+ that = createBuffer(that, length);
6870
+ for (var i = 0; i < length; i += 1) {
6871
+ that[i] = array[i] & 255;
6872
+ }
6873
+ return that
6874
+ }
6875
+
6876
+ function fromArrayBuffer (that, array, byteOffset, length) {
6877
+
6878
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
6879
+ throw new RangeError('\'offset\' is out of bounds')
6880
+ }
6881
+
6882
+ if (array.byteLength < byteOffset + (length || 0)) {
6883
+ throw new RangeError('\'length\' is out of bounds')
6884
+ }
6885
+
6886
+ if (byteOffset === undefined && length === undefined) {
6887
+ array = new Uint8Array(array);
6888
+ } else if (length === undefined) {
6889
+ array = new Uint8Array(array, byteOffset);
6890
+ } else {
6891
+ array = new Uint8Array(array, byteOffset, length);
6892
+ }
6893
+
6894
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
6895
+ // Return an augmented `Uint8Array` instance, for best performance
6896
+ that = array;
6897
+ that.__proto__ = Buffer.prototype;
6898
+ } else {
6899
+ // Fallback: Return an object instance of the Buffer class
6900
+ that = fromArrayLike(that, array);
6901
+ }
6902
+ return that
6903
+ }
6904
+
6905
+ function fromObject (that, obj) {
6906
+ if (internalIsBuffer(obj)) {
6907
+ var len = checked(obj.length) | 0;
6908
+ that = createBuffer(that, len);
6909
+
6910
+ if (that.length === 0) {
6911
+ return that
6912
+ }
6913
+
6914
+ obj.copy(that, 0, 0, len);
6915
+ return that
6916
+ }
6917
+
6918
+ if (obj) {
6919
+ if ((typeof ArrayBuffer !== 'undefined' &&
6920
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
6921
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
6922
+ return createBuffer(that, 0)
6923
+ }
6924
+ return fromArrayLike(that, obj)
6925
+ }
6926
+
6927
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
6928
+ return fromArrayLike(that, obj.data)
6929
+ }
6930
+ }
6931
+
6932
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
6933
+ }
6934
+
6935
+ function checked (length) {
6936
+ // Note: cannot use `length < kMaxLength()` here because that fails when
6937
+ // length is NaN (which is otherwise coerced to zero.)
6938
+ if (length >= kMaxLength()) {
6939
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
6940
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
6941
+ }
6942
+ return length | 0
6943
+ }
6944
+ Buffer.isBuffer = isBuffer;
6945
+ function internalIsBuffer (b) {
6946
+ return !!(b != null && b._isBuffer)
6947
+ }
6948
+
6949
+ Buffer.compare = function compare (a, b) {
6950
+ if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
6951
+ throw new TypeError('Arguments must be Buffers')
6952
+ }
6953
+
6954
+ if (a === b) return 0
6955
+
6956
+ var x = a.length;
6957
+ var y = b.length;
6958
+
6959
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
6960
+ if (a[i] !== b[i]) {
6961
+ x = a[i];
6962
+ y = b[i];
6963
+ break
6964
+ }
6965
+ }
6966
+
6967
+ if (x < y) return -1
6968
+ if (y < x) return 1
6969
+ return 0
6970
+ };
6971
+
6972
+ Buffer.isEncoding = function isEncoding (encoding) {
6973
+ switch (String(encoding).toLowerCase()) {
6974
+ case 'hex':
6975
+ case 'utf8':
6976
+ case 'utf-8':
6977
+ case 'ascii':
6978
+ case 'latin1':
6979
+ case 'binary':
6980
+ case 'base64':
6981
+ case 'ucs2':
6982
+ case 'ucs-2':
6983
+ case 'utf16le':
6984
+ case 'utf-16le':
6985
+ return true
6986
+ default:
6987
+ return false
6988
+ }
6989
+ };
6990
+
6991
+ Buffer.concat = function concat (list, length) {
6992
+ if (!isArray(list)) {
6993
+ throw new TypeError('"list" argument must be an Array of Buffers')
6994
+ }
6995
+
6996
+ if (list.length === 0) {
6997
+ return Buffer.alloc(0)
6998
+ }
6999
+
7000
+ var i;
7001
+ if (length === undefined) {
7002
+ length = 0;
7003
+ for (i = 0; i < list.length; ++i) {
7004
+ length += list[i].length;
7005
+ }
7006
+ }
7007
+
7008
+ var buffer = Buffer.allocUnsafe(length);
7009
+ var pos = 0;
7010
+ for (i = 0; i < list.length; ++i) {
7011
+ var buf = list[i];
7012
+ if (!internalIsBuffer(buf)) {
7013
+ throw new TypeError('"list" argument must be an Array of Buffers')
7014
+ }
7015
+ buf.copy(buffer, pos);
7016
+ pos += buf.length;
7017
+ }
7018
+ return buffer
7019
+ };
7020
+
7021
+ function byteLength (string, encoding) {
7022
+ if (internalIsBuffer(string)) {
7023
+ return string.length
7024
+ }
7025
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
7026
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
7027
+ return string.byteLength
7028
+ }
7029
+ if (typeof string !== 'string') {
7030
+ string = '' + string;
7031
+ }
7032
+
7033
+ var len = string.length;
7034
+ if (len === 0) return 0
7035
+
7036
+ // Use a for loop to avoid recursion
7037
+ var loweredCase = false;
7038
+ for (;;) {
7039
+ switch (encoding) {
7040
+ case 'ascii':
7041
+ case 'latin1':
7042
+ case 'binary':
7043
+ return len
7044
+ case 'utf8':
7045
+ case 'utf-8':
7046
+ case undefined:
7047
+ return utf8ToBytes(string).length
7048
+ case 'ucs2':
7049
+ case 'ucs-2':
7050
+ case 'utf16le':
7051
+ case 'utf-16le':
7052
+ return len * 2
7053
+ case 'hex':
7054
+ return len >>> 1
7055
+ case 'base64':
7056
+ return base64ToBytes(string).length
7057
+ default:
7058
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
7059
+ encoding = ('' + encoding).toLowerCase();
7060
+ loweredCase = true;
7061
+ }
7062
+ }
7063
+ }
7064
+ Buffer.byteLength = byteLength;
7065
+
7066
+ function slowToString (encoding, start, end) {
7067
+ var loweredCase = false;
7068
+
7069
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7070
+ // property of a typed array.
7071
+
7072
+ // This behaves neither like String nor Uint8Array in that we set start/end
7073
+ // to their upper/lower bounds if the value passed is out of range.
7074
+ // undefined is handled specially as per ECMA-262 6th Edition,
7075
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7076
+ if (start === undefined || start < 0) {
7077
+ start = 0;
7078
+ }
7079
+ // Return early if start > this.length. Done here to prevent potential uint32
7080
+ // coercion fail below.
7081
+ if (start > this.length) {
7082
+ return ''
7083
+ }
7084
+
7085
+ if (end === undefined || end > this.length) {
7086
+ end = this.length;
7087
+ }
7088
+
7089
+ if (end <= 0) {
7090
+ return ''
7091
+ }
7092
+
7093
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
7094
+ end >>>= 0;
7095
+ start >>>= 0;
7096
+
7097
+ if (end <= start) {
7098
+ return ''
7099
+ }
7100
+
7101
+ if (!encoding) encoding = 'utf8';
7102
+
7103
+ while (true) {
7104
+ switch (encoding) {
7105
+ case 'hex':
7106
+ return hexSlice(this, start, end)
7107
+
7108
+ case 'utf8':
7109
+ case 'utf-8':
7110
+ return utf8Slice(this, start, end)
7111
+
7112
+ case 'ascii':
7113
+ return asciiSlice(this, start, end)
7114
+
7115
+ case 'latin1':
7116
+ case 'binary':
7117
+ return latin1Slice(this, start, end)
7118
+
7119
+ case 'base64':
7120
+ return base64Slice(this, start, end)
7121
+
7122
+ case 'ucs2':
7123
+ case 'ucs-2':
7124
+ case 'utf16le':
7125
+ case 'utf-16le':
7126
+ return utf16leSlice(this, start, end)
7127
+
7128
+ default:
7129
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7130
+ encoding = (encoding + '').toLowerCase();
7131
+ loweredCase = true;
7132
+ }
7133
+ }
7134
+ }
7135
+
7136
+ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
7137
+ // Buffer instances.
7138
+ Buffer.prototype._isBuffer = true;
7139
+
7140
+ function swap (b, n, m) {
7141
+ var i = b[n];
7142
+ b[n] = b[m];
7143
+ b[m] = i;
7144
+ }
7145
+
7146
+ Buffer.prototype.swap16 = function swap16 () {
7147
+ var len = this.length;
7148
+ if (len % 2 !== 0) {
7149
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
7150
+ }
7151
+ for (var i = 0; i < len; i += 2) {
7152
+ swap(this, i, i + 1);
7153
+ }
7154
+ return this
7155
+ };
7156
+
7157
+ Buffer.prototype.swap32 = function swap32 () {
7158
+ var len = this.length;
7159
+ if (len % 4 !== 0) {
7160
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
7161
+ }
7162
+ for (var i = 0; i < len; i += 4) {
7163
+ swap(this, i, i + 3);
7164
+ swap(this, i + 1, i + 2);
7165
+ }
7166
+ return this
7167
+ };
7168
+
7169
+ Buffer.prototype.swap64 = function swap64 () {
7170
+ var len = this.length;
7171
+ if (len % 8 !== 0) {
7172
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
7173
+ }
7174
+ for (var i = 0; i < len; i += 8) {
7175
+ swap(this, i, i + 7);
7176
+ swap(this, i + 1, i + 6);
7177
+ swap(this, i + 2, i + 5);
7178
+ swap(this, i + 3, i + 4);
7179
+ }
7180
+ return this
7181
+ };
7182
+
7183
+ Buffer.prototype.toString = function toString () {
7184
+ var length = this.length | 0;
7185
+ if (length === 0) return ''
7186
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
7187
+ return slowToString.apply(this, arguments)
7188
+ };
7189
+
7190
+ Buffer.prototype.equals = function equals (b) {
7191
+ if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
7192
+ if (this === b) return true
7193
+ return Buffer.compare(this, b) === 0
7194
+ };
7195
+
7196
+ Buffer.prototype.inspect = function inspect () {
7197
+ var str = '';
7198
+ var max = INSPECT_MAX_BYTES;
7199
+ if (this.length > 0) {
7200
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
7201
+ if (this.length > max) str += ' ... ';
7202
+ }
7203
+ return '<Buffer ' + str + '>'
7204
+ };
7205
+
7206
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
7207
+ if (!internalIsBuffer(target)) {
7208
+ throw new TypeError('Argument must be a Buffer')
7209
+ }
7210
+
7211
+ if (start === undefined) {
7212
+ start = 0;
7213
+ }
7214
+ if (end === undefined) {
7215
+ end = target ? target.length : 0;
7216
+ }
7217
+ if (thisStart === undefined) {
7218
+ thisStart = 0;
7219
+ }
7220
+ if (thisEnd === undefined) {
7221
+ thisEnd = this.length;
7222
+ }
7223
+
7224
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
7225
+ throw new RangeError('out of range index')
7226
+ }
7227
+
7228
+ if (thisStart >= thisEnd && start >= end) {
7229
+ return 0
7230
+ }
7231
+ if (thisStart >= thisEnd) {
7232
+ return -1
7233
+ }
7234
+ if (start >= end) {
7235
+ return 1
7236
+ }
7237
+
7238
+ start >>>= 0;
7239
+ end >>>= 0;
7240
+ thisStart >>>= 0;
7241
+ thisEnd >>>= 0;
7242
+
7243
+ if (this === target) return 0
7244
+
7245
+ var x = thisEnd - thisStart;
7246
+ var y = end - start;
7247
+ var len = Math.min(x, y);
7248
+
7249
+ var thisCopy = this.slice(thisStart, thisEnd);
7250
+ var targetCopy = target.slice(start, end);
7251
+
7252
+ for (var i = 0; i < len; ++i) {
7253
+ if (thisCopy[i] !== targetCopy[i]) {
7254
+ x = thisCopy[i];
7255
+ y = targetCopy[i];
7256
+ break
7257
+ }
7258
+ }
7259
+
7260
+ if (x < y) return -1
7261
+ if (y < x) return 1
7262
+ return 0
7263
+ };
7264
+
7265
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7266
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7267
+ //
7268
+ // Arguments:
7269
+ // - buffer - a Buffer to search
7270
+ // - val - a string, Buffer, or number
7271
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
7272
+ // - encoding - an optional encoding, relevant is val is a string
7273
+ // - dir - true for indexOf, false for lastIndexOf
7274
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7275
+ // Empty buffer means no match
7276
+ if (buffer.length === 0) return -1
7277
+
7278
+ // Normalize byteOffset
7279
+ if (typeof byteOffset === 'string') {
7280
+ encoding = byteOffset;
7281
+ byteOffset = 0;
7282
+ } else if (byteOffset > 0x7fffffff) {
7283
+ byteOffset = 0x7fffffff;
7284
+ } else if (byteOffset < -0x80000000) {
7285
+ byteOffset = -0x80000000;
7286
+ }
7287
+ byteOffset = +byteOffset; // Coerce to Number.
7288
+ if (isNaN(byteOffset)) {
7289
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7290
+ byteOffset = dir ? 0 : (buffer.length - 1);
7291
+ }
7292
+
7293
+ // Normalize byteOffset: negative offsets start from the end of the buffer
7294
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
7295
+ if (byteOffset >= buffer.length) {
7296
+ if (dir) return -1
7297
+ else byteOffset = buffer.length - 1;
7298
+ } else if (byteOffset < 0) {
7299
+ if (dir) byteOffset = 0;
7300
+ else return -1
7301
+ }
7302
+
7303
+ // Normalize val
7304
+ if (typeof val === 'string') {
7305
+ val = Buffer.from(val, encoding);
7306
+ }
7307
+
7308
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
7309
+ if (internalIsBuffer(val)) {
7310
+ // Special case: looking for empty string/buffer always fails
7311
+ if (val.length === 0) {
7312
+ return -1
7313
+ }
7314
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7315
+ } else if (typeof val === 'number') {
7316
+ val = val & 0xFF; // Search for a byte value [0-255]
7317
+ if (Buffer.TYPED_ARRAY_SUPPORT &&
7318
+ typeof Uint8Array.prototype.indexOf === 'function') {
7319
+ if (dir) {
7320
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7321
+ } else {
7322
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7323
+ }
7324
+ }
7325
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
7326
+ }
7327
+
7328
+ throw new TypeError('val must be string, number or Buffer')
7329
+ }
7330
+
7331
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7332
+ var indexSize = 1;
7333
+ var arrLength = arr.length;
7334
+ var valLength = val.length;
7335
+
7336
+ if (encoding !== undefined) {
7337
+ encoding = String(encoding).toLowerCase();
7338
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7339
+ encoding === 'utf16le' || encoding === 'utf-16le') {
7340
+ if (arr.length < 2 || val.length < 2) {
7341
+ return -1
7342
+ }
7343
+ indexSize = 2;
7344
+ arrLength /= 2;
7345
+ valLength /= 2;
7346
+ byteOffset /= 2;
7347
+ }
7348
+ }
7349
+
7350
+ function read (buf, i) {
7351
+ if (indexSize === 1) {
7352
+ return buf[i]
7353
+ } else {
7354
+ return buf.readUInt16BE(i * indexSize)
7355
+ }
7356
+ }
7357
+
7358
+ var i;
7359
+ if (dir) {
7360
+ var foundIndex = -1;
7361
+ for (i = byteOffset; i < arrLength; i++) {
7362
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7363
+ if (foundIndex === -1) foundIndex = i;
7364
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7365
+ } else {
7366
+ if (foundIndex !== -1) i -= i - foundIndex;
7367
+ foundIndex = -1;
7368
+ }
7369
+ }
7370
+ } else {
7371
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
7372
+ for (i = byteOffset; i >= 0; i--) {
7373
+ var found = true;
7374
+ for (var j = 0; j < valLength; j++) {
7375
+ if (read(arr, i + j) !== read(val, j)) {
7376
+ found = false;
7377
+ break
7378
+ }
7379
+ }
7380
+ if (found) return i
7381
+ }
7382
+ }
7383
+
7384
+ return -1
7385
+ }
7386
+
7387
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7388
+ return this.indexOf(val, byteOffset, encoding) !== -1
7389
+ };
7390
+
7391
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7392
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7393
+ };
7394
+
7395
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7396
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7397
+ };
7398
+
7399
+ function hexWrite (buf, string, offset, length) {
7400
+ offset = Number(offset) || 0;
7401
+ var remaining = buf.length - offset;
7402
+ if (!length) {
7403
+ length = remaining;
7404
+ } else {
7405
+ length = Number(length);
7406
+ if (length > remaining) {
7407
+ length = remaining;
7408
+ }
7409
+ }
7410
+
7411
+ // must be an even number of digits
7412
+ var strLen = string.length;
7413
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
7414
+
7415
+ if (length > strLen / 2) {
7416
+ length = strLen / 2;
7417
+ }
7418
+ for (var i = 0; i < length; ++i) {
7419
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
7420
+ if (isNaN(parsed)) return i
7421
+ buf[offset + i] = parsed;
7422
+ }
7423
+ return i
7424
+ }
7425
+
7426
+ function utf8Write (buf, string, offset, length) {
7427
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7428
+ }
7429
+
7430
+ function asciiWrite (buf, string, offset, length) {
7431
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
7432
+ }
7433
+
7434
+ function latin1Write (buf, string, offset, length) {
7435
+ return asciiWrite(buf, string, offset, length)
7436
+ }
7437
+
7438
+ function base64Write (buf, string, offset, length) {
7439
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
7440
+ }
7441
+
7442
+ function ucs2Write (buf, string, offset, length) {
7443
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7444
+ }
7445
+
7446
+ Buffer.prototype.write = function write (string, offset, length, encoding) {
7447
+ // Buffer#write(string)
7448
+ if (offset === undefined) {
7449
+ encoding = 'utf8';
7450
+ length = this.length;
7451
+ offset = 0;
7452
+ // Buffer#write(string, encoding)
7453
+ } else if (length === undefined && typeof offset === 'string') {
7454
+ encoding = offset;
7455
+ length = this.length;
7456
+ offset = 0;
7457
+ // Buffer#write(string, offset[, length][, encoding])
7458
+ } else if (isFinite(offset)) {
7459
+ offset = offset | 0;
7460
+ if (isFinite(length)) {
7461
+ length = length | 0;
7462
+ if (encoding === undefined) encoding = 'utf8';
7463
+ } else {
7464
+ encoding = length;
7465
+ length = undefined;
7466
+ }
7467
+ // legacy write(string, encoding, offset, length) - remove in v0.13
7468
+ } else {
7469
+ throw new Error(
7470
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7471
+ )
7472
+ }
7473
+
7474
+ var remaining = this.length - offset;
7475
+ if (length === undefined || length > remaining) length = remaining;
7476
+
7477
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7478
+ throw new RangeError('Attempt to write outside buffer bounds')
7479
+ }
7480
+
7481
+ if (!encoding) encoding = 'utf8';
7482
+
7483
+ var loweredCase = false;
7484
+ for (;;) {
7485
+ switch (encoding) {
7486
+ case 'hex':
7487
+ return hexWrite(this, string, offset, length)
7488
+
7489
+ case 'utf8':
7490
+ case 'utf-8':
7491
+ return utf8Write(this, string, offset, length)
7492
+
7493
+ case 'ascii':
7494
+ return asciiWrite(this, string, offset, length)
7495
+
7496
+ case 'latin1':
7497
+ case 'binary':
7498
+ return latin1Write(this, string, offset, length)
7499
+
7500
+ case 'base64':
7501
+ // Warning: maxLength not taken into account in base64Write
7502
+ return base64Write(this, string, offset, length)
7503
+
7504
+ case 'ucs2':
7505
+ case 'ucs-2':
7506
+ case 'utf16le':
7507
+ case 'utf-16le':
7508
+ return ucs2Write(this, string, offset, length)
7509
+
7510
+ default:
7511
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7512
+ encoding = ('' + encoding).toLowerCase();
7513
+ loweredCase = true;
7514
+ }
7515
+ }
7516
+ };
7517
+
7518
+ Buffer.prototype.toJSON = function toJSON () {
7519
+ return {
7520
+ type: 'Buffer',
7521
+ data: Array.prototype.slice.call(this._arr || this, 0)
7522
+ }
7523
+ };
7524
+
7525
+ function base64Slice (buf, start, end) {
7526
+ if (start === 0 && end === buf.length) {
7527
+ return fromByteArray(buf)
7528
+ } else {
7529
+ return fromByteArray(buf.slice(start, end))
7530
+ }
7531
+ }
7532
+
7533
+ function utf8Slice (buf, start, end) {
7534
+ end = Math.min(buf.length, end);
7535
+ var res = [];
7536
+
7537
+ var i = start;
7538
+ while (i < end) {
7539
+ var firstByte = buf[i];
7540
+ var codePoint = null;
7541
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
7542
+ : (firstByte > 0xDF) ? 3
7543
+ : (firstByte > 0xBF) ? 2
7544
+ : 1;
7545
+
7546
+ if (i + bytesPerSequence <= end) {
7547
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
7548
+
7549
+ switch (bytesPerSequence) {
7550
+ case 1:
7551
+ if (firstByte < 0x80) {
7552
+ codePoint = firstByte;
7553
+ }
7554
+ break
7555
+ case 2:
7556
+ secondByte = buf[i + 1];
7557
+ if ((secondByte & 0xC0) === 0x80) {
7558
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
7559
+ if (tempCodePoint > 0x7F) {
7560
+ codePoint = tempCodePoint;
7561
+ }
7562
+ }
7563
+ break
7564
+ case 3:
7565
+ secondByte = buf[i + 1];
7566
+ thirdByte = buf[i + 2];
7567
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7568
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
7569
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7570
+ codePoint = tempCodePoint;
7571
+ }
7572
+ }
7573
+ break
7574
+ case 4:
7575
+ secondByte = buf[i + 1];
7576
+ thirdByte = buf[i + 2];
7577
+ fourthByte = buf[i + 3];
7578
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7579
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
7580
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7581
+ codePoint = tempCodePoint;
7582
+ }
7583
+ }
7584
+ }
7585
+ }
7586
+
7587
+ if (codePoint === null) {
7588
+ // we did not generate a valid codePoint so insert a
7589
+ // replacement char (U+FFFD) and advance only 1 byte
7590
+ codePoint = 0xFFFD;
7591
+ bytesPerSequence = 1;
7592
+ } else if (codePoint > 0xFFFF) {
7593
+ // encode to utf16 (surrogate pair dance)
7594
+ codePoint -= 0x10000;
7595
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
7596
+ codePoint = 0xDC00 | codePoint & 0x3FF;
7597
+ }
7598
+
7599
+ res.push(codePoint);
7600
+ i += bytesPerSequence;
7601
+ }
7602
+
7603
+ return decodeCodePointsArray(res)
7604
+ }
7605
+
7606
+ // Based on http://stackoverflow.com/a/22747272/680742, the browser with
7607
+ // the lowest limit is Chrome, with 0x10000 args.
7608
+ // We go 1 magnitude less, for safety
7609
+ var MAX_ARGUMENTS_LENGTH = 0x1000;
7610
+
7611
+ function decodeCodePointsArray (codePoints) {
7612
+ var len = codePoints.length;
7613
+ if (len <= MAX_ARGUMENTS_LENGTH) {
7614
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
7615
+ }
7616
+
7617
+ // Decode in chunks to avoid "call stack size exceeded".
7618
+ var res = '';
7619
+ var i = 0;
7620
+ while (i < len) {
7621
+ res += String.fromCharCode.apply(
7622
+ String,
7623
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
7624
+ );
7625
+ }
7626
+ return res
7627
+ }
7628
+
7629
+ function asciiSlice (buf, start, end) {
7630
+ var ret = '';
7631
+ end = Math.min(buf.length, end);
7632
+
7633
+ for (var i = start; i < end; ++i) {
7634
+ ret += String.fromCharCode(buf[i] & 0x7F);
7635
+ }
7636
+ return ret
7637
+ }
7638
+
7639
+ function latin1Slice (buf, start, end) {
7640
+ var ret = '';
7641
+ end = Math.min(buf.length, end);
7642
+
7643
+ for (var i = start; i < end; ++i) {
7644
+ ret += String.fromCharCode(buf[i]);
7645
+ }
7646
+ return ret
7647
+ }
7648
+
7649
+ function hexSlice (buf, start, end) {
7650
+ var len = buf.length;
7651
+
7652
+ if (!start || start < 0) start = 0;
7653
+ if (!end || end < 0 || end > len) end = len;
7654
+
7655
+ var out = '';
7656
+ for (var i = start; i < end; ++i) {
7657
+ out += toHex(buf[i]);
7658
+ }
7659
+ return out
7660
+ }
7661
+
7662
+ function utf16leSlice (buf, start, end) {
7663
+ var bytes = buf.slice(start, end);
7664
+ var res = '';
7665
+ for (var i = 0; i < bytes.length; i += 2) {
7666
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
7667
+ }
7668
+ return res
7669
+ }
7670
+
7671
+ Buffer.prototype.slice = function slice (start, end) {
7672
+ var len = this.length;
7673
+ start = ~~start;
7674
+ end = end === undefined ? len : ~~end;
7675
+
7676
+ if (start < 0) {
7677
+ start += len;
7678
+ if (start < 0) start = 0;
7679
+ } else if (start > len) {
7680
+ start = len;
7681
+ }
7682
+
7683
+ if (end < 0) {
7684
+ end += len;
7685
+ if (end < 0) end = 0;
7686
+ } else if (end > len) {
7687
+ end = len;
7688
+ }
7689
+
7690
+ if (end < start) end = start;
7691
+
7692
+ var newBuf;
7693
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7694
+ newBuf = this.subarray(start, end);
7695
+ newBuf.__proto__ = Buffer.prototype;
7696
+ } else {
7697
+ var sliceLen = end - start;
7698
+ newBuf = new Buffer(sliceLen, undefined);
7699
+ for (var i = 0; i < sliceLen; ++i) {
7700
+ newBuf[i] = this[i + start];
7701
+ }
7702
+ }
7703
+
7704
+ return newBuf
7705
+ };
7706
+
7707
+ /*
7708
+ * Need to make sure that buffer isn't trying to write out of bounds.
7709
+ */
7710
+ function checkOffset (offset, ext, length) {
7711
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
7712
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
7713
+ }
7714
+
7715
+ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
7716
+ offset = offset | 0;
7717
+ byteLength = byteLength | 0;
7718
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7719
+
7720
+ var val = this[offset];
7721
+ var mul = 1;
7722
+ var i = 0;
7723
+ while (++i < byteLength && (mul *= 0x100)) {
7724
+ val += this[offset + i] * mul;
7725
+ }
7726
+
7727
+ return val
7728
+ };
7729
+
7730
+ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
7731
+ offset = offset | 0;
7732
+ byteLength = byteLength | 0;
7733
+ if (!noAssert) {
7734
+ checkOffset(offset, byteLength, this.length);
7735
+ }
7736
+
7737
+ var val = this[offset + --byteLength];
7738
+ var mul = 1;
7739
+ while (byteLength > 0 && (mul *= 0x100)) {
7740
+ val += this[offset + --byteLength] * mul;
7741
+ }
7742
+
7743
+ return val
7744
+ };
7745
+
7746
+ Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
7747
+ if (!noAssert) checkOffset(offset, 1, this.length);
7748
+ return this[offset]
7749
+ };
7750
+
7751
+ Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
7752
+ if (!noAssert) checkOffset(offset, 2, this.length);
7753
+ return this[offset] | (this[offset + 1] << 8)
7754
+ };
7755
+
7756
+ Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
7757
+ if (!noAssert) checkOffset(offset, 2, this.length);
7758
+ return (this[offset] << 8) | this[offset + 1]
7759
+ };
7760
+
7761
+ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
7762
+ if (!noAssert) checkOffset(offset, 4, this.length);
7763
+
7764
+ return ((this[offset]) |
7765
+ (this[offset + 1] << 8) |
7766
+ (this[offset + 2] << 16)) +
7767
+ (this[offset + 3] * 0x1000000)
7768
+ };
7769
+
7770
+ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
7771
+ if (!noAssert) checkOffset(offset, 4, this.length);
7772
+
7773
+ return (this[offset] * 0x1000000) +
7774
+ ((this[offset + 1] << 16) |
7775
+ (this[offset + 2] << 8) |
7776
+ this[offset + 3])
7777
+ };
7778
+
7779
+ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
7780
+ offset = offset | 0;
7781
+ byteLength = byteLength | 0;
7782
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7783
+
7784
+ var val = this[offset];
7785
+ var mul = 1;
7786
+ var i = 0;
7787
+ while (++i < byteLength && (mul *= 0x100)) {
7788
+ val += this[offset + i] * mul;
7789
+ }
7790
+ mul *= 0x80;
7791
+
7792
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
7793
+
7794
+ return val
7795
+ };
7796
+
7797
+ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
7798
+ offset = offset | 0;
7799
+ byteLength = byteLength | 0;
7800
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
7801
+
7802
+ var i = byteLength;
7803
+ var mul = 1;
7804
+ var val = this[offset + --i];
7805
+ while (i > 0 && (mul *= 0x100)) {
7806
+ val += this[offset + --i] * mul;
7807
+ }
7808
+ mul *= 0x80;
7809
+
7810
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
7811
+
7812
+ return val
7813
+ };
7814
+
7815
+ Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
7816
+ if (!noAssert) checkOffset(offset, 1, this.length);
7817
+ if (!(this[offset] & 0x80)) return (this[offset])
7818
+ return ((0xff - this[offset] + 1) * -1)
7819
+ };
7820
+
7821
+ Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
7822
+ if (!noAssert) checkOffset(offset, 2, this.length);
7823
+ var val = this[offset] | (this[offset + 1] << 8);
7824
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
7825
+ };
7826
+
7827
+ Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
7828
+ if (!noAssert) checkOffset(offset, 2, this.length);
7829
+ var val = this[offset + 1] | (this[offset] << 8);
7830
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
7831
+ };
7832
+
7833
+ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
7834
+ if (!noAssert) checkOffset(offset, 4, this.length);
7835
+
7836
+ return (this[offset]) |
7837
+ (this[offset + 1] << 8) |
7838
+ (this[offset + 2] << 16) |
7839
+ (this[offset + 3] << 24)
7840
+ };
7841
+
7842
+ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
7843
+ if (!noAssert) checkOffset(offset, 4, this.length);
7844
+
7845
+ return (this[offset] << 24) |
7846
+ (this[offset + 1] << 16) |
7847
+ (this[offset + 2] << 8) |
7848
+ (this[offset + 3])
7849
+ };
7850
+
7851
+ Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
7852
+ if (!noAssert) checkOffset(offset, 4, this.length);
7853
+ return read(this, offset, true, 23, 4)
7854
+ };
7855
+
7856
+ Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
7857
+ if (!noAssert) checkOffset(offset, 4, this.length);
7858
+ return read(this, offset, false, 23, 4)
7859
+ };
7860
+
7861
+ Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
7862
+ if (!noAssert) checkOffset(offset, 8, this.length);
7863
+ return read(this, offset, true, 52, 8)
7864
+ };
7865
+
7866
+ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
7867
+ if (!noAssert) checkOffset(offset, 8, this.length);
7868
+ return read(this, offset, false, 52, 8)
7869
+ };
7870
+
7871
+ function checkInt (buf, value, offset, ext, max, min) {
7872
+ if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
7873
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
7874
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
7875
+ }
7876
+
7877
+ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
7878
+ value = +value;
7879
+ offset = offset | 0;
7880
+ byteLength = byteLength | 0;
7881
+ if (!noAssert) {
7882
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
7883
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
7884
+ }
7885
+
7886
+ var mul = 1;
7887
+ var i = 0;
7888
+ this[offset] = value & 0xFF;
7889
+ while (++i < byteLength && (mul *= 0x100)) {
7890
+ this[offset + i] = (value / mul) & 0xFF;
7891
+ }
7892
+
7893
+ return offset + byteLength
7894
+ };
7895
+
7896
+ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
7897
+ value = +value;
7898
+ offset = offset | 0;
7899
+ byteLength = byteLength | 0;
7900
+ if (!noAssert) {
7901
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1;
7902
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
7903
+ }
7904
+
7905
+ var i = byteLength - 1;
7906
+ var mul = 1;
7907
+ this[offset + i] = value & 0xFF;
7908
+ while (--i >= 0 && (mul *= 0x100)) {
7909
+ this[offset + i] = (value / mul) & 0xFF;
7910
+ }
7911
+
7912
+ return offset + byteLength
7913
+ };
7914
+
7915
+ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
7916
+ value = +value;
7917
+ offset = offset | 0;
7918
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
7919
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
7920
+ this[offset] = (value & 0xff);
7921
+ return offset + 1
7922
+ };
7923
+
7924
+ function objectWriteUInt16 (buf, value, offset, littleEndian) {
7925
+ if (value < 0) value = 0xffff + value + 1;
7926
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
7927
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
7928
+ (littleEndian ? i : 1 - i) * 8;
7929
+ }
7930
+ }
7931
+
7932
+ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
7933
+ value = +value;
7934
+ offset = offset | 0;
7935
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
7936
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7937
+ this[offset] = (value & 0xff);
7938
+ this[offset + 1] = (value >>> 8);
7939
+ } else {
7940
+ objectWriteUInt16(this, value, offset, true);
7941
+ }
7942
+ return offset + 2
7943
+ };
7944
+
7945
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
7946
+ value = +value;
7947
+ offset = offset | 0;
7948
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
7949
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7950
+ this[offset] = (value >>> 8);
7951
+ this[offset + 1] = (value & 0xff);
7952
+ } else {
7953
+ objectWriteUInt16(this, value, offset, false);
7954
+ }
7955
+ return offset + 2
7956
+ };
7957
+
7958
+ function objectWriteUInt32 (buf, value, offset, littleEndian) {
7959
+ if (value < 0) value = 0xffffffff + value + 1;
7960
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
7961
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
7962
+ }
7963
+ }
7964
+
7965
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
7966
+ value = +value;
7967
+ offset = offset | 0;
7968
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
7969
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7970
+ this[offset + 3] = (value >>> 24);
7971
+ this[offset + 2] = (value >>> 16);
7972
+ this[offset + 1] = (value >>> 8);
7973
+ this[offset] = (value & 0xff);
7974
+ } else {
7975
+ objectWriteUInt32(this, value, offset, true);
7976
+ }
7977
+ return offset + 4
7978
+ };
7979
+
7980
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
7981
+ value = +value;
7982
+ offset = offset | 0;
7983
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
7984
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
7985
+ this[offset] = (value >>> 24);
7986
+ this[offset + 1] = (value >>> 16);
7987
+ this[offset + 2] = (value >>> 8);
7988
+ this[offset + 3] = (value & 0xff);
7989
+ } else {
7990
+ objectWriteUInt32(this, value, offset, false);
7991
+ }
7992
+ return offset + 4
7993
+ };
7994
+
7995
+ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
7996
+ value = +value;
7997
+ offset = offset | 0;
7998
+ if (!noAssert) {
7999
+ var limit = Math.pow(2, 8 * byteLength - 1);
8000
+
8001
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
8002
+ }
8003
+
8004
+ var i = 0;
8005
+ var mul = 1;
8006
+ var sub = 0;
8007
+ this[offset] = value & 0xFF;
8008
+ while (++i < byteLength && (mul *= 0x100)) {
8009
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
8010
+ sub = 1;
8011
+ }
8012
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
8013
+ }
8014
+
8015
+ return offset + byteLength
8016
+ };
8017
+
8018
+ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
8019
+ value = +value;
8020
+ offset = offset | 0;
8021
+ if (!noAssert) {
8022
+ var limit = Math.pow(2, 8 * byteLength - 1);
8023
+
8024
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
8025
+ }
8026
+
8027
+ var i = byteLength - 1;
8028
+ var mul = 1;
8029
+ var sub = 0;
8030
+ this[offset + i] = value & 0xFF;
8031
+ while (--i >= 0 && (mul *= 0x100)) {
8032
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
8033
+ sub = 1;
8034
+ }
8035
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
8036
+ }
8037
+
8038
+ return offset + byteLength
8039
+ };
8040
+
8041
+ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8042
+ value = +value;
8043
+ offset = offset | 0;
8044
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
8045
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
8046
+ if (value < 0) value = 0xff + value + 1;
8047
+ this[offset] = (value & 0xff);
8048
+ return offset + 1
8049
+ };
8050
+
8051
+ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8052
+ value = +value;
8053
+ offset = offset | 0;
8054
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
8055
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8056
+ this[offset] = (value & 0xff);
8057
+ this[offset + 1] = (value >>> 8);
8058
+ } else {
8059
+ objectWriteUInt16(this, value, offset, true);
8060
+ }
8061
+ return offset + 2
8062
+ };
8063
+
8064
+ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8065
+ value = +value;
8066
+ offset = offset | 0;
8067
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
8068
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8069
+ this[offset] = (value >>> 8);
8070
+ this[offset + 1] = (value & 0xff);
8071
+ } else {
8072
+ objectWriteUInt16(this, value, offset, false);
8073
+ }
8074
+ return offset + 2
8075
+ };
8076
+
8077
+ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8078
+ value = +value;
8079
+ offset = offset | 0;
8080
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
8081
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8082
+ this[offset] = (value & 0xff);
8083
+ this[offset + 1] = (value >>> 8);
8084
+ this[offset + 2] = (value >>> 16);
8085
+ this[offset + 3] = (value >>> 24);
8086
+ } else {
8087
+ objectWriteUInt32(this, value, offset, true);
8088
+ }
8089
+ return offset + 4
8090
+ };
8091
+
8092
+ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8093
+ value = +value;
8094
+ offset = offset | 0;
8095
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
8096
+ if (value < 0) value = 0xffffffff + value + 1;
8097
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
8098
+ this[offset] = (value >>> 24);
8099
+ this[offset + 1] = (value >>> 16);
8100
+ this[offset + 2] = (value >>> 8);
8101
+ this[offset + 3] = (value & 0xff);
8102
+ } else {
8103
+ objectWriteUInt32(this, value, offset, false);
8104
+ }
8105
+ return offset + 4
8106
+ };
8107
+
8108
+ function checkIEEE754 (buf, value, offset, ext, max, min) {
8109
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
8110
+ if (offset < 0) throw new RangeError('Index out of range')
8111
+ }
8112
+
8113
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
8114
+ if (!noAssert) {
8115
+ checkIEEE754(buf, value, offset, 4);
8116
+ }
8117
+ write(buf, value, offset, littleEndian, 23, 4);
8118
+ return offset + 4
8119
+ }
8120
+
8121
+ Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8122
+ return writeFloat(this, value, offset, true, noAssert)
8123
+ };
8124
+
8125
+ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8126
+ return writeFloat(this, value, offset, false, noAssert)
8127
+ };
8128
+
8129
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
8130
+ if (!noAssert) {
8131
+ checkIEEE754(buf, value, offset, 8);
8132
+ }
8133
+ write(buf, value, offset, littleEndian, 52, 8);
8134
+ return offset + 8
8135
+ }
8136
+
8137
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
8138
+ return writeDouble(this, value, offset, true, noAssert)
8139
+ };
8140
+
8141
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
8142
+ return writeDouble(this, value, offset, false, noAssert)
8143
+ };
8144
+
8145
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8146
+ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8147
+ if (!start) start = 0;
8148
+ if (!end && end !== 0) end = this.length;
8149
+ if (targetStart >= target.length) targetStart = target.length;
8150
+ if (!targetStart) targetStart = 0;
8151
+ if (end > 0 && end < start) end = start;
8152
+
8153
+ // Copy 0 bytes; we're done
8154
+ if (end === start) return 0
8155
+ if (target.length === 0 || this.length === 0) return 0
8156
+
8157
+ // Fatal error conditions
8158
+ if (targetStart < 0) {
8159
+ throw new RangeError('targetStart out of bounds')
8160
+ }
8161
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
8162
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
8163
+
8164
+ // Are we oob?
8165
+ if (end > this.length) end = this.length;
8166
+ if (target.length - targetStart < end - start) {
8167
+ end = target.length - targetStart + start;
8168
+ }
8169
+
8170
+ var len = end - start;
8171
+ var i;
8172
+
8173
+ if (this === target && start < targetStart && targetStart < end) {
8174
+ // descending copy from end
8175
+ for (i = len - 1; i >= 0; --i) {
8176
+ target[i + targetStart] = this[i + start];
8177
+ }
8178
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
8179
+ // ascending copy from start
8180
+ for (i = 0; i < len; ++i) {
8181
+ target[i + targetStart] = this[i + start];
8182
+ }
8183
+ } else {
8184
+ Uint8Array.prototype.set.call(
8185
+ target,
8186
+ this.subarray(start, start + len),
8187
+ targetStart
8188
+ );
8189
+ }
8190
+
8191
+ return len
8192
+ };
8193
+
8194
+ // Usage:
8195
+ // buffer.fill(number[, offset[, end]])
8196
+ // buffer.fill(buffer[, offset[, end]])
8197
+ // buffer.fill(string[, offset[, end]][, encoding])
8198
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
8199
+ // Handle string cases:
8200
+ if (typeof val === 'string') {
8201
+ if (typeof start === 'string') {
8202
+ encoding = start;
8203
+ start = 0;
8204
+ end = this.length;
8205
+ } else if (typeof end === 'string') {
8206
+ encoding = end;
8207
+ end = this.length;
8208
+ }
8209
+ if (val.length === 1) {
8210
+ var code = val.charCodeAt(0);
8211
+ if (code < 256) {
8212
+ val = code;
8213
+ }
8214
+ }
8215
+ if (encoding !== undefined && typeof encoding !== 'string') {
8216
+ throw new TypeError('encoding must be a string')
8217
+ }
8218
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8219
+ throw new TypeError('Unknown encoding: ' + encoding)
8220
+ }
8221
+ } else if (typeof val === 'number') {
8222
+ val = val & 255;
8223
+ }
8224
+
8225
+ // Invalid ranges are not set to a default, so can range check early.
8226
+ if (start < 0 || this.length < start || this.length < end) {
8227
+ throw new RangeError('Out of range index')
8228
+ }
8229
+
8230
+ if (end <= start) {
8231
+ return this
8232
+ }
8233
+
8234
+ start = start >>> 0;
8235
+ end = end === undefined ? this.length : end >>> 0;
8236
+
8237
+ if (!val) val = 0;
8238
+
8239
+ var i;
8240
+ if (typeof val === 'number') {
8241
+ for (i = start; i < end; ++i) {
8242
+ this[i] = val;
8243
+ }
8244
+ } else {
8245
+ var bytes = internalIsBuffer(val)
8246
+ ? val
8247
+ : utf8ToBytes(new Buffer(val, encoding).toString());
8248
+ var len = bytes.length;
8249
+ for (i = 0; i < end - start; ++i) {
8250
+ this[i + start] = bytes[i % len];
8251
+ }
8252
+ }
8253
+
8254
+ return this
8255
+ };
8256
+
8257
+ // HELPER FUNCTIONS
8258
+ // ================
8259
+
8260
+ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
8261
+
8262
+ function base64clean (str) {
8263
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
8264
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '');
8265
+ // Node converts strings with length < 2 to ''
8266
+ if (str.length < 2) return ''
8267
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
8268
+ while (str.length % 4 !== 0) {
8269
+ str = str + '=';
8270
+ }
8271
+ return str
8272
+ }
8273
+
8274
+ function stringtrim (str) {
8275
+ if (str.trim) return str.trim()
8276
+ return str.replace(/^\s+|\s+$/g, '')
8277
+ }
8278
+
8279
+ function toHex (n) {
8280
+ if (n < 16) return '0' + n.toString(16)
8281
+ return n.toString(16)
8282
+ }
8283
+
8284
+ function utf8ToBytes (string, units) {
8285
+ units = units || Infinity;
8286
+ var codePoint;
8287
+ var length = string.length;
8288
+ var leadSurrogate = null;
8289
+ var bytes = [];
8290
+
8291
+ for (var i = 0; i < length; ++i) {
8292
+ codePoint = string.charCodeAt(i);
8293
+
8294
+ // is surrogate component
8295
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
8296
+ // last char was a lead
8297
+ if (!leadSurrogate) {
8298
+ // no lead yet
8299
+ if (codePoint > 0xDBFF) {
8300
+ // unexpected trail
8301
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8302
+ continue
8303
+ } else if (i + 1 === length) {
8304
+ // unpaired lead
8305
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8306
+ continue
8307
+ }
8308
+
8309
+ // valid lead
8310
+ leadSurrogate = codePoint;
8311
+
8312
+ continue
8313
+ }
8314
+
8315
+ // 2 leads in a row
8316
+ if (codePoint < 0xDC00) {
8317
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8318
+ leadSurrogate = codePoint;
8319
+ continue
8320
+ }
8321
+
8322
+ // valid surrogate pair
8323
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
8324
+ } else if (leadSurrogate) {
8325
+ // valid bmp char, but last char was a lead
8326
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
8327
+ }
8328
+
8329
+ leadSurrogate = null;
8330
+
8331
+ // encode utf8
8332
+ if (codePoint < 0x80) {
8333
+ if ((units -= 1) < 0) break
8334
+ bytes.push(codePoint);
8335
+ } else if (codePoint < 0x800) {
8336
+ if ((units -= 2) < 0) break
8337
+ bytes.push(
8338
+ codePoint >> 0x6 | 0xC0,
8339
+ codePoint & 0x3F | 0x80
8340
+ );
8341
+ } else if (codePoint < 0x10000) {
8342
+ if ((units -= 3) < 0) break
8343
+ bytes.push(
8344
+ codePoint >> 0xC | 0xE0,
8345
+ codePoint >> 0x6 & 0x3F | 0x80,
8346
+ codePoint & 0x3F | 0x80
8347
+ );
8348
+ } else if (codePoint < 0x110000) {
8349
+ if ((units -= 4) < 0) break
8350
+ bytes.push(
8351
+ codePoint >> 0x12 | 0xF0,
8352
+ codePoint >> 0xC & 0x3F | 0x80,
8353
+ codePoint >> 0x6 & 0x3F | 0x80,
8354
+ codePoint & 0x3F | 0x80
8355
+ );
8356
+ } else {
8357
+ throw new Error('Invalid code point')
8358
+ }
8359
+ }
8360
+
8361
+ return bytes
8362
+ }
8363
+
8364
+ function asciiToBytes (str) {
8365
+ var byteArray = [];
8366
+ for (var i = 0; i < str.length; ++i) {
8367
+ // Node's code seems to be doing this and not & 0x7F..
8368
+ byteArray.push(str.charCodeAt(i) & 0xFF);
8369
+ }
8370
+ return byteArray
8371
+ }
8372
+
8373
+ function utf16leToBytes (str, units) {
8374
+ var c, hi, lo;
8375
+ var byteArray = [];
8376
+ for (var i = 0; i < str.length; ++i) {
8377
+ if ((units -= 2) < 0) break
8378
+
8379
+ c = str.charCodeAt(i);
8380
+ hi = c >> 8;
8381
+ lo = c % 256;
8382
+ byteArray.push(lo);
8383
+ byteArray.push(hi);
8384
+ }
8385
+
8386
+ return byteArray
8387
+ }
8388
+
8389
+
8390
+ function base64ToBytes (str) {
8391
+ return toByteArray(base64clean(str))
8392
+ }
8393
+
8394
+ function blitBuffer (src, dst, offset, length) {
8395
+ for (var i = 0; i < length; ++i) {
8396
+ if ((i + offset >= dst.length) || (i >= src.length)) break
8397
+ dst[i + offset] = src[i];
8398
+ }
8399
+ return i
8400
+ }
8401
+
8402
+ function isnan (val) {
8403
+ return val !== val // eslint-disable-line no-self-compare
8404
+ }
8405
+
8406
+
8407
+ // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
8408
+ // The _isBuffer check is for Safari 5-7 support, because it's missing
8409
+ // Object.prototype.constructor. Remove this eventually
8410
+ function isBuffer(obj) {
8411
+ return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
8412
+ }
8413
+
8414
+ function isFastBuffer (obj) {
8415
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
8416
+ }
8417
+
8418
+ // For Node v0.10 support. Remove this eventually.
8419
+ function isSlowBuffer (obj) {
8420
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
8421
+ }
8422
+
6229
8423
  /**
6230
8424
  * Convert a data object to FormData
6231
8425
  * @param {Object} obj
@@ -6774,7 +8968,7 @@ function getDefaultAdapter() {
6774
8968
  if (typeof XMLHttpRequest !== 'undefined') {
6775
8969
  // For browsers use XHR adapter
6776
8970
  adapter = xhr;
6777
- } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
8971
+ } else if (typeof browser$1 !== 'undefined' && Object.prototype.toString.call(browser$1) === '[object process]') {
6778
8972
  // For node use HTTP adapter
6779
8973
  adapter = xhr;
6780
8974
  }
@@ -7551,4 +9745,4 @@ var axios = axios_1;
7551
9745
 
7552
9746
  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";
7553
9747
 
7554
- let i=function(e,t,a){return alert(e)},n=function(e,t){return i(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return i(e,t,a)},setNotifier:function(e){i=e;},error:n,success:function(e,t){return i(e,l.success,t)},info:function(e,t){return i(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&e.forEach((e=>{n(decodeURI(e.replace("?danger=","").replace("&danger=","")));}));},types:l};class d{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,s){return "event"===s?t:"api"===s?e:e&&e[s]||a[s]}})}}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,s=this,r=0;r<e.length;r++)a=new RegExp(e[r],"g"),s=s.replace(a,t[r]);return s},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 s=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(s="FORM"===this.tagName?this:s||this.closest("form")||this.closest("[salla-form-data]")||this,s&&"FORM"===s.tagName)return this.getFilteredData(new FormData(s),null,s);let r=s.querySelectorAll("[name]");if(!r.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return r.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let s=this.attributes[a].name.toLowerCase();if(0===s.indexOf(e))return !t||s}return !1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||a?.dataset||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((s=>{let r=a?.dataset[s]||this.dataset[s];if(r){var i=window[r];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${r}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+r+"() 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,t)};}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.dispatch(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){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",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.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",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed"},this.after_init();}},Salla.event.profile=new class extends c{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends c{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends c{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,(e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);}));}fireEvent(e,t,...a){return this.fireEventForElements(e,t,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...s){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...s)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const r=new CustomEvent(t,...s);return e.dispatchEvent(r)}},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 s=Array.isArray(e),r=s?this.getUrl(...e):this.getUrl(e);e=s?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1];})),t={params:e};}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?r=salla.url.get(r):"http"!==r.substring(0,4)&&(r=salla.url.api(r)),Salla.api.request(r,t,a,{headers:i})}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"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init();}async getCurrentCartId(){if(this.latestCart)return this.latestCart.cart.id;let e=await this.latest();return this.latestCart=e.data,this.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 s=await this.getCurrentCartId();return this.request([a,s,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return this.request(["deleteItem",a,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return "Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",a,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await this.getCurrentCartId();return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit();}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload();})).catch((function(e){throw salla.cart.event.submitFailed(e),e}));}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.storage.remove("cart"),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){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}))}}class g extends h{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class f extends h{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let s=await this.request(["verify",a],e);if(200!==s?.status)return salla.auth.event.verificationFailed(s,a),salla.api.errorPromise(s);let r="authenticated"===s.data?.case;return r&&salla.auth.event.tokenFetched(s.data.token),t&&await this.request("auth/jwt"),r&&salla.auth.event.loggedIn(s),salla.auth.event.verified(s,a),salla.auth.api.afterUserLogin(),salla.api.successPromise(s)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),await salla.auth.request("auth/jwt"),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return this.request("logout").then((function(e){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut(e),salla.log("Reloading after 0.2 sec..."),setTimeout((()=>location.reload()),200),e})).catch((function(e){throw salla.auth.event.failedLogout(e),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.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={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",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={giftDetail:"get"},this.after_init();}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribedFailed(t,e),t}))}search(e){let t=e.data;if(t||(t={params:"string"==typeof e?{query:e}:e}),!(e=t instanceof FormData?t.get("query"):t.query||t.params?.query)){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.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}))}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"]),s=salla.form.getPossibleValue(e,["type"]),r=salla.form.getPossibleValue(e,["comment"]);return a?s&&["products","pages","product","page"].includes(s)?r?(s+=["product","page"].includes(s)?"s":"",this.request(["add",s,a],{comment:r}).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 S extends h{constructor(){super(),this.namespace="document";}}class F 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 E 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 q{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),s=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,s).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}));}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1];})),a=e;}window[e]?window[e](t,a):salla.event.dispatch(e,t,a);}}setSallaReady(t){f$1.status="ready",f$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("salla::ready"));}}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 s=e.split("."),r=s.splice(-1);return await salla.call(s.join("."))[r](a).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){if(!e)return;if("object"!=typeof e)return e;let s;for(let a=0;a<t.length&&!(s=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(s=e.get(t[a])));a++);return s=s||e,"object"!=typeof s||a?s:void 0}},f$1.helpers.app=new class{toggleClassIf(e,t,a,s){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,a,s))),this}toggleElementClassIf(e,t,a,s){t=Array.isArray(t)?t:t.split(" "),a=Array.isArray(a)?a:a.split(" ");let r=s(e);return e?.classList.remove(...r?a:t),e?.classList.add(...r?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,s={}){return "object"==typeof t?(this.element(t).addEventListener(e,a,s),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,a,s))),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,s){s=this.getCustomOptions(a,s);let r="string"!=typeof e?e:document.querySelector(e),i=s.path;if(!r||!i||"string"==typeof i&&!document.querySelector(i))return void Salla.logger.warn(r?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new js(r,s);return n.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),n.on("request",Salla.infiniteScroll.event.request),n.on("load",Salla.infiniteScroll.event.load),n.on("append",Salla.infiniteScroll.event.append),n.on("error",Salla.infiniteScroll.event.error),n.on("last",Salla.infiniteScroll.event.last),n.on("history",Salla.infiniteScroll.event.history),this.instances.push(n),n}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}}(void 0,salla.event.infiniteScroll),f$1.api=new class extends class{constructor(){salla.event.on("twilight::initiated",(()=>this.initiateRequest())),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(){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:Salla.config.get("user.currency_code","SAR"),"accept-language":salla.lang.getLocale(),"s-user-id":Salla.config.get("user.id")});let e=salla.storage.get("scope");e&&this.setHeaders({"s-scope-type":e.type,"s-scope-id":e.id}),this.injectTokenToTheRequests();}injectTokenToTheRequests(){let e=salla.storage.get("token"),t=Salla.config.isGuest(),a=salla.storage.get("cart");if(a&&(a.user_id!==Salla.config.get("user.id")||a.store_id!==Salla.config.get("store.id")))return salla.log("Auth:: The cart is not belong to current "+(a.user_id!==Salla.config.get("user.id")?"user":"store")+"!"),void salla.cart.api.reset();if(t&&!e)return;if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();let s=o$1(e);return Date.now()/1e3>s.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):s.sub!==Salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}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",s={}){let r={endPoint:e,payload:t,method:a,options:s},i="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===i?.tagName&&(n=!0),n&&i?.load(),this.axios[r.method](r.endPoint,r.payload,r.options).then((e=>(n&&i?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&i?.stop(),salla.event.document.requestFailed(r,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,s=t&&t.googleTags?t.googleTags:a;dataLayer&&s&&dataLayer.push(s),this.fireEventsForResponse(e),this.showAlert(e),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 s=t[e];Array.isArray(s)?s.forEach((e=>a.push(e))):a.push(s);}));let s=(a.length>1?"* ":"")+a.join("\n* ");salla.error(s,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,s)=>t?a(e):s(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}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 F,this.product=new v,this.profile=new y,this.comment=new w,this.currency=new b,this.document=new S,this.wishlist=new _,this.scope=new E,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,s=t.split(".");for(;s.length&&(a=a[s.shift()]););return a},f$1.init=e=>new q(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.event.dispatch("twilight::ready"),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();},window.dispatchEvent(new CustomEvent("salla::created"));
9748
+ let i=function(e,t,a){return alert(e)},n=function(e,t){return i(e,l.error,t)},l={error:"error",success:"success",info:"info"};var o={fire:function(e,t,a){return i(e,t,a)},setNotifier:function(e){i=e;},error:n,success:function(e,t){return i(e,l.success,t)},info:function(e,t){return i(e,l.info,t)},sallaInitiated:function(){let e=window.location.href.match(/([\?\&]danger=)[^&]+/g);e&&e.forEach((e=>{n(decodeURI(e.replace("?danger=","").replace("&danger=","")));}));},types:l};class d{constructor(e,t){return this.api=e,this.event=t,new Proxy(this,{get:function(a,s){return "event"===s?t:"api"===s?e:e&&e[s]||a[s]}})}}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,s=this,r=0;r<e.length;r++)a=new RegExp(e[r],"g"),s=s.replace(a,t[r]);return s},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 s=this.hasAttribute("data-form-selector")?document.querySelector(this.dataset.formSelector):void 0;if(s="FORM"===this.tagName?this:s||this.closest("form")||this.closest("[salla-form-data]")||this,s&&"FORM"===s.tagName)return this.getFilteredData(new FormData(s),null,s);let r=s.querySelectorAll("[name]");if(!r.length)return this.getFilteredData();let i=Object.assign({},this.dataset);return r.forEach((e=>{if(!["checkbox","radio"].includes(e.type)||e.checked)try{let t=Salla.helpers.inputData(e.name,e.value,i);i[t.name]=t.value;}catch(t){Salla.log(e.name+" can't be send");}})),this.getFilteredData(i)},Element.prototype.canEventFireHook=function(e){return !!this.hasAttribute&&this.hasAttribute(Salla.api.hooksPrefix+e.type)},Element.prototype.hasAttributeStartsWith=function(e,t){e=e.toLowerCase();for(var a=0;a<this.attributes.length;a++){let s=this.attributes[a].name.toLowerCase();if(0===s.indexOf(e))return !t||s}return !1},HTMLFormElement.prototype.getAjaxFormData=function(e){var t=this.querySelectorAll('input[type="file"]');t.forEach((e=>{e.files.length||e.setAttribute("disabled","");}));var a=new FormData(this);return t.forEach((e=>{e.files.length||e.removeAttribute("disabled");})),{formData:this.getFilteredData(a,e),url:this.getAttribute("action"),method:this.getAttribute("method")||"post",events:{success:this.dataset.onSuccess,fail:this.dataset.onFail}}},Element.prototype.getFilteredData=function(e=null,t=null,a=null){return e=e||a?.dataset||this.dataset,a&&this.name&&void 0!==this.value&&(e=function(e,t,a){e instanceof FormData?e.append(t,a):e[t]=a;return e}(e,this.name,this.value)),["filterBeforeSubmit","filterBeforeSend"].forEach((s=>{let r=a?.dataset[s]||this.dataset[s];if(r){var i=window[r];if("function"==typeof i){if(!i(e,a||this,t)&&e)throw `Data failed to be pass verify function window.${r}(formData, element, event)!`;return i(e,a||this,t)}Salla.log("window."+r+"() 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,t)};}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.dispatch(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){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",couponAdded:"coupon.added",couponDeleted:"coupon.deleted",couponAdditionFailed:"coupon.addition.failed",couponDeletionFailed:"coupon.deletion.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",addGiftToCartSucceeded:"gift.add-to-cart.succeeded",addGiftToCartFailed:"gift.add-to-cart.failed",giftImageUploadSucceeded:"gift.image-upload.succeeded",giftImageUploadFailed:"gift.image-upload.failed"},this.after_init();}},Salla.event.profile=new class extends c{constructor(){super(),this.namespace="profile",this.events={updated:"updated",updateFailed:"update.failed",verificationCodeSent:"verification.code.sent",updateContactsFailed:"update.contacts.failed",verified:"verified",unverified:"unverified",infoFetched:"info.fetched",infoNotFetched:"info.not.fetched",settingsUpdated:"settings.updated",updateSettingsFailed:"update.settings.failed",deleted:"deleted",notDeleted:"not.deleted"},this.after_init();}},Salla.event.currency=new class extends c{constructor(){super(),this.namespace="currency",this.events={changed:"changed",failed:"failed",fetched:"fetched",failedToFetch:"failed.to.fetch"},this.after_init();}},Salla.event.document=new class extends c{constructor(){super(),this.namespace="document",this.events={click:"click",change:"change",submit:"submit",keyup:"keyup",leaving:"leaving",request:"request",requestFailed:"request.failed"},this.after_init();}onClick(e,t){this.fireCallableFuns("click",e,t);}onChange(e,t){this.fireCallableFuns("change",e,t);}onSubmit(e,t){this.fireCallableFuns("submit",e,t);}onKeyup(e,t){this.fireCallableFuns("keyup",e,t);}fireCallableFuns(e,t,a){this.on(e,(e=>{"function"!=typeof t?"function"==typeof a&&e.target.matches(t)&&a(e):t(e);}));}fireEvent(e,t,...a){return this.fireEventForElements(e,t,!1,...a)}fireEventForAll(e,t,...a){return this.fireEventForElements(e,t,!0,...a)}fireEventForElements(e,t,a,...s){if("string"==typeof e){if(a)return document.querySelectorAll(e).forEach((e=>this.fireEventForElements(e,t,!1,...s)));e=document.querySelector(e);}if(!e)return void salla.log("Failed To get element to fire event: "+t);const r=new CustomEvent(t,...s);return e.dispatchEvent(r)}},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 s=Array.isArray(e),r=s?this.getUrl(...e):this.getUrl(e);e=s?e[0]:e,a=a||this.endpointsMethods[e]||"post";let i=this.endpointsHeaders[e];if("get"===a&&t instanceof FormData){let e={};Array.from(t.entries()).forEach((function(t){e[t[0]]=t[1];})),t={params:e};}return i&&"get"===a&&(t=t?Object.assign(t,i):i),this.webEndpoints.includes(e)?r=salla.url.get(r):"http"!==r.substring(0,4)&&(r=salla.url.api(r)),Salla.api.request(r,t,a,{headers:i})}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"},this.endpointsMethods={latest:"get",details:"get",status:"get",updateItem:"post",deleteItem:"delete",deleteImage:"delete",deleteCoupon:"put"},this.webEndpoints=["latest"],this.latestCart=null,this.after_init();}async getCurrentCartId(){if(this.latestCart)return this.latestCart.cart.id;let e=await this.latest();return this.latestCart=e.data,this.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 s=await this.getCurrentCartId();return this.request([a,s,t.id],t.payload).then((function(e){return salla.cart.event.itemAdded(e,t.id),e})).catch((function(e){throw salla.cart.event.itemAddedFailed(e,t.id),e}))}async deleteItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemDeletedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return this.request(["deleteItem",a,t.id]).then((function(e){return salla.cart.event.itemDeleted(e,t.id),e})).catch((function(e){throw salla.cart.event.itemDeletedFailed(e,t.id),e}))}async updateItem(e){let t=this.getCartPayload(e);if(!t.id){let e='There is no "id"!';return salla.cart.event.itemUpdatedFailed(e),salla.api.errorPromise(e)}let a=await this.getCurrentCartId();return "Object"===t.payload.constructor?.name?t.payload._method="PUT":t.payload.append("_method","PUT"),this.request(["updateItem",a,t.id],t.payload).then((function(e){return salla.cart.event.itemUpdated(e,t.id),e})).catch((function(e){throw salla.cart.event.itemUpdatedFailed(e,t.id),e}))}async deleteImage(e){if(!(e=salla.form.getPossibleValue(e,["id","image_id","photo_id"]))){let e='There is no "id"!';return salla.cart.event.imageNotDeleted(e),salla.api.errorPromise(e)}let t=await this.getCurrentCartId();return this.request(["deleteImage",t,e]).then((function(t){return salla.cart.event.imageDeleted(t,e),t})).catch((function(t){throw salla.cart.event.imageNotDeleted(t,e),t}))}async status(e){return this.request(["status",e||await this.getCurrentCartId()],{params:{has_apple_pay:!!window.ApplePaySession}})}async submit(){this.status(await this.getCurrentCartId()).then((e=>{let t=e.data.next_step.to;if(!["checkout","refresh","login"].includes(t)){let e="Can't find next_step );";throw salla.cart.event.submitFailed(e),e}if(salla.cart.event.submitted(e),"login"===t)return salla.auth.setCanRedirect(!1),salla.event.dispatch("login::open"),void salla.auth.event.onLoggedIn((e=>{salla.event.dispatch("login::close"),this.submit();}));"checkout"===t?window.location.href=e.data.next_step.url+(window.ApplePaySession?"?has_apple_pay=true":""):window.location.reload();})).catch((function(e){throw salla.cart.event.submitFailed(e),e}));}getCartPayload(e){let t=e?.data||("object"==typeof e?e:void 0);return e=t?salla.form.getPossibleValue(t,["prod_id","product_id","item_id","id"]):e,t="object"==typeof t?t:void 0,{id:e,payload:t}}normalRequest(e,t,a=null){return super.normalRequest(e,t,a).catch((e=>{throw 403===e?.response?.status&&(salla.storage.remove("cart"),salla.error(salla.lang.get("pages.checkout.try_again"))),e}))}reset(){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}))}}class g extends h{constructor(){super(),this.namespace="loyalty",this.endpoints={getProgram:"loyalty",exchange:"loyalty/exchange",reset:"loyalty/exchange"},this.endpointsMethods={getProgram:"get",reset:"put"},this.after_init();}getProgram(){return this.request("getProgram").then((e=>(salla.loyalty.event.programFetched(e),e))).catch((e=>{throw salla.loyalty.event.programNotFetched(e),e}))}async exchange(e,t=null){if(!(e=salla.form.getPossibleValue(e,["id","loyalty_prize_id","prize_id"]))){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}if(!(t=t||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.exchangeFailed(e),salla.api.errorPromise(e)}return this.request("exchange",{loyalty_prize_id:e,cart_id:t}).then((function(t){return salla.loyalty.event.exchangeSucceeded(t,e),t})).catch((function(t){throw salla.loyalty.event.exchangeFailed(t,e),t}))}async reset(e=null){if(!(e=e||await salla.cart.getCurrentCartId())){let e="Unable to find cart id. Please provide one.";return salla.loyalty.event.resetFailed(e),salla.api.errorPromise(e)}return this.request("reset",{cart_id:e}).then((e=>(salla.loyalty.event.resetSucceeded(e),e))).catch((e=>{throw salla.loyalty.event.resetFailed(e),e}))}}class f extends h{constructor(){super(),this.namespace="auth",this.canRedirect_=!0,this.afterLoginEvent={event:null,payload:null},this.endpoints={login:"auth/{type}/send_verification",resend:"auth/resend_verification",verify:"auth/{type}/verify",register:"auth/register",logout:"logout",refresh:"auth/refresh"},this.webEndpoints=["logout","auth/jwt","refresh"],this.endpointsMethods={logout:"get"},this.after_init();}setAfterLoginEvent(e,t){salla.api.auth.afterLoginEvent={event:e,payload:t};}setCanRedirect(e){salla.api.auth.canRedirect_=e;}canRedirect(){return salla.api.auth.canRedirect_&&!salla.api.auth.afterLoginEvent.event}login(e){e?.data&&(e=e.data);let t=salla.form.getPossibleValue(e,["type"]);if(!["email","mobile"].includes(t)){let e="Login type should be in: [email, mobile]";return salla.auth.event.codeNotSent(e),salla.api.errorPromise(e)}return this.request(["login",t],e).then((function(e){return salla.auth.event.codeSent(e,t),e})).catch((function(e){throw salla.auth.event.codeNotSent(e,t),e}))}async verify(e,t=!0){let a=salla.form.getPossibleValue(e,["type"]);if(!a){let e="Failed to know what's login type!";return salla.auth.event.verificationFailed(e),salla.api.errorPromise(e)}t=!1!==salla.form.getPossibleValue(e,["supportWebAuth"])&&t,salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event);let s=await this.request(["verify",a],e);if(200!==s?.status)return salla.auth.event.verificationFailed(s,a),salla.api.errorPromise(s);let r="authenticated"===s.data?.case;return r&&salla.auth.event.tokenFetched(s.data.token),t&&await this.request("auth/jwt"),r&&salla.auth.event.loggedIn(s),salla.auth.event.verified(s,a),salla.auth.api.afterUserLogin(),salla.api.successPromise(s)}resend(e){let t;return (e=e.data||e).type=e.type||"mobile","mobile"!==e.type||e.phone&&e.country_code?"email"!==e.type||e.email?this.request("resend",e).then((function(t){return salla.auth.event.codeSent(t,e),t})).catch((function(t){throw salla.auth.event.codeNotSent(t,e),t})):(salla.auth.event.codeNotSent(t="There is no email!",e),salla.api.errorPromise(t)):(salla.auth.event.codeNotSent(t="There is no phone or country_code!",e),salla.api.errorPromise(t))}register(e){let t;return e.data&&(t=e.element,e=e.data),salla.auth.event.next_event&&(e.next_event=salla.auth.event.next_event),this.request("register",e).then((async function(e){return salla.auth.event.registered.call(t,e),"authenticated"===e.data?.case&&(salla.auth.event.tokenFetched(e.data.token),await salla.auth.request("auth/jwt"),salla.auth.event.loggedIn(e),salla.auth.api.afterUserLogin()),e})).catch((function(e){throw salla.auth.event.registrationFailed.call(t,e),e}))}logout(){return this.request("logout").then((function(e){return salla.storage.clearAll(),salla.cookie.clearAll(),salla.auth.event.loggedOut(e),salla.log("Reloading after 0.2 sec..."),setTimeout((()=>location.reload()),200),e})).catch((function(e){throw salla.auth.event.failedLogout(e),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.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={getPrice:"products/{id}/price",availabilitySubscribe:"products/{id}/availability-notify",search:"products/search",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={giftDetail:"get"},this.after_init();}getPrice(e){let t=e.data||e,a=salla.form.getPossibleValue(t,["id","prod_id","product_id"]);return this.request(["getPrice",a],"object"==typeof t?t:void 0).then((function(e){return salla.product.event.priceUpdated(e,a),e})).catch((function(e){throw salla.product.event.priceUpdateFailed(e,a),e}))}categories(e){return this.request(["categories",e||""],null,"get").then((function(e){return salla.product.event.categoriesFetched(e),e})).catch((function(e){throw salla.product.event.categoriesFailed(e),e}))}availabilitySubscribe(e){let t=e.data||e;return e=salla.form.getPossibleValue(t,["id","prod_id"]),this.request(["availabilitySubscribe",e],"object"==typeof t?t:void 0).then((function(t){return salla.product.event.availabilitySubscribed(t,e),t})).catch((function(t){throw salla.product.event.availabilitySubscribedFailed(t,e),t}))}search(e){let t=e.data;if(t||(t={params:"string"==typeof e?{query:e}:e}),!(e=t instanceof FormData?t.get("query"):t.query||t.params?.query)){let e='There is no "query"!';return salla.product.event.searchFailed(e),salla.api.errorPromise(e)}if(e===salla.api.product.previousQuery){let e="Query is same as previous one!";return salla.product.event.searchFailed(e),salla.api.product.previousQuery=null,salla.api.errorPromise(e)}return salla.api.product.previousQuery=e,this.request("search",t,"get").then((function(t){return salla.product.event.searchResults(t,e),t})).catch((function(t){throw salla.product.event.searchFailed(t,e),t}))}offers(e){if(!(e=salla.form.getPossibleValue(e?.data|e,["product_id","id"]))){let e='There is no "product_id"!';return salla.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}))}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"]),s=salla.form.getPossibleValue(e,["type"]),r=salla.form.getPossibleValue(e,["comment"]);return a?s&&["products","pages","product","page"].includes(s)?r?(s+=["product","page"].includes(s)?"s":"",this.request(["add",s,a],{comment:r}).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 S extends h{constructor(){super(),this.namespace="document";}}class F 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 E 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 q{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),s=a.method?a.method.toLowerCase():void 0;salla.api.request(a.url,a.formData,s).then((e=>(e.data&&e.request&&(e=e.data),salla.api.handleAfterResponseActions(e),this.callAjaxEvent(a.events.success,e,a.formData),e))).catch((e=>{throw salla.api.handleErrorResponse(e),this.callAjaxEvent(a.events.fail,e,a.formData),e}));}callAjaxEvent(e,t,a){if(e){if(a instanceof FormData){const e={};Array.from(a.entries()).forEach((function(t){e[t[0]]=t[1];})),a=e;}window[e]?window[e](t,a):salla.event.dispatch(e,t,a);}}setSallaReady(t){f$1.status="ready",f$1.event.dispatch("twilight::initiated",t),window.dispatchEvent(new CustomEvent("salla::ready"));}}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 s=e.split("."),r=s.splice(-1);return await salla.call(s.join("."))[r](a).finally((()=>t?.submitter?.parentElement?.stop())).catch((e=>{throw salla.logger.warn(e),e}))}onSubmit(e,t){return salla.form.submit(e,t),!1}onChange(e,t){return t?.currentTarget?"FORM"!==t?.currentTarget?.tagName||t.currentTarget.checkValidity()?(salla.form.submit(e,t.currentTarget.getElementSallaData()),!0):(salla.logger.warn(`Trying to trigger '${e}' without filling required fields!`),!1):(salla.logger.warn(`Trying to trigger '${e}' without event!`),!1)}getPossibleValue(e,t,a=!1){if(!e)return;if("object"!=typeof e)return e;let s;for(let a=0;a<t.length&&!(s=e[t[a]])&&!("undefined"!=typeof FormData&&e instanceof FormData&&(s=e.get(t[a])));a++);return s=s||e,"object"!=typeof s||a?s:void 0}},f$1.helpers.app=new class{toggleClassIf(e,t,a,s){return document.querySelectorAll(e).forEach((e=>this.toggleElementClassIf(e,t,a,s))),this}toggleElementClassIf(e,t,a,s){t=Array.isArray(t)?t:t.split(" "),a=Array.isArray(a)?a:a.split(" ");let r=s(e);return e?.classList.remove(...r?a:t),e?.classList.add(...r?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,s={}){return "object"==typeof t?(this.element(t).addEventListener(e,a,s),this):(document.querySelectorAll(t).forEach((t=>t.addEventListener(e,a,s))),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,s){s=this.getCustomOptions(a,s);let r="string"!=typeof e?e:document.querySelector(e),i=s.path;if(!r||!i||"string"==typeof i&&!document.querySelector(i))return void Salla.logger.warn(r?"Path Option (a link that has next page link) Not Existed!":"Container For InfiniteScroll not Existed!");let n=new js(r,s);return n.on("scrollThreshold",Salla.infiniteScroll.event.scrollThreshold),n.on("request",Salla.infiniteScroll.event.request),n.on("load",Salla.infiniteScroll.event.load),n.on("append",Salla.infiniteScroll.event.append),n.on("error",Salla.infiniteScroll.event.error),n.on("last",Salla.infiniteScroll.event.last),n.on("history",Salla.infiniteScroll.event.history),this.instances.push(n),n}getCustomOptions(e,t){return (t="object"==typeof e&&e||t||this.options).fetchOptions=this.fetchOptions,t.path=t.path||this.options.path,t.button=t.button||t.path,t.status=t.status||this.options.status,t.hasOwnProperty("history")||(t.history=this.options.history),t.nextPage=t.nextPage||t.next_page,t.append="string"==typeof e&&e||t.append||this.options.append,t}}(void 0,salla.event.infiniteScroll),f$1.api=new class extends class{constructor(){salla.event.on("twilight::initiated",(()=>this.initiateRequest())),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(){this.axios.defaults.baseURL=Salla.config.get("store.api",Salla.config.get("store.url")),this.setHeaders({"Store-Identifier":Salla.config.get("store.id"),currency:Salla.config.get("user.currency_code","SAR"),"accept-language":salla.lang.getLocale(),"s-user-id":Salla.config.get("user.id")});let e=salla.storage.get("scope");e&&this.setHeaders({"s-scope-type":e.type,"s-scope-id":e.id}),this.injectTokenToTheRequests();}injectTokenToTheRequests(){let e=salla.storage.get("token"),t=Salla.config.isGuest(),a=salla.storage.get("cart");if(a&&(a.user_id!==Salla.config.get("user.id")||a.store_id!==Salla.config.get("store.id")))return salla.log("Auth:: The cart is not belong to current "+(a.user_id!==Salla.config.get("user.id")?"user":"store")+"!"),void salla.cart.api.reset();if(t&&!e)return;if(t&&e)return salla.log("Auth:: Token without user!"),salla.storage.remove("token"),void salla.cart.api.reset();if(!e)return salla.cart.api.reset(),void salla.auth.api.refresh();let s=o$1(e);return Date.now()/1e3>s.exp?(salla.log("Auth:: An expired token!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):s.sub!==Salla.config.get("user.id")?(salla.log("Auth:: The user id is not match the token details!"),salla.storage.remove("token"),salla.cart.api.reset(),void salla.auth.api.refresh()):void this.setToken(e)}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",s={}){let r={endPoint:e,payload:t,method:a,options:s},i="undefined"!=typeof event?event.currentTarget:null,n=!1;return "SALLA-BUTTON"===i?.tagName&&(n=!0),n&&i?.load(),this.axios[r.method](r.endPoint,r.payload,r.options).then((e=>(n&&i?.stop(),e.data&&e.request&&(e=e.data),this.handleAfterResponseActions(e),e))).catch((e=>{throw n&&i?.stop(),salla.event.document.requestFailed(r,e),this.handleErrorResponse(e),e}))}handleAfterResponseActions(e){if(!e)return;let{data:t,googleTags:a=null}=e,s=t&&t.googleTags?t.googleTags:a;dataLayer&&s&&dataLayer.push(s),this.fireEventsForResponse(e),this.showAlert(e),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 s=t[e];Array.isArray(s)?s.forEach((e=>a.push(e))):a.push(s);}));let s=(a.length>1?"* ":"")+a.join("\n* ");salla.error(s,e);}isFastRequestsAllowed(){return Salla.config.get("fastRequests")}promise(e,t=!0){return new Promise(((a,s)=>t?a(e):s(e)))}errorPromise(e){return this.promise(e,!1)}successPromise(e){return this.promise(e,!0)}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 F,this.product=new v,this.profile=new y,this.comment=new w,this.currency=new b,this.document=new S,this.wishlist=new _,this.scope=new E,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,s=t.split(".");for(;s.length&&(a=a[s.shift()]););return a},f$1.init=e=>new q(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.event.dispatch("twilight::ready"),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();},window.dispatchEvent(new CustomEvent("salla::created"));