UNPKG

leaflet-mapbox-vector-tile

Version:

A Leaflet Plugin that renders Mapbox Vector Tiles on HTML5 Canvas.

1,748 lines (1,467 loc) 721 kB
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (Buffer){ 'use strict'; var ieee754 = require('ieee754'); module.exports = Protobuf; function Protobuf(buf) { this.buf = buf; this.pos = 0; } Protobuf.prototype = { get length() { return this.buf.length; } }; Protobuf.Varint = 0; Protobuf.Int64 = 1; Protobuf.Message = 2; Protobuf.String = 2; Protobuf.Packed = 2; Protobuf.Int32 = 5; Protobuf.prototype.destroy = function() { this.buf = null; }; // === READING ================================================================= Protobuf.prototype.readUInt32 = function() { var val = this.buf.readUInt32LE(this.pos); this.pos += 4; return val; }; Protobuf.prototype.readUInt64 = function() { var val = this.buf.readUInt64LE(this.pos); this.pos += 8; return val; }; Protobuf.prototype.readDouble = function() { var val = ieee754.read(this.buf, this.pos, true, 52, 8); this.pos += 8; return val; }; Protobuf.prototype.readVarint = function() { // TODO: bounds checking var pos = this.pos; if (this.buf[pos] <= 0x7f) { this.pos++; return this.buf[pos]; } else if (this.buf[pos + 1] <= 0x7f) { this.pos += 2; return (this.buf[pos] & 0x7f) | (this.buf[pos + 1] << 7); } else if (this.buf[pos + 2] <= 0x7f) { this.pos += 3; return (this.buf[pos] & 0x7f) | (this.buf[pos + 1] & 0x7f) << 7 | (this.buf[pos + 2]) << 14; } else if (this.buf[pos + 3] <= 0x7f) { this.pos += 4; return (this.buf[pos] & 0x7f) | (this.buf[pos + 1] & 0x7f) << 7 | (this.buf[pos + 2] & 0x7f) << 14 | (this.buf[pos + 3]) << 21; } else if (this.buf[pos + 4] <= 0x7f) { this.pos += 5; return ((this.buf[pos] & 0x7f) | (this.buf[pos + 1] & 0x7f) << 7 | (this.buf[pos + 2] & 0x7f) << 14 | (this.buf[pos + 3]) << 21) + (this.buf[pos + 4] * 268435456); } else { this.skip(Protobuf.Varint); return 0; // throw new Error("TODO: Handle 6+ byte varints"); } }; Protobuf.prototype.readSVarint = function() { var num = this.readVarint(); if (num > 2147483647) throw new Error('TODO: Handle numbers >= 2^30'); // zigzag encoding return ((num >> 1) ^ -(num & 1)); }; Protobuf.prototype.readString = function() { var bytes = this.readVarint(); // TODO: bounds checking var chr = String.fromCharCode; var b = this.buf; var p = this.pos; var end = this.pos + bytes; var str = ''; while (p < end) { if (b[p] <= 0x7F) str += chr(b[p++]); else if (b[p] <= 0xBF) throw new Error('Invalid UTF-8 codepoint: ' + b[p]); else if (b[p] <= 0xDF) str += chr((b[p++] & 0x1F) << 6 | (b[p++] & 0x3F)); else if (b[p] <= 0xEF) str += chr((b[p++] & 0x1F) << 12 | (b[p++] & 0x3F) << 6 | (b[p++] & 0x3F)); else if (b[p] <= 0xF7) p += 4; // We can't handle these codepoints in JS, so skip. else if (b[p] <= 0xFB) p += 5; else if (b[p] <= 0xFD) p += 6; else throw new Error('Invalid UTF-8 codepoint: ' + b[p]); } this.pos += bytes; return str; }; Protobuf.prototype.readBuffer = function() { var bytes = this.readVarint(); var buffer = this.buf.subarray(this.pos, this.pos + bytes); this.pos += bytes; return buffer; }; Protobuf.prototype.readPacked = function(type) { // TODO: bounds checking var bytes = this.readVarint(); var end = this.pos + bytes; var array = []; while (this.pos < end) { array.push(this['read' + type]()); } return array; }; Protobuf.prototype.skip = function(val) { // TODO: bounds checking var type = val & 0x7; switch (type) { /* varint */ case Protobuf.Varint: while (this.buf[this.pos++] > 0x7f); break; /* 64 bit */ case Protobuf.Int64: this.pos += 8; break; /* length */ case Protobuf.Message: var bytes = this.readVarint(); this.pos += bytes; break; /* 32 bit */ case Protobuf.Int32: this.pos += 4; break; default: throw new Error('Unimplemented type: ' + type); } }; // === WRITING ================================================================= Protobuf.prototype.writeTag = function(tag, type) { this.writeVarint((tag << 3) | type); }; Protobuf.prototype.realloc = function(min) { var length = this.buf.length; while (length < this.pos + min) length *= 2; if (length != this.buf.length) { var buf = new Buffer(length); this.buf.copy(buf); this.buf = buf; } }; Protobuf.prototype.finish = function() { return this.buf.slice(0, this.pos); }; Protobuf.prototype.writePacked = function(type, tag, items) { if (!items.length) return; var message = new Protobuf(); for (var i = 0; i < items.length; i++) { message['write' + type](items[i]); } var data = message.finish(); this.writeTag(tag, Protobuf.Packed); this.writeBuffer(data); }; Protobuf.prototype.writeUInt32 = function(val) { this.realloc(4); this.buf.writeUInt32LE(val, this.pos); this.pos += 4; }; Protobuf.prototype.writeTaggedUInt32 = function(tag, val) { this.writeTag(tag, Protobuf.Int32); this.writeUInt32(val); }; Protobuf.prototype.writeVarint = function(val) { val = Number(val); if (isNaN(val)) { val = 0; } if (val <= 0x7f) { this.realloc(1); this.buf[this.pos++] = val; } else if (val <= 0x3fff) { this.realloc(2); this.buf[this.pos++] = 0x80 | ((val >>> 0) & 0x7f); this.buf[this.pos++] = 0x00 | ((val >>> 7) & 0x7f); } else if (val <= 0x1ffffff) { this.realloc(3); this.buf[this.pos++] = 0x80 | ((val >>> 0) & 0x7f); this.buf[this.pos++] = 0x80 | ((val >>> 7) & 0x7f); this.buf[this.pos++] = 0x00 | ((val >>> 14) & 0x7f); } else if (val <= 0xfffffff) { this.realloc(4); this.buf[this.pos++] = 0x80 | ((val >>> 0) & 0x7f); this.buf[this.pos++] = 0x80 | ((val >>> 7) & 0x7f); this.buf[this.pos++] = 0x80 | ((val >>> 14) & 0x7f); this.buf[this.pos++] = 0x00 | ((val >>> 21) & 0x7f); } else { while (val > 0) { var b = val & 0x7f; val = Math.floor(val / 128); if (val > 0) b |= 0x80 this.realloc(1); this.buf[this.pos++] = b; } } }; Protobuf.prototype.writeTaggedVarint = function(tag, val) { this.writeTag(tag, Protobuf.Varint); this.writeVarint(val); }; Protobuf.prototype.writeSVarint = function(val) { if (val >= 0) { this.writeVarint(val * 2); } else { this.writeVarint(val * -2 - 1); } }; Protobuf.prototype.writeTaggedSVarint = function(tag, val) { this.writeTag(tag, Protobuf.Varint); this.writeSVarint(val); }; Protobuf.prototype.writeBoolean = function(val) { this.writeVarint(Boolean(val)); }; Protobuf.prototype.writeTaggedBoolean = function(tag, val) { this.writeTaggedVarint(tag, Boolean(val)); }; Protobuf.prototype.writeString = function(str) { str = String(str); var bytes = Buffer.byteLength(str); this.writeVarint(bytes); this.realloc(bytes); this.buf.write(str, this.pos); this.pos += bytes; }; Protobuf.prototype.writeTaggedString = function(tag, str) { this.writeTag(tag, Protobuf.String); this.writeString(str); }; Protobuf.prototype.writeFloat = function(val) { this.realloc(4); this.buf.writeFloatLE(val, this.pos); this.pos += 4; }; Protobuf.prototype.writeTaggedFloat = function(tag, val) { this.writeTag(tag, Protobuf.Int32); this.writeFloat(val); }; Protobuf.prototype.writeDouble = function(val) { this.realloc(8); this.buf.writeDoubleLE(val, this.pos); this.pos += 8; }; Protobuf.prototype.writeTaggedDouble = function(tag, val) { this.writeTag(tag, Protobuf.Int64); this.writeDouble(val); }; Protobuf.prototype.writeBuffer = function(buffer) { var bytes = buffer.length; this.writeVarint(bytes); this.realloc(bytes); buffer.copy(this.buf, this.pos); this.pos += bytes; }; Protobuf.prototype.writeTaggedBuffer = function(tag, buffer) { this.writeTag(tag, Protobuf.String); this.writeBuffer(buffer); }; Protobuf.prototype.writeMessage = function(tag, protobuf) { var buffer = protobuf.finish(); this.writeTag(tag, Protobuf.Message); this.writeBuffer(buffer); }; }).call(this,require("buffer").Buffer) },{"buffer":77,"ieee754":2}],2:[function(require,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, 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, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, 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; }; },{}],3:[function(require,module,exports){ 'use strict'; module.exports = Point; function Point(x, y) { this.x = x; this.y = y; } Point.prototype = { clone: function() { return new Point(this.x, this.y); }, add: function(p) { return this.clone()._add(p); }, sub: function(p) { return this.clone()._sub(p); }, mult: function(k) { return this.clone()._mult(k); }, div: function(k) { return this.clone()._div(k); }, rotate: function(a) { return this.clone()._rotate(a); }, matMult: function(m) { return this.clone()._matMult(m); }, unit: function() { return this.clone()._unit(); }, perp: function() { return this.clone()._perp(); }, round: function() { return this.clone()._round(); }, mag: function() { return Math.sqrt(this.x * this.x + this.y * this.y); }, equals: function(p) { return this.x === p.x && this.y === p.y; }, dist: function(p) { return Math.sqrt(this.distSqr(p)); }, distSqr: function(p) { var dx = p.x - this.x, dy = p.y - this.y; return dx * dx + dy * dy; }, angle: function() { return Math.atan2(this.y, this.x); }, angleTo: function(b) { return Math.atan2(this.y - b.y, this.x - b.x); }, angleWith: function(b) { return this.angleWithSep(b.x, b.y); }, // Find the angle of the two vectors, solving the formula for the cross product a x b = |a||b|sin(θ) for θ. angleWithSep: function(x, y) { return Math.atan2( this.x * y - this.y * x, this.x * x + this.y * y); }, _matMult: function(m) { var x = m[0] * this.x + m[1] * this.y, y = m[2] * this.x + m[3] * this.y; this.x = x; this.y = y; return this; }, _add: function(p) { this.x += p.x; this.y += p.y; return this; }, _sub: function(p) { this.x -= p.x; this.y -= p.y; return this; }, _mult: function(k) { this.x *= k; this.y *= k; return this; }, _div: function(k) { this.x /= k; this.y /= k; return this; }, _unit: function() { this._div(this.mag()); return this; }, _perp: function() { var y = this.y; this.y = this.x; this.x = -y; return this; }, _rotate: function(angle) { var cos = Math.cos(angle), sin = Math.sin(angle), x = cos * this.x - sin * this.y, y = sin * this.x + cos * this.y; this.x = x; this.y = y; return this; }, _round: function() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; } }; // constructs Point from an array if necessary Point.convert = function (a) { if (a instanceof Point) { return a; } if (Array.isArray(a)) { return new Point(a[0], a[1]); } return a; }; },{}],4:[function(require,module,exports){ (function (process){ // Copyright 2010-2012 Mikeal Rogers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var extend = require('util')._extend , cookies = require('./lib/cookies') , copy = require('./lib/copy') , helpers = require('./lib/helpers') , isFunction = helpers.isFunction , constructObject = helpers.constructObject , filterForCallback = helpers.filterForCallback , constructOptionsFrom = helpers.constructOptionsFrom , paramsHaveRequestBody = helpers.paramsHaveRequestBody ; // organize params for patch, post, put, head, del function initParams(uri, options, callback) { callback = filterForCallback([options, callback]) options = constructOptionsFrom(uri, options) return constructObject() .extend({callback: callback}) .extend({options: options}) .extend({uri: options.uri}) .done() } function request (uri, options, callback) { if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.') var params = initParams(uri, options, callback) options = params.options options.callback = params.callback options.uri = params.uri return new request.Request(options) } function requester(params) { if(typeof params.options._requester === 'function') return params.options._requester return request } request.get = function (uri, options, callback) { var params = initParams(uri, options, callback) params.options.method = 'GET' return requester(params)(params.uri || null, params.options, params.callback) } request.head = function (uri, options, callback) { var params = initParams(uri, options, callback) params.options.method = 'HEAD' if (paramsHaveRequestBody(params)) throw new Error("HTTP HEAD requests MUST NOT include a request body.") return requester(params)(params.uri || null, params.options, params.callback) } request.post = function (uri, options, callback) { var params = initParams(uri, options, callback) params.options.method = 'POST' return requester(params)(params.uri || null, params.options, params.callback) } request.put = function (uri, options, callback) { var params = initParams(uri, options, callback) params.options.method = 'PUT' return requester(params)(params.uri || null, params.options, params.callback) } request.patch = function (uri, options, callback) { var params = initParams(uri, options, callback) params.options.method = 'PATCH' return requester(params)(params.uri || null, params.options, params.callback) } request.del = function (uri, options, callback) { var params = initParams(uri, options, callback) params.options.method = 'DELETE' return requester(params)(params.uri || null, params.options, params.callback) } request.jar = function () { return cookies.jar() } request.cookie = function (str) { return cookies.parse(str) } request.defaults = function (options, requester) { var wrap = function (method) { var headerlessOptions = function (options) { options = extend({}, options) delete options.headers return options } var getHeaders = function (params, options) { return constructObject() .extend(options.headers) .extend(params.options.headers) .done() } return function (uri, opts, callback) { var params = initParams(uri, opts, callback) params.options = extend(headerlessOptions(options), params.options) if (options.headers) params.options.headers = getHeaders(params, options) if (isFunction(requester)) { if (method === request) { method = requester } else { params.options._requester = requester } } return method(params.options, params.callback) } } defaults = wrap(this) defaults.get = wrap(this.get) defaults.patch = wrap(this.patch) defaults.post = wrap(this.post) defaults.put = wrap(this.put) defaults.head = wrap(this.head) defaults.del = wrap(this.del) defaults.cookie = wrap(this.cookie) defaults.jar = this.jar defaults.defaults = this.defaults return defaults } request.forever = function (agentOptions, optionsArg) { var options = constructObject() if (optionsArg) options.extend(optionsArg) if (agentOptions) options.agentOptions = agentOptions options.extend({forever: true}) return request.defaults(options.done()) } // Exports module.exports = request request.Request = require('./request') request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) request.initParams = initParams }).call(this,require("q+64fw")) },{"./lib/cookies":5,"./lib/copy":6,"./lib/helpers":8,"./request":35,"q+64fw":94,"util":115}],5:[function(require,module,exports){ var optional = require('./optional') , tough = optional('tough-cookie') , Cookie = tough && tough.Cookie , CookieJar = tough && tough.CookieJar ; exports.parse = function(str) { if (str && str.uri) str = str.uri if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param") if (!Cookie) { return null; } return Cookie.parse(str) }; exports.jar = function() { if (!CookieJar) { // tough-cookie not loaded, return a stub object: return { setCookieSync: function(){}, getCookieStringSync: function(){}, getCookiesSync: function(){} }; } var jar = new CookieJar(); jar._jar = jar; // For backwards compatibility return jar; }; },{"./optional":9}],6:[function(require,module,exports){ module.exports = function copy (obj) { var o = {} Object.keys(obj).forEach(function (i) { o[i] = obj[i] }) return o } },{}],7:[function(require,module,exports){ var util = require('util') , request = require('../index') ; module.exports = function debug() { if (request.debug) { console.error('REQUEST %s', util.format.apply(util, arguments)) } } },{"../index":4,"util":115}],8:[function(require,module,exports){ var extend = require('util')._extend function constructObject(initialObject) { initialObject = initialObject || {} return { extend: function (object) { return constructObject(extend(initialObject, object)) }, done: function () { return initialObject } } } function constructOptionsFrom(uri, options) { var params = constructObject() if (typeof options === 'object') { params.extend(options).extend({uri: uri}) } else if (typeof uri === 'string') { params.extend({uri: uri}) } else { params.extend(uri) } return params.done() } function filterForCallback(values) { var callbacks = values.filter(isFunction) return callbacks[0] } function isFunction(value) { return typeof value === 'function' } function paramsHaveRequestBody(params) { return ( params.options.body || params.options.requestBodyStream || (params.options.json && typeof params.options.json !== 'boolean') || params.options.multipart ) } exports.isFunction = isFunction exports.constructObject = constructObject exports.constructOptionsFrom = constructOptionsFrom exports.filterForCallback = filterForCallback exports.paramsHaveRequestBody = paramsHaveRequestBody },{"util":115}],9:[function(require,module,exports){ module.exports = function(moduleName) { try { return module.parent.require(moduleName); } catch (e) { // This could mean that we are in a browser context. // Add another try catch like it used to be, for backwards compability // and browserify reasons. try { return require(moduleName); } catch (e) {} } }; },{}],10:[function(require,module,exports){ (function (Buffer){ var DuplexStream = require('readable-stream').Duplex , util = require('util') function BufferList (callback) { if (!(this instanceof BufferList)) return new BufferList(callback) this._bufs = [] this.length = 0 if (typeof callback == 'function') { this._callback = callback var piper = function (err) { if (this._callback) { this._callback(err) this._callback = null } }.bind(this) this.on('pipe', function (src) { src.on('error', piper) }) this.on('unpipe', function (src) { src.removeListener('error', piper) }) } else if (Buffer.isBuffer(callback)) this.append(callback) else if (Array.isArray(callback)) { callback.forEach(function (b) { Buffer.isBuffer(b) && this.append(b) }.bind(this)) } DuplexStream.call(this) } util.inherits(BufferList, DuplexStream) BufferList.prototype._offset = function (offset) { var tot = 0, i = 0, _t for (; i < this._bufs.length; i++) { _t = tot + this._bufs[i].length if (offset < _t) return [ i, offset - tot ] tot = _t } } BufferList.prototype.append = function (buf) { var isBuffer = Buffer.isBuffer(buf) || buf instanceof BufferList this._bufs.push(isBuffer ? buf : new Buffer(buf)) this.length += buf.length return this } BufferList.prototype._write = function (buf, encoding, callback) { this.append(buf) if (callback) callback() } BufferList.prototype._read = function (size) { if (!this.length) return this.push(null) size = Math.min(size, this.length) this.push(this.slice(0, size)) this.consume(size) } BufferList.prototype.end = function (chunk) { DuplexStream.prototype.end.call(this, chunk) if (this._callback) { this._callback(null, this.slice()) this._callback = null } } BufferList.prototype.get = function (index) { return this.slice(index, index + 1)[0] } BufferList.prototype.slice = function (start, end) { return this.copy(null, 0, start, end) } BufferList.prototype.copy = function (dst, dstStart, srcStart, srcEnd) { if (typeof srcStart != 'number' || srcStart < 0) srcStart = 0 if (typeof srcEnd != 'number' || srcEnd > this.length) srcEnd = this.length if (srcStart >= this.length) return dst || new Buffer(0) if (srcEnd <= 0) return dst || new Buffer(0) var copy = !!dst , off = this._offset(srcStart) , len = srcEnd - srcStart , bytes = len , bufoff = (copy && dstStart) || 0 , start = off[1] , l , i // copy/slice everything if (srcStart === 0 && srcEnd == this.length) { if (!copy) // slice, just return a full concat return Buffer.concat(this._bufs) // copy, need to copy individual buffers for (i = 0; i < this._bufs.length; i++) { this._bufs[i].copy(dst, bufoff) bufoff += this._bufs[i].length } return dst } // easy, cheap case where it's a subset of one of the buffers if (bytes <= this._bufs[off[0]].length - start) { return copy ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) : this._bufs[off[0]].slice(start, start + bytes) } if (!copy) // a slice, we need something to copy in to dst = new Buffer(len) for (i = off[0]; i < this._bufs.length; i++) { l = this._bufs[i].length - start if (bytes > l) { this._bufs[i].copy(dst, bufoff, start) } else { this._bufs[i].copy(dst, bufoff, start, start + bytes) break } bufoff += l bytes -= l if (start) start = 0 } return dst } BufferList.prototype.toString = function (encoding, start, end) { return this.slice(start, end).toString(encoding) } BufferList.prototype.consume = function (bytes) { while (this._bufs.length) { if (bytes > this._bufs[0].length) { bytes -= this._bufs[0].length this.length -= this._bufs[0].length this._bufs.shift() } else { this._bufs[0] = this._bufs[0].slice(bytes) this.length -= bytes break } } return this } BufferList.prototype.duplicate = function () { var i = 0 , copy = new BufferList() for (; i < this._bufs.length; i++) copy.append(this._bufs[i]) return copy } BufferList.prototype.destroy = function () { this._bufs.length = 0; this.length = 0; this.push(null); } ;(function () { var methods = { 'readDoubleBE' : 8 , 'readDoubleLE' : 8 , 'readFloatBE' : 4 , 'readFloatLE' : 4 , 'readInt32BE' : 4 , 'readInt32LE' : 4 , 'readUInt32BE' : 4 , 'readUInt32LE' : 4 , 'readInt16BE' : 2 , 'readInt16LE' : 2 , 'readUInt16BE' : 2 , 'readUInt16LE' : 2 , 'readInt8' : 1 , 'readUInt8' : 1 } for (var m in methods) { (function (m) { BufferList.prototype[m] = function (offset) { return this.slice(offset, offset + methods[m])[m](0) } }(m)) } }()) module.exports = BufferList }).call(this,require("buffer").Buffer) },{"buffer":77,"readable-stream":20,"util":115}],11:[function(require,module,exports){ (function (process){ // 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. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. module.exports = Duplex; /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; } /*</replacement>*/ /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); forEach(objectKeys(Writable.prototype), function(method) { if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; }); function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(this.end.bind(this)); } function forEach (xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } }).call(this,require("q+64fw")) },{"./_stream_readable":13,"./_stream_writable":15,"core-util-is":16,"inherits":17,"q+64fw":94}],12:[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. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":14,"core-util-is":16,"inherits":17}],13:[function(require,module,exports){ (function (process){ // 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. module.exports = Readable; /*<replacement>*/ var isArray = require('isarray'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('buffer').Buffer; /*</replacement>*/ Readable.ReadableState = ReadableState; var EE = require('events').EventEmitter; /*<replacement>*/ if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ var Stream = require('stream'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ var StringDecoder; util.inherits(Readable, Stream); function ReadableState(options, stream) { options = options || {}; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; // cast to ints. this.highWaterMark = ~~this.highWaterMark; this.buffer = []; this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = false; this.ended = false; this.endEmitted = false; this.reading = false; // In streams that never have any data, and do push(null) right away, // the consumer can miss the 'end' event if they do some I/O before // consuming the stream. So, we don't emit('end') until some reading // happens. this.calledRead = false; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, becuase any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // when piping, we only care about 'readable' events that happen // after read()ing all the bytes and not getting any pushback. this.ranOut = false; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; Stream.call(this); } // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function(chunk, encoding) { var state = this._readableState; if (typeof chunk === 'string' && !state.objectMode) { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = new Buffer(chunk, encoding); encoding = ''; } } return readableAddChunk(this, state, chunk, encoding, false); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function(chunk) { var state = this._readableState; return readableAddChunk(this, state, chunk, '', true); }; function readableAddChunk(stream, state, chunk, encoding, addToFront) { var er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (chunk === null || chunk === undefined) { state.reading = false; if (!state.ended) onEofChunk(stream, state); } else if (state.objectMode || chunk && chunk.length > 0) { if (state.ended && !addToFront) { var e = new Error('stream.push() after EOF'); stream.emit('error', e); } else if (state.endEmitted && addToFront) { var e = new Error('stream.unshift() after end event'); stream.emit('error', e); } else { if (state.decoder && !addToFront && !encoding) chunk = state.decoder.write(chunk); // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) { state.buffer.unshift(chunk); } else { state.reading = false; state.buffer.push(chunk); } if (state.needReadable) emitReadable(stream); maybeReadMore(stream, state); } } else if (!addToFront) { state.reading = false; } return needMoreData(state); } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } // backwards compatibility. Readable.prototype.setEncoding = function(enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; }; // Don't raise the hwm > 128MB var MAX_HWM = 0x800000; function roundUpToNextPowerOf2(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 n--; for (var p = 1; p < 32; p <<= 1) n |= n >> p; n++; } return n; } function howMuchToRead(n, state) { if (state.length === 0 && state.ended) return 0; if (state.objectMode) return n === 0 ? 0 : 1; if (n === null || isNaN(n)) { // only flow one buffer at a time if (state.flowing && state.buffer.length) return state.buffer[0].length; else return state.length; } if (n <= 0) return 0; // If we're asking for more than the target buffer level, // then raise the water mark. Bump up to the next highest // power of 2, to prevent increasing it excessively in tiny // amounts. if (n > state.highWaterMark) state.highWaterMark = roundUpToNextPowerOf2(n); // don't have that much. return null, unless we've ended. if (n > state.length) { if (!state.ended) { state.needReadable = true; return 0; } else return state.length; } return n; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function(n) { var state = this._readableState; state.calledRead = true; var nOrig = n; var ret; if (typeof n !== 'number' || n > 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { ret = null; // In cases where the decoder did not receive enough data // to produce a full chunk, then immediately received an // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>]. // howMuchToRead will see this and coerce the amount to // read to zero (because it's looking at the length of the // first <Buffer > in state.buffer), and we'll end up here. // // This can only happen via state.decoder -- no other venue // exists for pushing a zero-length chunk into state.buffer // and triggering this behavior. In this case, we return our // remaining data and end the stream, if appropriate. if (state.length > 0 && state.decoder) { ret = fromList(n, state); state.length -= ret.length; } if (state.length === 0) endReadable(this); return ret; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; // if we currently have less than the highWaterMark, then also read some if (state.length - n <= state.highWaterMark) doRead = true; // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) doRead = false; if (doRead) { state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; } // If _read called its callback synchronously, then `reading` // will be false, and we need to re-evaluate how much data we // can return to the user. if (doRead && !state.reading) n = howMuchToRead(nOrig, state); if (n > 0) ret = fromList(n, state); else ret = null; if (ret === null) { state.needReadable = true; n = 0; } state.length -= n; // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (state.length === 0 && !state.ended) state.needReadable = true; // If we happened to read() exactly the remaining amount in the // buffer, and the EOF has been seen at this point, then make sure // that we emit 'end' on the very next tick. if (state.ended && !state.endEmitted && state.length === 0) endReadable(this); return ret; }; function chunkInvalid(state, chunk) { var er = null; if (!Buffer.isBuffer(chunk) && 'string' !== typeof chunk && chunk !== null && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } function onEofChunk(stream, state) { if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // if we've ended and we have some data left, then emit // 'readable' now to make sure it gets picked up. if (state.length > 0) emitReadable(stream); else endReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (state.emittedReadable) return; state.emittedReadable = true; if (state.sync) process.nextTick(function() { emitReadable_(stream); }); else emitReadable_(stream); } function emitReadable_(stream) { stream.emit('readable'); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(function() { maybeReadMore_(stream, state); }); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function(n) { this.emit('error', new Error('not implemented')); }; Readable.prototype.pipe = function(dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : cleanup; if (state.endEmitted) process.nextTick(endFn); else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable) { if (readable !== src) return; cleanup(); } function onend() { dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); function cleanup() { // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', cleanup); // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (!dest._writableState || dest._writableState.needDrain) ondrain(); } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { unpipe(); dest.removeListener('error', onerror); if (EE.listenerCount(dest, 'error') === 0) dest.emit('error', er); } // This is a brutally ugly hack to make sure that our error handler // is attached before any userland ones. NEVER DO THIS. if (!dest._events || !dest._events.error) dest.on('error', onerror); else if (isArray(dest._events.error)) dest._events.error.unshift(onerror); else dest._events.error = [onerror, dest._events.error]; // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { src.unpipe(dest); } // tell the des