(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.OmegaTargetChromium = f()}})(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 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],2:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property * on objects. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() function typedArraySupport () { function Bar () {} try { var arr = new Uint8Array(1) arr.foo = function () { return 42 } arr.constructor = Bar return arr.foo() === 42 && // typed array instances can be augmented arr.constructor === Bar && // constructor can be set typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (arg) { if (!(this instanceof Buffer)) { // Avoid going through an ArgumentsAdaptorTrampoline in the common case. if (arguments.length > 1) return new Buffer(arg, arguments[1]) return new Buffer(arg) } if (!Buffer.TYPED_ARRAY_SUPPORT) { this.length = 0 this.parent = undefined } // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } function fromNumber (that, length) { that = allocate(that, length < 0 ? 0 : checked(length) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < length; i++) { that[i] = 0 } } return that } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined') { if (object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object instanceof ArrayBuffer) { return fromArrayBuffer(that, object) } } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } function fromArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) // Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance array.byteLength that = Buffer._augment(new Uint8Array(array)) } else { // Fallback: Return an object instance of the Buffer class that = fromTypedArray(that, new Uint8Array(array)) } return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject (that, object) { var array var length = 0 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array } else { // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (subject, encoding) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) var buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = '' + string var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'binary': // Deprecated case 'raw': case 'raws': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` is deprecated Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` is deprecated Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'binary': return binaryWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; i--) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; i++) { target[i + targetStart] = this[i + start] } } else { target._set(this.subarray(start, start + len), targetStart) } return len } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function toArrayBuffer () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function _augment (arr) { arr.constructor = Buffer arr._isBuffer = true // save reference to original Uint8Array set method before overwriting arr._set = arr.set // deprecated arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.indexOf = BP.indexOf arr.copy = BP.copy arr.slice = BP.slice arr.readUIntLE = BP.readUIntLE arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readIntLE = BP.readIntLE arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUIntLE = BP.writeUIntLE arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeIntLE = BP.writeIntLE arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":1,"ieee754":8,"isarray":3}],3:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],4:[function(require,module,exports){ 'use strict'; var isCallable = require('is-callable'); var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; var forEach = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (toStr.call(list) === '[object Array]') { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; module.exports = forEach; },{"is-callable":9}],5:[function(require,module,exports){ (function (global){ var win; if (typeof window !== "undefined") { win = window; } else if (typeof global !== "undefined") { win = global; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } module.exports = win; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],6:[function(require,module,exports){ module.exports = require('./lib/heap'); },{"./lib/heap":7}],7:[function(require,module,exports){ // Generated by CoffeeScript 1.8.0 (function() { var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; floor = Math.floor, min = Math.min; /* Default comparison function to be used */ defaultCmp = function(x, y) { if (x < y) { return -1; } if (x > y) { return 1; } return 0; }; /* Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default a.length) bound the slice of a to be searched. */ insort = function(a, x, lo, hi, cmp) { var mid; if (lo == null) { lo = 0; } if (cmp == null) { cmp = defaultCmp; } if (lo < 0) { throw new Error('lo must be non-negative'); } if (hi == null) { hi = a.length; } while (lo < hi) { mid = floor((lo + hi) / 2); if (cmp(x, a[mid]) < 0) { hi = mid; } else { lo = mid + 1; } } return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); }; /* Push item onto heap, maintaining the heap invariant. */ heappush = function(array, item, cmp) { if (cmp == null) { cmp = defaultCmp; } array.push(item); return _siftdown(array, 0, array.length - 1, cmp); }; /* Pop the smallest item off the heap, maintaining the heap invariant. */ heappop = function(array, cmp) { var lastelt, returnitem; if (cmp == null) { cmp = defaultCmp; } lastelt = array.pop(); if (array.length) { returnitem = array[0]; array[0] = lastelt; _siftup(array, 0, cmp); } else { returnitem = lastelt; } return returnitem; }; /* Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed size heap. Note that the value returned may be larger than item! That constrains reasonable use of this routine unless written as part of a conditional replacement: if item > array[0] item = heapreplace(array, item) */ heapreplace = function(array, item, cmp) { var returnitem; if (cmp == null) { cmp = defaultCmp; } returnitem = array[0]; array[0] = item; _siftup(array, 0, cmp); return returnitem; }; /* Fast version of a heappush followed by a heappop. */ heappushpop = function(array, item, cmp) { var _ref; if (cmp == null) { cmp = defaultCmp; } if (array.length && cmp(array[0], item) < 0) { _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; _siftup(array, 0, cmp); } return item; }; /* Transform list into a heap, in-place, in O(array.length) time. */ heapify = function(array, cmp) { var i, _i, _j, _len, _ref, _ref1, _results, _results1; if (cmp == null) { cmp = defaultCmp; } _ref1 = (function() { _results1 = []; for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } return _results1; }).apply(this).reverse(); _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { i = _ref1[_i]; _results.push(_siftup(array, i, cmp)); } return _results; }; /* Update the position of the given item in the heap. This function should be called every time the item is being modified. */ updateItem = function(array, item, cmp) { var pos; if (cmp == null) { cmp = defaultCmp; } pos = array.indexOf(item); if (pos === -1) { return; } _siftdown(array, 0, pos, cmp); return _siftup(array, pos, cmp); }; /* Find the n largest elements in a dataset. */ nlargest = function(array, n, cmp) { var elem, result, _i, _len, _ref; if (cmp == null) { cmp = defaultCmp; } result = array.slice(0, n); if (!result.length) { return result; } heapify(result, cmp); _ref = array.slice(n); for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; heappushpop(result, elem, cmp); } return result.sort(cmp).reverse(); }; /* Find the n smallest elements in a dataset. */ nsmallest = function(array, n, cmp) { var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; if (cmp == null) { cmp = defaultCmp; } if (n * 10 <= array.length) { result = array.slice(0, n).sort(cmp); if (!result.length) { return result; } los = result[result.length - 1]; _ref = array.slice(n); for (_i = 0, _len = _ref.length; _i < _len; _i++) { elem = _ref[_i]; if (cmp(elem, los) < 0) { insort(result, elem, 0, null, cmp); result.pop(); los = result[result.length - 1]; } } return result; } heapify(array, cmp); _results = []; for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { _results.push(heappop(array, cmp)); } return _results; }; _siftdown = function(array, startpos, pos, cmp) { var newitem, parent, parentpos; if (cmp == null) { cmp = defaultCmp; } newitem = array[pos]; while (pos > startpos) { parentpos = (pos - 1) >> 1; parent = array[parentpos]; if (cmp(newitem, parent) < 0) { array[pos] = parent; pos = parentpos; continue; } break; } return array[pos] = newitem; }; _siftup = function(array, pos, cmp) { var childpos, endpos, newitem, rightpos, startpos; if (cmp == null) { cmp = defaultCmp; } endpos = array.length; startpos = pos; newitem = array[pos]; childpos = 2 * pos + 1; while (childpos < endpos) { rightpos = childpos + 1; if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { childpos = rightpos; } array[pos] = array[childpos]; pos = childpos; childpos = 2 * pos + 1; } array[pos] = newitem; return _siftdown(array, startpos, pos, cmp); }; Heap = (function() { Heap.push = heappush; Heap.pop = heappop; Heap.replace = heapreplace; Heap.pushpop = heappushpop; Heap.heapify = heapify; Heap.updateItem = updateItem; Heap.nlargest = nlargest; Heap.nsmallest = nsmallest; function Heap(cmp) { this.cmp = cmp != null ? cmp : defaultCmp; this.nodes = []; } Heap.prototype.push = function(x) { return heappush(this.nodes, x, this.cmp); }; Heap.prototype.pop = function() { return heappop(this.nodes, this.cmp); }; Heap.prototype.peek = function() { return this.nodes[0]; }; Heap.prototype.contains = function(x) { return this.nodes.indexOf(x) !== -1; }; Heap.prototype.replace = function(x) { return heapreplace(this.nodes, x, this.cmp); }; Heap.prototype.pushpop = function(x) { return heappushpop(this.nodes, x, this.cmp); }; Heap.prototype.heapify = function() { return heapify(this.nodes, this.cmp); }; Heap.prototype.updateItem = function(x) { return updateItem(this.nodes, x, this.cmp); }; Heap.prototype.clear = function() { return this.nodes = []; }; Heap.prototype.empty = function() { return this.nodes.length === 0; }; Heap.prototype.size = function() { return this.nodes.length; }; Heap.prototype.clone = function() { var heap; heap = new Heap(); heap.nodes = this.nodes.slice(0); return heap; }; Heap.prototype.toArray = function() { return this.nodes.slice(0); }; Heap.prototype.insert = Heap.prototype.push; Heap.prototype.top = Heap.prototype.peek; Heap.prototype.front = Heap.prototype.peek; Heap.prototype.has = Heap.prototype.contains; Heap.prototype.copy = Heap.prototype.clone; return Heap; })(); (function(root, factory) { if (typeof define === 'function' && define.amd) { return define([], factory); } else if (typeof exports === 'object') { return module.exports = factory(); } else { return root.Heap = factory(); } })(this, function() { return Heap; }); }).call(this); },{}],8:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],9:[function(require,module,exports){ 'use strict'; var fnToStr = Function.prototype.toString; var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (typeof value === 'function' && !value.prototype) { return true; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; },{}],10:[function(require,module,exports){ module.exports = once once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) }) function once (fn) { var called = false return function () { if (called) return called = true return fn.apply(this, arguments) } } },{}],11:[function(require,module,exports){ var trim = require('trim') , forEach = require('for-each') , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } },{"for-each":4,"trim":16}],12:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],13:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],14:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],15:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":13,"./encode":14}],16:[function(require,module,exports){ exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; },{}],17:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = require('punycode'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); Object.keys(this).forEach(function(k) { result[k] = this[k]; }, this); // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative Object.keys(relative).forEach(function(k) { if (k !== 'protocol') result[k] = relative[k]; }); //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { Object.keys(relative).forEach(function(k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; function isString(arg) { return typeof arg === "string"; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; } },{"punycode":12,"querystring":15}],18:[function(require,module,exports){ var window = require("global/window") var once = require("once") var parseHeaders = require('parse-headers') var messages = { "0": "Internal XMLHttpRequest Error", "4": "4xx Client Error", "5": "5xx Server Error" } var XHR = window.XMLHttpRequest || noop var XDR = "withCredentials" in (new XHR()) ? XHR : window.XDomainRequest module.exports = createXHR function createXHR(options, callback) { if (typeof options === "string") { options = { uri: options } } options = options || {} callback = once(callback) var xhr = options.xhr || null if (!xhr) { if (options.cors || options.useXDR) { xhr = new XDR() }else{ xhr = new XHR() } } var uri = xhr.url = options.uri || options.url var method = xhr.method = options.method || "GET" var body = options.body || options.data var headers = xhr.headers = options.headers || {} var sync = !!options.sync var isJson = false var key var load = options.response ? loadResponse : loadXhr if ("json" in options) { isJson = true headers["Accept"] = "application/json" if (method !== "GET" && method !== "HEAD") { headers["Content-Type"] = "application/json" body = JSON.stringify(options.json) } } xhr.onreadystatechange = readystatechange xhr.onload = load xhr.onerror = error // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () { // IE must die } // hate IE xhr.ontimeout = noop xhr.open(method, uri, !sync) //backward compatibility if (options.withCredentials || (options.cors && options.withCredentials !== false)) { xhr.withCredentials = true } // Cannot set timeout with sync request if (!sync) { xhr.timeout = "timeout" in options ? options.timeout : 5000 } if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ xhr.setRequestHeader(key, headers[key]) } } } else if (options.headers) { throw new Error("Headers cannot be set on an XDomainRequest object") } if ("responseType" in options) { xhr.responseType = options.responseType } if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } xhr.send(body) return xhr function readystatechange() { if (xhr.readyState === 4) { load() } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = null if (xhr.response) { body = xhr.response } else if (xhr.responseType === 'text' || !xhr.responseType) { body = xhr.responseText || xhr.responseXML } if (isJson) { try { body = JSON.parse(body) } catch (e) {} } return body } function getStatusCode() { return xhr.status === 1223 ? 204 : xhr.status } // if we're getting a none-ok statusCode, build & return an error function errorFromStatusCode(status, body) { var error = null if (status === 0 || (status >= 400 && status < 600)) { var message = (typeof body === "string" ? body : false) || messages[String(status).charAt(0)] error = new Error(message) error.statusCode = status } return error } // will load the data & process the response in a special response object function loadResponse() { var status = getStatusCode() var body = getBody() var error = errorFromStatusCode(status, body) var response = { body: body, statusCode: status, statusText: xhr.statusText, raw: xhr } if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()) } else { response.headers = {} } callback(error, response, response.body) } // will load the data and add some response properties to the source xhr // and then respond with that function loadXhr() { var status = getStatusCode() var error = errorFromStatusCode(status) xhr.status = xhr.statusCode = status xhr.body = getBody() xhr.headers = parseHeaders(xhr.getAllResponseHeaders()) callback(error, xhr, xhr.body) } function error(evt) { callback(evt, xhr) } } function noop() {} },{"global/window":5,"once":10,"parse-headers":11}],19:[function(require,module,exports){ module.exports = OmegaTarget },{}],20:[function(require,module,exports){ var OmegaTarget, Promise, slice = [].slice; OmegaTarget = require('omega-target'); Promise = OmegaTarget.Promise; exports.chromeApiPromisify = function(target, method) { return function() { var args; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; return new Promise(function(resolve, reject) { var callback; callback = function() { var callbackArgs, error; callbackArgs = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (chrome.runtime.lastError != null) { error = new Error(chrome.runtime.lastError.message); error.original = chrome.runtime.lastError; return reject(error); } if (callbackArgs.length <= 1) { return resolve(callbackArgs[0]); } else { return resolve(callbackArgs); } }; args.push(callback); return target[method].apply(target, args); }); }; }; },{"omega-target":19}],21:[function(require,module,exports){ var ChromePort, TrackedEvent, slice = [].slice; module.exports = ChromePort = (function() { function ChromePort(port) { this.port = port; this.name = this.port.name; this.sender = this.port.sender; this.disconnect = this.port.disconnect.bind(this.port); this.postMessage = (function(_this) { return function() { var _, args, ref; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; try { return (ref = _this.port).postMessage.apply(ref, args); } catch (error) { _ = error; } }; })(this); this.onMessage = new TrackedEvent(this.port.onMessage); this.onDisconnect = new TrackedEvent(this.port.onDisconnect); this.onDisconnect.addListener(this.dispose.bind(this)); } ChromePort.prototype.dispose = function() { this.onMessage.dispose(); return this.onDisconnect.dispose(); }; return ChromePort; })(); TrackedEvent = (function() { function TrackedEvent(event) { var j, len, mes, method, methodName; this.event = event; this.callbacks = []; mes = ['hasListener', 'hasListeners', 'addRules', 'getRules', 'removeRules']; for (j = 0, len = mes.length; j < len; j++) { methodName = mes[j]; method = this.event[methodName]; if (method != null) { this[methodName] = method.bind(this.event); } } } TrackedEvent.prototype.addListener = function(callback) { this.event.addListener(callback); this.callbacks.push(callback); return this; }; TrackedEvent.prototype.removeListener = function(callback) { var i; this.event.removeListener(callback); i = this.callbacks.indexOf(callback); if (i >= 0) { this.callbacks.splice(i, 1); } return this; }; /** * Removes all listeners added via this TrackedEvent instance. * Note: Won't remove listeners added via other TrackedEvent or raw Event. */ TrackedEvent.prototype.removeAllListeners = function() { var callback, j, len, ref; ref = this.callbacks; for (j = 0, len = ref.length; j < len; j++) { callback = ref[j]; this.event.removeListener(callback); } this.callbacks = []; return this; }; /** * Removes all listeners added via this TrackedEvent instance and prevent any * further listeners from being added. It is considered safe to nullify any * references to this instance and the underlying Event without causing leaks. * This should be the last method called in the lifetime of TrackedEvent. * * Throws if the underlying raw Event object still has listeners. This can * happen when listeners have been added via other TrackedEvents or raw Event. */ TrackedEvent.prototype.dispose = function() { var base; this.removeAllListeners(); if (typeof (base = this.event).hasListeners === "function" ? base.hasListeners() : void 0) { throw new Error("Underlying Event still has listeners!"); } this.event = null; return this.callbacks = null; }; return TrackedEvent; })(); },{}],22:[function(require,module,exports){ var ChromePort, ExternalApi, OmegaPac, OmegaTarget, Promise; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; Promise = OmegaTarget.Promise; ChromePort = require('./chrome_port'); module.exports = ExternalApi = (function() { function ExternalApi(options) { this.options = options; } ExternalApi.prototype.knownExts = { 'padekgcemlokbadohgkifijomclgjgif': 32 }; ExternalApi.prototype.disabled = false; ExternalApi.prototype.listen = function() { if (!chrome.runtime.onConnectExternal) { return; } return chrome.runtime.onConnectExternal.addListener((function(_this) { return function(rawPort) { var port; port = new ChromePort(rawPort); port.onMessage.addListener(function(msg) { return _this.onMessage(msg, port); }); return port.onDisconnect.addListener(_this.reenable.bind(_this)); }; })(this)); }; ExternalApi.prototype._previousProfileName = null; ExternalApi.prototype.reenable = function() { var base; if (!this.disabled) { return; } this.options.setProxyNotControllable(null); if (typeof (base = chrome.browserAction).setPopup === "function") { base.setPopup({ popup: 'popup/index.html' }); } this.options.reloadQuickSwitch(); this.disabled = false; this.options.clearBadge(); return this.options.applyProfile(this._previousProfileName); }; ExternalApi.prototype.checkPerm = function(port, level) { var perm; perm = this.knownExts[port.sender.id] || 0; if (perm < level) { port.postMessage({ action: 'error', error: 'permission' }); return false; } else { return true; } }; ExternalApi.prototype.onMessage = function(msg, port) { var base, ref; this.options.log.log(port.sender.id + " -> " + msg.action, msg); switch (msg.action) { case 'disable': if (!this.checkPerm(port, 16)) { return; } if (this.disabled) { return; } this.disabled = true; this._previousProfileName = ((ref = this.options.currentProfile()) != null ? ref.name : void 0) || 'system'; this.options.applyProfile('system').then((function(_this) { return function() { var reason; reason = 'disabled'; if (_this.knownExts[port.sender.id] >= 32) { reason = 'upgrade'; } return _this.options.setProxyNotControllable(reason, { text: 'X', color: '#5ab432' }); }; })(this)); if (typeof (base = chrome.browserAction).setPopup === "function") { base.setPopup({ popup: 'popup/index.html' }); } return port.postMessage({ action: 'state', state: 'disabled' }); case 'enable': this.reenable(); return port.postMessage({ action: 'state', state: 'enabled' }); case 'getOptions': if (!this.checkPerm(port, 8)) { return; } return port.postMessage({ action: 'options', options: this.options.getAll() }); default: return port.postMessage({ action: 'error', error: 'noSuchAction', action_name: msg.action }); } }; return ExternalApi; })(); },{"./chrome_port":21,"omega-target":19}],23:[function(require,module,exports){ var ContentTypeRejectedError, Promise, Url, defaultHintHandler, fetchUrl, hintHandlers, xhr, xhrWrapper, slice = [].slice; Promise = OmegaTarget.Promise; xhr = Promise.promisify(require('xhr')); Url = require('url'); ContentTypeRejectedError = OmegaTarget.ContentTypeRejectedError; xhrWrapper = function() { var args; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; return xhr.apply(null, args)["catch"](function(err) { if (!err.isOperational) { throw err; } if (!err.statusCode) { throw new OmegaTarget.NetworkError(err); } if (err.statusCode === 404) { throw new OmegaTarget.HttpNotFoundError(err); } if (err.statusCode >= 500 && err.statusCode < 600) { throw new OmegaTarget.HttpServerError(err); } throw new OmegaTarget.HttpError(err); }); }; fetchUrl = function(dest_url, opt_bypass_cache, opt_type_hints) { var dest_url_nocache, getResBody, parsed; getResBody = function(arg) { var body, contentType, handler, hint, i, len, ref, ref1, response, result; response = arg[0], body = arg[1]; if (!opt_type_hints) { return body; } contentType = (ref = response.headers['content-type']) != null ? ref.toLowerCase() : void 0; for (i = 0, len = opt_type_hints.length; i < len; i++) { hint = opt_type_hints[i]; handler = (ref1 = hintHandlers[hint]) != null ? ref1 : defaultHintHandler; result = handler(response, body, { contentType: contentType, hint: hint }); if (result != null) { return result; } } throw new ContentTypeRejectedError('Unrecognized Content-Type: ' + contentType); return body; }; if (opt_bypass_cache && dest_url.indexOf('?') < 0) { parsed = Url.parse(dest_url, true); parsed.search = void 0; parsed.query['_'] = Date.now(); dest_url_nocache = Url.format(parsed); return xhrWrapper(dest_url_nocache).then(getResBody)["catch"](function() { return xhrWrapper(dest_url).then(getResBody); }); } else { return xhrWrapper(dest_url).then(getResBody); } }; defaultHintHandler = function(response, body, arg) { var contentType, hint; contentType = arg.contentType, hint = arg.hint; if ('!' + contentType === hint) { throw new ContentTypeRejectedError('Response Content-Type blacklisted: ' + contentType); } if (contentType === hint) { return body; } }; hintHandlers = { '*': function(response, body) { return body; }, '!text/html': function(response, body, arg) { var contentType, hint, looksLikeHtml; contentType = arg.contentType, hint = arg.hint; if (contentType === hint) { looksLikeHtml = false; if (body.indexOf('= 0 || body.indexOf('= 0) { looksLikeHtml = true; } else if (body.indexOf('') >= 0) { looksLikeHtml = true; } else if (body.indexOf('') >= 0) { looksLikeHtml = true; } if (looksLikeHtml) { throw new ContentTypeRejectedError('Response must not be HTML.'); } } }, '!application/xhtml+xml': function() { var args; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; return hintHandlers['!text/html'].apply(hintHandlers, args); }, 'application/x-ns-proxy-autoconfig': function(response, body, arg) { var contentType, hint; contentType = arg.contentType, hint = arg.hint; if (contentType === hint) { return body; } if (body.indexOf('FindProxyForURL') >= 0) { return body; } else { return void 0; } } }; module.exports = fetchUrl; },{"url":17,"xhr":18}],24:[function(require,module,exports){ var base, name, ref, value; module.exports = { Storage: require('./storage'), Options: require('./options'), ChromeTabs: require('./tabs'), SwitchySharp: require('./switchysharp'), ExternalApi: require('./external_api'), WebRequestMonitor: require('./web_request_monitor'), Inspect: require('./inspect'), Url: require('url'), proxy: require('./proxy') }; ref = require('omega-target'); for (name in ref) { value = ref[name]; if ((base = module.exports)[name] == null) { base[name] = value; } } },{"./external_api":22,"./inspect":25,"./options":26,"./proxy":27,"./storage":33,"./switchysharp":34,"./tabs":35,"./web_request_monitor":37,"omega-target":19,"url":17}],25:[function(require,module,exports){ var Inspect, OmegaPac, OmegaTarget, Promise, hasProp = {}.hasOwnProperty; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; Promise = OmegaTarget.Promise; module.exports = Inspect = (function() { Inspect.prototype._enabled = false; function Inspect(onInspect) { this.onInspect = onInspect; } Inspect.prototype.enable = function() { var webResource; if (chrome.contextMenus == null) { return; } if (chrome.i18n.getUILanguage == null) { return; } if (this._enabled) { return; } webResource = ["http://*/*", "https://*/*", "ftp://*/*"]; /* Not so useful... chrome.contextMenus.create({ id: 'inspectPage' title: chrome.i18n.getMessage('contextMenu_inspectPage') contexts: ['page'] onclick: @inspect.bind(this) documentUrlPatterns: webResource }) */ chrome.contextMenus.create({ id: 'inspectFrame', title: chrome.i18n.getMessage('contextMenu_inspectFrame'), contexts: ['frame'], onclick: this.inspect.bind(this), documentUrlPatterns: webResource }); chrome.contextMenus.create({ id: 'inspectLink', title: chrome.i18n.getMessage('contextMenu_inspectLink'), contexts: ['link'], onclick: this.inspect.bind(this), targetUrlPatterns: webResource }); chrome.contextMenus.create({ id: 'inspectElement', title: chrome.i18n.getMessage('contextMenu_inspectElement'), contexts: ['image', 'video', 'audio'], onclick: this.inspect.bind(this), targetUrlPatterns: webResource }); return this._enabled = true; }; Inspect.prototype.disable = function() { var menuId, ref; if (!this._enabled) { return; } ref = this.propForMenuItem; for (menuId in ref) { if (!hasProp.call(ref, menuId)) continue; try { chrome.contextMenus.remove(menuId); } catch (error) {} } return this._enabled = false; }; Inspect.prototype.propForMenuItem = { 'inspectPage': 'pageUrl', 'inspectFrame': 'frameUrl', 'inspectLink': 'linkUrl', 'inspectElement': 'srcUrl' }; Inspect.prototype.inspect = function(info, tab) { var url; if (!info.menuItemId) { return; } url = info[this.propForMenuItem[info.menuItemId]]; if (!url && info.menuItemId === 'inspectPage') { url = tab.url; } if (!url) { return; } return this.onInspect(url, tab); }; return Inspect; })(); },{"omega-target":19}],26:[function(require,module,exports){ var ChromeOptions, ChromePort, OmegaPac, OmegaTarget, Promise, Url, WebRequestMonitor, fetchUrl, querystring, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty, slice = [].slice; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; Promise = OmegaTarget.Promise; querystring = require('querystring'); WebRequestMonitor = require('./web_request_monitor'); ChromePort = require('./chrome_port'); fetchUrl = require('./fetch_url'); Url = require('url'); ChromeOptions = (function(superClass) { extend(ChromeOptions, superClass); function ChromeOptions() { return ChromeOptions.__super__.constructor.apply(this, arguments); } ChromeOptions.prototype._inspect = null; ChromeOptions.prototype.fetchUrl = fetchUrl; ChromeOptions.prototype.updateProfile = function() { var args; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; return ChromeOptions.__super__.updateProfile.apply(this, args).then(function(results) { var error, profileName, result; error = false; for (profileName in results) { if (!hasProp.call(results, profileName)) continue; result = results[profileName]; if (result instanceof Error) { error = true; break; } } if (error) { /* @setBadge( text: '!' color: '#faa732' title: chrome.i18n.getMessage('browserAction_titleDownloadFail') ) */ } return results; }); }; ChromeOptions.prototype._proxyNotControllable = null; ChromeOptions.prototype.proxyNotControllable = function() { return this._proxyNotControllable; }; ChromeOptions.prototype.setProxyNotControllable = function(reason, badge) { this._proxyNotControllable = reason; if (reason) { this._state.set({ 'proxyNotControllable': reason }); return this.setBadge(badge); } else { this._state.remove(['proxyNotControllable']); return this.clearBadge(); } }; ChromeOptions.prototype._badgeTitle = null; ChromeOptions.prototype.setBadge = function(options) { if (!options) { options = this._proxyNotControllable ? { text: '=', color: '#da4f49' } : { text: '?', color: '#49afcd' }; } chrome.browserAction.setBadgeText({ text: options.text }); chrome.browserAction.setBadgeBackgroundColor({ color: options.color }); if (options.title) { this._badgeTitle = options.title; return chrome.browserAction.setTitle({ title: options.title }); } else { return this._badgeTitle = null; } }; ChromeOptions.prototype.clearBadge = function() { var base; if (this.externalApi.disabled) { return; } if (this._badgeTitle) { this.currentProfileChanged('clearBadge'); } if (this._proxyNotControllable) { this.setBadge(); } else { if (typeof (base = chrome.browserAction).setBadgeText === "function") { base.setBadgeText({ text: '' }); } } }; ChromeOptions.prototype._quickSwitchInit = false; ChromeOptions.prototype._quickSwitchHandlerReady = false; ChromeOptions.prototype._quickSwitchCanEnable = false; ChromeOptions.prototype.setQuickSwitch = function(quickSwitch, canEnable) { var base, ref; this._quickSwitchCanEnable = canEnable; if (!this._quickSwitchHandlerReady) { this._quickSwitchHandlerReady = true; window.OmegaContextMenuQuickSwitchHandler = (function(_this) { return function(info) { var changes, setOptions; changes = {}; changes['-enableQuickSwitch'] = info.checked; setOptions = _this._setOptions(changes); if (info.checked && !_this._quickSwitchCanEnable) { return setOptions.then(function() { return chrome.tabs.create({ url: chrome.extension.getURL('options.html#/ui') }); }); } }; })(this); } if (quickSwitch || (chrome.browserAction.setPopup == null)) { if (typeof (base = chrome.browserAction).setPopup === "function") { base.setPopup({ popup: '' }); } if (!this._quickSwitchInit) { this._quickSwitchInit = true; chrome.browserAction.onClicked.addListener((function(_this) { return function(tab) { var index, profiles; _this.clearBadge(); if (!_this._options['-enableQuickSwitch']) { chrome.tabs.create({ url: 'popup/index.html' }); return; } profiles = _this._options['-quickSwitchProfiles']; index = profiles.indexOf(_this._currentProfileName); index = (index + 1) % profiles.length; return _this.applyProfile(profiles[index]).then(function() { var url; if (_this._options['-refreshOnProfileChange']) { url = tab.url; if (!url) { return; } if (url.substr(0, 6) === 'chrome') { return; } if (url.substr(0, 6) === 'about:') { return; } if (url.substr(0, 4) === 'moz-') { return; } return chrome.tabs.reload(tab.id); } }); }; })(this)); } } else { chrome.browserAction.setPopup({ popup: 'popup/index.html' }); } if ((ref = chrome.contextMenus) != null) { ref.update('enableQuickSwitch', { checked: !!quickSwitch }); } return Promise.resolve(); }; ChromeOptions.prototype.setInspect = function(settings) { if (this._inspect) { if (settings.showMenu) { this._inspect.enable(); } else { this._inspect.disable(); } } return Promise.resolve(); }; ChromeOptions.prototype._requestMonitor = null; ChromeOptions.prototype._monitorWebRequests = false; ChromeOptions.prototype._tabRequestInfoPorts = null; ChromeOptions.prototype.setMonitorWebRequests = function(enabled) { var wildcardForReq; this._monitorWebRequests = enabled; if (enabled && (this._requestMonitor == null)) { this._tabRequestInfoPorts = {}; wildcardForReq = function(req) { return OmegaPac.wildcardForUrl(req.url); }; this._requestMonitor = new WebRequestMonitor(wildcardForReq); this._requestMonitor.watchTabs((function(_this) { return function(tabId, info) { var badge, ref; if (!_this._monitorWebRequests) { return; } if (info.errorCount > 0) { info.badgeSet = true; badge = { text: info.errorCount.toString(), color: '#f0ad4e' }; chrome.browserAction.setBadgeText({ text: badge.text, tabId: tabId }); chrome.browserAction.setBadgeBackgroundColor({ color: badge.color, tabId: tabId }); } else if (info.badgeSet) { info.badgeSet = false; chrome.browserAction.setBadgeText({ text: '', tabId: tabId }); } return (ref = _this._tabRequestInfoPorts[tabId]) != null ? ref.postMessage({ errorCount: info.errorCount, summary: info.summary }) : void 0; }; })(this)); return chrome.runtime.onConnect.addListener((function(_this) { return function(rawPort) { var port, tabId; if (rawPort.name !== 'tabRequestInfo') { return; } if (!_this._monitorWebRequests) { return; } tabId = null; port = new ChromePort(rawPort); port.onMessage.addListener(function(msg) { var info; tabId = msg.tabId; _this._tabRequestInfoPorts[tabId] = port; info = _this._requestMonitor.tabInfo[tabId]; if (info) { return port.postMessage({ errorCount: info.errorCount, summary: info.summary }); } }); return port.onDisconnect.addListener(function() { if (tabId != null) { return delete _this._tabRequestInfoPorts[tabId]; } }); }; })(this)); } }; ChromeOptions.prototype._alarms = null; ChromeOptions.prototype.schedule = function(name, periodInMinutes, callback) { name = 'omega.' + name; if (typeof _alarms === "undefined" || _alarms === null) { this._alarms = {}; chrome.alarms.onAlarm.addListener((function(_this) { return function(alarm) { var base, name1; return typeof (base = _this._alarms)[name1 = alarm.name] === "function" ? base[name1]() : void 0; }; })(this)); } if (periodInMinutes < 0) { delete this._alarms[name]; chrome.alarms.clear(name); } else { this._alarms[name] = callback; chrome.alarms.create(name, { periodInMinutes: periodInMinutes }); } return Promise.resolve(); }; ChromeOptions.prototype.printFixedProfile = function(profile) { var i, len, pacResult, ref, result, scheme; if (profile.profileType !== 'FixedProfile') { return; } result = ''; ref = OmegaPac.Profiles.schemes; for (i = 0, len = ref.length; i < len; i++) { scheme = ref[i]; if (!profile[scheme.prop]) { continue; } pacResult = OmegaPac.Profiles.pacResult(profile[scheme.prop]); if (scheme.scheme) { result += scheme.scheme + ": " + pacResult + "\n"; } else { result += pacResult + "\n"; } } result || (result = chrome.i18n.getMessage('browserAction_profileDetails_DirectProfile')); return result; }; ChromeOptions.prototype.printProfile = function(profile) { var type; type = profile.profileType; if (type.indexOf('RuleListProfile') >= 0) { type = 'RuleListProfile'; } if (type === 'FixedProfile') { return this.printFixedProfile(profile); } else if (type === 'PacProfile' && profile.pacUrl) { return profile.pacUrl; } else { return chrome.i18n.getMessage('browserAction_profileDetails_' + type) || null; } }; ChromeOptions.prototype.upgrade = function(options, changes) { return ChromeOptions.__super__.upgrade.call(this, options)["catch"]((function(_this) { return function(err) { var getOldOptions; if (options != null ? options['schemaVersion'] : void 0) { return Promise.reject(err); } getOldOptions = _this.switchySharp ? _this.switchySharp.getOptions().timeout(1000) : Promise.reject(); getOldOptions = getOldOptions["catch"](function() { if (options != null ? options['config'] : void 0) { return Promise.resolve(options); } else if (localStorage['config']) { return Promise.resolve(localStorage); } else { return Promise.reject(new OmegaTarget.Options.NoOptionsError()); } }); return getOldOptions.then(function(oldOptions) { var ex, i18n, upgraded; i18n = { upgrade_profile_auto: chrome.i18n.getMessage('upgrade_profile_auto') }; try { upgraded = require('./upgrade')(oldOptions, i18n); } catch (error1) { ex = error1; _this.log.error(ex); return Promise.reject(ex); } if (localStorage['config']) { Object.getPrototypeOf(localStorage).clear.call(localStorage); } _this._state.set({ 'firstRun': 'upgrade' }); return _this && ChromeOptions.__super__.upgrade.call(_this, upgraded, upgraded); }); }; })(this)); }; ChromeOptions.prototype.onFirstRun = function(reason) { return chrome.tabs.create({ url: chrome.extension.getURL('options.html') }); }; ChromeOptions.prototype.getPageInfo = function(arg) { var errorCount, getBadge, getInspectUrl, ref, ref1, result, tabId, url; tabId = arg.tabId, url = arg.url; errorCount = (ref = this._requestMonitor) != null ? (ref1 = ref.tabInfo[tabId]) != null ? ref1.errorCount : void 0 : void 0; result = errorCount ? { errorCount: errorCount } : null; getBadge = new Promise(function(resolve, reject) { if (chrome.browserAction.getBadgeText == null) { resolve(''); return; } return chrome.browserAction.getBadgeText({ tabId: tabId }, function(result) { return resolve(result); }); }); getInspectUrl = this._state.get({ inspectUrl: '' }); return Promise.join(getBadge, getInspectUrl, (function(_this) { return function(badge, arg1) { var domain, errorPagePrefix, inspectUrl; inspectUrl = arg1.inspectUrl; if (badge === '#' && inspectUrl) { url = inspectUrl; } else { _this.clearBadge(); } if (!url) { return result; } if (url.substr(0, 6) === 'chrome') { errorPagePrefix = 'chrome://errorpage/'; if (url.substr(0, errorPagePrefix.length) === errorPagePrefix) { url = querystring.parse(url.substr(url.indexOf('?') + 1)).lasturl; if (!url) { return result; } } else { return result; } } if (url.substr(0, 6) === 'about:') { return result; } if (url.substr(0, 4) === 'moz-') { return result; } domain = OmegaPac.getBaseDomain(Url.parse(url).hostname); return { url: url, domain: domain, tempRuleProfileName: _this.queryTempRule(domain), errorCount: errorCount }; }; })(this)); }; return ChromeOptions; })(OmegaTarget.Options); module.exports = ChromeOptions; },{"./chrome_port":21,"./fetch_url":23,"./upgrade":36,"./web_request_monitor":37,"omega-target":19,"querystring":15,"url":17}],27:[function(require,module,exports){ var ListenerProxyImpl, ScriptProxyImpl, SettingsProxyImpl; ListenerProxyImpl = require('./proxy_impl_listener'); SettingsProxyImpl = require('./proxy_impl_settings'); ScriptProxyImpl = require('./proxy_impl_script'); exports.proxyImpls = [ListenerProxyImpl, ScriptProxyImpl, SettingsProxyImpl]; exports.getProxyImpl = function(log) { var Impl, i, len, ref; ref = exports.proxyImpls; for (i = 0, len = ref.length; i < len; i++) { Impl = ref[i]; if (Impl.isSupported()) { return new Impl(log); } } throw new Error('Your browser does not support proxy settings!'); }; },{"./proxy_impl_listener":30,"./proxy_impl_script":31,"./proxy_impl_settings":32}],28:[function(require,module,exports){ var OmegaPac, OmegaTarget, Promise, ProxyAuth; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; Promise = OmegaTarget.Promise; module.exports = ProxyAuth = (function() { function ProxyAuth(log) { this._requests = {}; this.log = log; } ProxyAuth.prototype.listening = false; ProxyAuth.prototype.listen = function() { if (this.listening) { return; } if (!chrome.webRequest) { this.log.error('Proxy auth disabled! No webRequest permission.'); return; } if (!chrome.webRequest.onAuthRequired) { this.log.error('Proxy auth disabled! onAuthRequired not available.'); return; } chrome.webRequest.onAuthRequired.addListener(this.authHandler.bind(this), { urls: [''] }, ['blocking']); chrome.webRequest.onCompleted.addListener(this._requestDone.bind(this), { urls: [''] }); chrome.webRequest.onErrorOccurred.addListener(this._requestDone.bind(this), { urls: [''] }); return this.listening = true; }; ProxyAuth.prototype._keyForProxy = function(proxy) { return (proxy.host.toLowerCase()) + ":" + proxy.port; }; ProxyAuth.prototype.setProxies = function(profiles) { var auth, fallback, i, j, key, len, len1, list, profile, proxy, ref, ref1, ref2, results, scheme; this._proxies = {}; this._fallbacks = []; results = []; for (i = 0, len = profiles.length; i < len; i++) { profile = profiles[i]; if (!profile.auth) { continue; } ref = OmegaPac.Profiles.schemes; for (j = 0, len1 = ref.length; j < len1; j++) { scheme = ref[j]; if (!profile[scheme.prop]) { continue; } auth = (ref1 = profile.auth) != null ? ref1[scheme.prop] : void 0; if (!auth) { continue; } proxy = profile[scheme.prop]; key = this._keyForProxy(proxy); list = this._proxies[key]; if (list == null) { this._proxies[key] = list = []; } list.push({ config: proxy, auth: auth, name: profile.name + '.' + scheme.prop }); } fallback = (ref2 = profile.auth) != null ? ref2['all'] : void 0; if (fallback != null) { results.push(this._fallbacks.push({ auth: fallback, name: profile.name + '.' + 'all' })); } else { results.push(void 0); } } return results; }; ProxyAuth.prototype._proxies = {}; ProxyAuth.prototype._fallbacks = []; ProxyAuth.prototype._requests = null; ProxyAuth.prototype.authHandler = function(details) { var key, list, listLen, proxy, req; if (!details.isProxy) { return {}; } req = this._requests[details.requestId]; if (req == null) { this._requests[details.requestId] = req = { authTries: 0 }; } key = this._keyForProxy({ host: details.challenger.host, port: details.challenger.port }); list = this._proxies[key]; listLen = list != null ? list.length : 0; if (req.authTries < listLen) { proxy = list[req.authTries]; } else { proxy = this._fallbacks[req.authTries - listLen]; } this.log.log('ProxyAuth', key, req.authTries, proxy != null ? proxy.name : void 0); if (proxy == null) { return {}; } req.authTries++; return { authCredentials: proxy.auth }; }; ProxyAuth.prototype._requestDone = function(details) { return delete this._requests[details.requestId]; }; return ProxyAuth; })(); },{"omega-target":19}],29:[function(require,module,exports){ var OmegaTarget, Promise, ProxyAuth, ProxyImpl, hasProp = {}.hasOwnProperty; OmegaTarget = require('omega-target'); Promise = OmegaTarget.Promise; ProxyAuth = require('./proxy_auth'); ProxyImpl = (function() { function ProxyImpl(log) { this.log = log; } ProxyImpl.isSupported = function() { return false; }; ProxyImpl.prototype.applyProfile = function(profile, meta) { return Promise.reject(); }; ProxyImpl.prototype.watchProxyChange = function(callback) { return null; }; ProxyImpl.prototype.parseExternalProfile = function(details, options) { return null; }; ProxyImpl.prototype._profileNotFound = function(name) { this.log.error("Profile " + name + " not found! Things may go very, very wrong."); return OmegaPac.Profiles.create({ name: name, profileType: 'VirtualProfile', defaultProfileName: 'direct' }); }; ProxyImpl.prototype.setProxyAuth = function(profile, options) { return Promise["try"]((function(_this) { return function() { var _, name, ref_set, referenced_profiles; if (_this._proxyAuth == null) { _this._proxyAuth = new ProxyAuth(_this.log); } _this._proxyAuth.listen(); referenced_profiles = []; ref_set = OmegaPac.Profiles.allReferenceSet(profile, options, { profileNotFound: _this._profileNotFound.bind(_this) }); for (_ in ref_set) { if (!hasProp.call(ref_set, _)) continue; name = ref_set[_]; profile = OmegaPac.Profiles.byName(name, options); if (profile) { referenced_profiles.push(profile); } } return _this._proxyAuth.setProxies(referenced_profiles); }; })(this)); }; ProxyImpl.prototype.getProfilePacScript = function(profile, meta, options) { var ast, prefix, profileName, script; if (meta == null) { meta = profile; } ast = OmegaPac.PacGenerator.script(options, profile, { profileNotFound: this._profileNotFound.bind(this) }); ast = OmegaPac.PacGenerator.compress(ast); script = OmegaPac.PacGenerator.ascii(ast.print_to_string()); profileName = OmegaPac.PacGenerator.ascii(JSON.stringify(meta.name)); profileName = profileName.replace(/\*/g, '\\u002a'); profileName = profileName.replace(/\\/g, '\\u002f'); prefix = "/*OmegaProfile*" + profileName + "*" + meta.revision + "*/"; return prefix + script; }; return ProxyImpl; })(); module.exports = ProxyImpl; },{"./proxy_auth":28,"omega-target":19}],30:[function(require,module,exports){ var ListenerProxyImpl, NativePromise, OmegaTarget, ProxyImpl, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; OmegaTarget = require('omega-target'); NativePromise = typeof Promise !== "undefined" && Promise !== null ? Promise : null; ProxyImpl = require('./proxy_impl'); ListenerProxyImpl = (function(superClass) { extend(ListenerProxyImpl, superClass); ListenerProxyImpl.isSupported = function() { var ref; return (typeof Promise !== "undefined" && Promise !== null) && ((typeof browser !== "undefined" && browser !== null ? (ref = browser.proxy) != null ? ref.onRequest : void 0 : void 0) != null); }; ListenerProxyImpl.prototype.features = ['fullUrl', 'socks5Auth']; function ListenerProxyImpl() { ListenerProxyImpl.__super__.constructor.apply(this, arguments); this._optionsReady = new NativePromise((function(_this) { return function(resolve) { return _this._optionsReadyCallback = resolve; }; })(this)); this._initRequestListeners(); } ListenerProxyImpl.prototype._initRequestListeners = function() { browser.proxy.onRequest.addListener(this.onRequest.bind(this), { urls: [""] }); return browser.proxy.onError.addListener(this.onError.bind(this)); }; ListenerProxyImpl.prototype.watchProxyChange = function(callback) { return null; }; ListenerProxyImpl.prototype.applyProfile = function(profile, state, options) { this._options = options; this._profile = profile; if (typeof this._optionsReadyCallback === "function") { this._optionsReadyCallback(); } this._optionsReadyCallback = null; return this.setProxyAuth(profile, options); }; ListenerProxyImpl.prototype.onRequest = function(requestDetails) { return NativePromise.resolve(this._optionsReady.then((function(_this) { return function() { var auth, next, profile, proxy, request, result; request = OmegaPac.Conditions.requestFromUrl(requestDetails.url); profile = _this._profile; while (profile) { result = OmegaPac.Profiles.match(profile, request); if (!result) { switch (profile.profileType) { case 'DirectProfile': return { type: 'direct' }; case 'SystemProfile': return void 0; default: throw new Error('Unsupported profile: ' + profile.profileType); } } if (Array.isArray(result)) { proxy = result[2]; auth = result[3]; if (proxy) { return _this.proxyInfo(proxy, auth); } next = result[0]; } else if (result.profileName) { next = OmegaPac.Profiles.nameAsKey(result.profileName); } else { break; } profile = OmegaPac.Profiles.byKey(next, _this._options); } throw new Error('Profile not found: ' + next); }; })(this))); }; ListenerProxyImpl.prototype.onError = function(error) { return this.log.error(error); }; ListenerProxyImpl.prototype.proxyInfo = function(proxy, auth) { var proxyInfo; proxyInfo = { type: proxy.scheme, host: proxy.host, port: proxy.port }; if (proxyInfo.type === 'socks5') { proxyInfo.type = 'socks'; if (auth) { proxyInfo.username = auth.username; proxyInfo.password = auth.password; } } if (proxyInfo.type === 'socks') { proxyInfo.proxyDNS = true; } return [proxyInfo]; }; return ListenerProxyImpl; })(ProxyImpl); module.exports = ListenerProxyImpl; },{"./proxy_impl":29,"omega-target":19}],31:[function(require,module,exports){ var OmegaTarget, Promise, ProxyImpl, ScriptProxyImpl, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; OmegaTarget = require('omega-target'); Promise = OmegaTarget.Promise; ProxyImpl = require('./proxy_impl'); ScriptProxyImpl = (function(superClass) { extend(ScriptProxyImpl, superClass); function ScriptProxyImpl() { return ScriptProxyImpl.__super__.constructor.apply(this, arguments); } ScriptProxyImpl.isSupported = function() { var ref, ref1; return ((typeof browser !== "undefined" && browser !== null ? (ref = browser.proxy) != null ? ref.register : void 0 : void 0) != null) || ((typeof browser !== "undefined" && browser !== null ? (ref1 = browser.proxy) != null ? ref1.registerProxyScript : void 0 : void 0) != null); }; ScriptProxyImpl.prototype.features = ['socks5Auth']; ScriptProxyImpl.prototype._proxyScriptUrl = 'js/omega_webext_proxy_script.min.js'; ScriptProxyImpl.prototype._proxyScriptDisabled = false; ScriptProxyImpl.prototype._proxyScriptInitialized = false; ScriptProxyImpl.prototype._proxyScriptState = {}; ScriptProxyImpl.prototype.watchProxyChange = function(callback) { return null; }; ScriptProxyImpl.prototype.applyProfile = function(profile, state, options) { this.log.error('Your browser is outdated! Full-URL based matching, etc. unsupported! ' + "Please update your browser ASAP!"); state = state != null ? state : {}; this._options = options; state.currentProfileName = profile.name; if (profile.name === '') { state.tempProfile = profile; } if (profile.profileType === 'SystemProfile') { if (browser.proxy.unregister != null) { browser.proxy.unregister(); } else { browser.proxy.registerProxyScript('js/omega_invalid_proxy_script.js'); } this._proxyScriptDisabled = true; } else { this._proxyScriptState = state; Promise.all([browser.runtime.getBrowserInfo(), this._initWebextProxyScript()]).then((function(_this) { return function(arg) { var info; info = arg[0]; if (info.vendor === 'Mozilla' && info.buildID < '20170918220054') { _this.log.error('Your browser is outdated! SOCKS5 DNS/Auth unsupported! ' + ("Please update your browser ASAP! (Current Build " + info.buildID + ")")); _this._proxyScriptState.useLegacyStringReturn = true; } return _this._proxyScriptStateChanged(); }; })(this)); } return this.setProxyAuth(profile, options); }; ScriptProxyImpl.prototype._initWebextProxyScript = function() { var promise; if (!this._proxyScriptInitialized) { browser.proxy.onProxyError.addListener((function(_this) { return function(err) { if ((err != null ? err.message : void 0) != null) { if (err.message.indexOf('Invalid Proxy Rule: DIRECT') >= 0) { return; } if (err.message.indexOf('Return type must be a string') >= 0) { _this.log.error('Your browser is outdated! SOCKS5 DNS/Auth unsupported! ' + 'Please update your browser ASAP!'); _this._proxyScriptState.useLegacyStringReturn = true; _this._proxyScriptStateChanged(); return; } } return _this.log.error(err); }; })(this)); browser.runtime.onMessage.addListener((function(_this) { return function(message) { if (message.event !== 'proxyScriptLog') { return; } if (message.level === 'error') { return _this.log.error(message); } else if (message.level === 'warn') { return _this.log.error(message); } else { return _this.log.log(message); } }; })(this)); } if (!this._proxyScriptInitialized || this._proxyScriptDisabled) { promise = new Promise(function(resolve) { var onMessage; onMessage = function(message) { if (message.event !== 'proxyScriptLoaded') { return; } resolve(); browser.runtime.onMessage.removeListener(onMessage); }; return browser.runtime.onMessage.addListener(onMessage); }); if (browser.proxy.register != null) { browser.proxy.register(this._proxyScriptUrl); } else { browser.proxy.registerProxyScript(this._proxyScriptUrl); } this._proxyScriptDisabled = false; } else { promise = Promise.resolve(); } this._proxyScriptInitialized = true; return promise; }; ScriptProxyImpl.prototype._proxyScriptStateChanged = function() { return browser.runtime.sendMessage({ event: 'proxyScriptStateChanged', state: this._proxyScriptState, options: this._options }, { toProxyScript: true }); }; return ScriptProxyImpl; })(ProxyImpl); module.exports = ScriptProxyImpl; },{"./proxy_impl":29,"omega-target":19}],32:[function(require,module,exports){ var OmegaPac, OmegaTarget, Promise, ProxyImpl, SettingsProxyImpl, chromeApiPromisify, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; Promise = OmegaTarget.Promise; chromeApiPromisify = require('../chrome_api').chromeApiPromisify; ProxyImpl = require('./proxy_impl'); SettingsProxyImpl = (function(superClass) { extend(SettingsProxyImpl, superClass); function SettingsProxyImpl() { return SettingsProxyImpl.__super__.constructor.apply(this, arguments); } SettingsProxyImpl.isSupported = function() { var ref; return (typeof chrome !== "undefined" && chrome !== null ? (ref = chrome.proxy) != null ? ref.settings : void 0 : void 0) != null; }; SettingsProxyImpl.prototype.features = ['fullUrlHttp', 'pacScript', 'watchProxyChange']; SettingsProxyImpl.prototype.applyProfile = function(profile, meta, options) { var config; if (meta == null) { meta = profile; } if (profile.profileType === 'SystemProfile') { return chromeApiPromisify(chrome.proxy.settings, 'clear')({}).then((function(_this) { return function() { chrome.proxy.settings.get({}, _this._proxyChangeListener); }; })(this)); } config = {}; if (profile.profileType === 'DirectProfile') { config['mode'] = 'direct'; } else if (profile.profileType === 'PacProfile') { config['mode'] = 'pac_script'; config['pacScript'] = !profile.pacScript || OmegaPac.Profiles.isFileUrl(profile.pacUrl) ? { url: profile.pacUrl, mandatory: true } : { data: OmegaPac.PacGenerator.ascii(profile.pacScript), mandatory: true }; } else if (profile.profileType === 'FixedProfile') { config = this._fixedProfileConfig(profile); } else { config['mode'] = 'pac_script'; config['pacScript'] = { mandatory: true, data: this.getProfilePacScript(profile, meta, options) }; } return this.setProxyAuth(profile, options).then(function() { return chromeApiPromisify(chrome.proxy.settings, 'set')({ value: config }); }).then((function(_this) { return function() { chrome.proxy.settings.get({}, _this._proxyChangeListener); }; })(this)); }; SettingsProxyImpl.prototype._fixedProfileConfig = function(profile) { var bypassList, condition, config, j, k, l, len, len1, len2, protocol, protocolProxySet, protocols, ref, rules; config = {}; config['mode'] = 'fixed_servers'; rules = {}; protocols = ['proxyForHttp', 'proxyForHttps', 'proxyForFtp']; protocolProxySet = false; for (j = 0, len = protocols.length; j < len; j++) { protocol = protocols[j]; if (!(profile[protocol] != null)) { continue; } rules[protocol] = profile[protocol]; protocolProxySet = true; } if (profile.fallbackProxy) { if (profile.fallbackProxy.scheme === 'http') { if (!protocolProxySet) { rules['singleProxy'] = profile.fallbackProxy; } else { for (k = 0, len1 = protocols.length; k < len1; k++) { protocol = protocols[k]; if (rules[protocol] == null) { rules[protocol] = JSON.parse(JSON.stringify(profile.fallbackProxy)); } } } } else { rules['fallbackProxy'] = profile.fallbackProxy; } } else if (!protocolProxySet) { config['mode'] = 'direct'; } if (config['mode'] !== 'direct') { rules['bypassList'] = bypassList = []; ref = profile.bypassList; for (l = 0, len2 = ref.length; l < len2; l++) { condition = ref[l]; bypassList.push(this._formatBypassItem(condition)); } config['rules'] = rules; } return config; }; SettingsProxyImpl.prototype._formatBypassItem = function(condition) { var i, str; str = OmegaPac.Conditions.str(condition); i = str.indexOf(' '); return str.substr(i + 1); }; SettingsProxyImpl.prototype._proxyChangeWatchers = null; SettingsProxyImpl.prototype._proxyChangeListener = function(details) { var j, len, ref, ref1, results, watcher; ref1 = (ref = this._proxyChangeWatchers) != null ? ref : []; results = []; for (j = 0, len = ref1.length; j < len; j++) { watcher = ref1[j]; results.push(watcher(details)); } return results; }; SettingsProxyImpl.prototype.watchProxyChange = function(callback) { var ref, ref1; if (this._proxyChangeWatchers == null) { this._proxyChangeWatchers = []; if ((typeof chrome !== "undefined" && chrome !== null ? (ref = chrome.proxy) != null ? (ref1 = ref.settings) != null ? ref1.onChange : void 0 : void 0 : void 0) != null) { chrome.proxy.settings.onChange.addListener(this._proxyChangeListener.bind(this)); } } this._proxyChangeWatchers.push(callback); }; SettingsProxyImpl.prototype.parseExternalProfile = function(details, options) { var bypassCount, bypassSet, host, j, k, l, len, len1, len2, len3, m, pattern, profile, prop, props, proxies, ref, ref1, result, url; if (details.name) { return details; } switch (details.value.mode) { case 'system': return OmegaPac.Profiles.byName('system'); case 'direct': return OmegaPac.Profiles.byName('direct'); case 'auto_detect': return OmegaPac.Profiles.create({ profileType: 'PacProfile', name: '', pacUrl: 'http://wpad/wpad.dat' }); case 'pac_script': url = details.value.pacScript.url; if (url) { profile = null; OmegaPac.Profiles.each(options, function(key, p) { if (p.profileType === 'PacProfile' && p.pacUrl === url) { return profile = p; } }); return profile != null ? profile : OmegaPac.Profiles.create({ profileType: 'PacProfile', name: '', pacUrl: url }); } else { return (function() { var _, end, i, magic, profileName, revision, script, tokens; profile = null; script = details.value.pacScript.data; OmegaPac.Profiles.each(options, function(key, p) { if (p.profileType === 'PacProfile' && p.pacScript === script) { return profile = p; } }); if (profile) { return profile; } script = script.trim(); magic = '/*OmegaProfile*'; if (script.substr(0, magic.length) === magic) { end = script.indexOf('*/'); if (end > 0) { i = magic.length; tokens = script.substring(magic.length, end).split('*'); profileName = tokens[0], revision = tokens[1]; try { profileName = JSON.parse(profileName); } catch (error) { _ = error; profileName = null; } if (profileName && revision) { profile = OmegaPac.Profiles.byName(profileName, options); if (OmegaPac.Revision.compare(profile.revision, revision) === 0) { return profile; } } } } return OmegaPac.Profiles.create({ profileType: 'PacProfile', name: '', pacScript: script }); })(); } break; case 'fixed_servers': props = ['proxyForHttp', 'proxyForHttps', 'proxyForFtp', 'fallbackProxy', 'singleProxy']; proxies = {}; for (j = 0, len = props.length; j < len; j++) { prop = props[j]; result = OmegaPac.Profiles.pacResult(details.value.rules[prop]); if (prop === 'singleProxy' && (details.value.rules[prop] != null)) { proxies['fallbackProxy'] = result; } else { proxies[prop] = result; } } bypassSet = {}; bypassCount = 0; if (details.value.rules.bypassList) { ref = details.value.rules.bypassList; for (k = 0, len1 = ref.length; k < len1; k++) { pattern = ref[k]; bypassSet[pattern] = true; bypassCount++; } } if (bypassSet['']) { ref1 = OmegaPac.Conditions.localHosts; for (l = 0, len2 = ref1.length; l < len2; l++) { host = ref1[l]; if (!bypassSet[host]) { continue; } delete bypassSet[host]; bypassCount--; } } profile = null; OmegaPac.Profiles.each(options, (function(_this) { return function(key, p) { var condition, len3, len4, m, n, ref2, rules; if (p.profileType !== 'FixedProfile') { return; } if (p.bypassList.length !== bypassCount) { return; } ref2 = p.bypassList; for (m = 0, len3 = ref2.length; m < len3; m++) { condition = ref2[m]; if (!bypassSet[condition.pattern]) { return; } } rules = _this._fixedProfileConfig(p).rules; if (rules['singleProxy']) { rules['fallbackProxy'] = rules['singleProxy']; delete rules['singleProxy']; } if (rules == null) { return; } for (n = 0, len4 = props.length; n < len4; n++) { prop = props[n]; if (rules[prop] || proxies[prop]) { if (OmegaPac.Profiles.pacResult(rules[prop]) !== proxies[prop]) { return; } } } return profile = p; }; })(this)); if (profile) { return profile; } else { profile = OmegaPac.Profiles.create({ profileType: 'FixedProfile', name: '' }); for (m = 0, len3 = props.length; m < len3; m++) { prop = props[m]; if (details.value.rules[prop]) { if (prop === 'singleProxy') { profile['fallbackProxy'] = details.value.rules[prop]; } else { profile[prop] = details.value.rules[prop]; } } } profile.bypassList = (function() { var results; results = []; for (pattern in bypassSet) { if (!hasProp.call(bypassSet, pattern)) continue; results.push({ conditionType: 'BypassCondition', pattern: pattern }); } return results; })(); return profile; } } }; return SettingsProxyImpl; })(ProxyImpl); module.exports = SettingsProxyImpl; },{"../chrome_api":20,"./proxy_impl":29,"omega-target":19}],33:[function(require,module,exports){ var ChromeStorage, OmegaTarget, Promise, chromeApiPromisify, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; chromeApiPromisify = require('./chrome_api').chromeApiPromisify; OmegaTarget = require('omega-target'); Promise = OmegaTarget.Promise; ChromeStorage = (function(superClass) { extend(ChromeStorage, superClass); ChromeStorage.parseStorageErrors = function(err) { var sustainedPerMinute; if (err != null ? err.message : void 0) { sustainedPerMinute = 'MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE'; if (err.message.indexOf('QUOTA_BYTES_PER_ITEM') >= 0) { err = new OmegaTarget.Storage.QuotaExceededError(); err.perItem = true; } else if (err.message.indexOf('QUOTA_BYTES') >= 0) { err = new OmegaTarget.Storage.QuotaExceededError(); } else if (err.message.indexOf('MAX_ITEMS') >= 0) { err = new OmegaTarget.Storage.QuotaExceededError(); err.maxItems = true; } else if (err.message.indexOf('MAX_WRITE_OPERATIONS_') >= 0) { err = new OmegaTarget.Storage.RateLimitExceededError(); if (err.message.indexOf('MAX_WRITE_OPERATIONS_PER_HOUR') >= 0) { err.perHour = true; } else if (err.message.indexOf('MAX_WRITE_OPERATIONS_PER_MINUTE') >= 0) { err.perMinute = true; } } else if (err.message.indexOf(sustainedPerMinute) >= 0) { err = new OmegaTarget.Storage.RateLimitExceededError(); err.perMinute = true; err.sustained = 10; } else if (err.message.indexOf('is not available') >= 0) { err = new OmegaTarget.Storage.StorageUnavailableError(); } else if (err.message.indexOf('Please set webextensions.storage.sync.enabled to true') >= 0) { err = new OmegaTarget.Storage.StorageUnavailableError(); } } return Promise.reject(err); }; function ChromeStorage(areaName1) { var ref; this.areaName = areaName1; if (typeof browser !== "undefined" && browser !== null ? (ref = browser.storage) != null ? ref[this.areaName] : void 0 : void 0) { this.storage = browser.storage[this.areaName]; } else { this.storage = { get: chromeApiPromisify(chrome.storage[this.areaName], 'get'), set: chromeApiPromisify(chrome.storage[this.areaName], 'set'), remove: chromeApiPromisify(chrome.storage[this.areaName], 'remove'), clear: chromeApiPromisify(chrome.storage[this.areaName], 'clear') }; } } ChromeStorage.prototype.get = function(keys) { if (keys == null) { keys = null; } return Promise.resolve(this.storage.get(keys))["catch"](ChromeStorage.parseStorageErrors); }; ChromeStorage.prototype.set = function(items) { if (Object.keys(items).length === 0) { return Promise.resolve({}); } return Promise.resolve(this.storage.set(items))["catch"](ChromeStorage.parseStorageErrors); }; ChromeStorage.prototype.remove = function(keys) { if (keys == null) { return Promise.resolve(this.storage.clear()); } if (Array.isArray(keys) && keys.length === 0) { return Promise.resolve({}); } return Promise.resolve(this.storage.remove(keys))["catch"](ChromeStorage.parseStorageErrors); }; ChromeStorage.prototype.watch = function(keys, callback) { var area, base, i, id, key, keyMap, len, name, watcher; if ((base = ChromeStorage.watchers)[name = this.areaName] == null) { base[name] = {}; } area = ChromeStorage.watchers[this.areaName]; watcher = { keys: keys, callback: callback }; id = Date.now().toString(); while (area[id]) { id = Date.now().toString(); } if (Array.isArray(keys)) { keyMap = {}; for (i = 0, len = keys.length; i < len; i++) { key = keys[i]; keyMap[key] = true; } keys = keyMap; } area[id] = { keys: keys, callback: callback }; if (!ChromeStorage.onChangedListenerInstalled) { chrome.storage.onChanged.addListener(ChromeStorage.onChangedListener); ChromeStorage.onChangedListenerInstalled = true; } return function() { return delete area[id]; }; }; ChromeStorage.onChangedListener = function(changes, areaName) { var _, change, key, map, match, ref, results, watcher; map = null; ref = ChromeStorage.watchers[areaName]; results = []; for (_ in ref) { watcher = ref[_]; match = watcher.keys === null; if (!match) { for (key in changes) { if (!hasProp.call(changes, key)) continue; if (watcher.keys[key]) { match = true; break; } } } if (match) { if (map == null) { map = {}; for (key in changes) { if (!hasProp.call(changes, key)) continue; change = changes[key]; map[key] = change.newValue; } } results.push(watcher.callback(map)); } else { results.push(void 0); } } return results; }; ChromeStorage.onChangedListenerInstalled = false; ChromeStorage.watchers = {}; return ChromeStorage; })(OmegaTarget.Storage); module.exports = ChromeStorage; },{"./chrome_api":20,"omega-target":19}],34:[function(require,module,exports){ var ChromePort, OmegaPac, OmegaTarget, Promise, SwitchySharp; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; Promise = OmegaTarget.Promise; ChromePort = require('./chrome_port'); module.exports = SwitchySharp = (function() { function SwitchySharp() {} SwitchySharp.extId = 'dpplabbmogkhghncfbfdeeokoefdjegm'; SwitchySharp.prototype.port = null; SwitchySharp.prototype.monitor = function(action) { if (location.href.substr(0, 4) === 'moz-') { return; } if ((typeof port === "undefined" || port === null) && (this._monitorTimerId == null)) { this._monitorTimerId = setInterval(this._connect.bind(this), 5000); if (action !== 'reconnect') { return this._connect(); } } }; SwitchySharp.prototype.getOptions = function() { if (!this._getOptions) { this._getOptions = new Promise((function(_this) { return function(resolve) { _this._getOptionsResolver = resolve; return _this.monitor(); }; })(this)); } return this._getOptions; }; SwitchySharp.prototype._getOptions = null; SwitchySharp.prototype._getOptionsResolver = null; SwitchySharp.prototype._monitorTimerId = null; SwitchySharp.prototype._onMessage = function(msg) { if (this._monitorTimerId) { clearInterval(this._monitorTimerId); this._monitorTimerId = null; } switch (msg != null ? msg.action : void 0) { case 'state': OmegaTarget.Log.log(msg); if (this._getOptionsResolver) { return this.port.postMessage({ action: 'getOptions' }); } break; case 'options': if (typeof this._getOptionsResolver === "function") { this._getOptionsResolver(msg.options); } return this._getOptionsResolver = null; } }; SwitchySharp.prototype._onDisconnect = function(msg) { this.port = null; this._getOptions = null; this._getOptionsResolver = null; return this.monitor('reconnect'); }; SwitchySharp.prototype._connect = function() { var _, ref; if (!this.port) { this.port = new ChromePort(chrome.runtime.connect(SwitchySharp.extId)); this.port.onDisconnect.addListener(this._onDisconnect.bind(this)); if ((ref = this.port) != null) { ref.onMessage.addListener(this._onMessage.bind(this)); } } try { this.port.postMessage({ action: 'disable' }); } catch (error) { _ = error; this.port = null; } return this.port != null; }; return SwitchySharp; })(); },{"./chrome_port":21,"omega-target":19}],35:[function(require,module,exports){ var ChromeTabs, hasProp = {}.hasOwnProperty; ChromeTabs = (function() { ChromeTabs.prototype._defaultAction = null; ChromeTabs.prototype._badgeTab = null; function ChromeTabs(actionForUrl) { this.actionForUrl = actionForUrl; this._dirtyTabs = {}; return; } ChromeTabs.prototype.ignoreError = function() { chrome.runtime.lastError; }; ChromeTabs.prototype.watch = function() { chrome.tabs.onUpdated.addListener(this.onUpdated.bind(this)); return chrome.tabs.onActivated.addListener((function(_this) { return function(info) { return chrome.tabs.get(info.tabId, function(tab) { if (chrome.runtime.lastError) { return; } if (_this._dirtyTabs.hasOwnProperty(info.tabId)) { return _this.onUpdated(tab.id, {}, tab); } }); }; })(this)); }; ChromeTabs.prototype.resetAll = function(action) { this._defaultAction = action; chrome.tabs.query({}, (function(_this) { return function(tabs) { _this._dirtyTabs = {}; return tabs.forEach(function(tab) { _this._dirtyTabs[tab.id] = tab.id; if (tab.active) { return _this.onUpdated(tab.id, {}, tab); } }); }; })(this)); if (chrome.browserAction.setPopup != null) { chrome.browserAction.setTitle({ title: action.title }); } else { chrome.browserAction.setTitle({ title: action.shortTitle }); } return this.setIcon(action.icon); }; ChromeTabs.prototype.onUpdated = function(tabId, changeInfo, tab) { if (this._dirtyTabs.hasOwnProperty(tab.id)) { delete this._dirtyTabs[tab.id]; } else if (changeInfo.url == null) { if ((changeInfo.status != null) && changeInfo.status !== 'loading') { return; } } return this.processTab(tab, changeInfo); }; ChromeTabs.prototype.processTab = function(tab, changeInfo) { var base, id, ref; if (this._badgeTab) { ref = this._badgeTab; for (id in ref) { if (!hasProp.call(ref, id)) continue; try { if (typeof (base = chrome.browserAction).setBadgeText === "function") { base.setBadgeText({ text: '', tabId: id }); } } catch (error) {} this._badgeTab = null; } } if ((tab.url == null) || tab.url.indexOf("chrome") === 0) { if (this._defaultAction) { chrome.browserAction.setTitle({ title: this._defaultAction.title, tabId: tab.id }); this.clearIcon(tab.id); } return; } return this.actionForUrl(tab.url).then((function(_this) { return function(action) { if (!action) { _this.clearIcon(tab.id); return; } _this.setIcon(action.icon, tab.id); if (chrome.browserAction.setPopup != null) { return chrome.browserAction.setTitle({ title: action.title, tabId: tab.id }); } else { return chrome.browserAction.setTitle({ title: action.shortTitle, tabId: tab.id }); } }; })(this)); }; ChromeTabs.prototype.setTabBadge = function(tab, badge) { var base, base1; if (this._badgeTab == null) { this._badgeTab = {}; } this._badgeTab[tab.id] = true; if (typeof (base = chrome.browserAction).setBadgeText === "function") { base.setBadgeText({ text: badge.text, tabId: tab.id }); } return typeof (base1 = chrome.browserAction).setBadgeBackgroundColor === "function" ? base1.setBadgeBackgroundColor({ color: badge.color, tabId: tab.id }) : void 0; }; ChromeTabs.prototype.setIcon = function(icon, tabId) { var params; if (icon == null) { return; } if (tabId != null) { params = { imageData: icon, tabId: tabId }; } else { params = { imageData: icon }; } return this._chromeSetIcon(params); }; ChromeTabs.prototype._chromeSetIcon = function(params) { var _, base, base1; try { return typeof (base = chrome.browserAction).setIcon === "function" ? base.setIcon(params, this.ignoreError) : void 0; } catch (error) { _ = error; params.imageData = { 19: params.imageData[19], 38: params.imageData[38] }; return typeof (base1 = chrome.browserAction).setIcon === "function" ? base1.setIcon(params, this.ignoreError) : void 0; } }; ChromeTabs.prototype.clearIcon = function(tabId) { var ref; if (((ref = this._defaultAction) != null ? ref.icon : void 0) == null) { return; } return this._chromeSetIcon({ imageData: this._defaultAction.icon, tabId: tabId }, this.ignoreError); }; return ChromeTabs; })(); module.exports = ChromeTabs; },{}],36:[function(require,module,exports){ var OmegaPac, OmegaTarget, hasProp = {}.hasOwnProperty; OmegaTarget = require('omega-target'); OmegaPac = OmegaTarget.OmegaPac; module.exports = function(oldOptions, i18n) { var Buffer, _, auto, boolItems, color, colorTranslations, conditionFromRule, config, defaultRule, exampleFixedProfileName, haslocalPattern, key, name, nameMap, num, oldKey, oldProfile, oldProfiles, options, profile, protocol, quickSwitch, ref, ref1, rule, rulelist, rules, seenFixedProfile, startupId, text, url; config = (function() { try { return JSON.parse(oldOptions['config']); } catch (error) {} })(); if (config) { options = typeof changes !== "undefined" && changes !== null ? changes : {}; options['schemaVersion'] = 2; boolItems = { '-confirmDeletion': 'confirmDeletion', '-refreshOnProfileChange': 'refreshTab', '-enableQuickSwitch': 'quickSwitch', '-revertProxyChanges': 'preventProxyChanges' }; for (key in boolItems) { if (!hasProp.call(boolItems, key)) continue; oldKey = boolItems[key]; options[key] = !!config[oldKey]; } options['-downloadInterval'] = parseInt(config['ruleListReload']) || 15; auto = OmegaPac.Profiles.create({ profileType: 'SwitchProfile', name: i18n.upgrade_profile_auto, color: '#55bb55', defaultProfileName: 'direct' }); OmegaPac.Profiles.updateRevision(auto); options[OmegaPac.Profiles.nameAsKey(auto.name)] = auto; rulelist = OmegaPac.Profiles.create({ profileType: 'RuleListProfile', name: '__ruleListOf_' + auto.name, color: '#dd6633', format: config['ruleListAutoProxy'] ? 'AutoProxy' : 'Switchy', defaultProfileName: 'direct', sourceUrl: config['ruleListUrl'] || '' }); options[OmegaPac.Profiles.nameAsKey(rulelist.name)] = rulelist; auto.defaultProfileName = rulelist.name; nameMap = { 'auto': auto.name, 'direct': 'direct' }; oldProfiles = ((function() { try { return JSON.parse(oldOptions['profiles']); } catch (error) {} })()) || {}; colorTranslations = { 'blue': '#99ccee', 'green': '#99dd99', 'red': '#ffaa88', 'yellow': '#ffee99', 'purple': '#d497ee', '': '#99ccee' }; seenFixedProfile = false; for (_ in oldProfiles) { if (!hasProp.call(oldProfiles, _)) continue; oldProfile = oldProfiles[_]; profile = null; switch (oldProfile['proxyMode']) { case 'auto': profile = OmegaPac.Profiles.create({ profileType: 'PacProfile' }); url = oldProfile['proxyConfigUrl']; if (url.substr(0, 5) === 'data:') { text = url.substr(url.indexOf(',') + 1); Buffer = require('buffer').Buffer; text = new Buffer(text, 'base64').toString('utf8'); profile.pacScript = text; } else { profile.pacUrl = url; } break; case 'manual': seenFixedProfile = true; profile = OmegaPac.Profiles.create({ profileType: 'FixedProfile' }); if (!!oldProfile['useSameProxy']) { profile.fallbackProxy = OmegaPac.Profiles.parseHostPort(oldProfile['proxyHttp'], 'http'); } else if (oldProfile['proxySocks']) { protocol = oldProfile['socksVersion'] === 5 ? 'socks5' : 'socks4'; profile.fallbackProxy = OmegaPac.Profiles.parseHostPort(oldProfile['proxySocks'], protocol); } else { profile.proxyForHttp = OmegaPac.Profiles.parseHostPort(oldProfile['proxyHttp'], 'http'); profile.proxyForHttps = OmegaPac.Profiles.parseHostPort(oldProfile['proxyHttps'], 'http'); profile.proxyForFtp = OmegaPac.Profiles.parseHostPort(oldProfile['proxyFtp'], 'http'); } if (oldProfile['proxyExceptions'] != null) { haslocalPattern = false; profile.bypassList = []; oldProfile['proxyExceptions'].split(';').forEach(function(line) { line = line.trim(); if (!line) { return; } if (line === '') { haslocalPattern = true; } return profile.bypassList.push({ conditionType: 'BypassCondition', pattern: line }); }); if (haslocalPattern) { profile.bypassList = profile.bypassList.filter(function(cond) { return OmegaPac.Conditions.localHosts.indexOf(cond.pattern) < 0; }); } } } if (profile) { color = oldProfile['color']; profile.color = (ref = colorTranslations[color]) != null ? ref : colorTranslations['']; name = (ref1 = oldProfile['name']) != null ? ref1 : oldProfile['id']; name = name.trim(); if (name[0] === '_') { name = 'p' + name; } profile.name = name; num = 1; while (OmegaPac.Profiles.byName(profile.name, options)) { profile.name = name + num; num++; } nameMap[oldProfile['id']] = profile.name; OmegaPac.Profiles.updateRevision(profile); options[OmegaPac.Profiles.nameAsKey(profile.name)] = profile; } } if (!seenFixedProfile) { exampleFixedProfileName = 'Example Profile'; options[OmegaPac.Profiles.nameAsKey(exampleFixedProfileName)] = { bypassList: [ { pattern: "127.0.0.1", conditionType: "BypassCondition" }, { pattern: "::1", conditionType: "BypassCondition" }, { pattern: "localhost", conditionType: "BypassCondition" } ], profileType: "FixedProfile", name: exampleFixedProfileName, color: "#99ccee", fallbackProxy: { port: 8080, scheme: "http", host: "proxy.example.com" } }; } startupId = config['startupProfileId']; options['-startupProfileName'] = nameMap[startupId] || ''; quickSwitch = (function() { try { return JSON.parse(oldOptions['quickSwitchProfiles']); } catch (error) {} })(); options['-quickSwitchProfiles'] = quickSwitch == null ? [] : quickSwitch.map(function(p) { return nameMap[p]; }); if (config['ruleListProfileId']) { rulelist.matchProfileName = nameMap[config['ruleListProfileId']] || 'direct'; } defaultRule = (function() { try { return JSON.parse(oldOptions['defaultRule']); } catch (error) {} })(); if (defaultRule) { rulelist.defaultProfileName = nameMap[defaultRule.profileId] || 'direct'; if (!config.ruleListEnabled) { auto.defaultProfileName = rulelist.defaultProfileName; } } OmegaPac.Profiles.updateRevision(rulelist); rules = (function() { try { return JSON.parse(oldOptions['rules']); } catch (error) {} })(); if (rules) { conditionFromRule = function(rule) { var pattern; switch (rule['patternType']) { case 'wildcard': pattern = rule['urlPattern']; return OmegaPac.RuleList['Switchy'].conditionFromLegacyWildcard(pattern); default: return { conditionType: 'UrlRegexCondition', pattern: rule['urlPattern'] }; } }; auto.rules = (function() { var results; results = []; for (_ in rules) { if (!hasProp.call(rules, _)) continue; rule = rules[_]; results.push({ profileName: nameMap[rule['profileId']] || 'direct', condition: conditionFromRule(rule), note: rule.name }); } return results; })(); } return options; } }; },{"buffer":2,"omega-target":19}],37:[function(require,module,exports){ var Heap, Url, WebRequestMonitor, hasProp = {}.hasOwnProperty; Heap = require('heap'); Url = require('url'); module.exports = WebRequestMonitor = (function() { function WebRequestMonitor(getSummaryId) { this.getSummaryId = getSummaryId; this._requests = {}; this._recentRequests = new Heap(function(a, b) { return a._startTime - b._startTime; }); this._callbacks = []; this._tabCallbacks = []; this.tabInfo = {}; } WebRequestMonitor.prototype._callbacks = null; WebRequestMonitor.prototype.watching = false; WebRequestMonitor.prototype.timer = null; WebRequestMonitor.prototype.watch = function(callback) { this._callbacks.push(callback); if (this.watching) { return; } if (!chrome.webRequest) { console.log('Request monitor disabled! No webRequest permission.'); return; } chrome.webRequest.onBeforeRequest.addListener(this._requestStart.bind(this), { urls: [''] }); chrome.webRequest.onHeadersReceived.addListener(this._requestHeadersReceived.bind(this), { urls: [''] }); chrome.webRequest.onBeforeRedirect.addListener(this._requestRedirected.bind(this), { urls: [''] }); chrome.webRequest.onCompleted.addListener(this._requestDone.bind(this), { urls: [''] }); chrome.webRequest.onErrorOccurred.addListener(this._requestError.bind(this), { urls: [''] }); return this.watching = true; }; WebRequestMonitor.prototype._requests = null; WebRequestMonitor.prototype._recentRequests = null; WebRequestMonitor.prototype._requestStart = function(req) { var callback, i, len, ref, results; if (req.tabId < 0) { return; } req._startTime = Date.now(); this._requests[req.requestId] = req; this._recentRequests.push(req); if (this.timer == null) { this.timer = setInterval(this._tick.bind(this), 1000); } ref = this._callbacks; results = []; for (i = 0, len = ref.length; i < len; i++) { callback = ref[i]; results.push(callback('start', req)); } return results; }; WebRequestMonitor.prototype._tick = function() { var callback, i, len, now, ref, req, reqInfo, results; now = Date.now(); results = []; while ((req = this._recentRequests.peek())) { reqInfo = this._requests[req.requestId]; if (reqInfo && !reqInfo.noTimeout) { if (now - req._startTime < 5000) { break; } else { reqInfo.timeoutCalled = true; ref = this._callbacks; for (i = 0, len = ref.length; i < len; i++) { callback = ref[i]; callback('timeout', reqInfo); } } } results.push(this._recentRequests.pop()); } return results; }; WebRequestMonitor.prototype._requestHeadersReceived = function(req) { var callback, i, len, ref, reqInfo, results; reqInfo = this._requests[req.requestId]; if (!reqInfo) { return; } reqInfo.noTimeout = true; if (reqInfo.timeoutCalled) { ref = this._callbacks; results = []; for (i = 0, len = ref.length; i < len; i++) { callback = ref[i]; results.push(callback('ongoing', req)); } return results; } }; WebRequestMonitor.prototype._requestRedirected = function(req) { var url; url = req.redirectUrl; if (!url) { return; } if (url.indexOf('data:') === 0 || url.indexOf('about:') === 0) { return this._requestDone(req); } }; WebRequestMonitor.prototype._requestError = function(req) { var callback, i, j, len, len1, ref, ref1, reqInfo, results; reqInfo = this._requests[req.requestId]; delete this._requests[req.requestId]; if (req.tabId < 0) { return; } if (req.error === 'net::ERR_INCOMPLETE_CHUNKED_ENCODING') { return; } if (req.error.indexOf('BLOCKED') >= 0) { return; } if (req.error.indexOf('net::ERR_FILE_') === 0) { return; } if (req.error.indexOf('NS_ERROR_ABORT') === 0) { return; } if (req.url.indexOf('file:') === 0) { return; } if (req.url.indexOf('chrome') === 0) { return; } if (req.url.indexOf('about:') === 0) { return; } if (req.url.indexOf('moz-') === 0) { return; } if (req.url.indexOf('://127.0.0.1') > 0) { return; } if (!reqInfo) { return; } if (req.error === 'net::ERR_ABORTED') { if (reqInfo.timeoutCalled && !reqInfo.noTimeout) { ref = this._callbacks; for (i = 0, len = ref.length; i < len; i++) { callback = ref[i]; callback('timeoutAbort', req); } } return; } ref1 = this._callbacks; results = []; for (j = 0, len1 = ref1.length; j < len1; j++) { callback = ref1[j]; results.push(callback('error', req)); } return results; }; WebRequestMonitor.prototype._requestDone = function(req) { var callback, i, len, ref; ref = this._callbacks; for (i = 0, len = ref.length; i < len; i++) { callback = ref[i]; callback('done', req); } return delete this._requests[req.requestId]; }; WebRequestMonitor.prototype.eventCategory = { start: 'ongoing', ongoing: 'ongoing', timeout: 'error', error: 'error', timeoutAbort: 'error', done: 'done' }; WebRequestMonitor.prototype.tabsWatching = false; WebRequestMonitor.prototype._tabCallbacks = null; WebRequestMonitor.prototype.watchTabs = function(callback) { var ref; this._tabCallbacks.push(callback); if (this.tabsWatching) { return; } this.watch(this.setTabRequestInfo.bind(this)); this.tabsWatching = true; chrome.tabs.onCreated.addListener((function(_this) { return function(tab) { if (!tab.id) { return; } return _this.tabInfo[tab.id] = _this._newTabInfo(); }; })(this)); chrome.tabs.onRemoved.addListener((function(_this) { return function(tab) { return delete _this.tabInfo[tab.id]; }; })(this)); if ((ref = chrome.tabs.onReplaced) != null) { ref.addListener((function(_this) { return function(added, removed) { var base; if ((base = _this.tabInfo)[added] == null) { base[added] = _this._newTabInfo(); } return delete _this.tabInfo[removed]; }; })(this)); } chrome.tabs.onUpdated.addListener((function(_this) { return function(tabId, changeInfo, tab) { var base, i, info, len, name, ref1, results; info = (base = _this.tabInfo)[name = tab.id] != null ? base[name] : base[name] = _this._newTabInfo(); if (!info) { return; } ref1 = _this._tabCallbacks; results = []; for (i = 0, len = ref1.length; i < len; i++) { callback = ref1[i]; results.push(callback(tab.id, info, null, 'updated')); } return results; }; })(this)); return chrome.tabs.query({}, (function(_this) { return function(tabs) { var base, i, len, name, results, tab; results = []; for (i = 0, len = tabs.length; i < len; i++) { tab = tabs[i]; results.push((base = _this.tabInfo)[name = tab.id] != null ? base[name] : base[name] = _this._newTabInfo()); } return results; }; })(this)); }; WebRequestMonitor.prototype._newTabInfo = function() { return { requests: {}, requestCount: 0, requestStatus: {}, ongoingCount: 0, errorCount: 0, doneCount: 0, summary: {} }; }; WebRequestMonitor.prototype.setTabRequestInfo = function(status, req) { var callback, i, id, info, key, len, oldStatus, ref, ref1, results, summaryItem, value; info = this.tabInfo[req.tabId]; if (info) { if (status === 'start' && req.type === 'main_frame') { if (req.url.indexOf('chrome://errorpage/') !== 0) { ref = this._newTabInfo(); for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; info[key] = value; } } } if (info.requestCount > 1000) { return; } info.requests[req.requestId] = req; if ((oldStatus = info.requestStatus[req.requestId])) { info[this.eventCategory[oldStatus] + 'Count']--; } else { if (status === 'timeoutAbort') { return; } info.requestCount++; } info.requestStatus[req.requestId] = status; info[this.eventCategory[status] + 'Count']++; id = typeof this.getSummaryId === "function" ? this.getSummaryId(req) : void 0; if (id != null) { if (this.eventCategory[status] === 'error') { if (this.eventCategory[oldStatus] !== 'error') { summaryItem = info.summary[id]; if (summaryItem == null) { summaryItem = info.summary[id] = { errorCount: 0 }; } summaryItem.errorCount++; } } else if (this.eventCategory[oldStatus] === 'error') { summaryItem = info.summary[id]; if (summaryItem != null) { summaryItem.errorCount--; } } } ref1 = this._tabCallbacks; results = []; for (i = 0, len = ref1.length; i < len; i++) { callback = ref1[i]; results.push(callback(req.tabId, info, req, status)); } return results; } }; return WebRequestMonitor; })(); },{"heap":6,"url":17}],"OmegaTargetChromium":[function(require,module,exports){ module.exports = require('./src/module'); },{"./src/module":24}]},{},["OmegaTargetChromium"])("OmegaTargetChromium") });