UNPKG

kitchensink

Version:

Dispatch's awesome components and style guide

1,658 lines (1,344 loc) 121 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["expect"] = factory(); else root["expect"] = factory(); })(this, function() { return /******/ (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] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = 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; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _Expectation = __webpack_require__(1); var _Expectation2 = _interopRequireDefault(_Expectation); var _SpyUtils = __webpack_require__(13); var _assert = __webpack_require__(11); var _assert2 = _interopRequireDefault(_assert); var _extend = __webpack_require__(31); var _extend2 = _interopRequireDefault(_extend); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function expect(actual) { return new _Expectation2.default(actual); } expect.createSpy = _SpyUtils.createSpy; expect.spyOn = _SpyUtils.spyOn; expect.isSpy = _SpyUtils.isSpy; expect.restoreSpies = _SpyUtils.restoreSpies; expect.assert = _assert2.default; expect.extend = _extend2.default; module.exports = expect; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _has = __webpack_require__(2); var _has2 = _interopRequireDefault(_has); var _tmatch = __webpack_require__(5); var _tmatch2 = _interopRequireDefault(_tmatch); var _assert = __webpack_require__(11); var _assert2 = _interopRequireDefault(_assert); var _SpyUtils = __webpack_require__(13); var _TestUtils = __webpack_require__(18); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * An Expectation is a wrapper around an assertion that allows it to be written * in a more natural style, without the need to remember the order of arguments. * This helps prevent you from making mistakes when writing tests. */ var Expectation = function () { function Expectation(actual) { _classCallCheck(this, Expectation); this.actual = actual; if ((0, _TestUtils.isFunction)(actual)) { this.context = null; this.args = []; } } _createClass(Expectation, [{ key: 'toExist', value: function toExist(message) { (0, _assert2.default)(this.actual, message || 'Expected %s to exist', this.actual); return this; } }, { key: 'toNotExist', value: function toNotExist(message) { (0, _assert2.default)(!this.actual, message || 'Expected %s to not exist', this.actual); return this; } }, { key: 'toBe', value: function toBe(value, message) { (0, _assert2.default)(this.actual === value, message || 'Expected %s to be %s', this.actual, value); return this; } }, { key: 'toNotBe', value: function toNotBe(value, message) { (0, _assert2.default)(this.actual !== value, message || 'Expected %s to not be %s', this.actual, value); return this; } }, { key: 'toEqual', value: function toEqual(value, message) { try { (0, _assert2.default)((0, _TestUtils.isEqual)(this.actual, value), message || 'Expected %s to equal %s', this.actual, value); } catch (error) { // These attributes are consumed by Mocha to produce a diff output. error.actual = this.actual; error.expected = value; error.showDiff = true; throw error; } return this; } }, { key: 'toNotEqual', value: function toNotEqual(value, message) { (0, _assert2.default)(!(0, _TestUtils.isEqual)(this.actual, value), message || 'Expected %s to not equal %s', this.actual, value); return this; } }, { key: 'toThrow', value: function toThrow(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).toThrow() must be a function, %s was given', this.actual); (0, _assert2.default)((0, _TestUtils.functionThrows)(this.actual, this.context, this.args, value), message || 'Expected %s to throw %s', this.actual, value || 'an error'); return this; } }, { key: 'toNotThrow', value: function toNotThrow(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).toNotThrow() must be a function, %s was given', this.actual); (0, _assert2.default)(!(0, _TestUtils.functionThrows)(this.actual, this.context, this.args, value), message || 'Expected %s to not throw %s', this.actual, value || 'an error'); return this; } }, { key: 'toBeA', value: function toBeA(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(value) || typeof value === 'string', 'The "value" argument in toBeA(value) must be a function or a string'); (0, _assert2.default)((0, _TestUtils.isA)(this.actual, value), message || 'Expected %s to be a %s', this.actual, value); return this; } }, { key: 'toNotBeA', value: function toNotBeA(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(value) || typeof value === 'string', 'The "value" argument in toNotBeA(value) must be a function or a string'); (0, _assert2.default)(!(0, _TestUtils.isA)(this.actual, value), message || 'Expected %s to not be a %s', this.actual, value); return this; } }, { key: 'toMatch', value: function toMatch(pattern, message) { (0, _assert2.default)((0, _tmatch2.default)(this.actual, pattern), message || 'Expected %s to match %s', this.actual, pattern); return this; } }, { key: 'toNotMatch', value: function toNotMatch(pattern, message) { (0, _assert2.default)(!(0, _tmatch2.default)(this.actual, pattern), message || 'Expected %s to not match %s', this.actual, pattern); return this; } }, { key: 'toBeLessThan', value: function toBeLessThan(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeLessThan() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeLessThan(value) must be a number'); (0, _assert2.default)(this.actual < value, message || 'Expected %s to be less than %s', this.actual, value); return this; } }, { key: 'toBeLessThanOrEqualTo', value: function toBeLessThanOrEqualTo(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeLessThanOrEqualTo() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeLessThanOrEqualTo(value) must be a number'); (0, _assert2.default)(this.actual <= value, message || 'Expected %s to be less than or equal to %s', this.actual, value); return this; } }, { key: 'toBeGreaterThan', value: function toBeGreaterThan(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeGreaterThan() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeGreaterThan(value) must be a number'); (0, _assert2.default)(this.actual > value, message || 'Expected %s to be greater than %s', this.actual, value); return this; } }, { key: 'toBeGreaterThanOrEqualTo', value: function toBeGreaterThanOrEqualTo(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeGreaterThanOrEqualTo() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeGreaterThanOrEqualTo(value) must be a number'); (0, _assert2.default)(this.actual >= value, message || 'Expected %s to be greater than or equal to %s', this.actual, value); return this; } }, { key: 'toInclude', value: function toInclude(value, compareValues, message) { if (typeof compareValues === 'string') { message = compareValues; compareValues = null; } if (compareValues == null) compareValues = _TestUtils.isEqual; var contains = false; if ((0, _TestUtils.isArray)(this.actual)) { contains = (0, _TestUtils.arrayContains)(this.actual, value, compareValues); } else if ((0, _TestUtils.isObject)(this.actual)) { contains = (0, _TestUtils.objectContains)(this.actual, value, compareValues); } else if (typeof this.actual === 'string') { contains = (0, _TestUtils.stringContains)(this.actual, value); } else { (0, _assert2.default)(false, 'The "actual" argument in expect(actual).toInclude() must be an array, object, or a string'); } (0, _assert2.default)(contains, message || 'Expected %s to include %s', this.actual, value); return this; } }, { key: 'toExclude', value: function toExclude(value, compareValues, message) { if (typeof compareValues === 'string') { message = compareValues; compareValues = null; } if (compareValues == null) compareValues = _TestUtils.isEqual; var contains = false; if ((0, _TestUtils.isArray)(this.actual)) { contains = (0, _TestUtils.arrayContains)(this.actual, value, compareValues); } else if ((0, _TestUtils.isObject)(this.actual)) { contains = (0, _TestUtils.objectContains)(this.actual, value, compareValues); } else if (typeof this.actual === 'string') { contains = (0, _TestUtils.stringContains)(this.actual, value); } else { (0, _assert2.default)(false, 'The "actual" argument in expect(actual).toExclude() must be an array, object, or a string'); } (0, _assert2.default)(!contains, message || 'Expected %s to exclude %s', this.actual, value); return this; } }, { key: 'toIncludeKeys', value: function toIncludeKeys(keys, comparator, message) { var _this = this; if (typeof comparator === 'string') { message = comparator; comparator = null; } if (comparator == null) comparator = _has2.default; (0, _assert2.default)(_typeof(this.actual) === 'object', 'The "actual" argument in expect(actual).toIncludeKeys() must be an object, not %s', this.actual); (0, _assert2.default)((0, _TestUtils.isArray)(keys), 'The "keys" argument in expect(actual).toIncludeKeys(keys) must be an array, not %s', keys); var contains = keys.every(function (key) { return comparator(_this.actual, key); }); (0, _assert2.default)(contains, message || 'Expected %s to include key(s) %s', this.actual, keys.join(', ')); return this; } }, { key: 'toIncludeKey', value: function toIncludeKey(key) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return this.toIncludeKeys.apply(this, [[key]].concat(args)); } }, { key: 'toExcludeKeys', value: function toExcludeKeys(keys, comparator, message) { var _this2 = this; if (typeof comparator === 'string') { message = comparator; comparator = null; } if (comparator == null) comparator = _has2.default; (0, _assert2.default)(_typeof(this.actual) === 'object', 'The "actual" argument in expect(actual).toExcludeKeys() must be an object, not %s', this.actual); (0, _assert2.default)((0, _TestUtils.isArray)(keys), 'The "keys" argument in expect(actual).toIncludeKeys(keys) must be an array, not %s', keys); var contains = keys.every(function (key) { return comparator(_this2.actual, key); }); (0, _assert2.default)(!contains, message || 'Expected %s to exclude key(s) %s', this.actual, keys.join(', ')); return this; } }, { key: 'toExcludeKey', value: function toExcludeKey(key) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return this.toExcludeKeys.apply(this, [[key]].concat(args)); } }, { key: 'toHaveBeenCalled', value: function toHaveBeenCalled(message) { var spy = this.actual; (0, _assert2.default)((0, _SpyUtils.isSpy)(spy), 'The "actual" argument in expect(actual).toHaveBeenCalled() must be a spy'); (0, _assert2.default)(spy.calls.length > 0, message || 'spy was not called'); return this; } }, { key: 'toHaveBeenCalledWith', value: function toHaveBeenCalledWith() { for (var _len3 = arguments.length, expectedArgs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { expectedArgs[_key3] = arguments[_key3]; } var spy = this.actual; (0, _assert2.default)((0, _SpyUtils.isSpy)(spy), 'The "actual" argument in expect(actual).toHaveBeenCalledWith() must be a spy'); (0, _assert2.default)(spy.calls.some(function (call) { return (0, _TestUtils.isEqual)(call.arguments, expectedArgs); }), 'spy was never called with %s', expectedArgs); return this; } }, { key: 'toNotHaveBeenCalled', value: function toNotHaveBeenCalled(message) { var spy = this.actual; (0, _assert2.default)((0, _SpyUtils.isSpy)(spy), 'The "actual" argument in expect(actual).toNotHaveBeenCalled() must be a spy'); (0, _assert2.default)(spy.calls.length === 0, message || 'spy was not supposed to be called'); return this; } }]); return Expectation; }(); var deprecate = function deprecate(fn, message) { var alreadyWarned = false; return function () { if (!alreadyWarned) { alreadyWarned = true; console.warn(message); } for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return fn.apply(this, args); }; }; Expectation.prototype.withContext = deprecate(function (context) { (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).withContext() must be a function'); this.context = context; return this; }, '\nwithContext is deprecated; use a closure instead.\n\n expect(fn).withContext(context).toThrow()\n\nbecomes\n\n expect(() => fn.call(context)).toThrow()\n'); Expectation.prototype.withArgs = deprecate(function () { var _args; (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).withArgs() must be a function'); if (arguments.length) this.args = (_args = this.args).concat.apply(_args, arguments); return this; }, '\nwithArgs is deprecated; use a closure instead.\n\n expect(fn).withArgs(a, b, c).toThrow()\n\nbecomes\n\n expect(() => fn(a, b, c)).toThrow()\n'); var aliases = { toBeAn: 'toBeA', toNotBeAn: 'toNotBeA', toBeTruthy: 'toExist', toBeFalsy: 'toNotExist', toBeFewerThan: 'toBeLessThan', toBeMoreThan: 'toBeGreaterThan', toContain: 'toInclude', toNotContain: 'toExclude', toNotInclude: 'toExclude', toContainKeys: 'toIncludeKeys', toNotContainKeys: 'toExcludeKeys', toNotIncludeKeys: 'toExcludeKeys', toContainKey: 'toIncludeKey', toNotContainKey: 'toExcludeKey', toNotIncludeKey: 'toExcludeKey' }; for (var alias in aliases) { if (aliases.hasOwnProperty(alias)) Expectation.prototype[alias] = Expectation.prototype[aliases[alias]]; }exports.default = Expectation; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var bind = __webpack_require__(3); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var implementation = __webpack_require__(4); module.exports = Function.prototype.bind || implementation; /***/ }, /* 4 */ /***/ function(module, exports) { var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, Buffer) {'use strict' function isArguments (obj) { return Object.prototype.toString.call(obj) === '[object Arguments]' } module.exports = match function match (obj, pattern) { return match_(obj, pattern, [], []) } /* istanbul ignore next */ var log = (/\btmatch\b/.test(process.env.NODE_DEBUG || '')) ? console.error : function () {} function match_ (obj, pattern, ca, cb) { log('TMATCH', typeof obj, pattern) if (obj == pattern) { log('TMATCH same object or simple value, or problem') // if one is object, and the other isn't, then this is bogus if (obj === null || pattern === null) { return true } else if (typeof obj === 'object' && typeof pattern === 'object') { return true } else if (typeof obj === 'object' && typeof pattern !== 'object') { return false } else if (typeof obj !== 'object' && typeof pattern === 'object') { return false } else { return true } } else if (obj === null || pattern === null) { log('TMATCH null test, already failed ==') return false } else if (typeof obj === 'string' && pattern instanceof RegExp) { log('TMATCH string~=regexp test') return pattern.test(obj) } else if (typeof obj === 'string' && typeof pattern === 'string' && pattern) { log('TMATCH string~=string test') return obj.indexOf(pattern) !== -1 } else if (obj instanceof Date && pattern instanceof Date) { log('TMATCH date test') return obj.getTime() === pattern.getTime() } else if (obj instanceof Date && typeof pattern === 'string') { log('TMATCH date~=string test') return obj.getTime() === new Date(pattern).getTime() } else if (isArguments(obj) || isArguments(pattern)) { log('TMATCH arguments test') var slice = Array.prototype.slice return match_(slice.call(obj), slice.call(pattern), ca, cb) } else if (pattern === Buffer) { log('TMATCH Buffer ctor') return Buffer.isBuffer(obj) } else if (pattern === Function) { log('TMATCH Function ctor') return typeof obj === 'function' } else if (pattern === Number) { log('TMATCH Number ctor (finite, not NaN)') return typeof obj === 'number' && obj === obj && isFinite(obj) } else if (pattern !== pattern) { log('TMATCH NaN') return obj !== obj } else if (pattern === String) { log('TMATCH String ctor') return typeof obj === 'string' } else if (pattern === Boolean) { log('TMATCH Boolean ctor') return typeof obj === 'boolean' } else if (pattern === Array) { log('TMATCH Array ctor', pattern, Array.isArray(obj)) return Array.isArray(obj) } else if (typeof pattern === 'function' && typeof obj === 'object') { log('TMATCH object~=function') return obj instanceof pattern } else if (typeof obj !== 'object' || typeof pattern !== 'object') { log('TMATCH obj is not object, pattern is not object, false') return false } else if (obj instanceof RegExp && pattern instanceof RegExp) { log('TMATCH regexp~=regexp test') return obj.source === pattern.source && obj.global === pattern.global && obj.multiline === pattern.multiline && obj.lastIndex === pattern.lastIndex && obj.ignoreCase === pattern.ignoreCase } else if (Buffer.isBuffer(obj) && Buffer.isBuffer(pattern)) { log('TMATCH buffer test') if (obj.equals) { return obj.equals(pattern) } else { if (obj.length !== pattern.length) return false for (var j = 0; j < obj.length; j++) if (obj[j] != pattern[j]) return false return true } } else { // both are objects. interesting case! log('TMATCH object~=object test') var kobj = Object.keys(obj) var kpat = Object.keys(pattern) log(' TMATCH patternkeys=%j objkeys=%j', kpat, kobj) // don't bother with stack acrobatics if there's nothing there if (kobj.length === 0 && kpat.length === 0) return true // if we've seen this exact pattern and object already, then // it means that pattern and obj have matching cyclicalness // however, non-cyclical patterns can match cyclical objects log(' TMATCH check seen objects...') var cal = ca.length while (cal--) if (ca[cal] === obj && cb[cal] === pattern) return true ca.push(obj); cb.push(pattern) log(' TMATCH not seen previously') var key for (var l = kpat.length - 1; l >= 0; l--) { key = kpat[l] log(' TMATCH test obj[%j]', key, obj[key], pattern[key]) if (!match_(obj[key], pattern[key], ca, cb)) return false } ca.pop() cb.pop() log(' TMATCH object pass') return true } /* istanbul ignore next */ throw new Error('impossible to reach this point') } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6), __webpack_require__(7).Buffer)) /***/ }, /* 6 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' 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 Buffer.poolSize = 8192 // not used by this implementation var rootParent = {} /** * 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. * * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property * on objects. * * - 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() function typedArraySupport () { function Bar () {} try { var arr = new Uint8Array(1) arr.foo = function () { return 42 } arr.constructor = Bar return arr.foo() === 42 && // typed array instances can be augmented arr.constructor === Bar && // constructor can be set 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 } /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (arg) { if (!(this instanceof Buffer)) { // Avoid going through an ArgumentsAdaptorTrampoline in the common case. if (arguments.length > 1) return new Buffer(arg, arguments[1]) return new Buffer(arg) } if (!Buffer.TYPED_ARRAY_SUPPORT) { this.length = 0 this.parent = undefined } // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } function fromNumber (that, length) { that = allocate(that, length < 0 ? 0 : checked(length) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < length; i++) { that[i] = 0 } } return that } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined') { if (object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object instanceof ArrayBuffer) { return fromArrayBuffer(that, object) } } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } function fromArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) // Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance array.byteLength that = Buffer._augment(new Uint8Array(array)) } else { // Fallback: Return an object instance of the Buffer class that = fromTypedArray(that, new Uint8Array(array)) } return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject (that, object) { var array var length = 0 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array } else { // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (subject, encoding) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) var buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = '' + string var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'binary': // Deprecated case 'raw': case 'raws': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` is deprecated Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` is deprecated Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'binary': return binaryWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeErro