-
Notifications
You must be signed in to change notification settings - Fork 1
/
monocle-client.js
3662 lines (3061 loc) · 97.4 KB
/
monocle-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.decode = exports.parse = __webpack_require__(12);
exports.encode = exports.stringify = __webpack_require__(13);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
// Assumes Promise is already loaded
(function(context) {
'use strict';
var Monocle = __webpack_require__(2);
var VanillaAdapter = __webpack_require__(16);
// @ts-ignore XMLHttpRequest and Window not found
var http = new VanillaAdapter(context.XMLHttpRequest, context.Promise);
// @ts-ignore adding property to Window
context.monocle = new Monocle(http);
})(window);
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Store = __webpack_require__(3);
var ResourceCache = __webpack_require__(4);
var querystring = __webpack_require__(0);
var CollectionCache = __webpack_require__(14);
function Monocle(http, promise) {
this._http = http;
this._base = '/';
this._cache = new Store(new ResourceCache('monocle', { capacity: 100 }));
this._batched = [];
this._batchTimeout = null;
// This is a flag that allows disabling batching. Useful for unit testing.
this._enableBatching = true;
this._queuedGets = {};
this._promise = promise || Promise;
this._host = '';
}
Monocle.prototype.setBase = function(base) {
this._base = base;
return this;
};
Monocle.prototype.setHost = function(host) {
this._host = host;
return this;
};
Monocle.prototype.getCache = function() {
return this._cache;
};
Monocle.prototype.enableBatching = function() {
this._enableBatching = true;
};
// Disable the usage of batching. Useful for unit testing.
Monocle.prototype.disableBatching = function() {
this._enableBatching = false;
};
['get', 'post', 'put', 'patch', 'delete', 'options'].forEach(function(method) {
Monocle.prototype[method] = function(path, options) {
return _handle.call(this, method, path, options);
};
});
var updateBatchTimeout = function() {
if (null !== this._batchTimeout) {
// Batch timeout already set up, nothing to do.
return;
}
this._batchTimeout = setTimeout(function() {
processBatch.call(this);
this._batchTimeout = null;
}.bind(this));
};
function handle304(batched, result) {
if (result && 304 === result.$httpStatus) {
batched.cached.$httpStatus = 304;
return batched.cached;
}
return this._promise.reject(result);
}
/**
* @returns {void}
*/
var processBatch = function() {
var batched = this._batched;
this._batched = [];
if (1 === batched.length || !this._enableBatching) {
// Do not use the batch endpoint if there is only one API call to be made.
batched.forEach(function(data) {
var fullPath = buildFullPath(this._host, this._base, data.url);
this._http.request(data.method.toUpperCase(), fullPath, data.options, data.headers)
.catch(handle304.bind(this, data))
.then(data.resolve)
.catch(data.reject);
}.bind(this));
return;
}
var envelopes = batched.map(function(data) {
var body;
// Extract the body from the options
// and pass it along as its own property in the request envelope.
if (data.options && data.options.body) {
body = data.options.body;
delete data.options.body;
}
return {
method: data.method,
url: data.url,
headers: data.headers,
options: data.options,
body: body,
resolve: data.resolve,
reject: data.reject
};
});
this._http.request('POST', buildFullPath(this._host, this._base, '/_batch'), {
body: envelopes
}).then(function(results) {
results.forEach(function(result, i) {
if (result.status >= 200 && result.status < 300) {
batched[i].resolve(result.body);
} else if (result.status === 304) {
batched[i].resolve(batched[i].cached);
} else {
batched[i].reject(result.body);
}
})
}).catch(function(error) {
batched.forEach(function(apiCall, i) {
batched[i].reject(error);
});
});
};
var getQueuedGetKey = function(path, options) {
return [path, JSON.stringify(options)].join(':');
};
var getQueuedGet = function(path, options) {
var key = getQueuedGetKey(path, options);
if (this._queuedGets.hasOwnProperty(key)) {
return this._queuedGets[key];
}
return null;
};
var enqueueGet = function(path, options, promise) {
var key = getQueuedGetKey(path, options);
this._queuedGets[key] = promise;
};
var clearQueuedGet = function(path, options) {
var key = getQueuedGetKey(path, options);
delete this._queuedGets[key];
};
var _handle = function(method, path, options) {
options = options || {};
var headers = {};
var cached = null;
// Validate props
if (options && options.props) {
var propRegex = /^[a-zA-Z0-9@.$_-]+$/;
var invalidPropsError = {
code: 422, // malformed request
message: 'Invalid props, expecting an array of strings'
};
var missingPropsError = {
code: 422, // malformed request
message: 'Invalid props, expecting one or more'
};
if (!Array.isArray(options.props)) {
return this._promise.reject(invalidPropsError);
}
if (!options.props.length) {
return this._promise.reject(missingPropsError);
}
for (var i = 0, len = options.props.length; i < len; i++) {
if (typeof options.props[i] !== 'string') {
return this._promise.reject(invalidPropsError);
}
if (!options.props[i].match(propRegex)) {
return this._promise.reject(invalidPropsError);
}
}
}
switch (method) {
case 'get':
// Check if this GET is already queued
var queuedGet = getQueuedGet.call(this, path, options);
if (queuedGet) return queuedGet;
var cacheKey = this._cache.generateCacheKey(path, options && options.query);
// Check cache if attempting to get resource
cached = this._cache.get(cacheKey);
if (cached && isResourceComplete(cached, options.props)) {
// Collections need to validate etag with the server first
if ('collection' === cached.$type) {
var collectionCache = new CollectionCache(cached, options.props, options.query);
var etag = collectionCache.id();
if (etag) {
headers['if-none-match'] = etag;
}
// We need to validate the etag with the server,
// so break early to allow an HTTP request to go through.
break;
}
return this._promise.resolve(cached);
}
break;
case 'post':
case 'put':
case 'delete':
case 'patch':
// Remove from cache when resource is being updated or removed
this._cache.removeMatchingTag(path);
break;
}
var promise = (new this._promise(function(resolve, reject) {
var query = buildQuery(options);
if (query) {
path += '?' + query;
}
this._batched.push({
method: method,
url: path,
headers: headers,
options: options,
resolve: resolve,
reject: reject,
cached: cached
});
updateBatchTimeout.call(this);
}.bind(this)))
.then(cacheResource.bind(this, method, options))
.finally(clearQueuedGet.bind(this, path, options));
if (method === 'get') {
enqueueGet.call(this, path, options, promise);
}
return promise;
};
/**
* Returns true if the provided resource fullfills all of the requirements of the options.
*
* @param {object} resource - The resource to check
* @param {object} props - Request options
* @returns {boolean}
*/
function isResourceComplete(resource, props) {
if (!props) {
return true;
}
for (var i in props) {
if (!Object.prototype.hasOwnProperty.call(props, i)) {
continue;
}
if (!hasProp(resource, props[i])) {
return false;
}
}
return true;
}
/**
* Returns true if the resource contains the specified property according to its path.
* a.b => reach into object `a` to look for `b` property
* a@b => reach into array `a` to look for `b` properties on each item
*
* @param {object} resource - The object to check
* @param {string} prop - The property path to verify
* @returns {boolean}
*/
function hasProp(resource, prop) {
if (!prop) {
return true;
}
var paths = [];
var currentPath = {
type: 'object',
property: ''
};
paths.push(currentPath);
for (var i = 0, len = prop.length; i < len; i++) {
var char = prop[i];
switch (char) {
case '.':
currentPath = {
type: 'object',
property: ''
};
paths.push(currentPath);
break;
case '@':
currentPath = {
type: 'array',
property: ''
};
paths.push(currentPath);
break;
default:
currentPath.property += char;
}
}
// Walk the path to see if the properties exist
var currentObject = resource;
var path;
for (i = 0, len = paths.length, path; i < len; i++) {
if (null === currentObject) {
// Trying to fetch a nested property from a top-level object that doesn't exist.
return false;
}
path = paths[i];
switch (path.type) {
case 'object':
if (!currentObject.hasOwnProperty(path.property)) {
return false;
}
currentObject = currentObject[path.property];
break;
case 'array':
if (!currentObject.length) {
currentObject = null;
break;
}
// Only check the first object
if (!currentObject[0].hasOwnProperty(path.property)) {
return false;
}
currentObject = currentObject[0][path.property];
break;
}
}
return true;
}
function cacheResource(method, options, resource) {
if ('get' === method) {
this._cache.put(resource, options && options.query);
}
return resource;
}
function buildFullPath(host, base, path) {
return host + (base + path).replace(/\/{2,}/g, '/');
}
function buildQuery(options) {
var query = {}
if (options && options.query && typeof options.query === "object") {
for (var i in options.query) {
query[i] = options.query[i];
}
}
if (options && Array.isArray(options.props)) query.props = options.props.join(',');
return querystring.stringify(query);
}
module.exports = Monocle;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function Store(backend) {
this._backend = backend;
}
Store.prototype.get = function(cacheKey) {
return this._backend.get(cacheKey);
};
Store.prototype.put = function(cacheKey, query) {
return this._backend.put(cacheKey, query);
};
Store.prototype.remove = function(cacheKey) {
return this._backend.remove(cacheKey);
};
Store.prototype.getAll = function() {
return this._backend.getAll();
};
Store.prototype.removeMatchingTag = function(tag) {
return this._backend.removeMatchingTag(tag);
};
Store.prototype.generateCacheKey = function(object, query) {
return this._backend.generateCacheKey(object, query);
};
module.exports = Store;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var clone = __webpack_require__(5);
var MemoryCache = __webpack_require__(11);
var querystring = __webpack_require__(0);
function ResourceCache(cacheId, options) {
this._cache = new MemoryCache(cacheId, options);
}
ResourceCache.prototype.generateCacheKey = function(path, query) {
if (!query) {
return path;
}
// Sort the query string parameters, because order doesn't matter
var sortedQuery = Object.keys(query)
.map(function(key) {
var obj = {};
obj[key] = query[key];
return querystring.stringify(obj);
}).sort();
return path + '?' + sortedQuery.join('&');
};
ResourceCache.prototype.get = function(cacheKey) {
return getFromCache.call(this, cacheKey);
};
function getFromCache(cacheKey) {
var entry = clone(this._cache.get(cacheKey));
// If parent or nested resources not in cache then return undefined.
if (typeof entry === 'undefined' || hasExpiredNestedResources.call(this, entry)) {
return undefined;
}
getNestedResourcesFromCache.call(this, entry);
return entry;
}
function hasExpiredNestedResources(obj) {
var keys = Object.keys(obj);
for(var i=0; i<keys.length; i++) {
var key = keys[i];
if (typeof obj[key] !== 'object' || obj[key] == null) {
continue;
}
if (obj[key].hasOwnProperty('key') && obj[key].hasOwnProperty('value') && obj[key].hasOwnProperty('expiration')) {
if (typeof getFromCache.call(this, obj[key].key) === 'undefined') {
return true;
}
} else {
return hasExpiredNestedResources.call(this, obj[key]);
}
}
return false;
}
function getNestedResourcesFromCache(obj) {
var keys = Object.keys(obj);
for(var i=0; i<keys.length; i++) {
var key = keys[i];
if (typeof obj[key] !== 'object' || obj[key] == null) {
continue;
}
if (obj[key].hasOwnProperty('key') && obj[key].hasOwnProperty('value') && obj[key].hasOwnProperty('expiration')) {
var cacheValue = getFromCache.call(this, obj[key].key);
//Only set the object value if getFromCache does not return an undefined object
if (typeof cacheValue !== 'undefined') {
obj[key] = cacheValue;
}
} else {
getNestedResourcesFromCache.call(this, obj[key]);
}
}
}
ResourceCache.prototype.getAll = function() {
return this._cache.getAll();
};
ResourceCache.prototype.put = function(resource, query) {
var entry = put.call(this, resource, query);
if (entry) {
return entry.key;
} else {
return undefined;
}
};
var put = function(resource, query) {
// Not a resource? Ignore it.
if (!resource.hasOwnProperty('$id') || !resource.hasOwnProperty('$expires')) {
return;
}
var clonedResource = clone(resource);
putNestedResources.call(this, clonedResource);
var cacheKey = this.generateCacheKey(clonedResource.$id, query);
var tags = [resource.$id];
return this._cache.put(cacheKey, clonedResource, clonedResource.$expires, tags);
};
var putNestedResources = function(obj) {
var keys = Object.keys(obj);
for(var i=0; i<keys.length; i++) {
var key = keys[i];
if (typeof obj[key] !== 'object' || obj[key] == null) {
continue;
}
if (obj[key].hasOwnProperty('$id') && obj[key].hasOwnProperty('$expires')) {
obj[key] = put.call(this, obj[key]);
} else if (typeof obj[key] === 'object') {
putNestedResources.call(this, obj[key]);
}
}
}
ResourceCache.prototype.printFromHead = function() {
this._cache.printFromHead();
};
ResourceCache.prototype.printFromTail = function() {
this._cache.printFromTail();
};
ResourceCache.prototype.remove = function(cacheKey) {
this._cache.remove(cacheKey);
};
ResourceCache.prototype.removeAll = function() {
this._cache.removeAll();
};
ResourceCache.prototype.removeMatchingTag = function(tag) {
this._cache.removeMatchingTag(tag);
};
module.exports = ResourceCache;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {var clone = (function() {
'use strict';
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
*/
function clone(parent, circular, depth, prototype) {
var filter;
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
filter = circular.filter;
circular = circular.circular
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth == 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
if (Buffer.allocUnsafe) {
// Node.js >= 4.5.0
child = Buffer.allocUnsafe(parent.length);
} else {
// Older Node.js versions
child = new Buffer(parent.length);
}
parent.copy(child);
return child;
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
};
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
};
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
};
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
};
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
};
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6).Buffer))
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(8)
var ieee754 = __webpack_require__(9)
var isArray = __webpack_require__(10)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**