UNPKG

609 kBJavaScriptView Raw
1!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APIValidator=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2/*jslint node: true */
3'use strict';
4
5var lodash = require('lodash'),
6 jjv = require('jjv'),
7 REQ = require('request'),
8 when = require('when'),
9
10AValidator = {
11 normalizeError: function (V, I) {
12 return {
13 type: 'validation',
14 target: I,
15 rule: V
16 };
17 },
18 ApiValidator: function (list, cb) {
19 lodash.map(list, this.promiseValidator, this);
20 },
21 all: function (list) {
22 if (!lodash.isArray(list)) {
23 return {
24 error: [{
25 'type': 'input',
26 message: 'Input is not array for all'
27 }]
28 };
29 }
30
31 return lodash.map(list, this.one, this);
32 },
33 one: function (D) {
34 var E, err;
35
36 if (!D) {
37 return {
38 error: [{
39 'type': 'internal',
40 message: 'No input for one'
41 }]
42 };
43 }
44
45 if (!D.schema) {
46 return {
47 error: [{
48 'type': 'input',
49 message: 'No schema in input for one'
50 }]
51 };
52 }
53
54 E = jjv();
55 err = E.validate(D.schema, D.data);
56
57 return err ? {error: lodash.map(err.validation, this.normalizeError, this)} : null;
58 }
59};
60
61module.exports = AValidator;
62
63},{"jjv":52,"lodash":54,"request":55,"when":82}],2:[function(require,module,exports){
64
65},{}],3:[function(require,module,exports){
66/*!
67 * The buffer module from node.js, for the browser.
68 *
69 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
70 * @license MIT
71 */
72
73var base64 = require('base64-js')
74var ieee754 = require('ieee754')
75var isArray = require('is-array')
76
77exports.Buffer = Buffer
78exports.SlowBuffer = Buffer
79exports.INSPECT_MAX_BYTES = 50
80Buffer.poolSize = 8192 // not used by this implementation
81
82var kMaxLength = 0x3fffffff
83
84/**
85 * If `Buffer.TYPED_ARRAY_SUPPORT`:
86 * === true Use Uint8Array implementation (fastest)
87 * === false Use Object implementation (most compatible, even IE6)
88 *
89 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
90 * Opera 11.6+, iOS 4.2+.
91 *
92 * Note:
93 *
94 * - Implementation must support adding new properties to `Uint8Array` instances.
95 * Firefox 4-29 lacked support, fixed in Firefox 30+.
96 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
97 *
98 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
99 *
100 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
101 * incorrect length in some situations.
102 *
103 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
104 * get the Object implementation, which is slower but will work correctly.
105 */
106Buffer.TYPED_ARRAY_SUPPORT = (function () {
107 try {
108 var buf = new ArrayBuffer(0)
109 var arr = new Uint8Array(buf)
110 arr.foo = function () { return 42 }
111 return 42 === arr.foo() && // typed array instances can be augmented
112 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
113 new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
114 } catch (e) {
115 return false
116 }
117})()
118
119/**
120 * Class: Buffer
121 * =============
122 *
123 * The Buffer constructor returns instances of `Uint8Array` that are augmented
124 * with function properties for all the node `Buffer` API functions. We use
125 * `Uint8Array` so that square bracket notation works as expected -- it returns
126 * a single octet.
127 *
128 * By augmenting the instances, we can avoid modifying the `Uint8Array`
129 * prototype.
130 */
131function Buffer (subject, encoding, noZero) {
132 if (!(this instanceof Buffer))
133 return new Buffer(subject, encoding, noZero)
134
135 var type = typeof subject
136
137 // Find the length
138 var length
139 if (type === 'number')
140 length = subject > 0 ? subject >>> 0 : 0
141 else if (type === 'string') {
142 if (encoding === 'base64')
143 subject = base64clean(subject)
144 length = Buffer.byteLength(subject, encoding)
145 } else if (type === 'object' && subject !== null) { // assume object is array-like
146 if (subject.type === 'Buffer' && isArray(subject.data))
147 subject = subject.data
148 length = +subject.length > 0 ? Math.floor(+subject.length) : 0
149 } else
150 throw new TypeError('must start with number, buffer, array or string')
151
152 if (this.length > kMaxLength)
153 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
154 'size: 0x' + kMaxLength.toString(16) + ' bytes')
155
156 var buf
157 if (Buffer.TYPED_ARRAY_SUPPORT) {
158 // Preferred: Return an augmented `Uint8Array` instance for best performance
159 buf = Buffer._augment(new Uint8Array(length))
160 } else {
161 // Fallback: Return THIS instance of Buffer (created by `new`)
162 buf = this
163 buf.length = length
164 buf._isBuffer = true
165 }
166
167 var i
168 if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
169 // Speed optimization -- use set if we're copying from a typed array
170 buf._set(subject)
171 } else if (isArrayish(subject)) {
172 // Treat array-ish objects as a byte array
173 if (Buffer.isBuffer(subject)) {
174 for (i = 0; i < length; i++)
175 buf[i] = subject.readUInt8(i)
176 } else {
177 for (i = 0; i < length; i++)
178 buf[i] = ((subject[i] % 256) + 256) % 256
179 }
180 } else if (type === 'string') {
181 buf.write(subject, 0, encoding)
182 } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
183 for (i = 0; i < length; i++) {
184 buf[i] = 0
185 }
186 }
187
188 return buf
189}
190
191Buffer.isBuffer = function (b) {
192 return !!(b != null && b._isBuffer)
193}
194
195Buffer.compare = function (a, b) {
196 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
197 throw new TypeError('Arguments must be Buffers')
198
199 var x = a.length
200 var y = b.length
201 for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
202 if (i !== len) {
203 x = a[i]
204 y = b[i]
205 }
206 if (x < y) return -1
207 if (y < x) return 1
208 return 0
209}
210
211Buffer.isEncoding = function (encoding) {
212 switch (String(encoding).toLowerCase()) {
213 case 'hex':
214 case 'utf8':
215 case 'utf-8':
216 case 'ascii':
217 case 'binary':
218 case 'base64':
219 case 'raw':
220 case 'ucs2':
221 case 'ucs-2':
222 case 'utf16le':
223 case 'utf-16le':
224 return true
225 default:
226 return false
227 }
228}
229
230Buffer.concat = function (list, totalLength) {
231 if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
232
233 if (list.length === 0) {
234 return new Buffer(0)
235 } else if (list.length === 1) {
236 return list[0]
237 }
238
239 var i
240 if (totalLength === undefined) {
241 totalLength = 0
242 for (i = 0; i < list.length; i++) {
243 totalLength += list[i].length
244 }
245 }
246
247 var buf = new Buffer(totalLength)
248 var pos = 0
249 for (i = 0; i < list.length; i++) {
250 var item = list[i]
251 item.copy(buf, pos)
252 pos += item.length
253 }
254 return buf
255}
256
257Buffer.byteLength = function (str, encoding) {
258 var ret
259 str = str + ''
260 switch (encoding || 'utf8') {
261 case 'ascii':
262 case 'binary':
263 case 'raw':
264 ret = str.length
265 break
266 case 'ucs2':
267 case 'ucs-2':
268 case 'utf16le':
269 case 'utf-16le':
270 ret = str.length * 2
271 break
272 case 'hex':
273 ret = str.length >>> 1
274 break
275 case 'utf8':
276 case 'utf-8':
277 ret = utf8ToBytes(str).length
278 break
279 case 'base64':
280 ret = base64ToBytes(str).length
281 break
282 default:
283 ret = str.length
284 }
285 return ret
286}
287
288// pre-set for values that may exist in the future
289Buffer.prototype.length = undefined
290Buffer.prototype.parent = undefined
291
292// toString(encoding, start=0, end=buffer.length)
293Buffer.prototype.toString = function (encoding, start, end) {
294 var loweredCase = false
295
296 start = start >>> 0
297 end = end === undefined || end === Infinity ? this.length : end >>> 0
298
299 if (!encoding) encoding = 'utf8'
300 if (start < 0) start = 0
301 if (end > this.length) end = this.length
302 if (end <= start) return ''
303
304 while (true) {
305 switch (encoding) {
306 case 'hex':
307 return hexSlice(this, start, end)
308
309 case 'utf8':
310 case 'utf-8':
311 return utf8Slice(this, start, end)
312
313 case 'ascii':
314 return asciiSlice(this, start, end)
315
316 case 'binary':
317 return binarySlice(this, start, end)
318
319 case 'base64':
320 return base64Slice(this, start, end)
321
322 case 'ucs2':
323 case 'ucs-2':
324 case 'utf16le':
325 case 'utf-16le':
326 return utf16leSlice(this, start, end)
327
328 default:
329 if (loweredCase)
330 throw new TypeError('Unknown encoding: ' + encoding)
331 encoding = (encoding + '').toLowerCase()
332 loweredCase = true
333 }
334 }
335}
336
337Buffer.prototype.equals = function (b) {
338 if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
339 return Buffer.compare(this, b) === 0
340}
341
342Buffer.prototype.inspect = function () {
343 var str = ''
344 var max = exports.INSPECT_MAX_BYTES
345 if (this.length > 0) {
346 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
347 if (this.length > max)
348 str += ' ... '
349 }
350 return '<Buffer ' + str + '>'
351}
352
353Buffer.prototype.compare = function (b) {
354 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
355 return Buffer.compare(this, b)
356}
357
358// `get` will be removed in Node 0.13+
359Buffer.prototype.get = function (offset) {
360 console.log('.get() is deprecated. Access using array indexes instead.')
361 return this.readUInt8(offset)
362}
363
364// `set` will be removed in Node 0.13+
365Buffer.prototype.set = function (v, offset) {
366 console.log('.set() is deprecated. Access using array indexes instead.')
367 return this.writeUInt8(v, offset)
368}
369
370function hexWrite (buf, string, offset, length) {
371 offset = Number(offset) || 0
372 var remaining = buf.length - offset
373 if (!length) {
374 length = remaining
375 } else {
376 length = Number(length)
377 if (length > remaining) {
378 length = remaining
379 }
380 }
381
382 // must be an even number of digits
383 var strLen = string.length
384 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
385
386 if (length > strLen / 2) {
387 length = strLen / 2
388 }
389 for (var i = 0; i < length; i++) {
390 var byte = parseInt(string.substr(i * 2, 2), 16)
391 if (isNaN(byte)) throw new Error('Invalid hex string')
392 buf[offset + i] = byte
393 }
394 return i
395}
396
397function utf8Write (buf, string, offset, length) {
398 var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
399 return charsWritten
400}
401
402function asciiWrite (buf, string, offset, length) {
403 var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
404 return charsWritten
405}
406
407function binaryWrite (buf, string, offset, length) {
408 return asciiWrite(buf, string, offset, length)
409}
410
411function base64Write (buf, string, offset, length) {
412 var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
413 return charsWritten
414}
415
416function utf16leWrite (buf, string, offset, length) {
417 var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
418 return charsWritten
419}
420
421Buffer.prototype.write = function (string, offset, length, encoding) {
422 // Support both (string, offset, length, encoding)
423 // and the legacy (string, encoding, offset, length)
424 if (isFinite(offset)) {
425 if (!isFinite(length)) {
426 encoding = length
427 length = undefined
428 }
429 } else { // legacy
430 var swap = encoding
431 encoding = offset
432 offset = length
433 length = swap
434 }
435
436 offset = Number(offset) || 0
437 var remaining = this.length - offset
438 if (!length) {
439 length = remaining
440 } else {
441 length = Number(length)
442 if (length > remaining) {
443 length = remaining
444 }
445 }
446 encoding = String(encoding || 'utf8').toLowerCase()
447
448 var ret
449 switch (encoding) {
450 case 'hex':
451 ret = hexWrite(this, string, offset, length)
452 break
453 case 'utf8':
454 case 'utf-8':
455 ret = utf8Write(this, string, offset, length)
456 break
457 case 'ascii':
458 ret = asciiWrite(this, string, offset, length)
459 break
460 case 'binary':
461 ret = binaryWrite(this, string, offset, length)
462 break
463 case 'base64':
464 ret = base64Write(this, string, offset, length)
465 break
466 case 'ucs2':
467 case 'ucs-2':
468 case 'utf16le':
469 case 'utf-16le':
470 ret = utf16leWrite(this, string, offset, length)
471 break
472 default:
473 throw new TypeError('Unknown encoding: ' + encoding)
474 }
475 return ret
476}
477
478Buffer.prototype.toJSON = function () {
479 return {
480 type: 'Buffer',
481 data: Array.prototype.slice.call(this._arr || this, 0)
482 }
483}
484
485function base64Slice (buf, start, end) {
486 if (start === 0 && end === buf.length) {
487 return base64.fromByteArray(buf)
488 } else {
489 return base64.fromByteArray(buf.slice(start, end))
490 }
491}
492
493function utf8Slice (buf, start, end) {
494 var res = ''
495 var tmp = ''
496 end = Math.min(buf.length, end)
497
498 for (var i = start; i < end; i++) {
499 if (buf[i] <= 0x7F) {
500 res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
501 tmp = ''
502 } else {
503 tmp += '%' + buf[i].toString(16)
504 }
505 }
506
507 return res + decodeUtf8Char(tmp)
508}
509
510function asciiSlice (buf, start, end) {
511 var ret = ''
512 end = Math.min(buf.length, end)
513
514 for (var i = start; i < end; i++) {
515 ret += String.fromCharCode(buf[i])
516 }
517 return ret
518}
519
520function binarySlice (buf, start, end) {
521 return asciiSlice(buf, start, end)
522}
523
524function hexSlice (buf, start, end) {
525 var len = buf.length
526
527 if (!start || start < 0) start = 0
528 if (!end || end < 0 || end > len) end = len
529
530 var out = ''
531 for (var i = start; i < end; i++) {
532 out += toHex(buf[i])
533 }
534 return out
535}
536
537function utf16leSlice (buf, start, end) {
538 var bytes = buf.slice(start, end)
539 var res = ''
540 for (var i = 0; i < bytes.length; i += 2) {
541 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
542 }
543 return res
544}
545
546Buffer.prototype.slice = function (start, end) {
547 var len = this.length
548 start = ~~start
549 end = end === undefined ? len : ~~end
550
551 if (start < 0) {
552 start += len;
553 if (start < 0)
554 start = 0
555 } else if (start > len) {
556 start = len
557 }
558
559 if (end < 0) {
560 end += len
561 if (end < 0)
562 end = 0
563 } else if (end > len) {
564 end = len
565 }
566
567 if (end < start)
568 end = start
569
570 if (Buffer.TYPED_ARRAY_SUPPORT) {
571 return Buffer._augment(this.subarray(start, end))
572 } else {
573 var sliceLen = end - start
574 var newBuf = new Buffer(sliceLen, undefined, true)
575 for (var i = 0; i < sliceLen; i++) {
576 newBuf[i] = this[i + start]
577 }
578 return newBuf
579 }
580}
581
582/*
583 * Need to make sure that buffer isn't trying to write out of bounds.
584 */
585function checkOffset (offset, ext, length) {
586 if ((offset % 1) !== 0 || offset < 0)
587 throw new RangeError('offset is not uint')
588 if (offset + ext > length)
589 throw new RangeError('Trying to access beyond buffer length')
590}
591
592Buffer.prototype.readUInt8 = function (offset, noAssert) {
593 if (!noAssert)
594 checkOffset(offset, 1, this.length)
595 return this[offset]
596}
597
598Buffer.prototype.readUInt16LE = function (offset, noAssert) {
599 if (!noAssert)
600 checkOffset(offset, 2, this.length)
601 return this[offset] | (this[offset + 1] << 8)
602}
603
604Buffer.prototype.readUInt16BE = function (offset, noAssert) {
605 if (!noAssert)
606 checkOffset(offset, 2, this.length)
607 return (this[offset] << 8) | this[offset + 1]
608}
609
610Buffer.prototype.readUInt32LE = function (offset, noAssert) {
611 if (!noAssert)
612 checkOffset(offset, 4, this.length)
613
614 return ((this[offset]) |
615 (this[offset + 1] << 8) |
616 (this[offset + 2] << 16)) +
617 (this[offset + 3] * 0x1000000)
618}
619
620Buffer.prototype.readUInt32BE = function (offset, noAssert) {
621 if (!noAssert)
622 checkOffset(offset, 4, this.length)
623
624 return (this[offset] * 0x1000000) +
625 ((this[offset + 1] << 16) |
626 (this[offset + 2] << 8) |
627 this[offset + 3])
628}
629
630Buffer.prototype.readInt8 = function (offset, noAssert) {
631 if (!noAssert)
632 checkOffset(offset, 1, this.length)
633 if (!(this[offset] & 0x80))
634 return (this[offset])
635 return ((0xff - this[offset] + 1) * -1)
636}
637
638Buffer.prototype.readInt16LE = function (offset, noAssert) {
639 if (!noAssert)
640 checkOffset(offset, 2, this.length)
641 var val = this[offset] | (this[offset + 1] << 8)
642 return (val & 0x8000) ? val | 0xFFFF0000 : val
643}
644
645Buffer.prototype.readInt16BE = function (offset, noAssert) {
646 if (!noAssert)
647 checkOffset(offset, 2, this.length)
648 var val = this[offset + 1] | (this[offset] << 8)
649 return (val & 0x8000) ? val | 0xFFFF0000 : val
650}
651
652Buffer.prototype.readInt32LE = function (offset, noAssert) {
653 if (!noAssert)
654 checkOffset(offset, 4, this.length)
655
656 return (this[offset]) |
657 (this[offset + 1] << 8) |
658 (this[offset + 2] << 16) |
659 (this[offset + 3] << 24)
660}
661
662Buffer.prototype.readInt32BE = function (offset, noAssert) {
663 if (!noAssert)
664 checkOffset(offset, 4, this.length)
665
666 return (this[offset] << 24) |
667 (this[offset + 1] << 16) |
668 (this[offset + 2] << 8) |
669 (this[offset + 3])
670}
671
672Buffer.prototype.readFloatLE = function (offset, noAssert) {
673 if (!noAssert)
674 checkOffset(offset, 4, this.length)
675 return ieee754.read(this, offset, true, 23, 4)
676}
677
678Buffer.prototype.readFloatBE = function (offset, noAssert) {
679 if (!noAssert)
680 checkOffset(offset, 4, this.length)
681 return ieee754.read(this, offset, false, 23, 4)
682}
683
684Buffer.prototype.readDoubleLE = function (offset, noAssert) {
685 if (!noAssert)
686 checkOffset(offset, 8, this.length)
687 return ieee754.read(this, offset, true, 52, 8)
688}
689
690Buffer.prototype.readDoubleBE = function (offset, noAssert) {
691 if (!noAssert)
692 checkOffset(offset, 8, this.length)
693 return ieee754.read(this, offset, false, 52, 8)
694}
695
696function checkInt (buf, value, offset, ext, max, min) {
697 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
698 if (value > max || value < min) throw new TypeError('value is out of bounds')
699 if (offset + ext > buf.length) throw new TypeError('index out of range')
700}
701
702Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
703 value = +value
704 offset = offset >>> 0
705 if (!noAssert)
706 checkInt(this, value, offset, 1, 0xff, 0)
707 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
708 this[offset] = value
709 return offset + 1
710}
711
712function objectWriteUInt16 (buf, value, offset, littleEndian) {
713 if (value < 0) value = 0xffff + value + 1
714 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
715 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
716 (littleEndian ? i : 1 - i) * 8
717 }
718}
719
720Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
721 value = +value
722 offset = offset >>> 0
723 if (!noAssert)
724 checkInt(this, value, offset, 2, 0xffff, 0)
725 if (Buffer.TYPED_ARRAY_SUPPORT) {
726 this[offset] = value
727 this[offset + 1] = (value >>> 8)
728 } else objectWriteUInt16(this, value, offset, true)
729 return offset + 2
730}
731
732Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
733 value = +value
734 offset = offset >>> 0
735 if (!noAssert)
736 checkInt(this, value, offset, 2, 0xffff, 0)
737 if (Buffer.TYPED_ARRAY_SUPPORT) {
738 this[offset] = (value >>> 8)
739 this[offset + 1] = value
740 } else objectWriteUInt16(this, value, offset, false)
741 return offset + 2
742}
743
744function objectWriteUInt32 (buf, value, offset, littleEndian) {
745 if (value < 0) value = 0xffffffff + value + 1
746 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
747 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
748 }
749}
750
751Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
752 value = +value
753 offset = offset >>> 0
754 if (!noAssert)
755 checkInt(this, value, offset, 4, 0xffffffff, 0)
756 if (Buffer.TYPED_ARRAY_SUPPORT) {
757 this[offset + 3] = (value >>> 24)
758 this[offset + 2] = (value >>> 16)
759 this[offset + 1] = (value >>> 8)
760 this[offset] = value
761 } else objectWriteUInt32(this, value, offset, true)
762 return offset + 4
763}
764
765Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
766 value = +value
767 offset = offset >>> 0
768 if (!noAssert)
769 checkInt(this, value, offset, 4, 0xffffffff, 0)
770 if (Buffer.TYPED_ARRAY_SUPPORT) {
771 this[offset] = (value >>> 24)
772 this[offset + 1] = (value >>> 16)
773 this[offset + 2] = (value >>> 8)
774 this[offset + 3] = value
775 } else objectWriteUInt32(this, value, offset, false)
776 return offset + 4
777}
778
779Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
780 value = +value
781 offset = offset >>> 0
782 if (!noAssert)
783 checkInt(this, value, offset, 1, 0x7f, -0x80)
784 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
785 if (value < 0) value = 0xff + value + 1
786 this[offset] = value
787 return offset + 1
788}
789
790Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
791 value = +value
792 offset = offset >>> 0
793 if (!noAssert)
794 checkInt(this, value, offset, 2, 0x7fff, -0x8000)
795 if (Buffer.TYPED_ARRAY_SUPPORT) {
796 this[offset] = value
797 this[offset + 1] = (value >>> 8)
798 } else objectWriteUInt16(this, value, offset, true)
799 return offset + 2
800}
801
802Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
803 value = +value
804 offset = offset >>> 0
805 if (!noAssert)
806 checkInt(this, value, offset, 2, 0x7fff, -0x8000)
807 if (Buffer.TYPED_ARRAY_SUPPORT) {
808 this[offset] = (value >>> 8)
809 this[offset + 1] = value
810 } else objectWriteUInt16(this, value, offset, false)
811 return offset + 2
812}
813
814Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
815 value = +value
816 offset = offset >>> 0
817 if (!noAssert)
818 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
819 if (Buffer.TYPED_ARRAY_SUPPORT) {
820 this[offset] = value
821 this[offset + 1] = (value >>> 8)
822 this[offset + 2] = (value >>> 16)
823 this[offset + 3] = (value >>> 24)
824 } else objectWriteUInt32(this, value, offset, true)
825 return offset + 4
826}
827
828Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
829 value = +value
830 offset = offset >>> 0
831 if (!noAssert)
832 checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
833 if (value < 0) value = 0xffffffff + value + 1
834 if (Buffer.TYPED_ARRAY_SUPPORT) {
835 this[offset] = (value >>> 24)
836 this[offset + 1] = (value >>> 16)
837 this[offset + 2] = (value >>> 8)
838 this[offset + 3] = value
839 } else objectWriteUInt32(this, value, offset, false)
840 return offset + 4
841}
842
843function checkIEEE754 (buf, value, offset, ext, max, min) {
844 if (value > max || value < min) throw new TypeError('value is out of bounds')
845 if (offset + ext > buf.length) throw new TypeError('index out of range')
846}
847
848function writeFloat (buf, value, offset, littleEndian, noAssert) {
849 if (!noAssert)
850 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
851 ieee754.write(buf, value, offset, littleEndian, 23, 4)
852 return offset + 4
853}
854
855Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
856 return writeFloat(this, value, offset, true, noAssert)
857}
858
859Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
860 return writeFloat(this, value, offset, false, noAssert)
861}
862
863function writeDouble (buf, value, offset, littleEndian, noAssert) {
864 if (!noAssert)
865 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
866 ieee754.write(buf, value, offset, littleEndian, 52, 8)
867 return offset + 8
868}
869
870Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
871 return writeDouble(this, value, offset, true, noAssert)
872}
873
874Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
875 return writeDouble(this, value, offset, false, noAssert)
876}
877
878// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
879Buffer.prototype.copy = function (target, target_start, start, end) {
880 var source = this
881
882 if (!start) start = 0
883 if (!end && end !== 0) end = this.length
884 if (!target_start) target_start = 0
885
886 // Copy 0 bytes; we're done
887 if (end === start) return
888 if (target.length === 0 || source.length === 0) return
889
890 // Fatal error conditions
891 if (end < start) throw new TypeError('sourceEnd < sourceStart')
892 if (target_start < 0 || target_start >= target.length)
893 throw new TypeError('targetStart out of bounds')
894 if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
895 if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
896
897 // Are we oob?
898 if (end > this.length)
899 end = this.length
900 if (target.length - target_start < end - start)
901 end = target.length - target_start + start
902
903 var len = end - start
904
905 if (len < 100 || !Buffer.TYPED_ARRAY_SUPPORT) {
906 for (var i = 0; i < len; i++) {
907 target[i + target_start] = this[i + start]
908 }
909 } else {
910 target._set(this.subarray(start, start + len), target_start)
911 }
912}
913
914// fill(value, start=0, end=buffer.length)
915Buffer.prototype.fill = function (value, start, end) {
916 if (!value) value = 0
917 if (!start) start = 0
918 if (!end) end = this.length
919
920 if (end < start) throw new TypeError('end < start')
921
922 // Fill 0 bytes; we're done
923 if (end === start) return
924 if (this.length === 0) return
925
926 if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
927 if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
928
929 var i
930 if (typeof value === 'number') {
931 for (i = start; i < end; i++) {
932 this[i] = value
933 }
934 } else {
935 var bytes = utf8ToBytes(value.toString())
936 var len = bytes.length
937 for (i = start; i < end; i++) {
938 this[i] = bytes[i % len]
939 }
940 }
941
942 return this
943}
944
945/**
946 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
947 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
948 */
949Buffer.prototype.toArrayBuffer = function () {
950 if (typeof Uint8Array !== 'undefined') {
951 if (Buffer.TYPED_ARRAY_SUPPORT) {
952 return (new Buffer(this)).buffer
953 } else {
954 var buf = new Uint8Array(this.length)
955 for (var i = 0, len = buf.length; i < len; i += 1) {
956 buf[i] = this[i]
957 }
958 return buf.buffer
959 }
960 } else {
961 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
962 }
963}
964
965// HELPER FUNCTIONS
966// ================
967
968var BP = Buffer.prototype
969
970/**
971 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
972 */
973Buffer._augment = function (arr) {
974 arr._isBuffer = true
975
976 // save reference to original Uint8Array get/set methods before overwriting
977 arr._get = arr.get
978 arr._set = arr.set
979
980 // deprecated, will be removed in node 0.13+
981 arr.get = BP.get
982 arr.set = BP.set
983
984 arr.write = BP.write
985 arr.toString = BP.toString
986 arr.toLocaleString = BP.toString
987 arr.toJSON = BP.toJSON
988 arr.equals = BP.equals
989 arr.compare = BP.compare
990 arr.copy = BP.copy
991 arr.slice = BP.slice
992 arr.readUInt8 = BP.readUInt8
993 arr.readUInt16LE = BP.readUInt16LE
994 arr.readUInt16BE = BP.readUInt16BE
995 arr.readUInt32LE = BP.readUInt32LE
996 arr.readUInt32BE = BP.readUInt32BE
997 arr.readInt8 = BP.readInt8
998 arr.readInt16LE = BP.readInt16LE
999 arr.readInt16BE = BP.readInt16BE
1000 arr.readInt32LE = BP.readInt32LE
1001 arr.readInt32BE = BP.readInt32BE
1002 arr.readFloatLE = BP.readFloatLE
1003 arr.readFloatBE = BP.readFloatBE
1004 arr.readDoubleLE = BP.readDoubleLE
1005 arr.readDoubleBE = BP.readDoubleBE
1006 arr.writeUInt8 = BP.writeUInt8
1007 arr.writeUInt16LE = BP.writeUInt16LE
1008 arr.writeUInt16BE = BP.writeUInt16BE
1009 arr.writeUInt32LE = BP.writeUInt32LE
1010 arr.writeUInt32BE = BP.writeUInt32BE
1011 arr.writeInt8 = BP.writeInt8
1012 arr.writeInt16LE = BP.writeInt16LE
1013 arr.writeInt16BE = BP.writeInt16BE
1014 arr.writeInt32LE = BP.writeInt32LE
1015 arr.writeInt32BE = BP.writeInt32BE
1016 arr.writeFloatLE = BP.writeFloatLE
1017 arr.writeFloatBE = BP.writeFloatBE
1018 arr.writeDoubleLE = BP.writeDoubleLE
1019 arr.writeDoubleBE = BP.writeDoubleBE
1020 arr.fill = BP.fill
1021 arr.inspect = BP.inspect
1022 arr.toArrayBuffer = BP.toArrayBuffer
1023
1024 return arr
1025}
1026
1027var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
1028
1029function base64clean (str) {
1030 // Node strips out invalid characters like \n and \t from the string, base64-js does not
1031 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1032 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1033 while (str.length % 4 !== 0) {
1034 str = str + '='
1035 }
1036 return str
1037}
1038
1039function stringtrim (str) {
1040 if (str.trim) return str.trim()
1041 return str.replace(/^\s+|\s+$/g, '')
1042}
1043
1044function isArrayish (subject) {
1045 return isArray(subject) || Buffer.isBuffer(subject) ||
1046 subject && typeof subject === 'object' &&
1047 typeof subject.length === 'number'
1048}
1049
1050function toHex (n) {
1051 if (n < 16) return '0' + n.toString(16)
1052 return n.toString(16)
1053}
1054
1055function utf8ToBytes (str) {
1056 var byteArray = []
1057 for (var i = 0; i < str.length; i++) {
1058 var b = str.charCodeAt(i)
1059 if (b <= 0x7F) {
1060 byteArray.push(b)
1061 } else {
1062 var start = i
1063 if (b >= 0xD800 && b <= 0xDFFF) i++
1064 var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
1065 for (var j = 0; j < h.length; j++) {
1066 byteArray.push(parseInt(h[j], 16))
1067 }
1068 }
1069 }
1070 return byteArray
1071}
1072
1073function asciiToBytes (str) {
1074 var byteArray = []
1075 for (var i = 0; i < str.length; i++) {
1076 // Node's code seems to be doing this and not & 0x7F..
1077 byteArray.push(str.charCodeAt(i) & 0xFF)
1078 }
1079 return byteArray
1080}
1081
1082function utf16leToBytes (str) {
1083 var c, hi, lo
1084 var byteArray = []
1085 for (var i = 0; i < str.length; i++) {
1086 c = str.charCodeAt(i)
1087 hi = c >> 8
1088 lo = c % 256
1089 byteArray.push(lo)
1090 byteArray.push(hi)
1091 }
1092
1093 return byteArray
1094}
1095
1096function base64ToBytes (str) {
1097 return base64.toByteArray(str)
1098}
1099
1100function blitBuffer (src, dst, offset, length) {
1101 for (var i = 0; i < length; i++) {
1102 if ((i + offset >= dst.length) || (i >= src.length))
1103 break
1104 dst[i + offset] = src[i]
1105 }
1106 return i
1107}
1108
1109function decodeUtf8Char (str) {
1110 try {
1111 return decodeURIComponent(str)
1112 } catch (err) {
1113 return String.fromCharCode(0xFFFD) // UTF 8 invalid char
1114 }
1115}
1116
1117},{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(require,module,exports){
1118var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1119
1120;(function (exports) {
1121 'use strict';
1122
1123 var Arr = (typeof Uint8Array !== 'undefined')
1124 ? Uint8Array
1125 : Array
1126
1127 var PLUS = '+'.charCodeAt(0)
1128 var SLASH = '/'.charCodeAt(0)
1129 var NUMBER = '0'.charCodeAt(0)
1130 var LOWER = 'a'.charCodeAt(0)
1131 var UPPER = 'A'.charCodeAt(0)
1132
1133 function decode (elt) {
1134 var code = elt.charCodeAt(0)
1135 if (code === PLUS)
1136 return 62 // '+'
1137 if (code === SLASH)
1138 return 63 // '/'
1139 if (code < NUMBER)
1140 return -1 //no match
1141 if (code < NUMBER + 10)
1142 return code - NUMBER + 26 + 26
1143 if (code < UPPER + 26)
1144 return code - UPPER
1145 if (code < LOWER + 26)
1146 return code - LOWER + 26
1147 }
1148
1149 function b64ToByteArray (b64) {
1150 var i, j, l, tmp, placeHolders, arr
1151
1152 if (b64.length % 4 > 0) {
1153 throw new Error('Invalid string. Length must be a multiple of 4')
1154 }
1155
1156 // the number of equal signs (place holders)
1157 // if there are two placeholders, than the two characters before it
1158 // represent one byte
1159 // if there is only one, then the three characters before it represent 2 bytes
1160 // this is just a cheap hack to not do indexOf twice
1161 var len = b64.length
1162 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
1163
1164 // base64 is 4/3 + up to two characters of the original data
1165 arr = new Arr(b64.length * 3 / 4 - placeHolders)
1166
1167 // if there are placeholders, only get up to the last complete 4 chars
1168 l = placeHolders > 0 ? b64.length - 4 : b64.length
1169
1170 var L = 0
1171
1172 function push (v) {
1173 arr[L++] = v
1174 }
1175
1176 for (i = 0, j = 0; i < l; i += 4, j += 3) {
1177 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
1178 push((tmp & 0xFF0000) >> 16)
1179 push((tmp & 0xFF00) >> 8)
1180 push(tmp & 0xFF)
1181 }
1182
1183 if (placeHolders === 2) {
1184 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
1185 push(tmp & 0xFF)
1186 } else if (placeHolders === 1) {
1187 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
1188 push((tmp >> 8) & 0xFF)
1189 push(tmp & 0xFF)
1190 }
1191
1192 return arr
1193 }
1194
1195 function uint8ToBase64 (uint8) {
1196 var i,
1197 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
1198 output = "",
1199 temp, length
1200
1201 function encode (num) {
1202 return lookup.charAt(num)
1203 }
1204
1205 function tripletToBase64 (num) {
1206 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
1207 }
1208
1209 // go through the array every three bytes, we'll deal with trailing stuff later
1210 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
1211 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
1212 output += tripletToBase64(temp)
1213 }
1214
1215 // pad the end with zeros, but make sure to not forget the extra bytes
1216 switch (extraBytes) {
1217 case 1:
1218 temp = uint8[uint8.length - 1]
1219 output += encode(temp >> 2)
1220 output += encode((temp << 4) & 0x3F)
1221 output += '=='
1222 break
1223 case 2:
1224 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
1225 output += encode(temp >> 10)
1226 output += encode((temp >> 4) & 0x3F)
1227 output += encode((temp << 2) & 0x3F)
1228 output += '='
1229 break
1230 }
1231
1232 return output
1233 }
1234
1235 exports.toByteArray = b64ToByteArray
1236 exports.fromByteArray = uint8ToBase64
1237}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
1238
1239},{}],5:[function(require,module,exports){
1240exports.read = function(buffer, offset, isLE, mLen, nBytes) {
1241 var e, m,
1242 eLen = nBytes * 8 - mLen - 1,
1243 eMax = (1 << eLen) - 1,
1244 eBias = eMax >> 1,
1245 nBits = -7,
1246 i = isLE ? (nBytes - 1) : 0,
1247 d = isLE ? -1 : 1,
1248 s = buffer[offset + i];
1249
1250 i += d;
1251
1252 e = s & ((1 << (-nBits)) - 1);
1253 s >>= (-nBits);
1254 nBits += eLen;
1255 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
1256
1257 m = e & ((1 << (-nBits)) - 1);
1258 e >>= (-nBits);
1259 nBits += mLen;
1260 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
1261
1262 if (e === 0) {
1263 e = 1 - eBias;
1264 } else if (e === eMax) {
1265 return m ? NaN : ((s ? -1 : 1) * Infinity);
1266 } else {
1267 m = m + Math.pow(2, mLen);
1268 e = e - eBias;
1269 }
1270 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
1271};
1272
1273exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
1274 var e, m, c,
1275 eLen = nBytes * 8 - mLen - 1,
1276 eMax = (1 << eLen) - 1,
1277 eBias = eMax >> 1,
1278 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
1279 i = isLE ? 0 : (nBytes - 1),
1280 d = isLE ? 1 : -1,
1281 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
1282
1283 value = Math.abs(value);
1284
1285 if (isNaN(value) || value === Infinity) {
1286 m = isNaN(value) ? 1 : 0;
1287 e = eMax;
1288 } else {
1289 e = Math.floor(Math.log(value) / Math.LN2);
1290 if (value * (c = Math.pow(2, -e)) < 1) {
1291 e--;
1292 c *= 2;
1293 }
1294 if (e + eBias >= 1) {
1295 value += rt / c;
1296 } else {
1297 value += rt * Math.pow(2, 1 - eBias);
1298 }
1299 if (value * c >= 2) {
1300 e++;
1301 c /= 2;
1302 }
1303
1304 if (e + eBias >= eMax) {
1305 m = 0;
1306 e = eMax;
1307 } else if (e + eBias >= 1) {
1308 m = (value * c - 1) * Math.pow(2, mLen);
1309 e = e + eBias;
1310 } else {
1311 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
1312 e = 0;
1313 }
1314 }
1315
1316 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
1317
1318 e = (e << mLen) | m;
1319 eLen += mLen;
1320 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
1321
1322 buffer[offset + i - d] |= s * 128;
1323};
1324
1325},{}],6:[function(require,module,exports){
1326
1327/**
1328 * isArray
1329 */
1330
1331var isArray = Array.isArray;
1332
1333/**
1334 * toString
1335 */
1336
1337var str = Object.prototype.toString;
1338
1339/**
1340 * Whether or not the given `val`
1341 * is an array.
1342 *
1343 * example:
1344 *
1345 * isArray([]);
1346 * // > true
1347 * isArray(arguments);
1348 * // > false
1349 * isArray('');
1350 * // > false
1351 *
1352 * @param {mixed} val
1353 * @return {bool}
1354 */
1355
1356module.exports = isArray || function (val) {
1357 return !! val && '[object Array]' == str.call(val);
1358};
1359
1360},{}],7:[function(require,module,exports){
1361(function (Buffer){
1362var createHash = require('sha.js')
1363
1364var md5 = toConstructor(require('./md5'))
1365var rmd160 = toConstructor(require('ripemd160'))
1366
1367function toConstructor (fn) {
1368 return function () {
1369 var buffers = []
1370 var m= {
1371 update: function (data, enc) {
1372 if(!Buffer.isBuffer(data)) data = new Buffer(data, enc)
1373 buffers.push(data)
1374 return this
1375 },
1376 digest: function (enc) {
1377 var buf = Buffer.concat(buffers)
1378 var r = fn(buf)
1379 buffers = null
1380 return enc ? r.toString(enc) : r
1381 }
1382 }
1383 return m
1384 }
1385}
1386
1387module.exports = function (alg) {
1388 if('md5' === alg) return new md5()
1389 if('rmd160' === alg) return new rmd160()
1390 return createHash(alg)
1391}
1392
1393}).call(this,require("buffer").Buffer)
1394},{"./md5":11,"buffer":3,"ripemd160":14,"sha.js":16}],8:[function(require,module,exports){
1395(function (Buffer){
1396var createHash = require('./create-hash')
1397
1398var zeroBuffer = new Buffer(128)
1399zeroBuffer.fill(0)
1400
1401module.exports = Hmac
1402
1403function Hmac (alg, key) {
1404 if(!(this instanceof Hmac)) return new Hmac(alg, key)
1405 this._opad = opad
1406 this._alg = alg
1407
1408 var blocksize = (alg === 'sha512') ? 128 : 64
1409
1410 key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key
1411
1412 if(key.length > blocksize) {
1413 key = createHash(alg).update(key).digest()
1414 } else if(key.length < blocksize) {
1415 key = Buffer.concat([key, zeroBuffer], blocksize)
1416 }
1417
1418 var ipad = this._ipad = new Buffer(blocksize)
1419 var opad = this._opad = new Buffer(blocksize)
1420
1421 for(var i = 0; i < blocksize; i++) {
1422 ipad[i] = key[i] ^ 0x36
1423 opad[i] = key[i] ^ 0x5C
1424 }
1425
1426 this._hash = createHash(alg).update(ipad)
1427}
1428
1429Hmac.prototype.update = function (data, enc) {
1430 this._hash.update(data, enc)
1431 return this
1432}
1433
1434Hmac.prototype.digest = function (enc) {
1435 var h = this._hash.digest()
1436 return createHash(this._alg).update(this._opad).update(h).digest(enc)
1437}
1438
1439
1440}).call(this,require("buffer").Buffer)
1441},{"./create-hash":7,"buffer":3}],9:[function(require,module,exports){
1442(function (Buffer){
1443var intSize = 4;
1444var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
1445var chrsz = 8;
1446
1447function toArray(buf, bigEndian) {
1448 if ((buf.length % intSize) !== 0) {
1449 var len = buf.length + (intSize - (buf.length % intSize));
1450 buf = Buffer.concat([buf, zeroBuffer], len);
1451 }
1452
1453 var arr = [];
1454 var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
1455 for (var i = 0; i < buf.length; i += intSize) {
1456 arr.push(fn.call(buf, i));
1457 }
1458 return arr;
1459}
1460
1461function toBuffer(arr, size, bigEndian) {
1462 var buf = new Buffer(size);
1463 var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
1464 for (var i = 0; i < arr.length; i++) {
1465 fn.call(buf, arr[i], i * 4, true);
1466 }
1467 return buf;
1468}
1469
1470function hash(buf, fn, hashSize, bigEndian) {
1471 if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
1472 var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
1473 return toBuffer(arr, hashSize, bigEndian);
1474}
1475
1476module.exports = { hash: hash };
1477
1478}).call(this,require("buffer").Buffer)
1479},{"buffer":3}],10:[function(require,module,exports){
1480(function (Buffer){
1481var rng = require('./rng')
1482
1483function error () {
1484 var m = [].slice.call(arguments).join(' ')
1485 throw new Error([
1486 m,
1487 'we accept pull requests',
1488 'http://github.com/dominictarr/crypto-browserify'
1489 ].join('\n'))
1490}
1491
1492exports.createHash = require('./create-hash')
1493
1494exports.createHmac = require('./create-hmac')
1495
1496exports.randomBytes = function(size, callback) {
1497 if (callback && callback.call) {
1498 try {
1499 callback.call(this, undefined, new Buffer(rng(size)))
1500 } catch (err) { callback(err) }
1501 } else {
1502 return new Buffer(rng(size))
1503 }
1504}
1505
1506function each(a, f) {
1507 for(var i in a)
1508 f(a[i], i)
1509}
1510
1511exports.getHashes = function () {
1512 return ['sha1', 'sha256', 'sha512', 'md5', 'rmd160']
1513}
1514
1515var p = require('./pbkdf2')(exports)
1516exports.pbkdf2 = p.pbkdf2
1517exports.pbkdf2Sync = p.pbkdf2Sync
1518
1519
1520// the least I can do is make error messages for the rest of the node.js/crypto api.
1521each(['createCredentials'
1522, 'createCipher'
1523, 'createCipheriv'
1524, 'createDecipher'
1525, 'createDecipheriv'
1526, 'createSign'
1527, 'createVerify'
1528, 'createDiffieHellman'
1529], function (name) {
1530 exports[name] = function () {
1531 error('sorry,', name, 'is not implemented yet')
1532 }
1533})
1534
1535}).call(this,require("buffer").Buffer)
1536},{"./create-hash":7,"./create-hmac":8,"./pbkdf2":20,"./rng":21,"buffer":3}],11:[function(require,module,exports){
1537/*
1538 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
1539 * Digest Algorithm, as defined in RFC 1321.
1540 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
1541 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
1542 * Distributed under the BSD License
1543 * See http://pajhome.org.uk/crypt/md5 for more info.
1544 */
1545
1546var helpers = require('./helpers');
1547
1548/*
1549 * Calculate the MD5 of an array of little-endian words, and a bit length
1550 */
1551function core_md5(x, len)
1552{
1553 /* append padding */
1554 x[len >> 5] |= 0x80 << ((len) % 32);
1555 x[(((len + 64) >>> 9) << 4) + 14] = len;
1556
1557 var a = 1732584193;
1558 var b = -271733879;
1559 var c = -1732584194;
1560 var d = 271733878;
1561
1562 for(var i = 0; i < x.length; i += 16)
1563 {
1564 var olda = a;
1565 var oldb = b;
1566 var oldc = c;
1567 var oldd = d;
1568
1569 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
1570 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
1571 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
1572 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
1573 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
1574 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
1575 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
1576 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
1577 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
1578 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
1579 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
1580 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
1581 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
1582 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
1583 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
1584 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
1585
1586 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
1587 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
1588 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
1589 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
1590 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
1591 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
1592 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
1593 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
1594 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
1595 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
1596 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
1597 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
1598 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
1599 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
1600 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
1601 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
1602
1603 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
1604 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
1605 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
1606 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
1607 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
1608 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
1609 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
1610 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
1611 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
1612 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
1613 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
1614 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
1615 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
1616 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
1617 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
1618 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
1619
1620 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
1621 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
1622 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
1623 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
1624 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
1625 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
1626 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
1627 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
1628 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
1629 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
1630 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
1631 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
1632 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
1633 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
1634 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
1635 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
1636
1637 a = safe_add(a, olda);
1638 b = safe_add(b, oldb);
1639 c = safe_add(c, oldc);
1640 d = safe_add(d, oldd);
1641 }
1642 return Array(a, b, c, d);
1643
1644}
1645
1646/*
1647 * These functions implement the four basic operations the algorithm uses.
1648 */
1649function md5_cmn(q, a, b, x, s, t)
1650{
1651 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
1652}
1653function md5_ff(a, b, c, d, x, s, t)
1654{
1655 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
1656}
1657function md5_gg(a, b, c, d, x, s, t)
1658{
1659 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
1660}
1661function md5_hh(a, b, c, d, x, s, t)
1662{
1663 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
1664}
1665function md5_ii(a, b, c, d, x, s, t)
1666{
1667 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
1668}
1669
1670/*
1671 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
1672 * to work around bugs in some JS interpreters.
1673 */
1674function safe_add(x, y)
1675{
1676 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
1677 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
1678 return (msw << 16) | (lsw & 0xFFFF);
1679}
1680
1681/*
1682 * Bitwise rotate a 32-bit number to the left.
1683 */
1684function bit_rol(num, cnt)
1685{
1686 return (num << cnt) | (num >>> (32 - cnt));
1687}
1688
1689module.exports = function md5(buf) {
1690 return helpers.hash(buf, core_md5, 16);
1691};
1692
1693},{"./helpers":9}],12:[function(require,module,exports){
1694var crypto = require('crypto')
1695
1696var exportFn = require('./pbkdf2')
1697var exported = exportFn(crypto)
1698
1699module.exports = {
1700 pbkdf2: exported.pbkdf2,
1701 pbkdf2Sync: exported.pbkdf2Sync,
1702
1703 // for crypto-browserify
1704 __pbkdf2Export: exportFn
1705}
1706
1707},{"./pbkdf2":13,"crypto":10}],13:[function(require,module,exports){
1708(function (Buffer){
1709module.exports = function(crypto) {
1710 function pbkdf2(password, salt, iterations, keylen, digest, callback) {
1711 if ('function' === typeof digest) {
1712 callback = digest
1713 digest = undefined
1714 }
1715
1716 if ('function' !== typeof callback)
1717 throw new Error('No callback provided to pbkdf2')
1718
1719 setTimeout(function() {
1720 var result
1721
1722 try {
1723 result = pbkdf2Sync(password, salt, iterations, keylen, digest)
1724 } catch (e) {
1725 return callback(e)
1726 }
1727
1728 callback(undefined, result)
1729 })
1730 }
1731
1732 function pbkdf2Sync(password, salt, iterations, keylen, digest) {
1733 if ('number' !== typeof iterations)
1734 throw new TypeError('Iterations not a number')
1735
1736 if (iterations < 0)
1737 throw new TypeError('Bad iterations')
1738
1739 if ('number' !== typeof keylen)
1740 throw new TypeError('Key length not a number')
1741
1742 if (keylen < 0)
1743 throw new TypeError('Bad key length')
1744
1745 digest = digest || 'sha1'
1746
1747 if (!Buffer.isBuffer(password)) password = new Buffer(password)
1748 if (!Buffer.isBuffer(salt)) salt = new Buffer(salt)
1749
1750 var hLen, l = 1, r, T
1751 var DK = new Buffer(keylen)
1752 var block1 = new Buffer(salt.length + 4)
1753 salt.copy(block1, 0, 0, salt.length)
1754
1755 for (var i = 1; i <= l; i++) {
1756 block1.writeUInt32BE(i, salt.length)
1757
1758 var U = crypto.createHmac(digest, password).update(block1).digest()
1759
1760 if (!hLen) {
1761 hLen = U.length
1762 T = new Buffer(hLen)
1763 l = Math.ceil(keylen / hLen)
1764 r = keylen - (l - 1) * hLen
1765
1766 if (keylen > (Math.pow(2, 32) - 1) * hLen)
1767 throw new TypeError('keylen exceeds maximum length')
1768 }
1769
1770 U.copy(T, 0, 0, hLen)
1771
1772 for (var j = 1; j < iterations; j++) {
1773 U = crypto.createHmac(digest, password).update(U).digest()
1774
1775 for (var k = 0; k < hLen; k++) {
1776 T[k] ^= U[k]
1777 }
1778 }
1779
1780 var destPos = (i - 1) * hLen
1781 var len = (i == l ? r : hLen)
1782 T.copy(DK, destPos, 0, len)
1783 }
1784
1785 return DK
1786 }
1787
1788 return {
1789 pbkdf2: pbkdf2,
1790 pbkdf2Sync: pbkdf2Sync
1791 }
1792}
1793
1794}).call(this,require("buffer").Buffer)
1795},{"buffer":3}],14:[function(require,module,exports){
1796(function (Buffer){
1797
1798module.exports = ripemd160
1799
1800
1801
1802/*
1803CryptoJS v3.1.2
1804code.google.com/p/crypto-js
1805(c) 2009-2013 by Jeff Mott. All rights reserved.
1806code.google.com/p/crypto-js/wiki/License
1807*/
1808/** @preserve
1809(c) 2012 by Cédric Mesnil. All rights reserved.
1810
1811Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1812
1813 - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
1814 - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
1815
1816THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1817*/
1818
1819// Constants table
1820var zl = [
1821 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
1822 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
1823 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1824 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
1825 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13];
1826var zr = [
1827 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
1828 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
1829 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
1830 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
1831 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11];
1832var sl = [
1833 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
1834 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
1835 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
1836 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
1837 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];
1838var sr = [
1839 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
1840 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
1841 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
1842 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
1843 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];
1844
1845var hl = [ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E];
1846var hr = [ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000];
1847
1848var bytesToWords = function (bytes) {
1849 var words = [];
1850 for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
1851 words[b >>> 5] |= bytes[i] << (24 - b % 32);
1852 }
1853 return words;
1854};
1855
1856var wordsToBytes = function (words) {
1857 var bytes = [];
1858 for (var b = 0; b < words.length * 32; b += 8) {
1859 bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
1860 }
1861 return bytes;
1862};
1863
1864var processBlock = function (H, M, offset) {
1865
1866 // Swap endian
1867 for (var i = 0; i < 16; i++) {
1868 var offset_i = offset + i;
1869 var M_offset_i = M[offset_i];
1870
1871 // Swap
1872 M[offset_i] = (
1873 (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
1874 (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
1875 );
1876 }
1877
1878 // Working variables
1879 var al, bl, cl, dl, el;
1880 var ar, br, cr, dr, er;
1881
1882 ar = al = H[0];
1883 br = bl = H[1];
1884 cr = cl = H[2];
1885 dr = dl = H[3];
1886 er = el = H[4];
1887 // Computation
1888 var t;
1889 for (var i = 0; i < 80; i += 1) {
1890 t = (al + M[offset+zl[i]])|0;
1891 if (i<16){
1892 t += f1(bl,cl,dl) + hl[0];
1893 } else if (i<32) {
1894 t += f2(bl,cl,dl) + hl[1];
1895 } else if (i<48) {
1896 t += f3(bl,cl,dl) + hl[2];
1897 } else if (i<64) {
1898 t += f4(bl,cl,dl) + hl[3];
1899 } else {// if (i<80) {
1900 t += f5(bl,cl,dl) + hl[4];
1901 }
1902 t = t|0;
1903 t = rotl(t,sl[i]);
1904 t = (t+el)|0;
1905 al = el;
1906 el = dl;
1907 dl = rotl(cl, 10);
1908 cl = bl;
1909 bl = t;
1910
1911 t = (ar + M[offset+zr[i]])|0;
1912 if (i<16){
1913 t += f5(br,cr,dr) + hr[0];
1914 } else if (i<32) {
1915 t += f4(br,cr,dr) + hr[1];
1916 } else if (i<48) {
1917 t += f3(br,cr,dr) + hr[2];
1918 } else if (i<64) {
1919 t += f2(br,cr,dr) + hr[3];
1920 } else {// if (i<80) {
1921 t += f1(br,cr,dr) + hr[4];
1922 }
1923 t = t|0;
1924 t = rotl(t,sr[i]) ;
1925 t = (t+er)|0;
1926 ar = er;
1927 er = dr;
1928 dr = rotl(cr, 10);
1929 cr = br;
1930 br = t;
1931 }
1932 // Intermediate hash value
1933 t = (H[1] + cl + dr)|0;
1934 H[1] = (H[2] + dl + er)|0;
1935 H[2] = (H[3] + el + ar)|0;
1936 H[3] = (H[4] + al + br)|0;
1937 H[4] = (H[0] + bl + cr)|0;
1938 H[0] = t;
1939};
1940
1941function f1(x, y, z) {
1942 return ((x) ^ (y) ^ (z));
1943}
1944
1945function f2(x, y, z) {
1946 return (((x)&(y)) | ((~x)&(z)));
1947}
1948
1949function f3(x, y, z) {
1950 return (((x) | (~(y))) ^ (z));
1951}
1952
1953function f4(x, y, z) {
1954 return (((x) & (z)) | ((y)&(~(z))));
1955}
1956
1957function f5(x, y, z) {
1958 return ((x) ^ ((y) |(~(z))));
1959}
1960
1961function rotl(x,n) {
1962 return (x<<n) | (x>>>(32-n));
1963}
1964
1965function ripemd160(message) {
1966 var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
1967
1968 if (typeof message == 'string')
1969 message = new Buffer(message, 'utf8');
1970
1971 var m = bytesToWords(message);
1972
1973 var nBitsLeft = message.length * 8;
1974 var nBitsTotal = message.length * 8;
1975
1976 // Add padding
1977 m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
1978 m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
1979 (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
1980 (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
1981 );
1982
1983 for (var i=0 ; i<m.length; i += 16) {
1984 processBlock(H, m, i);
1985 }
1986
1987 // Swap endian
1988 for (var i = 0; i < 5; i++) {
1989 // Shortcut
1990 var H_i = H[i];
1991
1992 // Swap
1993 H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
1994 (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
1995 }
1996
1997 var digestbytes = wordsToBytes(H);
1998 return new Buffer(digestbytes);
1999}
2000
2001
2002
2003}).call(this,require("buffer").Buffer)
2004},{"buffer":3}],15:[function(require,module,exports){
2005module.exports = function (Buffer) {
2006
2007 //prototype class for hash functions
2008 function Hash (blockSize, finalSize) {
2009 this._block = new Buffer(blockSize) //new Uint32Array(blockSize/4)
2010 this._finalSize = finalSize
2011 this._blockSize = blockSize
2012 this._len = 0
2013 this._s = 0
2014 }
2015
2016 Hash.prototype.init = function () {
2017 this._s = 0
2018 this._len = 0
2019 }
2020
2021 Hash.prototype.update = function (data, enc) {
2022 if ("string" === typeof data) {
2023 enc = enc || "utf8"
2024 data = new Buffer(data, enc)
2025 }
2026
2027 var l = this._len += data.length
2028 var s = this._s = (this._s || 0)
2029 var f = 0
2030 var buffer = this._block
2031
2032 while (s < l) {
2033 var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
2034 var ch = (t - f)
2035
2036 for (var i = 0; i < ch; i++) {
2037 buffer[(s % this._blockSize) + i] = data[i + f]
2038 }
2039
2040 s += ch
2041 f += ch
2042
2043 if ((s % this._blockSize) === 0) {
2044 this._update(buffer)
2045 }
2046 }
2047 this._s = s
2048
2049 return this
2050 }
2051
2052 Hash.prototype.digest = function (enc) {
2053 // Suppose the length of the message M, in bits, is l
2054 var l = this._len * 8
2055
2056 // Append the bit 1 to the end of the message
2057 this._block[this._len % this._blockSize] = 0x80
2058
2059 // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
2060 this._block.fill(0, this._len % this._blockSize + 1)
2061
2062 if (l % (this._blockSize * 8) >= this._finalSize * 8) {
2063 this._update(this._block)
2064 this._block.fill(0)
2065 }
2066
2067 // to this append the block which is equal to the number l written in binary
2068 // TODO: handle case where l is > Math.pow(2, 29)
2069 this._block.writeInt32BE(l, this._blockSize - 4)
2070
2071 var hash = this._update(this._block) || this._hash()
2072
2073 return enc ? hash.toString(enc) : hash
2074 }
2075
2076 Hash.prototype._update = function () {
2077 throw new Error('_update must be implemented by subclass')
2078 }
2079
2080 return Hash
2081}
2082
2083},{}],16:[function(require,module,exports){
2084var exports = module.exports = function (alg) {
2085 var Alg = exports[alg]
2086 if(!Alg) throw new Error(alg + ' is not supported (we accept pull requests)')
2087 return new Alg()
2088}
2089
2090var Buffer = require('buffer').Buffer
2091var Hash = require('./hash')(Buffer)
2092
2093exports.sha1 = require('./sha1')(Buffer, Hash)
2094exports.sha256 = require('./sha256')(Buffer, Hash)
2095exports.sha512 = require('./sha512')(Buffer, Hash)
2096
2097},{"./hash":15,"./sha1":17,"./sha256":18,"./sha512":19,"buffer":3}],17:[function(require,module,exports){
2098/*
2099 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
2100 * in FIPS PUB 180-1
2101 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
2102 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
2103 * Distributed under the BSD License
2104 * See http://pajhome.org.uk/crypt/md5 for details.
2105 */
2106
2107var inherits = require('util').inherits
2108
2109module.exports = function (Buffer, Hash) {
2110
2111 var A = 0|0
2112 var B = 4|0
2113 var C = 8|0
2114 var D = 12|0
2115 var E = 16|0
2116
2117 var W = new (typeof Int32Array === 'undefined' ? Array : Int32Array)(80)
2118
2119 var POOL = []
2120
2121 function Sha1 () {
2122 if(POOL.length)
2123 return POOL.pop().init()
2124
2125 if(!(this instanceof Sha1)) return new Sha1()
2126 this._w = W
2127 Hash.call(this, 16*4, 14*4)
2128
2129 this._h = null
2130 this.init()
2131 }
2132
2133 inherits(Sha1, Hash)
2134
2135 Sha1.prototype.init = function () {
2136 this._a = 0x67452301
2137 this._b = 0xefcdab89
2138 this._c = 0x98badcfe
2139 this._d = 0x10325476
2140 this._e = 0xc3d2e1f0
2141
2142 Hash.prototype.init.call(this)
2143 return this
2144 }
2145
2146 Sha1.prototype._POOL = POOL
2147 Sha1.prototype._update = function (X) {
2148
2149 var a, b, c, d, e, _a, _b, _c, _d, _e
2150
2151 a = _a = this._a
2152 b = _b = this._b
2153 c = _c = this._c
2154 d = _d = this._d
2155 e = _e = this._e
2156
2157 var w = this._w
2158
2159 for(var j = 0; j < 80; j++) {
2160 var W = w[j] = j < 16 ? X.readInt32BE(j*4)
2161 : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1)
2162
2163 var t = add(
2164 add(rol(a, 5), sha1_ft(j, b, c, d)),
2165 add(add(e, W), sha1_kt(j))
2166 )
2167
2168 e = d
2169 d = c
2170 c = rol(b, 30)
2171 b = a
2172 a = t
2173 }
2174
2175 this._a = add(a, _a)
2176 this._b = add(b, _b)
2177 this._c = add(c, _c)
2178 this._d = add(d, _d)
2179 this._e = add(e, _e)
2180 }
2181
2182 Sha1.prototype._hash = function () {
2183 if(POOL.length < 100) POOL.push(this)
2184 var H = new Buffer(20)
2185 //console.log(this._a|0, this._b|0, this._c|0, this._d|0, this._e|0)
2186 H.writeInt32BE(this._a|0, A)
2187 H.writeInt32BE(this._b|0, B)
2188 H.writeInt32BE(this._c|0, C)
2189 H.writeInt32BE(this._d|0, D)
2190 H.writeInt32BE(this._e|0, E)
2191 return H
2192 }
2193
2194 /*
2195 * Perform the appropriate triplet combination function for the current
2196 * iteration
2197 */
2198 function sha1_ft(t, b, c, d) {
2199 if(t < 20) return (b & c) | ((~b) & d);
2200 if(t < 40) return b ^ c ^ d;
2201 if(t < 60) return (b & c) | (b & d) | (c & d);
2202 return b ^ c ^ d;
2203 }
2204
2205 /*
2206 * Determine the appropriate additive constant for the current iteration
2207 */
2208 function sha1_kt(t) {
2209 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
2210 (t < 60) ? -1894007588 : -899497514;
2211 }
2212
2213 /*
2214 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
2215 * to work around bugs in some JS interpreters.
2216 * //dominictarr: this is 10 years old, so maybe this can be dropped?)
2217 *
2218 */
2219 function add(x, y) {
2220 return (x + y ) | 0
2221 //lets see how this goes on testling.
2222 // var lsw = (x & 0xFFFF) + (y & 0xFFFF);
2223 // var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
2224 // return (msw << 16) | (lsw & 0xFFFF);
2225 }
2226
2227 /*
2228 * Bitwise rotate a 32-bit number to the left.
2229 */
2230 function rol(num, cnt) {
2231 return (num << cnt) | (num >>> (32 - cnt));
2232 }
2233
2234 return Sha1
2235}
2236
2237},{"util":51}],18:[function(require,module,exports){
2238
2239/**
2240 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
2241 * in FIPS 180-2
2242 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
2243 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
2244 *
2245 */
2246
2247var inherits = require('util').inherits
2248
2249module.exports = function (Buffer, Hash) {
2250
2251 var K = [
2252 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
2253 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
2254 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
2255 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
2256 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
2257 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
2258 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
2259 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
2260 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
2261 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
2262 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
2263 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
2264 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
2265 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
2266 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
2267 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
2268 ]
2269
2270 var W = new Array(64)
2271
2272 function Sha256() {
2273 this.init()
2274
2275 this._w = W //new Array(64)
2276
2277 Hash.call(this, 16*4, 14*4)
2278 }
2279
2280 inherits(Sha256, Hash)
2281
2282 Sha256.prototype.init = function () {
2283
2284 this._a = 0x6a09e667|0
2285 this._b = 0xbb67ae85|0
2286 this._c = 0x3c6ef372|0
2287 this._d = 0xa54ff53a|0
2288 this._e = 0x510e527f|0
2289 this._f = 0x9b05688c|0
2290 this._g = 0x1f83d9ab|0
2291 this._h = 0x5be0cd19|0
2292
2293 this._len = this._s = 0
2294
2295 return this
2296 }
2297
2298 function S (X, n) {
2299 return (X >>> n) | (X << (32 - n));
2300 }
2301
2302 function R (X, n) {
2303 return (X >>> n);
2304 }
2305
2306 function Ch (x, y, z) {
2307 return ((x & y) ^ ((~x) & z));
2308 }
2309
2310 function Maj (x, y, z) {
2311 return ((x & y) ^ (x & z) ^ (y & z));
2312 }
2313
2314 function Sigma0256 (x) {
2315 return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
2316 }
2317
2318 function Sigma1256 (x) {
2319 return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
2320 }
2321
2322 function Gamma0256 (x) {
2323 return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
2324 }
2325
2326 function Gamma1256 (x) {
2327 return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
2328 }
2329
2330 Sha256.prototype._update = function(M) {
2331
2332 var W = this._w
2333 var a, b, c, d, e, f, g, h
2334 var T1, T2
2335
2336 a = this._a | 0
2337 b = this._b | 0
2338 c = this._c | 0
2339 d = this._d | 0
2340 e = this._e | 0
2341 f = this._f | 0
2342 g = this._g | 0
2343 h = this._h | 0
2344
2345 for (var j = 0; j < 64; j++) {
2346 var w = W[j] = j < 16
2347 ? M.readInt32BE(j * 4)
2348 : Gamma1256(W[j - 2]) + W[j - 7] + Gamma0256(W[j - 15]) + W[j - 16]
2349
2350 T1 = h + Sigma1256(e) + Ch(e, f, g) + K[j] + w
2351
2352 T2 = Sigma0256(a) + Maj(a, b, c);
2353 h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2;
2354 }
2355
2356 this._a = (a + this._a) | 0
2357 this._b = (b + this._b) | 0
2358 this._c = (c + this._c) | 0
2359 this._d = (d + this._d) | 0
2360 this._e = (e + this._e) | 0
2361 this._f = (f + this._f) | 0
2362 this._g = (g + this._g) | 0
2363 this._h = (h + this._h) | 0
2364
2365 };
2366
2367 Sha256.prototype._hash = function () {
2368 var H = new Buffer(32)
2369
2370 H.writeInt32BE(this._a, 0)
2371 H.writeInt32BE(this._b, 4)
2372 H.writeInt32BE(this._c, 8)
2373 H.writeInt32BE(this._d, 12)
2374 H.writeInt32BE(this._e, 16)
2375 H.writeInt32BE(this._f, 20)
2376 H.writeInt32BE(this._g, 24)
2377 H.writeInt32BE(this._h, 28)
2378
2379 return H
2380 }
2381
2382 return Sha256
2383
2384}
2385
2386},{"util":51}],19:[function(require,module,exports){
2387var inherits = require('util').inherits
2388
2389module.exports = function (Buffer, Hash) {
2390 var K = [
2391 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
2392 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
2393 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
2394 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
2395 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
2396 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
2397 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
2398 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
2399 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
2400 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
2401 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
2402 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
2403 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
2404 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
2405 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
2406 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
2407 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
2408 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
2409 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
2410 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
2411 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
2412 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
2413 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
2414 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
2415 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
2416 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
2417 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
2418 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
2419 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
2420 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
2421 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
2422 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
2423 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
2424 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
2425 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
2426 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
2427 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
2428 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
2429 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
2430 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
2431 ]
2432
2433 var W = new Array(160)
2434
2435 function Sha512() {
2436 this.init()
2437 this._w = W
2438
2439 Hash.call(this, 128, 112)
2440 }
2441
2442 inherits(Sha512, Hash)
2443
2444 Sha512.prototype.init = function () {
2445
2446 this._a = 0x6a09e667|0
2447 this._b = 0xbb67ae85|0
2448 this._c = 0x3c6ef372|0
2449 this._d = 0xa54ff53a|0
2450 this._e = 0x510e527f|0
2451 this._f = 0x9b05688c|0
2452 this._g = 0x1f83d9ab|0
2453 this._h = 0x5be0cd19|0
2454
2455 this._al = 0xf3bcc908|0
2456 this._bl = 0x84caa73b|0
2457 this._cl = 0xfe94f82b|0
2458 this._dl = 0x5f1d36f1|0
2459 this._el = 0xade682d1|0
2460 this._fl = 0x2b3e6c1f|0
2461 this._gl = 0xfb41bd6b|0
2462 this._hl = 0x137e2179|0
2463
2464 this._len = this._s = 0
2465
2466 return this
2467 }
2468
2469 function S (X, Xl, n) {
2470 return (X >>> n) | (Xl << (32 - n))
2471 }
2472
2473 function Ch (x, y, z) {
2474 return ((x & y) ^ ((~x) & z));
2475 }
2476
2477 function Maj (x, y, z) {
2478 return ((x & y) ^ (x & z) ^ (y & z));
2479 }
2480
2481 Sha512.prototype._update = function(M) {
2482
2483 var W = this._w
2484 var a, b, c, d, e, f, g, h
2485 var al, bl, cl, dl, el, fl, gl, hl
2486
2487 a = this._a | 0
2488 b = this._b | 0
2489 c = this._c | 0
2490 d = this._d | 0
2491 e = this._e | 0
2492 f = this._f | 0
2493 g = this._g | 0
2494 h = this._h | 0
2495
2496 al = this._al | 0
2497 bl = this._bl | 0
2498 cl = this._cl | 0
2499 dl = this._dl | 0
2500 el = this._el | 0
2501 fl = this._fl | 0
2502 gl = this._gl | 0
2503 hl = this._hl | 0
2504
2505 for (var i = 0; i < 80; i++) {
2506 var j = i * 2
2507
2508 var Wi, Wil
2509
2510 if (i < 16) {
2511 Wi = W[j] = M.readInt32BE(j * 4)
2512 Wil = W[j + 1] = M.readInt32BE(j * 4 + 4)
2513
2514 } else {
2515 var x = W[j - 15*2]
2516 var xl = W[j - 15*2 + 1]
2517 var gamma0 = S(x, xl, 1) ^ S(x, xl, 8) ^ (x >>> 7)
2518 var gamma0l = S(xl, x, 1) ^ S(xl, x, 8) ^ S(xl, x, 7)
2519
2520 x = W[j - 2*2]
2521 xl = W[j - 2*2 + 1]
2522 var gamma1 = S(x, xl, 19) ^ S(xl, x, 29) ^ (x >>> 6)
2523 var gamma1l = S(xl, x, 19) ^ S(x, xl, 29) ^ S(xl, x, 6)
2524
2525 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
2526 var Wi7 = W[j - 7*2]
2527 var Wi7l = W[j - 7*2 + 1]
2528
2529 var Wi16 = W[j - 16*2]
2530 var Wi16l = W[j - 16*2 + 1]
2531
2532 Wil = gamma0l + Wi7l
2533 Wi = gamma0 + Wi7 + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0)
2534 Wil = Wil + gamma1l
2535 Wi = Wi + gamma1 + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0)
2536 Wil = Wil + Wi16l
2537 Wi = Wi + Wi16 + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0)
2538
2539 W[j] = Wi
2540 W[j + 1] = Wil
2541 }
2542
2543 var maj = Maj(a, b, c)
2544 var majl = Maj(al, bl, cl)
2545
2546 var sigma0h = S(a, al, 28) ^ S(al, a, 2) ^ S(al, a, 7)
2547 var sigma0l = S(al, a, 28) ^ S(a, al, 2) ^ S(a, al, 7)
2548 var sigma1h = S(e, el, 14) ^ S(e, el, 18) ^ S(el, e, 9)
2549 var sigma1l = S(el, e, 14) ^ S(el, e, 18) ^ S(e, el, 9)
2550
2551 // t1 = h + sigma1 + ch + K[i] + W[i]
2552 var Ki = K[j]
2553 var Kil = K[j + 1]
2554
2555 var ch = Ch(e, f, g)
2556 var chl = Ch(el, fl, gl)
2557
2558 var t1l = hl + sigma1l
2559 var t1 = h + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0)
2560 t1l = t1l + chl
2561 t1 = t1 + ch + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0)
2562 t1l = t1l + Kil
2563 t1 = t1 + Ki + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0)
2564 t1l = t1l + Wil
2565 t1 = t1 + Wi + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0)
2566
2567 // t2 = sigma0 + maj
2568 var t2l = sigma0l + majl
2569 var t2 = sigma0h + maj + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0)
2570
2571 h = g
2572 hl = gl
2573 g = f
2574 gl = fl
2575 f = e
2576 fl = el
2577 el = (dl + t1l) | 0
2578 e = (d + t1 + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
2579 d = c
2580 dl = cl
2581 c = b
2582 cl = bl
2583 b = a
2584 bl = al
2585 al = (t1l + t2l) | 0
2586 a = (t1 + t2 + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0
2587 }
2588
2589 this._al = (this._al + al) | 0
2590 this._bl = (this._bl + bl) | 0
2591 this._cl = (this._cl + cl) | 0
2592 this._dl = (this._dl + dl) | 0
2593 this._el = (this._el + el) | 0
2594 this._fl = (this._fl + fl) | 0
2595 this._gl = (this._gl + gl) | 0
2596 this._hl = (this._hl + hl) | 0
2597
2598 this._a = (this._a + a + ((this._al >>> 0) < (al >>> 0) ? 1 : 0)) | 0
2599 this._b = (this._b + b + ((this._bl >>> 0) < (bl >>> 0) ? 1 : 0)) | 0
2600 this._c = (this._c + c + ((this._cl >>> 0) < (cl >>> 0) ? 1 : 0)) | 0
2601 this._d = (this._d + d + ((this._dl >>> 0) < (dl >>> 0) ? 1 : 0)) | 0
2602 this._e = (this._e + e + ((this._el >>> 0) < (el >>> 0) ? 1 : 0)) | 0
2603 this._f = (this._f + f + ((this._fl >>> 0) < (fl >>> 0) ? 1 : 0)) | 0
2604 this._g = (this._g + g + ((this._gl >>> 0) < (gl >>> 0) ? 1 : 0)) | 0
2605 this._h = (this._h + h + ((this._hl >>> 0) < (hl >>> 0) ? 1 : 0)) | 0
2606 }
2607
2608 Sha512.prototype._hash = function () {
2609 var H = new Buffer(64)
2610
2611 function writeInt64BE(h, l, offset) {
2612 H.writeInt32BE(h, offset)
2613 H.writeInt32BE(l, offset + 4)
2614 }
2615
2616 writeInt64BE(this._a, this._al, 0)
2617 writeInt64BE(this._b, this._bl, 8)
2618 writeInt64BE(this._c, this._cl, 16)
2619 writeInt64BE(this._d, this._dl, 24)
2620 writeInt64BE(this._e, this._el, 32)
2621 writeInt64BE(this._f, this._fl, 40)
2622 writeInt64BE(this._g, this._gl, 48)
2623 writeInt64BE(this._h, this._hl, 56)
2624
2625 return H
2626 }
2627
2628 return Sha512
2629
2630}
2631
2632},{"util":51}],20:[function(require,module,exports){
2633var pbkdf2Export = require('pbkdf2-compat').__pbkdf2Export
2634
2635module.exports = function (crypto, exports) {
2636 exports = exports || {}
2637
2638 var exported = pbkdf2Export(crypto)
2639
2640 exports.pbkdf2 = exported.pbkdf2
2641 exports.pbkdf2Sync = exported.pbkdf2Sync
2642
2643 return exports
2644}
2645
2646},{"pbkdf2-compat":12}],21:[function(require,module,exports){
2647(function (global,Buffer){
2648(function() {
2649 var g = ('undefined' === typeof window ? global : window) || {}
2650 var foolBrowserify = require
2651 _crypto = (
2652 g.crypto || g.msCrypto || foolBrowserify('crypto')
2653 )
2654 module.exports = function(size) {
2655 // Modern Browsers
2656 if(_crypto.getRandomValues) {
2657 var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
2658 /* This will not work in older browsers.
2659 * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
2660 */
2661
2662 _crypto.getRandomValues(bytes);
2663 return bytes;
2664 }
2665 else if (_crypto.randomBytes) {
2666 return _crypto.randomBytes(size)
2667 }
2668 else
2669 throw new Error(
2670 'secure random number generation not supported by this browser\n'+
2671 'use chrome, FireFox or Internet Explorer 11'
2672 )
2673 }
2674}())
2675
2676}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
2677},{"buffer":3}],22:[function(require,module,exports){
2678// Copyright Joyent, Inc. and other Node contributors.
2679//
2680// Permission is hereby granted, free of charge, to any person obtaining a
2681// copy of this software and associated documentation files (the
2682// "Software"), to deal in the Software without restriction, including
2683// without limitation the rights to use, copy, modify, merge, publish,
2684// distribute, sublicense, and/or sell copies of the Software, and to permit
2685// persons to whom the Software is furnished to do so, subject to the
2686// following conditions:
2687//
2688// The above copyright notice and this permission notice shall be included
2689// in all copies or substantial portions of the Software.
2690//
2691// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2692// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2693// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2694// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2695// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2696// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2697// USE OR OTHER DEALINGS IN THE SOFTWARE.
2698
2699function EventEmitter() {
2700 this._events = this._events || {};
2701 this._maxListeners = this._maxListeners || undefined;
2702}
2703module.exports = EventEmitter;
2704
2705// Backwards-compat with node 0.10.x
2706EventEmitter.EventEmitter = EventEmitter;
2707
2708EventEmitter.prototype._events = undefined;
2709EventEmitter.prototype._maxListeners = undefined;
2710
2711// By default EventEmitters will print a warning if more than 10 listeners are
2712// added to it. This is a useful default which helps finding memory leaks.
2713EventEmitter.defaultMaxListeners = 10;
2714
2715// Obviously not all Emitters should be limited to 10. This function allows
2716// that to be increased. Set to zero for unlimited.
2717EventEmitter.prototype.setMaxListeners = function(n) {
2718 if (!isNumber(n) || n < 0 || isNaN(n))
2719 throw TypeError('n must be a positive number');
2720 this._maxListeners = n;
2721 return this;
2722};
2723
2724EventEmitter.prototype.emit = function(type) {
2725 var er, handler, len, args, i, listeners;
2726
2727 if (!this._events)
2728 this._events = {};
2729
2730 // If there is no 'error' event listener then throw.
2731 if (type === 'error') {
2732 if (!this._events.error ||
2733 (isObject(this._events.error) && !this._events.error.length)) {
2734 er = arguments[1];
2735 if (er instanceof Error) {
2736 throw er; // Unhandled 'error' event
2737 }
2738 throw TypeError('Uncaught, unspecified "error" event.');
2739 }
2740 }
2741
2742 handler = this._events[type];
2743
2744 if (isUndefined(handler))
2745 return false;
2746
2747 if (isFunction(handler)) {
2748 switch (arguments.length) {
2749 // fast cases
2750 case 1:
2751 handler.call(this);
2752 break;
2753 case 2:
2754 handler.call(this, arguments[1]);
2755 break;
2756 case 3:
2757 handler.call(this, arguments[1], arguments[2]);
2758 break;
2759 // slower
2760 default:
2761 len = arguments.length;
2762 args = new Array(len - 1);
2763 for (i = 1; i < len; i++)
2764 args[i - 1] = arguments[i];
2765 handler.apply(this, args);
2766 }
2767 } else if (isObject(handler)) {
2768 len = arguments.length;
2769 args = new Array(len - 1);
2770 for (i = 1; i < len; i++)
2771 args[i - 1] = arguments[i];
2772
2773 listeners = handler.slice();
2774 len = listeners.length;
2775 for (i = 0; i < len; i++)
2776 listeners[i].apply(this, args);
2777 }
2778
2779 return true;
2780};
2781
2782EventEmitter.prototype.addListener = function(type, listener) {
2783 var m;
2784
2785 if (!isFunction(listener))
2786 throw TypeError('listener must be a function');
2787
2788 if (!this._events)
2789 this._events = {};
2790
2791 // To avoid recursion in the case that type === "newListener"! Before
2792 // adding it to the listeners, first emit "newListener".
2793 if (this._events.newListener)
2794 this.emit('newListener', type,
2795 isFunction(listener.listener) ?
2796 listener.listener : listener);
2797
2798 if (!this._events[type])
2799 // Optimize the case of one listener. Don't need the extra array object.
2800 this._events[type] = listener;
2801 else if (isObject(this._events[type]))
2802 // If we've already got an array, just append.
2803 this._events[type].push(listener);
2804 else
2805 // Adding the second element, need to change to array.
2806 this._events[type] = [this._events[type], listener];
2807
2808 // Check for listener leak
2809 if (isObject(this._events[type]) && !this._events[type].warned) {
2810 var m;
2811 if (!isUndefined(this._maxListeners)) {
2812 m = this._maxListeners;
2813 } else {
2814 m = EventEmitter.defaultMaxListeners;
2815 }
2816
2817 if (m && m > 0 && this._events[type].length > m) {
2818 this._events[type].warned = true;
2819 console.error('(node) warning: possible EventEmitter memory ' +
2820 'leak detected. %d listeners added. ' +
2821 'Use emitter.setMaxListeners() to increase limit.',
2822 this._events[type].length);
2823 if (typeof console.trace === 'function') {
2824 // not supported in IE 10
2825 console.trace();
2826 }
2827 }
2828 }
2829
2830 return this;
2831};
2832
2833EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2834
2835EventEmitter.prototype.once = function(type, listener) {
2836 if (!isFunction(listener))
2837 throw TypeError('listener must be a function');
2838
2839 var fired = false;
2840
2841 function g() {
2842 this.removeListener(type, g);
2843
2844 if (!fired) {
2845 fired = true;
2846 listener.apply(this, arguments);
2847 }
2848 }
2849
2850 g.listener = listener;
2851 this.on(type, g);
2852
2853 return this;
2854};
2855
2856// emits a 'removeListener' event iff the listener was removed
2857EventEmitter.prototype.removeListener = function(type, listener) {
2858 var list, position, length, i;
2859
2860 if (!isFunction(listener))
2861 throw TypeError('listener must be a function');
2862
2863 if (!this._events || !this._events[type])
2864 return this;
2865
2866 list = this._events[type];
2867 length = list.length;
2868 position = -1;
2869
2870 if (list === listener ||
2871 (isFunction(list.listener) && list.listener === listener)) {
2872 delete this._events[type];
2873 if (this._events.removeListener)
2874 this.emit('removeListener', type, listener);
2875
2876 } else if (isObject(list)) {
2877 for (i = length; i-- > 0;) {
2878 if (list[i] === listener ||
2879 (list[i].listener && list[i].listener === listener)) {
2880 position = i;
2881 break;
2882 }
2883 }
2884
2885 if (position < 0)
2886 return this;
2887
2888 if (list.length === 1) {
2889 list.length = 0;
2890 delete this._events[type];
2891 } else {
2892 list.splice(position, 1);
2893 }
2894
2895 if (this._events.removeListener)
2896 this.emit('removeListener', type, listener);
2897 }
2898
2899 return this;
2900};
2901
2902EventEmitter.prototype.removeAllListeners = function(type) {
2903 var key, listeners;
2904
2905 if (!this._events)
2906 return this;
2907
2908 // not listening for removeListener, no need to emit
2909 if (!this._events.removeListener) {
2910 if (arguments.length === 0)
2911 this._events = {};
2912 else if (this._events[type])
2913 delete this._events[type];
2914 return this;
2915 }
2916
2917 // emit removeListener for all listeners on all events
2918 if (arguments.length === 0) {
2919 for (key in this._events) {
2920 if (key === 'removeListener') continue;
2921 this.removeAllListeners(key);
2922 }
2923 this.removeAllListeners('removeListener');
2924 this._events = {};
2925 return this;
2926 }
2927
2928 listeners = this._events[type];
2929
2930 if (isFunction(listeners)) {
2931 this.removeListener(type, listeners);
2932 } else {
2933 // LIFO order
2934 while (listeners.length)
2935 this.removeListener(type, listeners[listeners.length - 1]);
2936 }
2937 delete this._events[type];
2938
2939 return this;
2940};
2941
2942EventEmitter.prototype.listeners = function(type) {
2943 var ret;
2944 if (!this._events || !this._events[type])
2945 ret = [];
2946 else if (isFunction(this._events[type]))
2947 ret = [this._events[type]];
2948 else
2949 ret = this._events[type].slice();
2950 return ret;
2951};
2952
2953EventEmitter.listenerCount = function(emitter, type) {
2954 var ret;
2955 if (!emitter._events || !emitter._events[type])
2956 ret = 0;
2957 else if (isFunction(emitter._events[type]))
2958 ret = 1;
2959 else
2960 ret = emitter._events[type].length;
2961 return ret;
2962};
2963
2964function isFunction(arg) {
2965 return typeof arg === 'function';
2966}
2967
2968function isNumber(arg) {
2969 return typeof arg === 'number';
2970}
2971
2972function isObject(arg) {
2973 return typeof arg === 'object' && arg !== null;
2974}
2975
2976function isUndefined(arg) {
2977 return arg === void 0;
2978}
2979
2980},{}],23:[function(require,module,exports){
2981var http = module.exports;
2982var EventEmitter = require('events').EventEmitter;
2983var Request = require('./lib/request');
2984var url = require('url')
2985
2986http.request = function (params, cb) {
2987 if (typeof params === 'string') {
2988 params = url.parse(params)
2989 }
2990 if (!params) params = {};
2991 if (!params.host && !params.port) {
2992 params.port = parseInt(window.location.port, 10);
2993 }
2994 if (!params.host && params.hostname) {
2995 params.host = params.hostname;
2996 }
2997
2998 if (!params.protocol) {
2999 if (params.scheme) {
3000 params.protocol = params.scheme + ':';
3001 } else {
3002 params.protocol = window.location.protocol;
3003 }
3004 }
3005
3006 if (!params.host) {
3007 params.host = window.location.hostname || window.location.host;
3008 }
3009 if (/:/.test(params.host)) {
3010 if (!params.port) {
3011 params.port = params.host.split(':')[1];
3012 }
3013 params.host = params.host.split(':')[0];
3014 }
3015 if (!params.port) params.port = params.protocol == 'https:' ? 443 : 80;
3016
3017 var req = new Request(new xhrHttp, params);
3018 if (cb) req.on('response', cb);
3019 return req;
3020};
3021
3022http.get = function (params, cb) {
3023 params.method = 'GET';
3024 var req = http.request(params, cb);
3025 req.end();
3026 return req;
3027};
3028
3029http.Agent = function () {};
3030http.Agent.defaultMaxSockets = 4;
3031
3032var xhrHttp = (function () {
3033 if (typeof window === 'undefined') {
3034 throw new Error('no window object present');
3035 }
3036 else if (window.XMLHttpRequest) {
3037 return window.XMLHttpRequest;
3038 }
3039 else if (window.ActiveXObject) {
3040 var axs = [
3041 'Msxml2.XMLHTTP.6.0',
3042 'Msxml2.XMLHTTP.3.0',
3043 'Microsoft.XMLHTTP'
3044 ];
3045 for (var i = 0; i < axs.length; i++) {
3046 try {
3047 var ax = new(window.ActiveXObject)(axs[i]);
3048 return function () {
3049 if (ax) {
3050 var ax_ = ax;
3051 ax = null;
3052 return ax_;
3053 }
3054 else {
3055 return new(window.ActiveXObject)(axs[i]);
3056 }
3057 };
3058 }
3059 catch (e) {}
3060 }
3061 throw new Error('ajax not supported in this browser')
3062 }
3063 else {
3064 throw new Error('ajax not supported in this browser');
3065 }
3066})();
3067
3068http.STATUS_CODES = {
3069 100 : 'Continue',
3070 101 : 'Switching Protocols',
3071 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918
3072 200 : 'OK',
3073 201 : 'Created',
3074 202 : 'Accepted',
3075 203 : 'Non-Authoritative Information',
3076 204 : 'No Content',
3077 205 : 'Reset Content',
3078 206 : 'Partial Content',
3079 207 : 'Multi-Status', // RFC 4918
3080 300 : 'Multiple Choices',
3081 301 : 'Moved Permanently',
3082 302 : 'Moved Temporarily',
3083 303 : 'See Other',
3084 304 : 'Not Modified',
3085 305 : 'Use Proxy',
3086 307 : 'Temporary Redirect',
3087 400 : 'Bad Request',
3088 401 : 'Unauthorized',
3089 402 : 'Payment Required',
3090 403 : 'Forbidden',
3091 404 : 'Not Found',
3092 405 : 'Method Not Allowed',
3093 406 : 'Not Acceptable',
3094 407 : 'Proxy Authentication Required',
3095 408 : 'Request Time-out',
3096 409 : 'Conflict',
3097 410 : 'Gone',
3098 411 : 'Length Required',
3099 412 : 'Precondition Failed',
3100 413 : 'Request Entity Too Large',
3101 414 : 'Request-URI Too Large',
3102 415 : 'Unsupported Media Type',
3103 416 : 'Requested Range Not Satisfiable',
3104 417 : 'Expectation Failed',
3105 418 : 'I\'m a teapot', // RFC 2324
3106 422 : 'Unprocessable Entity', // RFC 4918
3107 423 : 'Locked', // RFC 4918
3108 424 : 'Failed Dependency', // RFC 4918
3109 425 : 'Unordered Collection', // RFC 4918
3110 426 : 'Upgrade Required', // RFC 2817
3111 428 : 'Precondition Required', // RFC 6585
3112 429 : 'Too Many Requests', // RFC 6585
3113 431 : 'Request Header Fields Too Large',// RFC 6585
3114 500 : 'Internal Server Error',
3115 501 : 'Not Implemented',
3116 502 : 'Bad Gateway',
3117 503 : 'Service Unavailable',
3118 504 : 'Gateway Time-out',
3119 505 : 'HTTP Version Not Supported',
3120 506 : 'Variant Also Negotiates', // RFC 2295
3121 507 : 'Insufficient Storage', // RFC 4918
3122 509 : 'Bandwidth Limit Exceeded',
3123 510 : 'Not Extended', // RFC 2774
3124 511 : 'Network Authentication Required' // RFC 6585
3125};
3126},{"./lib/request":24,"events":22,"url":49}],24:[function(require,module,exports){
3127var Stream = require('stream');
3128var Response = require('./response');
3129var Base64 = require('Base64');
3130var inherits = require('inherits');
3131
3132var Request = module.exports = function (xhr, params) {
3133 var self = this;
3134 self.writable = true;
3135 self.xhr = xhr;
3136 self.body = [];
3137
3138 self.uri = (params.protocol || 'http:') + '//'
3139 + params.host
3140 + (params.port ? ':' + params.port : '')
3141 + (params.path || '/')
3142 ;
3143
3144 if (typeof params.withCredentials === 'undefined') {
3145 params.withCredentials = true;
3146 }
3147
3148 try { xhr.withCredentials = params.withCredentials }
3149 catch (e) {}
3150
3151 if (params.responseType) try { xhr.responseType = params.responseType }
3152 catch (e) {}
3153
3154 xhr.open(
3155 params.method || 'GET',
3156 self.uri,
3157 true
3158 );
3159
3160 xhr.onerror = function(event) {
3161 self.emit('error', new Error('Network error'));
3162 };
3163
3164 self._headers = {};
3165
3166 if (params.headers) {
3167 var keys = objectKeys(params.headers);
3168 for (var i = 0; i < keys.length; i++) {
3169 var key = keys[i];
3170 if (!self.isSafeRequestHeader(key)) continue;
3171 var value = params.headers[key];
3172 self.setHeader(key, value);
3173 }
3174 }
3175
3176 if (params.auth) {
3177 //basic auth
3178 this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth));
3179 }
3180
3181 var res = new Response;
3182 res.on('close', function () {
3183 self.emit('close');
3184 });
3185
3186 res.on('ready', function () {
3187 self.emit('response', res);
3188 });
3189
3190 res.on('error', function (err) {
3191 self.emit('error', err);
3192 });
3193
3194 xhr.onreadystatechange = function () {
3195 // Fix for IE9 bug
3196 // SCRIPT575: Could not complete the operation due to error c00c023f
3197 // It happens when a request is aborted, calling the success callback anyway with readyState === 4
3198 if (xhr.__aborted) return;
3199 res.handle(xhr);
3200 };
3201};
3202
3203inherits(Request, Stream);
3204
3205Request.prototype.setHeader = function (key, value) {
3206 this._headers[key.toLowerCase()] = value
3207};
3208
3209Request.prototype.getHeader = function (key) {
3210 return this._headers[key.toLowerCase()]
3211};
3212
3213Request.prototype.removeHeader = function (key) {
3214 delete this._headers[key.toLowerCase()]
3215};
3216
3217Request.prototype.write = function (s) {
3218 this.body.push(s);
3219};
3220
3221Request.prototype.destroy = function (s) {
3222 this.xhr.__aborted = true;
3223 this.xhr.abort();
3224 this.emit('close');
3225};
3226
3227Request.prototype.end = function (s) {
3228 if (s !== undefined) this.body.push(s);
3229
3230 var keys = objectKeys(this._headers);
3231 for (var i = 0; i < keys.length; i++) {
3232 var key = keys[i];
3233 var value = this._headers[key];
3234 if (isArray(value)) {
3235 for (var j = 0; j < value.length; j++) {
3236 this.xhr.setRequestHeader(key, value[j]);
3237 }
3238 }
3239 else this.xhr.setRequestHeader(key, value)
3240 }
3241
3242 if (this.body.length === 0) {
3243 this.xhr.send('');
3244 }
3245 else if (typeof this.body[0] === 'string') {
3246 this.xhr.send(this.body.join(''));
3247 }
3248 else if (isArray(this.body[0])) {
3249 var body = [];
3250 for (var i = 0; i < this.body.length; i++) {
3251 body.push.apply(body, this.body[i]);
3252 }
3253 this.xhr.send(body);
3254 }
3255 else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) {
3256 var len = 0;
3257 for (var i = 0; i < this.body.length; i++) {
3258 len += this.body[i].length;
3259 }
3260 var body = new(this.body[0].constructor)(len);
3261 var k = 0;
3262
3263 for (var i = 0; i < this.body.length; i++) {
3264 var b = this.body[i];
3265 for (var j = 0; j < b.length; j++) {
3266 body[k++] = b[j];
3267 }
3268 }
3269 this.xhr.send(body);
3270 }
3271 else if (isXHR2Compatible(this.body[0])) {
3272 this.xhr.send(this.body[0]);
3273 }
3274 else {
3275 var body = '';
3276 for (var i = 0; i < this.body.length; i++) {
3277 body += this.body[i].toString();
3278 }
3279 this.xhr.send(body);
3280 }
3281};
3282
3283// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html
3284Request.unsafeHeaders = [
3285 "accept-charset",
3286 "accept-encoding",
3287 "access-control-request-headers",
3288 "access-control-request-method",
3289 "connection",
3290 "content-length",
3291 "cookie",
3292 "cookie2",
3293 "content-transfer-encoding",
3294 "date",
3295 "expect",
3296 "host",
3297 "keep-alive",
3298 "origin",
3299 "referer",
3300 "te",
3301 "trailer",
3302 "transfer-encoding",
3303 "upgrade",
3304 "user-agent",
3305 "via"
3306];
3307
3308Request.prototype.isSafeRequestHeader = function (headerName) {
3309 if (!headerName) return false;
3310 return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1;
3311};
3312
3313var objectKeys = Object.keys || function (obj) {
3314 var keys = [];
3315 for (var key in obj) keys.push(key);
3316 return keys;
3317};
3318
3319var isArray = Array.isArray || function (xs) {
3320 return Object.prototype.toString.call(xs) === '[object Array]';
3321};
3322
3323var indexOf = function (xs, x) {
3324 if (xs.indexOf) return xs.indexOf(x);
3325 for (var i = 0; i < xs.length; i++) {
3326 if (xs[i] === x) return i;
3327 }
3328 return -1;
3329};
3330
3331var isXHR2Compatible = function (obj) {
3332 if (typeof Blob !== 'undefined' && obj instanceof Blob) return true;
3333 if (typeof ArrayBuffer !== 'undefined' && obj instanceof ArrayBuffer) return true;
3334 if (typeof FormData !== 'undefined' && obj instanceof FormData) return true;
3335};
3336
3337},{"./response":25,"Base64":26,"inherits":28,"stream":48}],25:[function(require,module,exports){
3338var Stream = require('stream');
3339var util = require('util');
3340
3341var Response = module.exports = function (res) {
3342 this.offset = 0;
3343 this.readable = true;
3344};
3345
3346util.inherits(Response, Stream);
3347
3348var capable = {
3349 streaming : true,
3350 status2 : true
3351};
3352
3353function parseHeaders (res) {
3354 var lines = res.getAllResponseHeaders().split(/\r?\n/);
3355 var headers = {};
3356 for (var i = 0; i < lines.length; i++) {
3357 var line = lines[i];
3358 if (line === '') continue;
3359
3360 var m = line.match(/^([^:]+):\s*(.*)/);
3361 if (m) {
3362 var key = m[1].toLowerCase(), value = m[2];
3363
3364 if (headers[key] !== undefined) {
3365
3366 if (isArray(headers[key])) {
3367 headers[key].push(value);
3368 }
3369 else {
3370 headers[key] = [ headers[key], value ];
3371 }
3372 }
3373 else {
3374 headers[key] = value;
3375 }
3376 }
3377 else {
3378 headers[line] = true;
3379 }
3380 }
3381 return headers;
3382}
3383
3384Response.prototype.getResponse = function (xhr) {
3385 var respType = String(xhr.responseType).toLowerCase();
3386 if (respType === 'blob') return xhr.responseBlob || xhr.response;
3387 if (respType === 'arraybuffer') return xhr.response;
3388 return xhr.responseText;
3389}
3390
3391Response.prototype.getHeader = function (key) {
3392 return this.headers[key.toLowerCase()];
3393};
3394
3395Response.prototype.handle = function (res) {
3396 if (res.readyState === 2 && capable.status2) {
3397 try {
3398 this.statusCode = res.status;
3399 this.headers = parseHeaders(res);
3400 }
3401 catch (err) {
3402 capable.status2 = false;
3403 }
3404
3405 if (capable.status2) {
3406 this.emit('ready');
3407 }
3408 }
3409 else if (capable.streaming && res.readyState === 3) {
3410 try {
3411 if (!this.statusCode) {
3412 this.statusCode = res.status;
3413 this.headers = parseHeaders(res);
3414 this.emit('ready');
3415 }
3416 }
3417 catch (err) {}
3418
3419 try {
3420 this._emitData(res);
3421 }
3422 catch (err) {
3423 capable.streaming = false;
3424 }
3425 }
3426 else if (res.readyState === 4) {
3427 if (!this.statusCode) {
3428 this.statusCode = res.status;
3429 this.emit('ready');
3430 }
3431 this._emitData(res);
3432
3433 if (res.error) {
3434 this.emit('error', this.getResponse(res));
3435 }
3436 else this.emit('end');
3437
3438 this.emit('close');
3439 }
3440};
3441
3442Response.prototype._emitData = function (res) {
3443 var respBody = this.getResponse(res);
3444 if (respBody.toString().match(/ArrayBuffer/)) {
3445 this.emit('data', new Uint8Array(respBody, this.offset));
3446 this.offset = respBody.byteLength;
3447 return;
3448 }
3449 if (respBody.length > this.offset) {
3450 this.emit('data', respBody.slice(this.offset));
3451 this.offset = respBody.length;
3452 }
3453};
3454
3455var isArray = Array.isArray || function (xs) {
3456 return Object.prototype.toString.call(xs) === '[object Array]';
3457};
3458
3459},{"stream":48,"util":51}],26:[function(require,module,exports){
3460;(function () {
3461
3462 var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
3463 var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
3464
3465 function InvalidCharacterError(message) {
3466 this.message = message;
3467 }
3468 InvalidCharacterError.prototype = new Error;
3469 InvalidCharacterError.prototype.name = 'InvalidCharacterError';
3470
3471 // encoder
3472 // [https://gist.github.com/999166] by [https://github.com/nignag]
3473 object.btoa || (
3474 object.btoa = function (input) {
3475 for (
3476 // initialize result and counter
3477 var block, charCode, idx = 0, map = chars, output = '';
3478 // if the next input index does not exist:
3479 // change the mapping table to "="
3480 // check if d has no fractional digits
3481 input.charAt(idx | 0) || (map = '=', idx % 1);
3482 // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
3483 output += map.charAt(63 & block >> 8 - idx % 1 * 8)
3484 ) {
3485 charCode = input.charCodeAt(idx += 3/4);
3486 if (charCode > 0xFF) {
3487 throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
3488 }
3489 block = block << 8 | charCode;
3490 }
3491 return output;
3492 });
3493
3494 // decoder
3495 // [https://gist.github.com/1020396] by [https://github.com/atk]
3496 object.atob || (
3497 object.atob = function (input) {
3498 input = input.replace(/=+$/, '');
3499 if (input.length % 4 == 1) {
3500 throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
3501 }
3502 for (
3503 // initialize result and counters
3504 var bc = 0, bs, buffer, idx = 0, output = '';
3505 // get next character
3506 buffer = input.charAt(idx++);
3507 // character found in table? initialize bit storage and add its ascii value;
3508 ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
3509 // and if not first of each 4 characters,
3510 // convert the first 8 bits to one ascii character
3511 bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
3512 ) {
3513 // try to find character in table (0-63, not found => -1)
3514 buffer = chars.indexOf(buffer);
3515 }
3516 return output;
3517 });
3518
3519}());
3520
3521},{}],27:[function(require,module,exports){
3522var http = require('http');
3523
3524var https = module.exports;
3525
3526for (var key in http) {
3527 if (http.hasOwnProperty(key)) https[key] = http[key];
3528};
3529
3530https.request = function (params, cb) {
3531 if (!params) params = {};
3532 params.scheme = 'https';
3533 return http.request.call(this, params, cb);
3534}
3535
3536},{"http":23}],28:[function(require,module,exports){
3537if (typeof Object.create === 'function') {
3538 // implementation from standard node.js 'util' module
3539 module.exports = function inherits(ctor, superCtor) {
3540 ctor.super_ = superCtor
3541 ctor.prototype = Object.create(superCtor.prototype, {
3542 constructor: {
3543 value: ctor,
3544 enumerable: false,
3545 writable: true,
3546 configurable: true
3547 }
3548 });
3549 };
3550} else {
3551 // old school shim for old browsers
3552 module.exports = function inherits(ctor, superCtor) {
3553 ctor.super_ = superCtor
3554 var TempCtor = function () {}
3555 TempCtor.prototype = superCtor.prototype
3556 ctor.prototype = new TempCtor()
3557 ctor.prototype.constructor = ctor
3558 }
3559}
3560
3561},{}],29:[function(require,module,exports){
3562module.exports = Array.isArray || function (arr) {
3563 return Object.prototype.toString.call(arr) == '[object Array]';
3564};
3565
3566},{}],30:[function(require,module,exports){
3567(function (process){
3568// Copyright Joyent, Inc. and other Node contributors.
3569//
3570// Permission is hereby granted, free of charge, to any person obtaining a
3571// copy of this software and associated documentation files (the
3572// "Software"), to deal in the Software without restriction, including
3573// without limitation the rights to use, copy, modify, merge, publish,
3574// distribute, sublicense, and/or sell copies of the Software, and to permit
3575// persons to whom the Software is furnished to do so, subject to the
3576// following conditions:
3577//
3578// The above copyright notice and this permission notice shall be included
3579// in all copies or substantial portions of the Software.
3580//
3581// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3582// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3583// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3584// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3585// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3586// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3587// USE OR OTHER DEALINGS IN THE SOFTWARE.
3588
3589// resolves . and .. elements in a path array with directory names there
3590// must be no slashes, empty elements, or device names (c:\) in the array
3591// (so also no leading and trailing slashes - it does not distinguish
3592// relative and absolute paths)
3593function normalizeArray(parts, allowAboveRoot) {
3594 // if the path tries to go above the root, `up` ends up > 0
3595 var up = 0;
3596 for (var i = parts.length - 1; i >= 0; i--) {
3597 var last = parts[i];
3598 if (last === '.') {
3599 parts.splice(i, 1);
3600 } else if (last === '..') {
3601 parts.splice(i, 1);
3602 up++;
3603 } else if (up) {
3604 parts.splice(i, 1);
3605 up--;
3606 }
3607 }
3608
3609 // if the path is allowed to go above the root, restore leading ..s
3610 if (allowAboveRoot) {
3611 for (; up--; up) {
3612 parts.unshift('..');
3613 }
3614 }
3615
3616 return parts;
3617}
3618
3619// Split a filename into [root, dir, basename, ext], unix version
3620// 'root' is just a slash, or nothing.
3621var splitPathRe =
3622 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3623var splitPath = function(filename) {
3624 return splitPathRe.exec(filename).slice(1);
3625};
3626
3627// path.resolve([from ...], to)
3628// posix version
3629exports.resolve = function() {
3630 var resolvedPath = '',
3631 resolvedAbsolute = false;
3632
3633 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3634 var path = (i >= 0) ? arguments[i] : process.cwd();
3635
3636 // Skip empty and invalid entries
3637 if (typeof path !== 'string') {
3638 throw new TypeError('Arguments to path.resolve must be strings');
3639 } else if (!path) {
3640 continue;
3641 }
3642
3643 resolvedPath = path + '/' + resolvedPath;
3644 resolvedAbsolute = path.charAt(0) === '/';
3645 }
3646
3647 // At this point the path should be resolved to a full absolute path, but
3648 // handle relative paths to be safe (might happen when process.cwd() fails)
3649
3650 // Normalize the path
3651 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3652 return !!p;
3653 }), !resolvedAbsolute).join('/');
3654
3655 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3656};
3657
3658// path.normalize(path)
3659// posix version
3660exports.normalize = function(path) {
3661 var isAbsolute = exports.isAbsolute(path),
3662 trailingSlash = substr(path, -1) === '/';
3663
3664 // Normalize the path
3665 path = normalizeArray(filter(path.split('/'), function(p) {
3666 return !!p;
3667 }), !isAbsolute).join('/');
3668
3669 if (!path && !isAbsolute) {
3670 path = '.';
3671 }
3672 if (path && trailingSlash) {
3673 path += '/';
3674 }
3675
3676 return (isAbsolute ? '/' : '') + path;
3677};
3678
3679// posix version
3680exports.isAbsolute = function(path) {
3681 return path.charAt(0) === '/';
3682};
3683
3684// posix version
3685exports.join = function() {
3686 var paths = Array.prototype.slice.call(arguments, 0);
3687 return exports.normalize(filter(paths, function(p, index) {
3688 if (typeof p !== 'string') {
3689 throw new TypeError('Arguments to path.join must be strings');
3690 }
3691 return p;
3692 }).join('/'));
3693};
3694
3695
3696// path.relative(from, to)
3697// posix version
3698exports.relative = function(from, to) {
3699 from = exports.resolve(from).substr(1);
3700 to = exports.resolve(to).substr(1);
3701
3702 function trim(arr) {
3703 var start = 0;
3704 for (; start < arr.length; start++) {
3705 if (arr[start] !== '') break;
3706 }
3707
3708 var end = arr.length - 1;
3709 for (; end >= 0; end--) {
3710 if (arr[end] !== '') break;
3711 }
3712
3713 if (start > end) return [];
3714 return arr.slice(start, end - start + 1);
3715 }
3716
3717 var fromParts = trim(from.split('/'));
3718 var toParts = trim(to.split('/'));
3719
3720 var length = Math.min(fromParts.length, toParts.length);
3721 var samePartsLength = length;
3722 for (var i = 0; i < length; i++) {
3723 if (fromParts[i] !== toParts[i]) {
3724 samePartsLength = i;
3725 break;
3726 }
3727 }
3728
3729 var outputParts = [];
3730 for (var i = samePartsLength; i < fromParts.length; i++) {
3731 outputParts.push('..');
3732 }
3733
3734 outputParts = outputParts.concat(toParts.slice(samePartsLength));
3735
3736 return outputParts.join('/');
3737};
3738
3739exports.sep = '/';
3740exports.delimiter = ':';
3741
3742exports.dirname = function(path) {
3743 var result = splitPath(path),
3744 root = result[0],
3745 dir = result[1];
3746
3747 if (!root && !dir) {
3748 // No dirname whatsoever
3749 return '.';
3750 }
3751
3752 if (dir) {
3753 // It has a dirname, strip trailing slash
3754 dir = dir.substr(0, dir.length - 1);
3755 }
3756
3757 return root + dir;
3758};
3759
3760
3761exports.basename = function(path, ext) {
3762 var f = splitPath(path)[2];
3763 // TODO: make this comparison case-insensitive on windows?
3764 if (ext && f.substr(-1 * ext.length) === ext) {
3765 f = f.substr(0, f.length - ext.length);
3766 }
3767 return f;
3768};
3769
3770
3771exports.extname = function(path) {
3772 return splitPath(path)[3];
3773};
3774
3775function filter (xs, f) {
3776 if (xs.filter) return xs.filter(f);
3777 var res = [];
3778 for (var i = 0; i < xs.length; i++) {
3779 if (f(xs[i], i, xs)) res.push(xs[i]);
3780 }
3781 return res;
3782}
3783
3784// String.prototype.substr - negative index don't work in IE8
3785var substr = 'ab'.substr(-1) === 'b'
3786 ? function (str, start, len) { return str.substr(start, len) }
3787 : function (str, start, len) {
3788 if (start < 0) start = str.length + start;
3789 return str.substr(start, len);
3790 }
3791;
3792
3793}).call(this,require('_process'))
3794},{"_process":31}],31:[function(require,module,exports){
3795// shim for using process in browser
3796
3797var process = module.exports = {};
3798
3799process.nextTick = (function () {
3800 var canSetImmediate = typeof window !== 'undefined'
3801 && window.setImmediate;
3802 var canPost = typeof window !== 'undefined'
3803 && window.postMessage && window.addEventListener
3804 ;
3805
3806 if (canSetImmediate) {
3807 return function (f) { return window.setImmediate(f) };
3808 }
3809
3810 if (canPost) {
3811 var queue = [];
3812 window.addEventListener('message', function (ev) {
3813 var source = ev.source;
3814 if ((source === window || source === null) && ev.data === 'process-tick') {
3815 ev.stopPropagation();
3816 if (queue.length > 0) {
3817 var fn = queue.shift();
3818 fn();
3819 }
3820 }
3821 }, true);
3822
3823 return function nextTick(fn) {
3824 queue.push(fn);
3825 window.postMessage('process-tick', '*');
3826 };
3827 }
3828
3829 return function nextTick(fn) {
3830 setTimeout(fn, 0);
3831 };
3832})();
3833
3834process.title = 'browser';
3835process.browser = true;
3836process.env = {};
3837process.argv = [];
3838
3839function noop() {}
3840
3841process.on = noop;
3842process.addListener = noop;
3843process.once = noop;
3844process.off = noop;
3845process.removeListener = noop;
3846process.removeAllListeners = noop;
3847process.emit = noop;
3848
3849process.binding = function (name) {
3850 throw new Error('process.binding is not supported');
3851}
3852
3853// TODO(shtylman)
3854process.cwd = function () { return '/' };
3855process.chdir = function (dir) {
3856 throw new Error('process.chdir is not supported');
3857};
3858
3859},{}],32:[function(require,module,exports){
3860(function (global){
3861/*! http://mths.be/punycode v1.2.4 by @mathias */
3862;(function(root) {
3863
3864 /** Detect free variables */
3865 var freeExports = typeof exports == 'object' && exports;
3866 var freeModule = typeof module == 'object' && module &&
3867 module.exports == freeExports && module;
3868 var freeGlobal = typeof global == 'object' && global;
3869 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
3870 root = freeGlobal;
3871 }
3872
3873 /**
3874 * The `punycode` object.
3875 * @name punycode
3876 * @type Object
3877 */
3878 var punycode,
3879
3880 /** Highest positive signed 32-bit float value */
3881 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
3882
3883 /** Bootstring parameters */
3884 base = 36,
3885 tMin = 1,
3886 tMax = 26,
3887 skew = 38,
3888 damp = 700,
3889 initialBias = 72,
3890 initialN = 128, // 0x80
3891 delimiter = '-', // '\x2D'
3892
3893 /** Regular expressions */
3894 regexPunycode = /^xn--/,
3895 regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
3896 regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
3897
3898 /** Error messages */
3899 errors = {
3900 'overflow': 'Overflow: input needs wider integers to process',
3901 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
3902 'invalid-input': 'Invalid input'
3903 },
3904
3905 /** Convenience shortcuts */
3906 baseMinusTMin = base - tMin,
3907 floor = Math.floor,
3908 stringFromCharCode = String.fromCharCode,
3909
3910 /** Temporary variable */
3911 key;
3912
3913 /*--------------------------------------------------------------------------*/
3914
3915 /**
3916 * A generic error utility function.
3917 * @private
3918 * @param {String} type The error type.
3919 * @returns {Error} Throws a `RangeError` with the applicable error message.
3920 */
3921 function error(type) {
3922 throw RangeError(errors[type]);
3923 }
3924
3925 /**
3926 * A generic `Array#map` utility function.
3927 * @private
3928 * @param {Array} array The array to iterate over.
3929 * @param {Function} callback The function that gets called for every array
3930 * item.
3931 * @returns {Array} A new array of values returned by the callback function.
3932 */
3933 function map(array, fn) {
3934 var length = array.length;
3935 while (length--) {
3936 array[length] = fn(array[length]);
3937 }
3938 return array;
3939 }
3940
3941 /**
3942 * A simple `Array#map`-like wrapper to work with domain name strings.
3943 * @private
3944 * @param {String} domain The domain name.
3945 * @param {Function} callback The function that gets called for every
3946 * character.
3947 * @returns {Array} A new string of characters returned by the callback
3948 * function.
3949 */
3950 function mapDomain(string, fn) {
3951 return map(string.split(regexSeparators), fn).join('.');
3952 }
3953
3954 /**
3955 * Creates an array containing the numeric code points of each Unicode
3956 * character in the string. While JavaScript uses UCS-2 internally,
3957 * this function will convert a pair of surrogate halves (each of which
3958 * UCS-2 exposes as separate characters) into a single code point,
3959 * matching UTF-16.
3960 * @see `punycode.ucs2.encode`
3961 * @see <http://mathiasbynens.be/notes/javascript-encoding>
3962 * @memberOf punycode.ucs2
3963 * @name decode
3964 * @param {String} string The Unicode input string (UCS-2).
3965 * @returns {Array} The new array of code points.
3966 */
3967 function ucs2decode(string) {
3968 var output = [],
3969 counter = 0,
3970 length = string.length,
3971 value,
3972 extra;
3973 while (counter < length) {
3974 value = string.charCodeAt(counter++);
3975 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
3976 // high surrogate, and there is a next character
3977 extra = string.charCodeAt(counter++);
3978 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
3979 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
3980 } else {
3981 // unmatched surrogate; only append this code unit, in case the next
3982 // code unit is the high surrogate of a surrogate pair
3983 output.push(value);
3984 counter--;
3985 }
3986 } else {
3987 output.push(value);
3988 }
3989 }
3990 return output;
3991 }
3992
3993 /**
3994 * Creates a string based on an array of numeric code points.
3995 * @see `punycode.ucs2.decode`
3996 * @memberOf punycode.ucs2
3997 * @name encode
3998 * @param {Array} codePoints The array of numeric code points.
3999 * @returns {String} The new Unicode string (UCS-2).
4000 */
4001 function ucs2encode(array) {
4002 return map(array, function(value) {
4003 var output = '';
4004 if (value > 0xFFFF) {
4005 value -= 0x10000;
4006 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
4007 value = 0xDC00 | value & 0x3FF;
4008 }
4009 output += stringFromCharCode(value);
4010 return output;
4011 }).join('');
4012 }
4013
4014 /**
4015 * Converts a basic code point into a digit/integer.
4016 * @see `digitToBasic()`
4017 * @private
4018 * @param {Number} codePoint The basic numeric code point value.
4019 * @returns {Number} The numeric value of a basic code point (for use in
4020 * representing integers) in the range `0` to `base - 1`, or `base` if
4021 * the code point does not represent a value.
4022 */
4023 function basicToDigit(codePoint) {
4024 if (codePoint - 48 < 10) {
4025 return codePoint - 22;
4026 }
4027 if (codePoint - 65 < 26) {
4028 return codePoint - 65;
4029 }
4030 if (codePoint - 97 < 26) {
4031 return codePoint - 97;
4032 }
4033 return base;
4034 }
4035
4036 /**
4037 * Converts a digit/integer into a basic code point.
4038 * @see `basicToDigit()`
4039 * @private
4040 * @param {Number} digit The numeric value of a basic code point.
4041 * @returns {Number} The basic code point whose value (when used for
4042 * representing integers) is `digit`, which needs to be in the range
4043 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
4044 * used; else, the lowercase form is used. The behavior is undefined
4045 * if `flag` is non-zero and `digit` has no uppercase form.
4046 */
4047 function digitToBasic(digit, flag) {
4048 // 0..25 map to ASCII a..z or A..Z
4049 // 26..35 map to ASCII 0..9
4050 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
4051 }
4052
4053 /**
4054 * Bias adaptation function as per section 3.4 of RFC 3492.
4055 * http://tools.ietf.org/html/rfc3492#section-3.4
4056 * @private
4057 */
4058 function adapt(delta, numPoints, firstTime) {
4059 var k = 0;
4060 delta = firstTime ? floor(delta / damp) : delta >> 1;
4061 delta += floor(delta / numPoints);
4062 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
4063 delta = floor(delta / baseMinusTMin);
4064 }
4065 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
4066 }
4067
4068 /**
4069 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
4070 * symbols.
4071 * @memberOf punycode
4072 * @param {String} input The Punycode string of ASCII-only symbols.
4073 * @returns {String} The resulting string of Unicode symbols.
4074 */
4075 function decode(input) {
4076 // Don't use UCS-2
4077 var output = [],
4078 inputLength = input.length,
4079 out,
4080 i = 0,
4081 n = initialN,
4082 bias = initialBias,
4083 basic,
4084 j,
4085 index,
4086 oldi,
4087 w,
4088 k,
4089 digit,
4090 t,
4091 /** Cached calculation results */
4092 baseMinusT;
4093
4094 // Handle the basic code points: let `basic` be the number of input code
4095 // points before the last delimiter, or `0` if there is none, then copy
4096 // the first basic code points to the output.
4097
4098 basic = input.lastIndexOf(delimiter);
4099 if (basic < 0) {
4100 basic = 0;
4101 }
4102
4103 for (j = 0; j < basic; ++j) {
4104 // if it's not a basic code point
4105 if (input.charCodeAt(j) >= 0x80) {
4106 error('not-basic');
4107 }
4108 output.push(input.charCodeAt(j));
4109 }
4110
4111 // Main decoding loop: start just after the last delimiter if any basic code
4112 // points were copied; start at the beginning otherwise.
4113
4114 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
4115
4116 // `index` is the index of the next character to be consumed.
4117 // Decode a generalized variable-length integer into `delta`,
4118 // which gets added to `i`. The overflow checking is easier
4119 // if we increase `i` as we go, then subtract off its starting
4120 // value at the end to obtain `delta`.
4121 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
4122
4123 if (index >= inputLength) {
4124 error('invalid-input');
4125 }
4126
4127 digit = basicToDigit(input.charCodeAt(index++));
4128
4129 if (digit >= base || digit > floor((maxInt - i) / w)) {
4130 error('overflow');
4131 }
4132
4133 i += digit * w;
4134 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
4135
4136 if (digit < t) {
4137 break;
4138 }
4139
4140 baseMinusT = base - t;
4141 if (w > floor(maxInt / baseMinusT)) {
4142 error('overflow');
4143 }
4144
4145 w *= baseMinusT;
4146
4147 }
4148
4149 out = output.length + 1;
4150 bias = adapt(i - oldi, out, oldi == 0);
4151
4152 // `i` was supposed to wrap around from `out` to `0`,
4153 // incrementing `n` each time, so we'll fix that now:
4154 if (floor(i / out) > maxInt - n) {
4155 error('overflow');
4156 }
4157
4158 n += floor(i / out);
4159 i %= out;
4160
4161 // Insert `n` at position `i` of the output
4162 output.splice(i++, 0, n);
4163
4164 }
4165
4166 return ucs2encode(output);
4167 }
4168
4169 /**
4170 * Converts a string of Unicode symbols to a Punycode string of ASCII-only
4171 * symbols.
4172 * @memberOf punycode
4173 * @param {String} input The string of Unicode symbols.
4174 * @returns {String} The resulting Punycode string of ASCII-only symbols.
4175 */
4176 function encode(input) {
4177 var n,
4178 delta,
4179 handledCPCount,
4180 basicLength,
4181 bias,
4182 j,
4183 m,
4184 q,
4185 k,
4186 t,
4187 currentValue,
4188 output = [],
4189 /** `inputLength` will hold the number of code points in `input`. */
4190 inputLength,
4191 /** Cached calculation results */
4192 handledCPCountPlusOne,
4193 baseMinusT,
4194 qMinusT;
4195
4196 // Convert the input in UCS-2 to Unicode
4197 input = ucs2decode(input);
4198
4199 // Cache the length
4200 inputLength = input.length;
4201
4202 // Initialize the state
4203 n = initialN;
4204 delta = 0;
4205 bias = initialBias;
4206
4207 // Handle the basic code points
4208 for (j = 0; j < inputLength; ++j) {
4209 currentValue = input[j];
4210 if (currentValue < 0x80) {
4211 output.push(stringFromCharCode(currentValue));
4212 }
4213 }
4214
4215 handledCPCount = basicLength = output.length;
4216
4217 // `handledCPCount` is the number of code points that have been handled;
4218 // `basicLength` is the number of basic code points.
4219
4220 // Finish the basic string - if it is not empty - with a delimiter
4221 if (basicLength) {
4222 output.push(delimiter);
4223 }
4224
4225 // Main encoding loop:
4226 while (handledCPCount < inputLength) {
4227
4228 // All non-basic code points < n have been handled already. Find the next
4229 // larger one:
4230 for (m = maxInt, j = 0; j < inputLength; ++j) {
4231 currentValue = input[j];
4232 if (currentValue >= n && currentValue < m) {
4233 m = currentValue;
4234 }
4235 }
4236
4237 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
4238 // but guard against overflow
4239 handledCPCountPlusOne = handledCPCount + 1;
4240 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
4241 error('overflow');
4242 }
4243
4244 delta += (m - n) * handledCPCountPlusOne;
4245 n = m;
4246
4247 for (j = 0; j < inputLength; ++j) {
4248 currentValue = input[j];
4249
4250 if (currentValue < n && ++delta > maxInt) {
4251 error('overflow');
4252 }
4253
4254 if (currentValue == n) {
4255 // Represent delta as a generalized variable-length integer
4256 for (q = delta, k = base; /* no condition */; k += base) {
4257 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
4258 if (q < t) {
4259 break;
4260 }
4261 qMinusT = q - t;
4262 baseMinusT = base - t;
4263 output.push(
4264 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
4265 );
4266 q = floor(qMinusT / baseMinusT);
4267 }
4268
4269 output.push(stringFromCharCode(digitToBasic(q, 0)));
4270 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
4271 delta = 0;
4272 ++handledCPCount;
4273 }
4274 }
4275
4276 ++delta;
4277 ++n;
4278
4279 }
4280 return output.join('');
4281 }
4282
4283 /**
4284 * Converts a Punycode string representing a domain name to Unicode. Only the
4285 * Punycoded parts of the domain name will be converted, i.e. it doesn't
4286 * matter if you call it on a string that has already been converted to
4287 * Unicode.
4288 * @memberOf punycode
4289 * @param {String} domain The Punycode domain name to convert to Unicode.
4290 * @returns {String} The Unicode representation of the given Punycode
4291 * string.
4292 */
4293 function toUnicode(domain) {
4294 return mapDomain(domain, function(string) {
4295 return regexPunycode.test(string)
4296 ? decode(string.slice(4).toLowerCase())
4297 : string;
4298 });
4299 }
4300
4301 /**
4302 * Converts a Unicode string representing a domain name to Punycode. Only the
4303 * non-ASCII parts of the domain name will be converted, i.e. it doesn't
4304 * matter if you call it with a domain that's already in ASCII.
4305 * @memberOf punycode
4306 * @param {String} domain The domain name to convert, as a Unicode string.
4307 * @returns {String} The Punycode representation of the given domain name.
4308 */
4309 function toASCII(domain) {
4310 return mapDomain(domain, function(string) {
4311 return regexNonASCII.test(string)
4312 ? 'xn--' + encode(string)
4313 : string;
4314 });
4315 }
4316
4317 /*--------------------------------------------------------------------------*/
4318
4319 /** Define the public API */
4320 punycode = {
4321 /**
4322 * A string representing the current Punycode.js version number.
4323 * @memberOf punycode
4324 * @type String
4325 */
4326 'version': '1.2.4',
4327 /**
4328 * An object of methods to convert from JavaScript's internal character
4329 * representation (UCS-2) to Unicode code points, and back.
4330 * @see <http://mathiasbynens.be/notes/javascript-encoding>
4331 * @memberOf punycode
4332 * @type Object
4333 */
4334 'ucs2': {
4335 'decode': ucs2decode,
4336 'encode': ucs2encode
4337 },
4338 'decode': decode,
4339 'encode': encode,
4340 'toASCII': toASCII,
4341 'toUnicode': toUnicode
4342 };
4343
4344 /** Expose `punycode` */
4345 // Some AMD build optimizers, like r.js, check for specific condition patterns
4346 // like the following:
4347 if (
4348 typeof define == 'function' &&
4349 typeof define.amd == 'object' &&
4350 define.amd
4351 ) {
4352 define('punycode', function() {
4353 return punycode;
4354 });
4355 } else if (freeExports && !freeExports.nodeType) {
4356 if (freeModule) { // in Node.js or RingoJS v0.8.0+
4357 freeModule.exports = punycode;
4358 } else { // in Narwhal or RingoJS v0.7.0-
4359 for (key in punycode) {
4360 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
4361 }
4362 }
4363 } else { // in Rhino or a web browser
4364 root.punycode = punycode;
4365 }
4366
4367}(this));
4368
4369}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4370},{}],33:[function(require,module,exports){
4371// Copyright Joyent, Inc. and other Node contributors.
4372//
4373// Permission is hereby granted, free of charge, to any person obtaining a
4374// copy of this software and associated documentation files (the
4375// "Software"), to deal in the Software without restriction, including
4376// without limitation the rights to use, copy, modify, merge, publish,
4377// distribute, sublicense, and/or sell copies of the Software, and to permit
4378// persons to whom the Software is furnished to do so, subject to the
4379// following conditions:
4380//
4381// The above copyright notice and this permission notice shall be included
4382// in all copies or substantial portions of the Software.
4383//
4384// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4385// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4386// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4387// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4388// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4389// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4390// USE OR OTHER DEALINGS IN THE SOFTWARE.
4391
4392'use strict';
4393
4394// If obj.hasOwnProperty has been overridden, then calling
4395// obj.hasOwnProperty(prop) will break.
4396// See: https://github.com/joyent/node/issues/1707
4397function hasOwnProperty(obj, prop) {
4398 return Object.prototype.hasOwnProperty.call(obj, prop);
4399}
4400
4401module.exports = function(qs, sep, eq, options) {
4402 sep = sep || '&';
4403 eq = eq || '=';
4404 var obj = {};
4405
4406 if (typeof qs !== 'string' || qs.length === 0) {
4407 return obj;
4408 }
4409
4410 var regexp = /\+/g;
4411 qs = qs.split(sep);
4412
4413 var maxKeys = 1000;
4414 if (options && typeof options.maxKeys === 'number') {
4415 maxKeys = options.maxKeys;
4416 }
4417
4418 var len = qs.length;
4419 // maxKeys <= 0 means that we should not limit keys count
4420 if (maxKeys > 0 && len > maxKeys) {
4421 len = maxKeys;
4422 }
4423
4424 for (var i = 0; i < len; ++i) {
4425 var x = qs[i].replace(regexp, '%20'),
4426 idx = x.indexOf(eq),
4427 kstr, vstr, k, v;
4428
4429 if (idx >= 0) {
4430 kstr = x.substr(0, idx);
4431 vstr = x.substr(idx + 1);
4432 } else {
4433 kstr = x;
4434 vstr = '';
4435 }
4436
4437 k = decodeURIComponent(kstr);
4438 v = decodeURIComponent(vstr);
4439
4440 if (!hasOwnProperty(obj, k)) {
4441 obj[k] = v;
4442 } else if (isArray(obj[k])) {
4443 obj[k].push(v);
4444 } else {
4445 obj[k] = [obj[k], v];
4446 }
4447 }
4448
4449 return obj;
4450};
4451
4452var isArray = Array.isArray || function (xs) {
4453 return Object.prototype.toString.call(xs) === '[object Array]';
4454};
4455
4456},{}],34:[function(require,module,exports){
4457// Copyright Joyent, Inc. and other Node contributors.
4458//
4459// Permission is hereby granted, free of charge, to any person obtaining a
4460// copy of this software and associated documentation files (the
4461// "Software"), to deal in the Software without restriction, including
4462// without limitation the rights to use, copy, modify, merge, publish,
4463// distribute, sublicense, and/or sell copies of the Software, and to permit
4464// persons to whom the Software is furnished to do so, subject to the
4465// following conditions:
4466//
4467// The above copyright notice and this permission notice shall be included
4468// in all copies or substantial portions of the Software.
4469//
4470// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4471// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4472// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4473// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4474// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4475// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4476// USE OR OTHER DEALINGS IN THE SOFTWARE.
4477
4478'use strict';
4479
4480var stringifyPrimitive = function(v) {
4481 switch (typeof v) {
4482 case 'string':
4483 return v;
4484
4485 case 'boolean':
4486 return v ? 'true' : 'false';
4487
4488 case 'number':
4489 return isFinite(v) ? v : '';
4490
4491 default:
4492 return '';
4493 }
4494};
4495
4496module.exports = function(obj, sep, eq, name) {
4497 sep = sep || '&';
4498 eq = eq || '=';
4499 if (obj === null) {
4500 obj = undefined;
4501 }
4502
4503 if (typeof obj === 'object') {
4504 return map(objectKeys(obj), function(k) {
4505 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
4506 if (isArray(obj[k])) {
4507 return map(obj[k], function(v) {
4508 return ks + encodeURIComponent(stringifyPrimitive(v));
4509 }).join(sep);
4510 } else {
4511 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
4512 }
4513 }).join(sep);
4514
4515 }
4516
4517 if (!name) return '';
4518 return encodeURIComponent(stringifyPrimitive(name)) + eq +
4519 encodeURIComponent(stringifyPrimitive(obj));
4520};
4521
4522var isArray = Array.isArray || function (xs) {
4523 return Object.prototype.toString.call(xs) === '[object Array]';
4524};
4525
4526function map (xs, f) {
4527 if (xs.map) return xs.map(f);
4528 var res = [];
4529 for (var i = 0; i < xs.length; i++) {
4530 res.push(f(xs[i], i));
4531 }
4532 return res;
4533}
4534
4535var objectKeys = Object.keys || function (obj) {
4536 var res = [];
4537 for (var key in obj) {
4538 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
4539 }
4540 return res;
4541};
4542
4543},{}],35:[function(require,module,exports){
4544'use strict';
4545
4546exports.decode = exports.parse = require('./decode');
4547exports.encode = exports.stringify = require('./encode');
4548
4549},{"./decode":33,"./encode":34}],36:[function(require,module,exports){
4550module.exports = require("./lib/_stream_duplex.js")
4551
4552},{"./lib/_stream_duplex.js":37}],37:[function(require,module,exports){
4553(function (process){
4554// Copyright Joyent, Inc. and other Node contributors.
4555//
4556// Permission is hereby granted, free of charge, to any person obtaining a
4557// copy of this software and associated documentation files (the
4558// "Software"), to deal in the Software without restriction, including
4559// without limitation the rights to use, copy, modify, merge, publish,
4560// distribute, sublicense, and/or sell copies of the Software, and to permit
4561// persons to whom the Software is furnished to do so, subject to the
4562// following conditions:
4563//
4564// The above copyright notice and this permission notice shall be included
4565// in all copies or substantial portions of the Software.
4566//
4567// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4568// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4569// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4570// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4571// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4572// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4573// USE OR OTHER DEALINGS IN THE SOFTWARE.
4574
4575// a duplex stream is just a stream that is both readable and writable.
4576// Since JS doesn't have multiple prototypal inheritance, this class
4577// prototypally inherits from Readable, and then parasitically from
4578// Writable.
4579
4580module.exports = Duplex;
4581
4582/*<replacement>*/
4583var objectKeys = Object.keys || function (obj) {
4584 var keys = [];
4585 for (var key in obj) keys.push(key);
4586 return keys;
4587}
4588/*</replacement>*/
4589
4590
4591/*<replacement>*/
4592var util = require('core-util-is');
4593util.inherits = require('inherits');
4594/*</replacement>*/
4595
4596var Readable = require('./_stream_readable');
4597var Writable = require('./_stream_writable');
4598
4599util.inherits(Duplex, Readable);
4600
4601forEach(objectKeys(Writable.prototype), function(method) {
4602 if (!Duplex.prototype[method])
4603 Duplex.prototype[method] = Writable.prototype[method];
4604});
4605
4606function Duplex(options) {
4607 if (!(this instanceof Duplex))
4608 return new Duplex(options);
4609
4610 Readable.call(this, options);
4611 Writable.call(this, options);
4612
4613 if (options && options.readable === false)
4614 this.readable = false;
4615
4616 if (options && options.writable === false)
4617 this.writable = false;
4618
4619 this.allowHalfOpen = true;
4620 if (options && options.allowHalfOpen === false)
4621 this.allowHalfOpen = false;
4622
4623 this.once('end', onend);
4624}
4625
4626// the no-half-open enforcer
4627function onend() {
4628 // if we allow half-open state, or if the writable side ended,
4629 // then we're ok.
4630 if (this.allowHalfOpen || this._writableState.ended)
4631 return;
4632
4633 // no more data can be written.
4634 // But allow more writes to happen in this tick.
4635 process.nextTick(this.end.bind(this));
4636}
4637
4638function forEach (xs, f) {
4639 for (var i = 0, l = xs.length; i < l; i++) {
4640 f(xs[i], i);
4641 }
4642}
4643
4644}).call(this,require('_process'))
4645},{"./_stream_readable":39,"./_stream_writable":41,"_process":31,"core-util-is":42,"inherits":28}],38:[function(require,module,exports){
4646// Copyright Joyent, Inc. and other Node contributors.
4647//
4648// Permission is hereby granted, free of charge, to any person obtaining a
4649// copy of this software and associated documentation files (the
4650// "Software"), to deal in the Software without restriction, including
4651// without limitation the rights to use, copy, modify, merge, publish,
4652// distribute, sublicense, and/or sell copies of the Software, and to permit
4653// persons to whom the Software is furnished to do so, subject to the
4654// following conditions:
4655//
4656// The above copyright notice and this permission notice shall be included
4657// in all copies or substantial portions of the Software.
4658//
4659// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4660// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4661// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4662// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4663// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4664// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4665// USE OR OTHER DEALINGS IN THE SOFTWARE.
4666
4667// a passthrough stream.
4668// basically just the most minimal sort of Transform stream.
4669// Every written chunk gets output as-is.
4670
4671module.exports = PassThrough;
4672
4673var Transform = require('./_stream_transform');
4674
4675/*<replacement>*/
4676var util = require('core-util-is');
4677util.inherits = require('inherits');
4678/*</replacement>*/
4679
4680util.inherits(PassThrough, Transform);
4681
4682function PassThrough(options) {
4683 if (!(this instanceof PassThrough))
4684 return new PassThrough(options);
4685
4686 Transform.call(this, options);
4687}
4688
4689PassThrough.prototype._transform = function(chunk, encoding, cb) {
4690 cb(null, chunk);
4691};
4692
4693},{"./_stream_transform":40,"core-util-is":42,"inherits":28}],39:[function(require,module,exports){
4694(function (process){
4695// Copyright Joyent, Inc. and other Node contributors.
4696//
4697// Permission is hereby granted, free of charge, to any person obtaining a
4698// copy of this software and associated documentation files (the
4699// "Software"), to deal in the Software without restriction, including
4700// without limitation the rights to use, copy, modify, merge, publish,
4701// distribute, sublicense, and/or sell copies of the Software, and to permit
4702// persons to whom the Software is furnished to do so, subject to the
4703// following conditions:
4704//
4705// The above copyright notice and this permission notice shall be included
4706// in all copies or substantial portions of the Software.
4707//
4708// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4709// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4710// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4711// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4712// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4713// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4714// USE OR OTHER DEALINGS IN THE SOFTWARE.
4715
4716module.exports = Readable;
4717
4718/*<replacement>*/
4719var isArray = require('isarray');
4720/*</replacement>*/
4721
4722
4723/*<replacement>*/
4724var Buffer = require('buffer').Buffer;
4725/*</replacement>*/
4726
4727Readable.ReadableState = ReadableState;
4728
4729var EE = require('events').EventEmitter;
4730
4731/*<replacement>*/
4732if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
4733 return emitter.listeners(type).length;
4734};
4735/*</replacement>*/
4736
4737var Stream = require('stream');
4738
4739/*<replacement>*/
4740var util = require('core-util-is');
4741util.inherits = require('inherits');
4742/*</replacement>*/
4743
4744var StringDecoder;
4745
4746util.inherits(Readable, Stream);
4747
4748function ReadableState(options, stream) {
4749 options = options || {};
4750
4751 // the point at which it stops calling _read() to fill the buffer
4752 // Note: 0 is a valid value, means "don't call _read preemptively ever"
4753 var hwm = options.highWaterMark;
4754 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
4755
4756 // cast to ints.
4757 this.highWaterMark = ~~this.highWaterMark;
4758
4759 this.buffer = [];
4760 this.length = 0;
4761 this.pipes = null;
4762 this.pipesCount = 0;
4763 this.flowing = false;
4764 this.ended = false;
4765 this.endEmitted = false;
4766 this.reading = false;
4767
4768 // In streams that never have any data, and do push(null) right away,
4769 // the consumer can miss the 'end' event if they do some I/O before
4770 // consuming the stream. So, we don't emit('end') until some reading
4771 // happens.
4772 this.calledRead = false;
4773
4774 // a flag to be able to tell if the onwrite cb is called immediately,
4775 // or on a later tick. We set this to true at first, becuase any
4776 // actions that shouldn't happen until "later" should generally also
4777 // not happen before the first write call.
4778 this.sync = true;
4779
4780 // whenever we return null, then we set a flag to say
4781 // that we're awaiting a 'readable' event emission.
4782 this.needReadable = false;
4783 this.emittedReadable = false;
4784 this.readableListening = false;
4785
4786
4787 // object stream flag. Used to make read(n) ignore n and to
4788 // make all the buffer merging and length checks go away
4789 this.objectMode = !!options.objectMode;
4790
4791 // Crypto is kind of old and crusty. Historically, its default string
4792 // encoding is 'binary' so we have to make this configurable.
4793 // Everything else in the universe uses 'utf8', though.
4794 this.defaultEncoding = options.defaultEncoding || 'utf8';
4795
4796 // when piping, we only care about 'readable' events that happen
4797 // after read()ing all the bytes and not getting any pushback.
4798 this.ranOut = false;
4799
4800 // the number of writers that are awaiting a drain event in .pipe()s
4801 this.awaitDrain = 0;
4802
4803 // if true, a maybeReadMore has been scheduled
4804 this.readingMore = false;
4805
4806 this.decoder = null;
4807 this.encoding = null;
4808 if (options.encoding) {
4809 if (!StringDecoder)
4810 StringDecoder = require('string_decoder/').StringDecoder;
4811 this.decoder = new StringDecoder(options.encoding);
4812 this.encoding = options.encoding;
4813 }
4814}
4815
4816function Readable(options) {
4817 if (!(this instanceof Readable))
4818 return new Readable(options);
4819
4820 this._readableState = new ReadableState(options, this);
4821
4822 // legacy
4823 this.readable = true;
4824
4825 Stream.call(this);
4826}
4827
4828// Manually shove something into the read() buffer.
4829// This returns true if the highWaterMark has not been hit yet,
4830// similar to how Writable.write() returns true if you should
4831// write() some more.
4832Readable.prototype.push = function(chunk, encoding) {
4833 var state = this._readableState;
4834
4835 if (typeof chunk === 'string' && !state.objectMode) {
4836 encoding = encoding || state.defaultEncoding;
4837 if (encoding !== state.encoding) {
4838 chunk = new Buffer(chunk, encoding);
4839 encoding = '';
4840 }
4841 }
4842
4843 return readableAddChunk(this, state, chunk, encoding, false);
4844};
4845
4846// Unshift should *always* be something directly out of read()
4847Readable.prototype.unshift = function(chunk) {
4848 var state = this._readableState;
4849 return readableAddChunk(this, state, chunk, '', true);
4850};
4851
4852function readableAddChunk(stream, state, chunk, encoding, addToFront) {
4853 var er = chunkInvalid(state, chunk);
4854 if (er) {
4855 stream.emit('error', er);
4856 } else if (chunk === null || chunk === undefined) {
4857 state.reading = false;
4858 if (!state.ended)
4859 onEofChunk(stream, state);
4860 } else if (state.objectMode || chunk && chunk.length > 0) {
4861 if (state.ended && !addToFront) {
4862 var e = new Error('stream.push() after EOF');
4863 stream.emit('error', e);
4864 } else if (state.endEmitted && addToFront) {
4865 var e = new Error('stream.unshift() after end event');
4866 stream.emit('error', e);
4867 } else {
4868 if (state.decoder && !addToFront && !encoding)
4869 chunk = state.decoder.write(chunk);
4870
4871 // update the buffer info.
4872 state.length += state.objectMode ? 1 : chunk.length;
4873 if (addToFront) {
4874 state.buffer.unshift(chunk);
4875 } else {
4876 state.reading = false;
4877 state.buffer.push(chunk);
4878 }
4879
4880 if (state.needReadable)
4881 emitReadable(stream);
4882
4883 maybeReadMore(stream, state);
4884 }
4885 } else if (!addToFront) {
4886 state.reading = false;
4887 }
4888
4889 return needMoreData(state);
4890}
4891
4892
4893
4894// if it's past the high water mark, we can push in some more.
4895// Also, if we have no data yet, we can stand some
4896// more bytes. This is to work around cases where hwm=0,
4897// such as the repl. Also, if the push() triggered a
4898// readable event, and the user called read(largeNumber) such that
4899// needReadable was set, then we ought to push more, so that another
4900// 'readable' event will be triggered.
4901function needMoreData(state) {
4902 return !state.ended &&
4903 (state.needReadable ||
4904 state.length < state.highWaterMark ||
4905 state.length === 0);
4906}
4907
4908// backwards compatibility.
4909Readable.prototype.setEncoding = function(enc) {
4910 if (!StringDecoder)
4911 StringDecoder = require('string_decoder/').StringDecoder;
4912 this._readableState.decoder = new StringDecoder(enc);
4913 this._readableState.encoding = enc;
4914};
4915
4916// Don't raise the hwm > 128MB
4917var MAX_HWM = 0x800000;
4918function roundUpToNextPowerOf2(n) {
4919 if (n >= MAX_HWM) {
4920 n = MAX_HWM;
4921 } else {
4922 // Get the next highest power of 2
4923 n--;
4924 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
4925 n++;
4926 }
4927 return n;
4928}
4929
4930function howMuchToRead(n, state) {
4931 if (state.length === 0 && state.ended)
4932 return 0;
4933
4934 if (state.objectMode)
4935 return n === 0 ? 0 : 1;
4936
4937 if (n === null || isNaN(n)) {
4938 // only flow one buffer at a time
4939 if (state.flowing && state.buffer.length)
4940 return state.buffer[0].length;
4941 else
4942 return state.length;
4943 }
4944
4945 if (n <= 0)
4946 return 0;
4947
4948 // If we're asking for more than the target buffer level,
4949 // then raise the water mark. Bump up to the next highest
4950 // power of 2, to prevent increasing it excessively in tiny
4951 // amounts.
4952 if (n > state.highWaterMark)
4953 state.highWaterMark = roundUpToNextPowerOf2(n);
4954
4955 // don't have that much. return null, unless we've ended.
4956 if (n > state.length) {
4957 if (!state.ended) {
4958 state.needReadable = true;
4959 return 0;
4960 } else
4961 return state.length;
4962 }
4963
4964 return n;
4965}
4966
4967// you can override either this method, or the async _read(n) below.
4968Readable.prototype.read = function(n) {
4969 var state = this._readableState;
4970 state.calledRead = true;
4971 var nOrig = n;
4972 var ret;
4973
4974 if (typeof n !== 'number' || n > 0)
4975 state.emittedReadable = false;
4976
4977 // if we're doing read(0) to trigger a readable event, but we
4978 // already have a bunch of data in the buffer, then just trigger
4979 // the 'readable' event and move on.
4980 if (n === 0 &&
4981 state.needReadable &&
4982 (state.length >= state.highWaterMark || state.ended)) {
4983 emitReadable(this);
4984 return null;
4985 }
4986
4987 n = howMuchToRead(n, state);
4988
4989 // if we've ended, and we're now clear, then finish it up.
4990 if (n === 0 && state.ended) {
4991 ret = null;
4992
4993 // In cases where the decoder did not receive enough data
4994 // to produce a full chunk, then immediately received an
4995 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
4996 // howMuchToRead will see this and coerce the amount to
4997 // read to zero (because it's looking at the length of the
4998 // first <Buffer > in state.buffer), and we'll end up here.
4999 //
5000 // This can only happen via state.decoder -- no other venue
5001 // exists for pushing a zero-length chunk into state.buffer
5002 // and triggering this behavior. In this case, we return our
5003 // remaining data and end the stream, if appropriate.
5004 if (state.length > 0 && state.decoder) {
5005 ret = fromList(n, state);
5006 state.length -= ret.length;
5007 }
5008
5009 if (state.length === 0)
5010 endReadable(this);
5011
5012 return ret;
5013 }
5014
5015 // All the actual chunk generation logic needs to be
5016 // *below* the call to _read. The reason is that in certain
5017 // synthetic stream cases, such as passthrough streams, _read
5018 // may be a completely synchronous operation which may change
5019 // the state of the read buffer, providing enough data when
5020 // before there was *not* enough.
5021 //
5022 // So, the steps are:
5023 // 1. Figure out what the state of things will be after we do
5024 // a read from the buffer.
5025 //
5026 // 2. If that resulting state will trigger a _read, then call _read.
5027 // Note that this may be asynchronous, or synchronous. Yes, it is
5028 // deeply ugly to write APIs this way, but that still doesn't mean
5029 // that the Readable class should behave improperly, as streams are
5030 // designed to be sync/async agnostic.
5031 // Take note if the _read call is sync or async (ie, if the read call
5032 // has returned yet), so that we know whether or not it's safe to emit
5033 // 'readable' etc.
5034 //
5035 // 3. Actually pull the requested chunks out of the buffer and return.
5036
5037 // if we need a readable event, then we need to do some reading.
5038 var doRead = state.needReadable;
5039
5040 // if we currently have less than the highWaterMark, then also read some
5041 if (state.length - n <= state.highWaterMark)
5042 doRead = true;
5043
5044 // however, if we've ended, then there's no point, and if we're already
5045 // reading, then it's unnecessary.
5046 if (state.ended || state.reading)
5047 doRead = false;
5048
5049 if (doRead) {
5050 state.reading = true;
5051 state.sync = true;
5052 // if the length is currently zero, then we *need* a readable event.
5053 if (state.length === 0)
5054 state.needReadable = true;
5055 // call internal read method
5056 this._read(state.highWaterMark);
5057 state.sync = false;
5058 }
5059
5060 // If _read called its callback synchronously, then `reading`
5061 // will be false, and we need to re-evaluate how much data we
5062 // can return to the user.
5063 if (doRead && !state.reading)
5064 n = howMuchToRead(nOrig, state);
5065
5066 if (n > 0)
5067 ret = fromList(n, state);
5068 else
5069 ret = null;
5070
5071 if (ret === null) {
5072 state.needReadable = true;
5073 n = 0;
5074 }
5075
5076 state.length -= n;
5077
5078 // If we have nothing in the buffer, then we want to know
5079 // as soon as we *do* get something into the buffer.
5080 if (state.length === 0 && !state.ended)
5081 state.needReadable = true;
5082
5083 // If we happened to read() exactly the remaining amount in the
5084 // buffer, and the EOF has been seen at this point, then make sure
5085 // that we emit 'end' on the very next tick.
5086 if (state.ended && !state.endEmitted && state.length === 0)
5087 endReadable(this);
5088
5089 return ret;
5090};
5091
5092function chunkInvalid(state, chunk) {
5093 var er = null;
5094 if (!Buffer.isBuffer(chunk) &&
5095 'string' !== typeof chunk &&
5096 chunk !== null &&
5097 chunk !== undefined &&
5098 !state.objectMode) {
5099 er = new TypeError('Invalid non-string/buffer chunk');
5100 }
5101 return er;
5102}
5103
5104
5105function onEofChunk(stream, state) {
5106 if (state.decoder && !state.ended) {
5107 var chunk = state.decoder.end();
5108 if (chunk && chunk.length) {
5109 state.buffer.push(chunk);
5110 state.length += state.objectMode ? 1 : chunk.length;
5111 }
5112 }
5113 state.ended = true;
5114
5115 // if we've ended and we have some data left, then emit
5116 // 'readable' now to make sure it gets picked up.
5117 if (state.length > 0)
5118 emitReadable(stream);
5119 else
5120 endReadable(stream);
5121}
5122
5123// Don't emit readable right away in sync mode, because this can trigger
5124// another read() call => stack overflow. This way, it might trigger
5125// a nextTick recursion warning, but that's not so bad.
5126function emitReadable(stream) {
5127 var state = stream._readableState;
5128 state.needReadable = false;
5129 if (state.emittedReadable)
5130 return;
5131
5132 state.emittedReadable = true;
5133 if (state.sync)
5134 process.nextTick(function() {
5135 emitReadable_(stream);
5136 });
5137 else
5138 emitReadable_(stream);
5139}
5140
5141function emitReadable_(stream) {
5142 stream.emit('readable');
5143}
5144
5145
5146// at this point, the user has presumably seen the 'readable' event,
5147// and called read() to consume some data. that may have triggered
5148// in turn another _read(n) call, in which case reading = true if
5149// it's in progress.
5150// However, if we're not ended, or reading, and the length < hwm,
5151// then go ahead and try to read some more preemptively.
5152function maybeReadMore(stream, state) {
5153 if (!state.readingMore) {
5154 state.readingMore = true;
5155 process.nextTick(function() {
5156 maybeReadMore_(stream, state);
5157 });
5158 }
5159}
5160
5161function maybeReadMore_(stream, state) {
5162 var len = state.length;
5163 while (!state.reading && !state.flowing && !state.ended &&
5164 state.length < state.highWaterMark) {
5165 stream.read(0);
5166 if (len === state.length)
5167 // didn't get any data, stop spinning.
5168 break;
5169 else
5170 len = state.length;
5171 }
5172 state.readingMore = false;
5173}
5174
5175// abstract method. to be overridden in specific implementation classes.
5176// call cb(er, data) where data is <= n in length.
5177// for virtual (non-string, non-buffer) streams, "length" is somewhat
5178// arbitrary, and perhaps not very meaningful.
5179Readable.prototype._read = function(n) {
5180 this.emit('error', new Error('not implemented'));
5181};
5182
5183Readable.prototype.pipe = function(dest, pipeOpts) {
5184 var src = this;
5185 var state = this._readableState;
5186
5187 switch (state.pipesCount) {
5188 case 0:
5189 state.pipes = dest;
5190 break;
5191 case 1:
5192 state.pipes = [state.pipes, dest];
5193 break;
5194 default:
5195 state.pipes.push(dest);
5196 break;
5197 }
5198 state.pipesCount += 1;
5199
5200 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
5201 dest !== process.stdout &&
5202 dest !== process.stderr;
5203
5204 var endFn = doEnd ? onend : cleanup;
5205 if (state.endEmitted)
5206 process.nextTick(endFn);
5207 else
5208 src.once('end', endFn);
5209
5210 dest.on('unpipe', onunpipe);
5211 function onunpipe(readable) {
5212 if (readable !== src) return;
5213 cleanup();
5214 }
5215
5216 function onend() {
5217 dest.end();
5218 }
5219
5220 // when the dest drains, it reduces the awaitDrain counter
5221 // on the source. This would be more elegant with a .once()
5222 // handler in flow(), but adding and removing repeatedly is
5223 // too slow.
5224 var ondrain = pipeOnDrain(src);
5225 dest.on('drain', ondrain);
5226
5227 function cleanup() {
5228 // cleanup event handlers once the pipe is broken
5229 dest.removeListener('close', onclose);
5230 dest.removeListener('finish', onfinish);
5231 dest.removeListener('drain', ondrain);
5232 dest.removeListener('error', onerror);
5233 dest.removeListener('unpipe', onunpipe);
5234 src.removeListener('end', onend);
5235 src.removeListener('end', cleanup);
5236
5237 // if the reader is waiting for a drain event from this
5238 // specific writer, then it would cause it to never start
5239 // flowing again.
5240 // So, if this is awaiting a drain, then we just call it now.
5241 // If we don't know, then assume that we are waiting for one.
5242 if (!dest._writableState || dest._writableState.needDrain)
5243 ondrain();
5244 }
5245
5246 // if the dest has an error, then stop piping into it.
5247 // however, don't suppress the throwing behavior for this.
5248 function onerror(er) {
5249 unpipe();
5250 dest.removeListener('error', onerror);
5251 if (EE.listenerCount(dest, 'error') === 0)
5252 dest.emit('error', er);
5253 }
5254 // This is a brutally ugly hack to make sure that our error handler
5255 // is attached before any userland ones. NEVER DO THIS.
5256 if (!dest._events || !dest._events.error)
5257 dest.on('error', onerror);
5258 else if (isArray(dest._events.error))
5259 dest._events.error.unshift(onerror);
5260 else
5261 dest._events.error = [onerror, dest._events.error];
5262
5263
5264
5265 // Both close and finish should trigger unpipe, but only once.
5266 function onclose() {
5267 dest.removeListener('finish', onfinish);
5268 unpipe();
5269 }
5270 dest.once('close', onclose);
5271 function onfinish() {
5272 dest.removeListener('close', onclose);
5273 unpipe();
5274 }
5275 dest.once('finish', onfinish);
5276
5277 function unpipe() {
5278 src.unpipe(dest);
5279 }
5280
5281 // tell the dest that it's being piped to
5282 dest.emit('pipe', src);
5283
5284 // start the flow if it hasn't been started already.
5285 if (!state.flowing) {
5286 // the handler that waits for readable events after all
5287 // the data gets sucked out in flow.
5288 // This would be easier to follow with a .once() handler
5289 // in flow(), but that is too slow.
5290 this.on('readable', pipeOnReadable);
5291
5292 state.flowing = true;
5293 process.nextTick(function() {
5294 flow(src);
5295 });
5296 }
5297
5298 return dest;
5299};
5300
5301function pipeOnDrain(src) {
5302 return function() {
5303 var dest = this;
5304 var state = src._readableState;
5305 state.awaitDrain--;
5306 if (state.awaitDrain === 0)
5307 flow(src);
5308 };
5309}
5310
5311function flow(src) {
5312 var state = src._readableState;
5313 var chunk;
5314 state.awaitDrain = 0;
5315
5316 function write(dest, i, list) {
5317 var written = dest.write(chunk);
5318 if (false === written) {
5319 state.awaitDrain++;
5320 }
5321 }
5322
5323 while (state.pipesCount && null !== (chunk = src.read())) {
5324
5325 if (state.pipesCount === 1)
5326 write(state.pipes, 0, null);
5327 else
5328 forEach(state.pipes, write);
5329
5330 src.emit('data', chunk);
5331
5332 // if anyone needs a drain, then we have to wait for that.
5333 if (state.awaitDrain > 0)
5334 return;
5335 }
5336
5337 // if every destination was unpiped, either before entering this
5338 // function, or in the while loop, then stop flowing.
5339 //
5340 // NB: This is a pretty rare edge case.
5341 if (state.pipesCount === 0) {
5342 state.flowing = false;
5343
5344 // if there were data event listeners added, then switch to old mode.
5345 if (EE.listenerCount(src, 'data') > 0)
5346 emitDataEvents(src);
5347 return;
5348 }
5349
5350 // at this point, no one needed a drain, so we just ran out of data
5351 // on the next readable event, start it over again.
5352 state.ranOut = true;
5353}
5354
5355function pipeOnReadable() {
5356 if (this._readableState.ranOut) {
5357 this._readableState.ranOut = false;
5358 flow(this);
5359 }
5360}
5361
5362
5363Readable.prototype.unpipe = function(dest) {
5364 var state = this._readableState;
5365
5366 // if we're not piping anywhere, then do nothing.
5367 if (state.pipesCount === 0)
5368 return this;
5369
5370 // just one destination. most common case.
5371 if (state.pipesCount === 1) {
5372 // passed in one, but it's not the right one.
5373 if (dest && dest !== state.pipes)
5374 return this;
5375
5376 if (!dest)
5377 dest = state.pipes;
5378
5379 // got a match.
5380 state.pipes = null;
5381 state.pipesCount = 0;
5382 this.removeListener('readable', pipeOnReadable);
5383 state.flowing = false;
5384 if (dest)
5385 dest.emit('unpipe', this);
5386 return this;
5387 }
5388
5389 // slow case. multiple pipe destinations.
5390
5391 if (!dest) {
5392 // remove all.
5393 var dests = state.pipes;
5394 var len = state.pipesCount;
5395 state.pipes = null;
5396 state.pipesCount = 0;
5397 this.removeListener('readable', pipeOnReadable);
5398 state.flowing = false;
5399
5400 for (var i = 0; i < len; i++)
5401 dests[i].emit('unpipe', this);
5402 return this;
5403 }
5404
5405 // try to find the right one.
5406 var i = indexOf(state.pipes, dest);
5407 if (i === -1)
5408 return this;
5409
5410 state.pipes.splice(i, 1);
5411 state.pipesCount -= 1;
5412 if (state.pipesCount === 1)
5413 state.pipes = state.pipes[0];
5414
5415 dest.emit('unpipe', this);
5416
5417 return this;
5418};
5419
5420// set up data events if they are asked for
5421// Ensure readable listeners eventually get something
5422Readable.prototype.on = function(ev, fn) {
5423 var res = Stream.prototype.on.call(this, ev, fn);
5424
5425 if (ev === 'data' && !this._readableState.flowing)
5426 emitDataEvents(this);
5427
5428 if (ev === 'readable' && this.readable) {
5429 var state = this._readableState;
5430 if (!state.readableListening) {
5431 state.readableListening = true;
5432 state.emittedReadable = false;
5433 state.needReadable = true;
5434 if (!state.reading) {
5435 this.read(0);
5436 } else if (state.length) {
5437 emitReadable(this, state);
5438 }
5439 }
5440 }
5441
5442 return res;
5443};
5444Readable.prototype.addListener = Readable.prototype.on;
5445
5446// pause() and resume() are remnants of the legacy readable stream API
5447// If the user uses them, then switch into old mode.
5448Readable.prototype.resume = function() {
5449 emitDataEvents(this);
5450 this.read(0);
5451 this.emit('resume');
5452};
5453
5454Readable.prototype.pause = function() {
5455 emitDataEvents(this, true);
5456 this.emit('pause');
5457};
5458
5459function emitDataEvents(stream, startPaused) {
5460 var state = stream._readableState;
5461
5462 if (state.flowing) {
5463 // https://github.com/isaacs/readable-stream/issues/16
5464 throw new Error('Cannot switch to old mode now.');
5465 }
5466
5467 var paused = startPaused || false;
5468 var readable = false;
5469
5470 // convert to an old-style stream.
5471 stream.readable = true;
5472 stream.pipe = Stream.prototype.pipe;
5473 stream.on = stream.addListener = Stream.prototype.on;
5474
5475 stream.on('readable', function() {
5476 readable = true;
5477
5478 var c;
5479 while (!paused && (null !== (c = stream.read())))
5480 stream.emit('data', c);
5481
5482 if (c === null) {
5483 readable = false;
5484 stream._readableState.needReadable = true;
5485 }
5486 });
5487
5488 stream.pause = function() {
5489 paused = true;
5490 this.emit('pause');
5491 };
5492
5493 stream.resume = function() {
5494 paused = false;
5495 if (readable)
5496 process.nextTick(function() {
5497 stream.emit('readable');
5498 });
5499 else
5500 this.read(0);
5501 this.emit('resume');
5502 };
5503
5504 // now make it start, just in case it hadn't already.
5505 stream.emit('readable');
5506}
5507
5508// wrap an old-style stream as the async data source.
5509// This is *not* part of the readable stream interface.
5510// It is an ugly unfortunate mess of history.
5511Readable.prototype.wrap = function(stream) {
5512 var state = this._readableState;
5513 var paused = false;
5514
5515 var self = this;
5516 stream.on('end', function() {
5517 if (state.decoder && !state.ended) {
5518 var chunk = state.decoder.end();
5519 if (chunk && chunk.length)
5520 self.push(chunk);
5521 }
5522
5523 self.push(null);
5524 });
5525
5526 stream.on('data', function(chunk) {
5527 if (state.decoder)
5528 chunk = state.decoder.write(chunk);
5529
5530 // don't skip over falsy values in objectMode
5531 //if (state.objectMode && util.isNullOrUndefined(chunk))
5532 if (state.objectMode && (chunk === null || chunk === undefined))
5533 return;
5534 else if (!state.objectMode && (!chunk || !chunk.length))
5535 return;
5536
5537 var ret = self.push(chunk);
5538 if (!ret) {
5539 paused = true;
5540 stream.pause();
5541 }
5542 });
5543
5544 // proxy all the other methods.
5545 // important when wrapping filters and duplexes.
5546 for (var i in stream) {
5547 if (typeof stream[i] === 'function' &&
5548 typeof this[i] === 'undefined') {
5549 this[i] = function(method) { return function() {
5550 return stream[method].apply(stream, arguments);
5551 }}(i);
5552 }
5553 }
5554
5555 // proxy certain important events.
5556 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
5557 forEach(events, function(ev) {
5558 stream.on(ev, self.emit.bind(self, ev));
5559 });
5560
5561 // when we try to consume some more bytes, simply unpause the
5562 // underlying stream.
5563 self._read = function(n) {
5564 if (paused) {
5565 paused = false;
5566 stream.resume();
5567 }
5568 };
5569
5570 return self;
5571};
5572
5573
5574
5575// exposed for testing purposes only.
5576Readable._fromList = fromList;
5577
5578// Pluck off n bytes from an array of buffers.
5579// Length is the combined lengths of all the buffers in the list.
5580function fromList(n, state) {
5581 var list = state.buffer;
5582 var length = state.length;
5583 var stringMode = !!state.decoder;
5584 var objectMode = !!state.objectMode;
5585 var ret;
5586
5587 // nothing in the list, definitely empty.
5588 if (list.length === 0)
5589 return null;
5590
5591 if (length === 0)
5592 ret = null;
5593 else if (objectMode)
5594 ret = list.shift();
5595 else if (!n || n >= length) {
5596 // read it all, truncate the array.
5597 if (stringMode)
5598 ret = list.join('');
5599 else
5600 ret = Buffer.concat(list, length);
5601 list.length = 0;
5602 } else {
5603 // read just some of it.
5604 if (n < list[0].length) {
5605 // just take a part of the first list item.
5606 // slice is the same for buffers and strings.
5607 var buf = list[0];
5608 ret = buf.slice(0, n);
5609 list[0] = buf.slice(n);
5610 } else if (n === list[0].length) {
5611 // first list is a perfect match
5612 ret = list.shift();
5613 } else {
5614 // complex case.
5615 // we have enough to cover it, but it spans past the first buffer.
5616 if (stringMode)
5617 ret = '';
5618 else
5619 ret = new Buffer(n);
5620
5621 var c = 0;
5622 for (var i = 0, l = list.length; i < l && c < n; i++) {
5623 var buf = list[0];
5624 var cpy = Math.min(n - c, buf.length);
5625
5626 if (stringMode)
5627 ret += buf.slice(0, cpy);
5628 else
5629 buf.copy(ret, c, 0, cpy);
5630
5631 if (cpy < buf.length)
5632 list[0] = buf.slice(cpy);
5633 else
5634 list.shift();
5635
5636 c += cpy;
5637 }
5638 }
5639 }
5640
5641 return ret;
5642}
5643
5644function endReadable(stream) {
5645 var state = stream._readableState;
5646
5647 // If we get here before consuming all the bytes, then that is a
5648 // bug in node. Should never happen.
5649 if (state.length > 0)
5650 throw new Error('endReadable called on non-empty stream');
5651
5652 if (!state.endEmitted && state.calledRead) {
5653 state.ended = true;
5654 process.nextTick(function() {
5655 // Check that we didn't get one last unshift.
5656 if (!state.endEmitted && state.length === 0) {
5657 state.endEmitted = true;
5658 stream.readable = false;
5659 stream.emit('end');
5660 }
5661 });
5662 }
5663}
5664
5665function forEach (xs, f) {
5666 for (var i = 0, l = xs.length; i < l; i++) {
5667 f(xs[i], i);
5668 }
5669}
5670
5671function indexOf (xs, x) {
5672 for (var i = 0, l = xs.length; i < l; i++) {
5673 if (xs[i] === x) return i;
5674 }
5675 return -1;
5676}
5677
5678}).call(this,require('_process'))
5679},{"_process":31,"buffer":3,"core-util-is":42,"events":22,"inherits":28,"isarray":29,"stream":48,"string_decoder/":43}],40:[function(require,module,exports){
5680// Copyright Joyent, Inc. and other Node contributors.
5681//
5682// Permission is hereby granted, free of charge, to any person obtaining a
5683// copy of this software and associated documentation files (the
5684// "Software"), to deal in the Software without restriction, including
5685// without limitation the rights to use, copy, modify, merge, publish,
5686// distribute, sublicense, and/or sell copies of the Software, and to permit
5687// persons to whom the Software is furnished to do so, subject to the
5688// following conditions:
5689//
5690// The above copyright notice and this permission notice shall be included
5691// in all copies or substantial portions of the Software.
5692//
5693// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5694// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5695// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5696// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5697// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5698// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5699// USE OR OTHER DEALINGS IN THE SOFTWARE.
5700
5701
5702// a transform stream is a readable/writable stream where you do
5703// something with the data. Sometimes it's called a "filter",
5704// but that's not a great name for it, since that implies a thing where
5705// some bits pass through, and others are simply ignored. (That would
5706// be a valid example of a transform, of course.)
5707//
5708// While the output is causally related to the input, it's not a
5709// necessarily symmetric or synchronous transformation. For example,
5710// a zlib stream might take multiple plain-text writes(), and then
5711// emit a single compressed chunk some time in the future.
5712//
5713// Here's how this works:
5714//
5715// The Transform stream has all the aspects of the readable and writable
5716// stream classes. When you write(chunk), that calls _write(chunk,cb)
5717// internally, and returns false if there's a lot of pending writes
5718// buffered up. When you call read(), that calls _read(n) until
5719// there's enough pending readable data buffered up.
5720//
5721// In a transform stream, the written data is placed in a buffer. When
5722// _read(n) is called, it transforms the queued up data, calling the
5723// buffered _write cb's as it consumes chunks. If consuming a single
5724// written chunk would result in multiple output chunks, then the first
5725// outputted bit calls the readcb, and subsequent chunks just go into
5726// the read buffer, and will cause it to emit 'readable' if necessary.
5727//
5728// This way, back-pressure is actually determined by the reading side,
5729// since _read has to be called to start processing a new chunk. However,
5730// a pathological inflate type of transform can cause excessive buffering
5731// here. For example, imagine a stream where every byte of input is
5732// interpreted as an integer from 0-255, and then results in that many
5733// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
5734// 1kb of data being output. In this case, you could write a very small
5735// amount of input, and end up with a very large amount of output. In
5736// such a pathological inflating mechanism, there'd be no way to tell
5737// the system to stop doing the transform. A single 4MB write could
5738// cause the system to run out of memory.
5739//
5740// However, even in such a pathological case, only a single written chunk
5741// would be consumed, and then the rest would wait (un-transformed) until
5742// the results of the previous transformed chunk were consumed.
5743
5744module.exports = Transform;
5745
5746var Duplex = require('./_stream_duplex');
5747
5748/*<replacement>*/
5749var util = require('core-util-is');
5750util.inherits = require('inherits');
5751/*</replacement>*/
5752
5753util.inherits(Transform, Duplex);
5754
5755
5756function TransformState(options, stream) {
5757 this.afterTransform = function(er, data) {
5758 return afterTransform(stream, er, data);
5759 };
5760
5761 this.needTransform = false;
5762 this.transforming = false;
5763 this.writecb = null;
5764 this.writechunk = null;
5765}
5766
5767function afterTransform(stream, er, data) {
5768 var ts = stream._transformState;
5769 ts.transforming = false;
5770
5771 var cb = ts.writecb;
5772
5773 if (!cb)
5774 return stream.emit('error', new Error('no writecb in Transform class'));
5775
5776 ts.writechunk = null;
5777 ts.writecb = null;
5778
5779 if (data !== null && data !== undefined)
5780 stream.push(data);
5781
5782 if (cb)
5783 cb(er);
5784
5785 var rs = stream._readableState;
5786 rs.reading = false;
5787 if (rs.needReadable || rs.length < rs.highWaterMark) {
5788 stream._read(rs.highWaterMark);
5789 }
5790}
5791
5792
5793function Transform(options) {
5794 if (!(this instanceof Transform))
5795 return new Transform(options);
5796
5797 Duplex.call(this, options);
5798
5799 var ts = this._transformState = new TransformState(options, this);
5800
5801 // when the writable side finishes, then flush out anything remaining.
5802 var stream = this;
5803
5804 // start out asking for a readable event once data is transformed.
5805 this._readableState.needReadable = true;
5806
5807 // we have implemented the _read method, and done the other things
5808 // that Readable wants before the first _read call, so unset the
5809 // sync guard flag.
5810 this._readableState.sync = false;
5811
5812 this.once('finish', function() {
5813 if ('function' === typeof this._flush)
5814 this._flush(function(er) {
5815 done(stream, er);
5816 });
5817 else
5818 done(stream);
5819 });
5820}
5821
5822Transform.prototype.push = function(chunk, encoding) {
5823 this._transformState.needTransform = false;
5824 return Duplex.prototype.push.call(this, chunk, encoding);
5825};
5826
5827// This is the part where you do stuff!
5828// override this function in implementation classes.
5829// 'chunk' is an input chunk.
5830//
5831// Call `push(newChunk)` to pass along transformed output
5832// to the readable side. You may call 'push' zero or more times.
5833//
5834// Call `cb(err)` when you are done with this chunk. If you pass
5835// an error, then that'll put the hurt on the whole operation. If you
5836// never call cb(), then you'll never get another chunk.
5837Transform.prototype._transform = function(chunk, encoding, cb) {
5838 throw new Error('not implemented');
5839};
5840
5841Transform.prototype._write = function(chunk, encoding, cb) {
5842 var ts = this._transformState;
5843 ts.writecb = cb;
5844 ts.writechunk = chunk;
5845 ts.writeencoding = encoding;
5846 if (!ts.transforming) {
5847 var rs = this._readableState;
5848 if (ts.needTransform ||
5849 rs.needReadable ||
5850 rs.length < rs.highWaterMark)
5851 this._read(rs.highWaterMark);
5852 }
5853};
5854
5855// Doesn't matter what the args are here.
5856// _transform does all the work.
5857// That we got here means that the readable side wants more data.
5858Transform.prototype._read = function(n) {
5859 var ts = this._transformState;
5860
5861 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
5862 ts.transforming = true;
5863 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
5864 } else {
5865 // mark that we need a transform, so that any data that comes in
5866 // will get processed, now that we've asked for it.
5867 ts.needTransform = true;
5868 }
5869};
5870
5871
5872function done(stream, er) {
5873 if (er)
5874 return stream.emit('error', er);
5875
5876 // if there's nothing in the write buffer, then that means
5877 // that nothing more will ever be provided
5878 var ws = stream._writableState;
5879 var rs = stream._readableState;
5880 var ts = stream._transformState;
5881
5882 if (ws.length)
5883 throw new Error('calling transform done when ws.length != 0');
5884
5885 if (ts.transforming)
5886 throw new Error('calling transform done when still transforming');
5887
5888 return stream.push(null);
5889}
5890
5891},{"./_stream_duplex":37,"core-util-is":42,"inherits":28}],41:[function(require,module,exports){
5892(function (process){
5893// Copyright Joyent, Inc. and other Node contributors.
5894//
5895// Permission is hereby granted, free of charge, to any person obtaining a
5896// copy of this software and associated documentation files (the
5897// "Software"), to deal in the Software without restriction, including
5898// without limitation the rights to use, copy, modify, merge, publish,
5899// distribute, sublicense, and/or sell copies of the Software, and to permit
5900// persons to whom the Software is furnished to do so, subject to the
5901// following conditions:
5902//
5903// The above copyright notice and this permission notice shall be included
5904// in all copies or substantial portions of the Software.
5905//
5906// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5907// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5908// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5909// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5910// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5911// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5912// USE OR OTHER DEALINGS IN THE SOFTWARE.
5913
5914// A bit simpler than readable streams.
5915// Implement an async ._write(chunk, cb), and it'll handle all
5916// the drain event emission and buffering.
5917
5918module.exports = Writable;
5919
5920/*<replacement>*/
5921var Buffer = require('buffer').Buffer;
5922/*</replacement>*/
5923
5924Writable.WritableState = WritableState;
5925
5926
5927/*<replacement>*/
5928var util = require('core-util-is');
5929util.inherits = require('inherits');
5930/*</replacement>*/
5931
5932var Stream = require('stream');
5933
5934util.inherits(Writable, Stream);
5935
5936function WriteReq(chunk, encoding, cb) {
5937 this.chunk = chunk;
5938 this.encoding = encoding;
5939 this.callback = cb;
5940}
5941
5942function WritableState(options, stream) {
5943 options = options || {};
5944
5945 // the point at which write() starts returning false
5946 // Note: 0 is a valid value, means that we always return false if
5947 // the entire buffer is not flushed immediately on write()
5948 var hwm = options.highWaterMark;
5949 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
5950
5951 // object stream flag to indicate whether or not this stream
5952 // contains buffers or objects.
5953 this.objectMode = !!options.objectMode;
5954
5955 // cast to ints.
5956 this.highWaterMark = ~~this.highWaterMark;
5957
5958 this.needDrain = false;
5959 // at the start of calling end()
5960 this.ending = false;
5961 // when end() has been called, and returned
5962 this.ended = false;
5963 // when 'finish' is emitted
5964 this.finished = false;
5965
5966 // should we decode strings into buffers before passing to _write?
5967 // this is here so that some node-core streams can optimize string
5968 // handling at a lower level.
5969 var noDecode = options.decodeStrings === false;
5970 this.decodeStrings = !noDecode;
5971
5972 // Crypto is kind of old and crusty. Historically, its default string
5973 // encoding is 'binary' so we have to make this configurable.
5974 // Everything else in the universe uses 'utf8', though.
5975 this.defaultEncoding = options.defaultEncoding || 'utf8';
5976
5977 // not an actual buffer we keep track of, but a measurement
5978 // of how much we're waiting to get pushed to some underlying
5979 // socket or file.
5980 this.length = 0;
5981
5982 // a flag to see when we're in the middle of a write.
5983 this.writing = false;
5984
5985 // a flag to be able to tell if the onwrite cb is called immediately,
5986 // or on a later tick. We set this to true at first, becuase any
5987 // actions that shouldn't happen until "later" should generally also
5988 // not happen before the first write call.
5989 this.sync = true;
5990
5991 // a flag to know if we're processing previously buffered items, which
5992 // may call the _write() callback in the same tick, so that we don't
5993 // end up in an overlapped onwrite situation.
5994 this.bufferProcessing = false;
5995
5996 // the callback that's passed to _write(chunk,cb)
5997 this.onwrite = function(er) {
5998 onwrite(stream, er);
5999 };
6000
6001 // the callback that the user supplies to write(chunk,encoding,cb)
6002 this.writecb = null;
6003
6004 // the amount that is being written when _write is called.
6005 this.writelen = 0;
6006
6007 this.buffer = [];
6008
6009 // True if the error was already emitted and should not be thrown again
6010 this.errorEmitted = false;
6011}
6012
6013function Writable(options) {
6014 var Duplex = require('./_stream_duplex');
6015
6016 // Writable ctor is applied to Duplexes, though they're not
6017 // instanceof Writable, they're instanceof Readable.
6018 if (!(this instanceof Writable) && !(this instanceof Duplex))
6019 return new Writable(options);
6020
6021 this._writableState = new WritableState(options, this);
6022
6023 // legacy.
6024 this.writable = true;
6025
6026 Stream.call(this);
6027}
6028
6029// Otherwise people can pipe Writable streams, which is just wrong.
6030Writable.prototype.pipe = function() {
6031 this.emit('error', new Error('Cannot pipe. Not readable.'));
6032};
6033
6034
6035function writeAfterEnd(stream, state, cb) {
6036 var er = new Error('write after end');
6037 // TODO: defer error events consistently everywhere, not just the cb
6038 stream.emit('error', er);
6039 process.nextTick(function() {
6040 cb(er);
6041 });
6042}
6043
6044// If we get something that is not a buffer, string, null, or undefined,
6045// and we're not in objectMode, then that's an error.
6046// Otherwise stream chunks are all considered to be of length=1, and the
6047// watermarks determine how many objects to keep in the buffer, rather than
6048// how many bytes or characters.
6049function validChunk(stream, state, chunk, cb) {
6050 var valid = true;
6051 if (!Buffer.isBuffer(chunk) &&
6052 'string' !== typeof chunk &&
6053 chunk !== null &&
6054 chunk !== undefined &&
6055 !state.objectMode) {
6056 var er = new TypeError('Invalid non-string/buffer chunk');
6057 stream.emit('error', er);
6058 process.nextTick(function() {
6059 cb(er);
6060 });
6061 valid = false;
6062 }
6063 return valid;
6064}
6065
6066Writable.prototype.write = function(chunk, encoding, cb) {
6067 var state = this._writableState;
6068 var ret = false;
6069
6070 if (typeof encoding === 'function') {
6071 cb = encoding;
6072 encoding = null;
6073 }
6074
6075 if (Buffer.isBuffer(chunk))
6076 encoding = 'buffer';
6077 else if (!encoding)
6078 encoding = state.defaultEncoding;
6079
6080 if (typeof cb !== 'function')
6081 cb = function() {};
6082
6083 if (state.ended)
6084 writeAfterEnd(this, state, cb);
6085 else if (validChunk(this, state, chunk, cb))
6086 ret = writeOrBuffer(this, state, chunk, encoding, cb);
6087
6088 return ret;
6089};
6090
6091function decodeChunk(state, chunk, encoding) {
6092 if (!state.objectMode &&
6093 state.decodeStrings !== false &&
6094 typeof chunk === 'string') {
6095 chunk = new Buffer(chunk, encoding);
6096 }
6097 return chunk;
6098}
6099
6100// if we're already writing something, then just put this
6101// in the queue, and wait our turn. Otherwise, call _write
6102// If we return false, then we need a drain event, so set that flag.
6103function writeOrBuffer(stream, state, chunk, encoding, cb) {
6104 chunk = decodeChunk(state, chunk, encoding);
6105 if (Buffer.isBuffer(chunk))
6106 encoding = 'buffer';
6107 var len = state.objectMode ? 1 : chunk.length;
6108
6109 state.length += len;
6110
6111 var ret = state.length < state.highWaterMark;
6112 // we must ensure that previous needDrain will not be reset to false.
6113 if (!ret)
6114 state.needDrain = true;
6115
6116 if (state.writing)
6117 state.buffer.push(new WriteReq(chunk, encoding, cb));
6118 else
6119 doWrite(stream, state, len, chunk, encoding, cb);
6120
6121 return ret;
6122}
6123
6124function doWrite(stream, state, len, chunk, encoding, cb) {
6125 state.writelen = len;
6126 state.writecb = cb;
6127 state.writing = true;
6128 state.sync = true;
6129 stream._write(chunk, encoding, state.onwrite);
6130 state.sync = false;
6131}
6132
6133function onwriteError(stream, state, sync, er, cb) {
6134 if (sync)
6135 process.nextTick(function() {
6136 cb(er);
6137 });
6138 else
6139 cb(er);
6140
6141 stream._writableState.errorEmitted = true;
6142 stream.emit('error', er);
6143}
6144
6145function onwriteStateUpdate(state) {
6146 state.writing = false;
6147 state.writecb = null;
6148 state.length -= state.writelen;
6149 state.writelen = 0;
6150}
6151
6152function onwrite(stream, er) {
6153 var state = stream._writableState;
6154 var sync = state.sync;
6155 var cb = state.writecb;
6156
6157 onwriteStateUpdate(state);
6158
6159 if (er)
6160 onwriteError(stream, state, sync, er, cb);
6161 else {
6162 // Check if we're actually ready to finish, but don't emit yet
6163 var finished = needFinish(stream, state);
6164
6165 if (!finished && !state.bufferProcessing && state.buffer.length)
6166 clearBuffer(stream, state);
6167
6168 if (sync) {
6169 process.nextTick(function() {
6170 afterWrite(stream, state, finished, cb);
6171 });
6172 } else {
6173 afterWrite(stream, state, finished, cb);
6174 }
6175 }
6176}
6177
6178function afterWrite(stream, state, finished, cb) {
6179 if (!finished)
6180 onwriteDrain(stream, state);
6181 cb();
6182 if (finished)
6183 finishMaybe(stream, state);
6184}
6185
6186// Must force callback to be called on nextTick, so that we don't
6187// emit 'drain' before the write() consumer gets the 'false' return
6188// value, and has a chance to attach a 'drain' listener.
6189function onwriteDrain(stream, state) {
6190 if (state.length === 0 && state.needDrain) {
6191 state.needDrain = false;
6192 stream.emit('drain');
6193 }
6194}
6195
6196
6197// if there's something in the buffer waiting, then process it
6198function clearBuffer(stream, state) {
6199 state.bufferProcessing = true;
6200
6201 for (var c = 0; c < state.buffer.length; c++) {
6202 var entry = state.buffer[c];
6203 var chunk = entry.chunk;
6204 var encoding = entry.encoding;
6205 var cb = entry.callback;
6206 var len = state.objectMode ? 1 : chunk.length;
6207
6208 doWrite(stream, state, len, chunk, encoding, cb);
6209
6210 // if we didn't call the onwrite immediately, then
6211 // it means that we need to wait until it does.
6212 // also, that means that the chunk and cb are currently
6213 // being processed, so move the buffer counter past them.
6214 if (state.writing) {
6215 c++;
6216 break;
6217 }
6218 }
6219
6220 state.bufferProcessing = false;
6221 if (c < state.buffer.length)
6222 state.buffer = state.buffer.slice(c);
6223 else
6224 state.buffer.length = 0;
6225}
6226
6227Writable.prototype._write = function(chunk, encoding, cb) {
6228 cb(new Error('not implemented'));
6229};
6230
6231Writable.prototype.end = function(chunk, encoding, cb) {
6232 var state = this._writableState;
6233
6234 if (typeof chunk === 'function') {
6235 cb = chunk;
6236 chunk = null;
6237 encoding = null;
6238 } else if (typeof encoding === 'function') {
6239 cb = encoding;
6240 encoding = null;
6241 }
6242
6243 if (typeof chunk !== 'undefined' && chunk !== null)
6244 this.write(chunk, encoding);
6245
6246 // ignore unnecessary end() calls.
6247 if (!state.ending && !state.finished)
6248 endWritable(this, state, cb);
6249};
6250
6251
6252function needFinish(stream, state) {
6253 return (state.ending &&
6254 state.length === 0 &&
6255 !state.finished &&
6256 !state.writing);
6257}
6258
6259function finishMaybe(stream, state) {
6260 var need = needFinish(stream, state);
6261 if (need) {
6262 state.finished = true;
6263 stream.emit('finish');
6264 }
6265 return need;
6266}
6267
6268function endWritable(stream, state, cb) {
6269 state.ending = true;
6270 finishMaybe(stream, state);
6271 if (cb) {
6272 if (state.finished)
6273 process.nextTick(cb);
6274 else
6275 stream.once('finish', cb);
6276 }
6277 state.ended = true;
6278}
6279
6280}).call(this,require('_process'))
6281},{"./_stream_duplex":37,"_process":31,"buffer":3,"core-util-is":42,"inherits":28,"stream":48}],42:[function(require,module,exports){
6282(function (Buffer){
6283// Copyright Joyent, Inc. and other Node contributors.
6284//
6285// Permission is hereby granted, free of charge, to any person obtaining a
6286// copy of this software and associated documentation files (the
6287// "Software"), to deal in the Software without restriction, including
6288// without limitation the rights to use, copy, modify, merge, publish,
6289// distribute, sublicense, and/or sell copies of the Software, and to permit
6290// persons to whom the Software is furnished to do so, subject to the
6291// following conditions:
6292//
6293// The above copyright notice and this permission notice shall be included
6294// in all copies or substantial portions of the Software.
6295//
6296// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6297// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6298// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6299// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6300// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6301// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6302// USE OR OTHER DEALINGS IN THE SOFTWARE.
6303
6304// NOTE: These type checking functions intentionally don't use `instanceof`
6305// because it is fragile and can be easily faked with `Object.create()`.
6306function isArray(ar) {
6307 return Array.isArray(ar);
6308}
6309exports.isArray = isArray;
6310
6311function isBoolean(arg) {
6312 return typeof arg === 'boolean';
6313}
6314exports.isBoolean = isBoolean;
6315
6316function isNull(arg) {
6317 return arg === null;
6318}
6319exports.isNull = isNull;
6320
6321function isNullOrUndefined(arg) {
6322 return arg == null;
6323}
6324exports.isNullOrUndefined = isNullOrUndefined;
6325
6326function isNumber(arg) {
6327 return typeof arg === 'number';
6328}
6329exports.isNumber = isNumber;
6330
6331function isString(arg) {
6332 return typeof arg === 'string';
6333}
6334exports.isString = isString;
6335
6336function isSymbol(arg) {
6337 return typeof arg === 'symbol';
6338}
6339exports.isSymbol = isSymbol;
6340
6341function isUndefined(arg) {
6342 return arg === void 0;
6343}
6344exports.isUndefined = isUndefined;
6345
6346function isRegExp(re) {
6347 return isObject(re) && objectToString(re) === '[object RegExp]';
6348}
6349exports.isRegExp = isRegExp;
6350
6351function isObject(arg) {
6352 return typeof arg === 'object' && arg !== null;
6353}
6354exports.isObject = isObject;
6355
6356function isDate(d) {
6357 return isObject(d) && objectToString(d) === '[object Date]';
6358}
6359exports.isDate = isDate;
6360
6361function isError(e) {
6362 return isObject(e) &&
6363 (objectToString(e) === '[object Error]' || e instanceof Error);
6364}
6365exports.isError = isError;
6366
6367function isFunction(arg) {
6368 return typeof arg === 'function';
6369}
6370exports.isFunction = isFunction;
6371
6372function isPrimitive(arg) {
6373 return arg === null ||
6374 typeof arg === 'boolean' ||
6375 typeof arg === 'number' ||
6376 typeof arg === 'string' ||
6377 typeof arg === 'symbol' || // ES6 symbol
6378 typeof arg === 'undefined';
6379}
6380exports.isPrimitive = isPrimitive;
6381
6382function isBuffer(arg) {
6383 return Buffer.isBuffer(arg);
6384}
6385exports.isBuffer = isBuffer;
6386
6387function objectToString(o) {
6388 return Object.prototype.toString.call(o);
6389}
6390}).call(this,require("buffer").Buffer)
6391},{"buffer":3}],43:[function(require,module,exports){
6392// Copyright Joyent, Inc. and other Node contributors.
6393//
6394// Permission is hereby granted, free of charge, to any person obtaining a
6395// copy of this software and associated documentation files (the
6396// "Software"), to deal in the Software without restriction, including
6397// without limitation the rights to use, copy, modify, merge, publish,
6398// distribute, sublicense, and/or sell copies of the Software, and to permit
6399// persons to whom the Software is furnished to do so, subject to the
6400// following conditions:
6401//
6402// The above copyright notice and this permission notice shall be included
6403// in all copies or substantial portions of the Software.
6404//
6405// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6406// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6407// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6408// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6409// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6410// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6411// USE OR OTHER DEALINGS IN THE SOFTWARE.
6412
6413var Buffer = require('buffer').Buffer;
6414
6415var isBufferEncoding = Buffer.isEncoding
6416 || function(encoding) {
6417 switch (encoding && encoding.toLowerCase()) {
6418 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
6419 default: return false;
6420 }
6421 }
6422
6423
6424function assertEncoding(encoding) {
6425 if (encoding && !isBufferEncoding(encoding)) {
6426 throw new Error('Unknown encoding: ' + encoding);
6427 }
6428}
6429
6430// StringDecoder provides an interface for efficiently splitting a series of
6431// buffers into a series of JS strings without breaking apart multi-byte
6432// characters. CESU-8 is handled as part of the UTF-8 encoding.
6433//
6434// @TODO Handling all encodings inside a single object makes it very difficult
6435// to reason about this code, so it should be split up in the future.
6436// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
6437// points as used by CESU-8.
6438var StringDecoder = exports.StringDecoder = function(encoding) {
6439 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
6440 assertEncoding(encoding);
6441 switch (this.encoding) {
6442 case 'utf8':
6443 // CESU-8 represents each of Surrogate Pair by 3-bytes
6444 this.surrogateSize = 3;
6445 break;
6446 case 'ucs2':
6447 case 'utf16le':
6448 // UTF-16 represents each of Surrogate Pair by 2-bytes
6449 this.surrogateSize = 2;
6450 this.detectIncompleteChar = utf16DetectIncompleteChar;
6451 break;
6452 case 'base64':
6453 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
6454 this.surrogateSize = 3;
6455 this.detectIncompleteChar = base64DetectIncompleteChar;
6456 break;
6457 default:
6458 this.write = passThroughWrite;
6459 return;
6460 }
6461
6462 // Enough space to store all bytes of a single character. UTF-8 needs 4
6463 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
6464 this.charBuffer = new Buffer(6);
6465 // Number of bytes received for the current incomplete multi-byte character.
6466 this.charReceived = 0;
6467 // Number of bytes expected for the current incomplete multi-byte character.
6468 this.charLength = 0;
6469};
6470
6471
6472// write decodes the given buffer and returns it as JS string that is
6473// guaranteed to not contain any partial multi-byte characters. Any partial
6474// character found at the end of the buffer is buffered up, and will be
6475// returned when calling write again with the remaining bytes.
6476//
6477// Note: Converting a Buffer containing an orphan surrogate to a String
6478// currently works, but converting a String to a Buffer (via `new Buffer`, or
6479// Buffer#write) will replace incomplete surrogates with the unicode
6480// replacement character. See https://codereview.chromium.org/121173009/ .
6481StringDecoder.prototype.write = function(buffer) {
6482 var charStr = '';
6483 // if our last write ended with an incomplete multibyte character
6484 while (this.charLength) {
6485 // determine how many remaining bytes this buffer has to offer for this char
6486 var available = (buffer.length >= this.charLength - this.charReceived) ?
6487 this.charLength - this.charReceived :
6488 buffer.length;
6489
6490 // add the new bytes to the char buffer
6491 buffer.copy(this.charBuffer, this.charReceived, 0, available);
6492 this.charReceived += available;
6493
6494 if (this.charReceived < this.charLength) {
6495 // still not enough chars in this buffer? wait for more ...
6496 return '';
6497 }
6498
6499 // remove bytes belonging to the current character from the buffer
6500 buffer = buffer.slice(available, buffer.length);
6501
6502 // get the character that was split
6503 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
6504
6505 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
6506 var charCode = charStr.charCodeAt(charStr.length - 1);
6507 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
6508 this.charLength += this.surrogateSize;
6509 charStr = '';
6510 continue;
6511 }
6512 this.charReceived = this.charLength = 0;
6513
6514 // if there are no more bytes in this buffer, just emit our char
6515 if (buffer.length === 0) {
6516 return charStr;
6517 }
6518 break;
6519 }
6520
6521 // determine and set charLength / charReceived
6522 this.detectIncompleteChar(buffer);
6523
6524 var end = buffer.length;
6525 if (this.charLength) {
6526 // buffer the incomplete character bytes we got
6527 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
6528 end -= this.charReceived;
6529 }
6530
6531 charStr += buffer.toString(this.encoding, 0, end);
6532
6533 var end = charStr.length - 1;
6534 var charCode = charStr.charCodeAt(end);
6535 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
6536 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
6537 var size = this.surrogateSize;
6538 this.charLength += size;
6539 this.charReceived += size;
6540 this.charBuffer.copy(this.charBuffer, size, 0, size);
6541 buffer.copy(this.charBuffer, 0, 0, size);
6542 return charStr.substring(0, end);
6543 }
6544
6545 // or just emit the charStr
6546 return charStr;
6547};
6548
6549// detectIncompleteChar determines if there is an incomplete UTF-8 character at
6550// the end of the given buffer. If so, it sets this.charLength to the byte
6551// length that character, and sets this.charReceived to the number of bytes
6552// that are available for this character.
6553StringDecoder.prototype.detectIncompleteChar = function(buffer) {
6554 // determine how many bytes we have to check at the end of this buffer
6555 var i = (buffer.length >= 3) ? 3 : buffer.length;
6556
6557 // Figure out if one of the last i bytes of our buffer announces an
6558 // incomplete char.
6559 for (; i > 0; i--) {
6560 var c = buffer[buffer.length - i];
6561
6562 // See http://en.wikipedia.org/wiki/UTF-8#Description
6563
6564 // 110XXXXX
6565 if (i == 1 && c >> 5 == 0x06) {
6566 this.charLength = 2;
6567 break;
6568 }
6569
6570 // 1110XXXX
6571 if (i <= 2 && c >> 4 == 0x0E) {
6572 this.charLength = 3;
6573 break;
6574 }
6575
6576 // 11110XXX
6577 if (i <= 3 && c >> 3 == 0x1E) {
6578 this.charLength = 4;
6579 break;
6580 }
6581 }
6582 this.charReceived = i;
6583};
6584
6585StringDecoder.prototype.end = function(buffer) {
6586 var res = '';
6587 if (buffer && buffer.length)
6588 res = this.write(buffer);
6589
6590 if (this.charReceived) {
6591 var cr = this.charReceived;
6592 var buf = this.charBuffer;
6593 var enc = this.encoding;
6594 res += buf.slice(0, cr).toString(enc);
6595 }
6596
6597 return res;
6598};
6599
6600function passThroughWrite(buffer) {
6601 return buffer.toString(this.encoding);
6602}
6603
6604function utf16DetectIncompleteChar(buffer) {
6605 this.charReceived = buffer.length % 2;
6606 this.charLength = this.charReceived ? 2 : 0;
6607}
6608
6609function base64DetectIncompleteChar(buffer) {
6610 this.charReceived = buffer.length % 3;
6611 this.charLength = this.charReceived ? 3 : 0;
6612}
6613
6614},{"buffer":3}],44:[function(require,module,exports){
6615module.exports = require("./lib/_stream_passthrough.js")
6616
6617},{"./lib/_stream_passthrough.js":38}],45:[function(require,module,exports){
6618exports = module.exports = require('./lib/_stream_readable.js');
6619exports.Readable = exports;
6620exports.Writable = require('./lib/_stream_writable.js');
6621exports.Duplex = require('./lib/_stream_duplex.js');
6622exports.Transform = require('./lib/_stream_transform.js');
6623exports.PassThrough = require('./lib/_stream_passthrough.js');
6624
6625},{"./lib/_stream_duplex.js":37,"./lib/_stream_passthrough.js":38,"./lib/_stream_readable.js":39,"./lib/_stream_transform.js":40,"./lib/_stream_writable.js":41}],46:[function(require,module,exports){
6626module.exports = require("./lib/_stream_transform.js")
6627
6628},{"./lib/_stream_transform.js":40}],47:[function(require,module,exports){
6629module.exports = require("./lib/_stream_writable.js")
6630
6631},{"./lib/_stream_writable.js":41}],48:[function(require,module,exports){
6632// Copyright Joyent, Inc. and other Node contributors.
6633//
6634// Permission is hereby granted, free of charge, to any person obtaining a
6635// copy of this software and associated documentation files (the
6636// "Software"), to deal in the Software without restriction, including
6637// without limitation the rights to use, copy, modify, merge, publish,
6638// distribute, sublicense, and/or sell copies of the Software, and to permit
6639// persons to whom the Software is furnished to do so, subject to the
6640// following conditions:
6641//
6642// The above copyright notice and this permission notice shall be included
6643// in all copies or substantial portions of the Software.
6644//
6645// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6646// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6647// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6648// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6649// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6650// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6651// USE OR OTHER DEALINGS IN THE SOFTWARE.
6652
6653module.exports = Stream;
6654
6655var EE = require('events').EventEmitter;
6656var inherits = require('inherits');
6657
6658inherits(Stream, EE);
6659Stream.Readable = require('readable-stream/readable.js');
6660Stream.Writable = require('readable-stream/writable.js');
6661Stream.Duplex = require('readable-stream/duplex.js');
6662Stream.Transform = require('readable-stream/transform.js');
6663Stream.PassThrough = require('readable-stream/passthrough.js');
6664
6665// Backwards-compat with node 0.4.x
6666Stream.Stream = Stream;
6667
6668
6669
6670// old-style streams. Note that the pipe method (the only relevant
6671// part of this class) is overridden in the Readable class.
6672
6673function Stream() {
6674 EE.call(this);
6675}
6676
6677Stream.prototype.pipe = function(dest, options) {
6678 var source = this;
6679
6680 function ondata(chunk) {
6681 if (dest.writable) {
6682 if (false === dest.write(chunk) && source.pause) {
6683 source.pause();
6684 }
6685 }
6686 }
6687
6688 source.on('data', ondata);
6689
6690 function ondrain() {
6691 if (source.readable && source.resume) {
6692 source.resume();
6693 }
6694 }
6695
6696 dest.on('drain', ondrain);
6697
6698 // If the 'end' option is not supplied, dest.end() will be called when
6699 // source gets the 'end' or 'close' events. Only dest.end() once.
6700 if (!dest._isStdio && (!options || options.end !== false)) {
6701 source.on('end', onend);
6702 source.on('close', onclose);
6703 }
6704
6705 var didOnEnd = false;
6706 function onend() {
6707 if (didOnEnd) return;
6708 didOnEnd = true;
6709
6710 dest.end();
6711 }
6712
6713
6714 function onclose() {
6715 if (didOnEnd) return;
6716 didOnEnd = true;
6717
6718 if (typeof dest.destroy === 'function') dest.destroy();
6719 }
6720
6721 // don't leave dangling pipes when there are errors.
6722 function onerror(er) {
6723 cleanup();
6724 if (EE.listenerCount(this, 'error') === 0) {
6725 throw er; // Unhandled stream error in pipe.
6726 }
6727 }
6728
6729 source.on('error', onerror);
6730 dest.on('error', onerror);
6731
6732 // remove all the event listeners that were added.
6733 function cleanup() {
6734 source.removeListener('data', ondata);
6735 dest.removeListener('drain', ondrain);
6736
6737 source.removeListener('end', onend);
6738 source.removeListener('close', onclose);
6739
6740 source.removeListener('error', onerror);
6741 dest.removeListener('error', onerror);
6742
6743 source.removeListener('end', cleanup);
6744 source.removeListener('close', cleanup);
6745
6746 dest.removeListener('close', cleanup);
6747 }
6748
6749 source.on('end', cleanup);
6750 source.on('close', cleanup);
6751
6752 dest.on('close', cleanup);
6753
6754 dest.emit('pipe', source);
6755
6756 // Allow for unix-like usage: A.pipe(B).pipe(C)
6757 return dest;
6758};
6759
6760},{"events":22,"inherits":28,"readable-stream/duplex.js":36,"readable-stream/passthrough.js":44,"readable-stream/readable.js":45,"readable-stream/transform.js":46,"readable-stream/writable.js":47}],49:[function(require,module,exports){
6761// Copyright Joyent, Inc. and other Node contributors.
6762//
6763// Permission is hereby granted, free of charge, to any person obtaining a
6764// copy of this software and associated documentation files (the
6765// "Software"), to deal in the Software without restriction, including
6766// without limitation the rights to use, copy, modify, merge, publish,
6767// distribute, sublicense, and/or sell copies of the Software, and to permit
6768// persons to whom the Software is furnished to do so, subject to the
6769// following conditions:
6770//
6771// The above copyright notice and this permission notice shall be included
6772// in all copies or substantial portions of the Software.
6773//
6774// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6775// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6776// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6777// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6778// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6779// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6780// USE OR OTHER DEALINGS IN THE SOFTWARE.
6781
6782var punycode = require('punycode');
6783
6784exports.parse = urlParse;
6785exports.resolve = urlResolve;
6786exports.resolveObject = urlResolveObject;
6787exports.format = urlFormat;
6788
6789exports.Url = Url;
6790
6791function Url() {
6792 this.protocol = null;
6793 this.slashes = null;
6794 this.auth = null;
6795 this.host = null;
6796 this.port = null;
6797 this.hostname = null;
6798 this.hash = null;
6799 this.search = null;
6800 this.query = null;
6801 this.pathname = null;
6802 this.path = null;
6803 this.href = null;
6804}
6805
6806// Reference: RFC 3986, RFC 1808, RFC 2396
6807
6808// define these here so at least they only have to be
6809// compiled once on the first module load.
6810var protocolPattern = /^([a-z0-9.+-]+:)/i,
6811 portPattern = /:[0-9]*$/,
6812
6813 // RFC 2396: characters reserved for delimiting URLs.
6814 // We actually just auto-escape these.
6815 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
6816
6817 // RFC 2396: characters not allowed for various reasons.
6818 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
6819
6820 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
6821 autoEscape = ['\''].concat(unwise),
6822 // Characters that are never ever allowed in a hostname.
6823 // Note that any invalid chars are also handled, but these
6824 // are the ones that are *expected* to be seen, so we fast-path
6825 // them.
6826 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
6827 hostEndingChars = ['/', '?', '#'],
6828 hostnameMaxLen = 255,
6829 hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/,
6830 hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,
6831 // protocols that can allow "unsafe" and "unwise" chars.
6832 unsafeProtocol = {
6833 'javascript': true,
6834 'javascript:': true
6835 },
6836 // protocols that never have a hostname.
6837 hostlessProtocol = {
6838 'javascript': true,
6839 'javascript:': true
6840 },
6841 // protocols that always contain a // bit.
6842 slashedProtocol = {
6843 'http': true,
6844 'https': true,
6845 'ftp': true,
6846 'gopher': true,
6847 'file': true,
6848 'http:': true,
6849 'https:': true,
6850 'ftp:': true,
6851 'gopher:': true,
6852 'file:': true
6853 },
6854 querystring = require('querystring');
6855
6856function urlParse(url, parseQueryString, slashesDenoteHost) {
6857 if (url && isObject(url) && url instanceof Url) return url;
6858
6859 var u = new Url;
6860 u.parse(url, parseQueryString, slashesDenoteHost);
6861 return u;
6862}
6863
6864Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
6865 if (!isString(url)) {
6866 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
6867 }
6868
6869 var rest = url;
6870
6871 // trim before proceeding.
6872 // This is to support parse stuff like " http://foo.com \n"
6873 rest = rest.trim();
6874
6875 var proto = protocolPattern.exec(rest);
6876 if (proto) {
6877 proto = proto[0];
6878 var lowerProto = proto.toLowerCase();
6879 this.protocol = lowerProto;
6880 rest = rest.substr(proto.length);
6881 }
6882
6883 // figure out if it's got a host
6884 // user@server is *always* interpreted as a hostname, and url
6885 // resolution will treat //foo/bar as host=foo,path=bar because that's
6886 // how the browser resolves relative URLs.
6887 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
6888 var slashes = rest.substr(0, 2) === '//';
6889 if (slashes && !(proto && hostlessProtocol[proto])) {
6890 rest = rest.substr(2);
6891 this.slashes = true;
6892 }
6893 }
6894
6895 if (!hostlessProtocol[proto] &&
6896 (slashes || (proto && !slashedProtocol[proto]))) {
6897
6898 // there's a hostname.
6899 // the first instance of /, ?, ;, or # ends the host.
6900 //
6901 // If there is an @ in the hostname, then non-host chars *are* allowed
6902 // to the left of the last @ sign, unless some host-ending character
6903 // comes *before* the @-sign.
6904 // URLs are obnoxious.
6905 //
6906 // ex:
6907 // http://a@b@c/ => user:a@b host:c
6908 // http://a@b?@c => user:a host:c path:/?@c
6909
6910 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
6911 // Review our test case against browsers more comprehensively.
6912
6913 // find the first instance of any hostEndingChars
6914 var hostEnd = -1;
6915 for (var i = 0; i < hostEndingChars.length; i++) {
6916 var hec = rest.indexOf(hostEndingChars[i]);
6917 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
6918 hostEnd = hec;
6919 }
6920
6921 // at this point, either we have an explicit point where the
6922 // auth portion cannot go past, or the last @ char is the decider.
6923 var auth, atSign;
6924 if (hostEnd === -1) {
6925 // atSign can be anywhere.
6926 atSign = rest.lastIndexOf('@');
6927 } else {
6928 // atSign must be in auth portion.
6929 // http://a@b/c@d => host:b auth:a path:/c@d
6930 atSign = rest.lastIndexOf('@', hostEnd);
6931 }
6932
6933 // Now we have a portion which is definitely the auth.
6934 // Pull that off.
6935 if (atSign !== -1) {
6936 auth = rest.slice(0, atSign);
6937 rest = rest.slice(atSign + 1);
6938 this.auth = decodeURIComponent(auth);
6939 }
6940
6941 // the host is the remaining to the left of the first non-host char
6942 hostEnd = -1;
6943 for (var i = 0; i < nonHostChars.length; i++) {
6944 var hec = rest.indexOf(nonHostChars[i]);
6945 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
6946 hostEnd = hec;
6947 }
6948 // if we still have not hit it, then the entire thing is a host.
6949 if (hostEnd === -1)
6950 hostEnd = rest.length;
6951
6952 this.host = rest.slice(0, hostEnd);
6953 rest = rest.slice(hostEnd);
6954
6955 // pull out port.
6956 this.parseHost();
6957
6958 // we've indicated that there is a hostname,
6959 // so even if it's empty, it has to be present.
6960 this.hostname = this.hostname || '';
6961
6962 // if hostname begins with [ and ends with ]
6963 // assume that it's an IPv6 address.
6964 var ipv6Hostname = this.hostname[0] === '[' &&
6965 this.hostname[this.hostname.length - 1] === ']';
6966
6967 // validate a little.
6968 if (!ipv6Hostname) {
6969 var hostparts = this.hostname.split(/\./);
6970 for (var i = 0, l = hostparts.length; i < l; i++) {
6971 var part = hostparts[i];
6972 if (!part) continue;
6973 if (!part.match(hostnamePartPattern)) {
6974 var newpart = '';
6975 for (var j = 0, k = part.length; j < k; j++) {
6976 if (part.charCodeAt(j) > 127) {
6977 // we replace non-ASCII char with a temporary placeholder
6978 // we need this to make sure size of hostname is not
6979 // broken by replacing non-ASCII by nothing
6980 newpart += 'x';
6981 } else {
6982 newpart += part[j];
6983 }
6984 }
6985 // we test again with ASCII char only
6986 if (!newpart.match(hostnamePartPattern)) {
6987 var validParts = hostparts.slice(0, i);
6988 var notHost = hostparts.slice(i + 1);
6989 var bit = part.match(hostnamePartStart);
6990 if (bit) {
6991 validParts.push(bit[1]);
6992 notHost.unshift(bit[2]);
6993 }
6994 if (notHost.length) {
6995 rest = '/' + notHost.join('.') + rest;
6996 }
6997 this.hostname = validParts.join('.');
6998 break;
6999 }
7000 }
7001 }
7002 }
7003
7004 if (this.hostname.length > hostnameMaxLen) {
7005 this.hostname = '';
7006 } else {
7007 // hostnames are always lower case.
7008 this.hostname = this.hostname.toLowerCase();
7009 }
7010
7011 if (!ipv6Hostname) {
7012 // IDNA Support: Returns a puny coded representation of "domain".
7013 // It only converts the part of the domain name that
7014 // has non ASCII characters. I.e. it dosent matter if
7015 // you call it with a domain that already is in ASCII.
7016 var domainArray = this.hostname.split('.');
7017 var newOut = [];
7018 for (var i = 0; i < domainArray.length; ++i) {
7019 var s = domainArray[i];
7020 newOut.push(s.match(/[^A-Za-z0-9_-]/) ?
7021 'xn--' + punycode.encode(s) : s);
7022 }
7023 this.hostname = newOut.join('.');
7024 }
7025
7026 var p = this.port ? ':' + this.port : '';
7027 var h = this.hostname || '';
7028 this.host = h + p;
7029 this.href += this.host;
7030
7031 // strip [ and ] from the hostname
7032 // the host field still retains them, though
7033 if (ipv6Hostname) {
7034 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
7035 if (rest[0] !== '/') {
7036 rest = '/' + rest;
7037 }
7038 }
7039 }
7040
7041 // now rest is set to the post-host stuff.
7042 // chop off any delim chars.
7043 if (!unsafeProtocol[lowerProto]) {
7044
7045 // First, make 100% sure that any "autoEscape" chars get
7046 // escaped, even if encodeURIComponent doesn't think they
7047 // need to be.
7048 for (var i = 0, l = autoEscape.length; i < l; i++) {
7049 var ae = autoEscape[i];
7050 var esc = encodeURIComponent(ae);
7051 if (esc === ae) {
7052 esc = escape(ae);
7053 }
7054 rest = rest.split(ae).join(esc);
7055 }
7056 }
7057
7058
7059 // chop off from the tail first.
7060 var hash = rest.indexOf('#');
7061 if (hash !== -1) {
7062 // got a fragment string.
7063 this.hash = rest.substr(hash);
7064 rest = rest.slice(0, hash);
7065 }
7066 var qm = rest.indexOf('?');
7067 if (qm !== -1) {
7068 this.search = rest.substr(qm);
7069 this.query = rest.substr(qm + 1);
7070 if (parseQueryString) {
7071 this.query = querystring.parse(this.query);
7072 }
7073 rest = rest.slice(0, qm);
7074 } else if (parseQueryString) {
7075 // no query string, but parseQueryString still requested
7076 this.search = '';
7077 this.query = {};
7078 }
7079 if (rest) this.pathname = rest;
7080 if (slashedProtocol[lowerProto] &&
7081 this.hostname && !this.pathname) {
7082 this.pathname = '/';
7083 }
7084
7085 //to support http.request
7086 if (this.pathname || this.search) {
7087 var p = this.pathname || '';
7088 var s = this.search || '';
7089 this.path = p + s;
7090 }
7091
7092 // finally, reconstruct the href based on what has been validated.
7093 this.href = this.format();
7094 return this;
7095};
7096
7097// format a parsed object into a url string
7098function urlFormat(obj) {
7099 // ensure it's an object, and not a string url.
7100 // If it's an obj, this is a no-op.
7101 // this way, you can call url_format() on strings
7102 // to clean up potentially wonky urls.
7103 if (isString(obj)) obj = urlParse(obj);
7104 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
7105 return obj.format();
7106}
7107
7108Url.prototype.format = function() {
7109 var auth = this.auth || '';
7110 if (auth) {
7111 auth = encodeURIComponent(auth);
7112 auth = auth.replace(/%3A/i, ':');
7113 auth += '@';
7114 }
7115
7116 var protocol = this.protocol || '',
7117 pathname = this.pathname || '',
7118 hash = this.hash || '',
7119 host = false,
7120 query = '';
7121
7122 if (this.host) {
7123 host = auth + this.host;
7124 } else if (this.hostname) {
7125 host = auth + (this.hostname.indexOf(':') === -1 ?
7126 this.hostname :
7127 '[' + this.hostname + ']');
7128 if (this.port) {
7129 host += ':' + this.port;
7130 }
7131 }
7132
7133 if (this.query &&
7134 isObject(this.query) &&
7135 Object.keys(this.query).length) {
7136 query = querystring.stringify(this.query);
7137 }
7138
7139 var search = this.search || (query && ('?' + query)) || '';
7140
7141 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
7142
7143 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
7144 // unless they had them to begin with.
7145 if (this.slashes ||
7146 (!protocol || slashedProtocol[protocol]) && host !== false) {
7147 host = '//' + (host || '');
7148 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
7149 } else if (!host) {
7150 host = '';
7151 }
7152
7153 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
7154 if (search && search.charAt(0) !== '?') search = '?' + search;
7155
7156 pathname = pathname.replace(/[?#]/g, function(match) {
7157 return encodeURIComponent(match);
7158 });
7159 search = search.replace('#', '%23');
7160
7161 return protocol + host + pathname + search + hash;
7162};
7163
7164function urlResolve(source, relative) {
7165 return urlParse(source, false, true).resolve(relative);
7166}
7167
7168Url.prototype.resolve = function(relative) {
7169 return this.resolveObject(urlParse(relative, false, true)).format();
7170};
7171
7172function urlResolveObject(source, relative) {
7173 if (!source) return relative;
7174 return urlParse(source, false, true).resolveObject(relative);
7175}
7176
7177Url.prototype.resolveObject = function(relative) {
7178 if (isString(relative)) {
7179 var rel = new Url();
7180 rel.parse(relative, false, true);
7181 relative = rel;
7182 }
7183
7184 var result = new Url();
7185 Object.keys(this).forEach(function(k) {
7186 result[k] = this[k];
7187 }, this);
7188
7189 // hash is always overridden, no matter what.
7190 // even href="" will remove it.
7191 result.hash = relative.hash;
7192
7193 // if the relative url is empty, then there's nothing left to do here.
7194 if (relative.href === '') {
7195 result.href = result.format();
7196 return result;
7197 }
7198
7199 // hrefs like //foo/bar always cut to the protocol.
7200 if (relative.slashes && !relative.protocol) {
7201 // take everything except the protocol from relative
7202 Object.keys(relative).forEach(function(k) {
7203 if (k !== 'protocol')
7204 result[k] = relative[k];
7205 });
7206
7207 //urlParse appends trailing / to urls like http://www.example.com
7208 if (slashedProtocol[result.protocol] &&
7209 result.hostname && !result.pathname) {
7210 result.path = result.pathname = '/';
7211 }
7212
7213 result.href = result.format();
7214 return result;
7215 }
7216
7217 if (relative.protocol && relative.protocol !== result.protocol) {
7218 // if it's a known url protocol, then changing
7219 // the protocol does weird things
7220 // first, if it's not file:, then we MUST have a host,
7221 // and if there was a path
7222 // to begin with, then we MUST have a path.
7223 // if it is file:, then the host is dropped,
7224 // because that's known to be hostless.
7225 // anything else is assumed to be absolute.
7226 if (!slashedProtocol[relative.protocol]) {
7227 Object.keys(relative).forEach(function(k) {
7228 result[k] = relative[k];
7229 });
7230 result.href = result.format();
7231 return result;
7232 }
7233
7234 result.protocol = relative.protocol;
7235 if (!relative.host && !hostlessProtocol[relative.protocol]) {
7236 var relPath = (relative.pathname || '').split('/');
7237 while (relPath.length && !(relative.host = relPath.shift()));
7238 if (!relative.host) relative.host = '';
7239 if (!relative.hostname) relative.hostname = '';
7240 if (relPath[0] !== '') relPath.unshift('');
7241 if (relPath.length < 2) relPath.unshift('');
7242 result.pathname = relPath.join('/');
7243 } else {
7244 result.pathname = relative.pathname;
7245 }
7246 result.search = relative.search;
7247 result.query = relative.query;
7248 result.host = relative.host || '';
7249 result.auth = relative.auth;
7250 result.hostname = relative.hostname || relative.host;
7251 result.port = relative.port;
7252 // to support http.request
7253 if (result.pathname || result.search) {
7254 var p = result.pathname || '';
7255 var s = result.search || '';
7256 result.path = p + s;
7257 }
7258 result.slashes = result.slashes || relative.slashes;
7259 result.href = result.format();
7260 return result;
7261 }
7262
7263 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
7264 isRelAbs = (
7265 relative.host ||
7266 relative.pathname && relative.pathname.charAt(0) === '/'
7267 ),
7268 mustEndAbs = (isRelAbs || isSourceAbs ||
7269 (result.host && relative.pathname)),
7270 removeAllDots = mustEndAbs,
7271 srcPath = result.pathname && result.pathname.split('/') || [],
7272 relPath = relative.pathname && relative.pathname.split('/') || [],
7273 psychotic = result.protocol && !slashedProtocol[result.protocol];
7274
7275 // if the url is a non-slashed url, then relative
7276 // links like ../.. should be able
7277 // to crawl up to the hostname, as well. This is strange.
7278 // result.protocol has already been set by now.
7279 // Later on, put the first path part into the host field.
7280 if (psychotic) {
7281 result.hostname = '';
7282 result.port = null;
7283 if (result.host) {
7284 if (srcPath[0] === '') srcPath[0] = result.host;
7285 else srcPath.unshift(result.host);
7286 }
7287 result.host = '';
7288 if (relative.protocol) {
7289 relative.hostname = null;
7290 relative.port = null;
7291 if (relative.host) {
7292 if (relPath[0] === '') relPath[0] = relative.host;
7293 else relPath.unshift(relative.host);
7294 }
7295 relative.host = null;
7296 }
7297 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
7298 }
7299
7300 if (isRelAbs) {
7301 // it's absolute.
7302 result.host = (relative.host || relative.host === '') ?
7303 relative.host : result.host;
7304 result.hostname = (relative.hostname || relative.hostname === '') ?
7305 relative.hostname : result.hostname;
7306 result.search = relative.search;
7307 result.query = relative.query;
7308 srcPath = relPath;
7309 // fall through to the dot-handling below.
7310 } else if (relPath.length) {
7311 // it's relative
7312 // throw away the existing file, and take the new path instead.
7313 if (!srcPath) srcPath = [];
7314 srcPath.pop();
7315 srcPath = srcPath.concat(relPath);
7316 result.search = relative.search;
7317 result.query = relative.query;
7318 } else if (!isNullOrUndefined(relative.search)) {
7319 // just pull out the search.
7320 // like href='?foo'.
7321 // Put this after the other two cases because it simplifies the booleans
7322 if (psychotic) {
7323 result.hostname = result.host = srcPath.shift();
7324 //occationaly the auth can get stuck only in host
7325 //this especialy happens in cases like
7326 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
7327 var authInHost = result.host && result.host.indexOf('@') > 0 ?
7328 result.host.split('@') : false;
7329 if (authInHost) {
7330 result.auth = authInHost.shift();
7331 result.host = result.hostname = authInHost.shift();
7332 }
7333 }
7334 result.search = relative.search;
7335 result.query = relative.query;
7336 //to support http.request
7337 if (!isNull(result.pathname) || !isNull(result.search)) {
7338 result.path = (result.pathname ? result.pathname : '') +
7339 (result.search ? result.search : '');
7340 }
7341 result.href = result.format();
7342 return result;
7343 }
7344
7345 if (!srcPath.length) {
7346 // no path at all. easy.
7347 // we've already handled the other stuff above.
7348 result.pathname = null;
7349 //to support http.request
7350 if (result.search) {
7351 result.path = '/' + result.search;
7352 } else {
7353 result.path = null;
7354 }
7355 result.href = result.format();
7356 return result;
7357 }
7358
7359 // if a url ENDs in . or .., then it must get a trailing slash.
7360 // however, if it ends in anything else non-slashy,
7361 // then it must NOT get a trailing slash.
7362 var last = srcPath.slice(-1)[0];
7363 var hasTrailingSlash = (
7364 (result.host || relative.host) && (last === '.' || last === '..') ||
7365 last === '');
7366
7367 // strip single dots, resolve double dots to parent dir
7368 // if the path tries to go above the root, `up` ends up > 0
7369 var up = 0;
7370 for (var i = srcPath.length; i >= 0; i--) {
7371 last = srcPath[i];
7372 if (last == '.') {
7373 srcPath.splice(i, 1);
7374 } else if (last === '..') {
7375 srcPath.splice(i, 1);
7376 up++;
7377 } else if (up) {
7378 srcPath.splice(i, 1);
7379 up--;
7380 }
7381 }
7382
7383 // if the path is allowed to go above the root, restore leading ..s
7384 if (!mustEndAbs && !removeAllDots) {
7385 for (; up--; up) {
7386 srcPath.unshift('..');
7387 }
7388 }
7389
7390 if (mustEndAbs && srcPath[0] !== '' &&
7391 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
7392 srcPath.unshift('');
7393 }
7394
7395 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
7396 srcPath.push('');
7397 }
7398
7399 var isAbsolute = srcPath[0] === '' ||
7400 (srcPath[0] && srcPath[0].charAt(0) === '/');
7401
7402 // put the host back
7403 if (psychotic) {
7404 result.hostname = result.host = isAbsolute ? '' :
7405 srcPath.length ? srcPath.shift() : '';
7406 //occationaly the auth can get stuck only in host
7407 //this especialy happens in cases like
7408 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
7409 var authInHost = result.host && result.host.indexOf('@') > 0 ?
7410 result.host.split('@') : false;
7411 if (authInHost) {
7412 result.auth = authInHost.shift();
7413 result.host = result.hostname = authInHost.shift();
7414 }
7415 }
7416
7417 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
7418
7419 if (mustEndAbs && !isAbsolute) {
7420 srcPath.unshift('');
7421 }
7422
7423 if (!srcPath.length) {
7424 result.pathname = null;
7425 result.path = null;
7426 } else {
7427 result.pathname = srcPath.join('/');
7428 }
7429
7430 //to support request.http
7431 if (!isNull(result.pathname) || !isNull(result.search)) {
7432 result.path = (result.pathname ? result.pathname : '') +
7433 (result.search ? result.search : '');
7434 }
7435 result.auth = relative.auth || result.auth;
7436 result.slashes = result.slashes || relative.slashes;
7437 result.href = result.format();
7438 return result;
7439};
7440
7441Url.prototype.parseHost = function() {
7442 var host = this.host;
7443 var port = portPattern.exec(host);
7444 if (port) {
7445 port = port[0];
7446 if (port !== ':') {
7447 this.port = port.substr(1);
7448 }
7449 host = host.substr(0, host.length - port.length);
7450 }
7451 if (host) this.hostname = host;
7452};
7453
7454function isString(arg) {
7455 return typeof arg === "string";
7456}
7457
7458function isObject(arg) {
7459 return typeof arg === 'object' && arg !== null;
7460}
7461
7462function isNull(arg) {
7463 return arg === null;
7464}
7465function isNullOrUndefined(arg) {
7466 return arg == null;
7467}
7468
7469},{"punycode":32,"querystring":35}],50:[function(require,module,exports){
7470module.exports = function isBuffer(arg) {
7471 return arg && typeof arg === 'object'
7472 && typeof arg.copy === 'function'
7473 && typeof arg.fill === 'function'
7474 && typeof arg.readUInt8 === 'function';
7475}
7476},{}],51:[function(require,module,exports){
7477(function (process,global){
7478// Copyright Joyent, Inc. and other Node contributors.
7479//
7480// Permission is hereby granted, free of charge, to any person obtaining a
7481// copy of this software and associated documentation files (the
7482// "Software"), to deal in the Software without restriction, including
7483// without limitation the rights to use, copy, modify, merge, publish,
7484// distribute, sublicense, and/or sell copies of the Software, and to permit
7485// persons to whom the Software is furnished to do so, subject to the
7486// following conditions:
7487//
7488// The above copyright notice and this permission notice shall be included
7489// in all copies or substantial portions of the Software.
7490//
7491// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7492// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7493// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7494// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7495// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7496// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7497// USE OR OTHER DEALINGS IN THE SOFTWARE.
7498
7499var formatRegExp = /%[sdj%]/g;
7500exports.format = function(f) {
7501 if (!isString(f)) {
7502 var objects = [];
7503 for (var i = 0; i < arguments.length; i++) {
7504 objects.push(inspect(arguments[i]));
7505 }
7506 return objects.join(' ');
7507 }
7508
7509 var i = 1;
7510 var args = arguments;
7511 var len = args.length;
7512 var str = String(f).replace(formatRegExp, function(x) {
7513 if (x === '%%') return '%';
7514 if (i >= len) return x;
7515 switch (x) {
7516 case '%s': return String(args[i++]);
7517 case '%d': return Number(args[i++]);
7518 case '%j':
7519 try {
7520 return JSON.stringify(args[i++]);
7521 } catch (_) {
7522 return '[Circular]';
7523 }
7524 default:
7525 return x;
7526 }
7527 });
7528 for (var x = args[i]; i < len; x = args[++i]) {
7529 if (isNull(x) || !isObject(x)) {
7530 str += ' ' + x;
7531 } else {
7532 str += ' ' + inspect(x);
7533 }
7534 }
7535 return str;
7536};
7537
7538
7539// Mark that a method should not be used.
7540// Returns a modified function which warns once by default.
7541// If --no-deprecation is set, then it is a no-op.
7542exports.deprecate = function(fn, msg) {
7543 // Allow for deprecating things in the process of starting up.
7544 if (isUndefined(global.process)) {
7545 return function() {
7546 return exports.deprecate(fn, msg).apply(this, arguments);
7547 };
7548 }
7549
7550 if (process.noDeprecation === true) {
7551 return fn;
7552 }
7553
7554 var warned = false;
7555 function deprecated() {
7556 if (!warned) {
7557 if (process.throwDeprecation) {
7558 throw new Error(msg);
7559 } else if (process.traceDeprecation) {
7560 console.trace(msg);
7561 } else {
7562 console.error(msg);
7563 }
7564 warned = true;
7565 }
7566 return fn.apply(this, arguments);
7567 }
7568
7569 return deprecated;
7570};
7571
7572
7573var debugs = {};
7574var debugEnviron;
7575exports.debuglog = function(set) {
7576 if (isUndefined(debugEnviron))
7577 debugEnviron = process.env.NODE_DEBUG || '';
7578 set = set.toUpperCase();
7579 if (!debugs[set]) {
7580 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
7581 var pid = process.pid;
7582 debugs[set] = function() {
7583 var msg = exports.format.apply(exports, arguments);
7584 console.error('%s %d: %s', set, pid, msg);
7585 };
7586 } else {
7587 debugs[set] = function() {};
7588 }
7589 }
7590 return debugs[set];
7591};
7592
7593
7594/**
7595 * Echos the value of a value. Trys to print the value out
7596 * in the best way possible given the different types.
7597 *
7598 * @param {Object} obj The object to print out.
7599 * @param {Object} opts Optional options object that alters the output.
7600 */
7601/* legacy: obj, showHidden, depth, colors*/
7602function inspect(obj, opts) {
7603 // default options
7604 var ctx = {
7605 seen: [],
7606 stylize: stylizeNoColor
7607 };
7608 // legacy...
7609 if (arguments.length >= 3) ctx.depth = arguments[2];
7610 if (arguments.length >= 4) ctx.colors = arguments[3];
7611 if (isBoolean(opts)) {
7612 // legacy...
7613 ctx.showHidden = opts;
7614 } else if (opts) {
7615 // got an "options" object
7616 exports._extend(ctx, opts);
7617 }
7618 // set default options
7619 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
7620 if (isUndefined(ctx.depth)) ctx.depth = 2;
7621 if (isUndefined(ctx.colors)) ctx.colors = false;
7622 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
7623 if (ctx.colors) ctx.stylize = stylizeWithColor;
7624 return formatValue(ctx, obj, ctx.depth);
7625}
7626exports.inspect = inspect;
7627
7628
7629// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
7630inspect.colors = {
7631 'bold' : [1, 22],
7632 'italic' : [3, 23],
7633 'underline' : [4, 24],
7634 'inverse' : [7, 27],
7635 'white' : [37, 39],
7636 'grey' : [90, 39],
7637 'black' : [30, 39],
7638 'blue' : [34, 39],
7639 'cyan' : [36, 39],
7640 'green' : [32, 39],
7641 'magenta' : [35, 39],
7642 'red' : [31, 39],
7643 'yellow' : [33, 39]
7644};
7645
7646// Don't use 'blue' not visible on cmd.exe
7647inspect.styles = {
7648 'special': 'cyan',
7649 'number': 'yellow',
7650 'boolean': 'yellow',
7651 'undefined': 'grey',
7652 'null': 'bold',
7653 'string': 'green',
7654 'date': 'magenta',
7655 // "name": intentionally not styling
7656 'regexp': 'red'
7657};
7658
7659
7660function stylizeWithColor(str, styleType) {
7661 var style = inspect.styles[styleType];
7662
7663 if (style) {
7664 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
7665 '\u001b[' + inspect.colors[style][1] + 'm';
7666 } else {
7667 return str;
7668 }
7669}
7670
7671
7672function stylizeNoColor(str, styleType) {
7673 return str;
7674}
7675
7676
7677function arrayToHash(array) {
7678 var hash = {};
7679
7680 array.forEach(function(val, idx) {
7681 hash[val] = true;
7682 });
7683
7684 return hash;
7685}
7686
7687
7688function formatValue(ctx, value, recurseTimes) {
7689 // Provide a hook for user-specified inspect functions.
7690 // Check that value is an object with an inspect function on it
7691 if (ctx.customInspect &&
7692 value &&
7693 isFunction(value.inspect) &&
7694 // Filter out the util module, it's inspect function is special
7695 value.inspect !== exports.inspect &&
7696 // Also filter out any prototype objects using the circular check.
7697 !(value.constructor && value.constructor.prototype === value)) {
7698 var ret = value.inspect(recurseTimes, ctx);
7699 if (!isString(ret)) {
7700 ret = formatValue(ctx, ret, recurseTimes);
7701 }
7702 return ret;
7703 }
7704
7705 // Primitive types cannot have properties
7706 var primitive = formatPrimitive(ctx, value);
7707 if (primitive) {
7708 return primitive;
7709 }
7710
7711 // Look up the keys of the object.
7712 var keys = Object.keys(value);
7713 var visibleKeys = arrayToHash(keys);
7714
7715 if (ctx.showHidden) {
7716 keys = Object.getOwnPropertyNames(value);
7717 }
7718
7719 // IE doesn't make error fields non-enumerable
7720 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
7721 if (isError(value)
7722 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
7723 return formatError(value);
7724 }
7725
7726 // Some type of object without properties can be shortcutted.
7727 if (keys.length === 0) {
7728 if (isFunction(value)) {
7729 var name = value.name ? ': ' + value.name : '';
7730 return ctx.stylize('[Function' + name + ']', 'special');
7731 }
7732 if (isRegExp(value)) {
7733 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7734 }
7735 if (isDate(value)) {
7736 return ctx.stylize(Date.prototype.toString.call(value), 'date');
7737 }
7738 if (isError(value)) {
7739 return formatError(value);
7740 }
7741 }
7742
7743 var base = '', array = false, braces = ['{', '}'];
7744
7745 // Make Array say that they are Array
7746 if (isArray(value)) {
7747 array = true;
7748 braces = ['[', ']'];
7749 }
7750
7751 // Make functions say that they are functions
7752 if (isFunction(value)) {
7753 var n = value.name ? ': ' + value.name : '';
7754 base = ' [Function' + n + ']';
7755 }
7756
7757 // Make RegExps say that they are RegExps
7758 if (isRegExp(value)) {
7759 base = ' ' + RegExp.prototype.toString.call(value);
7760 }
7761
7762 // Make dates with properties first say the date
7763 if (isDate(value)) {
7764 base = ' ' + Date.prototype.toUTCString.call(value);
7765 }
7766
7767 // Make error with message first say the error
7768 if (isError(value)) {
7769 base = ' ' + formatError(value);
7770 }
7771
7772 if (keys.length === 0 && (!array || value.length == 0)) {
7773 return braces[0] + base + braces[1];
7774 }
7775
7776 if (recurseTimes < 0) {
7777 if (isRegExp(value)) {
7778 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7779 } else {
7780 return ctx.stylize('[Object]', 'special');
7781 }
7782 }
7783
7784 ctx.seen.push(value);
7785
7786 var output;
7787 if (array) {
7788 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
7789 } else {
7790 output = keys.map(function(key) {
7791 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
7792 });
7793 }
7794
7795 ctx.seen.pop();
7796
7797 return reduceToSingleString(output, base, braces);
7798}
7799
7800
7801function formatPrimitive(ctx, value) {
7802 if (isUndefined(value))
7803 return ctx.stylize('undefined', 'undefined');
7804 if (isString(value)) {
7805 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
7806 .replace(/'/g, "\\'")
7807 .replace(/\\"/g, '"') + '\'';
7808 return ctx.stylize(simple, 'string');
7809 }
7810 if (isNumber(value))
7811 return ctx.stylize('' + value, 'number');
7812 if (isBoolean(value))
7813 return ctx.stylize('' + value, 'boolean');
7814 // For some reason typeof null is "object", so special case here.
7815 if (isNull(value))
7816 return ctx.stylize('null', 'null');
7817}
7818
7819
7820function formatError(value) {
7821 return '[' + Error.prototype.toString.call(value) + ']';
7822}
7823
7824
7825function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7826 var output = [];
7827 for (var i = 0, l = value.length; i < l; ++i) {
7828 if (hasOwnProperty(value, String(i))) {
7829 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7830 String(i), true));
7831 } else {
7832 output.push('');
7833 }
7834 }
7835 keys.forEach(function(key) {
7836 if (!key.match(/^\d+$/)) {
7837 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7838 key, true));
7839 }
7840 });
7841 return output;
7842}
7843
7844
7845function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7846 var name, str, desc;
7847 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7848 if (desc.get) {
7849 if (desc.set) {
7850 str = ctx.stylize('[Getter/Setter]', 'special');
7851 } else {
7852 str = ctx.stylize('[Getter]', 'special');
7853 }
7854 } else {
7855 if (desc.set) {
7856 str = ctx.stylize('[Setter]', 'special');
7857 }
7858 }
7859 if (!hasOwnProperty(visibleKeys, key)) {
7860 name = '[' + key + ']';
7861 }
7862 if (!str) {
7863 if (ctx.seen.indexOf(desc.value) < 0) {
7864 if (isNull(recurseTimes)) {
7865 str = formatValue(ctx, desc.value, null);
7866 } else {
7867 str = formatValue(ctx, desc.value, recurseTimes - 1);
7868 }
7869 if (str.indexOf('\n') > -1) {
7870 if (array) {
7871 str = str.split('\n').map(function(line) {
7872 return ' ' + line;
7873 }).join('\n').substr(2);
7874 } else {
7875 str = '\n' + str.split('\n').map(function(line) {
7876 return ' ' + line;
7877 }).join('\n');
7878 }
7879 }
7880 } else {
7881 str = ctx.stylize('[Circular]', 'special');
7882 }
7883 }
7884 if (isUndefined(name)) {
7885 if (array && key.match(/^\d+$/)) {
7886 return str;
7887 }
7888 name = JSON.stringify('' + key);
7889 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7890 name = name.substr(1, name.length - 2);
7891 name = ctx.stylize(name, 'name');
7892 } else {
7893 name = name.replace(/'/g, "\\'")
7894 .replace(/\\"/g, '"')
7895 .replace(/(^"|"$)/g, "'");
7896 name = ctx.stylize(name, 'string');
7897 }
7898 }
7899
7900 return name + ': ' + str;
7901}
7902
7903
7904function reduceToSingleString(output, base, braces) {
7905 var numLinesEst = 0;
7906 var length = output.reduce(function(prev, cur) {
7907 numLinesEst++;
7908 if (cur.indexOf('\n') >= 0) numLinesEst++;
7909 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7910 }, 0);
7911
7912 if (length > 60) {
7913 return braces[0] +
7914 (base === '' ? '' : base + '\n ') +
7915 ' ' +
7916 output.join(',\n ') +
7917 ' ' +
7918 braces[1];
7919 }
7920
7921 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7922}
7923
7924
7925// NOTE: These type checking functions intentionally don't use `instanceof`
7926// because it is fragile and can be easily faked with `Object.create()`.
7927function isArray(ar) {
7928 return Array.isArray(ar);
7929}
7930exports.isArray = isArray;
7931
7932function isBoolean(arg) {
7933 return typeof arg === 'boolean';
7934}
7935exports.isBoolean = isBoolean;
7936
7937function isNull(arg) {
7938 return arg === null;
7939}
7940exports.isNull = isNull;
7941
7942function isNullOrUndefined(arg) {
7943 return arg == null;
7944}
7945exports.isNullOrUndefined = isNullOrUndefined;
7946
7947function isNumber(arg) {
7948 return typeof arg === 'number';
7949}
7950exports.isNumber = isNumber;
7951
7952function isString(arg) {
7953 return typeof arg === 'string';
7954}
7955exports.isString = isString;
7956
7957function isSymbol(arg) {
7958 return typeof arg === 'symbol';
7959}
7960exports.isSymbol = isSymbol;
7961
7962function isUndefined(arg) {
7963 return arg === void 0;
7964}
7965exports.isUndefined = isUndefined;
7966
7967function isRegExp(re) {
7968 return isObject(re) && objectToString(re) === '[object RegExp]';
7969}
7970exports.isRegExp = isRegExp;
7971
7972function isObject(arg) {
7973 return typeof arg === 'object' && arg !== null;
7974}
7975exports.isObject = isObject;
7976
7977function isDate(d) {
7978 return isObject(d) && objectToString(d) === '[object Date]';
7979}
7980exports.isDate = isDate;
7981
7982function isError(e) {
7983 return isObject(e) &&
7984 (objectToString(e) === '[object Error]' || e instanceof Error);
7985}
7986exports.isError = isError;
7987
7988function isFunction(arg) {
7989 return typeof arg === 'function';
7990}
7991exports.isFunction = isFunction;
7992
7993function isPrimitive(arg) {
7994 return arg === null ||
7995 typeof arg === 'boolean' ||
7996 typeof arg === 'number' ||
7997 typeof arg === 'string' ||
7998 typeof arg === 'symbol' || // ES6 symbol
7999 typeof arg === 'undefined';
8000}
8001exports.isPrimitive = isPrimitive;
8002
8003exports.isBuffer = require('./support/isBuffer');
8004
8005function objectToString(o) {
8006 return Object.prototype.toString.call(o);
8007}
8008
8009
8010function pad(n) {
8011 return n < 10 ? '0' + n.toString(10) : n.toString(10);
8012}
8013
8014
8015var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
8016 'Oct', 'Nov', 'Dec'];
8017
8018// 26 Feb 16:19:34
8019function timestamp() {
8020 var d = new Date();
8021 var time = [pad(d.getHours()),
8022 pad(d.getMinutes()),
8023 pad(d.getSeconds())].join(':');
8024 return [d.getDate(), months[d.getMonth()], time].join(' ');
8025}
8026
8027
8028// log is just a thin wrapper to console.log that prepends a timestamp
8029exports.log = function() {
8030 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
8031};
8032
8033
8034/**
8035 * Inherit the prototype methods from one constructor into another.
8036 *
8037 * The Function.prototype.inherits from lang.js rewritten as a standalone
8038 * function (not on Function.prototype). NOTE: If this file is to be loaded
8039 * during bootstrapping this function needs to be rewritten using some native
8040 * functions as prototype setup using normal JavaScript does not work as
8041 * expected during bootstrapping (see mirror.js in r114903).
8042 *
8043 * @param {function} ctor Constructor function which needs to inherit the
8044 * prototype.
8045 * @param {function} superCtor Constructor function to inherit prototype from.
8046 */
8047exports.inherits = require('inherits');
8048
8049exports._extend = function(origin, add) {
8050 // Don't do anything if add isn't an object
8051 if (!add || !isObject(add)) return origin;
8052
8053 var keys = Object.keys(add);
8054 var i = keys.length;
8055 while (i--) {
8056 origin[keys[i]] = add[keys[i]];
8057 }
8058 return origin;
8059};
8060
8061function hasOwnProperty(obj, prop) {
8062 return Object.prototype.hasOwnProperty.call(obj, prop);
8063}
8064
8065}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8066},{"./support/isBuffer":50,"_process":31,"inherits":28}],52:[function(require,module,exports){
8067module.exports = require('./lib/jjv.js');
8068
8069},{"./lib/jjv.js":53}],53:[function(require,module,exports){
8070/* jshint proto: true */
8071
8072/**
8073 * jjv.js -- A javascript library to validate json input through a json-schema.
8074 *
8075 * Copyright (c) 2013 Alex Cornejo.
8076 *
8077 * Redistributable under a MIT-style open source license.
8078 */
8079
8080(function () {
8081 var clone = function (obj) {
8082 // Handle the 3 simple types (string, number, function), and null or undefined
8083 if (obj === null || typeof obj !== 'object') return obj;
8084 var copy;
8085
8086 // Handle Date
8087 if (obj instanceof Date) {
8088 copy = new Date();
8089 copy.setTime(obj.getTime());
8090 return copy;
8091 }
8092
8093 // handle RegExp
8094 if (obj instanceof RegExp) {
8095 copy = new RegExp(obj);
8096 return copy;
8097 }
8098
8099 // Handle Array
8100 if (obj instanceof Array) {
8101 copy = [];
8102 for (var i = 0, len = obj.length; i < len; i++)
8103 copy[i] = clone(obj[i]);
8104 return copy;
8105 }
8106
8107 // Handle Object
8108 if (obj instanceof Object) {
8109 copy = {};
8110// copy = Object.create(Object.getPrototypeOf(obj));
8111 for (var attr in obj) {
8112 if (obj.hasOwnProperty(attr))
8113 copy[attr] = clone(obj[attr]);
8114 }
8115 return copy;
8116 }
8117
8118 throw new Error("Unable to clone object!");
8119 };
8120
8121 var clone_stack = function (stack) {
8122 var new_stack = [ clone(stack[0]) ], key = new_stack[0].key, obj = new_stack[0].object;
8123 for (var i = 1, len = stack.length; i< len; i++) {
8124 obj = obj[key];
8125 key = stack[i].key;
8126 new_stack.push({ object: obj, key: key });
8127 }
8128 return new_stack;
8129 };
8130
8131 var copy_stack = function (new_stack, old_stack) {
8132 var stack_last = new_stack.length-1, key = new_stack[stack_last].key;
8133 old_stack[stack_last].object[key] = new_stack[stack_last].object[key];
8134 };
8135
8136 var handled = {
8137 'type': true,
8138 'not': true,
8139 'anyOf': true,
8140 'allOf': true,
8141 'oneOf': true,
8142 '$ref': true,
8143 '$schema': true,
8144 'id': true,
8145 'exclusiveMaximum': true,
8146 'exclusiveMininum': true,
8147 'properties': true,
8148 'patternProperties': true,
8149 'additionalProperties': true,
8150 'items': true,
8151 'additionalItems': true,
8152 'required': true,
8153 'default': true,
8154 'title': true,
8155 'description': true,
8156 'definitions': true,
8157 'dependencies': true
8158 };
8159
8160 var fieldType = {
8161 'null': function (x) {
8162 return x === null;
8163 },
8164 'string': function (x) {
8165 return typeof x === 'string';
8166 },
8167 'boolean': function (x) {
8168 return typeof x === 'boolean';
8169 },
8170 'number': function (x) {
8171 // Use x === x instead of !isNaN(x) for speed
8172 return typeof x === 'number' && x === x;
8173 },
8174 'integer': function (x) {
8175 return typeof x === 'number' && x%1 === 0;
8176 },
8177 'object': function (x) {
8178 return x && typeof x === 'object' && !Array.isArray(x);
8179 },
8180 'array': function (x) {
8181 return Array.isArray(x);
8182 },
8183 'date': function (x) {
8184 return x instanceof Date;
8185 }
8186 };
8187
8188 // missing: uri, date-time, ipv4, ipv6
8189 var fieldFormat = {
8190 'alpha': function (v) {
8191 return (/^[a-zA-Z]+$/).test(v);
8192 },
8193 'alphanumeric': function (v) {
8194 return (/^[a-zA-Z0-9]+$/).test(v);
8195 },
8196 'identifier': function (v) {
8197 return (/^[-_a-zA-Z0-9]+$/).test(v);
8198 },
8199 'hexadecimal': function (v) {
8200 return (/^[a-fA-F0-9]+$/).test(v);
8201 },
8202 'numeric': function (v) {
8203 return (/^[0-9]+$/).test(v);
8204 },
8205 'date-time': function (v) {
8206 return !isNaN(Date.parse(v)) && v.indexOf('/') === -1;
8207 },
8208 'uppercase': function (v) {
8209 return v === v.toUpperCase();
8210 },
8211 'lowercase': function (v) {
8212 return v === v.toLowerCase();
8213 },
8214 'hostname': function (v) {
8215 return v.length < 256 && (/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/).test(v);
8216 },
8217 'uri': function (v) {
8218 return (/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/).test(v);
8219 },
8220 'email': function (v) { // email, ipv4 and ipv6 adapted from node-validator
8221 return (/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/).test(v);
8222 },
8223 'ipv4': function (v) {
8224 if ((/^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/).test(v)) {
8225 var parts = v.split('.').sort();
8226 if (parts[3] <= 255)
8227 return true;
8228 }
8229 return false;
8230 },
8231 'ipv6': function(v) {
8232 return (/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/).test(v);
8233 /* return (/^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/).test(v); */
8234 }
8235 };
8236
8237 var fieldValidate = {
8238 'readOnly': function (v, p) {
8239 return false;
8240 },
8241 // ****** numeric validation ********
8242 'minimum': function (v, p, schema) {
8243 return !(v < p || schema.exclusiveMinimum && v <= p);
8244 },
8245 'maximum': function (v, p, schema) {
8246 return !(v > p || schema.exclusiveMaximum && v >= p);
8247 },
8248 'multipleOf': function (v, p) {
8249 return (v/p)%1 === 0 || typeof v !== 'number';
8250 },
8251 // ****** string validation ******
8252 'pattern': function (v, p) {
8253 if (typeof v !== 'string')
8254 return true;
8255 var pattern, modifiers;
8256 if (typeof p === 'string')
8257 pattern=p;
8258 else {
8259 pattern=p[0];
8260 modifiers=p[1];
8261 }
8262 var regex = new RegExp(pattern, modifiers);
8263 return regex.test(v);
8264 },
8265 'minLength': function (v, p) {
8266 return v.length >= p || typeof v !== 'string';
8267 },
8268 'maxLength': function (v, p) {
8269 return v.length <= p || typeof v !== 'string';
8270 },
8271 // ***** array validation *****
8272 'minItems': function (v, p) {
8273 return v.length >= p || !Array.isArray(v);
8274 },
8275 'maxItems': function (v, p) {
8276 return v.length <= p || !Array.isArray(v);
8277 },
8278 'uniqueItems': function (v, p) {
8279 var hash = {}, key;
8280 for (var i = 0, len = v.length; i < len; i++) {
8281 key = JSON.stringify(v[i]);
8282 if (hash.hasOwnProperty(key))
8283 return false;
8284 else
8285 hash[key] = true;
8286 }
8287 return true;
8288 },
8289 // ***** object validation ****
8290 'minProperties': function (v, p) {
8291 if (typeof v !== 'object')
8292 return true;
8293 var count = 0;
8294 for (var attr in v) if (v.hasOwnProperty(attr)) count = count + 1;
8295 return count >= p;
8296 },
8297 'maxProperties': function (v, p) {
8298 if (typeof v !== 'object')
8299 return true;
8300 var count = 0;
8301 for (var attr in v) if (v.hasOwnProperty(attr)) count = count + 1;
8302 return count <= p;
8303 },
8304 // ****** all *****
8305 'constant': function (v, p) {
8306 return JSON.stringify(v) == JSON.stringify(p);
8307 },
8308 'enum': function (v, p) {
8309 var i, len, vs;
8310 if (typeof v === 'object') {
8311 vs = JSON.stringify(v);
8312 for (i = 0, len = p.length; i < len; i++)
8313 if (vs === JSON.stringify(p[i]))
8314 return true;
8315 } else {
8316 for (i = 0, len = p.length; i < len; i++)
8317 if (v === p[i])
8318 return true;
8319 }
8320 return false;
8321 }
8322 };
8323
8324 var normalizeID = function (id) {
8325 return id.indexOf("://") === -1 ? id : id.split("#")[0];
8326 };
8327
8328 var resolveURI = function (env, schema_stack, uri) {
8329 var curschema, components, hash_idx, name;
8330
8331 hash_idx = uri.indexOf('#');
8332
8333 if (hash_idx === -1) {
8334 if (!env.schema.hasOwnProperty(uri))
8335 return null;
8336 return [env.schema[uri]];
8337 }
8338
8339 if (hash_idx > 0) {
8340 name = uri.substr(0, hash_idx);
8341 uri = uri.substr(hash_idx+1);
8342 if (!env.schema.hasOwnProperty(name)) {
8343 if (schema_stack && schema_stack[0].id === name)
8344 schema_stack = [schema_stack[0]];
8345 else
8346 return null;
8347 } else
8348 schema_stack = [env.schema[name]];
8349 } else {
8350 if (!schema_stack)
8351 return null;
8352 uri = uri.substr(1);
8353 }
8354
8355 if (uri === '')
8356 return [schema_stack[0]];
8357
8358 if (uri.charAt(0) === '/') {
8359 uri = uri.substr(1);
8360 curschema = schema_stack[0];
8361 components = uri.split('/');
8362 while (components.length > 0) {
8363 if (!curschema.hasOwnProperty(components[0]))
8364 return null;
8365 curschema = curschema[components[0]];
8366 schema_stack.push(curschema);
8367 components.shift();
8368 }
8369 return schema_stack;
8370 } else // FIX: should look for subschemas whose id matches uri
8371 return null;
8372 };
8373
8374 var resolveObjectRef = function (object_stack, uri) {
8375 var components, object, last_frame = object_stack.length-1, skip_frames, frame, m = /^(\d+)/.exec(uri);
8376
8377 if (m) {
8378 uri = uri.substr(m[0].length);
8379 skip_frames = parseInt(m[1], 10);
8380 if (skip_frames < 0 || skip_frames > last_frame)
8381 return;
8382 frame = object_stack[last_frame-skip_frames];
8383 if (uri === '#')
8384 return frame.key;
8385 } else
8386 frame = object_stack[0];
8387
8388 object = frame.object[frame.key];
8389
8390 if (uri === '')
8391 return object;
8392
8393 if (uri.charAt(0) === '/') {
8394 uri = uri.substr(1);
8395 components = uri.split('/');
8396 while (components.length > 0) {
8397 components[0] = components[0].replace(/~1/g, '/').replace(/~0/g, '~');
8398 if (!object.hasOwnProperty(components[0]))
8399 return;
8400 object = object[components[0]];
8401 components.shift();
8402 }
8403 return object;
8404 } else
8405 return;
8406 };
8407
8408 var checkValidity = function (env, schema_stack, object_stack, options) {
8409 var i, len, count, hasProp, hasPattern;
8410 var p, v, malformed = false, objerrs = {}, objerr, props, matched;
8411 var sl = schema_stack.length-1, schema = schema_stack[sl], new_stack;
8412 var ol = object_stack.length-1, object = object_stack[ol].object, name = object_stack[ol].key, prop = object[name];
8413 var errCount, minErrCount;
8414
8415 if (schema.hasOwnProperty('$ref')) {
8416 schema_stack= resolveURI(env, schema_stack, schema.$ref);
8417 if (!schema_stack)
8418 return {'$ref': schema.$ref};
8419 else
8420 return checkValidity(env, schema_stack, object_stack, options);
8421 }
8422
8423 if (schema.hasOwnProperty('type')) {
8424 if (typeof schema.type === 'string') {
8425 if (options.useCoerce && env.coerceType.hasOwnProperty(schema.type))
8426 prop = object[name] = env.coerceType[schema.type](prop);
8427 if (!env.fieldType[schema.type](prop))
8428 return {'type': schema.type};
8429 } else {
8430 malformed = true;
8431 for (i = 0, len = schema.type.length; i < len && malformed; i++)
8432 if (env.fieldType[schema.type[i]](prop))
8433 malformed = false;
8434 if (malformed)
8435 return {'type': schema.type};
8436 }
8437 }
8438
8439 if (schema.hasOwnProperty('allOf')) {
8440 for (i = 0, len = schema.allOf.length; i < len; i++) {
8441 objerr = checkValidity(env, schema_stack.concat(schema.allOf[i]), object_stack, options);
8442 if (objerr)
8443 return objerr;
8444 }
8445 }
8446
8447 if (!options.useCoerce && !options.useDefault && !options.removeAdditional) {
8448 if (schema.hasOwnProperty('oneOf')) {
8449 minErrCount = Infinity;
8450 for (i = 0, len = schema.oneOf.length, count = 0; i < len; i++) {
8451 objerr = checkValidity(env, schema_stack.concat(schema.oneOf[i]), object_stack, options);
8452 if (!objerr) {
8453 count = count + 1;
8454 if (count > 1)
8455 break;
8456 } else {
8457 errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
8458 if (errCount < minErrCount) {
8459 minErrCount = errCount;
8460 objerrs = objerr;
8461 }
8462 }
8463 }
8464 if (count > 1)
8465 return {'oneOf': true};
8466 else if (count < 1)
8467 return objerrs;
8468 objerrs = {};
8469 }
8470
8471 if (schema.hasOwnProperty('anyOf')) {
8472 objerrs = null;
8473 minErrCount = Infinity;
8474 for (i = 0, len = schema.anyOf.length; i < len; i++) {
8475 objerr = checkValidity(env, schema_stack.concat(schema.anyOf[i]), object_stack, options);
8476 if (!objerr) {
8477 objerrs = null;
8478 break;
8479 }
8480 else {
8481 errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
8482 if (errCount < minErrCount) {
8483 minErrCount = errCount;
8484 objerrs = objerr;
8485 }
8486 }
8487 }
8488 if (objerrs)
8489 return objerrs;
8490 }
8491
8492 if (schema.hasOwnProperty('not')) {
8493 objerr = checkValidity(env, schema_stack.concat(schema.not), object_stack, options);
8494 if (!objerr)
8495 return {'not': true};
8496 }
8497 } else {
8498 if (schema.hasOwnProperty('oneOf')) {
8499 minErrCount = Infinity;
8500 for (i = 0, len = schema.oneOf.length, count = 0; i < len; i++) {
8501 new_stack = clone_stack(object_stack);
8502 objerr = checkValidity(env, schema_stack.concat(schema.oneOf[i]), new_stack, options);
8503 if (!objerr) {
8504 count = count + 1;
8505 if (count > 1)
8506 break;
8507 else
8508 copy_stack(new_stack, object_stack);
8509 } else {
8510 errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
8511 if (errCount < minErrCount) {
8512 minErrCount = errCount;
8513 objerrs = objerr;
8514 }
8515 }
8516 }
8517 if (count > 1)
8518 return {'oneOf': true};
8519 else if (count < 1)
8520 return objerrs;
8521 objerrs = {};
8522 }
8523
8524 if (schema.hasOwnProperty('anyOf')) {
8525 objerrs = null;
8526 minErrCount = Infinity;
8527 for (i = 0, len = schema.anyOf.length; i < len; i++) {
8528 new_stack = clone_stack(object_stack);
8529 objerr = checkValidity(env, schema_stack.concat(schema.anyOf[i]), new_stack, options);
8530 if (!objerr) {
8531 copy_stack(new_stack, object_stack);
8532 objerrs = null;
8533 break;
8534 }
8535 else {
8536 errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
8537 if (errCount < minErrCount) {
8538 minErrCount = errCount;
8539 objerrs = objerr;
8540 }
8541 }
8542 }
8543 if (objerrs)
8544 return objerrs;
8545 }
8546
8547 if (schema.hasOwnProperty('not')) {
8548 new_stack = clone_stack(object_stack);
8549 objerr = checkValidity(env, schema_stack.concat(schema.not), new_stack, options);
8550 if (!objerr)
8551 return {'not': true};
8552 }
8553 }
8554
8555 if (schema.hasOwnProperty('dependencies')) {
8556 for (p in schema.dependencies)
8557 if (schema.dependencies.hasOwnProperty(p) && prop.hasOwnProperty(p)) {
8558 if (Array.isArray(schema.dependencies[p])) {
8559 for (i = 0, len = schema.dependencies[p].length; i < len; i++)
8560 if (!prop.hasOwnProperty(schema.dependencies[p][i])) {
8561 return {'dependencies': true};
8562 }
8563 } else {
8564 objerr = checkValidity(env, schema_stack.concat(schema.dependencies[p]), object_stack, options);
8565 if (objerr)
8566 return objerr;
8567 }
8568 }
8569 }
8570
8571 if (!Array.isArray(prop)) {
8572 props = [];
8573 objerrs = {};
8574 for (p in prop)
8575 if (prop.hasOwnProperty(p))
8576 props.push(p);
8577
8578 if (options.checkRequired && schema.required) {
8579 for (i = 0, len = schema.required.length; i < len; i++)
8580 if (!prop.hasOwnProperty(schema.required[i])) {
8581 objerrs[schema.required[i]] = {'required': true};
8582 malformed = true;
8583 }
8584 }
8585
8586 hasProp = schema.hasOwnProperty('properties');
8587 hasPattern = schema.hasOwnProperty('patternProperties');
8588 if (hasProp || hasPattern) {
8589 i = props.length;
8590 while (i--) {
8591 matched = false;
8592 if (hasProp && schema.properties.hasOwnProperty(props[i])) {
8593 matched = true;
8594 objerr = checkValidity(env, schema_stack.concat(schema.properties[props[i]]), object_stack.concat({object: prop, key: props[i]}), options);
8595 if (objerr !== null) {
8596 objerrs[props[i]] = objerr;
8597 malformed = true;
8598 }
8599 }
8600 if (hasPattern) {
8601 for (p in schema.patternProperties)
8602 if (schema.patternProperties.hasOwnProperty(p) && props[i].match(p)) {
8603 matched = true;
8604 objerr = checkValidity(env, schema_stack.concat(schema.patternProperties[p]), object_stack.concat({object: prop, key: props[i]}), options);
8605 if (objerr !== null) {
8606 objerrs[props[i]] = objerr;
8607 malformed = true;
8608 }
8609 }
8610 }
8611 if (matched)
8612 props.splice(i, 1);
8613 }
8614 }
8615
8616 if (options.useDefault && hasProp && !malformed) {
8617 for (p in schema.properties)
8618 if (schema.properties.hasOwnProperty(p) && !prop.hasOwnProperty(p) && schema.properties[p].hasOwnProperty('default'))
8619 prop[p] = schema.properties[p]['default'];
8620 }
8621
8622 if (options.removeAdditional && hasProp && schema.additionalProperties !== true && typeof schema.additionalProperties !== 'object') {
8623 for (i = 0, len = props.length; i < len; i++)
8624 delete prop[props[i]];
8625 } else {
8626 if (schema.hasOwnProperty('additionalProperties')) {
8627 if (typeof schema.additionalProperties === 'boolean') {
8628 if (!schema.additionalProperties) {
8629 for (i = 0, len = props.length; i < len; i++) {
8630 objerrs[props[i]] = {'additional': true};
8631 malformed = true;
8632 }
8633 }
8634 } else {
8635 for (i = 0, len = props.length; i < len; i++) {
8636 objerr = checkValidity(env, schema_stack.concat(schema.additionalProperties), object_stack.concat({object: prop, key: props[i]}), options);
8637 if (objerr !== null) {
8638 objerrs[props[i]] = objerr;
8639 malformed = true;
8640 }
8641 }
8642 }
8643 }
8644 }
8645 if (malformed)
8646 return {'schema': objerrs};
8647 } else {
8648 if (schema.hasOwnProperty('items')) {
8649 if (Array.isArray(schema.items)) {
8650 for (i = 0, len = schema.items.length; i < len; i++) {
8651 objerr = checkValidity(env, schema_stack.concat(schema.items[i]), object_stack.concat({object: prop, key: i}), options);
8652 if (objerr !== null) {
8653 objerrs[i] = objerr;
8654 malformed = true;
8655 }
8656 }
8657 if (prop.length > len && schema.hasOwnProperty('additionalItems')) {
8658 if (typeof schema.additionalItems === 'boolean') {
8659 if (!schema.additionalItems)
8660 return {'additionalItems': true};
8661 } else {
8662 for (i = len, len = prop.length; i < len; i++) {
8663 objerr = checkValidity(env, schema_stack.concat(schema.additionalItems), object_stack.concat({object: prop, key: i}), options);
8664 if (objerr !== null) {
8665 objerrs[i] = objerr;
8666 malformed = true;
8667 }
8668 }
8669 }
8670 }
8671 } else {
8672 for (i = 0, len = prop.length; i < len; i++) {
8673 objerr = checkValidity(env, schema_stack.concat(schema.items), object_stack.concat({object: prop, key: i}), options);
8674 if (objerr !== null) {
8675 objerrs[i] = objerr;
8676 malformed = true;
8677 }
8678 }
8679 }
8680 } else if (schema.hasOwnProperty('additionalItems')) {
8681 if (typeof schema.additionalItems !== 'boolean') {
8682 for (i = 0, len = prop.length; i < len; i++) {
8683 objerr = checkValidity(env, schema_stack.concat(schema.additionalItems), object_stack.concat({object: prop, key: i}), options);
8684 if (objerr !== null) {
8685 objerrs[i] = objerr;
8686 malformed = true;
8687 }
8688 }
8689 }
8690 }
8691 if (malformed)
8692 return {'schema': objerrs};
8693 }
8694
8695 for (v in schema) {
8696 if (schema.hasOwnProperty(v) && !handled.hasOwnProperty(v)) {
8697 if (v === 'format') {
8698 if (env.fieldFormat.hasOwnProperty(schema[v]) && !env.fieldFormat[schema[v]](prop, schema, object_stack, options)) {
8699 objerrs[v] = true;
8700 malformed = true;
8701 }
8702 } else {
8703 if (env.fieldValidate.hasOwnProperty(v) && !env.fieldValidate[v](prop, schema[v].hasOwnProperty('$data') ? resolveObjectRef(object_stack, schema[v].$data) : schema[v], schema, object_stack, options)) {
8704 objerrs[v] = true;
8705 malformed = true;
8706 }
8707 }
8708 }
8709 }
8710
8711 if (malformed)
8712 return objerrs;
8713 else
8714 return null;
8715 };
8716
8717 var defaultOptions = {
8718 useDefault: false,
8719 useCoerce: false,
8720 checkRequired: true,
8721 removeAdditional: false
8722 };
8723
8724 function Environment() {
8725 if (!(this instanceof Environment))
8726 return new Environment();
8727
8728 this.coerceType = {};
8729 this.fieldType = clone(fieldType);
8730 this.fieldValidate = clone(fieldValidate);
8731 this.fieldFormat = clone(fieldFormat);
8732 this.defaultOptions = clone(defaultOptions);
8733 this.schema = {};
8734 }
8735
8736 Environment.prototype = {
8737 validate: function (name, object, options) {
8738 var schema_stack = [name], errors = null, object_stack = [{object: {'__root__': object}, key: '__root__'}];
8739
8740 if (typeof name === 'string') {
8741 schema_stack = resolveURI(this, null, name);
8742 if (!schema_stack)
8743 throw new Error('jjv: could not find schema \'' + name + '\'.');
8744 }
8745
8746 if (!options) {
8747 options = this.defaultOptions;
8748 } else {
8749 for (var p in this.defaultOptions)
8750 if (this.defaultOptions.hasOwnProperty(p) && !options.hasOwnProperty(p))
8751 options[p] = this.defaultOptions[p];
8752 }
8753
8754 errors = checkValidity(this, schema_stack, object_stack, options);
8755
8756 if (errors)
8757 return {validation: errors.hasOwnProperty('schema') ? errors.schema : errors};
8758 else
8759 return null;
8760 },
8761
8762 resolveRef: function (schema_stack, $ref) {
8763 return resolveURI(this, schema_stack, $ref);
8764 },
8765
8766 addType: function (name, func) {
8767 this.fieldType[name] = func;
8768 },
8769
8770 addTypeCoercion: function (type, func) {
8771 this.coerceType[type] = func;
8772 },
8773
8774 addCheck: function (name, func) {
8775 this.fieldValidate[name] = func;
8776 },
8777
8778 addFormat: function (name, func) {
8779 this.fieldFormat[name] = func;
8780 },
8781
8782 addSchema: function (name, schema) {
8783 if (!schema && name) {
8784 schema = name;
8785 name = undefined;
8786 }
8787 if (schema.hasOwnProperty('id') && typeof schema.id === 'string' && schema.id !== name) {
8788 if (schema.id.charAt(0) === '/')
8789 throw new Error('jjv: schema id\'s starting with / are invalid.');
8790 this.schema[normalizeID(schema.id)] = schema;
8791 } else if (!name) {
8792 throw new Error('jjv: schema needs either a name or id attribute.');
8793 }
8794 if (name)
8795 this.schema[normalizeID(name)] = schema;
8796 }
8797 };
8798
8799 // Export for use in server and client.
8800 if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
8801 module.exports = Environment;
8802 else if (typeof define === 'function' && define.amd)
8803 define(function () {return Environment;});
8804 else
8805 this.jjv = Environment;
8806}).call(this);
8807
8808},{}],54:[function(require,module,exports){
8809(function (global){
8810/**
8811 * @license
8812 * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
8813 * Build: `lodash modern -o ./dist/lodash.js`
8814 * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
8815 * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
8816 * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
8817 * Available under MIT license <http://lodash.com/license>
8818 */
8819;(function() {
8820
8821 /** Used as a safe reference for `undefined` in pre ES5 environments */
8822 var undefined;
8823
8824 /** Used to pool arrays and objects used internally */
8825 var arrayPool = [],
8826 objectPool = [];
8827
8828 /** Used to generate unique IDs */
8829 var idCounter = 0;
8830
8831 /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
8832 var keyPrefix = +new Date + '';
8833
8834 /** Used as the size when optimizations are enabled for large arrays */
8835 var largeArraySize = 75;
8836
8837 /** Used as the max size of the `arrayPool` and `objectPool` */
8838 var maxPoolSize = 40;
8839
8840 /** Used to detect and test whitespace */
8841 var whitespace = (
8842 // whitespace
8843 ' \t\x0B\f\xA0\ufeff' +
8844
8845 // line terminators
8846 '\n\r\u2028\u2029' +
8847
8848 // unicode category "Zs" space separators
8849 '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'
8850 );
8851
8852 /** Used to match empty string literals in compiled template source */
8853 var reEmptyStringLeading = /\b__p \+= '';/g,
8854 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
8855 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
8856
8857 /**
8858 * Used to match ES6 template delimiters
8859 * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals
8860 */
8861 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
8862
8863 /** Used to match regexp flags from their coerced string values */
8864 var reFlags = /\w*$/;
8865
8866 /** Used to detected named functions */
8867 var reFuncName = /^\s*function[ \n\r\t]+\w/;
8868
8869 /** Used to match "interpolate" template delimiters */
8870 var reInterpolate = /<%=([\s\S]+?)%>/g;
8871
8872 /** Used to match leading whitespace and zeros to be removed */
8873 var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)');
8874
8875 /** Used to ensure capturing order of template delimiters */
8876 var reNoMatch = /($^)/;
8877
8878 /** Used to detect functions containing a `this` reference */
8879 var reThis = /\bthis\b/;
8880
8881 /** Used to match unescaped characters in compiled string literals */
8882 var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
8883
8884 /** Used to assign default `context` object properties */
8885 var contextProps = [
8886 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object',
8887 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN',
8888 'parseInt', 'setTimeout'
8889 ];
8890
8891 /** Used to make template sourceURLs easier to identify */
8892 var templateCounter = 0;
8893
8894 /** `Object#toString` result shortcuts */
8895 var argsClass = '[object Arguments]',
8896 arrayClass = '[object Array]',
8897 boolClass = '[object Boolean]',
8898 dateClass = '[object Date]',
8899 funcClass = '[object Function]',
8900 numberClass = '[object Number]',
8901 objectClass = '[object Object]',
8902 regexpClass = '[object RegExp]',
8903 stringClass = '[object String]';
8904
8905 /** Used to identify object classifications that `_.clone` supports */
8906 var cloneableClasses = {};
8907 cloneableClasses[funcClass] = false;
8908 cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
8909 cloneableClasses[boolClass] = cloneableClasses[dateClass] =
8910 cloneableClasses[numberClass] = cloneableClasses[objectClass] =
8911 cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
8912
8913 /** Used as an internal `_.debounce` options object */
8914 var debounceOptions = {
8915 'leading': false,
8916 'maxWait': 0,
8917 'trailing': false
8918 };
8919
8920 /** Used as the property descriptor for `__bindData__` */
8921 var descriptor = {
8922 'configurable': false,
8923 'enumerable': false,
8924 'value': null,
8925 'writable': false
8926 };
8927
8928 /** Used to determine if values are of the language type Object */
8929 var objectTypes = {
8930 'boolean': false,
8931 'function': true,
8932 'object': true,
8933 'number': false,
8934 'string': false,
8935 'undefined': false
8936 };
8937
8938 /** Used to escape characters for inclusion in compiled string literals */
8939 var stringEscapes = {
8940 '\\': '\\',
8941 "'": "'",
8942 '\n': 'n',
8943 '\r': 'r',
8944 '\t': 't',
8945 '\u2028': 'u2028',
8946 '\u2029': 'u2029'
8947 };
8948
8949 /** Used as a reference to the global object */
8950 var root = (objectTypes[typeof window] && window) || this;
8951
8952 /** Detect free variable `exports` */
8953 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
8954
8955 /** Detect free variable `module` */
8956 var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
8957
8958 /** Detect the popular CommonJS extension `module.exports` */
8959 var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
8960
8961 /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
8962 var freeGlobal = objectTypes[typeof global] && global;
8963 if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
8964 root = freeGlobal;
8965 }
8966
8967 /*--------------------------------------------------------------------------*/
8968
8969 /**
8970 * The base implementation of `_.indexOf` without support for binary searches
8971 * or `fromIndex` constraints.
8972 *
8973 * @private
8974 * @param {Array} array The array to search.
8975 * @param {*} value The value to search for.
8976 * @param {number} [fromIndex=0] The index to search from.
8977 * @returns {number} Returns the index of the matched value or `-1`.
8978 */
8979 function baseIndexOf(array, value, fromIndex) {
8980 var index = (fromIndex || 0) - 1,
8981 length = array ? array.length : 0;
8982
8983 while (++index < length) {
8984 if (array[index] === value) {
8985 return index;
8986 }
8987 }
8988 return -1;
8989 }
8990
8991 /**
8992 * An implementation of `_.contains` for cache objects that mimics the return
8993 * signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
8994 *
8995 * @private
8996 * @param {Object} cache The cache object to inspect.
8997 * @param {*} value The value to search for.
8998 * @returns {number} Returns `0` if `value` is found, else `-1`.
8999 */
9000 function cacheIndexOf(cache, value) {
9001 var type = typeof value;
9002 cache = cache.cache;
9003
9004 if (type == 'boolean' || value == null) {
9005 return cache[value] ? 0 : -1;
9006 }
9007 if (type != 'number' && type != 'string') {
9008 type = 'object';
9009 }
9010 var key = type == 'number' ? value : keyPrefix + value;
9011 cache = (cache = cache[type]) && cache[key];
9012
9013 return type == 'object'
9014 ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
9015 : (cache ? 0 : -1);
9016 }
9017
9018 /**
9019 * Adds a given value to the corresponding cache object.
9020 *
9021 * @private
9022 * @param {*} value The value to add to the cache.
9023 */
9024 function cachePush(value) {
9025 var cache = this.cache,
9026 type = typeof value;
9027
9028 if (type == 'boolean' || value == null) {
9029 cache[value] = true;
9030 } else {
9031 if (type != 'number' && type != 'string') {
9032 type = 'object';
9033 }
9034 var key = type == 'number' ? value : keyPrefix + value,
9035 typeCache = cache[type] || (cache[type] = {});
9036
9037 if (type == 'object') {
9038 (typeCache[key] || (typeCache[key] = [])).push(value);
9039 } else {
9040 typeCache[key] = true;
9041 }
9042 }
9043 }
9044
9045 /**
9046 * Used by `_.max` and `_.min` as the default callback when a given
9047 * collection is a string value.
9048 *
9049 * @private
9050 * @param {string} value The character to inspect.
9051 * @returns {number} Returns the code unit of given character.
9052 */
9053 function charAtCallback(value) {
9054 return value.charCodeAt(0);
9055 }
9056
9057 /**
9058 * Used by `sortBy` to compare transformed `collection` elements, stable sorting
9059 * them in ascending order.
9060 *
9061 * @private
9062 * @param {Object} a The object to compare to `b`.
9063 * @param {Object} b The object to compare to `a`.
9064 * @returns {number} Returns the sort order indicator of `1` or `-1`.
9065 */
9066 function compareAscending(a, b) {
9067 var ac = a.criteria,
9068 bc = b.criteria,
9069 index = -1,
9070 length = ac.length;
9071
9072 while (++index < length) {
9073 var value = ac[index],
9074 other = bc[index];
9075
9076 if (value !== other) {
9077 if (value > other || typeof value == 'undefined') {
9078 return 1;
9079 }
9080 if (value < other || typeof other == 'undefined') {
9081 return -1;
9082 }
9083 }
9084 }
9085 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
9086 // that causes it, under certain circumstances, to return the same value for
9087 // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247
9088 //
9089 // This also ensures a stable sort in V8 and other engines.
9090 // See http://code.google.com/p/v8/issues/detail?id=90
9091 return a.index - b.index;
9092 }
9093
9094 /**
9095 * Creates a cache object to optimize linear searches of large arrays.
9096 *
9097 * @private
9098 * @param {Array} [array=[]] The array to search.
9099 * @returns {null|Object} Returns the cache object or `null` if caching should not be used.
9100 */
9101 function createCache(array) {
9102 var index = -1,
9103 length = array.length,
9104 first = array[0],
9105 mid = array[(length / 2) | 0],
9106 last = array[length - 1];
9107
9108 if (first && typeof first == 'object' &&
9109 mid && typeof mid == 'object' && last && typeof last == 'object') {
9110 return false;
9111 }
9112 var cache = getObject();
9113 cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
9114
9115 var result = getObject();
9116 result.array = array;
9117 result.cache = cache;
9118 result.push = cachePush;
9119
9120 while (++index < length) {
9121 result.push(array[index]);
9122 }
9123 return result;
9124 }
9125
9126 /**
9127 * Used by `template` to escape characters for inclusion in compiled
9128 * string literals.
9129 *
9130 * @private
9131 * @param {string} match The matched character to escape.
9132 * @returns {string} Returns the escaped character.
9133 */
9134 function escapeStringChar(match) {
9135 return '\\' + stringEscapes[match];
9136 }
9137
9138 /**
9139 * Gets an array from the array pool or creates a new one if the pool is empty.
9140 *
9141 * @private
9142 * @returns {Array} The array from the pool.
9143 */
9144 function getArray() {
9145 return arrayPool.pop() || [];
9146 }
9147
9148 /**
9149 * Gets an object from the object pool or creates a new one if the pool is empty.
9150 *
9151 * @private
9152 * @returns {Object} The object from the pool.
9153 */
9154 function getObject() {
9155 return objectPool.pop() || {
9156 'array': null,
9157 'cache': null,
9158 'criteria': null,
9159 'false': false,
9160 'index': 0,
9161 'null': false,
9162 'number': null,
9163 'object': null,
9164 'push': null,
9165 'string': null,
9166 'true': false,
9167 'undefined': false,
9168 'value': null
9169 };
9170 }
9171
9172 /**
9173 * Releases the given array back to the array pool.
9174 *
9175 * @private
9176 * @param {Array} [array] The array to release.
9177 */
9178 function releaseArray(array) {
9179 array.length = 0;
9180 if (arrayPool.length < maxPoolSize) {
9181 arrayPool.push(array);
9182 }
9183 }
9184
9185 /**
9186 * Releases the given object back to the object pool.
9187 *
9188 * @private
9189 * @param {Object} [object] The object to release.
9190 */
9191 function releaseObject(object) {
9192 var cache = object.cache;
9193 if (cache) {
9194 releaseObject(cache);
9195 }
9196 object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null;
9197 if (objectPool.length < maxPoolSize) {
9198 objectPool.push(object);
9199 }
9200 }
9201
9202 /**
9203 * Slices the `collection` from the `start` index up to, but not including,
9204 * the `end` index.
9205 *
9206 * Note: This function is used instead of `Array#slice` to support node lists
9207 * in IE < 9 and to ensure dense arrays are returned.
9208 *
9209 * @private
9210 * @param {Array|Object|string} collection The collection to slice.
9211 * @param {number} start The start index.
9212 * @param {number} end The end index.
9213 * @returns {Array} Returns the new array.
9214 */
9215 function slice(array, start, end) {
9216 start || (start = 0);
9217 if (typeof end == 'undefined') {
9218 end = array ? array.length : 0;
9219 }
9220 var index = -1,
9221 length = end - start || 0,
9222 result = Array(length < 0 ? 0 : length);
9223
9224 while (++index < length) {
9225 result[index] = array[start + index];
9226 }
9227 return result;
9228 }
9229
9230 /*--------------------------------------------------------------------------*/
9231
9232 /**
9233 * Create a new `lodash` function using the given context object.
9234 *
9235 * @static
9236 * @memberOf _
9237 * @category Utilities
9238 * @param {Object} [context=root] The context object.
9239 * @returns {Function} Returns the `lodash` function.
9240 */
9241 function runInContext(context) {
9242 // Avoid issues with some ES3 environments that attempt to use values, named
9243 // after built-in constructors like `Object`, for the creation of literals.
9244 // ES5 clears this up by stating that literals must use built-in constructors.
9245 // See http://es5.github.io/#x11.1.5.
9246 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
9247
9248 /** Native constructor references */
9249 var Array = context.Array,
9250 Boolean = context.Boolean,
9251 Date = context.Date,
9252 Function = context.Function,
9253 Math = context.Math,
9254 Number = context.Number,
9255 Object = context.Object,
9256 RegExp = context.RegExp,
9257 String = context.String,
9258 TypeError = context.TypeError;
9259
9260 /**
9261 * Used for `Array` method references.
9262 *
9263 * Normally `Array.prototype` would suffice, however, using an array literal
9264 * avoids issues in Narwhal.
9265 */
9266 var arrayRef = [];
9267
9268 /** Used for native method references */
9269 var objectProto = Object.prototype;
9270
9271 /** Used to restore the original `_` reference in `noConflict` */
9272 var oldDash = context._;
9273
9274 /** Used to resolve the internal [[Class]] of values */
9275 var toString = objectProto.toString;
9276
9277 /** Used to detect if a method is native */
9278 var reNative = RegExp('^' +
9279 String(toString)
9280 .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
9281 .replace(/toString| for [^\]]+/g, '.*?') + '$'
9282 );
9283
9284 /** Native method shortcuts */
9285 var ceil = Math.ceil,
9286 clearTimeout = context.clearTimeout,
9287 floor = Math.floor,
9288 fnToString = Function.prototype.toString,
9289 getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
9290 hasOwnProperty = objectProto.hasOwnProperty,
9291 push = arrayRef.push,
9292 setTimeout = context.setTimeout,
9293 splice = arrayRef.splice,
9294 unshift = arrayRef.unshift;
9295
9296 /** Used to set meta data on functions */
9297 var defineProperty = (function() {
9298 // IE 8 only accepts DOM elements
9299 try {
9300 var o = {},
9301 func = isNative(func = Object.defineProperty) && func,
9302 result = func(o, o, o) && func;
9303 } catch(e) { }
9304 return result;
9305 }());
9306
9307 /* Native method shortcuts for methods with the same name as other `lodash` methods */
9308 var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
9309 nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
9310 nativeIsFinite = context.isFinite,
9311 nativeIsNaN = context.isNaN,
9312 nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
9313 nativeMax = Math.max,
9314 nativeMin = Math.min,
9315 nativeParseInt = context.parseInt,
9316 nativeRandom = Math.random;
9317
9318 /** Used to lookup a built-in constructor by [[Class]] */
9319 var ctorByClass = {};
9320 ctorByClass[arrayClass] = Array;
9321 ctorByClass[boolClass] = Boolean;
9322 ctorByClass[dateClass] = Date;
9323 ctorByClass[funcClass] = Function;
9324 ctorByClass[objectClass] = Object;
9325 ctorByClass[numberClass] = Number;
9326 ctorByClass[regexpClass] = RegExp;
9327 ctorByClass[stringClass] = String;
9328
9329 /*--------------------------------------------------------------------------*/
9330
9331 /**
9332 * Creates a `lodash` object which wraps the given value to enable intuitive
9333 * method chaining.
9334 *
9335 * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
9336 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
9337 * and `unshift`
9338 *
9339 * Chaining is supported in custom builds as long as the `value` method is
9340 * implicitly or explicitly included in the build.
9341 *
9342 * The chainable wrapper functions are:
9343 * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
9344 * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
9345 * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
9346 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
9347 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
9348 * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
9349 * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
9350 * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
9351 * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
9352 * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
9353 * and `zip`
9354 *
9355 * The non-chainable wrapper functions are:
9356 * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
9357 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
9358 * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
9359 * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
9360 * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
9361 * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
9362 * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
9363 * `template`, `unescape`, `uniqueId`, and `value`
9364 *
9365 * The wrapper functions `first` and `last` return wrapped values when `n` is
9366 * provided, otherwise they return unwrapped values.
9367 *
9368 * Explicit chaining can be enabled by using the `_.chain` method.
9369 *
9370 * @name _
9371 * @constructor
9372 * @category Chaining
9373 * @param {*} value The value to wrap in a `lodash` instance.
9374 * @returns {Object} Returns a `lodash` instance.
9375 * @example
9376 *
9377 * var wrapped = _([1, 2, 3]);
9378 *
9379 * // returns an unwrapped value
9380 * wrapped.reduce(function(sum, num) {
9381 * return sum + num;
9382 * });
9383 * // => 6
9384 *
9385 * // returns a wrapped value
9386 * var squares = wrapped.map(function(num) {
9387 * return num * num;
9388 * });
9389 *
9390 * _.isArray(squares);
9391 * // => false
9392 *
9393 * _.isArray(squares.value());
9394 * // => true
9395 */
9396 function lodash(value) {
9397 // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
9398 return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
9399 ? value
9400 : new lodashWrapper(value);
9401 }
9402
9403 /**
9404 * A fast path for creating `lodash` wrapper objects.
9405 *
9406 * @private
9407 * @param {*} value The value to wrap in a `lodash` instance.
9408 * @param {boolean} chainAll A flag to enable chaining for all methods
9409 * @returns {Object} Returns a `lodash` instance.
9410 */
9411 function lodashWrapper(value, chainAll) {
9412 this.__chain__ = !!chainAll;
9413 this.__wrapped__ = value;
9414 }
9415 // ensure `new lodashWrapper` is an instance of `lodash`
9416 lodashWrapper.prototype = lodash.prototype;
9417
9418 /**
9419 * An object used to flag environments features.
9420 *
9421 * @static
9422 * @memberOf _
9423 * @type Object
9424 */
9425 var support = lodash.support = {};
9426
9427 /**
9428 * Detect if functions can be decompiled by `Function#toString`
9429 * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
9430 *
9431 * @memberOf _.support
9432 * @type boolean
9433 */
9434 support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);
9435
9436 /**
9437 * Detect if `Function#name` is supported (all but IE).
9438 *
9439 * @memberOf _.support
9440 * @type boolean
9441 */
9442 support.funcNames = typeof Function.name == 'string';
9443
9444 /**
9445 * By default, the template delimiters used by Lo-Dash are similar to those in
9446 * embedded Ruby (ERB). Change the following template settings to use alternative
9447 * delimiters.
9448 *
9449 * @static
9450 * @memberOf _
9451 * @type Object
9452 */
9453 lodash.templateSettings = {
9454
9455 /**
9456 * Used to detect `data` property values to be HTML-escaped.
9457 *
9458 * @memberOf _.templateSettings
9459 * @type RegExp
9460 */
9461 'escape': /<%-([\s\S]+?)%>/g,
9462
9463 /**
9464 * Used to detect code to be evaluated.
9465 *
9466 * @memberOf _.templateSettings
9467 * @type RegExp
9468 */
9469 'evaluate': /<%([\s\S]+?)%>/g,
9470
9471 /**
9472 * Used to detect `data` property values to inject.
9473 *
9474 * @memberOf _.templateSettings
9475 * @type RegExp
9476 */
9477 'interpolate': reInterpolate,
9478
9479 /**
9480 * Used to reference the data object in the template text.
9481 *
9482 * @memberOf _.templateSettings
9483 * @type string
9484 */
9485 'variable': '',
9486
9487 /**
9488 * Used to import variables into the compiled template.
9489 *
9490 * @memberOf _.templateSettings
9491 * @type Object
9492 */
9493 'imports': {
9494
9495 /**
9496 * A reference to the `lodash` function.
9497 *
9498 * @memberOf _.templateSettings.imports
9499 * @type Function
9500 */
9501 '_': lodash
9502 }
9503 };
9504
9505 /*--------------------------------------------------------------------------*/
9506
9507 /**
9508 * The base implementation of `_.bind` that creates the bound function and
9509 * sets its meta data.
9510 *
9511 * @private
9512 * @param {Array} bindData The bind data array.
9513 * @returns {Function} Returns the new bound function.
9514 */
9515 function baseBind(bindData) {
9516 var func = bindData[0],
9517 partialArgs = bindData[2],
9518 thisArg = bindData[4];
9519
9520 function bound() {
9521 // `Function#bind` spec
9522 // http://es5.github.io/#x15.3.4.5
9523 if (partialArgs) {
9524 // avoid `arguments` object deoptimizations by using `slice` instead
9525 // of `Array.prototype.slice.call` and not assigning `arguments` to a
9526 // variable as a ternary expression
9527 var args = slice(partialArgs);
9528 push.apply(args, arguments);
9529 }
9530 // mimic the constructor's `return` behavior
9531 // http://es5.github.io/#x13.2.2
9532 if (this instanceof bound) {
9533 // ensure `new bound` is an instance of `func`
9534 var thisBinding = baseCreate(func.prototype),
9535 result = func.apply(thisBinding, args || arguments);
9536 return isObject(result) ? result : thisBinding;
9537 }
9538 return func.apply(thisArg, args || arguments);
9539 }
9540 setBindData(bound, bindData);
9541 return bound;
9542 }
9543
9544 /**
9545 * The base implementation of `_.clone` without argument juggling or support
9546 * for `thisArg` binding.
9547 *
9548 * @private
9549 * @param {*} value The value to clone.
9550 * @param {boolean} [isDeep=false] Specify a deep clone.
9551 * @param {Function} [callback] The function to customize cloning values.
9552 * @param {Array} [stackA=[]] Tracks traversed source objects.
9553 * @param {Array} [stackB=[]] Associates clones with source counterparts.
9554 * @returns {*} Returns the cloned value.
9555 */
9556 function baseClone(value, isDeep, callback, stackA, stackB) {
9557 if (callback) {
9558 var result = callback(value);
9559 if (typeof result != 'undefined') {
9560 return result;
9561 }
9562 }
9563 // inspect [[Class]]
9564 var isObj = isObject(value);
9565 if (isObj) {
9566 var className = toString.call(value);
9567 if (!cloneableClasses[className]) {
9568 return value;
9569 }
9570 var ctor = ctorByClass[className];
9571 switch (className) {
9572 case boolClass:
9573 case dateClass:
9574 return new ctor(+value);
9575
9576 case numberClass:
9577 case stringClass:
9578 return new ctor(value);
9579
9580 case regexpClass:
9581 result = ctor(value.source, reFlags.exec(value));
9582 result.lastIndex = value.lastIndex;
9583 return result;
9584 }
9585 } else {
9586 return value;
9587 }
9588 var isArr = isArray(value);
9589 if (isDeep) {
9590 // check for circular references and return corresponding clone
9591 var initedStack = !stackA;
9592 stackA || (stackA = getArray());
9593 stackB || (stackB = getArray());
9594
9595 var length = stackA.length;
9596 while (length--) {
9597 if (stackA[length] == value) {
9598 return stackB[length];
9599 }
9600 }
9601 result = isArr ? ctor(value.length) : {};
9602 }
9603 else {
9604 result = isArr ? slice(value) : assign({}, value);
9605 }
9606 // add array properties assigned by `RegExp#exec`
9607 if (isArr) {
9608 if (hasOwnProperty.call(value, 'index')) {
9609 result.index = value.index;
9610 }
9611 if (hasOwnProperty.call(value, 'input')) {
9612 result.input = value.input;
9613 }
9614 }
9615 // exit for shallow clone
9616 if (!isDeep) {
9617 return result;
9618 }
9619 // add the source value to the stack of traversed objects
9620 // and associate it with its clone
9621 stackA.push(value);
9622 stackB.push(result);
9623
9624 // recursively populate clone (susceptible to call stack limits)
9625 (isArr ? forEach : forOwn)(value, function(objValue, key) {
9626 result[key] = baseClone(objValue, isDeep, callback, stackA, stackB);
9627 });
9628
9629 if (initedStack) {
9630 releaseArray(stackA);
9631 releaseArray(stackB);
9632 }
9633 return result;
9634 }
9635
9636 /**
9637 * The base implementation of `_.create` without support for assigning
9638 * properties to the created object.
9639 *
9640 * @private
9641 * @param {Object} prototype The object to inherit from.
9642 * @returns {Object} Returns the new object.
9643 */
9644 function baseCreate(prototype, properties) {
9645 return isObject(prototype) ? nativeCreate(prototype) : {};
9646 }
9647 // fallback for browsers without `Object.create`
9648 if (!nativeCreate) {
9649 baseCreate = (function() {
9650 function Object() {}
9651 return function(prototype) {
9652 if (isObject(prototype)) {
9653 Object.prototype = prototype;
9654 var result = new Object;
9655 Object.prototype = null;
9656 }
9657 return result || context.Object();
9658 };
9659 }());
9660 }
9661
9662 /**
9663 * The base implementation of `_.createCallback` without support for creating
9664 * "_.pluck" or "_.where" style callbacks.
9665 *
9666 * @private
9667 * @param {*} [func=identity] The value to convert to a callback.
9668 * @param {*} [thisArg] The `this` binding of the created callback.
9669 * @param {number} [argCount] The number of arguments the callback accepts.
9670 * @returns {Function} Returns a callback function.
9671 */
9672 function baseCreateCallback(func, thisArg, argCount) {
9673 if (typeof func != 'function') {
9674 return identity;
9675 }
9676 // exit early for no `thisArg` or already bound by `Function#bind`
9677 if (typeof thisArg == 'undefined' || !('prototype' in func)) {
9678 return func;
9679 }
9680 var bindData = func.__bindData__;
9681 if (typeof bindData == 'undefined') {
9682 if (support.funcNames) {
9683 bindData = !func.name;
9684 }
9685 bindData = bindData || !support.funcDecomp;
9686 if (!bindData) {
9687 var source = fnToString.call(func);
9688 if (!support.funcNames) {
9689 bindData = !reFuncName.test(source);
9690 }
9691 if (!bindData) {
9692 // checks if `func` references the `this` keyword and stores the result
9693 bindData = reThis.test(source);
9694 setBindData(func, bindData);
9695 }
9696 }
9697 }
9698 // exit early if there are no `this` references or `func` is bound
9699 if (bindData === false || (bindData !== true && bindData[1] & 1)) {
9700 return func;
9701 }
9702 switch (argCount) {
9703 case 1: return function(value) {
9704 return func.call(thisArg, value);
9705 };
9706 case 2: return function(a, b) {
9707 return func.call(thisArg, a, b);
9708 };
9709 case 3: return function(value, index, collection) {
9710 return func.call(thisArg, value, index, collection);
9711 };
9712 case 4: return function(accumulator, value, index, collection) {
9713 return func.call(thisArg, accumulator, value, index, collection);
9714 };
9715 }
9716 return bind(func, thisArg);
9717 }
9718
9719 /**
9720 * The base implementation of `createWrapper` that creates the wrapper and
9721 * sets its meta data.
9722 *
9723 * @private
9724 * @param {Array} bindData The bind data array.
9725 * @returns {Function} Returns the new function.
9726 */
9727 function baseCreateWrapper(bindData) {
9728 var func = bindData[0],
9729 bitmask = bindData[1],
9730 partialArgs = bindData[2],
9731 partialRightArgs = bindData[3],
9732 thisArg = bindData[4],
9733 arity = bindData[5];
9734
9735 var isBind = bitmask & 1,
9736 isBindKey = bitmask & 2,
9737 isCurry = bitmask & 4,
9738 isCurryBound = bitmask & 8,
9739 key = func;
9740
9741 function bound() {
9742 var thisBinding = isBind ? thisArg : this;
9743 if (partialArgs) {
9744 var args = slice(partialArgs);
9745 push.apply(args, arguments);
9746 }
9747 if (partialRightArgs || isCurry) {
9748 args || (args = slice(arguments));
9749 if (partialRightArgs) {
9750 push.apply(args, partialRightArgs);
9751 }
9752 if (isCurry && args.length < arity) {
9753 bitmask |= 16 & ~32;
9754 return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
9755 }
9756 }
9757 args || (args = arguments);
9758 if (isBindKey) {
9759 func = thisBinding[key];
9760 }
9761 if (this instanceof bound) {
9762 thisBinding = baseCreate(func.prototype);
9763 var result = func.apply(thisBinding, args);
9764 return isObject(result) ? result : thisBinding;
9765 }
9766 return func.apply(thisBinding, args);
9767 }
9768 setBindData(bound, bindData);
9769 return bound;
9770 }
9771
9772 /**
9773 * The base implementation of `_.difference` that accepts a single array
9774 * of values to exclude.
9775 *
9776 * @private
9777 * @param {Array} array The array to process.
9778 * @param {Array} [values] The array of values to exclude.
9779 * @returns {Array} Returns a new array of filtered values.
9780 */
9781 function baseDifference(array, values) {
9782 var index = -1,
9783 indexOf = getIndexOf(),
9784 length = array ? array.length : 0,
9785 isLarge = length >= largeArraySize && indexOf === baseIndexOf,
9786 result = [];
9787
9788 if (isLarge) {
9789 var cache = createCache(values);
9790 if (cache) {
9791 indexOf = cacheIndexOf;
9792 values = cache;
9793 } else {
9794 isLarge = false;
9795 }
9796 }
9797 while (++index < length) {
9798 var value = array[index];
9799 if (indexOf(values, value) < 0) {
9800 result.push(value);
9801 }
9802 }
9803 if (isLarge) {
9804 releaseObject(values);
9805 }
9806 return result;
9807 }
9808
9809 /**
9810 * The base implementation of `_.flatten` without support for callback
9811 * shorthands or `thisArg` binding.
9812 *
9813 * @private
9814 * @param {Array} array The array to flatten.
9815 * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
9816 * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
9817 * @param {number} [fromIndex=0] The index to start from.
9818 * @returns {Array} Returns a new flattened array.
9819 */
9820 function baseFlatten(array, isShallow, isStrict, fromIndex) {
9821 var index = (fromIndex || 0) - 1,
9822 length = array ? array.length : 0,
9823 result = [];
9824
9825 while (++index < length) {
9826 var value = array[index];
9827
9828 if (value && typeof value == 'object' && typeof value.length == 'number'
9829 && (isArray(value) || isArguments(value))) {
9830 // recursively flatten arrays (susceptible to call stack limits)
9831 if (!isShallow) {
9832 value = baseFlatten(value, isShallow, isStrict);
9833 }
9834 var valIndex = -1,
9835 valLength = value.length,
9836 resIndex = result.length;
9837
9838 result.length += valLength;
9839 while (++valIndex < valLength) {
9840 result[resIndex++] = value[valIndex];
9841 }
9842 } else if (!isStrict) {
9843 result.push(value);
9844 }
9845 }
9846 return result;
9847 }
9848
9849 /**
9850 * The base implementation of `_.isEqual`, without support for `thisArg` binding,
9851 * that allows partial "_.where" style comparisons.
9852 *
9853 * @private
9854 * @param {*} a The value to compare.
9855 * @param {*} b The other value to compare.
9856 * @param {Function} [callback] The function to customize comparing values.
9857 * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
9858 * @param {Array} [stackA=[]] Tracks traversed `a` objects.
9859 * @param {Array} [stackB=[]] Tracks traversed `b` objects.
9860 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
9861 */
9862 function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
9863 // used to indicate that when comparing objects, `a` has at least the properties of `b`
9864 if (callback) {
9865 var result = callback(a, b);
9866 if (typeof result != 'undefined') {
9867 return !!result;
9868 }
9869 }
9870 // exit early for identical values
9871 if (a === b) {
9872 // treat `+0` vs. `-0` as not equal
9873 return a !== 0 || (1 / a == 1 / b);
9874 }
9875 var type = typeof a,
9876 otherType = typeof b;
9877
9878 // exit early for unlike primitive values
9879 if (a === a &&
9880 !(a && objectTypes[type]) &&
9881 !(b && objectTypes[otherType])) {
9882 return false;
9883 }
9884 // exit early for `null` and `undefined` avoiding ES3's Function#call behavior
9885 // http://es5.github.io/#x15.3.4.4
9886 if (a == null || b == null) {
9887 return a === b;
9888 }
9889 // compare [[Class]] names
9890 var className = toString.call(a),
9891 otherClass = toString.call(b);
9892
9893 if (className == argsClass) {
9894 className = objectClass;
9895 }
9896 if (otherClass == argsClass) {
9897 otherClass = objectClass;
9898 }
9899 if (className != otherClass) {
9900 return false;
9901 }
9902 switch (className) {
9903 case boolClass:
9904 case dateClass:
9905 // coerce dates and booleans to numbers, dates to milliseconds and booleans
9906 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal
9907 return +a == +b;
9908
9909 case numberClass:
9910 // treat `NaN` vs. `NaN` as equal
9911 return (a != +a)
9912 ? b != +b
9913 // but treat `+0` vs. `-0` as not equal
9914 : (a == 0 ? (1 / a == 1 / b) : a == +b);
9915
9916 case regexpClass:
9917 case stringClass:
9918 // coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
9919 // treat string primitives and their corresponding object instances as equal
9920 return a == String(b);
9921 }
9922 var isArr = className == arrayClass;
9923 if (!isArr) {
9924 // unwrap any `lodash` wrapped values
9925 var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
9926 bWrapped = hasOwnProperty.call(b, '__wrapped__');
9927
9928 if (aWrapped || bWrapped) {
9929 return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
9930 }
9931 // exit for functions and DOM nodes
9932 if (className != objectClass) {
9933 return false;
9934 }
9935 // in older versions of Opera, `arguments` objects have `Array` constructors
9936 var ctorA = a.constructor,
9937 ctorB = b.constructor;
9938
9939 // non `Object` object instances with different constructors are not equal
9940 if (ctorA != ctorB &&
9941 !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
9942 ('constructor' in a && 'constructor' in b)
9943 ) {
9944 return false;
9945 }
9946 }
9947 // assume cyclic structures are equal
9948 // the algorithm for detecting cyclic structures is adapted from ES 5.1
9949 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
9950 var initedStack = !stackA;
9951 stackA || (stackA = getArray());
9952 stackB || (stackB = getArray());
9953
9954 var length = stackA.length;
9955 while (length--) {
9956 if (stackA[length] == a) {
9957 return stackB[length] == b;
9958 }
9959 }
9960 var size = 0;
9961 result = true;
9962
9963 // add `a` and `b` to the stack of traversed objects
9964 stackA.push(a);
9965 stackB.push(b);
9966
9967 // recursively compare objects and arrays (susceptible to call stack limits)
9968 if (isArr) {
9969 // compare lengths to determine if a deep comparison is necessary
9970 length = a.length;
9971 size = b.length;
9972 result = size == length;
9973
9974 if (result || isWhere) {
9975 // deep compare the contents, ignoring non-numeric properties
9976 while (size--) {
9977 var index = length,
9978 value = b[size];
9979
9980 if (isWhere) {
9981 while (index--) {
9982 if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
9983 break;
9984 }
9985 }
9986 } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
9987 break;
9988 }
9989 }
9990 }
9991 }
9992 else {
9993 // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
9994 // which, in this case, is more costly
9995 forIn(b, function(value, key, b) {
9996 if (hasOwnProperty.call(b, key)) {
9997 // count the number of properties.
9998 size++;
9999 // deep compare each property value.
10000 return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
10001 }
10002 });
10003
10004 if (result && !isWhere) {
10005 // ensure both objects have the same number of properties
10006 forIn(a, function(value, key, a) {
10007 if (hasOwnProperty.call(a, key)) {
10008 // `size` will be `-1` if `a` has more properties than `b`
10009 return (result = --size > -1);
10010 }
10011 });
10012 }
10013 }
10014 stackA.pop();
10015 stackB.pop();
10016
10017 if (initedStack) {
10018 releaseArray(stackA);
10019 releaseArray(stackB);
10020 }
10021 return result;
10022 }
10023
10024 /**
10025 * The base implementation of `_.merge` without argument juggling or support
10026 * for `thisArg` binding.
10027 *
10028 * @private
10029 * @param {Object} object The destination object.
10030 * @param {Object} source The source object.
10031 * @param {Function} [callback] The function to customize merging properties.
10032 * @param {Array} [stackA=[]] Tracks traversed source objects.
10033 * @param {Array} [stackB=[]] Associates values with source counterparts.
10034 */
10035 function baseMerge(object, source, callback, stackA, stackB) {
10036 (isArray(source) ? forEach : forOwn)(source, function(source, key) {
10037 var found,
10038 isArr,
10039 result = source,
10040 value = object[key];
10041
10042 if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
10043 // avoid merging previously merged cyclic sources
10044 var stackLength = stackA.length;
10045 while (stackLength--) {
10046 if ((found = stackA[stackLength] == source)) {
10047 value = stackB[stackLength];
10048 break;
10049 }
10050 }
10051 if (!found) {
10052 var isShallow;
10053 if (callback) {
10054 result = callback(value, source);
10055 if ((isShallow = typeof result != 'undefined')) {
10056 value = result;
10057 }
10058 }
10059 if (!isShallow) {
10060 value = isArr
10061 ? (isArray(value) ? value : [])
10062 : (isPlainObject(value) ? value : {});
10063 }
10064 // add `source` and associated `value` to the stack of traversed objects
10065 stackA.push(source);
10066 stackB.push(value);
10067
10068 // recursively merge objects and arrays (susceptible to call stack limits)
10069 if (!isShallow) {
10070 baseMerge(value, source, callback, stackA, stackB);
10071 }
10072 }
10073 }
10074 else {
10075 if (callback) {
10076 result = callback(value, source);
10077 if (typeof result == 'undefined') {
10078 result = source;
10079 }
10080 }
10081 if (typeof result != 'undefined') {
10082 value = result;
10083 }
10084 }
10085 object[key] = value;
10086 });
10087 }
10088
10089 /**
10090 * The base implementation of `_.random` without argument juggling or support
10091 * for returning floating-point numbers.
10092 *
10093 * @private
10094 * @param {number} min The minimum possible value.
10095 * @param {number} max The maximum possible value.
10096 * @returns {number} Returns a random number.
10097 */
10098 function baseRandom(min, max) {
10099 return min + floor(nativeRandom() * (max - min + 1));
10100 }
10101
10102 /**
10103 * The base implementation of `_.uniq` without support for callback shorthands
10104 * or `thisArg` binding.
10105 *
10106 * @private
10107 * @param {Array} array The array to process.
10108 * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
10109 * @param {Function} [callback] The function called per iteration.
10110 * @returns {Array} Returns a duplicate-value-free array.
10111 */
10112 function baseUniq(array, isSorted, callback) {
10113 var index = -1,
10114 indexOf = getIndexOf(),
10115 length = array ? array.length : 0,
10116 result = [];
10117
10118 var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf,
10119 seen = (callback || isLarge) ? getArray() : result;
10120
10121 if (isLarge) {
10122 var cache = createCache(seen);
10123 indexOf = cacheIndexOf;
10124 seen = cache;
10125 }
10126 while (++index < length) {
10127 var value = array[index],
10128 computed = callback ? callback(value, index, array) : value;
10129
10130 if (isSorted
10131 ? !index || seen[seen.length - 1] !== computed
10132 : indexOf(seen, computed) < 0
10133 ) {
10134 if (callback || isLarge) {
10135 seen.push(computed);
10136 }
10137 result.push(value);
10138 }
10139 }
10140 if (isLarge) {
10141 releaseArray(seen.array);
10142 releaseObject(seen);
10143 } else if (callback) {
10144 releaseArray(seen);
10145 }
10146 return result;
10147 }
10148
10149 /**
10150 * Creates a function that aggregates a collection, creating an object composed
10151 * of keys generated from the results of running each element of the collection
10152 * through a callback. The given `setter` function sets the keys and values
10153 * of the composed object.
10154 *
10155 * @private
10156 * @param {Function} setter The setter function.
10157 * @returns {Function} Returns the new aggregator function.
10158 */
10159 function createAggregator(setter) {
10160 return function(collection, callback, thisArg) {
10161 var result = {};
10162 callback = lodash.createCallback(callback, thisArg, 3);
10163
10164 var index = -1,
10165 length = collection ? collection.length : 0;
10166
10167 if (typeof length == 'number') {
10168 while (++index < length) {
10169 var value = collection[index];
10170 setter(result, value, callback(value, index, collection), collection);
10171 }
10172 } else {
10173 forOwn(collection, function(value, key, collection) {
10174 setter(result, value, callback(value, key, collection), collection);
10175 });
10176 }
10177 return result;
10178 };
10179 }
10180
10181 /**
10182 * Creates a function that, when called, either curries or invokes `func`
10183 * with an optional `this` binding and partially applied arguments.
10184 *
10185 * @private
10186 * @param {Function|string} func The function or method name to reference.
10187 * @param {number} bitmask The bitmask of method flags to compose.
10188 * The bitmask may be composed of the following flags:
10189 * 1 - `_.bind`
10190 * 2 - `_.bindKey`
10191 * 4 - `_.curry`
10192 * 8 - `_.curry` (bound)
10193 * 16 - `_.partial`
10194 * 32 - `_.partialRight`
10195 * @param {Array} [partialArgs] An array of arguments to prepend to those
10196 * provided to the new function.
10197 * @param {Array} [partialRightArgs] An array of arguments to append to those
10198 * provided to the new function.
10199 * @param {*} [thisArg] The `this` binding of `func`.
10200 * @param {number} [arity] The arity of `func`.
10201 * @returns {Function} Returns the new function.
10202 */
10203 function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
10204 var isBind = bitmask & 1,
10205 isBindKey = bitmask & 2,
10206 isCurry = bitmask & 4,
10207 isCurryBound = bitmask & 8,
10208 isPartial = bitmask & 16,
10209 isPartialRight = bitmask & 32;
10210
10211 if (!isBindKey && !isFunction(func)) {
10212 throw new TypeError;
10213 }
10214 if (isPartial && !partialArgs.length) {
10215 bitmask &= ~16;
10216 isPartial = partialArgs = false;
10217 }
10218 if (isPartialRight && !partialRightArgs.length) {
10219 bitmask &= ~32;
10220 isPartialRight = partialRightArgs = false;
10221 }
10222 var bindData = func && func.__bindData__;
10223 if (bindData && bindData !== true) {
10224 // clone `bindData`
10225 bindData = slice(bindData);
10226 if (bindData[2]) {
10227 bindData[2] = slice(bindData[2]);
10228 }
10229 if (bindData[3]) {
10230 bindData[3] = slice(bindData[3]);
10231 }
10232 // set `thisBinding` is not previously bound
10233 if (isBind && !(bindData[1] & 1)) {
10234 bindData[4] = thisArg;
10235 }
10236 // set if previously bound but not currently (subsequent curried functions)
10237 if (!isBind && bindData[1] & 1) {
10238 bitmask |= 8;
10239 }
10240 // set curried arity if not yet set
10241 if (isCurry && !(bindData[1] & 4)) {
10242 bindData[5] = arity;
10243 }
10244 // append partial left arguments
10245 if (isPartial) {
10246 push.apply(bindData[2] || (bindData[2] = []), partialArgs);
10247 }
10248 // append partial right arguments
10249 if (isPartialRight) {
10250 unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
10251 }
10252 // merge flags
10253 bindData[1] |= bitmask;
10254 return createWrapper.apply(null, bindData);
10255 }
10256 // fast path for `_.bind`
10257 var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
10258 return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
10259 }
10260
10261 /**
10262 * Used by `escape` to convert characters to HTML entities.
10263 *
10264 * @private
10265 * @param {string} match The matched character to escape.
10266 * @returns {string} Returns the escaped character.
10267 */
10268 function escapeHtmlChar(match) {
10269 return htmlEscapes[match];
10270 }
10271
10272 /**
10273 * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
10274 * customized, this method returns the custom method, otherwise it returns
10275 * the `baseIndexOf` function.
10276 *
10277 * @private
10278 * @returns {Function} Returns the "indexOf" function.
10279 */
10280 function getIndexOf() {
10281 var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
10282 return result;
10283 }
10284
10285 /**
10286 * Checks if `value` is a native function.
10287 *
10288 * @private
10289 * @param {*} value The value to check.
10290 * @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
10291 */
10292 function isNative(value) {
10293 return typeof value == 'function' && reNative.test(value);
10294 }
10295
10296 /**
10297 * Sets `this` binding data on a given function.
10298 *
10299 * @private
10300 * @param {Function} func The function to set data on.
10301 * @param {Array} value The data array to set.
10302 */
10303 var setBindData = !defineProperty ? noop : function(func, value) {
10304 descriptor.value = value;
10305 defineProperty(func, '__bindData__', descriptor);
10306 };
10307
10308 /**
10309 * A fallback implementation of `isPlainObject` which checks if a given value
10310 * is an object created by the `Object` constructor, assuming objects created
10311 * by the `Object` constructor have no inherited enumerable properties and that
10312 * there are no `Object.prototype` extensions.
10313 *
10314 * @private
10315 * @param {*} value The value to check.
10316 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
10317 */
10318 function shimIsPlainObject(value) {
10319 var ctor,
10320 result;
10321
10322 // avoid non Object objects, `arguments` objects, and DOM elements
10323 if (!(value && toString.call(value) == objectClass) ||
10324 (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) {
10325 return false;
10326 }
10327 // In most environments an object's own properties are iterated before
10328 // its inherited properties. If the last iterated property is an object's
10329 // own property then there are no inherited enumerable properties.
10330 forIn(value, function(value, key) {
10331 result = key;
10332 });
10333 return typeof result == 'undefined' || hasOwnProperty.call(value, result);
10334 }
10335
10336 /**
10337 * Used by `unescape` to convert HTML entities to characters.
10338 *
10339 * @private
10340 * @param {string} match The matched character to unescape.
10341 * @returns {string} Returns the unescaped character.
10342 */
10343 function unescapeHtmlChar(match) {
10344 return htmlUnescapes[match];
10345 }
10346
10347 /*--------------------------------------------------------------------------*/
10348
10349 /**
10350 * Checks if `value` is an `arguments` object.
10351 *
10352 * @static
10353 * @memberOf _
10354 * @category Objects
10355 * @param {*} value The value to check.
10356 * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
10357 * @example
10358 *
10359 * (function() { return _.isArguments(arguments); })(1, 2, 3);
10360 * // => true
10361 *
10362 * _.isArguments([1, 2, 3]);
10363 * // => false
10364 */
10365 function isArguments(value) {
10366 return value && typeof value == 'object' && typeof value.length == 'number' &&
10367 toString.call(value) == argsClass || false;
10368 }
10369
10370 /**
10371 * Checks if `value` is an array.
10372 *
10373 * @static
10374 * @memberOf _
10375 * @type Function
10376 * @category Objects
10377 * @param {*} value The value to check.
10378 * @returns {boolean} Returns `true` if the `value` is an array, else `false`.
10379 * @example
10380 *
10381 * (function() { return _.isArray(arguments); })();
10382 * // => false
10383 *
10384 * _.isArray([1, 2, 3]);
10385 * // => true
10386 */
10387 var isArray = nativeIsArray || function(value) {
10388 return value && typeof value == 'object' && typeof value.length == 'number' &&
10389 toString.call(value) == arrayClass || false;
10390 };
10391
10392 /**
10393 * A fallback implementation of `Object.keys` which produces an array of the
10394 * given object's own enumerable property names.
10395 *
10396 * @private
10397 * @type Function
10398 * @param {Object} object The object to inspect.
10399 * @returns {Array} Returns an array of property names.
10400 */
10401 var shimKeys = function(object) {
10402 var index, iterable = object, result = [];
10403 if (!iterable) return result;
10404 if (!(objectTypes[typeof object])) return result;
10405 for (index in iterable) {
10406 if (hasOwnProperty.call(iterable, index)) {
10407 result.push(index);
10408 }
10409 }
10410 return result
10411 };
10412
10413 /**
10414 * Creates an array composed of the own enumerable property names of an object.
10415 *
10416 * @static
10417 * @memberOf _
10418 * @category Objects
10419 * @param {Object} object The object to inspect.
10420 * @returns {Array} Returns an array of property names.
10421 * @example
10422 *
10423 * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
10424 * // => ['one', 'two', 'three'] (property order is not guaranteed across environments)
10425 */
10426 var keys = !nativeKeys ? shimKeys : function(object) {
10427 if (!isObject(object)) {
10428 return [];
10429 }
10430 return nativeKeys(object);
10431 };
10432
10433 /**
10434 * Used to convert characters to HTML entities:
10435 *
10436 * Though the `>` character is escaped for symmetry, characters like `>` and `/`
10437 * don't require escaping in HTML and have no special meaning unless they're part
10438 * of a tag or an unquoted attribute value.
10439 * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
10440 */
10441 var htmlEscapes = {
10442 '&': '&amp;',
10443 '<': '&lt;',
10444 '>': '&gt;',
10445 '"': '&quot;',
10446 "'": '&#39;'
10447 };
10448
10449 /** Used to convert HTML entities to characters */
10450 var htmlUnescapes = invert(htmlEscapes);
10451
10452 /** Used to match HTML entities and HTML characters */
10453 var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'),
10454 reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g');
10455
10456 /*--------------------------------------------------------------------------*/
10457
10458 /**
10459 * Assigns own enumerable properties of source object(s) to the destination
10460 * object. Subsequent sources will overwrite property assignments of previous
10461 * sources. If a callback is provided it will be executed to produce the
10462 * assigned values. The callback is bound to `thisArg` and invoked with two
10463 * arguments; (objectValue, sourceValue).
10464 *
10465 * @static
10466 * @memberOf _
10467 * @type Function
10468 * @alias extend
10469 * @category Objects
10470 * @param {Object} object The destination object.
10471 * @param {...Object} [source] The source objects.
10472 * @param {Function} [callback] The function to customize assigning values.
10473 * @param {*} [thisArg] The `this` binding of `callback`.
10474 * @returns {Object} Returns the destination object.
10475 * @example
10476 *
10477 * _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
10478 * // => { 'name': 'fred', 'employer': 'slate' }
10479 *
10480 * var defaults = _.partialRight(_.assign, function(a, b) {
10481 * return typeof a == 'undefined' ? b : a;
10482 * });
10483 *
10484 * var object = { 'name': 'barney' };
10485 * defaults(object, { 'name': 'fred', 'employer': 'slate' });
10486 * // => { 'name': 'barney', 'employer': 'slate' }
10487 */
10488 var assign = function(object, source, guard) {
10489 var index, iterable = object, result = iterable;
10490 if (!iterable) return result;
10491 var args = arguments,
10492 argsIndex = 0,
10493 argsLength = typeof guard == 'number' ? 2 : args.length;
10494 if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {
10495 var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);
10496 } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {
10497 callback = args[--argsLength];
10498 }
10499 while (++argsIndex < argsLength) {
10500 iterable = args[argsIndex];
10501 if (iterable && objectTypes[typeof iterable]) {
10502 var ownIndex = -1,
10503 ownProps = objectTypes[typeof iterable] && keys(iterable),
10504 length = ownProps ? ownProps.length : 0;
10505
10506 while (++ownIndex < length) {
10507 index = ownProps[ownIndex];
10508 result[index] = callback ? callback(result[index], iterable[index]) : iterable[index];
10509 }
10510 }
10511 }
10512 return result
10513 };
10514
10515 /**
10516 * Creates a clone of `value`. If `isDeep` is `true` nested objects will also
10517 * be cloned, otherwise they will be assigned by reference. If a callback
10518 * is provided it will be executed to produce the cloned values. If the
10519 * callback returns `undefined` cloning will be handled by the method instead.
10520 * The callback is bound to `thisArg` and invoked with one argument; (value).
10521 *
10522 * @static
10523 * @memberOf _
10524 * @category Objects
10525 * @param {*} value The value to clone.
10526 * @param {boolean} [isDeep=false] Specify a deep clone.
10527 * @param {Function} [callback] The function to customize cloning values.
10528 * @param {*} [thisArg] The `this` binding of `callback`.
10529 * @returns {*} Returns the cloned value.
10530 * @example
10531 *
10532 * var characters = [
10533 * { 'name': 'barney', 'age': 36 },
10534 * { 'name': 'fred', 'age': 40 }
10535 * ];
10536 *
10537 * var shallow = _.clone(characters);
10538 * shallow[0] === characters[0];
10539 * // => true
10540 *
10541 * var deep = _.clone(characters, true);
10542 * deep[0] === characters[0];
10543 * // => false
10544 *
10545 * _.mixin({
10546 * 'clone': _.partialRight(_.clone, function(value) {
10547 * return _.isElement(value) ? value.cloneNode(false) : undefined;
10548 * })
10549 * });
10550 *
10551 * var clone = _.clone(document.body);
10552 * clone.childNodes.length;
10553 * // => 0
10554 */
10555 function clone(value, isDeep, callback, thisArg) {
10556 // allows working with "Collections" methods without using their `index`
10557 // and `collection` arguments for `isDeep` and `callback`
10558 if (typeof isDeep != 'boolean' && isDeep != null) {
10559 thisArg = callback;
10560 callback = isDeep;
10561 isDeep = false;
10562 }
10563 return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
10564 }
10565
10566 /**
10567 * Creates a deep clone of `value`. If a callback is provided it will be
10568 * executed to produce the cloned values. If the callback returns `undefined`
10569 * cloning will be handled by the method instead. The callback is bound to
10570 * `thisArg` and invoked with one argument; (value).
10571 *
10572 * Note: This method is loosely based on the structured clone algorithm. Functions
10573 * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
10574 * objects created by constructors other than `Object` are cloned to plain `Object` objects.
10575 * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
10576 *
10577 * @static
10578 * @memberOf _
10579 * @category Objects
10580 * @param {*} value The value to deep clone.
10581 * @param {Function} [callback] The function to customize cloning values.
10582 * @param {*} [thisArg] The `this` binding of `callback`.
10583 * @returns {*} Returns the deep cloned value.
10584 * @example
10585 *
10586 * var characters = [
10587 * { 'name': 'barney', 'age': 36 },
10588 * { 'name': 'fred', 'age': 40 }
10589 * ];
10590 *
10591 * var deep = _.cloneDeep(characters);
10592 * deep[0] === characters[0];
10593 * // => false
10594 *
10595 * var view = {
10596 * 'label': 'docs',
10597 * 'node': element
10598 * };
10599 *
10600 * var clone = _.cloneDeep(view, function(value) {
10601 * return _.isElement(value) ? value.cloneNode(true) : undefined;
10602 * });
10603 *
10604 * clone.node == view.node;
10605 * // => false
10606 */
10607 function cloneDeep(value, callback, thisArg) {
10608 return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1));
10609 }
10610
10611 /**
10612 * Creates an object that inherits from the given `prototype` object. If a
10613 * `properties` object is provided its own enumerable properties are assigned
10614 * to the created object.
10615 *
10616 * @static
10617 * @memberOf _
10618 * @category Objects
10619 * @param {Object} prototype The object to inherit from.
10620 * @param {Object} [properties] The properties to assign to the object.
10621 * @returns {Object} Returns the new object.
10622 * @example
10623 *
10624 * function Shape() {
10625 * this.x = 0;
10626 * this.y = 0;
10627 * }
10628 *
10629 * function Circle() {
10630 * Shape.call(this);
10631 * }
10632 *
10633 * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle });
10634 *
10635 * var circle = new Circle;
10636 * circle instanceof Circle;
10637 * // => true
10638 *
10639 * circle instanceof Shape;
10640 * // => true
10641 */
10642 function create(prototype, properties) {
10643 var result = baseCreate(prototype);
10644 return properties ? assign(result, properties) : result;
10645 }
10646
10647 /**
10648 * Assigns own enumerable properties of source object(s) to the destination
10649 * object for all destination properties that resolve to `undefined`. Once a
10650 * property is set, additional defaults of the same property will be ignored.
10651 *
10652 * @static
10653 * @memberOf _
10654 * @type Function
10655 * @category Objects
10656 * @param {Object} object The destination object.
10657 * @param {...Object} [source] The source objects.
10658 * @param- {Object} [guard] Allows working with `_.reduce` without using its
10659 * `key` and `object` arguments as sources.
10660 * @returns {Object} Returns the destination object.
10661 * @example
10662 *
10663 * var object = { 'name': 'barney' };
10664 * _.defaults(object, { 'name': 'fred', 'employer': 'slate' });
10665 * // => { 'name': 'barney', 'employer': 'slate' }
10666 */
10667 var defaults = function(object, source, guard) {
10668 var index, iterable = object, result = iterable;
10669 if (!iterable) return result;
10670 var args = arguments,
10671 argsIndex = 0,
10672 argsLength = typeof guard == 'number' ? 2 : args.length;
10673 while (++argsIndex < argsLength) {
10674 iterable = args[argsIndex];
10675 if (iterable && objectTypes[typeof iterable]) {
10676 var ownIndex = -1,
10677 ownProps = objectTypes[typeof iterable] && keys(iterable),
10678 length = ownProps ? ownProps.length : 0;
10679
10680 while (++ownIndex < length) {
10681 index = ownProps[ownIndex];
10682 if (typeof result[index] == 'undefined') result[index] = iterable[index];
10683 }
10684 }
10685 }
10686 return result
10687 };
10688
10689 /**
10690 * This method is like `_.findIndex` except that it returns the key of the
10691 * first element that passes the callback check, instead of the element itself.
10692 *
10693 * If a property name is provided for `callback` the created "_.pluck" style
10694 * callback will return the property value of the given element.
10695 *
10696 * If an object is provided for `callback` the created "_.where" style callback
10697 * will return `true` for elements that have the properties of the given object,
10698 * else `false`.
10699 *
10700 * @static
10701 * @memberOf _
10702 * @category Objects
10703 * @param {Object} object The object to search.
10704 * @param {Function|Object|string} [callback=identity] The function called per
10705 * iteration. If a property name or object is provided it will be used to
10706 * create a "_.pluck" or "_.where" style callback, respectively.
10707 * @param {*} [thisArg] The `this` binding of `callback`.
10708 * @returns {string|undefined} Returns the key of the found element, else `undefined`.
10709 * @example
10710 *
10711 * var characters = {
10712 * 'barney': { 'age': 36, 'blocked': false },
10713 * 'fred': { 'age': 40, 'blocked': true },
10714 * 'pebbles': { 'age': 1, 'blocked': false }
10715 * };
10716 *
10717 * _.findKey(characters, function(chr) {
10718 * return chr.age < 40;
10719 * });
10720 * // => 'barney' (property order is not guaranteed across environments)
10721 *
10722 * // using "_.where" callback shorthand
10723 * _.findKey(characters, { 'age': 1 });
10724 * // => 'pebbles'
10725 *
10726 * // using "_.pluck" callback shorthand
10727 * _.findKey(characters, 'blocked');
10728 * // => 'fred'
10729 */
10730 function findKey(object, callback, thisArg) {
10731 var result;
10732 callback = lodash.createCallback(callback, thisArg, 3);
10733 forOwn(object, function(value, key, object) {
10734 if (callback(value, key, object)) {
10735 result = key;
10736 return false;
10737 }
10738 });
10739 return result;
10740 }
10741
10742 /**
10743 * This method is like `_.findKey` except that it iterates over elements
10744 * of a `collection` in the opposite order.
10745 *
10746 * If a property name is provided for `callback` the created "_.pluck" style
10747 * callback will return the property value of the given element.
10748 *
10749 * If an object is provided for `callback` the created "_.where" style callback
10750 * will return `true` for elements that have the properties of the given object,
10751 * else `false`.
10752 *
10753 * @static
10754 * @memberOf _
10755 * @category Objects
10756 * @param {Object} object The object to search.
10757 * @param {Function|Object|string} [callback=identity] The function called per
10758 * iteration. If a property name or object is provided it will be used to
10759 * create a "_.pluck" or "_.where" style callback, respectively.
10760 * @param {*} [thisArg] The `this` binding of `callback`.
10761 * @returns {string|undefined} Returns the key of the found element, else `undefined`.
10762 * @example
10763 *
10764 * var characters = {
10765 * 'barney': { 'age': 36, 'blocked': true },
10766 * 'fred': { 'age': 40, 'blocked': false },
10767 * 'pebbles': { 'age': 1, 'blocked': true }
10768 * };
10769 *
10770 * _.findLastKey(characters, function(chr) {
10771 * return chr.age < 40;
10772 * });
10773 * // => returns `pebbles`, assuming `_.findKey` returns `barney`
10774 *
10775 * // using "_.where" callback shorthand
10776 * _.findLastKey(characters, { 'age': 40 });
10777 * // => 'fred'
10778 *
10779 * // using "_.pluck" callback shorthand
10780 * _.findLastKey(characters, 'blocked');
10781 * // => 'pebbles'
10782 */
10783 function findLastKey(object, callback, thisArg) {
10784 var result;
10785 callback = lodash.createCallback(callback, thisArg, 3);
10786 forOwnRight(object, function(value, key, object) {
10787 if (callback(value, key, object)) {
10788 result = key;
10789 return false;
10790 }
10791 });
10792 return result;
10793 }
10794
10795 /**
10796 * Iterates over own and inherited enumerable properties of an object,
10797 * executing the callback for each property. The callback is bound to `thisArg`
10798 * and invoked with three arguments; (value, key, object). Callbacks may exit
10799 * iteration early by explicitly returning `false`.
10800 *
10801 * @static
10802 * @memberOf _
10803 * @type Function
10804 * @category Objects
10805 * @param {Object} object The object to iterate over.
10806 * @param {Function} [callback=identity] The function called per iteration.
10807 * @param {*} [thisArg] The `this` binding of `callback`.
10808 * @returns {Object} Returns `object`.
10809 * @example
10810 *
10811 * function Shape() {
10812 * this.x = 0;
10813 * this.y = 0;
10814 * }
10815 *
10816 * Shape.prototype.move = function(x, y) {
10817 * this.x += x;
10818 * this.y += y;
10819 * };
10820 *
10821 * _.forIn(new Shape, function(value, key) {
10822 * console.log(key);
10823 * });
10824 * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments)
10825 */
10826 var forIn = function(collection, callback, thisArg) {
10827 var index, iterable = collection, result = iterable;
10828 if (!iterable) return result;
10829 if (!objectTypes[typeof iterable]) return result;
10830 callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
10831 for (index in iterable) {
10832 if (callback(iterable[index], index, collection) === false) return result;
10833 }
10834 return result
10835 };
10836
10837 /**
10838 * This method is like `_.forIn` except that it iterates over elements
10839 * of a `collection` in the opposite order.
10840 *
10841 * @static
10842 * @memberOf _
10843 * @category Objects
10844 * @param {Object} object The object to iterate over.
10845 * @param {Function} [callback=identity] The function called per iteration.
10846 * @param {*} [thisArg] The `this` binding of `callback`.
10847 * @returns {Object} Returns `object`.
10848 * @example
10849 *
10850 * function Shape() {
10851 * this.x = 0;
10852 * this.y = 0;
10853 * }
10854 *
10855 * Shape.prototype.move = function(x, y) {
10856 * this.x += x;
10857 * this.y += y;
10858 * };
10859 *
10860 * _.forInRight(new Shape, function(value, key) {
10861 * console.log(key);
10862 * });
10863 * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move'
10864 */
10865 function forInRight(object, callback, thisArg) {
10866 var pairs = [];
10867
10868 forIn(object, function(value, key) {
10869 pairs.push(key, value);
10870 });
10871
10872 var length = pairs.length;
10873 callback = baseCreateCallback(callback, thisArg, 3);
10874 while (length--) {
10875 if (callback(pairs[length--], pairs[length], object) === false) {
10876 break;
10877 }
10878 }
10879 return object;
10880 }
10881
10882 /**
10883 * Iterates over own enumerable properties of an object, executing the callback
10884 * for each property. The callback is bound to `thisArg` and invoked with three
10885 * arguments; (value, key, object). Callbacks may exit iteration early by
10886 * explicitly returning `false`.
10887 *
10888 * @static
10889 * @memberOf _
10890 * @type Function
10891 * @category Objects
10892 * @param {Object} object The object to iterate over.
10893 * @param {Function} [callback=identity] The function called per iteration.
10894 * @param {*} [thisArg] The `this` binding of `callback`.
10895 * @returns {Object} Returns `object`.
10896 * @example
10897 *
10898 * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
10899 * console.log(key);
10900 * });
10901 * // => logs '0', '1', and 'length' (property order is not guaranteed across environments)
10902 */
10903 var forOwn = function(collection, callback, thisArg) {
10904 var index, iterable = collection, result = iterable;
10905 if (!iterable) return result;
10906 if (!objectTypes[typeof iterable]) return result;
10907 callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
10908 var ownIndex = -1,
10909 ownProps = objectTypes[typeof iterable] && keys(iterable),
10910 length = ownProps ? ownProps.length : 0;
10911
10912 while (++ownIndex < length) {
10913 index = ownProps[ownIndex];
10914 if (callback(iterable[index], index, collection) === false) return result;
10915 }
10916 return result
10917 };
10918
10919 /**
10920 * This method is like `_.forOwn` except that it iterates over elements
10921 * of a `collection` in the opposite order.
10922 *
10923 * @static
10924 * @memberOf _
10925 * @category Objects
10926 * @param {Object} object The object to iterate over.
10927 * @param {Function} [callback=identity] The function called per iteration.
10928 * @param {*} [thisArg] The `this` binding of `callback`.
10929 * @returns {Object} Returns `object`.
10930 * @example
10931 *
10932 * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
10933 * console.log(key);
10934 * });
10935 * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length'
10936 */
10937 function forOwnRight(object, callback, thisArg) {
10938 var props = keys(object),
10939 length = props.length;
10940
10941 callback = baseCreateCallback(callback, thisArg, 3);
10942 while (length--) {
10943 var key = props[length];
10944 if (callback(object[key], key, object) === false) {
10945 break;
10946 }
10947 }
10948 return object;
10949 }
10950
10951 /**
10952 * Creates a sorted array of property names of all enumerable properties,
10953 * own and inherited, of `object` that have function values.
10954 *
10955 * @static
10956 * @memberOf _
10957 * @alias methods
10958 * @category Objects
10959 * @param {Object} object The object to inspect.
10960 * @returns {Array} Returns an array of property names that have function values.
10961 * @example
10962 *
10963 * _.functions(_);
10964 * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
10965 */
10966 function functions(object) {
10967 var result = [];
10968 forIn(object, function(value, key) {
10969 if (isFunction(value)) {
10970 result.push(key);
10971 }
10972 });
10973 return result.sort();
10974 }
10975
10976 /**
10977 * Checks if the specified property name exists as a direct property of `object`,
10978 * instead of an inherited property.
10979 *
10980 * @static
10981 * @memberOf _
10982 * @category Objects
10983 * @param {Object} object The object to inspect.
10984 * @param {string} key The name of the property to check.
10985 * @returns {boolean} Returns `true` if key is a direct property, else `false`.
10986 * @example
10987 *
10988 * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
10989 * // => true
10990 */
10991 function has(object, key) {
10992 return object ? hasOwnProperty.call(object, key) : false;
10993 }
10994
10995 /**
10996 * Creates an object composed of the inverted keys and values of the given object.
10997 *
10998 * @static
10999 * @memberOf _
11000 * @category Objects
11001 * @param {Object} object The object to invert.
11002 * @returns {Object} Returns the created inverted object.
11003 * @example
11004 *
11005 * _.invert({ 'first': 'fred', 'second': 'barney' });
11006 * // => { 'fred': 'first', 'barney': 'second' }
11007 */
11008 function invert(object) {
11009 var index = -1,
11010 props = keys(object),
11011 length = props.length,
11012 result = {};
11013
11014 while (++index < length) {
11015 var key = props[index];
11016 result[object[key]] = key;
11017 }
11018 return result;
11019 }
11020
11021 /**
11022 * Checks if `value` is a boolean value.
11023 *
11024 * @static
11025 * @memberOf _
11026 * @category Objects
11027 * @param {*} value The value to check.
11028 * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
11029 * @example
11030 *
11031 * _.isBoolean(null);
11032 * // => false
11033 */
11034 function isBoolean(value) {
11035 return value === true || value === false ||
11036 value && typeof value == 'object' && toString.call(value) == boolClass || false;
11037 }
11038
11039 /**
11040 * Checks if `value` is a date.
11041 *
11042 * @static
11043 * @memberOf _
11044 * @category Objects
11045 * @param {*} value The value to check.
11046 * @returns {boolean} Returns `true` if the `value` is a date, else `false`.
11047 * @example
11048 *
11049 * _.isDate(new Date);
11050 * // => true
11051 */
11052 function isDate(value) {
11053 return value && typeof value == 'object' && toString.call(value) == dateClass || false;
11054 }
11055
11056 /**
11057 * Checks if `value` is a DOM element.
11058 *
11059 * @static
11060 * @memberOf _
11061 * @category Objects
11062 * @param {*} value The value to check.
11063 * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`.
11064 * @example
11065 *
11066 * _.isElement(document.body);
11067 * // => true
11068 */
11069 function isElement(value) {
11070 return value && value.nodeType === 1 || false;
11071 }
11072
11073 /**
11074 * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
11075 * length of `0` and objects with no own enumerable properties are considered
11076 * "empty".
11077 *
11078 * @static
11079 * @memberOf _
11080 * @category Objects
11081 * @param {Array|Object|string} value The value to inspect.
11082 * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
11083 * @example
11084 *
11085 * _.isEmpty([1, 2, 3]);
11086 * // => false
11087 *
11088 * _.isEmpty({});
11089 * // => true
11090 *
11091 * _.isEmpty('');
11092 * // => true
11093 */
11094 function isEmpty(value) {
11095 var result = true;
11096 if (!value) {
11097 return result;
11098 }
11099 var className = toString.call(value),
11100 length = value.length;
11101
11102 if ((className == arrayClass || className == stringClass || className == argsClass ) ||
11103 (className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
11104 return !length;
11105 }
11106 forOwn(value, function() {
11107 return (result = false);
11108 });
11109 return result;
11110 }
11111
11112 /**
11113 * Performs a deep comparison between two values to determine if they are
11114 * equivalent to each other. If a callback is provided it will be executed
11115 * to compare values. If the callback returns `undefined` comparisons will
11116 * be handled by the method instead. The callback is bound to `thisArg` and
11117 * invoked with two arguments; (a, b).
11118 *
11119 * @static
11120 * @memberOf _
11121 * @category Objects
11122 * @param {*} a The value to compare.
11123 * @param {*} b The other value to compare.
11124 * @param {Function} [callback] The function to customize comparing values.
11125 * @param {*} [thisArg] The `this` binding of `callback`.
11126 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
11127 * @example
11128 *
11129 * var object = { 'name': 'fred' };
11130 * var copy = { 'name': 'fred' };
11131 *
11132 * object == copy;
11133 * // => false
11134 *
11135 * _.isEqual(object, copy);
11136 * // => true
11137 *
11138 * var words = ['hello', 'goodbye'];
11139 * var otherWords = ['hi', 'goodbye'];
11140 *
11141 * _.isEqual(words, otherWords, function(a, b) {
11142 * var reGreet = /^(?:hello|hi)$/i,
11143 * aGreet = _.isString(a) && reGreet.test(a),
11144 * bGreet = _.isString(b) && reGreet.test(b);
11145 *
11146 * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
11147 * });
11148 * // => true
11149 */
11150 function isEqual(a, b, callback, thisArg) {
11151 return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2));
11152 }
11153
11154 /**
11155 * Checks if `value` is, or can be coerced to, a finite number.
11156 *
11157 * Note: This is not the same as native `isFinite` which will return true for
11158 * booleans and empty strings. See http://es5.github.io/#x15.1.2.5.
11159 *
11160 * @static
11161 * @memberOf _
11162 * @category Objects
11163 * @param {*} value The value to check.
11164 * @returns {boolean} Returns `true` if the `value` is finite, else `false`.
11165 * @example
11166 *
11167 * _.isFinite(-101);
11168 * // => true
11169 *
11170 * _.isFinite('10');
11171 * // => true
11172 *
11173 * _.isFinite(true);
11174 * // => false
11175 *
11176 * _.isFinite('');
11177 * // => false
11178 *
11179 * _.isFinite(Infinity);
11180 * // => false
11181 */
11182 function isFinite(value) {
11183 return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
11184 }
11185
11186 /**
11187 * Checks if `value` is a function.
11188 *
11189 * @static
11190 * @memberOf _
11191 * @category Objects
11192 * @param {*} value The value to check.
11193 * @returns {boolean} Returns `true` if the `value` is a function, else `false`.
11194 * @example
11195 *
11196 * _.isFunction(_);
11197 * // => true
11198 */
11199 function isFunction(value) {
11200 return typeof value == 'function';
11201 }
11202
11203 /**
11204 * Checks if `value` is the language type of Object.
11205 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
11206 *
11207 * @static
11208 * @memberOf _
11209 * @category Objects
11210 * @param {*} value The value to check.
11211 * @returns {boolean} Returns `true` if the `value` is an object, else `false`.
11212 * @example
11213 *
11214 * _.isObject({});
11215 * // => true
11216 *
11217 * _.isObject([1, 2, 3]);
11218 * // => true
11219 *
11220 * _.isObject(1);
11221 * // => false
11222 */
11223 function isObject(value) {
11224 // check if the value is the ECMAScript language type of Object
11225 // http://es5.github.io/#x8
11226 // and avoid a V8 bug
11227 // http://code.google.com/p/v8/issues/detail?id=2291
11228 return !!(value && objectTypes[typeof value]);
11229 }
11230
11231 /**
11232 * Checks if `value` is `NaN`.
11233 *
11234 * Note: This is not the same as native `isNaN` which will return `true` for
11235 * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
11236 *
11237 * @static
11238 * @memberOf _
11239 * @category Objects
11240 * @param {*} value The value to check.
11241 * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
11242 * @example
11243 *
11244 * _.isNaN(NaN);
11245 * // => true
11246 *
11247 * _.isNaN(new Number(NaN));
11248 * // => true
11249 *
11250 * isNaN(undefined);
11251 * // => true
11252 *
11253 * _.isNaN(undefined);
11254 * // => false
11255 */
11256 function isNaN(value) {
11257 // `NaN` as a primitive is the only value that is not equal to itself
11258 // (perform the [[Class]] check first to avoid errors with some host objects in IE)
11259 return isNumber(value) && value != +value;
11260 }
11261
11262 /**
11263 * Checks if `value` is `null`.
11264 *
11265 * @static
11266 * @memberOf _
11267 * @category Objects
11268 * @param {*} value The value to check.
11269 * @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
11270 * @example
11271 *
11272 * _.isNull(null);
11273 * // => true
11274 *
11275 * _.isNull(undefined);
11276 * // => false
11277 */
11278 function isNull(value) {
11279 return value === null;
11280 }
11281
11282 /**
11283 * Checks if `value` is a number.
11284 *
11285 * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
11286 *
11287 * @static
11288 * @memberOf _
11289 * @category Objects
11290 * @param {*} value The value to check.
11291 * @returns {boolean} Returns `true` if the `value` is a number, else `false`.
11292 * @example
11293 *
11294 * _.isNumber(8.4 * 5);
11295 * // => true
11296 */
11297 function isNumber(value) {
11298 return typeof value == 'number' ||
11299 value && typeof value == 'object' && toString.call(value) == numberClass || false;
11300 }
11301
11302 /**
11303 * Checks if `value` is an object created by the `Object` constructor.
11304 *
11305 * @static
11306 * @memberOf _
11307 * @category Objects
11308 * @param {*} value The value to check.
11309 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
11310 * @example
11311 *
11312 * function Shape() {
11313 * this.x = 0;
11314 * this.y = 0;
11315 * }
11316 *
11317 * _.isPlainObject(new Shape);
11318 * // => false
11319 *
11320 * _.isPlainObject([1, 2, 3]);
11321 * // => false
11322 *
11323 * _.isPlainObject({ 'x': 0, 'y': 0 });
11324 * // => true
11325 */
11326 var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
11327 if (!(value && toString.call(value) == objectClass)) {
11328 return false;
11329 }
11330 var valueOf = value.valueOf,
11331 objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
11332
11333 return objProto
11334 ? (value == objProto || getPrototypeOf(value) == objProto)
11335 : shimIsPlainObject(value);
11336 };
11337
11338 /**
11339 * Checks if `value` is a regular expression.
11340 *
11341 * @static
11342 * @memberOf _
11343 * @category Objects
11344 * @param {*} value The value to check.
11345 * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`.
11346 * @example
11347 *
11348 * _.isRegExp(/fred/);
11349 * // => true
11350 */
11351 function isRegExp(value) {
11352 return value && typeof value == 'object' && toString.call(value) == regexpClass || false;
11353 }
11354
11355 /**
11356 * Checks if `value` is a string.
11357 *
11358 * @static
11359 * @memberOf _
11360 * @category Objects
11361 * @param {*} value The value to check.
11362 * @returns {boolean} Returns `true` if the `value` is a string, else `false`.
11363 * @example
11364 *
11365 * _.isString('fred');
11366 * // => true
11367 */
11368 function isString(value) {
11369 return typeof value == 'string' ||
11370 value && typeof value == 'object' && toString.call(value) == stringClass || false;
11371 }
11372
11373 /**
11374 * Checks if `value` is `undefined`.
11375 *
11376 * @static
11377 * @memberOf _
11378 * @category Objects
11379 * @param {*} value The value to check.
11380 * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
11381 * @example
11382 *
11383 * _.isUndefined(void 0);
11384 * // => true
11385 */
11386 function isUndefined(value) {
11387 return typeof value == 'undefined';
11388 }
11389
11390 /**
11391 * Creates an object with the same keys as `object` and values generated by
11392 * running each own enumerable property of `object` through the callback.
11393 * The callback is bound to `thisArg` and invoked with three arguments;
11394 * (value, key, object).
11395 *
11396 * If a property name is provided for `callback` the created "_.pluck" style
11397 * callback will return the property value of the given element.
11398 *
11399 * If an object is provided for `callback` the created "_.where" style callback
11400 * will return `true` for elements that have the properties of the given object,
11401 * else `false`.
11402 *
11403 * @static
11404 * @memberOf _
11405 * @category Objects
11406 * @param {Object} object The object to iterate over.
11407 * @param {Function|Object|string} [callback=identity] The function called
11408 * per iteration. If a property name or object is provided it will be used
11409 * to create a "_.pluck" or "_.where" style callback, respectively.
11410 * @param {*} [thisArg] The `this` binding of `callback`.
11411 * @returns {Array} Returns a new object with values of the results of each `callback` execution.
11412 * @example
11413 *
11414 * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; });
11415 * // => { 'a': 3, 'b': 6, 'c': 9 }
11416 *
11417 * var characters = {
11418 * 'fred': { 'name': 'fred', 'age': 40 },
11419 * 'pebbles': { 'name': 'pebbles', 'age': 1 }
11420 * };
11421 *
11422 * // using "_.pluck" callback shorthand
11423 * _.mapValues(characters, 'age');
11424 * // => { 'fred': 40, 'pebbles': 1 }
11425 */
11426 function mapValues(object, callback, thisArg) {
11427 var result = {};
11428 callback = lodash.createCallback(callback, thisArg, 3);
11429
11430 forOwn(object, function(value, key, object) {
11431 result[key] = callback(value, key, object);
11432 });
11433 return result;
11434 }
11435
11436 /**
11437 * Recursively merges own enumerable properties of the source object(s), that
11438 * don't resolve to `undefined` into the destination object. Subsequent sources
11439 * will overwrite property assignments of previous sources. If a callback is
11440 * provided it will be executed to produce the merged values of the destination
11441 * and source properties. If the callback returns `undefined` merging will
11442 * be handled by the method instead. The callback is bound to `thisArg` and
11443 * invoked with two arguments; (objectValue, sourceValue).
11444 *
11445 * @static
11446 * @memberOf _
11447 * @category Objects
11448 * @param {Object} object The destination object.
11449 * @param {...Object} [source] The source objects.
11450 * @param {Function} [callback] The function to customize merging properties.
11451 * @param {*} [thisArg] The `this` binding of `callback`.
11452 * @returns {Object} Returns the destination object.
11453 * @example
11454 *
11455 * var names = {
11456 * 'characters': [
11457 * { 'name': 'barney' },
11458 * { 'name': 'fred' }
11459 * ]
11460 * };
11461 *
11462 * var ages = {
11463 * 'characters': [
11464 * { 'age': 36 },
11465 * { 'age': 40 }
11466 * ]
11467 * };
11468 *
11469 * _.merge(names, ages);
11470 * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
11471 *
11472 * var food = {
11473 * 'fruits': ['apple'],
11474 * 'vegetables': ['beet']
11475 * };
11476 *
11477 * var otherFood = {
11478 * 'fruits': ['banana'],
11479 * 'vegetables': ['carrot']
11480 * };
11481 *
11482 * _.merge(food, otherFood, function(a, b) {
11483 * return _.isArray(a) ? a.concat(b) : undefined;
11484 * });
11485 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
11486 */
11487 function merge(object) {
11488 var args = arguments,
11489 length = 2;
11490
11491 if (!isObject(object)) {
11492 return object;
11493 }
11494 // allows working with `_.reduce` and `_.reduceRight` without using
11495 // their `index` and `collection` arguments
11496 if (typeof args[2] != 'number') {
11497 length = args.length;
11498 }
11499 if (length > 3 && typeof args[length - 2] == 'function') {
11500 var callback = baseCreateCallback(args[--length - 1], args[length--], 2);
11501 } else if (length > 2 && typeof args[length - 1] == 'function') {
11502 callback = args[--length];
11503 }
11504 var sources = slice(arguments, 1, length),
11505 index = -1,
11506 stackA = getArray(),
11507 stackB = getArray();
11508
11509 while (++index < length) {
11510 baseMerge(object, sources[index], callback, stackA, stackB);
11511 }
11512 releaseArray(stackA);
11513 releaseArray(stackB);
11514 return object;
11515 }
11516
11517 /**
11518 * Creates a shallow clone of `object` excluding the specified properties.
11519 * Property names may be specified as individual arguments or as arrays of
11520 * property names. If a callback is provided it will be executed for each
11521 * property of `object` omitting the properties the callback returns truey
11522 * for. The callback is bound to `thisArg` and invoked with three arguments;
11523 * (value, key, object).
11524 *
11525 * @static
11526 * @memberOf _
11527 * @category Objects
11528 * @param {Object} object The source object.
11529 * @param {Function|...string|string[]} [callback] The properties to omit or the
11530 * function called per iteration.
11531 * @param {*} [thisArg] The `this` binding of `callback`.
11532 * @returns {Object} Returns an object without the omitted properties.
11533 * @example
11534 *
11535 * _.omit({ 'name': 'fred', 'age': 40 }, 'age');
11536 * // => { 'name': 'fred' }
11537 *
11538 * _.omit({ 'name': 'fred', 'age': 40 }, function(value) {
11539 * return typeof value == 'number';
11540 * });
11541 * // => { 'name': 'fred' }
11542 */
11543 function omit(object, callback, thisArg) {
11544 var result = {};
11545 if (typeof callback != 'function') {
11546 var props = [];
11547 forIn(object, function(value, key) {
11548 props.push(key);
11549 });
11550 props = baseDifference(props, baseFlatten(arguments, true, false, 1));
11551
11552 var index = -1,
11553 length = props.length;
11554
11555 while (++index < length) {
11556 var key = props[index];
11557 result[key] = object[key];
11558 }
11559 } else {
11560 callback = lodash.createCallback(callback, thisArg, 3);
11561 forIn(object, function(value, key, object) {
11562 if (!callback(value, key, object)) {
11563 result[key] = value;
11564 }
11565 });
11566 }
11567 return result;
11568 }
11569
11570 /**
11571 * Creates a two dimensional array of an object's key-value pairs,
11572 * i.e. `[[key1, value1], [key2, value2]]`.
11573 *
11574 * @static
11575 * @memberOf _
11576 * @category Objects
11577 * @param {Object} object The object to inspect.
11578 * @returns {Array} Returns new array of key-value pairs.
11579 * @example
11580 *
11581 * _.pairs({ 'barney': 36, 'fred': 40 });
11582 * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments)
11583 */
11584 function pairs(object) {
11585 var index = -1,
11586 props = keys(object),
11587 length = props.length,
11588 result = Array(length);
11589
11590 while (++index < length) {
11591 var key = props[index];
11592 result[index] = [key, object[key]];
11593 }
11594 return result;
11595 }
11596
11597 /**
11598 * Creates a shallow clone of `object` composed of the specified properties.
11599 * Property names may be specified as individual arguments or as arrays of
11600 * property names. If a callback is provided it will be executed for each
11601 * property of `object` picking the properties the callback returns truey
11602 * for. The callback is bound to `thisArg` and invoked with three arguments;
11603 * (value, key, object).
11604 *
11605 * @static
11606 * @memberOf _
11607 * @category Objects
11608 * @param {Object} object The source object.
11609 * @param {Function|...string|string[]} [callback] The function called per
11610 * iteration or property names to pick, specified as individual property
11611 * names or arrays of property names.
11612 * @param {*} [thisArg] The `this` binding of `callback`.
11613 * @returns {Object} Returns an object composed of the picked properties.
11614 * @example
11615 *
11616 * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name');
11617 * // => { 'name': 'fred' }
11618 *
11619 * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) {
11620 * return key.charAt(0) != '_';
11621 * });
11622 * // => { 'name': 'fred' }
11623 */
11624 function pick(object, callback, thisArg) {
11625 var result = {};
11626 if (typeof callback != 'function') {
11627 var index = -1,
11628 props = baseFlatten(arguments, true, false, 1),
11629 length = isObject(object) ? props.length : 0;
11630
11631 while (++index < length) {
11632 var key = props[index];
11633 if (key in object) {
11634 result[key] = object[key];
11635 }
11636 }
11637 } else {
11638 callback = lodash.createCallback(callback, thisArg, 3);
11639 forIn(object, function(value, key, object) {
11640 if (callback(value, key, object)) {
11641 result[key] = value;
11642 }
11643 });
11644 }
11645 return result;
11646 }
11647
11648 /**
11649 * An alternative to `_.reduce` this method transforms `object` to a new
11650 * `accumulator` object which is the result of running each of its own
11651 * enumerable properties through a callback, with each callback execution
11652 * potentially mutating the `accumulator` object. The callback is bound to
11653 * `thisArg` and invoked with four arguments; (accumulator, value, key, object).
11654 * Callbacks may exit iteration early by explicitly returning `false`.
11655 *
11656 * @static
11657 * @memberOf _
11658 * @category Objects
11659 * @param {Array|Object} object The object to iterate over.
11660 * @param {Function} [callback=identity] The function called per iteration.
11661 * @param {*} [accumulator] The custom accumulator value.
11662 * @param {*} [thisArg] The `this` binding of `callback`.
11663 * @returns {*} Returns the accumulated value.
11664 * @example
11665 *
11666 * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) {
11667 * num *= num;
11668 * if (num % 2) {
11669 * return result.push(num) < 3;
11670 * }
11671 * });
11672 * // => [1, 9, 25]
11673 *
11674 * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
11675 * result[key] = num * 3;
11676 * });
11677 * // => { 'a': 3, 'b': 6, 'c': 9 }
11678 */
11679 function transform(object, callback, accumulator, thisArg) {
11680 var isArr = isArray(object);
11681 if (accumulator == null) {
11682 if (isArr) {
11683 accumulator = [];
11684 } else {
11685 var ctor = object && object.constructor,
11686 proto = ctor && ctor.prototype;
11687
11688 accumulator = baseCreate(proto);
11689 }
11690 }
11691 if (callback) {
11692 callback = lodash.createCallback(callback, thisArg, 4);
11693 (isArr ? forEach : forOwn)(object, function(value, index, object) {
11694 return callback(accumulator, value, index, object);
11695 });
11696 }
11697 return accumulator;
11698 }
11699
11700 /**
11701 * Creates an array composed of the own enumerable property values of `object`.
11702 *
11703 * @static
11704 * @memberOf _
11705 * @category Objects
11706 * @param {Object} object The object to inspect.
11707 * @returns {Array} Returns an array of property values.
11708 * @example
11709 *
11710 * _.values({ 'one': 1, 'two': 2, 'three': 3 });
11711 * // => [1, 2, 3] (property order is not guaranteed across environments)
11712 */
11713 function values(object) {
11714 var index = -1,
11715 props = keys(object),
11716 length = props.length,
11717 result = Array(length);
11718
11719 while (++index < length) {
11720 result[index] = object[props[index]];
11721 }
11722 return result;
11723 }
11724
11725 /*--------------------------------------------------------------------------*/
11726
11727 /**
11728 * Creates an array of elements from the specified indexes, or keys, of the
11729 * `collection`. Indexes may be specified as individual arguments or as arrays
11730 * of indexes.
11731 *
11732 * @static
11733 * @memberOf _
11734 * @category Collections
11735 * @param {Array|Object|string} collection The collection to iterate over.
11736 * @param {...(number|number[]|string|string[])} [index] The indexes of `collection`
11737 * to retrieve, specified as individual indexes or arrays of indexes.
11738 * @returns {Array} Returns a new array of elements corresponding to the
11739 * provided indexes.
11740 * @example
11741 *
11742 * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
11743 * // => ['a', 'c', 'e']
11744 *
11745 * _.at(['fred', 'barney', 'pebbles'], 0, 2);
11746 * // => ['fred', 'pebbles']
11747 */
11748 function at(collection) {
11749 var args = arguments,
11750 index = -1,
11751 props = baseFlatten(args, true, false, 1),
11752 length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length,
11753 result = Array(length);
11754
11755 while(++index < length) {
11756 result[index] = collection[props[index]];
11757 }
11758 return result;
11759 }
11760
11761 /**
11762 * Checks if a given value is present in a collection using strict equality
11763 * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the
11764 * offset from the end of the collection.
11765 *
11766 * @static
11767 * @memberOf _
11768 * @alias include
11769 * @category Collections
11770 * @param {Array|Object|string} collection The collection to iterate over.
11771 * @param {*} target The value to check for.
11772 * @param {number} [fromIndex=0] The index to search from.
11773 * @returns {boolean} Returns `true` if the `target` element is found, else `false`.
11774 * @example
11775 *
11776 * _.contains([1, 2, 3], 1);
11777 * // => true
11778 *
11779 * _.contains([1, 2, 3], 1, 2);
11780 * // => false
11781 *
11782 * _.contains({ 'name': 'fred', 'age': 40 }, 'fred');
11783 * // => true
11784 *
11785 * _.contains('pebbles', 'eb');
11786 * // => true
11787 */
11788 function contains(collection, target, fromIndex) {
11789 var index = -1,
11790 indexOf = getIndexOf(),
11791 length = collection ? collection.length : 0,
11792 result = false;
11793
11794 fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
11795 if (isArray(collection)) {
11796 result = indexOf(collection, target, fromIndex) > -1;
11797 } else if (typeof length == 'number') {
11798 result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1;
11799 } else {
11800 forOwn(collection, function(value) {
11801 if (++index >= fromIndex) {
11802 return !(result = value === target);
11803 }
11804 });
11805 }
11806 return result;
11807 }
11808
11809 /**
11810 * Creates an object composed of keys generated from the results of running
11811 * each element of `collection` through the callback. The corresponding value
11812 * of each key is the number of times the key was returned by the callback.
11813 * The callback is bound to `thisArg` and invoked with three arguments;
11814 * (value, index|key, collection).
11815 *
11816 * If a property name is provided for `callback` the created "_.pluck" style
11817 * callback will return the property value of the given element.
11818 *
11819 * If an object is provided for `callback` the created "_.where" style callback
11820 * will return `true` for elements that have the properties of the given object,
11821 * else `false`.
11822 *
11823 * @static
11824 * @memberOf _
11825 * @category Collections
11826 * @param {Array|Object|string} collection The collection to iterate over.
11827 * @param {Function|Object|string} [callback=identity] The function called
11828 * per iteration. If a property name or object is provided it will be used
11829 * to create a "_.pluck" or "_.where" style callback, respectively.
11830 * @param {*} [thisArg] The `this` binding of `callback`.
11831 * @returns {Object} Returns the composed aggregate object.
11832 * @example
11833 *
11834 * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
11835 * // => { '4': 1, '6': 2 }
11836 *
11837 * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
11838 * // => { '4': 1, '6': 2 }
11839 *
11840 * _.countBy(['one', 'two', 'three'], 'length');
11841 * // => { '3': 2, '5': 1 }
11842 */
11843 var countBy = createAggregator(function(result, value, key) {
11844 (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
11845 });
11846
11847 /**
11848 * Checks if the given callback returns truey value for **all** elements of
11849 * a collection. The callback is bound to `thisArg` and invoked with three
11850 * arguments; (value, index|key, collection).
11851 *
11852 * If a property name is provided for `callback` the created "_.pluck" style
11853 * callback will return the property value of the given element.
11854 *
11855 * If an object is provided for `callback` the created "_.where" style callback
11856 * will return `true` for elements that have the properties of the given object,
11857 * else `false`.
11858 *
11859 * @static
11860 * @memberOf _
11861 * @alias all
11862 * @category Collections
11863 * @param {Array|Object|string} collection The collection to iterate over.
11864 * @param {Function|Object|string} [callback=identity] The function called
11865 * per iteration. If a property name or object is provided it will be used
11866 * to create a "_.pluck" or "_.where" style callback, respectively.
11867 * @param {*} [thisArg] The `this` binding of `callback`.
11868 * @returns {boolean} Returns `true` if all elements passed the callback check,
11869 * else `false`.
11870 * @example
11871 *
11872 * _.every([true, 1, null, 'yes']);
11873 * // => false
11874 *
11875 * var characters = [
11876 * { 'name': 'barney', 'age': 36 },
11877 * { 'name': 'fred', 'age': 40 }
11878 * ];
11879 *
11880 * // using "_.pluck" callback shorthand
11881 * _.every(characters, 'age');
11882 * // => true
11883 *
11884 * // using "_.where" callback shorthand
11885 * _.every(characters, { 'age': 36 });
11886 * // => false
11887 */
11888 function every(collection, callback, thisArg) {
11889 var result = true;
11890 callback = lodash.createCallback(callback, thisArg, 3);
11891
11892 var index = -1,
11893 length = collection ? collection.length : 0;
11894
11895 if (typeof length == 'number') {
11896 while (++index < length) {
11897 if (!(result = !!callback(collection[index], index, collection))) {
11898 break;
11899 }
11900 }
11901 } else {
11902 forOwn(collection, function(value, index, collection) {
11903 return (result = !!callback(value, index, collection));
11904 });
11905 }
11906 return result;
11907 }
11908
11909 /**
11910 * Iterates over elements of a collection, returning an array of all elements
11911 * the callback returns truey for. The callback is bound to `thisArg` and
11912 * invoked with three arguments; (value, index|key, collection).
11913 *
11914 * If a property name is provided for `callback` the created "_.pluck" style
11915 * callback will return the property value of the given element.
11916 *
11917 * If an object is provided for `callback` the created "_.where" style callback
11918 * will return `true` for elements that have the properties of the given object,
11919 * else `false`.
11920 *
11921 * @static
11922 * @memberOf _
11923 * @alias select
11924 * @category Collections
11925 * @param {Array|Object|string} collection The collection to iterate over.
11926 * @param {Function|Object|string} [callback=identity] The function called
11927 * per iteration. If a property name or object is provided it will be used
11928 * to create a "_.pluck" or "_.where" style callback, respectively.
11929 * @param {*} [thisArg] The `this` binding of `callback`.
11930 * @returns {Array} Returns a new array of elements that passed the callback check.
11931 * @example
11932 *
11933 * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
11934 * // => [2, 4, 6]
11935 *
11936 * var characters = [
11937 * { 'name': 'barney', 'age': 36, 'blocked': false },
11938 * { 'name': 'fred', 'age': 40, 'blocked': true }
11939 * ];
11940 *
11941 * // using "_.pluck" callback shorthand
11942 * _.filter(characters, 'blocked');
11943 * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
11944 *
11945 * // using "_.where" callback shorthand
11946 * _.filter(characters, { 'age': 36 });
11947 * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
11948 */
11949 function filter(collection, callback, thisArg) {
11950 var result = [];
11951 callback = lodash.createCallback(callback, thisArg, 3);
11952
11953 var index = -1,
11954 length = collection ? collection.length : 0;
11955
11956 if (typeof length == 'number') {
11957 while (++index < length) {
11958 var value = collection[index];
11959 if (callback(value, index, collection)) {
11960 result.push(value);
11961 }
11962 }
11963 } else {
11964 forOwn(collection, function(value, index, collection) {
11965 if (callback(value, index, collection)) {
11966 result.push(value);
11967 }
11968 });
11969 }
11970 return result;
11971 }
11972
11973 /**
11974 * Iterates over elements of a collection, returning the first element that
11975 * the callback returns truey for. The callback is bound to `thisArg` and
11976 * invoked with three arguments; (value, index|key, collection).
11977 *
11978 * If a property name is provided for `callback` the created "_.pluck" style
11979 * callback will return the property value of the given element.
11980 *
11981 * If an object is provided for `callback` the created "_.where" style callback
11982 * will return `true` for elements that have the properties of the given object,
11983 * else `false`.
11984 *
11985 * @static
11986 * @memberOf _
11987 * @alias detect, findWhere
11988 * @category Collections
11989 * @param {Array|Object|string} collection The collection to iterate over.
11990 * @param {Function|Object|string} [callback=identity] The function called
11991 * per iteration. If a property name or object is provided it will be used
11992 * to create a "_.pluck" or "_.where" style callback, respectively.
11993 * @param {*} [thisArg] The `this` binding of `callback`.
11994 * @returns {*} Returns the found element, else `undefined`.
11995 * @example
11996 *
11997 * var characters = [
11998 * { 'name': 'barney', 'age': 36, 'blocked': false },
11999 * { 'name': 'fred', 'age': 40, 'blocked': true },
12000 * { 'name': 'pebbles', 'age': 1, 'blocked': false }
12001 * ];
12002 *
12003 * _.find(characters, function(chr) {
12004 * return chr.age < 40;
12005 * });
12006 * // => { 'name': 'barney', 'age': 36, 'blocked': false }
12007 *
12008 * // using "_.where" callback shorthand
12009 * _.find(characters, { 'age': 1 });
12010 * // => { 'name': 'pebbles', 'age': 1, 'blocked': false }
12011 *
12012 * // using "_.pluck" callback shorthand
12013 * _.find(characters, 'blocked');
12014 * // => { 'name': 'fred', 'age': 40, 'blocked': true }
12015 */
12016 function find(collection, callback, thisArg) {
12017 callback = lodash.createCallback(callback, thisArg, 3);
12018
12019 var index = -1,
12020 length = collection ? collection.length : 0;
12021
12022 if (typeof length == 'number') {
12023 while (++index < length) {
12024 var value = collection[index];
12025 if (callback(value, index, collection)) {
12026 return value;
12027 }
12028 }
12029 } else {
12030 var result;
12031 forOwn(collection, function(value, index, collection) {
12032 if (callback(value, index, collection)) {
12033 result = value;
12034 return false;
12035 }
12036 });
12037 return result;
12038 }
12039 }
12040
12041 /**
12042 * This method is like `_.find` except that it iterates over elements
12043 * of a `collection` from right to left.
12044 *
12045 * @static
12046 * @memberOf _
12047 * @category Collections
12048 * @param {Array|Object|string} collection The collection to iterate over.
12049 * @param {Function|Object|string} [callback=identity] The function called
12050 * per iteration. If a property name or object is provided it will be used
12051 * to create a "_.pluck" or "_.where" style callback, respectively.
12052 * @param {*} [thisArg] The `this` binding of `callback`.
12053 * @returns {*} Returns the found element, else `undefined`.
12054 * @example
12055 *
12056 * _.findLast([1, 2, 3, 4], function(num) {
12057 * return num % 2 == 1;
12058 * });
12059 * // => 3
12060 */
12061 function findLast(collection, callback, thisArg) {
12062 var result;
12063 callback = lodash.createCallback(callback, thisArg, 3);
12064 forEachRight(collection, function(value, index, collection) {
12065 if (callback(value, index, collection)) {
12066 result = value;
12067 return false;
12068 }
12069 });
12070 return result;
12071 }
12072
12073 /**
12074 * Iterates over elements of a collection, executing the callback for each
12075 * element. The callback is bound to `thisArg` and invoked with three arguments;
12076 * (value, index|key, collection). Callbacks may exit iteration early by
12077 * explicitly returning `false`.
12078 *
12079 * Note: As with other "Collections" methods, objects with a `length` property
12080 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
12081 * may be used for object iteration.
12082 *
12083 * @static
12084 * @memberOf _
12085 * @alias each
12086 * @category Collections
12087 * @param {Array|Object|string} collection The collection to iterate over.
12088 * @param {Function} [callback=identity] The function called per iteration.
12089 * @param {*} [thisArg] The `this` binding of `callback`.
12090 * @returns {Array|Object|string} Returns `collection`.
12091 * @example
12092 *
12093 * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
12094 * // => logs each number and returns '1,2,3'
12095 *
12096 * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
12097 * // => logs each number and returns the object (property order is not guaranteed across environments)
12098 */
12099 function forEach(collection, callback, thisArg) {
12100 var index = -1,
12101 length = collection ? collection.length : 0;
12102
12103 callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
12104 if (typeof length == 'number') {
12105 while (++index < length) {
12106 if (callback(collection[index], index, collection) === false) {
12107 break;
12108 }
12109 }
12110 } else {
12111 forOwn(collection, callback);
12112 }
12113 return collection;
12114 }
12115
12116 /**
12117 * This method is like `_.forEach` except that it iterates over elements
12118 * of a `collection` from right to left.
12119 *
12120 * @static
12121 * @memberOf _
12122 * @alias eachRight
12123 * @category Collections
12124 * @param {Array|Object|string} collection The collection to iterate over.
12125 * @param {Function} [callback=identity] The function called per iteration.
12126 * @param {*} [thisArg] The `this` binding of `callback`.
12127 * @returns {Array|Object|string} Returns `collection`.
12128 * @example
12129 *
12130 * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(',');
12131 * // => logs each number from right to left and returns '3,2,1'
12132 */
12133 function forEachRight(collection, callback, thisArg) {
12134 var length = collection ? collection.length : 0;
12135 callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3);
12136 if (typeof length == 'number') {
12137 while (length--) {
12138 if (callback(collection[length], length, collection) === false) {
12139 break;
12140 }
12141 }
12142 } else {
12143 var props = keys(collection);
12144 length = props.length;
12145 forOwn(collection, function(value, key, collection) {
12146 key = props ? props[--length] : --length;
12147 return callback(collection[key], key, collection);
12148 });
12149 }
12150 return collection;
12151 }
12152
12153 /**
12154 * Creates an object composed of keys generated from the results of running
12155 * each element of a collection through the callback. The corresponding value
12156 * of each key is an array of the elements responsible for generating the key.
12157 * The callback is bound to `thisArg` and invoked with three arguments;
12158 * (value, index|key, collection).
12159 *
12160 * If a property name is provided for `callback` the created "_.pluck" style
12161 * callback will return the property value of the given element.
12162 *
12163 * If an object is provided for `callback` the created "_.where" style callback
12164 * will return `true` for elements that have the properties of the given object,
12165 * else `false`
12166 *
12167 * @static
12168 * @memberOf _
12169 * @category Collections
12170 * @param {Array|Object|string} collection The collection to iterate over.
12171 * @param {Function|Object|string} [callback=identity] The function called
12172 * per iteration. If a property name or object is provided it will be used
12173 * to create a "_.pluck" or "_.where" style callback, respectively.
12174 * @param {*} [thisArg] The `this` binding of `callback`.
12175 * @returns {Object} Returns the composed aggregate object.
12176 * @example
12177 *
12178 * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
12179 * // => { '4': [4.2], '6': [6.1, 6.4] }
12180 *
12181 * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
12182 * // => { '4': [4.2], '6': [6.1, 6.4] }
12183 *
12184 * // using "_.pluck" callback shorthand
12185 * _.groupBy(['one', 'two', 'three'], 'length');
12186 * // => { '3': ['one', 'two'], '5': ['three'] }
12187 */
12188 var groupBy = createAggregator(function(result, value, key) {
12189 (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
12190 });
12191
12192 /**
12193 * Creates an object composed of keys generated from the results of running
12194 * each element of the collection through the given callback. The corresponding
12195 * value of each key is the last element responsible for generating the key.
12196 * The callback is bound to `thisArg` and invoked with three arguments;
12197 * (value, index|key, collection).
12198 *
12199 * If a property name is provided for `callback` the created "_.pluck" style
12200 * callback will return the property value of the given element.
12201 *
12202 * If an object is provided for `callback` the created "_.where" style callback
12203 * will return `true` for elements that have the properties of the given object,
12204 * else `false`.
12205 *
12206 * @static
12207 * @memberOf _
12208 * @category Collections
12209 * @param {Array|Object|string} collection The collection to iterate over.
12210 * @param {Function|Object|string} [callback=identity] The function called
12211 * per iteration. If a property name or object is provided it will be used
12212 * to create a "_.pluck" or "_.where" style callback, respectively.
12213 * @param {*} [thisArg] The `this` binding of `callback`.
12214 * @returns {Object} Returns the composed aggregate object.
12215 * @example
12216 *
12217 * var keys = [
12218 * { 'dir': 'left', 'code': 97 },
12219 * { 'dir': 'right', 'code': 100 }
12220 * ];
12221 *
12222 * _.indexBy(keys, 'dir');
12223 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
12224 *
12225 * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
12226 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
12227 *
12228 * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String);
12229 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
12230 */
12231 var indexBy = createAggregator(function(result, value, key) {
12232 result[key] = value;
12233 });
12234
12235 /**
12236 * Invokes the method named by `methodName` on each element in the `collection`
12237 * returning an array of the results of each invoked method. Additional arguments
12238 * will be provided to each invoked method. If `methodName` is a function it
12239 * will be invoked for, and `this` bound to, each element in the `collection`.
12240 *
12241 * @static
12242 * @memberOf _
12243 * @category Collections
12244 * @param {Array|Object|string} collection The collection to iterate over.
12245 * @param {Function|string} methodName The name of the method to invoke or
12246 * the function invoked per iteration.
12247 * @param {...*} [arg] Arguments to invoke the method with.
12248 * @returns {Array} Returns a new array of the results of each invoked method.
12249 * @example
12250 *
12251 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
12252 * // => [[1, 5, 7], [1, 2, 3]]
12253 *
12254 * _.invoke([123, 456], String.prototype.split, '');
12255 * // => [['1', '2', '3'], ['4', '5', '6']]
12256 */
12257 function invoke(collection, methodName) {
12258 var args = slice(arguments, 2),
12259 index = -1,
12260 isFunc = typeof methodName == 'function',
12261 length = collection ? collection.length : 0,
12262 result = Array(typeof length == 'number' ? length : 0);
12263
12264 forEach(collection, function(value) {
12265 result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
12266 });
12267 return result;
12268 }
12269
12270 /**
12271 * Creates an array of values by running each element in the collection
12272 * through the callback. The callback is bound to `thisArg` and invoked with
12273 * three arguments; (value, index|key, collection).
12274 *
12275 * If a property name is provided for `callback` the created "_.pluck" style
12276 * callback will return the property value of the given element.
12277 *
12278 * If an object is provided for `callback` the created "_.where" style callback
12279 * will return `true` for elements that have the properties of the given object,
12280 * else `false`.
12281 *
12282 * @static
12283 * @memberOf _
12284 * @alias collect
12285 * @category Collections
12286 * @param {Array|Object|string} collection The collection to iterate over.
12287 * @param {Function|Object|string} [callback=identity] The function called
12288 * per iteration. If a property name or object is provided it will be used
12289 * to create a "_.pluck" or "_.where" style callback, respectively.
12290 * @param {*} [thisArg] The `this` binding of `callback`.
12291 * @returns {Array} Returns a new array of the results of each `callback` execution.
12292 * @example
12293 *
12294 * _.map([1, 2, 3], function(num) { return num * 3; });
12295 * // => [3, 6, 9]
12296 *
12297 * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
12298 * // => [3, 6, 9] (property order is not guaranteed across environments)
12299 *
12300 * var characters = [
12301 * { 'name': 'barney', 'age': 36 },
12302 * { 'name': 'fred', 'age': 40 }
12303 * ];
12304 *
12305 * // using "_.pluck" callback shorthand
12306 * _.map(characters, 'name');
12307 * // => ['barney', 'fred']
12308 */
12309 function map(collection, callback, thisArg) {
12310 var index = -1,
12311 length = collection ? collection.length : 0;
12312
12313 callback = lodash.createCallback(callback, thisArg, 3);
12314 if (typeof length == 'number') {
12315 var result = Array(length);
12316 while (++index < length) {
12317 result[index] = callback(collection[index], index, collection);
12318 }
12319 } else {
12320 result = [];
12321 forOwn(collection, function(value, key, collection) {
12322 result[++index] = callback(value, key, collection);
12323 });
12324 }
12325 return result;
12326 }
12327
12328 /**
12329 * Retrieves the maximum value of a collection. If the collection is empty or
12330 * falsey `-Infinity` is returned. If a callback is provided it will be executed
12331 * for each value in the collection to generate the criterion by which the value
12332 * is ranked. The callback is bound to `thisArg` and invoked with three
12333 * arguments; (value, index, collection).
12334 *
12335 * If a property name is provided for `callback` the created "_.pluck" style
12336 * callback will return the property value of the given element.
12337 *
12338 * If an object is provided for `callback` the created "_.where" style callback
12339 * will return `true` for elements that have the properties of the given object,
12340 * else `false`.
12341 *
12342 * @static
12343 * @memberOf _
12344 * @category Collections
12345 * @param {Array|Object|string} collection The collection to iterate over.
12346 * @param {Function|Object|string} [callback=identity] The function called
12347 * per iteration. If a property name or object is provided it will be used
12348 * to create a "_.pluck" or "_.where" style callback, respectively.
12349 * @param {*} [thisArg] The `this` binding of `callback`.
12350 * @returns {*} Returns the maximum value.
12351 * @example
12352 *
12353 * _.max([4, 2, 8, 6]);
12354 * // => 8
12355 *
12356 * var characters = [
12357 * { 'name': 'barney', 'age': 36 },
12358 * { 'name': 'fred', 'age': 40 }
12359 * ];
12360 *
12361 * _.max(characters, function(chr) { return chr.age; });
12362 * // => { 'name': 'fred', 'age': 40 };
12363 *
12364 * // using "_.pluck" callback shorthand
12365 * _.max(characters, 'age');
12366 * // => { 'name': 'fred', 'age': 40 };
12367 */
12368 function max(collection, callback, thisArg) {
12369 var computed = -Infinity,
12370 result = computed;
12371
12372 // allows working with functions like `_.map` without using
12373 // their `index` argument as a callback
12374 if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
12375 callback = null;
12376 }
12377 if (callback == null && isArray(collection)) {
12378 var index = -1,
12379 length = collection.length;
12380
12381 while (++index < length) {
12382 var value = collection[index];
12383 if (value > result) {
12384 result = value;
12385 }
12386 }
12387 } else {
12388 callback = (callback == null && isString(collection))
12389 ? charAtCallback
12390 : lodash.createCallback(callback, thisArg, 3);
12391
12392 forEach(collection, function(value, index, collection) {
12393 var current = callback(value, index, collection);
12394 if (current > computed) {
12395 computed = current;
12396 result = value;
12397 }
12398 });
12399 }
12400 return result;
12401 }
12402
12403 /**
12404 * Retrieves the minimum value of a collection. If the collection is empty or
12405 * falsey `Infinity` is returned. If a callback is provided it will be executed
12406 * for each value in the collection to generate the criterion by which the value
12407 * is ranked. The callback is bound to `thisArg` and invoked with three
12408 * arguments; (value, index, collection).
12409 *
12410 * If a property name is provided for `callback` the created "_.pluck" style
12411 * callback will return the property value of the given element.
12412 *
12413 * If an object is provided for `callback` the created "_.where" style callback
12414 * will return `true` for elements that have the properties of the given object,
12415 * else `false`.
12416 *
12417 * @static
12418 * @memberOf _
12419 * @category Collections
12420 * @param {Array|Object|string} collection The collection to iterate over.
12421 * @param {Function|Object|string} [callback=identity] The function called
12422 * per iteration. If a property name or object is provided it will be used
12423 * to create a "_.pluck" or "_.where" style callback, respectively.
12424 * @param {*} [thisArg] The `this` binding of `callback`.
12425 * @returns {*} Returns the minimum value.
12426 * @example
12427 *
12428 * _.min([4, 2, 8, 6]);
12429 * // => 2
12430 *
12431 * var characters = [
12432 * { 'name': 'barney', 'age': 36 },
12433 * { 'name': 'fred', 'age': 40 }
12434 * ];
12435 *
12436 * _.min(characters, function(chr) { return chr.age; });
12437 * // => { 'name': 'barney', 'age': 36 };
12438 *
12439 * // using "_.pluck" callback shorthand
12440 * _.min(characters, 'age');
12441 * // => { 'name': 'barney', 'age': 36 };
12442 */
12443 function min(collection, callback, thisArg) {
12444 var computed = Infinity,
12445 result = computed;
12446
12447 // allows working with functions like `_.map` without using
12448 // their `index` argument as a callback
12449 if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) {
12450 callback = null;
12451 }
12452 if (callback == null && isArray(collection)) {
12453 var index = -1,
12454 length = collection.length;
12455
12456 while (++index < length) {
12457 var value = collection[index];
12458 if (value < result) {
12459 result = value;
12460 }
12461 }
12462 } else {
12463 callback = (callback == null && isString(collection))
12464 ? charAtCallback
12465 : lodash.createCallback(callback, thisArg, 3);
12466
12467 forEach(collection, function(value, index, collection) {
12468 var current = callback(value, index, collection);
12469 if (current < computed) {
12470 computed = current;
12471 result = value;
12472 }
12473 });
12474 }
12475 return result;
12476 }
12477
12478 /**
12479 * Retrieves the value of a specified property from all elements in the collection.
12480 *
12481 * @static
12482 * @memberOf _
12483 * @type Function
12484 * @category Collections
12485 * @param {Array|Object|string} collection The collection to iterate over.
12486 * @param {string} property The name of the property to pluck.
12487 * @returns {Array} Returns a new array of property values.
12488 * @example
12489 *
12490 * var characters = [
12491 * { 'name': 'barney', 'age': 36 },
12492 * { 'name': 'fred', 'age': 40 }
12493 * ];
12494 *
12495 * _.pluck(characters, 'name');
12496 * // => ['barney', 'fred']
12497 */
12498 var pluck = map;
12499
12500 /**
12501 * Reduces a collection to a value which is the accumulated result of running
12502 * each element in the collection through the callback, where each successive
12503 * callback execution consumes the return value of the previous execution. If
12504 * `accumulator` is not provided the first element of the collection will be
12505 * used as the initial `accumulator` value. The callback is bound to `thisArg`
12506 * and invoked with four arguments; (accumulator, value, index|key, collection).
12507 *
12508 * @static
12509 * @memberOf _
12510 * @alias foldl, inject
12511 * @category Collections
12512 * @param {Array|Object|string} collection The collection to iterate over.
12513 * @param {Function} [callback=identity] The function called per iteration.
12514 * @param {*} [accumulator] Initial value of the accumulator.
12515 * @param {*} [thisArg] The `this` binding of `callback`.
12516 * @returns {*} Returns the accumulated value.
12517 * @example
12518 *
12519 * var sum = _.reduce([1, 2, 3], function(sum, num) {
12520 * return sum + num;
12521 * });
12522 * // => 6
12523 *
12524 * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
12525 * result[key] = num * 3;
12526 * return result;
12527 * }, {});
12528 * // => { 'a': 3, 'b': 6, 'c': 9 }
12529 */
12530 function reduce(collection, callback, accumulator, thisArg) {
12531 if (!collection) return accumulator;
12532 var noaccum = arguments.length < 3;
12533 callback = lodash.createCallback(callback, thisArg, 4);
12534
12535 var index = -1,
12536 length = collection.length;
12537
12538 if (typeof length == 'number') {
12539 if (noaccum) {
12540 accumulator = collection[++index];
12541 }
12542 while (++index < length) {
12543 accumulator = callback(accumulator, collection[index], index, collection);
12544 }
12545 } else {
12546 forOwn(collection, function(value, index, collection) {
12547 accumulator = noaccum
12548 ? (noaccum = false, value)
12549 : callback(accumulator, value, index, collection)
12550 });
12551 }
12552 return accumulator;
12553 }
12554
12555 /**
12556 * This method is like `_.reduce` except that it iterates over elements
12557 * of a `collection` from right to left.
12558 *
12559 * @static
12560 * @memberOf _
12561 * @alias foldr
12562 * @category Collections
12563 * @param {Array|Object|string} collection The collection to iterate over.
12564 * @param {Function} [callback=identity] The function called per iteration.
12565 * @param {*} [accumulator] Initial value of the accumulator.
12566 * @param {*} [thisArg] The `this` binding of `callback`.
12567 * @returns {*} Returns the accumulated value.
12568 * @example
12569 *
12570 * var list = [[0, 1], [2, 3], [4, 5]];
12571 * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
12572 * // => [4, 5, 2, 3, 0, 1]
12573 */
12574 function reduceRight(collection, callback, accumulator, thisArg) {
12575 var noaccum = arguments.length < 3;
12576 callback = lodash.createCallback(callback, thisArg, 4);
12577 forEachRight(collection, function(value, index, collection) {
12578 accumulator = noaccum
12579 ? (noaccum = false, value)
12580 : callback(accumulator, value, index, collection);
12581 });
12582 return accumulator;
12583 }
12584
12585 /**
12586 * The opposite of `_.filter` this method returns the elements of a
12587 * collection that the callback does **not** return truey for.
12588 *
12589 * If a property name is provided for `callback` the created "_.pluck" style
12590 * callback will return the property value of the given element.
12591 *
12592 * If an object is provided for `callback` the created "_.where" style callback
12593 * will return `true` for elements that have the properties of the given object,
12594 * else `false`.
12595 *
12596 * @static
12597 * @memberOf _
12598 * @category Collections
12599 * @param {Array|Object|string} collection The collection to iterate over.
12600 * @param {Function|Object|string} [callback=identity] The function called
12601 * per iteration. If a property name or object is provided it will be used
12602 * to create a "_.pluck" or "_.where" style callback, respectively.
12603 * @param {*} [thisArg] The `this` binding of `callback`.
12604 * @returns {Array} Returns a new array of elements that failed the callback check.
12605 * @example
12606 *
12607 * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
12608 * // => [1, 3, 5]
12609 *
12610 * var characters = [
12611 * { 'name': 'barney', 'age': 36, 'blocked': false },
12612 * { 'name': 'fred', 'age': 40, 'blocked': true }
12613 * ];
12614 *
12615 * // using "_.pluck" callback shorthand
12616 * _.reject(characters, 'blocked');
12617 * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }]
12618 *
12619 * // using "_.where" callback shorthand
12620 * _.reject(characters, { 'age': 36 });
12621 * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }]
12622 */
12623 function reject(collection, callback, thisArg) {
12624 callback = lodash.createCallback(callback, thisArg, 3);
12625 return filter(collection, function(value, index, collection) {
12626 return !callback(value, index, collection);
12627 });
12628 }
12629
12630 /**
12631 * Retrieves a random element or `n` random elements from a collection.
12632 *
12633 * @static
12634 * @memberOf _
12635 * @category Collections
12636 * @param {Array|Object|string} collection The collection to sample.
12637 * @param {number} [n] The number of elements to sample.
12638 * @param- {Object} [guard] Allows working with functions like `_.map`
12639 * without using their `index` arguments as `n`.
12640 * @returns {Array} Returns the random sample(s) of `collection`.
12641 * @example
12642 *
12643 * _.sample([1, 2, 3, 4]);
12644 * // => 2
12645 *
12646 * _.sample([1, 2, 3, 4], 2);
12647 * // => [3, 1]
12648 */
12649 function sample(collection, n, guard) {
12650 if (collection && typeof collection.length != 'number') {
12651 collection = values(collection);
12652 }
12653 if (n == null || guard) {
12654 return collection ? collection[baseRandom(0, collection.length - 1)] : undefined;
12655 }
12656 var result = shuffle(collection);
12657 result.length = nativeMin(nativeMax(0, n), result.length);
12658 return result;
12659 }
12660
12661 /**
12662 * Creates an array of shuffled values, using a version of the Fisher-Yates
12663 * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
12664 *
12665 * @static
12666 * @memberOf _
12667 * @category Collections
12668 * @param {Array|Object|string} collection The collection to shuffle.
12669 * @returns {Array} Returns a new shuffled collection.
12670 * @example
12671 *
12672 * _.shuffle([1, 2, 3, 4, 5, 6]);
12673 * // => [4, 1, 6, 3, 5, 2]
12674 */
12675 function shuffle(collection) {
12676 var index = -1,
12677 length = collection ? collection.length : 0,
12678 result = Array(typeof length == 'number' ? length : 0);
12679
12680 forEach(collection, function(value) {
12681 var rand = baseRandom(0, ++index);
12682 result[index] = result[rand];
12683 result[rand] = value;
12684 });
12685 return result;
12686 }
12687
12688 /**
12689 * Gets the size of the `collection` by returning `collection.length` for arrays
12690 * and array-like objects or the number of own enumerable properties for objects.
12691 *
12692 * @static
12693 * @memberOf _
12694 * @category Collections
12695 * @param {Array|Object|string} collection The collection to inspect.
12696 * @returns {number} Returns `collection.length` or number of own enumerable properties.
12697 * @example
12698 *
12699 * _.size([1, 2]);
12700 * // => 2
12701 *
12702 * _.size({ 'one': 1, 'two': 2, 'three': 3 });
12703 * // => 3
12704 *
12705 * _.size('pebbles');
12706 * // => 7
12707 */
12708 function size(collection) {
12709 var length = collection ? collection.length : 0;
12710 return typeof length == 'number' ? length : keys(collection).length;
12711 }
12712
12713 /**
12714 * Checks if the callback returns a truey value for **any** element of a
12715 * collection. The function returns as soon as it finds a passing value and
12716 * does not iterate over the entire collection. The callback is bound to
12717 * `thisArg` and invoked with three arguments; (value, index|key, collection).
12718 *
12719 * If a property name is provided for `callback` the created "_.pluck" style
12720 * callback will return the property value of the given element.
12721 *
12722 * If an object is provided for `callback` the created "_.where" style callback
12723 * will return `true` for elements that have the properties of the given object,
12724 * else `false`.
12725 *
12726 * @static
12727 * @memberOf _
12728 * @alias any
12729 * @category Collections
12730 * @param {Array|Object|string} collection The collection to iterate over.
12731 * @param {Function|Object|string} [callback=identity] The function called
12732 * per iteration. If a property name or object is provided it will be used
12733 * to create a "_.pluck" or "_.where" style callback, respectively.
12734 * @param {*} [thisArg] The `this` binding of `callback`.
12735 * @returns {boolean} Returns `true` if any element passed the callback check,
12736 * else `false`.
12737 * @example
12738 *
12739 * _.some([null, 0, 'yes', false], Boolean);
12740 * // => true
12741 *
12742 * var characters = [
12743 * { 'name': 'barney', 'age': 36, 'blocked': false },
12744 * { 'name': 'fred', 'age': 40, 'blocked': true }
12745 * ];
12746 *
12747 * // using "_.pluck" callback shorthand
12748 * _.some(characters, 'blocked');
12749 * // => true
12750 *
12751 * // using "_.where" callback shorthand
12752 * _.some(characters, { 'age': 1 });
12753 * // => false
12754 */
12755 function some(collection, callback, thisArg) {
12756 var result;
12757 callback = lodash.createCallback(callback, thisArg, 3);
12758
12759 var index = -1,
12760 length = collection ? collection.length : 0;
12761
12762 if (typeof length == 'number') {
12763 while (++index < length) {
12764 if ((result = callback(collection[index], index, collection))) {
12765 break;
12766 }
12767 }
12768 } else {
12769 forOwn(collection, function(value, index, collection) {
12770 return !(result = callback(value, index, collection));
12771 });
12772 }
12773 return !!result;
12774 }
12775
12776 /**
12777 * Creates an array of elements, sorted in ascending order by the results of
12778 * running each element in a collection through the callback. This method
12779 * performs a stable sort, that is, it will preserve the original sort order
12780 * of equal elements. The callback is bound to `thisArg` and invoked with
12781 * three arguments; (value, index|key, collection).
12782 *
12783 * If a property name is provided for `callback` the created "_.pluck" style
12784 * callback will return the property value of the given element.
12785 *
12786 * If an array of property names is provided for `callback` the collection
12787 * will be sorted by each property value.
12788 *
12789 * If an object is provided for `callback` the created "_.where" style callback
12790 * will return `true` for elements that have the properties of the given object,
12791 * else `false`.
12792 *
12793 * @static
12794 * @memberOf _
12795 * @category Collections
12796 * @param {Array|Object|string} collection The collection to iterate over.
12797 * @param {Array|Function|Object|string} [callback=identity] The function called
12798 * per iteration. If a property name or object is provided it will be used
12799 * to create a "_.pluck" or "_.where" style callback, respectively.
12800 * @param {*} [thisArg] The `this` binding of `callback`.
12801 * @returns {Array} Returns a new array of sorted elements.
12802 * @example
12803 *
12804 * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
12805 * // => [3, 1, 2]
12806 *
12807 * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
12808 * // => [3, 1, 2]
12809 *
12810 * var characters = [
12811 * { 'name': 'barney', 'age': 36 },
12812 * { 'name': 'fred', 'age': 40 },
12813 * { 'name': 'barney', 'age': 26 },
12814 * { 'name': 'fred', 'age': 30 }
12815 * ];
12816 *
12817 * // using "_.pluck" callback shorthand
12818 * _.map(_.sortBy(characters, 'age'), _.values);
12819 * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]]
12820 *
12821 * // sorting by multiple properties
12822 * _.map(_.sortBy(characters, ['name', 'age']), _.values);
12823 * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]
12824 */
12825 function sortBy(collection, callback, thisArg) {
12826 var index = -1,
12827 isArr = isArray(callback),
12828 length = collection ? collection.length : 0,
12829 result = Array(typeof length == 'number' ? length : 0);
12830
12831 if (!isArr) {
12832 callback = lodash.createCallback(callback, thisArg, 3);
12833 }
12834 forEach(collection, function(value, key, collection) {
12835 var object = result[++index] = getObject();
12836 if (isArr) {
12837 object.criteria = map(callback, function(key) { return value[key]; });
12838 } else {
12839 (object.criteria = getArray())[0] = callback(value, key, collection);
12840 }
12841 object.index = index;
12842 object.value = value;
12843 });
12844
12845 length = result.length;
12846 result.sort(compareAscending);
12847 while (length--) {
12848 var object = result[length];
12849 result[length] = object.value;
12850 if (!isArr) {
12851 releaseArray(object.criteria);
12852 }
12853 releaseObject(object);
12854 }
12855 return result;
12856 }
12857
12858 /**
12859 * Converts the `collection` to an array.
12860 *
12861 * @static
12862 * @memberOf _
12863 * @category Collections
12864 * @param {Array|Object|string} collection The collection to convert.
12865 * @returns {Array} Returns the new converted array.
12866 * @example
12867 *
12868 * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
12869 * // => [2, 3, 4]
12870 */
12871 function toArray(collection) {
12872 if (collection && typeof collection.length == 'number') {
12873 return slice(collection);
12874 }
12875 return values(collection);
12876 }
12877
12878 /**
12879 * Performs a deep comparison of each element in a `collection` to the given
12880 * `properties` object, returning an array of all elements that have equivalent
12881 * property values.
12882 *
12883 * @static
12884 * @memberOf _
12885 * @type Function
12886 * @category Collections
12887 * @param {Array|Object|string} collection The collection to iterate over.
12888 * @param {Object} props The object of property values to filter by.
12889 * @returns {Array} Returns a new array of elements that have the given properties.
12890 * @example
12891 *
12892 * var characters = [
12893 * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
12894 * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
12895 * ];
12896 *
12897 * _.where(characters, { 'age': 36 });
12898 * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }]
12899 *
12900 * _.where(characters, { 'pets': ['dino'] });
12901 * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }]
12902 */
12903 var where = filter;
12904
12905 /*--------------------------------------------------------------------------*/
12906
12907 /**
12908 * Creates an array with all falsey values removed. The values `false`, `null`,
12909 * `0`, `""`, `undefined`, and `NaN` are all falsey.
12910 *
12911 * @static
12912 * @memberOf _
12913 * @category Arrays
12914 * @param {Array} array The array to compact.
12915 * @returns {Array} Returns a new array of filtered values.
12916 * @example
12917 *
12918 * _.compact([0, 1, false, 2, '', 3]);
12919 * // => [1, 2, 3]
12920 */
12921 function compact(array) {
12922 var index = -1,
12923 length = array ? array.length : 0,
12924 result = [];
12925
12926 while (++index < length) {
12927 var value = array[index];
12928 if (value) {
12929 result.push(value);
12930 }
12931 }
12932 return result;
12933 }
12934
12935 /**
12936 * Creates an array excluding all values of the provided arrays using strict
12937 * equality for comparisons, i.e. `===`.
12938 *
12939 * @static
12940 * @memberOf _
12941 * @category Arrays
12942 * @param {Array} array The array to process.
12943 * @param {...Array} [values] The arrays of values to exclude.
12944 * @returns {Array} Returns a new array of filtered values.
12945 * @example
12946 *
12947 * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
12948 * // => [1, 3, 4]
12949 */
12950 function difference(array) {
12951 return baseDifference(array, baseFlatten(arguments, true, true, 1));
12952 }
12953
12954 /**
12955 * This method is like `_.find` except that it returns the index of the first
12956 * element that passes the callback check, instead of the element itself.
12957 *
12958 * If a property name is provided for `callback` the created "_.pluck" style
12959 * callback will return the property value of the given element.
12960 *
12961 * If an object is provided for `callback` the created "_.where" style callback
12962 * will return `true` for elements that have the properties of the given object,
12963 * else `false`.
12964 *
12965 * @static
12966 * @memberOf _
12967 * @category Arrays
12968 * @param {Array} array The array to search.
12969 * @param {Function|Object|string} [callback=identity] The function called
12970 * per iteration. If a property name or object is provided it will be used
12971 * to create a "_.pluck" or "_.where" style callback, respectively.
12972 * @param {*} [thisArg] The `this` binding of `callback`.
12973 * @returns {number} Returns the index of the found element, else `-1`.
12974 * @example
12975 *
12976 * var characters = [
12977 * { 'name': 'barney', 'age': 36, 'blocked': false },
12978 * { 'name': 'fred', 'age': 40, 'blocked': true },
12979 * { 'name': 'pebbles', 'age': 1, 'blocked': false }
12980 * ];
12981 *
12982 * _.findIndex(characters, function(chr) {
12983 * return chr.age < 20;
12984 * });
12985 * // => 2
12986 *
12987 * // using "_.where" callback shorthand
12988 * _.findIndex(characters, { 'age': 36 });
12989 * // => 0
12990 *
12991 * // using "_.pluck" callback shorthand
12992 * _.findIndex(characters, 'blocked');
12993 * // => 1
12994 */
12995 function findIndex(array, callback, thisArg) {
12996 var index = -1,
12997 length = array ? array.length : 0;
12998
12999 callback = lodash.createCallback(callback, thisArg, 3);
13000 while (++index < length) {
13001 if (callback(array[index], index, array)) {
13002 return index;
13003 }
13004 }
13005 return -1;
13006 }
13007
13008 /**
13009 * This method is like `_.findIndex` except that it iterates over elements
13010 * of a `collection` from right to left.
13011 *
13012 * If a property name is provided for `callback` the created "_.pluck" style
13013 * callback will return the property value of the given element.
13014 *
13015 * If an object is provided for `callback` the created "_.where" style callback
13016 * will return `true` for elements that have the properties of the given object,
13017 * else `false`.
13018 *
13019 * @static
13020 * @memberOf _
13021 * @category Arrays
13022 * @param {Array} array The array to search.
13023 * @param {Function|Object|string} [callback=identity] The function called
13024 * per iteration. If a property name or object is provided it will be used
13025 * to create a "_.pluck" or "_.where" style callback, respectively.
13026 * @param {*} [thisArg] The `this` binding of `callback`.
13027 * @returns {number} Returns the index of the found element, else `-1`.
13028 * @example
13029 *
13030 * var characters = [
13031 * { 'name': 'barney', 'age': 36, 'blocked': true },
13032 * { 'name': 'fred', 'age': 40, 'blocked': false },
13033 * { 'name': 'pebbles', 'age': 1, 'blocked': true }
13034 * ];
13035 *
13036 * _.findLastIndex(characters, function(chr) {
13037 * return chr.age > 30;
13038 * });
13039 * // => 1
13040 *
13041 * // using "_.where" callback shorthand
13042 * _.findLastIndex(characters, { 'age': 36 });
13043 * // => 0
13044 *
13045 * // using "_.pluck" callback shorthand
13046 * _.findLastIndex(characters, 'blocked');
13047 * // => 2
13048 */
13049 function findLastIndex(array, callback, thisArg) {
13050 var length = array ? array.length : 0;
13051 callback = lodash.createCallback(callback, thisArg, 3);
13052 while (length--) {
13053 if (callback(array[length], length, array)) {
13054 return length;
13055 }
13056 }
13057 return -1;
13058 }
13059
13060 /**
13061 * Gets the first element or first `n` elements of an array. If a callback
13062 * is provided elements at the beginning of the array are returned as long
13063 * as the callback returns truey. The callback is bound to `thisArg` and
13064 * invoked with three arguments; (value, index, array).
13065 *
13066 * If a property name is provided for `callback` the created "_.pluck" style
13067 * callback will return the property value of the given element.
13068 *
13069 * If an object is provided for `callback` the created "_.where" style callback
13070 * will return `true` for elements that have the properties of the given object,
13071 * else `false`.
13072 *
13073 * @static
13074 * @memberOf _
13075 * @alias head, take
13076 * @category Arrays
13077 * @param {Array} array The array to query.
13078 * @param {Function|Object|number|string} [callback] The function called
13079 * per element or the number of elements to return. If a property name or
13080 * object is provided it will be used to create a "_.pluck" or "_.where"
13081 * style callback, respectively.
13082 * @param {*} [thisArg] The `this` binding of `callback`.
13083 * @returns {*} Returns the first element(s) of `array`.
13084 * @example
13085 *
13086 * _.first([1, 2, 3]);
13087 * // => 1
13088 *
13089 * _.first([1, 2, 3], 2);
13090 * // => [1, 2]
13091 *
13092 * _.first([1, 2, 3], function(num) {
13093 * return num < 3;
13094 * });
13095 * // => [1, 2]
13096 *
13097 * var characters = [
13098 * { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
13099 * { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
13100 * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
13101 * ];
13102 *
13103 * // using "_.pluck" callback shorthand
13104 * _.first(characters, 'blocked');
13105 * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }]
13106 *
13107 * // using "_.where" callback shorthand
13108 * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name');
13109 * // => ['barney', 'fred']
13110 */
13111 function first(array, callback, thisArg) {
13112 var n = 0,
13113 length = array ? array.length : 0;
13114
13115 if (typeof callback != 'number' && callback != null) {
13116 var index = -1;
13117 callback = lodash.createCallback(callback, thisArg, 3);
13118 while (++index < length && callback(array[index], index, array)) {
13119 n++;
13120 }
13121 } else {
13122 n = callback;
13123 if (n == null || thisArg) {
13124 return array ? array[0] : undefined;
13125 }
13126 }
13127 return slice(array, 0, nativeMin(nativeMax(0, n), length));
13128 }
13129
13130 /**
13131 * Flattens a nested array (the nesting can be to any depth). If `isShallow`
13132 * is truey, the array will only be flattened a single level. If a callback
13133 * is provided each element of the array is passed through the callback before
13134 * flattening. The callback is bound to `thisArg` and invoked with three
13135 * arguments; (value, index, array).
13136 *
13137 * If a property name is provided for `callback` the created "_.pluck" style
13138 * callback will return the property value of the given element.
13139 *
13140 * If an object is provided for `callback` the created "_.where" style callback
13141 * will return `true` for elements that have the properties of the given object,
13142 * else `false`.
13143 *
13144 * @static
13145 * @memberOf _
13146 * @category Arrays
13147 * @param {Array} array The array to flatten.
13148 * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
13149 * @param {Function|Object|string} [callback=identity] The function called
13150 * per iteration. If a property name or object is provided it will be used
13151 * to create a "_.pluck" or "_.where" style callback, respectively.
13152 * @param {*} [thisArg] The `this` binding of `callback`.
13153 * @returns {Array} Returns a new flattened array.
13154 * @example
13155 *
13156 * _.flatten([1, [2], [3, [[4]]]]);
13157 * // => [1, 2, 3, 4];
13158 *
13159 * _.flatten([1, [2], [3, [[4]]]], true);
13160 * // => [1, 2, 3, [[4]]];
13161 *
13162 * var characters = [
13163 * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] },
13164 * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
13165 * ];
13166 *
13167 * // using "_.pluck" callback shorthand
13168 * _.flatten(characters, 'pets');
13169 * // => ['hoppy', 'baby puss', 'dino']
13170 */
13171 function flatten(array, isShallow, callback, thisArg) {
13172 // juggle arguments
13173 if (typeof isShallow != 'boolean' && isShallow != null) {
13174 thisArg = callback;
13175 callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow;
13176 isShallow = false;
13177 }
13178 if (callback != null) {
13179 array = map(array, callback, thisArg);
13180 }
13181 return baseFlatten(array, isShallow);
13182 }
13183
13184 /**
13185 * Gets the index at which the first occurrence of `value` is found using
13186 * strict equality for comparisons, i.e. `===`. If the array is already sorted
13187 * providing `true` for `fromIndex` will run a faster binary search.
13188 *
13189 * @static
13190 * @memberOf _
13191 * @category Arrays
13192 * @param {Array} array The array to search.
13193 * @param {*} value The value to search for.
13194 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
13195 * to perform a binary search on a sorted array.
13196 * @returns {number} Returns the index of the matched value or `-1`.
13197 * @example
13198 *
13199 * _.indexOf([1, 2, 3, 1, 2, 3], 2);
13200 * // => 1
13201 *
13202 * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
13203 * // => 4
13204 *
13205 * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
13206 * // => 2
13207 */
13208 function indexOf(array, value, fromIndex) {
13209 if (typeof fromIndex == 'number') {
13210 var length = array ? array.length : 0;
13211 fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
13212 } else if (fromIndex) {
13213 var index = sortedIndex(array, value);
13214 return array[index] === value ? index : -1;
13215 }
13216 return baseIndexOf(array, value, fromIndex);
13217 }
13218
13219 /**
13220 * Gets all but the last element or last `n` elements of an array. If a
13221 * callback is provided elements at the end of the array are excluded from
13222 * the result as long as the callback returns truey. The callback is bound
13223 * to `thisArg` and invoked with three arguments; (value, index, array).
13224 *
13225 * If a property name is provided for `callback` the created "_.pluck" style
13226 * callback will return the property value of the given element.
13227 *
13228 * If an object is provided for `callback` the created "_.where" style callback
13229 * will return `true` for elements that have the properties of the given object,
13230 * else `false`.
13231 *
13232 * @static
13233 * @memberOf _
13234 * @category Arrays
13235 * @param {Array} array The array to query.
13236 * @param {Function|Object|number|string} [callback=1] The function called
13237 * per element or the number of elements to exclude. If a property name or
13238 * object is provided it will be used to create a "_.pluck" or "_.where"
13239 * style callback, respectively.
13240 * @param {*} [thisArg] The `this` binding of `callback`.
13241 * @returns {Array} Returns a slice of `array`.
13242 * @example
13243 *
13244 * _.initial([1, 2, 3]);
13245 * // => [1, 2]
13246 *
13247 * _.initial([1, 2, 3], 2);
13248 * // => [1]
13249 *
13250 * _.initial([1, 2, 3], function(num) {
13251 * return num > 1;
13252 * });
13253 * // => [1]
13254 *
13255 * var characters = [
13256 * { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
13257 * { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
13258 * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
13259 * ];
13260 *
13261 * // using "_.pluck" callback shorthand
13262 * _.initial(characters, 'blocked');
13263 * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }]
13264 *
13265 * // using "_.where" callback shorthand
13266 * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name');
13267 * // => ['barney', 'fred']
13268 */
13269 function initial(array, callback, thisArg) {
13270 var n = 0,
13271 length = array ? array.length : 0;
13272
13273 if (typeof callback != 'number' && callback != null) {
13274 var index = length;
13275 callback = lodash.createCallback(callback, thisArg, 3);
13276 while (index-- && callback(array[index], index, array)) {
13277 n++;
13278 }
13279 } else {
13280 n = (callback == null || thisArg) ? 1 : callback || n;
13281 }
13282 return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
13283 }
13284
13285 /**
13286 * Creates an array of unique values present in all provided arrays using
13287 * strict equality for comparisons, i.e. `===`.
13288 *
13289 * @static
13290 * @memberOf _
13291 * @category Arrays
13292 * @param {...Array} [array] The arrays to inspect.
13293 * @returns {Array} Returns an array of shared values.
13294 * @example
13295 *
13296 * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]);
13297 * // => [1, 2]
13298 */
13299 function intersection() {
13300 var args = [],
13301 argsIndex = -1,
13302 argsLength = arguments.length,
13303 caches = getArray(),
13304 indexOf = getIndexOf(),
13305 trustIndexOf = indexOf === baseIndexOf,
13306 seen = getArray();
13307
13308 while (++argsIndex < argsLength) {
13309 var value = arguments[argsIndex];
13310 if (isArray(value) || isArguments(value)) {
13311 args.push(value);
13312 caches.push(trustIndexOf && value.length >= largeArraySize &&
13313 createCache(argsIndex ? args[argsIndex] : seen));
13314 }
13315 }
13316 var array = args[0],
13317 index = -1,
13318 length = array ? array.length : 0,
13319 result = [];
13320
13321 outer:
13322 while (++index < length) {
13323 var cache = caches[0];
13324 value = array[index];
13325
13326 if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) {
13327 argsIndex = argsLength;
13328 (cache || seen).push(value);
13329 while (--argsIndex) {
13330 cache = caches[argsIndex];
13331 if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {
13332 continue outer;
13333 }
13334 }
13335 result.push(value);
13336 }
13337 }
13338 while (argsLength--) {
13339 cache = caches[argsLength];
13340 if (cache) {
13341 releaseObject(cache);
13342 }
13343 }
13344 releaseArray(caches);
13345 releaseArray(seen);
13346 return result;
13347 }
13348
13349 /**
13350 * Gets the last element or last `n` elements of an array. If a callback is
13351 * provided elements at the end of the array are returned as long as the
13352 * callback returns truey. The callback is bound to `thisArg` and invoked
13353 * with three arguments; (value, index, array).
13354 *
13355 * If a property name is provided for `callback` the created "_.pluck" style
13356 * callback will return the property value of the given element.
13357 *
13358 * If an object is provided for `callback` the created "_.where" style callback
13359 * will return `true` for elements that have the properties of the given object,
13360 * else `false`.
13361 *
13362 * @static
13363 * @memberOf _
13364 * @category Arrays
13365 * @param {Array} array The array to query.
13366 * @param {Function|Object|number|string} [callback] The function called
13367 * per element or the number of elements to return. If a property name or
13368 * object is provided it will be used to create a "_.pluck" or "_.where"
13369 * style callback, respectively.
13370 * @param {*} [thisArg] The `this` binding of `callback`.
13371 * @returns {*} Returns the last element(s) of `array`.
13372 * @example
13373 *
13374 * _.last([1, 2, 3]);
13375 * // => 3
13376 *
13377 * _.last([1, 2, 3], 2);
13378 * // => [2, 3]
13379 *
13380 * _.last([1, 2, 3], function(num) {
13381 * return num > 1;
13382 * });
13383 * // => [2, 3]
13384 *
13385 * var characters = [
13386 * { 'name': 'barney', 'blocked': false, 'employer': 'slate' },
13387 * { 'name': 'fred', 'blocked': true, 'employer': 'slate' },
13388 * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
13389 * ];
13390 *
13391 * // using "_.pluck" callback shorthand
13392 * _.pluck(_.last(characters, 'blocked'), 'name');
13393 * // => ['fred', 'pebbles']
13394 *
13395 * // using "_.where" callback shorthand
13396 * _.last(characters, { 'employer': 'na' });
13397 * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
13398 */
13399 function last(array, callback, thisArg) {
13400 var n = 0,
13401 length = array ? array.length : 0;
13402
13403 if (typeof callback != 'number' && callback != null) {
13404 var index = length;
13405 callback = lodash.createCallback(callback, thisArg, 3);
13406 while (index-- && callback(array[index], index, array)) {
13407 n++;
13408 }
13409 } else {
13410 n = callback;
13411 if (n == null || thisArg) {
13412 return array ? array[length - 1] : undefined;
13413 }
13414 }
13415 return slice(array, nativeMax(0, length - n));
13416 }
13417
13418 /**
13419 * Gets the index at which the last occurrence of `value` is found using strict
13420 * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
13421 * as the offset from the end of the collection.
13422 *
13423 * If a property name is provided for `callback` the created "_.pluck" style
13424 * callback will return the property value of the given element.
13425 *
13426 * If an object is provided for `callback` the created "_.where" style callback
13427 * will return `true` for elements that have the properties of the given object,
13428 * else `false`.
13429 *
13430 * @static
13431 * @memberOf _
13432 * @category Arrays
13433 * @param {Array} array The array to search.
13434 * @param {*} value The value to search for.
13435 * @param {number} [fromIndex=array.length-1] The index to search from.
13436 * @returns {number} Returns the index of the matched value or `-1`.
13437 * @example
13438 *
13439 * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
13440 * // => 4
13441 *
13442 * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
13443 * // => 1
13444 */
13445 function lastIndexOf(array, value, fromIndex) {
13446 var index = array ? array.length : 0;
13447 if (typeof fromIndex == 'number') {
13448 index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
13449 }
13450 while (index--) {
13451 if (array[index] === value) {
13452 return index;
13453 }
13454 }
13455 return -1;
13456 }
13457
13458 /**
13459 * Removes all provided values from the given array using strict equality for
13460 * comparisons, i.e. `===`.
13461 *
13462 * @static
13463 * @memberOf _
13464 * @category Arrays
13465 * @param {Array} array The array to modify.
13466 * @param {...*} [value] The values to remove.
13467 * @returns {Array} Returns `array`.
13468 * @example
13469 *
13470 * var array = [1, 2, 3, 1, 2, 3];
13471 * _.pull(array, 2, 3);
13472 * console.log(array);
13473 * // => [1, 1]
13474 */
13475 function pull(array) {
13476 var args = arguments,
13477 argsIndex = 0,
13478 argsLength = args.length,
13479 length = array ? array.length : 0;
13480
13481 while (++argsIndex < argsLength) {
13482 var index = -1,
13483 value = args[argsIndex];
13484 while (++index < length) {
13485 if (array[index] === value) {
13486 splice.call(array, index--, 1);
13487 length--;
13488 }
13489 }
13490 }
13491 return array;
13492 }
13493
13494 /**
13495 * Creates an array of numbers (positive and/or negative) progressing from
13496 * `start` up to but not including `end`. If `start` is less than `stop` a
13497 * zero-length range is created unless a negative `step` is specified.
13498 *
13499 * @static
13500 * @memberOf _
13501 * @category Arrays
13502 * @param {number} [start=0] The start of the range.
13503 * @param {number} end The end of the range.
13504 * @param {number} [step=1] The value to increment or decrement by.
13505 * @returns {Array} Returns a new range array.
13506 * @example
13507 *
13508 * _.range(4);
13509 * // => [0, 1, 2, 3]
13510 *
13511 * _.range(1, 5);
13512 * // => [1, 2, 3, 4]
13513 *
13514 * _.range(0, 20, 5);
13515 * // => [0, 5, 10, 15]
13516 *
13517 * _.range(0, -4, -1);
13518 * // => [0, -1, -2, -3]
13519 *
13520 * _.range(1, 4, 0);
13521 * // => [1, 1, 1]
13522 *
13523 * _.range(0);
13524 * // => []
13525 */
13526 function range(start, end, step) {
13527 start = +start || 0;
13528 step = typeof step == 'number' ? step : (+step || 1);
13529
13530 if (end == null) {
13531 end = start;
13532 start = 0;
13533 }
13534 // use `Array(length)` so engines like Chakra and V8 avoid slower modes
13535 // http://youtu.be/XAqIpGU8ZZk#t=17m25s
13536 var index = -1,
13537 length = nativeMax(0, ceil((end - start) / (step || 1))),
13538 result = Array(length);
13539
13540 while (++index < length) {
13541 result[index] = start;
13542 start += step;
13543 }
13544 return result;
13545 }
13546
13547 /**
13548 * Removes all elements from an array that the callback returns truey for
13549 * and returns an array of removed elements. The callback is bound to `thisArg`
13550 * and invoked with three arguments; (value, index, array).
13551 *
13552 * If a property name is provided for `callback` the created "_.pluck" style
13553 * callback will return the property value of the given element.
13554 *
13555 * If an object is provided for `callback` the created "_.where" style callback
13556 * will return `true` for elements that have the properties of the given object,
13557 * else `false`.
13558 *
13559 * @static
13560 * @memberOf _
13561 * @category Arrays
13562 * @param {Array} array The array to modify.
13563 * @param {Function|Object|string} [callback=identity] The function called
13564 * per iteration. If a property name or object is provided it will be used
13565 * to create a "_.pluck" or "_.where" style callback, respectively.
13566 * @param {*} [thisArg] The `this` binding of `callback`.
13567 * @returns {Array} Returns a new array of removed elements.
13568 * @example
13569 *
13570 * var array = [1, 2, 3, 4, 5, 6];
13571 * var evens = _.remove(array, function(num) { return num % 2 == 0; });
13572 *
13573 * console.log(array);
13574 * // => [1, 3, 5]
13575 *
13576 * console.log(evens);
13577 * // => [2, 4, 6]
13578 */
13579 function remove(array, callback, thisArg) {
13580 var index = -1,
13581 length = array ? array.length : 0,
13582 result = [];
13583
13584 callback = lodash.createCallback(callback, thisArg, 3);
13585 while (++index < length) {
13586 var value = array[index];
13587 if (callback(value, index, array)) {
13588 result.push(value);
13589 splice.call(array, index--, 1);
13590 length--;
13591 }
13592 }
13593 return result;
13594 }
13595
13596 /**
13597 * The opposite of `_.initial` this method gets all but the first element or
13598 * first `n` elements of an array. If a callback function is provided elements
13599 * at the beginning of the array are excluded from the result as long as the
13600 * callback returns truey. The callback is bound to `thisArg` and invoked
13601 * with three arguments; (value, index, array).
13602 *
13603 * If a property name is provided for `callback` the created "_.pluck" style
13604 * callback will return the property value of the given element.
13605 *
13606 * If an object is provided for `callback` the created "_.where" style callback
13607 * will return `true` for elements that have the properties of the given object,
13608 * else `false`.
13609 *
13610 * @static
13611 * @memberOf _
13612 * @alias drop, tail
13613 * @category Arrays
13614 * @param {Array} array The array to query.
13615 * @param {Function|Object|number|string} [callback=1] The function called
13616 * per element or the number of elements to exclude. If a property name or
13617 * object is provided it will be used to create a "_.pluck" or "_.where"
13618 * style callback, respectively.
13619 * @param {*} [thisArg] The `this` binding of `callback`.
13620 * @returns {Array} Returns a slice of `array`.
13621 * @example
13622 *
13623 * _.rest([1, 2, 3]);
13624 * // => [2, 3]
13625 *
13626 * _.rest([1, 2, 3], 2);
13627 * // => [3]
13628 *
13629 * _.rest([1, 2, 3], function(num) {
13630 * return num < 3;
13631 * });
13632 * // => [3]
13633 *
13634 * var characters = [
13635 * { 'name': 'barney', 'blocked': true, 'employer': 'slate' },
13636 * { 'name': 'fred', 'blocked': false, 'employer': 'slate' },
13637 * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' }
13638 * ];
13639 *
13640 * // using "_.pluck" callback shorthand
13641 * _.pluck(_.rest(characters, 'blocked'), 'name');
13642 * // => ['fred', 'pebbles']
13643 *
13644 * // using "_.where" callback shorthand
13645 * _.rest(characters, { 'employer': 'slate' });
13646 * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }]
13647 */
13648 function rest(array, callback, thisArg) {
13649 if (typeof callback != 'number' && callback != null) {
13650 var n = 0,
13651 index = -1,
13652 length = array ? array.length : 0;
13653
13654 callback = lodash.createCallback(callback, thisArg, 3);
13655 while (++index < length && callback(array[index], index, array)) {
13656 n++;
13657 }
13658 } else {
13659 n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
13660 }
13661 return slice(array, n);
13662 }
13663
13664 /**
13665 * Uses a binary search to determine the smallest index at which a value
13666 * should be inserted into a given sorted array in order to maintain the sort
13667 * order of the array. If a callback is provided it will be executed for
13668 * `value` and each element of `array` to compute their sort ranking. The
13669 * callback is bound to `thisArg` and invoked with one argument; (value).
13670 *
13671 * If a property name is provided for `callback` the created "_.pluck" style
13672 * callback will return the property value of the given element.
13673 *
13674 * If an object is provided for `callback` the created "_.where" style callback
13675 * will return `true` for elements that have the properties of the given object,
13676 * else `false`.
13677 *
13678 * @static
13679 * @memberOf _
13680 * @category Arrays
13681 * @param {Array} array The array to inspect.
13682 * @param {*} value The value to evaluate.
13683 * @param {Function|Object|string} [callback=identity] The function called
13684 * per iteration. If a property name or object is provided it will be used
13685 * to create a "_.pluck" or "_.where" style callback, respectively.
13686 * @param {*} [thisArg] The `this` binding of `callback`.
13687 * @returns {number} Returns the index at which `value` should be inserted
13688 * into `array`.
13689 * @example
13690 *
13691 * _.sortedIndex([20, 30, 50], 40);
13692 * // => 2
13693 *
13694 * // using "_.pluck" callback shorthand
13695 * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
13696 * // => 2
13697 *
13698 * var dict = {
13699 * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
13700 * };
13701 *
13702 * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
13703 * return dict.wordToNumber[word];
13704 * });
13705 * // => 2
13706 *
13707 * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
13708 * return this.wordToNumber[word];
13709 * }, dict);
13710 * // => 2
13711 */
13712 function sortedIndex(array, value, callback, thisArg) {
13713 var low = 0,
13714 high = array ? array.length : low;
13715
13716 // explicitly reference `identity` for better inlining in Firefox
13717 callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
13718 value = callback(value);
13719
13720 while (low < high) {
13721 var mid = (low + high) >>> 1;
13722 (callback(array[mid]) < value)
13723 ? low = mid + 1
13724 : high = mid;
13725 }
13726 return low;
13727 }
13728
13729 /**
13730 * Creates an array of unique values, in order, of the provided arrays using
13731 * strict equality for comparisons, i.e. `===`.
13732 *
13733 * @static
13734 * @memberOf _
13735 * @category Arrays
13736 * @param {...Array} [array] The arrays to inspect.
13737 * @returns {Array} Returns an array of combined values.
13738 * @example
13739 *
13740 * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]);
13741 * // => [1, 2, 3, 5, 4]
13742 */
13743 function union() {
13744 return baseUniq(baseFlatten(arguments, true, true));
13745 }
13746
13747 /**
13748 * Creates a duplicate-value-free version of an array using strict equality
13749 * for comparisons, i.e. `===`. If the array is sorted, providing
13750 * `true` for `isSorted` will use a faster algorithm. If a callback is provided
13751 * each element of `array` is passed through the callback before uniqueness
13752 * is computed. The callback is bound to `thisArg` and invoked with three
13753 * arguments; (value, index, array).
13754 *
13755 * If a property name is provided for `callback` the created "_.pluck" style
13756 * callback will return the property value of the given element.
13757 *
13758 * If an object is provided for `callback` the created "_.where" style callback
13759 * will return `true` for elements that have the properties of the given object,
13760 * else `false`.
13761 *
13762 * @static
13763 * @memberOf _
13764 * @alias unique
13765 * @category Arrays
13766 * @param {Array} array The array to process.
13767 * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
13768 * @param {Function|Object|string} [callback=identity] The function called
13769 * per iteration. If a property name or object is provided it will be used
13770 * to create a "_.pluck" or "_.where" style callback, respectively.
13771 * @param {*} [thisArg] The `this` binding of `callback`.
13772 * @returns {Array} Returns a duplicate-value-free array.
13773 * @example
13774 *
13775 * _.uniq([1, 2, 1, 3, 1]);
13776 * // => [1, 2, 3]
13777 *
13778 * _.uniq([1, 1, 2, 2, 3], true);
13779 * // => [1, 2, 3]
13780 *
13781 * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); });
13782 * // => ['A', 'b', 'C']
13783 *
13784 * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math);
13785 * // => [1, 2.5, 3]
13786 *
13787 * // using "_.pluck" callback shorthand
13788 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
13789 * // => [{ 'x': 1 }, { 'x': 2 }]
13790 */
13791 function uniq(array, isSorted, callback, thisArg) {
13792 // juggle arguments
13793 if (typeof isSorted != 'boolean' && isSorted != null) {
13794 thisArg = callback;
13795 callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted;
13796 isSorted = false;
13797 }
13798 if (callback != null) {
13799 callback = lodash.createCallback(callback, thisArg, 3);
13800 }
13801 return baseUniq(array, isSorted, callback);
13802 }
13803
13804 /**
13805 * Creates an array excluding all provided values using strict equality for
13806 * comparisons, i.e. `===`.
13807 *
13808 * @static
13809 * @memberOf _
13810 * @category Arrays
13811 * @param {Array} array The array to filter.
13812 * @param {...*} [value] The values to exclude.
13813 * @returns {Array} Returns a new array of filtered values.
13814 * @example
13815 *
13816 * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
13817 * // => [2, 3, 4]
13818 */
13819 function without(array) {
13820 return baseDifference(array, slice(arguments, 1));
13821 }
13822
13823 /**
13824 * Creates an array that is the symmetric difference of the provided arrays.
13825 * See http://en.wikipedia.org/wiki/Symmetric_difference.
13826 *
13827 * @static
13828 * @memberOf _
13829 * @category Arrays
13830 * @param {...Array} [array] The arrays to inspect.
13831 * @returns {Array} Returns an array of values.
13832 * @example
13833 *
13834 * _.xor([1, 2, 3], [5, 2, 1, 4]);
13835 * // => [3, 5, 4]
13836 *
13837 * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]);
13838 * // => [1, 4, 5]
13839 */
13840 function xor() {
13841 var index = -1,
13842 length = arguments.length;
13843
13844 while (++index < length) {
13845 var array = arguments[index];
13846 if (isArray(array) || isArguments(array)) {
13847 var result = result
13848 ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result)))
13849 : array;
13850 }
13851 }
13852 return result || [];
13853 }
13854
13855 /**
13856 * Creates an array of grouped elements, the first of which contains the first
13857 * elements of the given arrays, the second of which contains the second
13858 * elements of the given arrays, and so on.
13859 *
13860 * @static
13861 * @memberOf _
13862 * @alias unzip
13863 * @category Arrays
13864 * @param {...Array} [array] Arrays to process.
13865 * @returns {Array} Returns a new array of grouped elements.
13866 * @example
13867 *
13868 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
13869 * // => [['fred', 30, true], ['barney', 40, false]]
13870 */
13871 function zip() {
13872 var array = arguments.length > 1 ? arguments : arguments[0],
13873 index = -1,
13874 length = array ? max(pluck(array, 'length')) : 0,
13875 result = Array(length < 0 ? 0 : length);
13876
13877 while (++index < length) {
13878 result[index] = pluck(array, index);
13879 }
13880 return result;
13881 }
13882
13883 /**
13884 * Creates an object composed from arrays of `keys` and `values`. Provide
13885 * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`
13886 * or two arrays, one of `keys` and one of corresponding `values`.
13887 *
13888 * @static
13889 * @memberOf _
13890 * @alias object
13891 * @category Arrays
13892 * @param {Array} keys The array of keys.
13893 * @param {Array} [values=[]] The array of values.
13894 * @returns {Object} Returns an object composed of the given keys and
13895 * corresponding values.
13896 * @example
13897 *
13898 * _.zipObject(['fred', 'barney'], [30, 40]);
13899 * // => { 'fred': 30, 'barney': 40 }
13900 */
13901 function zipObject(keys, values) {
13902 var index = -1,
13903 length = keys ? keys.length : 0,
13904 result = {};
13905
13906 if (!values && length && !isArray(keys[0])) {
13907 values = [];
13908 }
13909 while (++index < length) {
13910 var key = keys[index];
13911 if (values) {
13912 result[key] = values[index];
13913 } else if (key) {
13914 result[key[0]] = key[1];
13915 }
13916 }
13917 return result;
13918 }
13919
13920 /*--------------------------------------------------------------------------*/
13921
13922 /**
13923 * Creates a function that executes `func`, with the `this` binding and
13924 * arguments of the created function, only after being called `n` times.
13925 *
13926 * @static
13927 * @memberOf _
13928 * @category Functions
13929 * @param {number} n The number of times the function must be called before
13930 * `func` is executed.
13931 * @param {Function} func The function to restrict.
13932 * @returns {Function} Returns the new restricted function.
13933 * @example
13934 *
13935 * var saves = ['profile', 'settings'];
13936 *
13937 * var done = _.after(saves.length, function() {
13938 * console.log('Done saving!');
13939 * });
13940 *
13941 * _.forEach(saves, function(type) {
13942 * asyncSave({ 'type': type, 'complete': done });
13943 * });
13944 * // => logs 'Done saving!', after all saves have completed
13945 */
13946 function after(n, func) {
13947 if (!isFunction(func)) {
13948 throw new TypeError;
13949 }
13950 return function() {
13951 if (--n < 1) {
13952 return func.apply(this, arguments);
13953 }
13954 };
13955 }
13956
13957 /**
13958 * Creates a function that, when called, invokes `func` with the `this`
13959 * binding of `thisArg` and prepends any additional `bind` arguments to those
13960 * provided to the bound function.
13961 *
13962 * @static
13963 * @memberOf _
13964 * @category Functions
13965 * @param {Function} func The function to bind.
13966 * @param {*} [thisArg] The `this` binding of `func`.
13967 * @param {...*} [arg] Arguments to be partially applied.
13968 * @returns {Function} Returns the new bound function.
13969 * @example
13970 *
13971 * var func = function(greeting) {
13972 * return greeting + ' ' + this.name;
13973 * };
13974 *
13975 * func = _.bind(func, { 'name': 'fred' }, 'hi');
13976 * func();
13977 * // => 'hi fred'
13978 */
13979 function bind(func, thisArg) {
13980 return arguments.length > 2
13981 ? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
13982 : createWrapper(func, 1, null, null, thisArg);
13983 }
13984
13985 /**
13986 * Binds methods of an object to the object itself, overwriting the existing
13987 * method. Method names may be specified as individual arguments or as arrays
13988 * of method names. If no method names are provided all the function properties
13989 * of `object` will be bound.
13990 *
13991 * @static
13992 * @memberOf _
13993 * @category Functions
13994 * @param {Object} object The object to bind and assign the bound methods to.
13995 * @param {...string} [methodName] The object method names to
13996 * bind, specified as individual method names or arrays of method names.
13997 * @returns {Object} Returns `object`.
13998 * @example
13999 *
14000 * var view = {
14001 * 'label': 'docs',
14002 * 'onClick': function() { console.log('clicked ' + this.label); }
14003 * };
14004 *
14005 * _.bindAll(view);
14006 * jQuery('#docs').on('click', view.onClick);
14007 * // => logs 'clicked docs', when the button is clicked
14008 */
14009 function bindAll(object) {
14010 var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object),
14011 index = -1,
14012 length = funcs.length;
14013
14014 while (++index < length) {
14015 var key = funcs[index];
14016 object[key] = createWrapper(object[key], 1, null, null, object);
14017 }
14018 return object;
14019 }
14020
14021 /**
14022 * Creates a function that, when called, invokes the method at `object[key]`
14023 * and prepends any additional `bindKey` arguments to those provided to the bound
14024 * function. This method differs from `_.bind` by allowing bound functions to
14025 * reference methods that will be redefined or don't yet exist.
14026 * See http://michaux.ca/articles/lazy-function-definition-pattern.
14027 *
14028 * @static
14029 * @memberOf _
14030 * @category Functions
14031 * @param {Object} object The object the method belongs to.
14032 * @param {string} key The key of the method.
14033 * @param {...*} [arg] Arguments to be partially applied.
14034 * @returns {Function} Returns the new bound function.
14035 * @example
14036 *
14037 * var object = {
14038 * 'name': 'fred',
14039 * 'greet': function(greeting) {
14040 * return greeting + ' ' + this.name;
14041 * }
14042 * };
14043 *
14044 * var func = _.bindKey(object, 'greet', 'hi');
14045 * func();
14046 * // => 'hi fred'
14047 *
14048 * object.greet = function(greeting) {
14049 * return greeting + 'ya ' + this.name + '!';
14050 * };
14051 *
14052 * func();
14053 * // => 'hiya fred!'
14054 */
14055 function bindKey(object, key) {
14056 return arguments.length > 2
14057 ? createWrapper(key, 19, slice(arguments, 2), null, object)
14058 : createWrapper(key, 3, null, null, object);
14059 }
14060
14061 /**
14062 * Creates a function that is the composition of the provided functions,
14063 * where each function consumes the return value of the function that follows.
14064 * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
14065 * Each function is executed with the `this` binding of the composed function.
14066 *
14067 * @static
14068 * @memberOf _
14069 * @category Functions
14070 * @param {...Function} [func] Functions to compose.
14071 * @returns {Function} Returns the new composed function.
14072 * @example
14073 *
14074 * var realNameMap = {
14075 * 'pebbles': 'penelope'
14076 * };
14077 *
14078 * var format = function(name) {
14079 * name = realNameMap[name.toLowerCase()] || name;
14080 * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
14081 * };
14082 *
14083 * var greet = function(formatted) {
14084 * return 'Hiya ' + formatted + '!';
14085 * };
14086 *
14087 * var welcome = _.compose(greet, format);
14088 * welcome('pebbles');
14089 * // => 'Hiya Penelope!'
14090 */
14091 function compose() {
14092 var funcs = arguments,
14093 length = funcs.length;
14094
14095 while (length--) {
14096 if (!isFunction(funcs[length])) {
14097 throw new TypeError;
14098 }
14099 }
14100 return function() {
14101 var args = arguments,
14102 length = funcs.length;
14103
14104 while (length--) {
14105 args = [funcs[length].apply(this, args)];
14106 }
14107 return args[0];
14108 };
14109 }
14110
14111 /**
14112 * Creates a function which accepts one or more arguments of `func` that when
14113 * invoked either executes `func` returning its result, if all `func` arguments
14114 * have been provided, or returns a function that accepts one or more of the
14115 * remaining `func` arguments, and so on. The arity of `func` can be specified
14116 * if `func.length` is not sufficient.
14117 *
14118 * @static
14119 * @memberOf _
14120 * @category Functions
14121 * @param {Function} func The function to curry.
14122 * @param {number} [arity=func.length] The arity of `func`.
14123 * @returns {Function} Returns the new curried function.
14124 * @example
14125 *
14126 * var curried = _.curry(function(a, b, c) {
14127 * console.log(a + b + c);
14128 * });
14129 *
14130 * curried(1)(2)(3);
14131 * // => 6
14132 *
14133 * curried(1, 2)(3);
14134 * // => 6
14135 *
14136 * curried(1, 2, 3);
14137 * // => 6
14138 */
14139 function curry(func, arity) {
14140 arity = typeof arity == 'number' ? arity : (+arity || func.length);
14141 return createWrapper(func, 4, null, null, null, arity);
14142 }
14143
14144 /**
14145 * Creates a function that will delay the execution of `func` until after
14146 * `wait` milliseconds have elapsed since the last time it was invoked.
14147 * Provide an options object to indicate that `func` should be invoked on
14148 * the leading and/or trailing edge of the `wait` timeout. Subsequent calls
14149 * to the debounced function will return the result of the last `func` call.
14150 *
14151 * Note: If `leading` and `trailing` options are `true` `func` will be called
14152 * on the trailing edge of the timeout only if the the debounced function is
14153 * invoked more than once during the `wait` timeout.
14154 *
14155 * @static
14156 * @memberOf _
14157 * @category Functions
14158 * @param {Function} func The function to debounce.
14159 * @param {number} wait The number of milliseconds to delay.
14160 * @param {Object} [options] The options object.
14161 * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout.
14162 * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called.
14163 * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
14164 * @returns {Function} Returns the new debounced function.
14165 * @example
14166 *
14167 * // avoid costly calculations while the window size is in flux
14168 * var lazyLayout = _.debounce(calculateLayout, 150);
14169 * jQuery(window).on('resize', lazyLayout);
14170 *
14171 * // execute `sendMail` when the click event is fired, debouncing subsequent calls
14172 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
14173 * 'leading': true,
14174 * 'trailing': false
14175 * });
14176 *
14177 * // ensure `batchLog` is executed once after 1 second of debounced calls
14178 * var source = new EventSource('/stream');
14179 * source.addEventListener('message', _.debounce(batchLog, 250, {
14180 * 'maxWait': 1000
14181 * }, false);
14182 */
14183 function debounce(func, wait, options) {
14184 var args,
14185 maxTimeoutId,
14186 result,
14187 stamp,
14188 thisArg,
14189 timeoutId,
14190 trailingCall,
14191 lastCalled = 0,
14192 maxWait = false,
14193 trailing = true;
14194
14195 if (!isFunction(func)) {
14196 throw new TypeError;
14197 }
14198 wait = nativeMax(0, wait) || 0;
14199 if (options === true) {
14200 var leading = true;
14201 trailing = false;
14202 } else if (isObject(options)) {
14203 leading = options.leading;
14204 maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);
14205 trailing = 'trailing' in options ? options.trailing : trailing;
14206 }
14207 var delayed = function() {
14208 var remaining = wait - (now() - stamp);
14209 if (remaining <= 0) {
14210 if (maxTimeoutId) {
14211 clearTimeout(maxTimeoutId);
14212 }
14213 var isCalled = trailingCall;
14214 maxTimeoutId = timeoutId = trailingCall = undefined;
14215 if (isCalled) {
14216 lastCalled = now();
14217 result = func.apply(thisArg, args);
14218 if (!timeoutId && !maxTimeoutId) {
14219 args = thisArg = null;
14220 }
14221 }
14222 } else {
14223 timeoutId = setTimeout(delayed, remaining);
14224 }
14225 };
14226
14227 var maxDelayed = function() {
14228 if (timeoutId) {
14229 clearTimeout(timeoutId);
14230 }
14231 maxTimeoutId = timeoutId = trailingCall = undefined;
14232 if (trailing || (maxWait !== wait)) {
14233 lastCalled = now();
14234 result = func.apply(thisArg, args);
14235 if (!timeoutId && !maxTimeoutId) {
14236 args = thisArg = null;
14237 }
14238 }
14239 };
14240
14241 return function() {
14242 args = arguments;
14243 stamp = now();
14244 thisArg = this;
14245 trailingCall = trailing && (timeoutId || !leading);
14246
14247 if (maxWait === false) {
14248 var leadingCall = leading && !timeoutId;
14249 } else {
14250 if (!maxTimeoutId && !leading) {
14251 lastCalled = stamp;
14252 }
14253 var remaining = maxWait - (stamp - lastCalled),
14254 isCalled = remaining <= 0;
14255
14256 if (isCalled) {
14257 if (maxTimeoutId) {
14258 maxTimeoutId = clearTimeout(maxTimeoutId);
14259 }
14260 lastCalled = stamp;
14261 result = func.apply(thisArg, args);
14262 }
14263 else if (!maxTimeoutId) {
14264 maxTimeoutId = setTimeout(maxDelayed, remaining);
14265 }
14266 }
14267 if (isCalled && timeoutId) {
14268 timeoutId = clearTimeout(timeoutId);
14269 }
14270 else if (!timeoutId && wait !== maxWait) {
14271 timeoutId = setTimeout(delayed, wait);
14272 }
14273 if (leadingCall) {
14274 isCalled = true;
14275 result = func.apply(thisArg, args);
14276 }
14277 if (isCalled && !timeoutId && !maxTimeoutId) {
14278 args = thisArg = null;
14279 }
14280 return result;
14281 };
14282 }
14283
14284 /**
14285 * Defers executing the `func` function until the current call stack has cleared.
14286 * Additional arguments will be provided to `func` when it is invoked.
14287 *
14288 * @static
14289 * @memberOf _
14290 * @category Functions
14291 * @param {Function} func The function to defer.
14292 * @param {...*} [arg] Arguments to invoke the function with.
14293 * @returns {number} Returns the timer id.
14294 * @example
14295 *
14296 * _.defer(function(text) { console.log(text); }, 'deferred');
14297 * // logs 'deferred' after one or more milliseconds
14298 */
14299 function defer(func) {
14300 if (!isFunction(func)) {
14301 throw new TypeError;
14302 }
14303 var args = slice(arguments, 1);
14304 return setTimeout(function() { func.apply(undefined, args); }, 1);
14305 }
14306
14307 /**
14308 * Executes the `func` function after `wait` milliseconds. Additional arguments
14309 * will be provided to `func` when it is invoked.
14310 *
14311 * @static
14312 * @memberOf _
14313 * @category Functions
14314 * @param {Function} func The function to delay.
14315 * @param {number} wait The number of milliseconds to delay execution.
14316 * @param {...*} [arg] Arguments to invoke the function with.
14317 * @returns {number} Returns the timer id.
14318 * @example
14319 *
14320 * _.delay(function(text) { console.log(text); }, 1000, 'later');
14321 * // => logs 'later' after one second
14322 */
14323 function delay(func, wait) {
14324 if (!isFunction(func)) {
14325 throw new TypeError;
14326 }
14327 var args = slice(arguments, 2);
14328 return setTimeout(function() { func.apply(undefined, args); }, wait);
14329 }
14330
14331 /**
14332 * Creates a function that memoizes the result of `func`. If `resolver` is
14333 * provided it will be used to determine the cache key for storing the result
14334 * based on the arguments provided to the memoized function. By default, the
14335 * first argument provided to the memoized function is used as the cache key.
14336 * The `func` is executed with the `this` binding of the memoized function.
14337 * The result cache is exposed as the `cache` property on the memoized function.
14338 *
14339 * @static
14340 * @memberOf _
14341 * @category Functions
14342 * @param {Function} func The function to have its output memoized.
14343 * @param {Function} [resolver] A function used to resolve the cache key.
14344 * @returns {Function} Returns the new memoizing function.
14345 * @example
14346 *
14347 * var fibonacci = _.memoize(function(n) {
14348 * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
14349 * });
14350 *
14351 * fibonacci(9)
14352 * // => 34
14353 *
14354 * var data = {
14355 * 'fred': { 'name': 'fred', 'age': 40 },
14356 * 'pebbles': { 'name': 'pebbles', 'age': 1 }
14357 * };
14358 *
14359 * // modifying the result cache
14360 * var get = _.memoize(function(name) { return data[name]; }, _.identity);
14361 * get('pebbles');
14362 * // => { 'name': 'pebbles', 'age': 1 }
14363 *
14364 * get.cache.pebbles.name = 'penelope';
14365 * get('pebbles');
14366 * // => { 'name': 'penelope', 'age': 1 }
14367 */
14368 function memoize(func, resolver) {
14369 if (!isFunction(func)) {
14370 throw new TypeError;
14371 }
14372 var memoized = function() {
14373 var cache = memoized.cache,
14374 key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0];
14375
14376 return hasOwnProperty.call(cache, key)
14377 ? cache[key]
14378 : (cache[key] = func.apply(this, arguments));
14379 }
14380 memoized.cache = {};
14381 return memoized;
14382 }
14383
14384 /**
14385 * Creates a function that is restricted to execute `func` once. Repeat calls to
14386 * the function will return the value of the first call. The `func` is executed
14387 * with the `this` binding of the created function.
14388 *
14389 * @static
14390 * @memberOf _
14391 * @category Functions
14392 * @param {Function} func The function to restrict.
14393 * @returns {Function} Returns the new restricted function.
14394 * @example
14395 *
14396 * var initialize = _.once(createApplication);
14397 * initialize();
14398 * initialize();
14399 * // `initialize` executes `createApplication` once
14400 */
14401 function once(func) {
14402 var ran,
14403 result;
14404
14405 if (!isFunction(func)) {
14406 throw new TypeError;
14407 }
14408 return function() {
14409 if (ran) {
14410 return result;
14411 }
14412 ran = true;
14413 result = func.apply(this, arguments);
14414
14415 // clear the `func` variable so the function may be garbage collected
14416 func = null;
14417 return result;
14418 };
14419 }
14420
14421 /**
14422 * Creates a function that, when called, invokes `func` with any additional
14423 * `partial` arguments prepended to those provided to the new function. This
14424 * method is similar to `_.bind` except it does **not** alter the `this` binding.
14425 *
14426 * @static
14427 * @memberOf _
14428 * @category Functions
14429 * @param {Function} func The function to partially apply arguments to.
14430 * @param {...*} [arg] Arguments to be partially applied.
14431 * @returns {Function} Returns the new partially applied function.
14432 * @example
14433 *
14434 * var greet = function(greeting, name) { return greeting + ' ' + name; };
14435 * var hi = _.partial(greet, 'hi');
14436 * hi('fred');
14437 * // => 'hi fred'
14438 */
14439 function partial(func) {
14440 return createWrapper(func, 16, slice(arguments, 1));
14441 }
14442
14443 /**
14444 * This method is like `_.partial` except that `partial` arguments are
14445 * appended to those provided to the new function.
14446 *
14447 * @static
14448 * @memberOf _
14449 * @category Functions
14450 * @param {Function} func The function to partially apply arguments to.
14451 * @param {...*} [arg] Arguments to be partially applied.
14452 * @returns {Function} Returns the new partially applied function.
14453 * @example
14454 *
14455 * var defaultsDeep = _.partialRight(_.merge, _.defaults);
14456 *
14457 * var options = {
14458 * 'variable': 'data',
14459 * 'imports': { 'jq': $ }
14460 * };
14461 *
14462 * defaultsDeep(options, _.templateSettings);
14463 *
14464 * options.variable
14465 * // => 'data'
14466 *
14467 * options.imports
14468 * // => { '_': _, 'jq': $ }
14469 */
14470 function partialRight(func) {
14471 return createWrapper(func, 32, null, slice(arguments, 1));
14472 }
14473
14474 /**
14475 * Creates a function that, when executed, will only call the `func` function
14476 * at most once per every `wait` milliseconds. Provide an options object to
14477 * indicate that `func` should be invoked on the leading and/or trailing edge
14478 * of the `wait` timeout. Subsequent calls to the throttled function will
14479 * return the result of the last `func` call.
14480 *
14481 * Note: If `leading` and `trailing` options are `true` `func` will be called
14482 * on the trailing edge of the timeout only if the the throttled function is
14483 * invoked more than once during the `wait` timeout.
14484 *
14485 * @static
14486 * @memberOf _
14487 * @category Functions
14488 * @param {Function} func The function to throttle.
14489 * @param {number} wait The number of milliseconds to throttle executions to.
14490 * @param {Object} [options] The options object.
14491 * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout.
14492 * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout.
14493 * @returns {Function} Returns the new throttled function.
14494 * @example
14495 *
14496 * // avoid excessively updating the position while scrolling
14497 * var throttled = _.throttle(updatePosition, 100);
14498 * jQuery(window).on('scroll', throttled);
14499 *
14500 * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes
14501 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
14502 * 'trailing': false
14503 * }));
14504 */
14505 function throttle(func, wait, options) {
14506 var leading = true,
14507 trailing = true;
14508
14509 if (!isFunction(func)) {
14510 throw new TypeError;
14511 }
14512 if (options === false) {
14513 leading = false;
14514 } else if (isObject(options)) {
14515 leading = 'leading' in options ? options.leading : leading;
14516 trailing = 'trailing' in options ? options.trailing : trailing;
14517 }
14518 debounceOptions.leading = leading;
14519 debounceOptions.maxWait = wait;
14520 debounceOptions.trailing = trailing;
14521
14522 return debounce(func, wait, debounceOptions);
14523 }
14524
14525 /**
14526 * Creates a function that provides `value` to the wrapper function as its
14527 * first argument. Additional arguments provided to the function are appended
14528 * to those provided to the wrapper function. The wrapper is executed with
14529 * the `this` binding of the created function.
14530 *
14531 * @static
14532 * @memberOf _
14533 * @category Functions
14534 * @param {*} value The value to wrap.
14535 * @param {Function} wrapper The wrapper function.
14536 * @returns {Function} Returns the new function.
14537 * @example
14538 *
14539 * var p = _.wrap(_.escape, function(func, text) {
14540 * return '<p>' + func(text) + '</p>';
14541 * });
14542 *
14543 * p('Fred, Wilma, & Pebbles');
14544 * // => '<p>Fred, Wilma, &amp; Pebbles</p>'
14545 */
14546 function wrap(value, wrapper) {
14547 return createWrapper(wrapper, 16, [value]);
14548 }
14549
14550 /*--------------------------------------------------------------------------*/
14551
14552 /**
14553 * Creates a function that returns `value`.
14554 *
14555 * @static
14556 * @memberOf _
14557 * @category Utilities
14558 * @param {*} value The value to return from the new function.
14559 * @returns {Function} Returns the new function.
14560 * @example
14561 *
14562 * var object = { 'name': 'fred' };
14563 * var getter = _.constant(object);
14564 * getter() === object;
14565 * // => true
14566 */
14567 function constant(value) {
14568 return function() {
14569 return value;
14570 };
14571 }
14572
14573 /**
14574 * Produces a callback bound to an optional `thisArg`. If `func` is a property
14575 * name the created callback will return the property value for a given element.
14576 * If `func` is an object the created callback will return `true` for elements
14577 * that contain the equivalent object properties, otherwise it will return `false`.
14578 *
14579 * @static
14580 * @memberOf _
14581 * @category Utilities
14582 * @param {*} [func=identity] The value to convert to a callback.
14583 * @param {*} [thisArg] The `this` binding of the created callback.
14584 * @param {number} [argCount] The number of arguments the callback accepts.
14585 * @returns {Function} Returns a callback function.
14586 * @example
14587 *
14588 * var characters = [
14589 * { 'name': 'barney', 'age': 36 },
14590 * { 'name': 'fred', 'age': 40 }
14591 * ];
14592 *
14593 * // wrap to create custom callback shorthands
14594 * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
14595 * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
14596 * return !match ? func(callback, thisArg) : function(object) {
14597 * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
14598 * };
14599 * });
14600 *
14601 * _.filter(characters, 'age__gt38');
14602 * // => [{ 'name': 'fred', 'age': 40 }]
14603 */
14604 function createCallback(func, thisArg, argCount) {
14605 var type = typeof func;
14606 if (func == null || type == 'function') {
14607 return baseCreateCallback(func, thisArg, argCount);
14608 }
14609 // handle "_.pluck" style callback shorthands
14610 if (type != 'object') {
14611 return property(func);
14612 }
14613 var props = keys(func),
14614 key = props[0],
14615 a = func[key];
14616
14617 // handle "_.where" style callback shorthands
14618 if (props.length == 1 && a === a && !isObject(a)) {
14619 // fast path the common case of providing an object with a single
14620 // property containing a primitive value
14621 return function(object) {
14622 var b = object[key];
14623 return a === b && (a !== 0 || (1 / a == 1 / b));
14624 };
14625 }
14626 return function(object) {
14627 var length = props.length,
14628 result = false;
14629
14630 while (length--) {
14631 if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
14632 break;
14633 }
14634 }
14635 return result;
14636 };
14637 }
14638
14639 /**
14640 * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
14641 * corresponding HTML entities.
14642 *
14643 * @static
14644 * @memberOf _
14645 * @category Utilities
14646 * @param {string} string The string to escape.
14647 * @returns {string} Returns the escaped string.
14648 * @example
14649 *
14650 * _.escape('Fred, Wilma, & Pebbles');
14651 * // => 'Fred, Wilma, &amp; Pebbles'
14652 */
14653 function escape(string) {
14654 return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
14655 }
14656
14657 /**
14658 * This method returns the first argument provided to it.
14659 *
14660 * @static
14661 * @memberOf _
14662 * @category Utilities
14663 * @param {*} value Any value.
14664 * @returns {*} Returns `value`.
14665 * @example
14666 *
14667 * var object = { 'name': 'fred' };
14668 * _.identity(object) === object;
14669 * // => true
14670 */
14671 function identity(value) {
14672 return value;
14673 }
14674
14675 /**
14676 * Adds function properties of a source object to the destination object.
14677 * If `object` is a function methods will be added to its prototype as well.
14678 *
14679 * @static
14680 * @memberOf _
14681 * @category Utilities
14682 * @param {Function|Object} [object=lodash] object The destination object.
14683 * @param {Object} source The object of functions to add.
14684 * @param {Object} [options] The options object.
14685 * @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
14686 * @example
14687 *
14688 * function capitalize(string) {
14689 * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
14690 * }
14691 *
14692 * _.mixin({ 'capitalize': capitalize });
14693 * _.capitalize('fred');
14694 * // => 'Fred'
14695 *
14696 * _('fred').capitalize().value();
14697 * // => 'Fred'
14698 *
14699 * _.mixin({ 'capitalize': capitalize }, { 'chain': false });
14700 * _('fred').capitalize();
14701 * // => 'Fred'
14702 */
14703 function mixin(object, source, options) {
14704 var chain = true,
14705 methodNames = source && functions(source);
14706
14707 if (!source || (!options && !methodNames.length)) {
14708 if (options == null) {
14709 options = source;
14710 }
14711 ctor = lodashWrapper;
14712 source = object;
14713 object = lodash;
14714 methodNames = functions(source);
14715 }
14716 if (options === false) {
14717 chain = false;
14718 } else if (isObject(options) && 'chain' in options) {
14719 chain = options.chain;
14720 }
14721 var ctor = object,
14722 isFunc = isFunction(ctor);
14723
14724 forEach(methodNames, function(methodName) {
14725 var func = object[methodName] = source[methodName];
14726 if (isFunc) {
14727 ctor.prototype[methodName] = function() {
14728 var chainAll = this.__chain__,
14729 value = this.__wrapped__,
14730 args = [value];
14731
14732 push.apply(args, arguments);
14733 var result = func.apply(object, args);
14734 if (chain || chainAll) {
14735 if (value === result && isObject(result)) {
14736 return this;
14737 }
14738 result = new ctor(result);
14739 result.__chain__ = chainAll;
14740 }
14741 return result;
14742 };
14743 }
14744 });
14745 }
14746
14747 /**
14748 * Reverts the '_' variable to its previous value and returns a reference to
14749 * the `lodash` function.
14750 *
14751 * @static
14752 * @memberOf _
14753 * @category Utilities
14754 * @returns {Function} Returns the `lodash` function.
14755 * @example
14756 *
14757 * var lodash = _.noConflict();
14758 */
14759 function noConflict() {
14760 context._ = oldDash;
14761 return this;
14762 }
14763
14764 /**
14765 * A no-operation function.
14766 *
14767 * @static
14768 * @memberOf _
14769 * @category Utilities
14770 * @example
14771 *
14772 * var object = { 'name': 'fred' };
14773 * _.noop(object) === undefined;
14774 * // => true
14775 */
14776 function noop() {
14777 // no operation performed
14778 }
14779
14780 /**
14781 * Gets the number of milliseconds that have elapsed since the Unix epoch
14782 * (1 January 1970 00:00:00 UTC).
14783 *
14784 * @static
14785 * @memberOf _
14786 * @category Utilities
14787 * @example
14788 *
14789 * var stamp = _.now();
14790 * _.defer(function() { console.log(_.now() - stamp); });
14791 * // => logs the number of milliseconds it took for the deferred function to be called
14792 */
14793 var now = isNative(now = Date.now) && now || function() {
14794 return new Date().getTime();
14795 };
14796
14797 /**
14798 * Converts the given value into an integer of the specified radix.
14799 * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the
14800 * `value` is a hexadecimal, in which case a `radix` of `16` is used.
14801 *
14802 * Note: This method avoids differences in native ES3 and ES5 `parseInt`
14803 * implementations. See http://es5.github.io/#E.
14804 *
14805 * @static
14806 * @memberOf _
14807 * @category Utilities
14808 * @param {string} value The value to parse.
14809 * @param {number} [radix] The radix used to interpret the value to parse.
14810 * @returns {number} Returns the new integer value.
14811 * @example
14812 *
14813 * _.parseInt('08');
14814 * // => 8
14815 */
14816 var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) {
14817 // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt`
14818 return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0);
14819 };
14820
14821 /**
14822 * Creates a "_.pluck" style function, which returns the `key` value of a
14823 * given object.
14824 *
14825 * @static
14826 * @memberOf _
14827 * @category Utilities
14828 * @param {string} key The name of the property to retrieve.
14829 * @returns {Function} Returns the new function.
14830 * @example
14831 *
14832 * var characters = [
14833 * { 'name': 'fred', 'age': 40 },
14834 * { 'name': 'barney', 'age': 36 }
14835 * ];
14836 *
14837 * var getName = _.property('name');
14838 *
14839 * _.map(characters, getName);
14840 * // => ['barney', 'fred']
14841 *
14842 * _.sortBy(characters, getName);
14843 * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }]
14844 */
14845 function property(key) {
14846 return function(object) {
14847 return object[key];
14848 };
14849 }
14850
14851 /**
14852 * Produces a random number between `min` and `max` (inclusive). If only one
14853 * argument is provided a number between `0` and the given number will be
14854 * returned. If `floating` is truey or either `min` or `max` are floats a
14855 * floating-point number will be returned instead of an integer.
14856 *
14857 * @static
14858 * @memberOf _
14859 * @category Utilities
14860 * @param {number} [min=0] The minimum possible value.
14861 * @param {number} [max=1] The maximum possible value.
14862 * @param {boolean} [floating=false] Specify returning a floating-point number.
14863 * @returns {number} Returns a random number.
14864 * @example
14865 *
14866 * _.random(0, 5);
14867 * // => an integer between 0 and 5
14868 *
14869 * _.random(5);
14870 * // => also an integer between 0 and 5
14871 *
14872 * _.random(5, true);
14873 * // => a floating-point number between 0 and 5
14874 *
14875 * _.random(1.2, 5.2);
14876 * // => a floating-point number between 1.2 and 5.2
14877 */
14878 function random(min, max, floating) {
14879 var noMin = min == null,
14880 noMax = max == null;
14881
14882 if (floating == null) {
14883 if (typeof min == 'boolean' && noMax) {
14884 floating = min;
14885 min = 1;
14886 }
14887 else if (!noMax && typeof max == 'boolean') {
14888 floating = max;
14889 noMax = true;
14890 }
14891 }
14892 if (noMin && noMax) {
14893 max = 1;
14894 }
14895 min = +min || 0;
14896 if (noMax) {
14897 max = min;
14898 min = 0;
14899 } else {
14900 max = +max || 0;
14901 }
14902 if (floating || min % 1 || max % 1) {
14903 var rand = nativeRandom();
14904 return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max);
14905 }
14906 return baseRandom(min, max);
14907 }
14908
14909 /**
14910 * Resolves the value of property `key` on `object`. If `key` is a function
14911 * it will be invoked with the `this` binding of `object` and its result returned,
14912 * else the property value is returned. If `object` is falsey then `undefined`
14913 * is returned.
14914 *
14915 * @static
14916 * @memberOf _
14917 * @category Utilities
14918 * @param {Object} object The object to inspect.
14919 * @param {string} key The name of the property to resolve.
14920 * @returns {*} Returns the resolved value.
14921 * @example
14922 *
14923 * var object = {
14924 * 'cheese': 'crumpets',
14925 * 'stuff': function() {
14926 * return 'nonsense';
14927 * }
14928 * };
14929 *
14930 * _.result(object, 'cheese');
14931 * // => 'crumpets'
14932 *
14933 * _.result(object, 'stuff');
14934 * // => 'nonsense'
14935 */
14936 function result(object, key) {
14937 if (object) {
14938 var value = object[key];
14939 return isFunction(value) ? object[key]() : value;
14940 }
14941 }
14942
14943 /**
14944 * A micro-templating method that handles arbitrary delimiters, preserves
14945 * whitespace, and correctly escapes quotes within interpolated code.
14946 *
14947 * Note: In the development build, `_.template` utilizes sourceURLs for easier
14948 * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
14949 *
14950 * For more information on precompiling templates see:
14951 * http://lodash.com/custom-builds
14952 *
14953 * For more information on Chrome extension sandboxes see:
14954 * http://developer.chrome.com/stable/extensions/sandboxingEval.html
14955 *
14956 * @static
14957 * @memberOf _
14958 * @category Utilities
14959 * @param {string} text The template text.
14960 * @param {Object} data The data object used to populate the text.
14961 * @param {Object} [options] The options object.
14962 * @param {RegExp} [options.escape] The "escape" delimiter.
14963 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
14964 * @param {Object} [options.imports] An object to import into the template as local variables.
14965 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
14966 * @param {string} [sourceURL] The sourceURL of the template's compiled source.
14967 * @param {string} [variable] The data object variable name.
14968 * @returns {Function|string} Returns a compiled function when no `data` object
14969 * is given, else it returns the interpolated text.
14970 * @example
14971 *
14972 * // using the "interpolate" delimiter to create a compiled template
14973 * var compiled = _.template('hello <%= name %>');
14974 * compiled({ 'name': 'fred' });
14975 * // => 'hello fred'
14976 *
14977 * // using the "escape" delimiter to escape HTML in data property values
14978 * _.template('<b><%- value %></b>', { 'value': '<script>' });
14979 * // => '<b>&lt;script&gt;</b>'
14980 *
14981 * // using the "evaluate" delimiter to generate HTML
14982 * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
14983 * _.template(list, { 'people': ['fred', 'barney'] });
14984 * // => '<li>fred</li><li>barney</li>'
14985 *
14986 * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
14987 * _.template('hello ${ name }', { 'name': 'pebbles' });
14988 * // => 'hello pebbles'
14989 *
14990 * // using the internal `print` function in "evaluate" delimiters
14991 * _.template('<% print("hello " + name); %>!', { 'name': 'barney' });
14992 * // => 'hello barney!'
14993 *
14994 * // using a custom template delimiters
14995 * _.templateSettings = {
14996 * 'interpolate': /{{([\s\S]+?)}}/g
14997 * };
14998 *
14999 * _.template('hello {{ name }}!', { 'name': 'mustache' });
15000 * // => 'hello mustache!'
15001 *
15002 * // using the `imports` option to import jQuery
15003 * var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
15004 * _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
15005 * // => '<li>fred</li><li>barney</li>'
15006 *
15007 * // using the `sourceURL` option to specify a custom sourceURL for the template
15008 * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
15009 * compiled(data);
15010 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
15011 *
15012 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
15013 * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
15014 * compiled.source;
15015 * // => function(data) {
15016 * var __t, __p = '', __e = _.escape;
15017 * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
15018 * return __p;
15019 * }
15020 *
15021 * // using the `source` property to inline compiled templates for meaningful
15022 * // line numbers in error messages and a stack trace
15023 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
15024 * var JST = {\
15025 * "main": ' + _.template(mainText).source + '\
15026 * };\
15027 * ');
15028 */
15029 function template(text, data, options) {
15030 // based on John Resig's `tmpl` implementation
15031 // http://ejohn.org/blog/javascript-micro-templating/
15032 // and Laura Doktorova's doT.js
15033 // https://github.com/olado/doT
15034 var settings = lodash.templateSettings;
15035 text = String(text || '');
15036
15037 // avoid missing dependencies when `iteratorTemplate` is not defined
15038 options = defaults({}, options, settings);
15039
15040 var imports = defaults({}, options.imports, settings.imports),
15041 importsKeys = keys(imports),
15042 importsValues = values(imports);
15043
15044 var isEvaluating,
15045 index = 0,
15046 interpolate = options.interpolate || reNoMatch,
15047 source = "__p += '";
15048
15049 // compile the regexp to match each delimiter
15050 var reDelimiters = RegExp(
15051 (options.escape || reNoMatch).source + '|' +
15052 interpolate.source + '|' +
15053 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
15054 (options.evaluate || reNoMatch).source + '|$'
15055 , 'g');
15056
15057 text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
15058 interpolateValue || (interpolateValue = esTemplateValue);
15059
15060 // escape characters that cannot be included in string literals
15061 source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
15062
15063 // replace delimiters with snippets
15064 if (escapeValue) {
15065 source += "' +\n__e(" + escapeValue + ") +\n'";
15066 }
15067 if (evaluateValue) {
15068 isEvaluating = true;
15069 source += "';\n" + evaluateValue + ";\n__p += '";
15070 }
15071 if (interpolateValue) {
15072 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
15073 }
15074 index = offset + match.length;
15075
15076 // the JS engine embedded in Adobe products requires returning the `match`
15077 // string in order to produce the correct `offset` value
15078 return match;
15079 });
15080
15081 source += "';\n";
15082
15083 // if `variable` is not specified, wrap a with-statement around the generated
15084 // code to add the data object to the top of the scope chain
15085 var variable = options.variable,
15086 hasVariable = variable;
15087
15088 if (!hasVariable) {
15089 variable = 'obj';
15090 source = 'with (' + variable + ') {\n' + source + '\n}\n';
15091 }
15092 // cleanup code by stripping empty strings
15093 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
15094 .replace(reEmptyStringMiddle, '$1')
15095 .replace(reEmptyStringTrailing, '$1;');
15096
15097 // frame code as the function body
15098 source = 'function(' + variable + ') {\n' +
15099 (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
15100 "var __t, __p = '', __e = _.escape" +
15101 (isEvaluating
15102 ? ', __j = Array.prototype.join;\n' +
15103 "function print() { __p += __j.call(arguments, '') }\n"
15104 : ';\n'
15105 ) +
15106 source +
15107 'return __p\n}';
15108
15109 // Use a sourceURL for easier debugging.
15110 // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
15111 var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
15112
15113 try {
15114 var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
15115 } catch(e) {
15116 e.source = source;
15117 throw e;
15118 }
15119 if (data) {
15120 return result(data);
15121 }
15122 // provide the compiled function's source by its `toString` method, in
15123 // supported environments, or the `source` property as a convenience for
15124 // inlining compiled templates during the build process
15125 result.source = source;
15126 return result;
15127 }
15128
15129 /**
15130 * Executes the callback `n` times, returning an array of the results
15131 * of each callback execution. The callback is bound to `thisArg` and invoked
15132 * with one argument; (index).
15133 *
15134 * @static
15135 * @memberOf _
15136 * @category Utilities
15137 * @param {number} n The number of times to execute the callback.
15138 * @param {Function} callback The function called per iteration.
15139 * @param {*} [thisArg] The `this` binding of `callback`.
15140 * @returns {Array} Returns an array of the results of each `callback` execution.
15141 * @example
15142 *
15143 * var diceRolls = _.times(3, _.partial(_.random, 1, 6));
15144 * // => [3, 6, 4]
15145 *
15146 * _.times(3, function(n) { mage.castSpell(n); });
15147 * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
15148 *
15149 * _.times(3, function(n) { this.cast(n); }, mage);
15150 * // => also calls `mage.castSpell(n)` three times
15151 */
15152 function times(n, callback, thisArg) {
15153 n = (n = +n) > -1 ? n : 0;
15154 var index = -1,
15155 result = Array(n);
15156
15157 callback = baseCreateCallback(callback, thisArg, 1);
15158 while (++index < n) {
15159 result[index] = callback(index);
15160 }
15161 return result;
15162 }
15163
15164 /**
15165 * The inverse of `_.escape` this method converts the HTML entities
15166 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their
15167 * corresponding characters.
15168 *
15169 * @static
15170 * @memberOf _
15171 * @category Utilities
15172 * @param {string} string The string to unescape.
15173 * @returns {string} Returns the unescaped string.
15174 * @example
15175 *
15176 * _.unescape('Fred, Barney &amp; Pebbles');
15177 * // => 'Fred, Barney & Pebbles'
15178 */
15179 function unescape(string) {
15180 return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
15181 }
15182
15183 /**
15184 * Generates a unique ID. If `prefix` is provided the ID will be appended to it.
15185 *
15186 * @static
15187 * @memberOf _
15188 * @category Utilities
15189 * @param {string} [prefix] The value to prefix the ID with.
15190 * @returns {string} Returns the unique ID.
15191 * @example
15192 *
15193 * _.uniqueId('contact_');
15194 * // => 'contact_104'
15195 *
15196 * _.uniqueId();
15197 * // => '105'
15198 */
15199 function uniqueId(prefix) {
15200 var id = ++idCounter;
15201 return String(prefix == null ? '' : prefix) + id;
15202 }
15203
15204 /*--------------------------------------------------------------------------*/
15205
15206 /**
15207 * Creates a `lodash` object that wraps the given value with explicit
15208 * method chaining enabled.
15209 *
15210 * @static
15211 * @memberOf _
15212 * @category Chaining
15213 * @param {*} value The value to wrap.
15214 * @returns {Object} Returns the wrapper object.
15215 * @example
15216 *
15217 * var characters = [
15218 * { 'name': 'barney', 'age': 36 },
15219 * { 'name': 'fred', 'age': 40 },
15220 * { 'name': 'pebbles', 'age': 1 }
15221 * ];
15222 *
15223 * var youngest = _.chain(characters)
15224 * .sortBy('age')
15225 * .map(function(chr) { return chr.name + ' is ' + chr.age; })
15226 * .first()
15227 * .value();
15228 * // => 'pebbles is 1'
15229 */
15230 function chain(value) {
15231 value = new lodashWrapper(value);
15232 value.__chain__ = true;
15233 return value;
15234 }
15235
15236 /**
15237 * Invokes `interceptor` with the `value` as the first argument and then
15238 * returns `value`. The purpose of this method is to "tap into" a method
15239 * chain in order to perform operations on intermediate results within
15240 * the chain.
15241 *
15242 * @static
15243 * @memberOf _
15244 * @category Chaining
15245 * @param {*} value The value to provide to `interceptor`.
15246 * @param {Function} interceptor The function to invoke.
15247 * @returns {*} Returns `value`.
15248 * @example
15249 *
15250 * _([1, 2, 3, 4])
15251 * .tap(function(array) { array.pop(); })
15252 * .reverse()
15253 * .value();
15254 * // => [3, 2, 1]
15255 */
15256 function tap(value, interceptor) {
15257 interceptor(value);
15258 return value;
15259 }
15260
15261 /**
15262 * Enables explicit method chaining on the wrapper object.
15263 *
15264 * @name chain
15265 * @memberOf _
15266 * @category Chaining
15267 * @returns {*} Returns the wrapper object.
15268 * @example
15269 *
15270 * var characters = [
15271 * { 'name': 'barney', 'age': 36 },
15272 * { 'name': 'fred', 'age': 40 }
15273 * ];
15274 *
15275 * // without explicit chaining
15276 * _(characters).first();
15277 * // => { 'name': 'barney', 'age': 36 }
15278 *
15279 * // with explicit chaining
15280 * _(characters).chain()
15281 * .first()
15282 * .pick('age')
15283 * .value();
15284 * // => { 'age': 36 }
15285 */
15286 function wrapperChain() {
15287 this.__chain__ = true;
15288 return this;
15289 }
15290
15291 /**
15292 * Produces the `toString` result of the wrapped value.
15293 *
15294 * @name toString
15295 * @memberOf _
15296 * @category Chaining
15297 * @returns {string} Returns the string result.
15298 * @example
15299 *
15300 * _([1, 2, 3]).toString();
15301 * // => '1,2,3'
15302 */
15303 function wrapperToString() {
15304 return String(this.__wrapped__);
15305 }
15306
15307 /**
15308 * Extracts the wrapped value.
15309 *
15310 * @name valueOf
15311 * @memberOf _
15312 * @alias value
15313 * @category Chaining
15314 * @returns {*} Returns the wrapped value.
15315 * @example
15316 *
15317 * _([1, 2, 3]).valueOf();
15318 * // => [1, 2, 3]
15319 */
15320 function wrapperValueOf() {
15321 return this.__wrapped__;
15322 }
15323
15324 /*--------------------------------------------------------------------------*/
15325
15326 // add functions that return wrapped values when chaining
15327 lodash.after = after;
15328 lodash.assign = assign;
15329 lodash.at = at;
15330 lodash.bind = bind;
15331 lodash.bindAll = bindAll;
15332 lodash.bindKey = bindKey;
15333 lodash.chain = chain;
15334 lodash.compact = compact;
15335 lodash.compose = compose;
15336 lodash.constant = constant;
15337 lodash.countBy = countBy;
15338 lodash.create = create;
15339 lodash.createCallback = createCallback;
15340 lodash.curry = curry;
15341 lodash.debounce = debounce;
15342 lodash.defaults = defaults;
15343 lodash.defer = defer;
15344 lodash.delay = delay;
15345 lodash.difference = difference;
15346 lodash.filter = filter;
15347 lodash.flatten = flatten;
15348 lodash.forEach = forEach;
15349 lodash.forEachRight = forEachRight;
15350 lodash.forIn = forIn;
15351 lodash.forInRight = forInRight;
15352 lodash.forOwn = forOwn;
15353 lodash.forOwnRight = forOwnRight;
15354 lodash.functions = functions;
15355 lodash.groupBy = groupBy;
15356 lodash.indexBy = indexBy;
15357 lodash.initial = initial;
15358 lodash.intersection = intersection;
15359 lodash.invert = invert;
15360 lodash.invoke = invoke;
15361 lodash.keys = keys;
15362 lodash.map = map;
15363 lodash.mapValues = mapValues;
15364 lodash.max = max;
15365 lodash.memoize = memoize;
15366 lodash.merge = merge;
15367 lodash.min = min;
15368 lodash.omit = omit;
15369 lodash.once = once;
15370 lodash.pairs = pairs;
15371 lodash.partial = partial;
15372 lodash.partialRight = partialRight;
15373 lodash.pick = pick;
15374 lodash.pluck = pluck;
15375 lodash.property = property;
15376 lodash.pull = pull;
15377 lodash.range = range;
15378 lodash.reject = reject;
15379 lodash.remove = remove;
15380 lodash.rest = rest;
15381 lodash.shuffle = shuffle;
15382 lodash.sortBy = sortBy;
15383 lodash.tap = tap;
15384 lodash.throttle = throttle;
15385 lodash.times = times;
15386 lodash.toArray = toArray;
15387 lodash.transform = transform;
15388 lodash.union = union;
15389 lodash.uniq = uniq;
15390 lodash.values = values;
15391 lodash.where = where;
15392 lodash.without = without;
15393 lodash.wrap = wrap;
15394 lodash.xor = xor;
15395 lodash.zip = zip;
15396 lodash.zipObject = zipObject;
15397
15398 // add aliases
15399 lodash.collect = map;
15400 lodash.drop = rest;
15401 lodash.each = forEach;
15402 lodash.eachRight = forEachRight;
15403 lodash.extend = assign;
15404 lodash.methods = functions;
15405 lodash.object = zipObject;
15406 lodash.select = filter;
15407 lodash.tail = rest;
15408 lodash.unique = uniq;
15409 lodash.unzip = zip;
15410
15411 // add functions to `lodash.prototype`
15412 mixin(lodash);
15413
15414 /*--------------------------------------------------------------------------*/
15415
15416 // add functions that return unwrapped values when chaining
15417 lodash.clone = clone;
15418 lodash.cloneDeep = cloneDeep;
15419 lodash.contains = contains;
15420 lodash.escape = escape;
15421 lodash.every = every;
15422 lodash.find = find;
15423 lodash.findIndex = findIndex;
15424 lodash.findKey = findKey;
15425 lodash.findLast = findLast;
15426 lodash.findLastIndex = findLastIndex;
15427 lodash.findLastKey = findLastKey;
15428 lodash.has = has;
15429 lodash.identity = identity;
15430 lodash.indexOf = indexOf;
15431 lodash.isArguments = isArguments;
15432 lodash.isArray = isArray;
15433 lodash.isBoolean = isBoolean;
15434 lodash.isDate = isDate;
15435 lodash.isElement = isElement;
15436 lodash.isEmpty = isEmpty;
15437 lodash.isEqual = isEqual;
15438 lodash.isFinite = isFinite;
15439 lodash.isFunction = isFunction;
15440 lodash.isNaN = isNaN;
15441 lodash.isNull = isNull;
15442 lodash.isNumber = isNumber;
15443 lodash.isObject = isObject;
15444 lodash.isPlainObject = isPlainObject;
15445 lodash.isRegExp = isRegExp;
15446 lodash.isString = isString;
15447 lodash.isUndefined = isUndefined;
15448 lodash.lastIndexOf = lastIndexOf;
15449 lodash.mixin = mixin;
15450 lodash.noConflict = noConflict;
15451 lodash.noop = noop;
15452 lodash.now = now;
15453 lodash.parseInt = parseInt;
15454 lodash.random = random;
15455 lodash.reduce = reduce;
15456 lodash.reduceRight = reduceRight;
15457 lodash.result = result;
15458 lodash.runInContext = runInContext;
15459 lodash.size = size;
15460 lodash.some = some;
15461 lodash.sortedIndex = sortedIndex;
15462 lodash.template = template;
15463 lodash.unescape = unescape;
15464 lodash.uniqueId = uniqueId;
15465
15466 // add aliases
15467 lodash.all = every;
15468 lodash.any = some;
15469 lodash.detect = find;
15470 lodash.findWhere = find;
15471 lodash.foldl = reduce;
15472 lodash.foldr = reduceRight;
15473 lodash.include = contains;
15474 lodash.inject = reduce;
15475
15476 mixin(function() {
15477 var source = {}
15478 forOwn(lodash, function(func, methodName) {
15479 if (!lodash.prototype[methodName]) {
15480 source[methodName] = func;
15481 }
15482 });
15483 return source;
15484 }(), false);
15485
15486 /*--------------------------------------------------------------------------*/
15487
15488 // add functions capable of returning wrapped and unwrapped values when chaining
15489 lodash.first = first;
15490 lodash.last = last;
15491 lodash.sample = sample;
15492
15493 // add aliases
15494 lodash.take = first;
15495 lodash.head = first;
15496
15497 forOwn(lodash, function(func, methodName) {
15498 var callbackable = methodName !== 'sample';
15499 if (!lodash.prototype[methodName]) {
15500 lodash.prototype[methodName]= function(n, guard) {
15501 var chainAll = this.__chain__,
15502 result = func(this.__wrapped__, n, guard);
15503
15504 return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function')))
15505 ? result
15506 : new lodashWrapper(result, chainAll);
15507 };
15508 }
15509 });
15510
15511 /*--------------------------------------------------------------------------*/
15512
15513 /**
15514 * The semantic version number.
15515 *
15516 * @static
15517 * @memberOf _
15518 * @type string
15519 */
15520 lodash.VERSION = '2.4.1';
15521
15522 // add "Chaining" functions to the wrapper
15523 lodash.prototype.chain = wrapperChain;
15524 lodash.prototype.toString = wrapperToString;
15525 lodash.prototype.value = wrapperValueOf;
15526 lodash.prototype.valueOf = wrapperValueOf;
15527
15528 // add `Array` functions that return unwrapped values
15529 forEach(['join', 'pop', 'shift'], function(methodName) {
15530 var func = arrayRef[methodName];
15531 lodash.prototype[methodName] = function() {
15532 var chainAll = this.__chain__,
15533 result = func.apply(this.__wrapped__, arguments);
15534
15535 return chainAll
15536 ? new lodashWrapper(result, chainAll)
15537 : result;
15538 };
15539 });
15540
15541 // add `Array` functions that return the existing wrapped value
15542 forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
15543 var func = arrayRef[methodName];
15544 lodash.prototype[methodName] = function() {
15545 func.apply(this.__wrapped__, arguments);
15546 return this;
15547 };
15548 });
15549
15550 // add `Array` functions that return new wrapped values
15551 forEach(['concat', 'slice', 'splice'], function(methodName) {
15552 var func = arrayRef[methodName];
15553 lodash.prototype[methodName] = function() {
15554 return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
15555 };
15556 });
15557
15558 return lodash;
15559 }
15560
15561 /*--------------------------------------------------------------------------*/
15562
15563 // expose Lo-Dash
15564 var _ = runInContext();
15565
15566 // some AMD build optimizers like r.js check for condition patterns like the following:
15567 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
15568 // Expose Lo-Dash to the global object even when an AMD loader is present in
15569 // case Lo-Dash is loaded with a RequireJS shim config.
15570 // See http://requirejs.org/docs/api.html#config-shim
15571 root._ = _;
15572
15573 // define as an anonymous module so, through path mapping, it can be
15574 // referenced as the "underscore" module
15575 define(function() {
15576 return _;
15577 });
15578 }
15579 // check for `exports` after `define` in case a build optimizer adds an `exports` object
15580 else if (freeExports && freeModule) {
15581 // in Node.js or RingoJS
15582 if (moduleExports) {
15583 (freeModule.exports = _)._ = _;
15584 }
15585 // in Narwhal or Rhino -require
15586 else {
15587 freeExports._ = _;
15588 }
15589 }
15590 else {
15591 // in a browser or Rhino
15592 root._ = _;
15593 }
15594}.call(this));
15595
15596}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15597},{}],55:[function(require,module,exports){
15598(function (process){
15599// Copyright 2010-2012 Mikeal Rogers
15600//
15601// Licensed under the Apache License, Version 2.0 (the "License");
15602// you may not use this file except in compliance with the License.
15603// You may obtain a copy of the License at
15604//
15605// http://www.apache.org/licenses/LICENSE-2.0
15606//
15607// Unless required by applicable law or agreed to in writing, software
15608// distributed under the License is distributed on an "AS IS" BASIS,
15609// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15610// See the License for the specific language governing permissions and
15611// limitations under the License.
15612
15613var optional = require('./lib/optional')
15614 , cookie = optional('tough-cookie')
15615 , Cookie = cookie && cookie.Cookie
15616 , CookieJar = cookie && cookie.CookieJar
15617 , cookieJar = CookieJar && new CookieJar
15618
15619 , copy = require('./lib/copy')
15620 , Request = require('./request')
15621 ;
15622
15623
15624
15625// organize params for patch, post, put, head, del
15626function initParams(uri, options, callback) {
15627 if ((typeof options === 'function') && !callback) callback = options
15628 if (options && typeof options === 'object') {
15629 options.uri = uri
15630 } else if (typeof uri === 'string') {
15631 options = {uri:uri}
15632 } else {
15633 options = uri
15634 uri = options.uri
15635 }
15636 return { uri: uri, options: options, callback: callback }
15637}
15638
15639function request (uri, options, callback) {
15640 if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.')
15641 if ((typeof options === 'function') && !callback) callback = options
15642 if (options && typeof options === 'object') {
15643 options.uri = uri
15644 } else if (typeof uri === 'string') {
15645 options = {uri:uri}
15646 } else {
15647 options = uri
15648 }
15649
15650 options = copy(options)
15651
15652 if (callback) options.callback = callback
15653 var r = new Request(options)
15654 return r
15655}
15656
15657module.exports = request
15658
15659request.Request = Request;
15660
15661request.debug = process.env.NODE_DEBUG && /request/.test(process.env.NODE_DEBUG)
15662
15663request.initParams = initParams
15664
15665request.defaults = function (options, requester) {
15666 var def = function (method) {
15667 var d = function (uri, opts, callback) {
15668 var params = initParams(uri, opts, callback)
15669 for (var i in options) {
15670 if (params.options[i] === undefined) params.options[i] = options[i]
15671 }
15672 if(typeof requester === 'function') {
15673 if(method === request) {
15674 method = requester
15675 } else {
15676 params.options._requester = requester
15677 }
15678 }
15679 return method(params.options, params.callback)
15680 }
15681 return d
15682 }
15683 var de = def(request)
15684 de.get = def(request.get)
15685 de.patch = def(request.patch)
15686 de.post = def(request.post)
15687 de.put = def(request.put)
15688 de.head = def(request.head)
15689 de.del = def(request.del)
15690 de.cookie = def(request.cookie)
15691 de.jar = request.jar
15692 return de
15693}
15694
15695function requester(params) {
15696 if(typeof params.options._requester === 'function') {
15697 return params.options._requester
15698 } else {
15699 return request
15700 }
15701}
15702
15703request.forever = function (agentOptions, optionsArg) {
15704 var options = {}
15705 if (optionsArg) {
15706 for (var option in optionsArg) {
15707 options[option] = optionsArg[option]
15708 }
15709 }
15710 if (agentOptions) options.agentOptions = agentOptions
15711 options.forever = true
15712 return request.defaults(options)
15713}
15714
15715request.get = request
15716request.post = function (uri, options, callback) {
15717 var params = initParams(uri, options, callback)
15718 params.options.method = 'POST'
15719 return requester(params)(params.uri || null, params.options, params.callback)
15720}
15721request.put = function (uri, options, callback) {
15722 var params = initParams(uri, options, callback)
15723 params.options.method = 'PUT'
15724 return requester(params)(params.uri || null, params.options, params.callback)
15725}
15726request.patch = function (uri, options, callback) {
15727 var params = initParams(uri, options, callback)
15728 params.options.method = 'PATCH'
15729 return requester(params)(params.uri || null, params.options, params.callback)
15730}
15731request.head = function (uri, options, callback) {
15732 var params = initParams(uri, options, callback)
15733 params.options.method = 'HEAD'
15734 if (params.options.body ||
15735 params.options.requestBodyStream ||
15736 (params.options.json && typeof params.options.json !== 'boolean') ||
15737 params.options.multipart) {
15738 throw new Error("HTTP HEAD requests MUST NOT include a request body.")
15739 }
15740
15741 return requester(params)(params.uri || null, params.options, params.callback)
15742}
15743request.del = function (uri, options, callback) {
15744 var params = initParams(uri, options, callback)
15745 params.options.method = 'DELETE'
15746 return requester(params)(params.uri || null, params.options, params.callback)
15747}
15748request.jar = function () {
15749 return new CookieJar
15750}
15751request.cookie = function (str) {
15752 if (str && str.uri) str = str.uri
15753 if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param")
15754 return new Cookie(str)
15755}
15756
15757}).call(this,require('_process'))
15758},{"./lib/copy":56,"./lib/optional":59,"./request":65,"_process":31}],56:[function(require,module,exports){
15759module.exports =
15760function copy (obj) {
15761 var o = {}
15762 Object.keys(obj).forEach(function (i) {
15763 o[i] = obj[i]
15764 })
15765 return o
15766}
15767},{}],57:[function(require,module,exports){
15768(function (process){
15769var util = require('util')
15770
15771module.exports =
15772function debug () {
15773 if (/\brequest\b/.test(process.env.NODE_DEBUG))
15774 console.error('REQUEST %s', util.format.apply(util, arguments))
15775}
15776
15777}).call(this,require('_process'))
15778},{"_process":31,"util":51}],58:[function(require,module,exports){
15779// Safe toJSON
15780module.exports =
15781function getSafe (self, uuid) {
15782 if (typeof self === 'object' || typeof self === 'function') var safe = {}
15783 if (Array.isArray(self)) var safe = []
15784
15785 var recurse = []
15786
15787 Object.defineProperty(self, uuid, {})
15788
15789 var attrs = Object.keys(self).filter(function (i) {
15790 if (i === uuid) return false
15791 if ( (typeof self[i] !== 'object' && typeof self[i] !== 'function') || self[i] === null) return true
15792 return !(Object.getOwnPropertyDescriptor(self[i], uuid))
15793 })
15794
15795
15796 for (var i=0;i<attrs.length;i++) {
15797 if ( (typeof self[attrs[i]] !== 'object' && typeof self[attrs[i]] !== 'function') ||
15798 self[attrs[i]] === null
15799 ) {
15800 safe[attrs[i]] = self[attrs[i]]
15801 } else {
15802 recurse.push(attrs[i])
15803 Object.defineProperty(self[attrs[i]], uuid, {})
15804 }
15805 }
15806
15807 for (var i=0;i<recurse.length;i++) {
15808 safe[recurse[i]] = getSafe(self[recurse[i]], uuid)
15809 }
15810
15811 return safe
15812}
15813},{}],59:[function(require,module,exports){
15814module.exports = function(module) {
15815 try {
15816 return require(module);
15817 } catch (e) {}
15818};
15819
15820},{}],60:[function(require,module,exports){
15821module.exports = ForeverAgent
15822ForeverAgent.SSL = ForeverAgentSSL
15823
15824var util = require('util')
15825 , Agent = require('http').Agent
15826 , net = require('net')
15827 , tls = require('tls')
15828 , AgentSSL = require('https').Agent
15829
15830function ForeverAgent(options) {
15831 var self = this
15832 self.options = options || {}
15833 self.requests = {}
15834 self.sockets = {}
15835 self.freeSockets = {}
15836 self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
15837 self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
15838 self.on('free', function(socket, host, port) {
15839 var name = host + ':' + port
15840 if (self.requests[name] && self.requests[name].length) {
15841 self.requests[name].shift().onSocket(socket)
15842 } else if (self.sockets[name].length < self.minSockets) {
15843 if (!self.freeSockets[name]) self.freeSockets[name] = []
15844 self.freeSockets[name].push(socket)
15845
15846 // if an error happens while we don't use the socket anyway, meh, throw the socket away
15847 var onIdleError = function() {
15848 socket.destroy()
15849 }
15850 socket._onIdleError = onIdleError
15851 socket.on('error', onIdleError)
15852 } else {
15853 // If there are no pending requests just destroy the
15854 // socket and it will get removed from the pool. This
15855 // gets us out of timeout issues and allows us to
15856 // default to Connection:keep-alive.
15857 socket.destroy()
15858 }
15859 })
15860
15861}
15862util.inherits(ForeverAgent, Agent)
15863
15864ForeverAgent.defaultMinSockets = 5
15865
15866
15867ForeverAgent.prototype.createConnection = net.createConnection
15868ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
15869ForeverAgent.prototype.addRequest = function(req, host, port) {
15870 var name = host + ':' + port
15871 if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
15872 var idleSocket = this.freeSockets[name].pop()
15873 idleSocket.removeListener('error', idleSocket._onIdleError)
15874 delete idleSocket._onIdleError
15875 req._reusedSocket = true
15876 req.onSocket(idleSocket)
15877 } else {
15878 this.addRequestNoreuse(req, host, port)
15879 }
15880}
15881
15882ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
15883 if (this.sockets[name]) {
15884 var index = this.sockets[name].indexOf(s)
15885 if (index !== -1) {
15886 this.sockets[name].splice(index, 1)
15887 }
15888 } else if (this.sockets[name] && this.sockets[name].length === 0) {
15889 // don't leak
15890 delete this.sockets[name]
15891 delete this.requests[name]
15892 }
15893
15894 if (this.freeSockets[name]) {
15895 var index = this.freeSockets[name].indexOf(s)
15896 if (index !== -1) {
15897 this.freeSockets[name].splice(index, 1)
15898 if (this.freeSockets[name].length === 0) {
15899 delete this.freeSockets[name]
15900 }
15901 }
15902 }
15903
15904 if (this.requests[name] && this.requests[name].length) {
15905 // If we have pending requests and a socket gets closed a new one
15906 // needs to be created to take over in the pool for the one that closed.
15907 this.createSocket(name, host, port).emit('free')
15908 }
15909}
15910
15911function ForeverAgentSSL (options) {
15912 ForeverAgent.call(this, options)
15913}
15914util.inherits(ForeverAgentSSL, ForeverAgent)
15915
15916ForeverAgentSSL.prototype.createConnection = createConnectionSSL
15917ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
15918
15919function createConnectionSSL (port, host, options) {
15920 if (typeof port === 'object') {
15921 options = port;
15922 } else if (typeof host === 'object') {
15923 options = host;
15924 } else if (typeof options === 'object') {
15925 options = options;
15926 } else {
15927 options = {};
15928 }
15929
15930 if (typeof port === 'number') {
15931 options.port = port;
15932 }
15933
15934 if (typeof host === 'string') {
15935 options.host = host;
15936 }
15937
15938 return tls.connect(options);
15939}
15940
15941},{"http":23,"https":27,"net":2,"tls":2,"util":51}],61:[function(require,module,exports){
15942module.exports = stringify;
15943
15944function getSerialize (fn, decycle) {
15945 var seen = [], keys = [];
15946 decycle = decycle || function(key, value) {
15947 return '[Circular ' + getPath(value, seen, keys) + ']'
15948 };
15949 return function(key, value) {
15950 var ret = value;
15951 if (typeof value === 'object' && value) {
15952 if (seen.indexOf(value) !== -1)
15953 ret = decycle(key, value);
15954 else {
15955 seen.push(value);
15956 keys.push(key);
15957 }
15958 }
15959 if (fn) ret = fn(key, ret);
15960 return ret;
15961 }
15962}
15963
15964function getPath (value, seen, keys) {
15965 var index = seen.indexOf(value);
15966 var path = [ keys[index] ];
15967 for (index--; index >= 0; index--) {
15968 if (seen[index][ path[0] ] === value) {
15969 value = seen[index];
15970 path.unshift(keys[index]);
15971 }
15972 }
15973 return '~' + path.join('.');
15974}
15975
15976function stringify(obj, fn, spaces, decycle) {
15977 return JSON.stringify(obj, getSerialize(fn, decycle), spaces);
15978}
15979
15980stringify.getSerialize = getSerialize;
15981
15982},{}],62:[function(require,module,exports){
15983(function (process,__dirname){
15984var path = require('path');
15985var fs = require('fs');
15986
15987function Mime() {
15988 // Map of extension -> mime type
15989 this.types = Object.create(null);
15990
15991 // Map of mime type -> extension
15992 this.extensions = Object.create(null);
15993}
15994
15995/**
15996 * Define mimetype -> extension mappings. Each key is a mime-type that maps
15997 * to an array of extensions associated with the type. The first extension is
15998 * used as the default extension for the type.
15999 *
16000 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
16001 *
16002 * @param map (Object) type definitions
16003 */
16004Mime.prototype.define = function (map) {
16005 for (var type in map) {
16006 var exts = map[type];
16007
16008 for (var i = 0; i < exts.length; i++) {
16009 if (process.env.DEBUG_MIME && this.types[exts]) {
16010 console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
16011 this.types[exts] + ' to ' + type);
16012 }
16013
16014 this.types[exts[i]] = type;
16015 }
16016
16017 // Default extension is the first one we encounter
16018 if (!this.extensions[type]) {
16019 this.extensions[type] = exts[0];
16020 }
16021 }
16022};
16023
16024/**
16025 * Load an Apache2-style ".types" file
16026 *
16027 * This may be called multiple times (it's expected). Where files declare
16028 * overlapping types/extensions, the last file wins.
16029 *
16030 * @param file (String) path of file to load.
16031 */
16032Mime.prototype.load = function(file) {
16033
16034 this._loading = file;
16035 // Read file and split into lines
16036 var map = {},
16037 content = fs.readFileSync(file, 'ascii'),
16038 lines = content.split(/[\r\n]+/);
16039
16040 lines.forEach(function(line) {
16041 // Clean up whitespace/comments, and split into fields
16042 var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
16043 map[fields.shift()] = fields;
16044 });
16045
16046 this.define(map);
16047
16048 this._loading = null;
16049};
16050
16051/**
16052 * Lookup a mime type based on extension
16053 */
16054Mime.prototype.lookup = function(path, fallback) {
16055 var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase();
16056
16057 return this.types[ext] || fallback || this.default_type;
16058};
16059
16060/**
16061 * Return file extension associated with a mime type
16062 */
16063Mime.prototype.extension = function(mimeType) {
16064 var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
16065 return this.extensions[type];
16066};
16067
16068// Default instance
16069var mime = new Mime();
16070
16071// Load local copy of
16072// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
16073mime.load(path.join(__dirname, 'types/mime.types'));
16074
16075// Load additional types from node.js community
16076mime.load(path.join(__dirname, 'types/node.types'));
16077
16078// Default type
16079mime.default_type = mime.lookup('bin');
16080
16081//
16082// Additional API specific to the default instance
16083//
16084
16085mime.Mime = Mime;
16086
16087/**
16088 * Lookup a charset based on mime type.
16089 */
16090mime.charsets = {
16091 lookup: function(mimeType, fallback) {
16092 // Assume text types are utf8
16093 return (/^text\//).test(mimeType) ? 'UTF-8' : fallback;
16094 }
16095};
16096
16097module.exports = mime;
16098
16099}).call(this,require('_process'),"/node_modules/request/node_modules/mime")
16100},{"_process":31,"fs":2,"path":30}],63:[function(require,module,exports){
16101(function (Buffer){
16102// uuid.js
16103//
16104// Copyright (c) 2010-2012 Robert Kieffer
16105// MIT License - http://opensource.org/licenses/mit-license.php
16106
16107(function() {
16108 var _global = this;
16109
16110 // Unique ID creation requires a high quality random # generator. We feature
16111 // detect to determine the best RNG source, normalizing to a function that
16112 // returns 128-bits of randomness, since that's what's usually required
16113 var _rng;
16114
16115 // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
16116 //
16117 // Moderately fast, high quality
16118 if (typeof(require) == 'function') {
16119 try {
16120 var _rb = require('crypto').randomBytes;
16121 _rng = _rb && function() {return _rb(16);};
16122 } catch(e) {}
16123 }
16124
16125 if (!_rng && _global.crypto && crypto.getRandomValues) {
16126 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
16127 //
16128 // Moderately fast, high quality
16129 var _rnds8 = new Uint8Array(16);
16130 _rng = function whatwgRNG() {
16131 crypto.getRandomValues(_rnds8);
16132 return _rnds8;
16133 };
16134 }
16135
16136 if (!_rng) {
16137 // Math.random()-based (RNG)
16138 //
16139 // If all else fails, use Math.random(). It's fast, but is of unspecified
16140 // quality.
16141 var _rnds = new Array(16);
16142 _rng = function() {
16143 for (var i = 0, r; i < 16; i++) {
16144 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
16145 _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
16146 }
16147
16148 return _rnds;
16149 };
16150 }
16151
16152 // Buffer class to use
16153 var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;
16154
16155 // Maps for number <-> hex string conversion
16156 var _byteToHex = [];
16157 var _hexToByte = {};
16158 for (var i = 0; i < 256; i++) {
16159 _byteToHex[i] = (i + 0x100).toString(16).substr(1);
16160 _hexToByte[_byteToHex[i]] = i;
16161 }
16162
16163 // **`parse()` - Parse a UUID into it's component bytes**
16164 function parse(s, buf, offset) {
16165 var i = (buf && offset) || 0, ii = 0;
16166
16167 buf = buf || [];
16168 s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
16169 if (ii < 16) { // Don't overflow!
16170 buf[i + ii++] = _hexToByte[oct];
16171 }
16172 });
16173
16174 // Zero out remaining bytes if string was short
16175 while (ii < 16) {
16176 buf[i + ii++] = 0;
16177 }
16178
16179 return buf;
16180 }
16181
16182 // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
16183 function unparse(buf, offset) {
16184 var i = offset || 0, bth = _byteToHex;
16185 return bth[buf[i++]] + bth[buf[i++]] +
16186 bth[buf[i++]] + bth[buf[i++]] + '-' +
16187 bth[buf[i++]] + bth[buf[i++]] + '-' +
16188 bth[buf[i++]] + bth[buf[i++]] + '-' +
16189 bth[buf[i++]] + bth[buf[i++]] + '-' +
16190 bth[buf[i++]] + bth[buf[i++]] +
16191 bth[buf[i++]] + bth[buf[i++]] +
16192 bth[buf[i++]] + bth[buf[i++]];
16193 }
16194
16195 // **`v1()` - Generate time-based UUID**
16196 //
16197 // Inspired by https://github.com/LiosK/UUID.js
16198 // and http://docs.python.org/library/uuid.html
16199
16200 // random #'s we need to init node and clockseq
16201 var _seedBytes = _rng();
16202
16203 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
16204 var _nodeId = [
16205 _seedBytes[0] | 0x01,
16206 _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
16207 ];
16208
16209 // Per 4.2.2, randomize (14 bit) clockseq
16210 var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
16211
16212 // Previous uuid creation time
16213 var _lastMSecs = 0, _lastNSecs = 0;
16214
16215 // See https://github.com/broofa/node-uuid for API details
16216 function v1(options, buf, offset) {
16217 var i = buf && offset || 0;
16218 var b = buf || [];
16219
16220 options = options || {};
16221
16222 var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
16223
16224 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
16225 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
16226 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
16227 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
16228 var msecs = options.msecs != null ? options.msecs : new Date().getTime();
16229
16230 // Per 4.2.1.2, use count of uuid's generated during the current clock
16231 // cycle to simulate higher resolution clock
16232 var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
16233
16234 // Time since last uuid creation (in msecs)
16235 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
16236
16237 // Per 4.2.1.2, Bump clockseq on clock regression
16238 if (dt < 0 && options.clockseq == null) {
16239 clockseq = clockseq + 1 & 0x3fff;
16240 }
16241
16242 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
16243 // time interval
16244 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
16245 nsecs = 0;
16246 }
16247
16248 // Per 4.2.1.2 Throw error if too many uuids are requested
16249 if (nsecs >= 10000) {
16250 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
16251 }
16252
16253 _lastMSecs = msecs;
16254 _lastNSecs = nsecs;
16255 _clockseq = clockseq;
16256
16257 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
16258 msecs += 12219292800000;
16259
16260 // `time_low`
16261 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
16262 b[i++] = tl >>> 24 & 0xff;
16263 b[i++] = tl >>> 16 & 0xff;
16264 b[i++] = tl >>> 8 & 0xff;
16265 b[i++] = tl & 0xff;
16266
16267 // `time_mid`
16268 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
16269 b[i++] = tmh >>> 8 & 0xff;
16270 b[i++] = tmh & 0xff;
16271
16272 // `time_high_and_version`
16273 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
16274 b[i++] = tmh >>> 16 & 0xff;
16275
16276 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
16277 b[i++] = clockseq >>> 8 | 0x80;
16278
16279 // `clock_seq_low`
16280 b[i++] = clockseq & 0xff;
16281
16282 // `node`
16283 var node = options.node || _nodeId;
16284 for (var n = 0; n < 6; n++) {
16285 b[i + n] = node[n];
16286 }
16287
16288 return buf ? buf : unparse(b);
16289 }
16290
16291 // **`v4()` - Generate random UUID**
16292
16293 // See https://github.com/broofa/node-uuid for API details
16294 function v4(options, buf, offset) {
16295 // Deprecated - 'format' argument, as supported in v1.2
16296 var i = buf && offset || 0;
16297
16298 if (typeof(options) == 'string') {
16299 buf = options == 'binary' ? new BufferClass(16) : null;
16300 options = null;
16301 }
16302 options = options || {};
16303
16304 var rnds = options.random || (options.rng || _rng)();
16305
16306 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
16307 rnds[6] = (rnds[6] & 0x0f) | 0x40;
16308 rnds[8] = (rnds[8] & 0x3f) | 0x80;
16309
16310 // Copy bytes to buffer, if provided
16311 if (buf) {
16312 for (var ii = 0; ii < 16; ii++) {
16313 buf[i + ii] = rnds[ii];
16314 }
16315 }
16316
16317 return buf || unparse(rnds);
16318 }
16319
16320 // Export public API
16321 var uuid = v4;
16322 uuid.v1 = v1;
16323 uuid.v4 = v4;
16324 uuid.parse = parse;
16325 uuid.unparse = unparse;
16326 uuid.BufferClass = BufferClass;
16327
16328 if (typeof define === 'function' && define.amd) {
16329 // Publish as AMD module
16330 define(function() {return uuid;});
16331 } else if (typeof(module) != 'undefined' && module.exports) {
16332 // Publish as node.js module
16333 module.exports = uuid;
16334 } else {
16335 // Publish as global (in browsers)
16336 var _previousRoot = _global.uuid;
16337
16338 // **`noConflict()` - (browser only) to reset global 'uuid' var**
16339 uuid.noConflict = function() {
16340 _global.uuid = _previousRoot;
16341 return uuid;
16342 };
16343
16344 _global.uuid = uuid;
16345 }
16346}).call(this);
16347
16348}).call(this,require("buffer").Buffer)
16349},{"buffer":3,"crypto":10}],64:[function(require,module,exports){
16350/**
16351 * Object#toString() ref for stringify().
16352 */
16353
16354var toString = Object.prototype.toString;
16355
16356/**
16357 * Object#hasOwnProperty ref
16358 */
16359
16360var hasOwnProperty = Object.prototype.hasOwnProperty;
16361
16362/**
16363 * Array#indexOf shim.
16364 */
16365
16366var indexOf = typeof Array.prototype.indexOf === 'function'
16367 ? function(arr, el) { return arr.indexOf(el); }
16368 : function(arr, el) {
16369 for (var i = 0; i < arr.length; i++) {
16370 if (arr[i] === el) return i;
16371 }
16372 return -1;
16373 };
16374
16375/**
16376 * Array.isArray shim.
16377 */
16378
16379var isArray = Array.isArray || function(arr) {
16380 return toString.call(arr) == '[object Array]';
16381};
16382
16383/**
16384 * Object.keys shim.
16385 */
16386
16387var objectKeys = Object.keys || function(obj) {
16388 var ret = [];
16389 for (var key in obj) {
16390 if (obj.hasOwnProperty(key)) {
16391 ret.push(key);
16392 }
16393 }
16394 return ret;
16395};
16396
16397/**
16398 * Array#forEach shim.
16399 */
16400
16401var forEach = typeof Array.prototype.forEach === 'function'
16402 ? function(arr, fn) { return arr.forEach(fn); }
16403 : function(arr, fn) {
16404 for (var i = 0; i < arr.length; i++) fn(arr[i]);
16405 };
16406
16407/**
16408 * Array#reduce shim.
16409 */
16410
16411var reduce = function(arr, fn, initial) {
16412 if (typeof arr.reduce === 'function') return arr.reduce(fn, initial);
16413 var res = initial;
16414 for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]);
16415 return res;
16416};
16417
16418/**
16419 * Cache non-integer test regexp.
16420 */
16421
16422var isint = /^[0-9]+$/;
16423
16424function promote(parent, key) {
16425 if (parent[key].length == 0) return parent[key] = {}
16426 var t = {};
16427 for (var i in parent[key]) {
16428 if (hasOwnProperty.call(parent[key], i)) {
16429 t[i] = parent[key][i];
16430 }
16431 }
16432 parent[key] = t;
16433 return t;
16434}
16435
16436function parse(parts, parent, key, val) {
16437 var part = parts.shift();
16438
16439 // illegal
16440 if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return;
16441
16442 // end
16443 if (!part) {
16444 if (isArray(parent[key])) {
16445 parent[key].push(val);
16446 } else if ('object' == typeof parent[key]) {
16447 parent[key] = val;
16448 } else if ('undefined' == typeof parent[key]) {
16449 parent[key] = val;
16450 } else {
16451 parent[key] = [parent[key], val];
16452 }
16453 // array
16454 } else {
16455 var obj = parent[key] = parent[key] || [];
16456 if (']' == part) {
16457 if (isArray(obj)) {
16458 if ('' != val) obj.push(val);
16459 } else if ('object' == typeof obj) {
16460 obj[objectKeys(obj).length] = val;
16461 } else {
16462 obj = parent[key] = [parent[key], val];
16463 }
16464 // prop
16465 } else if (~indexOf(part, ']')) {
16466 part = part.substr(0, part.length - 1);
16467 if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
16468 parse(parts, obj, part, val);
16469 // key
16470 } else {
16471 if (!isint.test(part) && isArray(obj)) obj = promote(parent, key);
16472 parse(parts, obj, part, val);
16473 }
16474 }
16475}
16476
16477/**
16478 * Merge parent key/val pair.
16479 */
16480
16481function merge(parent, key, val){
16482 if (~indexOf(key, ']')) {
16483 var parts = key.split('[')
16484 , len = parts.length
16485 , last = len - 1;
16486 parse(parts, parent, 'base', val);
16487 // optimize
16488 } else {
16489 if (!isint.test(key) && isArray(parent.base)) {
16490 var t = {};
16491 for (var k in parent.base) t[k] = parent.base[k];
16492 parent.base = t;
16493 }
16494 set(parent.base, key, val);
16495 }
16496
16497 return parent;
16498}
16499
16500/**
16501 * Compact sparse arrays.
16502 */
16503
16504function compact(obj) {
16505 if ('object' != typeof obj) return obj;
16506
16507 if (isArray(obj)) {
16508 var ret = [];
16509
16510 for (var i in obj) {
16511 if (hasOwnProperty.call(obj, i)) {
16512 ret.push(obj[i]);
16513 }
16514 }
16515
16516 return ret;
16517 }
16518
16519 for (var key in obj) {
16520 obj[key] = compact(obj[key]);
16521 }
16522
16523 return obj;
16524}
16525
16526/**
16527 * Parse the given obj.
16528 */
16529
16530function parseObject(obj){
16531 var ret = { base: {} };
16532
16533 forEach(objectKeys(obj), function(name){
16534 merge(ret, name, obj[name]);
16535 });
16536
16537 return compact(ret.base);
16538}
16539
16540/**
16541 * Parse the given str.
16542 */
16543
16544function parseString(str){
16545 var ret = reduce(String(str).split('&'), function(ret, pair){
16546 var eql = indexOf(pair, '=')
16547 , brace = lastBraceInKey(pair)
16548 , key = pair.substr(0, brace || eql)
16549 , val = pair.substr(brace || eql, pair.length)
16550 , val = val.substr(indexOf(val, '=') + 1, val.length);
16551
16552 // ?foo
16553 if ('' == key) key = pair, val = '';
16554 if ('' == key) return ret;
16555
16556 return merge(ret, decode(key), decode(val));
16557 }, { base: {} }).base;
16558
16559 return compact(ret);
16560}
16561
16562/**
16563 * Parse the given query `str` or `obj`, returning an object.
16564 *
16565 * @param {String} str | {Object} obj
16566 * @return {Object}
16567 * @api public
16568 */
16569
16570exports.parse = function(str){
16571 if (null == str || '' == str) return {};
16572 return 'object' == typeof str
16573 ? parseObject(str)
16574 : parseString(str);
16575};
16576
16577/**
16578 * Turn the given `obj` into a query string
16579 *
16580 * @param {Object} obj
16581 * @return {String}
16582 * @api public
16583 */
16584
16585var stringify = exports.stringify = function(obj, prefix) {
16586 if (isArray(obj)) {
16587 return stringifyArray(obj, prefix);
16588 } else if ('[object Object]' == toString.call(obj)) {
16589 return stringifyObject(obj, prefix);
16590 } else if ('string' == typeof obj) {
16591 return stringifyString(obj, prefix);
16592 } else {
16593 return prefix + '=' + encodeURIComponent(String(obj));
16594 }
16595};
16596
16597/**
16598 * Stringify the given `str`.
16599 *
16600 * @param {String} str
16601 * @param {String} prefix
16602 * @return {String}
16603 * @api private
16604 */
16605
16606function stringifyString(str, prefix) {
16607 if (!prefix) throw new TypeError('stringify expects an object');
16608 return prefix + '=' + encodeURIComponent(str);
16609}
16610
16611/**
16612 * Stringify the given `arr`.
16613 *
16614 * @param {Array} arr
16615 * @param {String} prefix
16616 * @return {String}
16617 * @api private
16618 */
16619
16620function stringifyArray(arr, prefix) {
16621 var ret = [];
16622 if (!prefix) throw new TypeError('stringify expects an object');
16623 for (var i = 0; i < arr.length; i++) {
16624 ret.push(stringify(arr[i], prefix + '[' + i + ']'));
16625 }
16626 return ret.join('&');
16627}
16628
16629/**
16630 * Stringify the given `obj`.
16631 *
16632 * @param {Object} obj
16633 * @param {String} prefix
16634 * @return {String}
16635 * @api private
16636 */
16637
16638function stringifyObject(obj, prefix) {
16639 var ret = []
16640 , keys = objectKeys(obj)
16641 , key;
16642
16643 for (var i = 0, len = keys.length; i < len; ++i) {
16644 key = keys[i];
16645 if ('' == key) continue;
16646 if (null == obj[key]) {
16647 ret.push(encodeURIComponent(key) + '=');
16648 } else {
16649 ret.push(stringify(obj[key], prefix
16650 ? prefix + '[' + encodeURIComponent(key) + ']'
16651 : encodeURIComponent(key)));
16652 }
16653 }
16654
16655 return ret.join('&');
16656}
16657
16658/**
16659 * Set `obj`'s `key` to `val` respecting
16660 * the weird and wonderful syntax of a qs,
16661 * where "foo=bar&foo=baz" becomes an array.
16662 *
16663 * @param {Object} obj
16664 * @param {String} key
16665 * @param {String} val
16666 * @api private
16667 */
16668
16669function set(obj, key, val) {
16670 var v = obj[key];
16671 if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return;
16672 if (undefined === v) {
16673 obj[key] = val;
16674 } else if (isArray(v)) {
16675 v.push(val);
16676 } else {
16677 obj[key] = [v, val];
16678 }
16679}
16680
16681/**
16682 * Locate last brace in `str` within the key.
16683 *
16684 * @param {String} str
16685 * @return {Number}
16686 * @api private
16687 */
16688
16689function lastBraceInKey(str) {
16690 var len = str.length
16691 , brace
16692 , c;
16693 for (var i = 0; i < len; ++i) {
16694 c = str[i];
16695 if (']' == c) brace = false;
16696 if ('[' == c) brace = true;
16697 if ('=' == c && !brace) return i;
16698 }
16699}
16700
16701/**
16702 * Decode `str`.
16703 *
16704 * @param {String} str
16705 * @return {String}
16706 * @api private
16707 */
16708
16709function decode(str) {
16710 try {
16711 return decodeURIComponent(str.replace(/\+/g, ' '));
16712 } catch (err) {
16713 return str;
16714 }
16715}
16716
16717},{}],65:[function(require,module,exports){
16718(function (process,Buffer){
16719var optional = require('./lib/optional')
16720 , http = require('http')
16721 , https = optional('https')
16722 , tls = optional('tls')
16723 , url = require('url')
16724 , util = require('util')
16725 , stream = require('stream')
16726 , qs = require('qs')
16727 , querystring = require('querystring')
16728 , crypto = require('crypto')
16729
16730 , oauth = optional('oauth-sign')
16731 , hawk = optional('hawk')
16732 , aws = optional('aws-sign')
16733 , httpSignature = optional('http-signature')
16734 , uuid = require('node-uuid')
16735 , mime = require('mime')
16736 , tunnel = optional('tunnel-agent')
16737 , _safeStringify = require('json-stringify-safe')
16738
16739 , ForeverAgent = require('forever-agent')
16740 , FormData = optional('form-data')
16741
16742 , Cookie = optional('tough-cookie')
16743 , CookieJar = Cookie && Cookie.CookieJar
16744 , cookieJar = CookieJar && new CookieJar
16745
16746 , copy = require('./lib/copy')
16747 , debug = require('./lib/debug')
16748 , getSafe = require('./lib/getSafe')
16749 ;
16750
16751function safeStringify (obj) {
16752 var ret
16753 try { ret = JSON.stringify(obj) }
16754 catch (e) { ret = _safeStringify(obj) }
16755 return ret
16756}
16757
16758var globalPool = {}
16759var isUrl = /^https?:/i
16760
16761
16762// Hacky fix for pre-0.4.4 https
16763if (https && !https.Agent) {
16764 https.Agent = function (options) {
16765 http.Agent.call(this, options)
16766 }
16767 util.inherits(https.Agent, http.Agent)
16768 https.Agent.prototype._getConnection = function (host, port, cb) {
16769 var s = tls.connect(port, host, this.options, function () {
16770 // do other checks here?
16771 if (cb) cb()
16772 })
16773 return s
16774 }
16775}
16776
16777function isReadStream (rs) {
16778 if (rs.readable && rs.path && rs.mode) {
16779 return true
16780 }
16781}
16782
16783function toBase64 (str) {
16784 return (new Buffer(str || "", "ascii")).toString("base64")
16785}
16786
16787function md5 (str) {
16788 return crypto.createHash('md5').update(str).digest('hex')
16789}
16790
16791function Request (options) {
16792 stream.Stream.call(this)
16793 this.readable = true
16794 this.writable = true
16795
16796 if (typeof options === 'string') {
16797 options = {uri:options}
16798 }
16799
16800 var reserved = Object.keys(Request.prototype)
16801 for (var i in options) {
16802 if (reserved.indexOf(i) === -1) {
16803 this[i] = options[i]
16804 } else {
16805 if (typeof options[i] === 'function') {
16806 delete options[i]
16807 }
16808 }
16809 }
16810
16811 if (options.method) {
16812 this.explicitMethod = true
16813 }
16814
16815 this.canTunnel = options.tunnel !== false && tunnel;
16816
16817 this.init(options)
16818}
16819util.inherits(Request, stream.Stream)
16820Request.prototype.init = function (options) {
16821 // init() contains all the code to setup the request object.
16822 // the actual outgoing request is not started until start() is called
16823 // this function is called from both the constructor and on redirect.
16824 var self = this
16825 if (!options) options = {}
16826
16827 if (!self.method) self.method = options.method || 'GET'
16828 self.localAddress = options.localAddress
16829
16830 debug(options)
16831 if (!self.pool && self.pool !== false) self.pool = globalPool
16832 self.dests = self.dests || []
16833 self.__isRequestRequest = true
16834
16835 // Protect against double callback
16836 if (!self._callback && self.callback) {
16837 self._callback = self.callback
16838 self.callback = function () {
16839 if (self._callbackCalled) return // Print a warning maybe?
16840 self._callbackCalled = true
16841 self._callback.apply(self, arguments)
16842 }
16843 self.on('error', self.callback.bind())
16844 self.on('complete', self.callback.bind(self, null))
16845 }
16846
16847 if (self.url && !self.uri) {
16848 // People use this property instead all the time so why not just support it.
16849 self.uri = self.url
16850 delete self.url
16851 }
16852
16853 if (!self.uri) {
16854 // this will throw if unhandled but is handleable when in a redirect
16855 return self.emit('error', new Error("options.uri is a required argument"))
16856 } else {
16857 if (typeof self.uri == "string") self.uri = url.parse(self.uri)
16858 }
16859
16860 if (self.strictSSL === false) {
16861 self.rejectUnauthorized = false
16862 }
16863
16864 if (self.proxy) {
16865 if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy)
16866
16867 // do the HTTP CONNECT dance using koichik/node-tunnel
16868 if (http.globalAgent && self.uri.protocol === "https:" && self.canTunnel) {
16869 var tunnelFn = self.proxy.protocol === "http:"
16870 ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
16871
16872 var tunnelOptions = { proxy: { host: self.proxy.hostname
16873 , port: +self.proxy.port
16874 , proxyAuth: self.proxy.auth
16875 , headers: { Host: self.uri.hostname + ':' +
16876 (self.uri.port || self.uri.protocol === 'https:' ? 443 : 80) }}
16877 , rejectUnauthorized: self.rejectUnauthorized
16878 , ca: this.ca }
16879
16880 self.agent = tunnelFn(tunnelOptions)
16881 self.tunnel = true
16882 }
16883 }
16884
16885 if (!self.uri.pathname) {self.uri.pathname = '/'}
16886
16887 if (!self.uri.host) {
16888 // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar
16889 // Detect and reject it as soon as possible
16890 var faultyUri = url.format(self.uri)
16891 var message = 'Invalid URI "' + faultyUri + '"'
16892 if (Object.keys(options).length === 0) {
16893 // No option ? This can be the sign of a redirect
16894 // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
16895 // they should be warned that it can be caused by a redirection (can save some hair)
16896 message += '. This can be caused by a crappy redirection.'
16897 }
16898 self.emit('error', new Error(message))
16899 return // This error was fatal
16900 }
16901
16902 self._redirectsFollowed = self._redirectsFollowed || 0
16903 self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10
16904 self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true
16905 self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false
16906 if (self.followRedirect || self.followAllRedirects)
16907 self.redirects = self.redirects || []
16908
16909 self.headers = self.headers ? copy(self.headers) : {}
16910
16911 self.setHost = false
16912 if (!self.hasHeader('host')) {
16913 self.setHeader('host', self.uri.hostname)
16914 if (self.uri.port) {
16915 if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
16916 !(self.uri.port === 443 && self.uri.protocol === 'https:') )
16917 self.setHeader('host', self.getHeader('host') + (':'+self.uri.port) )
16918 }
16919 self.setHost = true
16920 }
16921
16922 self.jar(self._jar || options.jar)
16923
16924 if (!self.uri.port) {
16925 if (self.uri.protocol == 'http:') {self.uri.port = 80}
16926 else if (self.uri.protocol == 'https:') {self.uri.port = 443}
16927 }
16928
16929 if (self.proxy && !self.tunnel) {
16930 self.port = self.proxy.port
16931 self.host = self.proxy.hostname
16932 } else {
16933 self.port = self.uri.port
16934 self.host = self.uri.hostname
16935 }
16936
16937 self.clientErrorHandler = function (error) {
16938 if (self._aborted) return
16939 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
16940 && self.agent.addRequestNoreuse) {
16941 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
16942 self.start()
16943 self.req.end()
16944 return
16945 }
16946 if (self.timeout && self.timeoutTimer) {
16947 clearTimeout(self.timeoutTimer)
16948 self.timeoutTimer = null
16949 }
16950 self.emit('error', error)
16951 }
16952
16953 self._parserErrorHandler = function (error) {
16954 if (this.res) {
16955 if (this.res.request) {
16956 this.res.request.emit('error', error)
16957 } else {
16958 this.res.emit('error', error)
16959 }
16960 } else {
16961 this._httpMessage.emit('error', error)
16962 }
16963 }
16964
16965 if (options.form) {
16966 self.form(options.form)
16967 }
16968
16969 if (options.qs) self.qs(options.qs)
16970
16971 if (self.uri.path) {
16972 self.path = self.uri.path
16973 } else {
16974 self.path = self.uri.pathname + (self.uri.search || "")
16975 }
16976
16977 if (self.path.length === 0) self.path = '/'
16978
16979
16980 // Auth must happen last in case signing is dependent on other headers
16981 if (options.oauth) {
16982 self.oauth(options.oauth)
16983 }
16984
16985 if (options.aws) {
16986 self.aws(options.aws)
16987 }
16988
16989 if (options.hawk) {
16990 self.hawk(options.hawk)
16991 }
16992
16993 if (options.httpSignature) {
16994 self.httpSignature(options.httpSignature)
16995 }
16996
16997 if (options.auth) {
16998 if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) options.auth.user = options.auth.username
16999 if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) options.auth.pass = options.auth.password
17000
17001 self.auth(
17002 options.auth.user,
17003 options.auth.pass,
17004 options.auth.sendImmediately
17005 )
17006 }
17007
17008 if (self.uri.auth && !self.hasHeader('authorization')) {
17009 var authPieces = self.uri.auth.split(':').map(function(item){ return querystring.unescape(item) })
17010 self.auth(authPieces[0], authPieces.slice(1).join(':'), true)
17011 }
17012 if (self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization') && !self.tunnel) {
17013 self.setHeader('proxy-authorization', "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return querystring.unescape(item)}).join(':')))
17014 }
17015
17016
17017 if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
17018
17019 if (options.json) {
17020 self.json(options.json)
17021 } else if (options.multipart) {
17022 self.boundary = uuid()
17023 self.multipart(options.multipart)
17024 }
17025
17026 if (self.body) {
17027 var length = 0
17028 if (!Buffer.isBuffer(self.body)) {
17029 if (Array.isArray(self.body)) {
17030 for (var i = 0; i < self.body.length; i++) {
17031 length += self.body[i].length
17032 }
17033 } else {
17034 self.body = new Buffer(self.body)
17035 length = self.body.length
17036 }
17037 } else {
17038 length = self.body.length
17039 }
17040 if (length) {
17041 if (!self.hasHeader('content-length')) self.setHeader('content-length', length)
17042 } else {
17043 throw new Error('Argument error, options.body.')
17044 }
17045 }
17046
17047 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
17048 , defaultModules = {'http:':http, 'https:':https}
17049 , httpModules = self.httpModules || {}
17050 ;
17051 self.httpModule = httpModules[protocol] || defaultModules[protocol]
17052
17053 if (!self.httpModule) return this.emit('error', new Error("Invalid protocol"))
17054
17055 if (options.ca) self.ca = options.ca
17056
17057 if (!self.agent) {
17058 if (options.agentOptions) self.agentOptions = options.agentOptions
17059
17060 if (options.agentClass) {
17061 self.agentClass = options.agentClass
17062 } else if (options.forever) {
17063 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
17064 } else {
17065 self.agentClass = self.httpModule.Agent
17066 }
17067 }
17068
17069 if (self.pool === false) {
17070 self.agent = false
17071 } else {
17072 self.agent = self.agent || self.getAgent()
17073 if (self.maxSockets) {
17074 // Don't use our pooling if node has the refactored client
17075 self.agent.maxSockets = self.maxSockets
17076 }
17077 if (self.pool.maxSockets) {
17078 // Don't use our pooling if node has the refactored client
17079 self.agent.maxSockets = self.pool.maxSockets
17080 }
17081 }
17082
17083 self.on('pipe', function (src) {
17084 if (self.ntick && self._started) throw new Error("You cannot pipe to this stream after the outbound request has started.")
17085 self.src = src
17086 if (isReadStream(src)) {
17087 if (!self.hasHeader('content-type')) self.setHeader('content-type', mime.lookup(src.path))
17088 } else {
17089 if (src.headers) {
17090 for (var i in src.headers) {
17091 if (!self.hasHeader(i)) {
17092 self.setHeader(i, src.headers[i])
17093 }
17094 }
17095 }
17096 if (self._json && !self.hasHeader('content-type'))
17097 self.setHeader('content-type', 'application/json')
17098 if (src.method && !self.explicitMethod) {
17099 self.method = src.method
17100 }
17101 }
17102
17103 // self.on('pipe', function () {
17104 // console.error("You have already piped to this stream. Pipeing twice is likely to break the request.")
17105 // })
17106 })
17107
17108 process.nextTick(function () {
17109 if (self._aborted) return
17110
17111 if (self._form) {
17112 self.setHeaders(self._form.getHeaders())
17113 self._form.pipe(self)
17114 }
17115 if (self.body) {
17116 if (Array.isArray(self.body)) {
17117 self.body.forEach(function (part) {
17118 self.write(part)
17119 })
17120 } else {
17121 self.write(self.body)
17122 }
17123 self.end()
17124 } else if (self.requestBodyStream) {
17125 console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.")
17126 self.requestBodyStream.pipe(self)
17127 } else if (!self.src) {
17128 if (self.method !== 'GET' && typeof self.method !== 'undefined') {
17129 self.setHeader('content-length', 0)
17130 }
17131 self.end()
17132 }
17133 self.ntick = true
17134 })
17135}
17136
17137// Must call this when following a redirect from https to http or vice versa
17138// Attempts to keep everything as identical as possible, but update the
17139// httpModule, Tunneling agent, and/or Forever Agent in use.
17140Request.prototype._updateProtocol = function () {
17141 var self = this
17142 var protocol = self.uri.protocol
17143
17144 if (protocol === 'https:') {
17145 // previously was doing http, now doing https
17146 // if it's https, then we might need to tunnel now.
17147 if (self.proxy && self.canTunnel) {
17148 self.tunnel = true
17149 var tunnelFn = self.proxy.protocol === 'http:'
17150 ? tunnel.httpsOverHttp : tunnel.httpsOverHttps
17151 var tunnelOptions = { proxy: { host: self.proxy.hostname
17152 , port: +self.proxy.port
17153 , proxyAuth: self.proxy.auth }
17154 , rejectUnauthorized: self.rejectUnauthorized
17155 , ca: self.ca }
17156 self.agent = tunnelFn(tunnelOptions)
17157 return
17158 }
17159
17160 self.httpModule = https
17161 switch (self.agentClass) {
17162 case ForeverAgent:
17163 self.agentClass = ForeverAgent.SSL
17164 break
17165 case http.Agent:
17166 self.agentClass = https.Agent
17167 break
17168 default:
17169 // nothing we can do. Just hope for the best.
17170 return
17171 }
17172
17173 // if there's an agent, we need to get a new one.
17174 if (self.agent) self.agent = self.getAgent()
17175
17176 } else {
17177 // previously was doing https, now doing http
17178 // stop any tunneling.
17179 if (self.tunnel) self.tunnel = false
17180 self.httpModule = http
17181 switch (self.agentClass) {
17182 case ForeverAgent.SSL:
17183 self.agentClass = ForeverAgent
17184 break
17185 case https.Agent:
17186 self.agentClass = http.Agent
17187 break
17188 default:
17189 // nothing we can do. just hope for the best
17190 return
17191 }
17192
17193 // if there's an agent, then get a new one.
17194 if (self.agent) {
17195 self.agent = null
17196 self.agent = self.getAgent()
17197 }
17198 }
17199}
17200
17201Request.prototype.getAgent = function () {
17202 var Agent = this.agentClass
17203 var options = {}
17204 if (this.agentOptions) {
17205 for (var i in this.agentOptions) {
17206 options[i] = this.agentOptions[i]
17207 }
17208 }
17209 if (this.ca) options.ca = this.ca
17210 if (this.ciphers) options.ciphers = this.ciphers
17211 if (this.secureProtocol) options.secureProtocol = this.secureProtocol
17212 if (typeof this.rejectUnauthorized !== 'undefined') options.rejectUnauthorized = this.rejectUnauthorized
17213
17214 if (this.cert && this.key) {
17215 options.key = this.key
17216 options.cert = this.cert
17217 }
17218
17219 var poolKey = ''
17220
17221 // different types of agents are in different pools
17222 if (Agent !== this.httpModule.Agent) {
17223 poolKey += Agent.name
17224 }
17225
17226 if (!this.httpModule.globalAgent) {
17227 // node 0.4.x
17228 options.host = this.host
17229 options.port = this.port
17230 if (poolKey) poolKey += ':'
17231 poolKey += this.host + ':' + this.port
17232 }
17233
17234 // ca option is only relevant if proxy or destination are https
17235 var proxy = this.proxy
17236 if (typeof proxy === 'string') proxy = url.parse(proxy)
17237 var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
17238 if (isHttps) {
17239 if (options.ca) {
17240 if (poolKey) poolKey += ':'
17241 poolKey += options.ca
17242 }
17243
17244 if (typeof options.rejectUnauthorized !== 'undefined') {
17245 if (poolKey) poolKey += ':'
17246 poolKey += options.rejectUnauthorized
17247 }
17248
17249 if (options.cert)
17250 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
17251
17252 if (options.ciphers) {
17253 if (poolKey) poolKey += ':'
17254 poolKey += options.ciphers
17255 }
17256
17257 if (options.secureProtocol) {
17258 if (poolKey) poolKey += ':'
17259 poolKey += options.secureProtocol
17260 }
17261 }
17262
17263 if (this.pool === globalPool && !poolKey && Object.keys(options).length === 0 && this.httpModule.globalAgent) {
17264 // not doing anything special. Use the globalAgent
17265 return this.httpModule.globalAgent
17266 }
17267
17268 // we're using a stored agent. Make sure it's protocol-specific
17269 poolKey = this.uri.protocol + poolKey
17270
17271 // already generated an agent for this setting
17272 if (this.pool[poolKey]) return this.pool[poolKey]
17273
17274 return this.pool[poolKey] = new Agent(options)
17275}
17276
17277Request.prototype.start = function () {
17278 // start() is called once we are ready to send the outgoing HTTP request.
17279 // this is usually called on the first write(), end() or on nextTick()
17280 var self = this
17281
17282 if (self._aborted) return
17283
17284 self._started = true
17285 self.method = self.method || 'GET'
17286 self.href = self.uri.href
17287
17288 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
17289 self.setHeader('content-length', self.src.stat.size)
17290 }
17291 if (self._aws) {
17292 self.aws(self._aws, true)
17293 }
17294
17295 // We have a method named auth, which is completely different from the http.request
17296 // auth option. If we don't remove it, we're gonna have a bad time.
17297 var reqOptions = copy(self)
17298 delete reqOptions.auth
17299
17300 debug('make request', self.uri.href)
17301 self.req = self.httpModule.request(reqOptions, self.onResponse.bind(self))
17302
17303 if (self.timeout && !self.timeoutTimer) {
17304 self.timeoutTimer = setTimeout(function () {
17305 self.req.abort()
17306 var e = new Error("ETIMEDOUT")
17307 e.code = "ETIMEDOUT"
17308 self.emit("error", e)
17309 }, self.timeout)
17310
17311 // Set additional timeout on socket - in case if remote
17312 // server freeze after sending headers
17313 if (self.req.setTimeout) { // only works on node 0.6+
17314 self.req.setTimeout(self.timeout, function () {
17315 if (self.req) {
17316 self.req.abort()
17317 var e = new Error("ESOCKETTIMEDOUT")
17318 e.code = "ESOCKETTIMEDOUT"
17319 self.emit("error", e)
17320 }
17321 })
17322 }
17323 }
17324
17325 self.req.on('error', self.clientErrorHandler)
17326 self.req.on('drain', function() {
17327 self.emit('drain')
17328 })
17329 self.on('end', function() {
17330 if ( self.req.connection ) self.req.connection.removeListener('error', self._parserErrorHandler)
17331 })
17332 self.emit('request', self.req)
17333}
17334Request.prototype.onResponse = function (response) {
17335 var self = this
17336 debug('onResponse', self.uri.href, response.statusCode, response.headers)
17337 response.on('end', function() {
17338 debug('response end', self.uri.href, response.statusCode, response.headers)
17339 });
17340
17341 if (response.connection.listeners('error').indexOf(self._parserErrorHandler) === -1) {
17342 response.connection.once('error', self._parserErrorHandler)
17343 }
17344 if (self._aborted) {
17345 debug('aborted', self.uri.href)
17346 response.resume()
17347 return
17348 }
17349 if (self._paused) response.pause()
17350 else response.resume()
17351
17352 self.response = response
17353 response.request = self
17354 response.toJSON = toJSON
17355
17356 // XXX This is different on 0.10, because SSL is strict by default
17357 if (self.httpModule === https &&
17358 self.strictSSL &&
17359 !response.client.authorized) {
17360 debug('strict ssl error', self.uri.href)
17361 var sslErr = response.client.authorizationError
17362 self.emit('error', new Error('SSL Error: '+ sslErr))
17363 return
17364 }
17365
17366 if (self.setHost && self.hasHeader('host')) delete self.headers[self.hasHeader('host')]
17367 if (self.timeout && self.timeoutTimer) {
17368 clearTimeout(self.timeoutTimer)
17369 self.timeoutTimer = null
17370 }
17371
17372 var addCookie = function (cookie) {
17373 if (self._jar){
17374 var targetCookieJar = self._jar.setCookie?self._jar:cookieJar;
17375
17376 //set the cookie if it's domain in the href's domain.
17377 targetCookieJar.setCookie(cookie, self.uri.href, function(err){
17378 if (err){
17379 console.warn('set cookie failed,'+ err)
17380 }
17381 })
17382 }
17383
17384 }
17385
17386 if (hasHeader('set-cookie', response.headers) && (!self._disableCookies)) {
17387 var headerName = hasHeader('set-cookie', response.headers)
17388 if (Array.isArray(response.headers[headerName])) response.headers[headerName].forEach(addCookie)
17389 else addCookie(response.headers[headerName])
17390 }
17391
17392 var redirectTo = null
17393 if (response.statusCode >= 300 && response.statusCode < 400 && hasHeader('location', response.headers)) {
17394 var location = response.headers[hasHeader('location', response.headers)]
17395 debug('redirect', location)
17396
17397 if (self.followAllRedirects) {
17398 redirectTo = location
17399 } else if (self.followRedirect) {
17400 switch (self.method) {
17401 case 'PATCH':
17402 case 'PUT':
17403 case 'POST':
17404 case 'DELETE':
17405 // Do not follow redirects
17406 break
17407 default:
17408 redirectTo = location
17409 break
17410 }
17411 }
17412 } else if (response.statusCode == 401 && self._hasAuth && !self._sentAuth) {
17413 var authHeader = response.headers[hasHeader('www-authenticate', response.headers)]
17414 var authVerb = authHeader && authHeader.split(' ')[0]
17415 debug('reauth', authVerb)
17416
17417 switch (authVerb) {
17418 case 'Basic':
17419 self.auth(self._user, self._pass, true)
17420 redirectTo = self.uri
17421 break
17422
17423 case 'Digest':
17424 // TODO: More complete implementation of RFC 2617.
17425 // - check challenge.algorithm
17426 // - support algorithm="MD5-sess"
17427 // - handle challenge.domain
17428 // - support qop="auth-int" only
17429 // - handle Authentication-Info (not necessarily?)
17430 // - check challenge.stale (not necessarily?)
17431 // - increase nc (not necessarily?)
17432 // For reference:
17433 // http://tools.ietf.org/html/rfc2617#section-3
17434 // https://github.com/bagder/curl/blob/master/lib/http_digest.c
17435
17436 var challenge = {}
17437 var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
17438 for (;;) {
17439 var match = re.exec(authHeader)
17440 if (!match) break
17441 challenge[match[1]] = match[2] || match[3];
17442 }
17443
17444 var ha1 = md5(self._user + ':' + challenge.realm + ':' + self._pass)
17445 var ha2 = md5(self.method + ':' + self.uri.path)
17446 var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
17447 var nc = qop && '00000001'
17448 var cnonce = qop && uuid().replace(/-/g, '')
17449 var digestResponse = qop ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
17450 var authValues = {
17451 username: self._user,
17452 realm: challenge.realm,
17453 nonce: challenge.nonce,
17454 uri: self.uri.path,
17455 qop: qop,
17456 response: digestResponse,
17457 nc: nc,
17458 cnonce: cnonce,
17459 algorithm: challenge.algorithm,
17460 opaque: challenge.opaque
17461 }
17462
17463 authHeader = []
17464 for (var k in authValues) {
17465 if (!authValues[k]) {
17466 //ignore
17467 } else if (k === 'qop' || k === 'nc' || k === 'algorithm') {
17468 authHeader.push(k + '=' + authValues[k])
17469 } else {
17470 authHeader.push(k + '="' + authValues[k] + '"')
17471 }
17472 }
17473 authHeader = 'Digest ' + authHeader.join(', ')
17474 self.setHeader('authorization', authHeader)
17475 self._sentAuth = true
17476
17477 redirectTo = self.uri
17478 break
17479 }
17480 }
17481
17482 if (redirectTo) {
17483 debug('redirect to', redirectTo)
17484
17485 // ignore any potential response body. it cannot possibly be useful
17486 // to us at this point.
17487 if (self._paused) response.resume()
17488
17489 if (self._redirectsFollowed >= self.maxRedirects) {
17490 self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop "+self.uri.href))
17491 return
17492 }
17493 self._redirectsFollowed += 1
17494
17495 if (!isUrl.test(redirectTo)) {
17496 redirectTo = url.resolve(self.uri.href, redirectTo)
17497 }
17498
17499 var uriPrev = self.uri
17500 self.uri = url.parse(redirectTo)
17501
17502 // handle the case where we change protocol from https to http or vice versa
17503 if (self.uri.protocol !== uriPrev.protocol) {
17504 self._updateProtocol()
17505 }
17506
17507 self.redirects.push(
17508 { statusCode : response.statusCode
17509 , redirectUri: redirectTo
17510 }
17511 )
17512 if (self.followAllRedirects && response.statusCode != 401) self.method = 'GET'
17513 // self.method = 'GET' // Force all redirects to use GET || commented out fixes #215
17514 delete self.src
17515 delete self.req
17516 delete self.agent
17517 delete self._started
17518 if (response.statusCode != 401) {
17519 // Remove parameters from the previous response, unless this is the second request
17520 // for a server that requires digest authentication.
17521 delete self.body
17522 delete self._form
17523 if (self.headers) {
17524 if (self.hasHeader('host')) delete self.headers[self.hasHeader('host')]
17525 if (self.hasHeader('content-type')) delete self.headers[self.hasHeader('content-type')]
17526 if (self.hasHeader('content-length')) delete self.headers[self.hasHeader('content-length')]
17527 }
17528 }
17529
17530 self.emit('redirect');
17531
17532 self.init()
17533 return // Ignore the rest of the response
17534 } else {
17535 self._redirectsFollowed = self._redirectsFollowed || 0
17536 // Be a good stream and emit end when the response is finished.
17537 // Hack to emit end on close because of a core bug that never fires end
17538 response.on('close', function () {
17539 if (!self._ended) self.response.emit('end')
17540 })
17541
17542 if (self.encoding) {
17543 if (self.dests.length !== 0) {
17544 console.error("Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.")
17545 } else {
17546 response.setEncoding(self.encoding)
17547 }
17548 }
17549
17550 self.emit('response', response)
17551
17552 self.dests.forEach(function (dest) {
17553 self.pipeDest(dest)
17554 })
17555
17556 response.on("data", function (chunk) {
17557 self._destdata = true
17558 self.emit("data", chunk)
17559 })
17560 response.on("end", function (chunk) {
17561 self._ended = true
17562 self.emit("end", chunk)
17563 })
17564 response.on("close", function () {self.emit("close")})
17565
17566 if (self.callback) {
17567 var buffer = []
17568 var bodyLen = 0
17569 self.on("data", function (chunk) {
17570 buffer.push(chunk)
17571 bodyLen += chunk.length
17572 })
17573 self.on("end", function () {
17574 debug('end event', self.uri.href)
17575 if (self._aborted) {
17576 debug('aborted', self.uri.href)
17577 return
17578 }
17579
17580 if (buffer.length && Buffer.isBuffer(buffer[0])) {
17581 debug('has body', self.uri.href, bodyLen)
17582 var body = new Buffer(bodyLen)
17583 var i = 0
17584 buffer.forEach(function (chunk) {
17585 chunk.copy(body, i, 0, chunk.length)
17586 i += chunk.length
17587 })
17588 if (self.encoding === null) {
17589 response.body = body
17590 } else {
17591 response.body = body.toString(self.encoding)
17592 }
17593 } else if (buffer.length) {
17594 // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
17595 // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
17596 if (self.encoding === 'utf8' && buffer[0].length > 0 && buffer[0][0] === "\uFEFF") {
17597 buffer[0] = buffer[0].substring(1)
17598 }
17599 response.body = buffer.join('')
17600 }
17601
17602 if (self._json) {
17603 try {
17604 response.body = JSON.parse(response.body)
17605 } catch (e) {}
17606 }
17607 debug('emitting complete', self.uri.href)
17608 if(response.body == undefined && !self._json) {
17609 response.body = "";
17610 }
17611 self.emit('complete', response, response.body)
17612 })
17613 }
17614 //if no callback
17615 else{
17616 self.on("end", function () {
17617 if (self._aborted) {
17618 debug('aborted', self.uri.href)
17619 return
17620 }
17621 self.emit('complete', response);
17622 });
17623 }
17624 }
17625 debug('finish init function', self.uri.href)
17626}
17627
17628Request.prototype.abort = function () {
17629 this._aborted = true
17630
17631 if (this.req) {
17632 this.req.abort()
17633 }
17634 else if (this.response) {
17635 this.response.abort()
17636 }
17637
17638 this.emit("abort")
17639}
17640
17641Request.prototype.pipeDest = function (dest) {
17642 var response = this.response
17643 // Called after the response is received
17644 if (dest.headers && !dest.headersSent) {
17645 if (hasHeader('content-type', response.headers)) {
17646 var ctname = hasHeader('content-type', response.headers)
17647 if (dest.setHeader) dest.setHeader(ctname, response.headers[ctname])
17648 else dest.headers[ctname] = response.headers[ctname]
17649 }
17650
17651 if (hasHeader('content-length', response.headers)) {
17652 var clname = hasHeader('content-length', response.headers)
17653 if (dest.setHeader) dest.setHeader(clname, response.headers[clname])
17654 else dest.headers[clname] = response.headers[clname]
17655 }
17656 }
17657 if (dest.setHeader && !dest.headersSent) {
17658 for (var i in response.headers) {
17659 dest.setHeader(i, response.headers[i])
17660 }
17661 dest.statusCode = response.statusCode
17662 }
17663 if (this.pipefilter) this.pipefilter(response, dest)
17664}
17665
17666// Composable API
17667Request.prototype.setHeader = function (name, value, clobber) {
17668 if (clobber === undefined) clobber = true
17669 if (clobber || !this.hasHeader(name)) this.headers[name] = value
17670 else this.headers[this.hasHeader(name)] += ',' + value
17671 return this
17672}
17673Request.prototype.setHeaders = function (headers) {
17674 for (var i in headers) {this.setHeader(i, headers[i])}
17675 return this
17676}
17677Request.prototype.hasHeader = function (header, headers) {
17678 var headers = Object.keys(headers || this.headers)
17679 , lheaders = headers.map(function (h) {return h.toLowerCase()})
17680 ;
17681 header = header.toLowerCase()
17682 for (var i=0;i<lheaders.length;i++) {
17683 if (lheaders[i] === header) return headers[i]
17684 }
17685 return false
17686}
17687
17688var hasHeader = Request.prototype.hasHeader
17689
17690Request.prototype.qs = function (q, clobber) {
17691 var base
17692 if (!clobber && this.uri.query) base = qs.parse(this.uri.query)
17693 else base = {}
17694
17695 for (var i in q) {
17696 base[i] = q[i]
17697 }
17698
17699 if (qs.stringify(base) === ''){
17700 return this
17701 }
17702
17703 this.uri = url.parse(this.uri.href.split('?')[0] + '?' + qs.stringify(base))
17704 this.url = this.uri
17705 this.path = this.uri.path
17706
17707 return this
17708}
17709Request.prototype.form = function (form) {
17710 if (form) {
17711 this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8')
17712 this.body = qs.stringify(form).toString('utf8')
17713 return this
17714 }
17715 // create form-data object
17716 this._form = new FormData()
17717 return this._form
17718}
17719Request.prototype.multipart = function (multipart) {
17720 var self = this
17721 self.body = []
17722
17723 if (!self.hasHeader('content-type')) {
17724 self.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
17725 } else {
17726 var headerName = self.hasHeader('content-type');
17727 self.setHeader(headerName, self.headers[headerName].split(';')[0] + '; boundary=' + self.boundary)
17728 }
17729
17730 if (!multipart.forEach) throw new Error('Argument error, options.multipart.')
17731
17732 if (self.preambleCRLF) {
17733 self.body.push(new Buffer('\r\n'))
17734 }
17735
17736 multipart.forEach(function (part) {
17737 var body = part.body
17738 if(body == null) throw Error('Body attribute missing in multipart.')
17739 delete part.body
17740 var preamble = '--' + self.boundary + '\r\n'
17741 Object.keys(part).forEach(function (key) {
17742 preamble += key + ': ' + part[key] + '\r\n'
17743 })
17744 preamble += '\r\n'
17745 self.body.push(new Buffer(preamble))
17746 self.body.push(new Buffer(body))
17747 self.body.push(new Buffer('\r\n'))
17748 })
17749 self.body.push(new Buffer('--' + self.boundary + '--'))
17750 return self
17751}
17752Request.prototype.json = function (val) {
17753 var self = this
17754
17755 if (!self.hasHeader('accept')) self.setHeader('accept', 'application/json')
17756
17757 this._json = true
17758 if (typeof val === 'boolean') {
17759 if (typeof this.body === 'object') {
17760 this.body = safeStringify(this.body)
17761 self.setHeader('content-type', 'application/json')
17762 }
17763 } else {
17764 this.body = safeStringify(val)
17765 self.setHeader('content-type', 'application/json')
17766 }
17767 return this
17768}
17769Request.prototype.getHeader = function (name, headers) {
17770 var result, re, match
17771 if (!headers) headers = this.headers
17772 Object.keys(headers).forEach(function (key) {
17773 re = new RegExp(name, 'i')
17774 match = key.match(re)
17775 if (match) result = headers[key]
17776 })
17777 return result
17778}
17779var getHeader = Request.prototype.getHeader
17780
17781Request.prototype.auth = function (user, pass, sendImmediately) {
17782 if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
17783 throw new Error('auth() received invalid user or password')
17784 }
17785 this._user = user
17786 this._pass = pass
17787 this._hasAuth = true
17788 var header = typeof pass !== 'undefined' ? user + ':' + pass : user
17789 if (sendImmediately || typeof sendImmediately == 'undefined') {
17790 this.setHeader('authorization', 'Basic ' + toBase64(header))
17791 this._sentAuth = true
17792 }
17793 return this
17794}
17795Request.prototype.aws = function (opts, now) {
17796 if (!now) {
17797 this._aws = opts
17798 return this
17799 }
17800 var date = new Date()
17801 this.setHeader('date', date.toUTCString())
17802 var auth =
17803 { key: opts.key
17804 , secret: opts.secret
17805 , verb: this.method.toUpperCase()
17806 , date: date
17807 , contentType: this.getHeader('content-type') || ''
17808 , md5: this.getHeader('content-md5') || ''
17809 , amazonHeaders: aws.canonicalizeHeaders(this.headers)
17810 }
17811 if (opts.bucket && this.path) {
17812 auth.resource = '/' + opts.bucket + this.path
17813 } else if (opts.bucket && !this.path) {
17814 auth.resource = '/' + opts.bucket
17815 } else if (!opts.bucket && this.path) {
17816 auth.resource = this.path
17817 } else if (!opts.bucket && !this.path) {
17818 auth.resource = '/'
17819 }
17820 auth.resource = aws.canonicalizeResource(auth.resource)
17821 this.setHeader('authorization', aws.authorization(auth))
17822
17823 return this
17824}
17825Request.prototype.httpSignature = function (opts) {
17826 var req = this
17827 httpSignature.signRequest({
17828 getHeader: function(header) {
17829 return getHeader(header, req.headers)
17830 },
17831 setHeader: function(header, value) {
17832 req.setHeader(header, value)
17833 },
17834 method: this.method,
17835 path: this.path
17836 }, opts)
17837 debug('httpSignature authorization', this.getHeader('authorization'))
17838
17839 return this
17840}
17841
17842Request.prototype.hawk = function (opts) {
17843 this.setHeader('Authorization', hawk.client.header(this.uri, this.method, opts).field)
17844}
17845
17846Request.prototype.oauth = function (_oauth) {
17847 var form
17848 if (this.hasHeader('content-type') &&
17849 this.getHeader('content-type').slice(0, 'application/x-www-form-urlencoded'.length) ===
17850 'application/x-www-form-urlencoded'
17851 ) {
17852 form = qs.parse(this.body)
17853 }
17854 if (this.uri.query) {
17855 form = qs.parse(this.uri.query)
17856 }
17857 if (!form) form = {}
17858 var oa = {}
17859 for (var i in form) oa[i] = form[i]
17860 for (var i in _oauth) oa['oauth_'+i] = _oauth[i]
17861 if (!oa.oauth_version) oa.oauth_version = '1.0'
17862 if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
17863 if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '')
17864
17865 oa.oauth_signature_method = 'HMAC-SHA1'
17866
17867 var consumer_secret = oa.oauth_consumer_secret
17868 delete oa.oauth_consumer_secret
17869 var token_secret = oa.oauth_token_secret
17870 delete oa.oauth_token_secret
17871 var timestamp = oa.oauth_timestamp
17872
17873 var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname
17874 var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret)
17875
17876 // oa.oauth_signature = signature
17877 for (var i in form) {
17878 if ( i.slice(0, 'oauth_') in _oauth) {
17879 // skip
17880 } else {
17881 delete oa['oauth_'+i]
17882 if (i !== 'x_auth_mode') delete oa[i]
17883 }
17884 }
17885 oa.oauth_timestamp = timestamp
17886 var authHeader = 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',')
17887 authHeader += ',oauth_signature="' + oauth.rfc3986(signature) + '"'
17888 this.setHeader('Authorization', authHeader)
17889 return this
17890}
17891Request.prototype.jar = function (jar) {
17892 var cookies
17893
17894 if (this._redirectsFollowed === 0) {
17895 this.originalCookieHeader = this.getHeader('cookie')
17896 }
17897
17898 if (!jar) {
17899 // disable cookies
17900 cookies = false
17901 this._disableCookies = true
17902 } else {
17903 var targetCookieJar = (jar && jar.getCookieString)?jar:cookieJar;
17904 var urihref = this.uri.href
17905
17906 //fetch cookie in the Specified host
17907 targetCookieJar.getCookieString(urihref, function(err, hrefCookie){
17908 if (err){
17909 console.warn('get cookieString failed,' +err)
17910 } else {
17911 cookies = hrefCookie
17912 }
17913 })
17914
17915 }
17916
17917 //if need cookie and cookie is not empty
17918 if (cookies && cookies.length) {
17919 if (this.originalCookieHeader) {
17920 // Don't overwrite existing Cookie header
17921 this.setHeader('cookie', this.originalCookieHeader + '; ' + cookies)
17922 } else {
17923 this.setHeader('cookie', cookies)
17924 }
17925 }
17926 this._jar = jar
17927 return this
17928}
17929
17930
17931// Stream API
17932Request.prototype.pipe = function (dest, opts) {
17933 if (this.response) {
17934 if (this._destdata) {
17935 throw new Error("You cannot pipe after data has been emitted from the response.")
17936 } else if (this._ended) {
17937 throw new Error("You cannot pipe after the response has been ended.")
17938 } else {
17939 stream.Stream.prototype.pipe.call(this, dest, opts)
17940 this.pipeDest(dest)
17941 return dest
17942 }
17943 } else {
17944 this.dests.push(dest)
17945 stream.Stream.prototype.pipe.call(this, dest, opts)
17946 return dest
17947 }
17948}
17949Request.prototype.write = function () {
17950 if (!this._started) this.start()
17951 return this.req.write.apply(this.req, arguments)
17952}
17953Request.prototype.end = function (chunk) {
17954 if (chunk) this.write(chunk)
17955 if (!this._started) this.start()
17956 this.req.end()
17957}
17958Request.prototype.pause = function () {
17959 if (!this.response) this._paused = true
17960 else this.response.pause.apply(this.response, arguments)
17961}
17962Request.prototype.resume = function () {
17963 if (!this.response) this._paused = false
17964 else this.response.resume.apply(this.response, arguments)
17965}
17966Request.prototype.destroy = function () {
17967 if (!this._ended) this.end()
17968 else if (this.response) this.response.destroy()
17969}
17970
17971function toJSON () {
17972 return getSafe(this, '__' + (((1+Math.random())*0x10000)|0).toString(16))
17973}
17974
17975Request.prototype.toJSON = toJSON
17976
17977
17978module.exports = Request
17979
17980}).call(this,require('_process'),require("buffer").Buffer)
17981},{"./lib/copy":56,"./lib/debug":57,"./lib/getSafe":58,"./lib/optional":59,"_process":31,"buffer":3,"crypto":10,"forever-agent":60,"http":23,"json-stringify-safe":61,"mime":62,"node-uuid":63,"qs":64,"querystring":35,"stream":48,"url":49,"util":51}],66:[function(require,module,exports){
17982/** @license MIT License (c) copyright 2010-2014 original author or authors */
17983/** @author Brian Cavalier */
17984/** @author John Hann */
17985
17986(function(define) { 'use strict';
17987define(function (require) {
17988
17989 var makePromise = require('./makePromise');
17990 var Scheduler = require('./scheduler');
17991 var async = require('./async');
17992
17993 return makePromise({
17994 scheduler: new Scheduler(async)
17995 });
17996
17997});
17998})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
17999
18000},{"./async":69,"./makePromise":79,"./scheduler":80}],67:[function(require,module,exports){
18001/** @license MIT License (c) copyright 2010-2014 original author or authors */
18002/** @author Brian Cavalier */
18003/** @author John Hann */
18004
18005(function(define) { 'use strict';
18006define(function() {
18007 /**
18008 * Circular queue
18009 * @param {number} capacityPow2 power of 2 to which this queue's capacity
18010 * will be set initially. eg when capacityPow2 == 3, queue capacity
18011 * will be 8.
18012 * @constructor
18013 */
18014 function Queue(capacityPow2) {
18015 this.head = this.tail = this.length = 0;
18016 this.buffer = new Array(1 << capacityPow2);
18017 }
18018
18019 Queue.prototype.push = function(x) {
18020 if(this.length === this.buffer.length) {
18021 this._ensureCapacity(this.length * 2);
18022 }
18023
18024 this.buffer[this.tail] = x;
18025 this.tail = (this.tail + 1) & (this.buffer.length - 1);
18026 ++this.length;
18027 return this.length;
18028 };
18029
18030 Queue.prototype.shift = function() {
18031 var x = this.buffer[this.head];
18032 this.buffer[this.head] = void 0;
18033 this.head = (this.head + 1) & (this.buffer.length - 1);
18034 --this.length;
18035 return x;
18036 };
18037
18038 Queue.prototype._ensureCapacity = function(capacity) {
18039 var head = this.head;
18040 var buffer = this.buffer;
18041 var newBuffer = new Array(capacity);
18042 var i = 0;
18043 var len;
18044
18045 if(head === 0) {
18046 len = this.length;
18047 for(; i<len; ++i) {
18048 newBuffer[i] = buffer[i];
18049 }
18050 } else {
18051 capacity = buffer.length;
18052 len = this.tail;
18053 for(; head<capacity; ++i, ++head) {
18054 newBuffer[i] = buffer[head];
18055 }
18056
18057 for(head=0; head<len; ++i, ++head) {
18058 newBuffer[i] = buffer[head];
18059 }
18060 }
18061
18062 this.buffer = newBuffer;
18063 this.head = 0;
18064 this.tail = this.length;
18065 };
18066
18067 return Queue;
18068
18069});
18070}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18071
18072},{}],68:[function(require,module,exports){
18073/** @license MIT License (c) copyright 2010-2014 original author or authors */
18074/** @author Brian Cavalier */
18075/** @author John Hann */
18076
18077(function(define) { 'use strict';
18078define(function() {
18079
18080 /**
18081 * Custom error type for promises rejected by promise.timeout
18082 * @param {string} message
18083 * @constructor
18084 */
18085 function TimeoutError (message) {
18086 Error.call(this);
18087 this.message = message;
18088 this.name = TimeoutError.name;
18089 if (typeof Error.captureStackTrace === 'function') {
18090 Error.captureStackTrace(this, TimeoutError);
18091 }
18092 }
18093
18094 TimeoutError.prototype = Object.create(Error.prototype);
18095 TimeoutError.prototype.constructor = TimeoutError;
18096
18097 return TimeoutError;
18098});
18099}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18100},{}],69:[function(require,module,exports){
18101(function (process){
18102/** @license MIT License (c) copyright 2010-2014 original author or authors */
18103/** @author Brian Cavalier */
18104/** @author John Hann */
18105
18106(function(define) { 'use strict';
18107define(function(require) {
18108
18109 // Sniff "best" async scheduling option
18110 // Prefer process.nextTick or MutationObserver, then check for
18111 // vertx and finally fall back to setTimeout
18112
18113 /*jshint maxcomplexity:6*/
18114 /*global process,document,setTimeout,MutationObserver,WebKitMutationObserver*/
18115 var nextTick, MutationObs;
18116
18117 if (typeof process !== 'undefined' && process !== null &&
18118 typeof process.nextTick === 'function') {
18119 nextTick = function(f) {
18120 process.nextTick(f);
18121 };
18122
18123 } else if (MutationObs =
18124 (typeof MutationObserver === 'function' && MutationObserver) ||
18125 (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver)) {
18126 nextTick = (function (document, MutationObserver) {
18127 var scheduled;
18128 var el = document.createElement('div');
18129 var o = new MutationObserver(run);
18130 o.observe(el, { attributes: true });
18131
18132 function run() {
18133 var f = scheduled;
18134 scheduled = void 0;
18135 f();
18136 }
18137
18138 return function (f) {
18139 scheduled = f;
18140 el.setAttribute('class', 'x');
18141 };
18142 }(document, MutationObs));
18143
18144 } else {
18145 nextTick = (function(cjsRequire) {
18146 try {
18147 // vert.x 1.x || 2.x
18148 return cjsRequire('vertx').runOnLoop || cjsRequire('vertx').runOnContext;
18149 } catch (ignore) {}
18150
18151 // capture setTimeout to avoid being caught by fake timers
18152 // used in time based tests
18153 var capturedSetTimeout = setTimeout;
18154 return function (t) {
18155 capturedSetTimeout(t, 0);
18156 };
18157 }(require));
18158 }
18159
18160 return nextTick;
18161});
18162}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18163
18164}).call(this,require('_process'))
18165},{"_process":31}],70:[function(require,module,exports){
18166/** @license MIT License (c) copyright 2010-2014 original author or authors */
18167/** @author Brian Cavalier */
18168/** @author John Hann */
18169
18170(function(define) { 'use strict';
18171define(function() {
18172
18173 return function array(Promise) {
18174
18175 var arrayMap = Array.prototype.map;
18176 var arrayReduce = Array.prototype.reduce;
18177 var arrayReduceRight = Array.prototype.reduceRight;
18178 var arrayForEach = Array.prototype.forEach;
18179
18180 var toPromise = Promise.resolve;
18181 var all = Promise.all;
18182
18183 // Additional array combinators
18184
18185 Promise.any = any;
18186 Promise.some = some;
18187 Promise.settle = settle;
18188
18189 Promise.map = map;
18190 Promise.reduce = reduce;
18191 Promise.reduceRight = reduceRight;
18192
18193 /**
18194 * When this promise fulfills with an array, do
18195 * onFulfilled.apply(void 0, array)
18196 * @param (function) onFulfilled function to apply
18197 * @returns {Promise} promise for the result of applying onFulfilled
18198 */
18199 Promise.prototype.spread = function(onFulfilled) {
18200 return this.then(all).then(function(array) {
18201 return onFulfilled.apply(void 0, array);
18202 });
18203 };
18204
18205 return Promise;
18206
18207 /**
18208 * One-winner competitive race.
18209 * Return a promise that will fulfill when one of the promises
18210 * in the input array fulfills, or will reject when all promises
18211 * have rejected.
18212 * @param {array} promises
18213 * @returns {Promise} promise for the first fulfilled value
18214 */
18215 function any(promises) {
18216 return new Promise(function(resolve, reject) {
18217 var pending = 0;
18218 var errors = [];
18219
18220 arrayForEach.call(promises, function(p) {
18221 ++pending;
18222 toPromise(p).then(resolve, handleReject);
18223 });
18224
18225 if(pending === 0) {
18226 resolve();
18227 }
18228
18229 function handleReject(e) {
18230 errors.push(e);
18231 if(--pending === 0) {
18232 reject(errors);
18233 }
18234 }
18235 });
18236 }
18237
18238 /**
18239 * N-winner competitive race
18240 * Return a promise that will fulfill when n input promises have
18241 * fulfilled, or will reject when it becomes impossible for n
18242 * input promises to fulfill (ie when promises.length - n + 1
18243 * have rejected)
18244 * @param {array} promises
18245 * @param {number} n
18246 * @returns {Promise} promise for the earliest n fulfillment values
18247 *
18248 * @deprecated
18249 */
18250 function some(promises, n) {
18251 return new Promise(function(resolve, reject, notify) {
18252 var nFulfill = 0;
18253 var nReject;
18254 var results = [];
18255 var errors = [];
18256
18257 arrayForEach.call(promises, function(p) {
18258 ++nFulfill;
18259 toPromise(p).then(handleResolve, handleReject, notify);
18260 });
18261
18262 n = Math.max(n, 0);
18263 nReject = (nFulfill - n + 1);
18264 nFulfill = Math.min(n, nFulfill);
18265
18266 if(nFulfill === 0) {
18267 resolve(results);
18268 return;
18269 }
18270
18271 function handleResolve(x) {
18272 if(nFulfill > 0) {
18273 --nFulfill;
18274 results.push(x);
18275
18276 if(nFulfill === 0) {
18277 resolve(results);
18278 }
18279 }
18280 }
18281
18282 function handleReject(e) {
18283 if(nReject > 0) {
18284 --nReject;
18285 errors.push(e);
18286
18287 if(nReject === 0) {
18288 reject(errors);
18289 }
18290 }
18291 }
18292 });
18293 }
18294
18295 /**
18296 * Apply f to the value of each promise in a list of promises
18297 * and return a new list containing the results.
18298 * @param {array} promises
18299 * @param {function} f
18300 * @param {function} fallback
18301 * @returns {Promise}
18302 */
18303 function map(promises, f, fallback) {
18304 return all(arrayMap.call(promises, function(x) {
18305 return toPromise(x).then(f, fallback);
18306 }));
18307 }
18308
18309 /**
18310 * Return a promise that will always fulfill with an array containing
18311 * the outcome states of all input promises. The returned promise
18312 * will never reject.
18313 * @param {array} promises
18314 * @returns {Promise}
18315 */
18316 function settle(promises) {
18317 return all(arrayMap.call(promises, function(p) {
18318 p = toPromise(p);
18319 return p.then(inspect, inspect);
18320
18321 function inspect() {
18322 return p.inspect();
18323 }
18324 }));
18325 }
18326
18327 function reduce(promises, f) {
18328 return arguments.length > 2
18329 ? arrayReduce.call(promises, reducer, arguments[2])
18330 : arrayReduce.call(promises, reducer);
18331
18332 function reducer(result, x, i) {
18333 return toPromise(result).then(function(r) {
18334 return toPromise(x).then(function(x) {
18335 return f(r, x, i);
18336 });
18337 });
18338 }
18339 }
18340
18341 function reduceRight(promises, f) {
18342 return arguments.length > 2
18343 ? arrayReduceRight.call(promises, reducer, arguments[2])
18344 : arrayReduceRight.call(promises, reducer);
18345
18346 function reducer(result, x, i) {
18347 return toPromise(result).then(function(r) {
18348 return toPromise(x).then(function(x) {
18349 return f(r, x, i);
18350 });
18351 });
18352 }
18353 }
18354 };
18355
18356
18357});
18358}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18359
18360},{}],71:[function(require,module,exports){
18361/** @license MIT License (c) copyright 2010-2014 original author or authors */
18362/** @author Brian Cavalier */
18363/** @author John Hann */
18364
18365(function(define) { 'use strict';
18366define(function() {
18367
18368 return function flow(Promise) {
18369
18370 var reject = Promise.reject;
18371 var origCatch = Promise.prototype['catch'];
18372
18373 /**
18374 * Handle the ultimate fulfillment value or rejection reason, and assume
18375 * responsibility for all errors. If an error propagates out of result
18376 * or handleFatalError, it will be rethrown to the host, resulting in a
18377 * loud stack track on most platforms and a crash on some.
18378 * @param {function?} onResult
18379 * @param {function?} onError
18380 * @returns {undefined}
18381 */
18382 Promise.prototype.done = function(onResult, onError) {
18383 var h = this._handler;
18384 h.when({ resolve: this._maybeFatal, notify: noop, context: this,
18385 receiver: h.receiver, fulfilled: onResult, rejected: onError,
18386 progress: void 0 });
18387 };
18388
18389 /**
18390 * Add Error-type and predicate matching to catch. Examples:
18391 * promise.catch(TypeError, handleTypeError)
18392 * .catch(predicate, handleMatchedErrors)
18393 * .catch(handleRemainingErrors)
18394 * @param onRejected
18395 * @returns {*}
18396 */
18397 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
18398 if (arguments.length === 1) {
18399 return origCatch.call(this, onRejected);
18400 } else {
18401 if(typeof onRejected !== 'function') {
18402 return this.ensure(rejectInvalidPredicate);
18403 }
18404
18405 return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
18406 }
18407 };
18408
18409 /**
18410 * Wraps the provided catch handler, so that it will only be called
18411 * if the predicate evaluates truthy
18412 * @param {?function} handler
18413 * @param {function} predicate
18414 * @returns {function} conditional catch handler
18415 */
18416 function createCatchFilter(handler, predicate) {
18417 return function(e) {
18418 return evaluatePredicate(e, predicate)
18419 ? handler.call(this, e)
18420 : reject(e);
18421 };
18422 }
18423
18424 /**
18425 * Ensures that onFulfilledOrRejected will be called regardless of whether
18426 * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
18427 * receive the promises' value or reason. Any returned value will be disregarded.
18428 * onFulfilledOrRejected may throw or return a rejected promise to signal
18429 * an additional error.
18430 * @param {function} handler handler to be called regardless of
18431 * fulfillment or rejection
18432 * @returns {Promise}
18433 */
18434 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
18435 if(typeof handler !== 'function') {
18436 // Optimization: result will not change, return same promise
18437 return this;
18438 }
18439
18440 handler = isolate(handler, this);
18441 return this.then(handler, handler);
18442 };
18443
18444 /**
18445 * Recover from a failure by returning a defaultValue. If defaultValue
18446 * is a promise, it's fulfillment value will be used. If defaultValue is
18447 * a promise that rejects, the returned promise will reject with the
18448 * same reason.
18449 * @param {*} defaultValue
18450 * @returns {Promise} new promise
18451 */
18452 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
18453 return this.then(void 0, function() {
18454 return defaultValue;
18455 });
18456 };
18457
18458 /**
18459 * Shortcut for .then(function() { return value; })
18460 * @param {*} value
18461 * @return {Promise} a promise that:
18462 * - is fulfilled if value is not a promise, or
18463 * - if value is a promise, will fulfill with its value, or reject
18464 * with its reason.
18465 */
18466 Promise.prototype['yield'] = function(value) {
18467 return this.then(function() {
18468 return value;
18469 });
18470 };
18471
18472 /**
18473 * Runs a side effect when this promise fulfills, without changing the
18474 * fulfillment value.
18475 * @param {function} onFulfilledSideEffect
18476 * @returns {Promise}
18477 */
18478 Promise.prototype.tap = function(onFulfilledSideEffect) {
18479 return this.then(onFulfilledSideEffect)['yield'](this);
18480 };
18481
18482 return Promise;
18483 };
18484
18485 function rejectInvalidPredicate() {
18486 throw new TypeError('catch predicate must be a function');
18487 }
18488
18489 function evaluatePredicate(e, predicate) {
18490 return isError(predicate) ? e instanceof predicate : predicate(e);
18491 }
18492
18493 function isError(predicate) {
18494 return predicate === Error
18495 || (predicate != null && predicate.prototype instanceof Error);
18496 }
18497
18498 // prevent argument passing to f and ignore return value
18499 function isolate(f, x) {
18500 return function() {
18501 f.call(this);
18502 return x;
18503 };
18504 }
18505
18506 function noop() {}
18507
18508});
18509}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18510
18511},{}],72:[function(require,module,exports){
18512/** @license MIT License (c) copyright 2010-2014 original author or authors */
18513/** @author Brian Cavalier */
18514/** @author John Hann */
18515/** @author Jeff Escalante */
18516
18517(function(define) { 'use strict';
18518define(function() {
18519
18520 return function fold(Promise) {
18521
18522 Promise.prototype.fold = function(fn, arg) {
18523 var promise = this._beget();
18524 this._handler.fold(promise._handler, fn, arg);
18525 return promise;
18526 };
18527
18528 return Promise;
18529 };
18530
18531});
18532}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18533
18534},{}],73:[function(require,module,exports){
18535/** @license MIT License (c) copyright 2010-2014 original author or authors */
18536/** @author Brian Cavalier */
18537/** @author John Hann */
18538
18539(function(define) { 'use strict';
18540define(function() {
18541
18542 return function inspect(Promise) {
18543
18544 Promise.prototype.inspect = function() {
18545 return this._handler.inspect();
18546 };
18547
18548 return Promise;
18549 };
18550
18551});
18552}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18553
18554},{}],74:[function(require,module,exports){
18555/** @license MIT License (c) copyright 2010-2014 original author or authors */
18556/** @author Brian Cavalier */
18557/** @author John Hann */
18558
18559(function(define) { 'use strict';
18560define(function() {
18561
18562 return function generate(Promise) {
18563
18564 var resolve = Promise.resolve;
18565
18566 Promise.iterate = iterate;
18567 Promise.unfold = unfold;
18568
18569 return Promise;
18570
18571 /**
18572 * Generate a (potentially infinite) stream of promised values:
18573 * x, f(x), f(f(x)), etc. until condition(x) returns true
18574 * @param {function} f function to generate a new x from the previous x
18575 * @param {function} condition function that, given the current x, returns
18576 * truthy when the iterate should stop
18577 * @param {function} handler function to handle the value produced by f
18578 * @param {*|Promise} x starting value, may be a promise
18579 * @return {Promise} the result of the last call to f before
18580 * condition returns true
18581 */
18582 function iterate(f, condition, handler, x) {
18583 return unfold(function(x) {
18584 return [x, f(x)];
18585 }, condition, handler, x);
18586 }
18587
18588 /**
18589 * Generate a (potentially infinite) stream of promised values
18590 * by applying handler(generator(seed)) iteratively until
18591 * condition(seed) returns true.
18592 * @param {function} unspool function that generates a [value, newSeed]
18593 * given a seed.
18594 * @param {function} condition function that, given the current seed, returns
18595 * truthy when the unfold should stop
18596 * @param {function} handler function to handle the value produced by unspool
18597 * @param x {*|Promise} starting value, may be a promise
18598 * @return {Promise} the result of the last value produced by unspool before
18599 * condition returns true
18600 */
18601 function unfold(unspool, condition, handler, x) {
18602 return resolve(x).then(function(seed) {
18603 return resolve(condition(seed)).then(function(done) {
18604 return done ? seed : resolve(unspool(seed)).spread(next);
18605 });
18606 });
18607
18608 function next(item, newSeed) {
18609 return resolve(handler(item)).then(function() {
18610 return unfold(unspool, condition, handler, newSeed);
18611 });
18612 }
18613 }
18614 };
18615
18616});
18617}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18618
18619},{}],75:[function(require,module,exports){
18620/** @license MIT License (c) copyright 2010-2014 original author or authors */
18621/** @author Brian Cavalier */
18622/** @author John Hann */
18623
18624(function(define) { 'use strict';
18625define(function() {
18626
18627 return function progress(Promise) {
18628
18629 /**
18630 * Register a progress handler for this promise
18631 * @param {function} onProgress
18632 * @returns {Promise}
18633 */
18634 Promise.prototype.progress = function(onProgress) {
18635 return this.then(void 0, void 0, onProgress);
18636 };
18637
18638 return Promise;
18639 };
18640
18641});
18642}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18643
18644},{}],76:[function(require,module,exports){
18645/** @license MIT License (c) copyright 2010-2014 original author or authors */
18646/** @author Brian Cavalier */
18647/** @author John Hann */
18648
18649(function(define) { 'use strict';
18650define(function(require) {
18651
18652 var timer = require('../timer');
18653 var TimeoutError = require('../TimeoutError');
18654
18655 return function timed(Promise) {
18656 /**
18657 * Return a new promise whose fulfillment value is revealed only
18658 * after ms milliseconds
18659 * @param {number} ms milliseconds
18660 * @returns {Promise}
18661 */
18662 Promise.prototype.delay = function(ms) {
18663 var p = this._beget();
18664 var h = p._handler;
18665
18666 this._handler.map(function delay(x) {
18667 timer.set(function() { h.resolve(x); }, ms);
18668 }, h);
18669
18670 return p;
18671 };
18672
18673 /**
18674 * Return a new promise that rejects after ms milliseconds unless
18675 * this promise fulfills earlier, in which case the returned promise
18676 * fulfills with the same value.
18677 * @param {number} ms milliseconds
18678 * @param {Error|*=} reason optional rejection reason to use, defaults
18679 * to an Error if not provided
18680 * @returns {Promise}
18681 */
18682 Promise.prototype.timeout = function(ms, reason) {
18683 var hasReason = arguments.length > 1;
18684 var p = this._beget();
18685 var h = p._handler;
18686
18687 var t = timer.set(onTimeout, ms);
18688
18689 this._handler.chain(h,
18690 function onFulfill(x) {
18691 timer.clear(t);
18692 this.resolve(x); // this = p._handler
18693 },
18694 function onReject(x) {
18695 timer.clear(t);
18696 this.reject(x); // this = p._handler
18697 },
18698 h.notify);
18699
18700 return p;
18701
18702 function onTimeout() {
18703 h.reject(hasReason
18704 ? reason : new TimeoutError('timed out after ' + ms + 'ms'));
18705 }
18706 };
18707
18708 return Promise;
18709 };
18710
18711});
18712}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18713
18714},{"../TimeoutError":68,"../timer":81}],77:[function(require,module,exports){
18715/** @license MIT License (c) copyright 2010-2014 original author or authors */
18716/** @author Brian Cavalier */
18717/** @author John Hann */
18718
18719(function(define) { 'use strict';
18720define(function(require) {
18721
18722 var async = require('../async');
18723
18724 return function unhandledRejection(Promise) {
18725 var logError = (function() {
18726 if(typeof console !== 'undefined') {
18727 if(typeof console.error !== 'undefined') {
18728 return function(e) {
18729 console.error(e);
18730 };
18731 }
18732
18733 return function(e) {
18734 console.log(e);
18735 };
18736 }
18737
18738 return noop;
18739 }());
18740
18741 Promise.onPotentiallyUnhandledRejection = function(rejection) {
18742 logError('Potentially unhandled rejection ' + formatError(rejection.value));
18743 };
18744
18745 Promise.onFatalRejection = function(rejection) {
18746 async(function() {
18747 throw rejection.value;
18748 });
18749 };
18750
18751 return Promise;
18752 };
18753
18754 function formatError(e) {
18755 var s;
18756 if(typeof e === 'object' && e.stack) {
18757 s = e.stack;
18758 } else {
18759 s = String(e);
18760 if(s === '[object Object]' && typeof JSON !== 'undefined') {
18761 s = tryStringify(e, s);
18762 }
18763 }
18764
18765 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
18766 }
18767
18768 function tryStringify(e, defaultValue) {
18769 try {
18770 return JSON.stringify(e);
18771 } catch(e) {
18772 // Ignore. Cannot JSON.stringify e, stick with String(e)
18773 return defaultValue;
18774 }
18775 }
18776
18777 function noop() {}
18778
18779});
18780}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18781
18782},{"../async":69}],78:[function(require,module,exports){
18783/** @license MIT License (c) copyright 2010-2014 original author or authors */
18784/** @author Brian Cavalier */
18785/** @author John Hann */
18786
18787(function(define) { 'use strict';
18788define(function() {
18789
18790 return function addWith(Promise) {
18791 /**
18792 * Returns a promise whose handlers will be called with `this` set to
18793 * the supplied `thisArg`. Subsequent promises derived from the
18794 * returned promise will also have their handlers called with `thisArg`.
18795 * Calling `with` with undefined or no arguments will return a promise
18796 * whose handlers will again be called in the usual Promises/A+ way (no `this`)
18797 * thus safely undoing any previous `with` in the promise chain.
18798 *
18799 * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
18800 * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
18801 *
18802 * @param {object} thisArg `this` value for all handlers attached to
18803 * the returned promise.
18804 * @returns {Promise}
18805 */
18806 Promise.prototype['with'] = Promise.prototype.withThis
18807 = Promise.prototype._bindContext;
18808
18809 return Promise;
18810 };
18811
18812});
18813}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18814
18815
18816},{}],79:[function(require,module,exports){
18817/** @license MIT License (c) copyright 2010-2014 original author or authors */
18818/** @author Brian Cavalier */
18819/** @author John Hann */
18820
18821(function(define) { 'use strict';
18822define(function() {
18823
18824 return function makePromise(environment) {
18825
18826 var tasks = environment.scheduler;
18827
18828 var objectCreate = Object.create ||
18829 function(proto) {
18830 function Child() {}
18831 Child.prototype = proto;
18832 return new Child();
18833 };
18834
18835 /**
18836 * Create a promise whose fate is determined by resolver
18837 * @constructor
18838 * @returns {Promise} promise
18839 * @name Promise
18840 */
18841 function Promise(resolver, handler) {
18842 this._handler = resolver === Handler ? handler : init(resolver);
18843// this._handler = arguments.length === 0
18844// ? foreverPendingHandler : init(resolver);
18845 }
18846
18847 /**
18848 * Run the supplied resolver
18849 * @param resolver
18850 * @returns {makePromise.DeferredHandler}
18851 */
18852 function init(resolver) {
18853 var handler = new DeferredHandler();
18854
18855 try {
18856 resolver(promiseResolve, promiseReject, promiseNotify);
18857 } catch (e) {
18858 promiseReject(e);
18859 }
18860
18861 return handler;
18862
18863 /**
18864 * Transition from pre-resolution state to post-resolution state, notifying
18865 * all listeners of the ultimate fulfillment or rejection
18866 * @param {*} x resolution value
18867 */
18868 function promiseResolve (x) {
18869 handler.resolve(x);
18870 }
18871 /**
18872 * Reject this promise with reason, which will be used verbatim
18873 * @param {Error|*} reason rejection reason, strongly suggested
18874 * to be an Error type
18875 */
18876 function promiseReject (reason) {
18877 handler.reject(reason);
18878 }
18879
18880 /**
18881 * Issue a progress event, notifying all progress listeners
18882 * @param {*} x progress event payload to pass to all listeners
18883 */
18884 function promiseNotify (x) {
18885 handler.notify(x);
18886 }
18887 }
18888
18889 // Creation
18890
18891 Promise.resolve = resolve;
18892 Promise.reject = reject;
18893 Promise.never = never;
18894
18895 Promise._defer = defer;
18896
18897 /**
18898 * Returns a trusted promise. If x is already a trusted promise, it is
18899 * returned, otherwise returns a new trusted Promise which follows x.
18900 * @param {*} x
18901 * @return {Promise} promise
18902 */
18903 function resolve(x) {
18904 return x instanceof Promise ? x
18905 : new Promise(Handler, new AsyncHandler(getHandler(x)));
18906 }
18907
18908 /**
18909 * Return a reject promise with x as its reason (x is used verbatim)
18910 * @param {*} x
18911 * @returns {Promise} rejected promise
18912 */
18913 function reject(x) {
18914 return new Promise(Handler, new AsyncHandler(new RejectedHandler(x)));
18915 }
18916
18917 /**
18918 * Return a promise that remains pending forever
18919 * @returns {Promise} forever-pending promise.
18920 */
18921 function never() {
18922 return foreverPendingPromise; // Should be frozen
18923 }
18924
18925 /**
18926 * Creates an internal {promise, resolver} pair
18927 * @private
18928 * @returns {Promise}
18929 */
18930 function defer() {
18931 return new Promise(Handler, new DeferredHandler());
18932 }
18933
18934 // Transformation and flow control
18935
18936 /**
18937 * Transform this promise's fulfillment value, returning a new Promise
18938 * for the transformed result. If the promise cannot be fulfilled, onRejected
18939 * is called with the reason. onProgress *may* be called with updates toward
18940 * this promise's fulfillment.
18941 * @param {function=} onFulfilled fulfillment handler
18942 * @param {function=} onRejected rejection handler
18943 * @deprecated @param {function=} onProgress progress handler
18944 * @return {Promise} new promise
18945 */
18946 Promise.prototype.then = function(onFulfilled, onRejected) {
18947 var parent = this._handler;
18948
18949 if (typeof onFulfilled !== 'function' && parent.join().state > 0) {
18950 // Short circuit: value will not change, simply share handler
18951 return new Promise(Handler, parent);
18952 }
18953
18954 var p = this._beget();
18955 var child = p._handler;
18956
18957 parent.when({
18958 resolve: child.resolve,
18959 notify: child.notify,
18960 context: child,
18961 receiver: parent.receiver,
18962 fulfilled: onFulfilled,
18963 rejected: onRejected,
18964 progress: arguments.length > 2 ? arguments[2] : void 0
18965 });
18966
18967 return p;
18968 };
18969
18970 /**
18971 * If this promise cannot be fulfilled due to an error, call onRejected to
18972 * handle the error. Shortcut for .then(undefined, onRejected)
18973 * @param {function?} onRejected
18974 * @return {Promise}
18975 */
18976 Promise.prototype['catch'] = function(onRejected) {
18977 return this.then(void 0, onRejected);
18978 };
18979
18980 /**
18981 * Private function to bind a thisArg for this promise's handlers
18982 * @private
18983 * @param {object} thisArg `this` value for all handlers attached to
18984 * the returned promise.
18985 * @returns {Promise}
18986 */
18987 Promise.prototype._bindContext = function(thisArg) {
18988 return new Promise(Handler, new BoundHandler(this._handler, thisArg));
18989 };
18990
18991 /**
18992 * Creates a new, pending promise of the same type as this promise
18993 * @private
18994 * @returns {Promise}
18995 */
18996 Promise.prototype._beget = function() {
18997 var parent = this._handler;
18998 var child = new DeferredHandler(parent.receiver, parent.join().context);
18999 return new this.constructor(Handler, child);
19000 };
19001
19002 /**
19003 * Check if x is a rejected promise, and if so, delegate to handler._fatal
19004 * @private
19005 * @param {*} x
19006 */
19007 Promise.prototype._maybeFatal = function(x) {
19008 if(!maybeThenable(x)) {
19009 return;
19010 }
19011
19012 var handler = getHandler(x);
19013 var context = this._handler.context;
19014 handler.catchError(function() {
19015 this._fatal(context);
19016 }, handler);
19017 };
19018
19019 // Array combinators
19020
19021 Promise.all = all;
19022 Promise.race = race;
19023
19024 /**
19025 * Return a promise that will fulfill when all promises in the
19026 * input array have fulfilled, or will reject when one of the
19027 * promises rejects.
19028 * @param {array} promises array of promises
19029 * @returns {Promise} promise for array of fulfillment values
19030 */
19031 function all(promises) {
19032 /*jshint maxcomplexity:8*/
19033 var resolver = new DeferredHandler();
19034 var pending = promises.length >>> 0;
19035 var results = new Array(pending);
19036
19037 var i, h, x;
19038 for (i = 0; i < promises.length; ++i) {
19039 x = promises[i];
19040
19041 if (x === void 0 && !(i in promises)) {
19042 --pending;
19043 continue;
19044 }
19045
19046 if (maybeThenable(x)) {
19047 h = x instanceof Promise
19048 ? x._handler.join()
19049 : getHandlerUntrusted(x);
19050
19051 if (h.state === 0) {
19052 resolveOne(resolver, results, h, i);
19053 } else if (h.state > 0) {
19054 results[i] = h.value;
19055 --pending;
19056 } else {
19057 h.catchError(resolver.reject, resolver);
19058 break;
19059 }
19060
19061 } else {
19062 results[i] = x;
19063 --pending;
19064 }
19065 }
19066
19067 if(pending === 0) {
19068 resolver.resolve(results);
19069 }
19070
19071 return new Promise(Handler, resolver);
19072 function resolveOne(resolver, results, handler, i) {
19073 handler.map(function(x) {
19074 results[i] = x;
19075 if(--pending === 0) {
19076 this.resolve(results);
19077 }
19078 }, resolver);
19079 }
19080 }
19081
19082 /**
19083 * Fulfill-reject competitive race. Return a promise that will settle
19084 * to the same state as the earliest input promise to settle.
19085 *
19086 * WARNING: The ES6 Promise spec requires that race()ing an empty array
19087 * must return a promise that is pending forever. This implementation
19088 * returns a singleton forever-pending promise, the same singleton that is
19089 * returned by Promise.never(), thus can be checked with ===
19090 *
19091 * @param {array} promises array of promises to race
19092 * @returns {Promise} if input is non-empty, a promise that will settle
19093 * to the same outcome as the earliest input promise to settle. if empty
19094 * is empty, returns a promise that will never settle.
19095 */
19096 function race(promises) {
19097 // Sigh, race([]) is untestable unless we return *something*
19098 // that is recognizable without calling .then() on it.
19099 if(Object(promises) === promises && promises.length === 0) {
19100 return never();
19101 }
19102
19103 var h = new DeferredHandler();
19104 var i, x;
19105 for(i=0; i<promises.length; ++i) {
19106 x = promises[i];
19107 if (x !== void 0 && i in promises) {
19108 getHandler(x).chain(h, h.resolve, h.reject);
19109 }
19110 }
19111 return new Promise(Handler, h);
19112 }
19113
19114 // Promise internals
19115
19116 /**
19117 * Get an appropriate handler for x, without checking for cycles
19118 * @private
19119 * @param {*} x
19120 * @returns {object} handler
19121 */
19122 function getHandler(x) {
19123 if(x instanceof Promise) {
19124 return x._handler.join();
19125 }
19126 return maybeThenable(x) ? getHandlerUntrusted(x) : new FulfilledHandler(x);
19127 }
19128
19129 /**
19130 * Get a handler for potentially untrusted thenable x
19131 * @param {*} x
19132 * @returns {object} handler
19133 */
19134 function getHandlerUntrusted(x) {
19135 try {
19136 var untrustedThen = x.then;
19137 return typeof untrustedThen === 'function'
19138 ? new ThenableHandler(untrustedThen, x)
19139 : new FulfilledHandler(x);
19140 } catch(e) {
19141 return new RejectedHandler(e);
19142 }
19143 }
19144
19145 /**
19146 * Handler for a promise that is pending forever
19147 * @private
19148 * @constructor
19149 */
19150 function Handler() {
19151 this.state = 0;
19152 }
19153
19154 Handler.prototype.when
19155 = Handler.prototype.resolve
19156 = Handler.prototype.reject
19157 = Handler.prototype.notify
19158 = Handler.prototype._fatal
19159 = Handler.prototype._unreport
19160 = Handler.prototype._report
19161 = noop;
19162
19163 Handler.prototype.inspect = toPendingState;
19164
19165 /**
19166 * Recursively collapse handler chain to find the handler
19167 * nearest to the fully resolved value.
19168 * @returns {object} handler nearest the fully resolved value
19169 */
19170 Handler.prototype.join = function() {
19171 var h = this;
19172 while(h.handler !== void 0) {
19173 h = h.handler;
19174 }
19175 return h;
19176 };
19177
19178 Handler.prototype.chain = function(to, fulfilled, rejected, progress) {
19179 this.when({
19180 resolve: noop,
19181 notify: noop,
19182 context: void 0,
19183 receiver: to,
19184 fulfilled: fulfilled,
19185 rejected: rejected,
19186 progress: progress
19187 });
19188 };
19189
19190 Handler.prototype.map = function(f, to) {
19191 this.chain(to, f, to.reject, to.notify);
19192 };
19193
19194 Handler.prototype.catchError = function(f, to) {
19195 this.chain(to, to.resolve, f, to.notify);
19196 };
19197
19198 Handler.prototype.fold = function(to, f, z) {
19199 this.join().map(function(x) {
19200 getHandler(z).map(function(z) {
19201 this.resolve(tryCatchReject2(f, z, x, this.receiver));
19202 }, this);
19203 }, to);
19204 };
19205
19206 /**
19207 * Handler that manages a queue of consumers waiting on a pending promise
19208 * @private
19209 * @constructor
19210 */
19211 function DeferredHandler(receiver, inheritedContext) {
19212 Promise.createContext(this, inheritedContext);
19213
19214 this.consumers = void 0;
19215 this.receiver = receiver;
19216 this.handler = void 0;
19217 this.resolved = false;
19218 this.state = 0;
19219 }
19220
19221 inherit(Handler, DeferredHandler);
19222
19223 DeferredHandler.prototype.inspect = function() {
19224 return this.resolved ? this.join().inspect() : toPendingState();
19225 };
19226
19227 DeferredHandler.prototype.resolve = function(x) {
19228 if(!this.resolved) {
19229 this.become(getHandler(x));
19230 }
19231 };
19232
19233 DeferredHandler.prototype.reject = function(x) {
19234 if(!this.resolved) {
19235 this.become(new RejectedHandler(x));
19236 }
19237 };
19238
19239 DeferredHandler.prototype.join = function() {
19240 if (this.resolved) {
19241 var h = this;
19242 while(h.handler !== void 0) {
19243 h = h.handler;
19244 if(h === this) {
19245 return this.handler = new Cycle();
19246 }
19247 }
19248 return h;
19249 } else {
19250 return this;
19251 }
19252 };
19253
19254 DeferredHandler.prototype.run = function() {
19255 var q = this.consumers;
19256 var handler = this.join();
19257 this.consumers = void 0;
19258
19259 for (var i = 0; i < q.length; ++i) {
19260 handler.when(q[i]);
19261 }
19262 };
19263
19264 DeferredHandler.prototype.become = function(handler) {
19265 this.resolved = true;
19266 this.handler = handler;
19267 if(this.consumers !== void 0) {
19268 tasks.enqueue(this);
19269 }
19270
19271 if(this.context !== void 0) {
19272 handler._report(this.context);
19273 }
19274 };
19275
19276 DeferredHandler.prototype.when = function(continuation) {
19277 if(this.resolved) {
19278 tasks.enqueue(new ContinuationTask(continuation, this.handler));
19279 } else {
19280 if(this.consumers === void 0) {
19281 this.consumers = [continuation];
19282 } else {
19283 this.consumers.push(continuation);
19284 }
19285 }
19286 };
19287
19288 DeferredHandler.prototype.notify = function(x) {
19289 if(!this.resolved) {
19290 tasks.enqueue(new ProgressTask(this, x));
19291 }
19292 };
19293
19294 DeferredHandler.prototype._report = function(context) {
19295 this.resolved && this.handler.join()._report(context);
19296 };
19297
19298 DeferredHandler.prototype._unreport = function() {
19299 this.resolved && this.handler.join()._unreport();
19300 };
19301
19302 DeferredHandler.prototype._fatal = function(context) {
19303 var c = typeof context === 'undefined' ? this.context : context;
19304 this.resolved && this.handler.join()._fatal(c);
19305 };
19306
19307 /**
19308 * Abstract base for handler that delegates to another handler
19309 * @private
19310 * @param {object} handler
19311 * @constructor
19312 */
19313 function DelegateHandler(handler) {
19314 this.handler = handler;
19315 this.state = 0;
19316 }
19317
19318 inherit(Handler, DelegateHandler);
19319
19320 DelegateHandler.prototype.inspect = function() {
19321 return this.join().inspect();
19322 };
19323
19324 DelegateHandler.prototype._report = function(context) {
19325 this.join()._report(context);
19326 };
19327
19328 DelegateHandler.prototype._unreport = function() {
19329 this.join()._unreport();
19330 };
19331
19332 /**
19333 * Wrap another handler and force it into a future stack
19334 * @private
19335 * @param {object} handler
19336 * @constructor
19337 */
19338 function AsyncHandler(handler) {
19339 DelegateHandler.call(this, handler);
19340 }
19341
19342 inherit(DelegateHandler, AsyncHandler);
19343
19344 AsyncHandler.prototype.when = function(continuation) {
19345 tasks.enqueue(new ContinuationTask(continuation, this.join()));
19346 };
19347
19348 /**
19349 * Handler that follows another handler, injecting a receiver
19350 * @private
19351 * @param {object} handler another handler to follow
19352 * @param {object=undefined} receiver
19353 * @constructor
19354 */
19355 function BoundHandler(handler, receiver) {
19356 DelegateHandler.call(this, handler);
19357 this.receiver = receiver;
19358 }
19359
19360 inherit(DelegateHandler, BoundHandler);
19361
19362 BoundHandler.prototype.when = function(continuation) {
19363 // Because handlers are allowed to be shared among promises,
19364 // each of which possibly having a different receiver, we have
19365 // to insert our own receiver into the chain if it has been set
19366 // so that callbacks (f, r, u) will be called using our receiver
19367 if(this.receiver !== void 0) {
19368 continuation.receiver = this.receiver;
19369 }
19370 this.join().when(continuation);
19371 };
19372
19373 /**
19374 * Handler that wraps an untrusted thenable and assimilates it in a future stack
19375 * @private
19376 * @param {function} then
19377 * @param {{then: function}} thenable
19378 * @constructor
19379 */
19380 function ThenableHandler(then, thenable) {
19381 DeferredHandler.call(this);
19382 this.assimilated = false;
19383 this.untrustedThen = then;
19384 this.thenable = thenable;
19385 }
19386
19387 inherit(DeferredHandler, ThenableHandler);
19388
19389 ThenableHandler.prototype.when = function(continuation) {
19390 if(!this.assimilated) {
19391 this.assimilated = true;
19392 assimilate(this);
19393 }
19394 DeferredHandler.prototype.when.call(this, continuation);
19395 };
19396
19397 function assimilate(h) {
19398 tryAssimilate(h.untrustedThen, h.thenable, _resolve, _reject, _notify);
19399
19400 function _resolve(x) { h.resolve(x); }
19401 function _reject(x) { h.reject(x); }
19402 function _notify(x) { h.notify(x); }
19403 }
19404
19405 function tryAssimilate(then, thenable, resolve, reject, notify) {
19406 try {
19407 then.call(thenable, resolve, reject, notify);
19408 } catch (e) {
19409 reject(e);
19410 }
19411 }
19412
19413 /**
19414 * Handler for a fulfilled promise
19415 * @private
19416 * @param {*} x fulfillment value
19417 * @constructor
19418 */
19419 function FulfilledHandler(x) {
19420 Promise.createContext(this);
19421
19422 this.value = x;
19423 this.state = 1;
19424 }
19425
19426 inherit(Handler, FulfilledHandler);
19427
19428 FulfilledHandler.prototype.inspect = function() {
19429 return { state: 'fulfilled', value: this.value };
19430 };
19431
19432 FulfilledHandler.prototype.when = function(cont) {
19433 var x;
19434
19435 if (typeof cont.fulfilled === 'function') {
19436 Promise.enterContext(this);
19437 x = tryCatchReject(cont.fulfilled, this.value, cont.receiver);
19438 Promise.exitContext();
19439 } else {
19440 x = this.value;
19441 }
19442
19443 cont.resolve.call(cont.context, x);
19444 };
19445
19446 /**
19447 * Handler for a rejected promise
19448 * @private
19449 * @param {*} x rejection reason
19450 * @constructor
19451 */
19452 function RejectedHandler(x) {
19453 Promise.createContext(this);
19454
19455 this.value = x;
19456 this.state = -1; // -1: rejected, -2: rejected and reported
19457 this.handled = false;
19458
19459 this._report();
19460 }
19461
19462 inherit(Handler, RejectedHandler);
19463
19464 RejectedHandler.prototype.inspect = function() {
19465 return { state: 'rejected', reason: this.value };
19466 };
19467
19468 RejectedHandler.prototype.when = function(cont) {
19469 var x;
19470
19471 if (typeof cont.rejected === 'function') {
19472 this._unreport();
19473 Promise.enterContext(this);
19474 x = tryCatchReject(cont.rejected, this.value, cont.receiver);
19475 Promise.exitContext();
19476 } else {
19477 x = new Promise(Handler, this);
19478 }
19479
19480
19481 cont.resolve.call(cont.context, x);
19482 };
19483
19484 RejectedHandler.prototype._report = function(context) {
19485 tasks.afterQueue(reportUnhandled, this, context);
19486 };
19487
19488 RejectedHandler.prototype._unreport = function() {
19489 this.handled = true;
19490 tasks.afterQueue(reportHandled, this);
19491 };
19492
19493 RejectedHandler.prototype._fatal = function(context) {
19494 Promise.onFatalRejection(this, context);
19495 };
19496
19497 function reportUnhandled(rejection, context) {
19498 if(!rejection.handled) {
19499 rejection.state = -2;
19500 Promise.onPotentiallyUnhandledRejection(rejection, context);
19501 }
19502 }
19503
19504 function reportHandled(rejection) {
19505 if(rejection.state === -2) {
19506 Promise.onPotentiallyUnhandledRejectionHandled(rejection);
19507 }
19508 }
19509
19510 // Unhandled rejection hooks
19511 // By default, everything is a noop
19512
19513 // TODO: Better names: "annotate"?
19514 Promise.createContext
19515 = Promise.enterContext
19516 = Promise.exitContext
19517 = Promise.onPotentiallyUnhandledRejection
19518 = Promise.onPotentiallyUnhandledRejectionHandled
19519 = Promise.onFatalRejection
19520 = noop;
19521
19522 // Errors and singletons
19523
19524 var foreverPendingHandler = new Handler();
19525 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
19526
19527 function Cycle() {
19528 RejectedHandler.call(this, new TypeError('Promise cycle'));
19529 }
19530
19531 inherit(RejectedHandler, Cycle);
19532
19533 // Snapshot states
19534
19535 /**
19536 * Creates a pending state snapshot
19537 * @private
19538 * @returns {{state:'pending'}}
19539 */
19540 function toPendingState() {
19541 return { state: 'pending' };
19542 }
19543
19544 // Task runners
19545
19546 /**
19547 * Run a single consumer
19548 * @private
19549 * @constructor
19550 */
19551 function ContinuationTask(continuation, handler) {
19552 this.continuation = continuation;
19553 this.handler = handler;
19554 }
19555
19556 ContinuationTask.prototype.run = function() {
19557 this.handler.join().when(this.continuation);
19558 };
19559
19560 /**
19561 * Run a queue of progress handlers
19562 * @private
19563 * @constructor
19564 */
19565 function ProgressTask(handler, value) {
19566 this.handler = handler;
19567 this.value = value;
19568 }
19569
19570 ProgressTask.prototype.run = function() {
19571 var q = this.handler.consumers;
19572 if(q === void 0) {
19573 return;
19574 }
19575 // First progress handler is at index 1
19576 for (var i = 0; i < q.length; ++i) {
19577 this._notify(q[i]);
19578 }
19579 };
19580
19581 ProgressTask.prototype._notify = function(continuation) {
19582 var x = typeof continuation.progress === 'function'
19583 ? tryCatchReturn(continuation.progress, this.value, continuation.receiver)
19584 : this.value;
19585
19586 continuation.notify.call(continuation.context, x);
19587 };
19588
19589 // Other helpers
19590
19591 /**
19592 * @param {*} x
19593 * @returns {boolean} false iff x is guaranteed not to be a thenable
19594 */
19595 function maybeThenable(x) {
19596 return (typeof x === 'object' || typeof x === 'function') && x !== null;
19597 }
19598
19599 /**
19600 * Return f.call(thisArg, x), or if it throws return a rejected promise for
19601 * the thrown exception
19602 * @private
19603 */
19604 function tryCatchReject(f, x, thisArg) {
19605 try {
19606 return f.call(thisArg, x);
19607 } catch(e) {
19608 return reject(e);
19609 }
19610 }
19611
19612 /**
19613 * Same as above, but includes the extra argument parameter.
19614 * @private
19615 */
19616 function tryCatchReject2(f, x, y, thisArg) {
19617 try {
19618 return f.call(thisArg, x, y);
19619 } catch(e) {
19620 return reject(e);
19621 }
19622 }
19623
19624 /**
19625 * Return f.call(thisArg, x), or if it throws, *return* the exception
19626 * @private
19627 */
19628 function tryCatchReturn(f, x, thisArg) {
19629 try {
19630 return f.call(thisArg, x);
19631 } catch(e) {
19632 return e;
19633 }
19634 }
19635
19636 function inherit(Parent, Child) {
19637 Child.prototype = objectCreate(Parent.prototype);
19638 Child.prototype.constructor = Child;
19639 }
19640
19641 function noop() {}
19642
19643 return Promise;
19644 };
19645});
19646}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19647
19648},{}],80:[function(require,module,exports){
19649/** @license MIT License (c) copyright 2010-2014 original author or authors */
19650/** @author Brian Cavalier */
19651/** @author John Hann */
19652
19653(function(define) { 'use strict';
19654define(function(require) {
19655
19656 var Queue = require('./Queue');
19657
19658 // Credit to Twisol (https://github.com/Twisol) for suggesting
19659 // this type of extensible queue + trampoline approach for next-tick conflation.
19660
19661 function Scheduler(enqueue) {
19662 this._enqueue = enqueue;
19663 this._handlerQueue = new Queue(15);
19664 this._afterQueue = new Queue(5);
19665 this._running = false;
19666
19667 var self = this;
19668 this.drain = function() {
19669 self._drain();
19670 };
19671 }
19672
19673 /**
19674 * Enqueue a task. If the queue is not currently scheduled to be
19675 * drained, schedule it.
19676 * @param {function} task
19677 */
19678 Scheduler.prototype.enqueue = function(task) {
19679 this._handlerQueue.push(task);
19680 if(!this._running) {
19681 this._running = true;
19682 this._enqueue(this.drain);
19683 }
19684 };
19685
19686 Scheduler.prototype.afterQueue = function(f, x, y) {
19687 this._afterQueue.push(f);
19688 this._afterQueue.push(x);
19689 this._afterQueue.push(y);
19690 if(!this._running) {
19691 this._running = true;
19692 this._enqueue(this.drain);
19693 }
19694 };
19695
19696 /**
19697 * Drain the handler queue entirely, being careful to allow the
19698 * queue to be extended while it is being processed, and to continue
19699 * processing until it is truly empty.
19700 */
19701 Scheduler.prototype._drain = function() {
19702 var q = this._handlerQueue;
19703 while(q.length > 0) {
19704 q.shift().run();
19705 }
19706
19707 q = this._afterQueue;
19708 while(q.length > 0) {
19709 q.shift()(q.shift(), q.shift());
19710 }
19711
19712 this._running = false;
19713 };
19714
19715 return Scheduler;
19716
19717});
19718}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
19719
19720},{"./Queue":67}],81:[function(require,module,exports){
19721/** @license MIT License (c) copyright 2010-2014 original author or authors */
19722/** @author Brian Cavalier */
19723/** @author John Hann */
19724
19725(function(define) { 'use strict';
19726define(function(require) {
19727 /*global setTimeout,clearTimeout*/
19728 var cjsRequire, vertx, setTimer, clearTimer;
19729
19730 cjsRequire = require;
19731
19732 try {
19733 vertx = cjsRequire('vertx');
19734 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
19735 clearTimer = vertx.cancelTimer;
19736 } catch (e) {
19737 setTimer = function(f, ms) { return setTimeout(f, ms); };
19738 clearTimer = function(t) { return clearTimeout(t); };
19739 }
19740
19741 return {
19742 set: setTimer,
19743 clear: clearTimer
19744 };
19745
19746});
19747}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
19748
19749},{}],82:[function(require,module,exports){
19750/** @license MIT License (c) copyright 2010-2014 original author or authors */
19751
19752/**
19753 * Promises/A+ and when() implementation
19754 * when is part of the cujoJS family of libraries (http://cujojs.com/)
19755 * @author Brian Cavalier
19756 * @author John Hann
19757 * @version 3.2.2
19758 */
19759(function(define) { 'use strict';
19760define(function (require) {
19761
19762 var timed = require('./lib/decorators/timed');
19763 var array = require('./lib/decorators/array');
19764 var flow = require('./lib/decorators/flow');
19765 var fold = require('./lib/decorators/fold');
19766 var inspect = require('./lib/decorators/inspect');
19767 var generate = require('./lib/decorators/iterate');
19768 var progress = require('./lib/decorators/progress');
19769 var withThis = require('./lib/decorators/with');
19770 var unhandledRejection = require('./lib/decorators/unhandledRejection');
19771 var TimeoutError = require('./lib/TimeoutError');
19772
19773 var Promise = [array, flow, fold, generate, progress,
19774 inspect, withThis, timed, unhandledRejection]
19775 .reduce(function(Promise, feature) {
19776 return feature(Promise);
19777 }, require('./lib/Promise'));
19778
19779 var slice = Array.prototype.slice;
19780
19781 // Public API
19782
19783 when.promise = promise; // Create a pending promise
19784 when.resolve = Promise.resolve; // Create a resolved promise
19785 when.reject = Promise.reject; // Create a rejected promise
19786
19787 when.lift = lift; // lift a function to return promises
19788 when['try'] = attempt; // call a function and return a promise
19789 when.attempt = attempt; // alias for when.try
19790
19791 when.iterate = Promise.iterate; // Generate a stream of promises
19792 when.unfold = Promise.unfold; // Generate a stream of promises
19793
19794 when.join = join; // Join 2 or more promises
19795
19796 when.all = all; // Resolve a list of promises
19797 when.settle = settle; // Settle a list of promises
19798
19799 when.any = lift(Promise.any); // One-winner race
19800 when.some = lift(Promise.some); // Multi-winner race
19801
19802 when.map = map; // Array.map() for promises
19803 when.reduce = reduce; // Array.reduce() for promises
19804 when.reduceRight = reduceRight; // Array.reduceRight() for promises
19805
19806 when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
19807
19808 when.Promise = Promise; // Promise constructor
19809 when.defer = defer; // Create a {promise, resolve, reject} tuple
19810
19811 // Error types
19812
19813 when.TimeoutError = TimeoutError;
19814
19815 /**
19816 * Get a trusted promise for x, or by transforming x with onFulfilled
19817 *
19818 * @param {*} x
19819 * @param {function?} onFulfilled callback to be called when x is
19820 * successfully fulfilled. If promiseOrValue is an immediate value, callback
19821 * will be invoked immediately.
19822 * @param {function?} onRejected callback to be called when x is
19823 * rejected.
19824 * @deprecated @param {function?} onProgress callback to be called when progress updates
19825 * are issued for x.
19826 * @returns {Promise} a new promise that will fulfill with the return
19827 * value of callback or errback or the completion value of promiseOrValue if
19828 * callback and/or errback is not supplied.
19829 */
19830 function when(x, onFulfilled, onRejected) {
19831 var p = Promise.resolve(x);
19832 if(arguments.length < 2) {
19833 return p;
19834 }
19835
19836 return arguments.length > 3
19837 ? p.then(onFulfilled, onRejected, arguments[3])
19838 : p.then(onFulfilled, onRejected);
19839 }
19840
19841 /**
19842 * Creates a new promise whose fate is determined by resolver.
19843 * @param {function} resolver function(resolve, reject, notify)
19844 * @returns {Promise} promise whose fate is determine by resolver
19845 */
19846 function promise(resolver) {
19847 return new Promise(resolver);
19848 }
19849
19850 /**
19851 * Lift the supplied function, creating a version of f that returns
19852 * promises, and accepts promises as arguments.
19853 * @param {function} f
19854 * @returns {Function} version of f that returns promises
19855 */
19856 function lift(f) {
19857 return function() {
19858 return _apply(f, this, slice.call(arguments));
19859 };
19860 }
19861
19862 /**
19863 * Call f in a future turn, with the supplied args, and return a promise
19864 * for the result.
19865 * @param {function} f
19866 * @returns {Promise}
19867 */
19868 function attempt(f /*, args... */) {
19869 /*jshint validthis:true */
19870 return _apply(f, this, slice.call(arguments, 1));
19871 }
19872
19873 /**
19874 * try/lift helper that allows specifying thisArg
19875 * @private
19876 */
19877 function _apply(f, thisArg, args) {
19878 return Promise.all(args).then(function(args) {
19879 return f.apply(thisArg, args);
19880 });
19881 }
19882
19883 /**
19884 * Creates a {promise, resolver} pair, either or both of which
19885 * may be given out safely to consumers.
19886 * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
19887 */
19888 function defer() {
19889 return new Deferred();
19890 }
19891
19892 function Deferred() {
19893 var p = Promise._defer();
19894
19895 function resolve(x) { p._handler.resolve(x); }
19896 function reject(x) { p._handler.reject(x); }
19897 function notify(x) { p._handler.notify(x); }
19898
19899 this.promise = p;
19900 this.resolve = resolve;
19901 this.reject = reject;
19902 this.notify = notify;
19903 this.resolver = { resolve: resolve, reject: reject, notify: notify };
19904 }
19905
19906 /**
19907 * Determines if x is promise-like, i.e. a thenable object
19908 * NOTE: Will return true for *any thenable object*, and isn't truly
19909 * safe, since it may attempt to access the `then` property of x (i.e.
19910 * clever/malicious getters may do weird things)
19911 * @param {*} x anything
19912 * @returns {boolean} true if x is promise-like
19913 */
19914 function isPromiseLike(x) {
19915 return x && typeof x.then === 'function';
19916 }
19917
19918 /**
19919 * Return a promise that will resolve only once all the supplied arguments
19920 * have resolved. The resolution value of the returned promise will be an array
19921 * containing the resolution values of each of the arguments.
19922 * @param {...*} arguments may be a mix of promises and values
19923 * @returns {Promise}
19924 */
19925 function join(/* ...promises */) {
19926 return Promise.all(arguments);
19927 }
19928
19929 /**
19930 * Return a promise that will fulfill once all input promises have
19931 * fulfilled, or reject when any one input promise rejects.
19932 * @param {array|Promise} promises array (or promise for an array) of promises
19933 * @returns {Promise}
19934 */
19935 function all(promises) {
19936 return when(promises, Promise.all);
19937 }
19938
19939 /**
19940 * Return a promise that will always fulfill with an array containing
19941 * the outcome states of all input promises. The returned promise
19942 * will only reject if `promises` itself is a rejected promise.
19943 * @param {array|Promise} promises array (or promise for an array) of promises
19944 * @returns {Promise}
19945 */
19946 function settle(promises) {
19947 return when(promises, Promise.settle);
19948 }
19949
19950 /**
19951 * Promise-aware array map function, similar to `Array.prototype.map()`,
19952 * but input array may contain promises or values.
19953 * @param {Array|Promise} promises array of anything, may contain promises and values
19954 * @param {function} mapFunc map function which may return a promise or value
19955 * @returns {Promise} promise that will fulfill with an array of mapped values
19956 * or reject if any input promise rejects.
19957 */
19958 function map(promises, mapFunc) {
19959 return when(promises, function(promises) {
19960 return Promise.map(promises, mapFunc);
19961 });
19962 }
19963
19964 /**
19965 * Traditional reduce function, similar to `Array.prototype.reduce()`, but
19966 * input may contain promises and/or values, and reduceFunc
19967 * may return either a value or a promise, *and* initialValue may
19968 * be a promise for the starting value.
19969 *
19970 * @param {Array|Promise} promises array or promise for an array of anything,
19971 * may contain a mix of promises and values.
19972 * @param {function} f reduce function reduce(currentValue, nextValue, index)
19973 * @returns {Promise} that will resolve to the final reduced value
19974 */
19975 function reduce(promises, f /*, initialValue */) {
19976 /*jshint unused:false*/
19977 var args = slice.call(arguments, 1);
19978 return when(promises, function(array) {
19979 args.unshift(array);
19980 return Promise.reduce.apply(Promise, args);
19981 });
19982 }
19983
19984 /**
19985 * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
19986 * input may contain promises and/or values, and reduceFunc
19987 * may return either a value or a promise, *and* initialValue may
19988 * be a promise for the starting value.
19989 *
19990 * @param {Array|Promise} promises array or promise for an array of anything,
19991 * may contain a mix of promises and values.
19992 * @param {function} f reduce function reduce(currentValue, nextValue, index)
19993 * @returns {Promise} that will resolve to the final reduced value
19994 */
19995 function reduceRight(promises, f /*, initialValue */) {
19996 /*jshint unused:false*/
19997 var args = slice.call(arguments, 1);
19998 return when(promises, function(array) {
19999 args.unshift(array);
20000 return Promise.reduceRight.apply(Promise, args);
20001 });
20002 }
20003
20004 return when;
20005});
20006})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
20007
20008},{"./lib/Promise":66,"./lib/TimeoutError":68,"./lib/decorators/array":70,"./lib/decorators/flow":71,"./lib/decorators/fold":72,"./lib/decorators/inspect":73,"./lib/decorators/iterate":74,"./lib/decorators/progress":75,"./lib/decorators/timed":76,"./lib/decorators/unhandledRejection":77,"./lib/decorators/with":78}]},{},[1])(1)
20009});
\No newline at end of file