diff --git a/build/knex.js b/build/knex.js index bd39d35677..e7eeca654d 100644 --- a/build/knex.js +++ b/build/knex.js @@ -7,7 +7,7 @@ exports["Knex"] = factory(require("lodash"), require("bluebird")); else root["Knex"] = factory(root["_"], root["Promise"]); -})(this, function(__WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_12__) { +})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_12__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; @@ -56,28 +56,29 @@ return /******/ (function(modules) { // webpackBootstrap /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var Raw = __webpack_require__(1); - var warn = __webpack_require__(2).warn; - var Client = __webpack_require__(3); + var _lodash = __webpack_require__(1); - var makeClient = __webpack_require__(4); - var makeKnex = __webpack_require__(5); - var parseConnection = __webpack_require__(6); - var assign = __webpack_require__(29); + var Raw = __webpack_require__(2); + var warn = __webpack_require__(3).warn; + var Client = __webpack_require__(4); + + var makeClient = __webpack_require__(5); + var makeKnex = __webpack_require__(6); + var parseConnection = __webpack_require__(7); function Knex(config) { if (typeof config === 'string') { - return new Knex(assign(parseConnection(config), arguments[2])); + return new Knex((0, _lodash.assign)(parseConnection(config), arguments[2])); } var Dialect; if (arguments.length === 0 || !config.client && !config.dialect) { Dialect = makeClient(Client); } else { var clientName = config.client || config.dialect; - Dialect = makeClient(__webpack_require__(7)("./" + (aliases[clientName] || clientName) + '/index.js')); + Dialect = makeClient(__webpack_require__(8)("./" + (aliases[clientName] || clientName) + '/index.js')); } if (typeof config.connection === 'string') { - config = assign({}, config, { connection: parseConnection(config.connection).connection }); + config = (0, _lodash.assign)({}, config, { connection: parseConnection(config.connection).connection }); } return makeKnex(new Dialect(config)); } @@ -98,7 +99,7 @@ return /******/ (function(modules) { // webpackBootstrap }; // Bluebird - Knex.Promise = __webpack_require__(8); + Knex.Promise = __webpack_require__(9); // The client names we'll allow in the `{name: lib}` pairing. var aliases = { @@ -112,27 +113,31 @@ return /******/ (function(modules) { // webpackBootstrap // Doing this ensures Browserify works. Still need to figure out // the best way to do some of this. if (process.browser) { - __webpack_require__(9); + __webpack_require__(10); } module.exports = Knex; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { + module.exports = __WEBPACK_EXTERNAL_MODULE_1__; + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + // Raw // ------- 'use strict'; - var inherits = __webpack_require__(47); - var EventEmitter = __webpack_require__(43).EventEmitter; - var assign = __webpack_require__(29); - var reduce = __webpack_require__(30); - var isPlainObject = __webpack_require__(31); - var _ = __webpack_require__(11); + var _lodash = __webpack_require__(1); + + var inherits = __webpack_require__(51); + var EventEmitter = __webpack_require__(38).EventEmitter; function Raw(client) { this.client = client; @@ -148,13 +153,20 @@ return /******/ (function(modules) { // webpackBootstrap } inherits(Raw, EventEmitter); - assign(Raw.prototype, { + (0, _lodash.assign)(Raw.prototype, { set: function set(sql, bindings) { this._cached = undefined; this.sql = sql; - this.bindings = _.isObject(bindings) || _.isUndefined(bindings) ? bindings : [bindings]; + this.bindings = (0, _lodash.isObject)(bindings) || (0, _lodash.isUndefined)(bindings) ? bindings : [bindings]; + + return this; + }, + timeout: function timeout(ms) { + if ((0, _lodash.isNumber)(ms) && ms > 0) { + this._timeout = ms; + } return this; }, @@ -172,17 +184,17 @@ return /******/ (function(modules) { // webpackBootstrap }, // Returns the raw sql for the query. - toSQL: function toSQL() { + toSQL: function toSQL(method, tz) { if (this._cached) return this._cached; if (Array.isArray(this.bindings)) { this._cached = replaceRawArrBindings(this); - } else if (this.bindings && isPlainObject(this.bindings)) { + } else if (this.bindings && (0, _lodash.isPlainObject)(this.bindings)) { this._cached = replaceKeyBindings(this); } else { this._cached = { method: 'raw', sql: this.sql, - bindings: this.bindings + bindings: (0, _lodash.isUndefined)(this.bindings) ? void 0 : [this.bindings] }; } if (this._wrappedBefore) { @@ -191,7 +203,13 @@ return /******/ (function(modules) { // webpackBootstrap if (this._wrappedAfter) { this._cached.sql = this._cached.sql + this._wrappedAfter; } - this._cached.options = reduce(this._options, assign, {}); + this._cached.options = (0, _lodash.reduce)(this._options, _lodash.assign, {}); + if (this._timeout) { + this._cached.timeout = this._timeout; + } + if (this.client && this.client.prepBindings) { + this._cached.bindings = this.client.prepBindings(this._cached.bindings || [], tz); + } return this._cached; } @@ -243,12 +261,14 @@ return /******/ (function(modules) { // webpackBootstrap var sql = raw.sql, bindings = []; - var regex = new RegExp('(^|\\s)(\\:\\w+\\:?)', 'g'); + var regex = new RegExp('(\\:\\w+\\:?)', 'g'); sql = raw.sql.replace(regex, function (full) { var key = full.trim(); var isIdentifier = key[key.length - 1] === ':'; var value = isIdentifier ? values[key.slice(1, -1)] : values[key.slice(1)]; - if (value === undefined) return ''; + if (value === undefined) { + return full; + } if (value && typeof value.toSQL === 'function') { var bindingSQL = value.toSQL(); if (bindingSQL.bindings !== undefined) { @@ -277,20 +297,21 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Raw; /***/ }, -/* 2 */ +/* 3 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var _ = __webpack_require__(11); - var chalk = __webpack_require__(44); + var _lodash = __webpack_require__(1); + + var chalk = __webpack_require__(40); var helpers = { // Pick off the attributes from only the current layer of the object. skim: function skim(data) { - return _.map(data, function (obj) { - return _.pick(obj, _.keys(obj)); + return (0, _lodash.map)(data, function (obj) { + return (0, _lodash.pick)(obj, (0, _lodash.keys)(obj)); }); }, @@ -323,49 +344,47 @@ return /******/ (function(modules) { // webpackBootstrap exit: function exit(msg) { console.log(chalk.red(msg)); - process.exit(); + process.exit(1); } }; module.exports = helpers; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) /***/ }, -/* 3 */ +/* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _ = __webpack_require__(11); - var Promise = __webpack_require__(8); - var helpers = __webpack_require__(2); + var _lodash = __webpack_require__(1); - var Raw = __webpack_require__(1); - var Runner = __webpack_require__(14); - var Formatter = __webpack_require__(15); - var Transaction = __webpack_require__(16); + var Promise = __webpack_require__(9); + var helpers = __webpack_require__(3); - var QueryBuilder = __webpack_require__(17); - var QueryCompiler = __webpack_require__(18); + var Raw = __webpack_require__(2); + var Runner = __webpack_require__(16); + var Formatter = __webpack_require__(17); + var Transaction = __webpack_require__(18); - var SchemaBuilder = __webpack_require__(19); - var SchemaCompiler = __webpack_require__(20); - var TableBuilder = __webpack_require__(21); - var TableCompiler = __webpack_require__(22); - var ColumnBuilder = __webpack_require__(23); - var ColumnCompiler = __webpack_require__(24); + var QueryBuilder = __webpack_require__(19); + var QueryCompiler = __webpack_require__(20); - var Pool2 = __webpack_require__(25); - var inherits = __webpack_require__(47); - var EventEmitter = __webpack_require__(43).EventEmitter; - var SqlString = __webpack_require__(26); + var SchemaBuilder = __webpack_require__(21); + var SchemaCompiler = __webpack_require__(22); + var TableBuilder = __webpack_require__(23); + var TableCompiler = __webpack_require__(24); + var ColumnBuilder = __webpack_require__(25); + var ColumnCompiler = __webpack_require__(26); - var assign = __webpack_require__(29); - var uniqueId = __webpack_require__(33); - var cloneDeep = __webpack_require__(32); - var debug = __webpack_require__(48)('knex:client'); - var debugQuery = __webpack_require__(48)('knex:query'); + var Pool2 = __webpack_require__(27); + var inherits = __webpack_require__(51); + var EventEmitter = __webpack_require__(38).EventEmitter; + var SqlString = __webpack_require__(28); + + var debug = __webpack_require__(52)('knex:client'); + var debugQuery = __webpack_require__(52)('knex:query'); // The base client provides the general structure // for a dialect specific client object. @@ -373,7 +392,7 @@ return /******/ (function(modules) { // webpackBootstrap var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.config = config; - this.connectionSettings = cloneDeep(config.connection || {}); + this.connectionSettings = (0, _lodash.cloneDeep)(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || config.pool && config.pool.max !== 0) { @@ -387,7 +406,7 @@ return /******/ (function(modules) { // webpackBootstrap } inherits(Client, EventEmitter); - assign(Client.prototype, { + (0, _lodash.assign)(Client.prototype, { Formatter: Formatter, @@ -468,26 +487,28 @@ return /******/ (function(modules) { // webpackBootstrap var _this = this; if (typeof obj === 'string') obj = { sql: obj }; - this.emit('query', assign({ __knexUid: connection.__knexUid }, obj)); + this.emit('query', (0, _lodash.assign)({ __knexUid: connection.__knexUid }, obj)); debugQuery(obj.sql); return this._query.call(this, connection, obj)['catch'](function (err) { err.message = SqlString.format(obj.sql, obj.bindings) + ' - ' + err.message; - _this.emit('query-error', err, obj); + _this.emit('query-error', err, (0, _lodash.assign)({ __knexUid: connection.__knexUid }, obj)); throw err; }); }, stream: function stream(connection, obj, _stream, options) { if (typeof obj === 'string') obj = { sql: obj }; - this.emit('query', assign({ __knexUid: connection.__knexUid }, obj)); + this.emit('query', (0, _lodash.assign)({ __knexUid: connection.__knexUid }, obj)); debugQuery(obj.sql); return this._stream.call(this, connection, obj, _stream, options); }, prepBindings: function prepBindings(bindings) { - return _.map(bindings, function (binding) { - return binding === undefined ? this.valueForUndefined : binding; - }, this); + var _this2 = this; + + return (0, _lodash.map)(bindings, function (binding) { + return binding === undefined ? _this2.valueForUndefined : binding; + }); }, wrapIdentifier: function wrapIdentifier(value) { @@ -506,7 +527,7 @@ return /******/ (function(modules) { // webpackBootstrap initializePool: function initializePool(config) { if (this.pool) this.destroy(); - this.pool = new this.Pool(assign(this.poolDefaults(config.pool || {}), config.pool)); + this.pool = new this.Pool((0, _lodash.assign)(this.poolDefaults(config.pool || {}), config.pool)); this.pool.on('error', function (err) { helpers.error('Pool2 - ' + err); }); @@ -527,11 +548,11 @@ return /******/ (function(modules) { // webpackBootstrap max: 10, acquire: function acquire(callback) { client.acquireRawConnection().tap(function (connection) { - connection.__knexUid = uniqueId('__knexUid'); + connection.__knexUid = (0, _lodash.uniqueId)('__knexUid'); if (poolConfig.afterCreate) { return Promise.promisify(poolConfig.afterCreate)(connection); } - }).nodeify(callback); + }).asCallback(callback); }, dispose: function dispose(connection, callback) { if (poolConfig.beforeDestroy) { @@ -543,6 +564,9 @@ return /******/ (function(modules) { // webpackBootstrap } else if (connection !== void 0) { client.destroyRawConnection(connection, callback); } + }, + ping: function ping(resource, callback) { + return client.ping(resource, callback); } }; }, @@ -585,7 +609,7 @@ return /******/ (function(modules) { // webpackBootstrap }); // Allow either a callback or promise interface for destruction. if (typeof callback === 'function') { - promise.nodeify(callback); + promise.asCallback(callback); } else { return promise; } @@ -605,16 +629,18 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Client; /***/ }, -/* 4 */ +/* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var assign = __webpack_require__(29); - var inherits = __webpack_require__(47); + var _lodash = __webpack_require__(1); // Ensure the client has fresh objects so we can tack onto // the prototypes without mutating them globally. + + var inherits = __webpack_require__(51); + module.exports = function makeClient(ParentClient) { if (typeof ParentClient.prototype === 'undefined') { @@ -666,7 +692,7 @@ return /******/ (function(modules) { // webpackBootstrap } inherits(ColumnCompiler, ParentClient.prototype.ColumnCompiler); - assign(Client.prototype, { + (0, _lodash.assign)(Client.prototype, { Formatter: Formatter, QueryBuilder: QueryBuilder, SchemaBuilder: SchemaBuilder, @@ -681,21 +707,21 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 5 */ +/* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var EventEmitter = __webpack_require__(43).EventEmitter; - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); + + var EventEmitter = __webpack_require__(38).EventEmitter; - var Migrator = __webpack_require__(25); - var Seeder = __webpack_require__(25); - var FunctionHelper = __webpack_require__(27); - var QueryInterface = __webpack_require__(28); - var helpers = __webpack_require__(2); - var Promise = __webpack_require__(8); - var _ = __webpack_require__(11); + var Migrator = __webpack_require__(27); + var Seeder = __webpack_require__(27); + var FunctionHelper = __webpack_require__(14); + var QueryInterface = __webpack_require__(15); + var helpers = __webpack_require__(3); + var Promise = __webpack_require__(9); module.exports = function makeKnex(client) { @@ -708,11 +734,11 @@ return /******/ (function(modules) { // webpackBootstrap return tableName ? qb.table(tableName) : qb; } - assign(knex, { + (0, _lodash.assign)(knex, { - Promise: __webpack_require__(8), + Promise: __webpack_require__(9), - // A new query builder instance + // A new query builder instance. queryBuilder: function queryBuilder() { return client.queryBuilder(); }, @@ -724,15 +750,14 @@ return /******/ (function(modules) { // webpackBootstrap batchInsert: function batchInsert(table, batch) { var chunkSize = arguments.length <= 2 || arguments[2] === undefined ? 1000 : arguments[2]; - if (!_.isNumber(chunkSize) || chunkSize < 1) { + if (!(0, _lodash.isNumber)(chunkSize) || chunkSize < 1) { throw new TypeError("Invalid chunkSize: " + chunkSize); } return this.transaction(function (tr) { - - //Avoid unnecessary call + // Avoid unnecessary call. if (chunkSize !== 1) { - batch = _.chunk(batch, chunkSize); + batch = (0, _lodash.chunk)(batch, chunkSize); } return Promise.all(batch.map(function (items) { @@ -761,7 +786,7 @@ return /******/ (function(modules) { // webpackBootstrap // The `__knex__` is used if you need to duck-type check whether this // is a knex builder, without a full on `instanceof` check. - knex.VERSION = knex.__knex__ = '0.10.0'; + knex.VERSION = knex.__knex__ = '0.11.0'; // Hook up the "knex" object as an EventEmitter. var ee = new EventEmitter(); @@ -821,6 +846,10 @@ return /******/ (function(modules) { // webpackBootstrap knex.emit('query-error', err, obj); }); + client.on('query-response', function (response, obj, builder) { + knex.emit('query-response', response, obj, builder); + }); + client.makeKnex = function (client) { return makeKnex(client); }; @@ -829,7 +858,7 @@ return /******/ (function(modules) { // webpackBootstrap }; /***/ }, -/* 6 */ +/* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; @@ -841,11 +870,11 @@ return /******/ (function(modules) { // webpackBootstrap function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } - var _url = __webpack_require__(45); + var _url = __webpack_require__(39); var _url2 = _interopRequireDefault(_url); - var _pgConnectionString = __webpack_require__(46); + var _pgConnectionString = __webpack_require__(41); function parseConnectionString(str) { var parsed = _url2['default'].parse(str); @@ -882,7 +911,11 @@ return /******/ (function(modules) { // webpackBootstrap connection.database = db; } if (parsed.hostname) { - connection.host = parsed.hostname; + if (parsed.protocol.indexOf('mssql') === 0) { + connection.server = parsed.hostname; + } else { + connection.host = parsed.hostname; + } } if (parsed.port) { connection.port = parsed.port; @@ -901,19 +934,19 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = exports['default']; /***/ }, -/* 7 */ +/* 8 */ /***/ function(module, exports, __webpack_require__) { var map = { - "./maria/index.js": 36, - "./mssql/index.js": 37, - "./mysql/index.js": 38, - "./mysql2/index.js": 39, - "./oracle/index.js": 40, - "./postgres/index.js": 41, + "./maria/index.js": 29, + "./mssql/index.js": 30, + "./mysql/index.js": 31, + "./mysql2/index.js": 32, + "./oracle/index.js": 33, + "./postgres/index.js": 34, "./sqlite3/index.js": 35, - "./strong-oracle/index.js": 42, - "./websql/index.js": 9 + "./strong-oracle/index.js": 36, + "./websql/index.js": 10 }; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); @@ -926,30 +959,27 @@ return /******/ (function(modules) { // webpackBootstrap }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; - webpackContext.id = 7; + webpackContext.id = 8; /***/ }, -/* 8 */ +/* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Promise = __webpack_require__(12); - var deprecate = __webpack_require__(2).deprecate; - - // Incase we're using an older version of bluebird - Promise.prototype.asCallback = Promise.prototype.nodeify; + var deprecate = __webpack_require__(3).deprecate; Promise.prototype.exec = function (cb) { - deprecate('.exec', '.nodeify or .asCallback'); - return this.nodeify(cb); + deprecate('.exec', '.asCallback'); + return this.asCallback(cb); }; module.exports = Promise; /***/ }, -/* 9 */ +/* 10 */ /***/ function(module, exports, __webpack_require__) { @@ -957,13 +987,13 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var inherits = __webpack_require__(47); - var _ = __webpack_require__(11); + var _lodash = __webpack_require__(1); - var Transaction = __webpack_require__(34); + var inherits = __webpack_require__(51); + + var Transaction = __webpack_require__(37); var Client_SQLite3 = __webpack_require__(35); - var Promise = __webpack_require__(8); - var assign = __webpack_require__(29); + var Promise = __webpack_require__(9); function Client_WebSQL(config) { Client_SQLite3.call(this, config); @@ -974,7 +1004,7 @@ return /******/ (function(modules) { // webpackBootstrap } inherits(Client_WebSQL, Client_SQLite3); - assign(Client_WebSQL.prototype, { + (0, _lodash.assign)(Client_WebSQL.prototype, { Transaction: Transaction, @@ -988,7 +1018,7 @@ return /******/ (function(modules) { // webpackBootstrap /*jslint browser: true*/ var db = openDatabase(client.name, client.version, client.displayName, client.estimatedSize); db.transaction(function (t) { - t.__knexUid = _.uniqueId('__knexUid'); + t.__knexUid = (0, _lodash.uniqueId)('__knexUid'); resolve(t); }); } catch (e) { @@ -1043,9 +1073,9 @@ return /******/ (function(modules) { // webpackBootstrap case 'select': var results = []; for (var i = 0, l = resp.rows.length; i < l; i++) { - results[i] = _.clone(resp.rows.item(i)); + results[i] = (0, _lodash.clone)(resp.rows.item(i)); } - if (obj.method === 'pluck') results = _.pluck(results, obj.pluck); + if (obj.method === 'pluck') results = (0, _lodash.map)(results, obj.pluck); return obj.method === 'first' ? results[0] : results; case 'insert': return [resp.insertId]; @@ -1056,6 +1086,10 @@ return /******/ (function(modules) { // webpackBootstrap default: return resp; } + }, + + ping: function ping(resource, callback) { + callback(); } }); @@ -1063,7 +1097,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Client_WebSQL; /***/ }, -/* 10 */ +/* 11 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser @@ -1126,12 +1160,6 @@ return /******/ (function(modules) { // webpackBootstrap process.umask = function() { return 0; }; -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = __WEBPACK_EXTERNAL_MODULE_11__; - /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { @@ -1144,24 +1172,24 @@ return /******/ (function(modules) { // webpackBootstrap 'use strict'; - var helpers = __webpack_require__(2); + var _lodash = __webpack_require__(1); + + var helpers = __webpack_require__(3); module.exports = function (Target) { - var _ = __webpack_require__(11); Target.prototype.toQuery = function (tz) { - var data = this.toSQL(this._method); - if (!_.isArray(data)) data = [data]; - return _.map(data, function (statement) { - return this._formatQuery(statement.sql, statement.bindings, tz); - }, this).join(';\n'); + var _this = this; + + var data = this.toSQL(this._method, tz); + if (!(0, _lodash.isArray)(data)) data = [data]; + return (0, _lodash.map)(data, function (statement) { + return _this._formatQuery(statement.sql, statement.bindings, tz); + }).join(';\n'); }; // Format the query as sql, prepping bindings as necessary. Target.prototype._formatQuery = function (sql, bindings, tz) { - if (this.client && this.client.prepBindings) { - bindings = this.client.prepBindings(bindings, tz); - } return this.client.SqlString.format(sql, bindings, tz); }; @@ -1175,7 +1203,7 @@ return /******/ (function(modules) { // webpackBootstrap // items, like the `mysql` and `sqlite3` drivers. Target.prototype.options = function (opts) { this._options = this._options || []; - this._options.push(_.clone(opts) || {}); + this._options.push((0, _lodash.clone)(opts) || {}); this._cached = undefined; return this; }; @@ -1216,7 +1244,7 @@ return /******/ (function(modules) { // webpackBootstrap // Creates a method which "coerces" to a promise, by calling a // "then" method on the current `Target` - _.each(['bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'nodeify', 'exec'], function (method) { + (0, _lodash.each)(['bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'exec', 'reflect'], function (method) { Target.prototype[method] = function () { var then = this.then(); then = then[method].apply(then, arguments); @@ -1229,11 +1257,41 @@ return /******/ (function(modules) { // webpackBootstrap /* 14 */ /***/ function(module, exports, __webpack_require__) { + + // FunctionHelper + // ------- + 'use strict'; + + function FunctionHelper(client) { + this.client = client; + } + + FunctionHelper.prototype.now = function () { + return this.client.raw('CURRENT_TIMESTAMP'); + }; + + module.exports = FunctionHelper; + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + + // All properties we can use to start a query chain + // from the `knex` object, e.g. `knex.select('*').from(...` + 'use strict'; + + module.exports = ['select', 'as', 'columns', 'column', 'from', 'fromJS', 'into', 'withSchema', 'table', 'distinct', 'join', 'joinRaw', 'innerJoin', 'leftJoin', 'leftOuterJoin', 'rightJoin', 'rightOuterJoin', 'outerJoin', 'fullOuterJoin', 'crossJoin', 'where', 'andWhere', 'orWhere', 'whereNot', 'orWhereNot', 'whereRaw', 'whereWrapped', 'havingWrapped', 'orWhereRaw', 'whereExists', 'orWhereExists', 'whereNotExists', 'orWhereNotExists', 'whereIn', 'orWhereIn', 'whereNotIn', 'orWhereNotIn', 'whereNull', 'orWhereNull', 'whereNotNull', 'orWhereNotNull', 'whereBetween', 'whereNotBetween', 'andWhereBetween', 'andWhereNotBetween', 'orWhereBetween', 'orWhereNotBetween', 'groupBy', 'groupByRaw', 'orderBy', 'orderByRaw', 'union', 'unionAll', 'having', 'havingRaw', 'orHaving', 'orHavingRaw', 'offset', 'limit', 'count', 'countDistinct', 'min', 'max', 'sum', 'sumDistinct', 'avg', 'avgDistinct', 'increment', 'decrement', 'first', 'debug', 'pluck', 'insert', 'update', 'returning', 'del', 'delete', 'truncate', 'transacting', 'connection']; + +/***/ }, +/* 16 */ +/***/ function(module, exports, __webpack_require__) { + 'use strict'; - var _ = __webpack_require__(11); - var Promise = __webpack_require__(8); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); + + var Promise = __webpack_require__(9); var PassThrough; @@ -1250,7 +1308,7 @@ return /******/ (function(modules) { // webpackBootstrap this.connection = void 0; } - assign(Runner.prototype, { + (0, _lodash.assign)(Runner.prototype, { // "Run" the target, calling "toSQL" on the builder, returning // an object or array of queries to run, each of which are run on @@ -1268,7 +1326,7 @@ return /******/ (function(modules) { // webpackBootstrap console.log(sql); } - if (_.isArray(sql)) { + if ((0, _lodash.isArray)(sql)) { return runner.queryArray(sql); } return runner.query(sql); @@ -1307,7 +1365,7 @@ return /******/ (function(modules) { // webpackBootstrap var hasHandler = typeof handler === 'function'; // Lazy-load the "PassThrough" dependency. - PassThrough = PassThrough || __webpack_require__(111).PassThrough; + PassThrough = PassThrough || __webpack_require__(89).PassThrough; var runner = this; var stream = new PassThrough({ objectMode: true }); @@ -1315,7 +1373,7 @@ return /******/ (function(modules) { // webpackBootstrap runner.connection = connection; var sql = runner.builder.toSQL(); var err = new Error('The stream may only be used with a single query statement.'); - if (_.isArray(sql)) { + if ((0, _lodash.isArray)(sql)) { if (hasHandler) throw err; stream.emit('error', err); } @@ -1341,10 +1399,31 @@ return /******/ (function(modules) { // webpackBootstrap // to run in sequence, and on the same connection, especially helpful when schema building // and dealing with foreign key constraints, etc. query: Promise.method(function (obj) { - this.builder.emit('query', assign({ __knexUid: this.connection.__knexUid }, obj)); + var _this = this; + + this.builder.emit('query', (0, _lodash.assign)({ __knexUid: this.connection.__knexUid }, obj)); var runner = this; - return this.client.query(this.connection, obj).then(function (resp) { - return runner.client.processResponse(resp, runner); + var queryPromise = this.client.query(this.connection, obj); + + if (obj.timeout) { + queryPromise = queryPromise.timeout(obj.timeout); + } + + return queryPromise.then(function (resp) { + var processedResponse = _this.client.processResponse(resp, runner); + _this.builder.emit('query-response', processedResponse, (0, _lodash.assign)({ __knexUid: _this.connection.__knexUid }, obj), _this.builder); + _this.client.emit('query-response', processedResponse, (0, _lodash.assign)({ __knexUid: _this.connection.__knexUid }, obj), _this.builder); + return processedResponse; + })['catch'](Promise.TimeoutError, function (error) { + throw (0, _lodash.assign)(error, { + message: 'Defined query timeout of ' + obj.timeout + 'ms exceeded when running query.', + sql: obj.sql, + bindings: obj.bindings, + timeout: obj.timeout + }); + })['catch'](function (error) { + _this.builder.emit('query-error', error, (0, _lodash.assign)({ __knexUid: _this.connection.__knexUid }, obj)); + throw error; }); }), @@ -1376,7 +1455,7 @@ return /******/ (function(modules) { // webpackBootstrap additionalErrorInformation.bindings = runner.builder.bindings; } - assign(timeoutError, additionalErrorInformation); + (0, _lodash.assign)(timeoutError, additionalErrorInformation); rejecter(timeoutError); })['catch'](rejecter); @@ -1392,22 +1471,22 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Runner; /***/ }, -/* 15 */ +/* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var QueryBuilder = __webpack_require__(17); - var Raw = __webpack_require__(1); - var assign = __webpack_require__(29); - var transform = __webpack_require__(61); + var _lodash = __webpack_require__(1); + + var QueryBuilder = __webpack_require__(19); + var Raw = __webpack_require__(2); function Formatter(client) { this.client = client; this.bindings = []; } - assign(Formatter.prototype, { + (0, _lodash.assign)(Formatter.prototype, { // Accepts a string or array of columns to wrap as appropriate. columnize: function columnize(target) { @@ -1568,14 +1647,14 @@ return /******/ (function(modules) { // webpackBootstrap var orderBys = ['asc', 'desc']; // Turn this into a lookup map - var operators = transform(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp', '~', '~*', '!~', '!~*', '#', '&&', '@>', '<@', '||'], function (obj, key) { + var operators = (0, _lodash.transform)(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp', '~', '~*', '!~', '!~*', '#', '&&', '@>', '<@', '||'], function (obj, key) { obj[key] = true; }, Object.create(null)); module.exports = Formatter; /***/ }, -/* 16 */ +/* 18 */ /***/ function(module, exports, __webpack_require__) { @@ -1583,21 +1662,21 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var Promise = __webpack_require__(8); - var EventEmitter = __webpack_require__(43).EventEmitter; - var inherits = __webpack_require__(47); - - var makeKnex = __webpack_require__(5); - var assign = __webpack_require__(29); - var uniqueId = __webpack_require__(33); - var debug = __webpack_require__(48)('knex:tx'); + var _lodash = __webpack_require__(1); // Acts as a facade for a Promise, keeping the internal state // and managing any child transactions. + var Promise = __webpack_require__(9); + var EventEmitter = __webpack_require__(38).EventEmitter; + var inherits = __webpack_require__(51); + + var makeKnex = __webpack_require__(6); + var debug = __webpack_require__(52)('knex:tx'); + function Transaction(client, container, config, outerTx) { var _this = this; - var txid = this.txid = uniqueId('trx'); + var txid = this.txid = (0, _lodash.uniqueId)('trx'); this.client = client; this.outerTx = outerTx; @@ -1614,12 +1693,15 @@ return /******/ (function(modules) { // webpackBootstrap init.then(function () { return makeTransactor(_this, connection, trxClient); }).then(function (transactor) { - - var result = container(transactor); - - // If we've returned a "thenable" from the transaction container, - // and it's got the transaction object we're running for this, assume + // If we've returned a "thenable" from the transaction container, assume // the rollback and commit are chained to this object's success / failure. + // Directly thrown errors are treated as automatic rollbacks. + var result; + try { + result = container(transactor); + } catch (err) { + result = Promise.reject(err); + } if (result && result.then && typeof result.then === 'function') { result.then(function (val) { transactor.commit(val); @@ -1639,33 +1721,19 @@ return /******/ (function(modules) { // webpackBootstrap this._completed = false; - // If there is more than one child transaction, - // we queue them, executing each when the previous completes. - this._childQueue = []; - - // The queue is a noop unless we have child promises. - this._queue = this._queue || Promise.resolve(true); - - // If there's a wrapping transaction, we need to see if there are - // any current children in the pending queue. + // If there's a wrapping transaction, we need to wait for any older sibling + // transactions to settle (commit or rollback) before we can start, and we + // need to register ourselves with the parent transaction so any younger + // siblings can wait for us to complete before they can start. + this._previousSibling = Promise.resolve(true); if (outerTx) { - - // If there are other promises pending, we just wait until that one - // settles (commit or rollback) and then we can continue. - if (outerTx._childQueue.length > 0) { - - this._queue = this._queue.then(function () { - return Promise.settle(outerTx._childQueue[outerTx._childQueue.length - 1]); - }); - } - - // Push the current promise onto the queue of promises. - outerTx._childQueue.push(this._promise); + if (outerTx._lastChild) this._previousSibling = outerTx._lastChild; + outerTx._lastChild = this._promise; } } inherits(Transaction, EventEmitter); - assign(Transaction.prototype, { + (0, _lodash.assign)(Transaction.prototype, { isCompleted: function isCompleted() { return this._completed || this.outerTx && this.outerTx.isCompleted() || false; @@ -1688,24 +1756,32 @@ return /******/ (function(modules) { // webpackBootstrap }, rollback: function rollback(conn, error) { - return this.query(conn, 'ROLLBACK;', 2, error); + var _this2 = this; + + return this.query(conn, 'ROLLBACK;', 2, error).timeout(5000)['catch'](Promise.TimeoutError, function () { + _this2._resolver(); + }); }, rollbackTo: function rollbackTo(conn, error) { - return this.query(conn, 'ROLLBACK TO SAVEPOINT ' + this.txid, 2, error); + var _this3 = this; + + return this.query(conn, 'ROLLBACK TO SAVEPOINT ' + this.txid, 2, error).timeout(5000)['catch'](Promise.TimeoutError, function () { + _this3._resolver(); + }); }, query: function query(conn, sql, status, value) { - var _this2 = this; + var _this4 = this; var q = this.trxClient.query(conn, sql)['catch'](function (err) { status = 2; value = err; - _this2._completed = true; - debug('%s error running transaction query', _this2.txid); + _this4._completed = true; + debug('%s error running transaction query', _this4.txid); }).tap(function () { - if (status === 1) _this2._resolver(value); - if (status === 2) _this2._rejecter(value); + if (status === 1) _this4._resolver(value); + if (status === 2) _this4._rejecter(value); }); if (status === 1 || status === 2) { this._completed = true; @@ -1796,6 +1872,11 @@ return /******/ (function(modules) { // webpackBootstrap client.emit('query-error', err, obj); }); + trxClient.on('query-response', function (response, obj, builder) { + trx.emit('query-response', response, obj, builder); + client.emit('query-response', response, obj, builder); + }); + var _query = trxClient.query; trxClient.query = function (conn, obj) { var completed = trx.isCompleted(); @@ -1815,7 +1896,7 @@ return /******/ (function(modules) { // webpackBootstrap }); }; trxClient.acquireConnection = function () { - return trx._queue.then(function () { + return trx._previousSibling.reflect().then(function () { return connection; }); }; @@ -1832,10 +1913,10 @@ return /******/ (function(modules) { // webpackBootstrap throw new Error('Transaction query already complete, run with DEBUG=knex:tx for more info'); } - var promiseInterface = ['then', 'bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'nodeify', 'exec']; + var promiseInterface = ['then', 'bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'exec', 'reflect']; // Creates a method which "coerces" to a promise, by calling a - // "then" method on the current `Target` + // "then" method on the current `Target`. promiseInterface.forEach(function (method) { Transaction.prototype[method] = function () { return this._promise = this._promise[method].apply(this._promise, arguments); @@ -1845,7 +1926,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Transaction; /***/ }, -/* 17 */ +/* 19 */ /***/ function(module, exports, __webpack_require__) { @@ -1853,20 +1934,17 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var _ = __webpack_require__(11); - var assert = __webpack_require__(109); - var inherits = __webpack_require__(47); - var EventEmitter = __webpack_require__(43).EventEmitter; - - var Raw = __webpack_require__(1); - var helpers = __webpack_require__(2); - var JoinClause = __webpack_require__(58); - var _clone = __webpack_require__(59); - var isUndefined = __webpack_require__(60); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); // Typically called from `knex.builder`, // start a new query building chain. + var assert = __webpack_require__(87); + var inherits = __webpack_require__(51); + var EventEmitter = __webpack_require__(38).EventEmitter; + + var Raw = __webpack_require__(2); + var helpers = __webpack_require__(3); + var JoinClause = __webpack_require__(53); function Builder(client) { this.client = client; this.and = this; @@ -1882,33 +1960,40 @@ return /******/ (function(modules) { // webpackBootstrap } inherits(Builder, EventEmitter); - assign(Builder.prototype, { + (0, _lodash.assign)(Builder.prototype, { toString: function toString() { return this.toQuery(); }, // Convert the current query "toSQL" - toSQL: function toSQL(method) { - return this.client.queryCompiler(this).toSQL(method || this._method); + toSQL: function toSQL(method, tz) { + return this.client.queryCompiler(this).toSQL(method || this._method, tz); }, // Create a shallow clone of the current query builder. clone: function clone() { var cloned = new this.constructor(this.client); cloned._method = this._method; - cloned._single = _clone(this._single); - cloned._statements = _clone(this._statements); + cloned._single = (0, _lodash.clone)(this._single); + cloned._statements = (0, _lodash.clone)(this._statements); cloned._debug = this._debug; // `_option` is assigned by the `Interface` mixin. - if (!isUndefined(this._options)) { - cloned._options = _clone(this._options); + if (!(0, _lodash.isUndefined)(this._options)) { + cloned._options = (0, _lodash.clone)(this._options); } return cloned; }, + timeout: function timeout(ms) { + if ((0, _lodash.isNumber)(ms) && ms > 0) { + this._timeout = ms; + } + return this; + }, + // Select // ------ @@ -1969,7 +2054,7 @@ return /******/ (function(modules) { // webpackBootstrap } else { join = new JoinClause(table, joinType, schema); if (arguments.length > 1) { - join.on.apply(join, _.toArray(arguments).slice(1)); + join.on.apply(join, (0, _lodash.toArray)(arguments).slice(1)); } } this._statements.push(join); @@ -2025,7 +2110,7 @@ return /******/ (function(modules) { // webpackBootstrap if (column instanceof Raw && arguments.length === 1) return this.whereRaw(column); // Allows `where({id: 2})` syntax. - if (_.isObject(column) && !(column instanceof Raw)) return this._objectWhere(column); + if ((0, _lodash.isObject)(column) && !(column instanceof Raw)) return this._objectWhere(column); // Enable the where('key', value) syntax, only when there // are explicitly two arguments passed, so it's not possible to @@ -2078,7 +2163,16 @@ return /******/ (function(modules) { // webpackBootstrap }, // Adds an `or where` clause to the query. orWhere: function orWhere() { - return this._bool('or').where.apply(this, arguments); + this._bool('or'); + var obj = arguments[0]; + if ((0, _lodash.isObject)(obj) && !(0, _lodash.isFunction)(obj) && !(obj instanceof Raw)) { + return this.whereWrapped(function () { + for (var key in obj) { + this.andWhere(key, obj[key]); + } + }); + } + return this.where.apply(this, arguments); }, // Adds an `not where` clause to the query. @@ -2169,7 +2263,7 @@ return /******/ (function(modules) { // webpackBootstrap // Adds a `where in` clause to the query. whereIn: function whereIn(column, values) { - if (Array.isArray(values) && _.isEmpty(values)) return this.where(this._not()); + if (Array.isArray(values) && (0, _lodash.isEmpty)(values)) return this.where(this._not()); this._statements.push({ grouping: 'where', type: 'whereIn', @@ -2301,7 +2395,7 @@ return /******/ (function(modules) { // webpackBootstrap // Add a union statement to the query. union: function union(callbacks, wrap) { - if (arguments.length === 1 || arguments.length === 2 && _.isBoolean(wrap)) { + if (arguments.length === 1 || arguments.length === 2 && (0, _lodash.isBoolean)(wrap)) { if (!Array.isArray(callbacks)) { callbacks = [callbacks]; } @@ -2314,9 +2408,9 @@ return /******/ (function(modules) { // webpackBootstrap }); } } else { - callbacks = _.toArray(arguments).slice(0, arguments.length - 1); + callbacks = (0, _lodash.toArray)(arguments).slice(0, arguments.length - 1); wrap = arguments[arguments.length - 1]; - if (!_.isBoolean(wrap)) { + if (!(0, _lodash.isBoolean)(wrap)) { callbacks.push(wrap); wrap = false; } @@ -2479,7 +2573,7 @@ return /******/ (function(modules) { // webpackBootstrap // Sets the values for an `insert` query. insert: function insert(values, returning) { this._method = 'insert'; - if (!_.isEmpty(returning)) this.returning(returning); + if (!(0, _lodash.isEmpty)(returning)) this.returning(returning); this._single.insert = values; return this; }, @@ -2490,7 +2584,7 @@ return /******/ (function(modules) { // webpackBootstrap var ret, obj = this._single.update || {}; this._method = 'update'; - if (_.isString(values)) { + if ((0, _lodash.isString)(values)) { obj[values] = returning; if (arguments.length > 2) { ret = arguments[2]; @@ -2506,7 +2600,7 @@ return /******/ (function(modules) { // webpackBootstrap } ret = arguments[1]; } - if (!_.isEmpty(ret)) this.returning(ret); + if (!(0, _lodash.isEmpty)(ret)) this.returning(ret); this._single.update = obj; return this; }, @@ -2523,7 +2617,7 @@ return /******/ (function(modules) { // webpackBootstrap // Executes a delete statement on the query; 'delete': function _delete(ret) { this._method = 'del'; - if (!_.isEmpty(ret)) this.returning(ret); + if (!(0, _lodash.isEmpty)(ret)) this.returning(ret); return this; }, @@ -2557,23 +2651,25 @@ return /******/ (function(modules) { // webpackBootstrap // Takes a JS object of methods to call and calls them fromJS: function fromJS(obj) { - _.each(obj, function (val, key) { - if (typeof this[key] !== 'function') { + var _this = this; + + (0, _lodash.each)(obj, function (val, key) { + if (typeof _this[key] !== 'function') { helpers.warn('Knex Error: unknown key ' + key); } if (Array.isArray(val)) { - this[key].apply(this, val); + _this[key].apply(_this, val); } else { - this[key](val); + _this[key](val); } - }, this); + }); return this; }, // Passes query to provided callback function, useful for e.g. composing // domain-specific helpers modify: function modify(callback) { - callback.apply(this, [this].concat(_.rest(arguments))); + callback.apply(this, [this].concat((0, _lodash.tail)(arguments))); return this; }, @@ -2656,6 +2752,8 @@ return /******/ (function(modules) { // webpackBootstrap Builder.prototype.andWhereNot = Builder.prototype.whereNot; Builder.prototype.andWhere = Builder.prototype.where; Builder.prototype.andWhereRaw = Builder.prototype.whereRaw; + Builder.prototype.andWhereBetween = Builder.prototype.whereBetween; + Builder.prototype.andWhereNotBetween = Builder.prototype.whereNotBetween; Builder.prototype.andHaving = Builder.prototype.having; Builder.prototype.from = Builder.prototype.table; Builder.prototype.into = Builder.prototype.table; @@ -2667,7 +2765,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = Builder; /***/ }, -/* 18 */ +/* 20 */ /***/ function(module, exports, __webpack_require__) { @@ -2675,47 +2773,50 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var _ = __webpack_require__(11); - var helpers = __webpack_require__(2); - var Raw = __webpack_require__(1); - var assign = __webpack_require__(29); - var reduce = __webpack_require__(30); + var _lodash = __webpack_require__(1); // The "QueryCompiler" takes all of the query statements which // have been gathered in the "QueryBuilder" and turns them into a // properly formatted / bound query string. + var helpers = __webpack_require__(3); + var Raw = __webpack_require__(2); function QueryCompiler(client, builder) { this.client = client; this.method = builder._method || 'select'; this.options = builder._options; this.single = builder._single; - this.grouped = _.groupBy(builder._statements, 'grouping'); + this.timeout = builder._timeout || false; + this.grouped = (0, _lodash.groupBy)(builder._statements, 'grouping'); this.formatter = client.formatter(); } var components = ['columns', 'join', 'where', 'union', 'group', 'having', 'order', 'limit', 'offset', 'lock']; - assign(QueryCompiler.prototype, { + (0, _lodash.assign)(QueryCompiler.prototype, { // Used when the insert call is empty. _emptyInsertValue: 'default values', // Collapse the builder into a single object - toSQL: function toSQL(method) { + toSQL: function toSQL(method, tz) { method = method || this.method; var val = this[method](); var defaults = { method: method, - options: reduce(this.options, assign, {}), + options: (0, _lodash.reduce)(this.options, _lodash.assign, {}), + timeout: this.timeout, bindings: this.formatter.bindings }; - if (_.isString(val)) { + if ((0, _lodash.isString)(val)) { val = { sql: val }; } if (method === 'select' && this.single.as) { defaults.as = this.single.as; } - return assign(defaults, val); + + defaults.bindings = this.client.prepBindings(defaults.bindings || [], tz); + + return (0, _lodash.assign)(defaults, val); }, // Compiles the `select` statement, or nested sub-selects @@ -2727,7 +2828,7 @@ return /******/ (function(modules) { // webpackBootstrap while (++i < components.length) { statements.push(this[components[i]](this)); } - return _.compact(statements).join(' '); + return (0, _lodash.compact)(statements).join(' '); }, pluck: function pluck() { @@ -2747,7 +2848,7 @@ return /******/ (function(modules) { // webpackBootstrap if (insertValues.length === 0) { return ''; } - } else if (typeof insertValues === 'object' && _.isEmpty(insertValues)) { + } else if (typeof insertValues === 'object' && (0, _lodash.isEmpty)(insertValues)) { return sql + this._emptyInsertValue; } @@ -2837,8 +2938,8 @@ return /******/ (function(modules) { // webpackBootstrap var clause = join.clauses[ii]; sql += ' ' + (ii > 0 ? clause[0] : clause[1]) + ' '; sql += this.formatter.wrap(clause[2]); - if (!_.isUndefined(clause[3])) sql += ' ' + this.formatter.operator(clause[3]); - if (!_.isUndefined(clause[4])) sql += ' ' + this.formatter.wrap(clause[4]); + if (!(0, _lodash.isUndefined)(clause[3])) sql += ' ' + this.formatter.operator(clause[3]); + if (!(0, _lodash.isUndefined)(clause[4])) sql += ' ' + this.formatter.wrap(clause[4]); } } } @@ -3005,7 +3106,7 @@ return /******/ (function(modules) { // webpackBootstrap }, whereBetween: function whereBetween(statement) { - return this.formatter.wrap(statement.column) + ' ' + this._not(statement, 'between') + ' ' + _.map(statement.value, this.formatter.parameter, this.formatter).join(' and '); + return this.formatter.wrap(statement.column) + ' ' + this._not(statement, 'between') + ' ' + (0, _lodash.map)(statement.value, (0, _lodash.bind)(this.formatter.parameter, this.formatter)).join(' and '); }, // Compiles a "whereRaw" query. @@ -3061,7 +3162,7 @@ return /******/ (function(modules) { // webpackBootstrap // "Preps" the update. _prepUpdate: function _prepUpdate(data) { - data = _.omit(data, _.isUndefined); + data = (0, _lodash.omitBy)(data, _lodash.isUndefined); var vals = []; var sorted = Object.keys(data).sort(); var i = -1; @@ -3106,19 +3207,20 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = QueryCompiler; /***/ }, -/* 19 */ +/* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var EventEmitter = __webpack_require__(43).EventEmitter; + var _lodash = __webpack_require__(1); // Constructor for the builder instance, typically called from // `knex.builder`, accepting the current `knex` instance, // and pulling out the `client` and `grammar` from the current // knex instance. + + var inherits = __webpack_require__(51); + var EventEmitter = __webpack_require__(38).EventEmitter; function SchemaBuilder(client) { this.client = client; this._sequence = []; @@ -3128,12 +3230,12 @@ return /******/ (function(modules) { // webpackBootstrap // Each of the schema builder methods just add to the // "_sequence" array for consistency. - _.each(['createTable', 'createTableIfNotExists', 'createSchema', 'createSchemaIfNotExists', 'dropSchema', 'dropSchemaIfExists', 'createExtension', 'createExtensionIfNotExists', 'dropExtension', 'dropExtensionIfExists', 'table', 'alterTable', 'hasTable', 'hasColumn', 'dropTable', 'renameTable', 'dropTableIfExists', 'raw'], function (method) { + (0, _lodash.each)(['createTable', 'createTableIfNotExists', 'createSchema', 'createSchemaIfNotExists', 'dropSchema', 'dropSchemaIfExists', 'createExtension', 'createExtensionIfNotExists', 'dropExtension', 'dropExtensionIfExists', 'table', 'alterTable', 'hasTable', 'hasColumn', 'dropTable', 'renameTable', 'dropTableIfExists', 'raw'], function (method) { SchemaBuilder.prototype[method] = function () { if (method === 'table') method = 'alterTable'; this._sequence.push({ method: method, - args: _.toArray(arguments) + args: (0, _lodash.toArray)(arguments) }); return this; }; @@ -3157,17 +3259,19 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = SchemaBuilder; /***/ }, -/* 20 */ +/* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var helpers = __webpack_require__(62); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); // The "SchemaCompiler" takes all of the query statements which have been // gathered in the "SchemaBuilder" and turns them into an array of // properly formatted / bound query strings. + + var helpers = __webpack_require__(54); + function SchemaCompiler(client, builder) { this.builder = builder; this.client = client; @@ -3176,7 +3280,7 @@ return /******/ (function(modules) { // webpackBootstrap this.sequence = []; } - assign(SchemaCompiler.prototype, { + (0, _lodash.assign)(SchemaCompiler.prototype, { pushQuery: helpers.pushQuery, @@ -3233,7 +3337,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = SchemaCompiler; /***/ }, -/* 21 */ +/* 23 */ /***/ function(module, exports, __webpack_require__) { @@ -3247,8 +3351,9 @@ return /******/ (function(modules) { // webpackBootstrap // ------ 'use strict'; - var _ = __webpack_require__(11); - var helpers = __webpack_require__(2); + var _lodash = __webpack_require__(1); + + var helpers = __webpack_require__(3); function TableBuilder(client, method, tableName, fn) { this.client = client; @@ -3258,6 +3363,10 @@ return /******/ (function(modules) { // webpackBootstrap this._tableName = tableName; this._statements = []; this._single = {}; + + if (!(0, _lodash.isFunction)(this._fn)) { + throw new TypeError('A callback function must be supplied to calls against `.createTable` and `.table`'); + } } TableBuilder.prototype.setSchema = function (schemaName) { @@ -3269,13 +3378,13 @@ return /******/ (function(modules) { // webpackBootstrap // rather than creating the table. TableBuilder.prototype.toSQL = function () { if (this._method === 'alter') { - _.extend(this, AlterMethods); + (0, _lodash.extend)(this, AlterMethods); } this._fn.call(this, this); return this.client.tableCompiler(this).toSQL(); }; - _.each([ + (0, _lodash.each)([ // Each of the index methods can be called individually, with the // column name to be used, e.g. table.unique('column'). @@ -3287,24 +3396,30 @@ return /******/ (function(modules) { // webpackBootstrap this._statements.push({ grouping: 'alterTable', method: method, - args: _.toArray(arguments) + args: (0, _lodash.toArray)(arguments) }); return this; }; }); - // Warn if we're not in MySQL, since that's the only time these - // three are supported. - var specialMethods = ['engine', 'charset', 'collate']; - _.each(specialMethods, function (method) { - TableBuilder.prototype[method] = function (value) { - if (false) { - helpers.warn('Knex only supports ' + method + ' statement with mysql.'); - }if (this._method === 'alter') { - helpers.warn('Knex does not support altering the ' + method + ' outside of the create table, please use knex.raw statement.'); - } - this._single[method] = value; - }; + // Warn for dialect-specific table methods, since that's the + // only time these are supported. + var specialMethods = { + mysql: ['engine', 'charset', 'collate'], + postgresql: ['inherits'] + }; + (0, _lodash.each)(specialMethods, function (methods, dialect) { + (0, _lodash.each)(methods, function (method) { + TableBuilder.prototype[method] = function (value) { + if (this.client.dialect !== dialect) { + helpers.warn('Knex only supports ' + method + ' statement with ' + dialect + '.'); + } + if (this._method === 'alter') { + helpers.warn('Knex does not support altering the ' + method + ' outside of the create table, please use knex.raw statement.'); + } + this._single[method] = value; + }; + }); }); // Each of the column types that we can add, we create a new ColumnBuilder @@ -3326,19 +3441,20 @@ return /******/ (function(modules) { // webpackBootstrap // For each of the column methods, create a new "ColumnBuilder" interface, // push it onto the "allStatements" stack, and then return the interface, // with which we can add indexes, etc. - _.each(columnTypes, function (type) { + (0, _lodash.each)(columnTypes, function (type) { TableBuilder.prototype[type] = function () { - var args = _.toArray(arguments); + var args = (0, _lodash.toArray)(arguments); // The "timestamps" call is really a compound call to set the // `created_at` and `updated_at` columns. if (type === 'timestamps') { - if (args[0] === true) { - this.timestamp('created_at'); - this.timestamp('updated_at'); - } else { - this.datetime('created_at'); - this.datetime('updated_at'); + var col = args[0] === true ? 'timestamp' : 'datetime'; + var createdAt = this[col]('created_at'); + var updatedAt = this[col]('updated_at'); + if (args[1] === true) { + var now = this.client.raw('CURRENT_TIMESTAMP'); + createdAt.notNullable().defaultTo(now); + updatedAt.notNullable().defaultTo(now); } return; } @@ -3371,13 +3487,16 @@ return /******/ (function(modules) { // webpackBootstrap var returnObj = { references: function references(tableColumn) { var pieces; - if (_.isString(tableColumn)) { + if ((0, _lodash.isString)(tableColumn)) { pieces = tableColumn.split('.'); } if (!pieces || pieces.length === 1) { foreignData.references = pieces ? pieces[0] : tableColumn; return { on: function on(tableName) { + if (typeof tableName !== 'string') { + throw new TypeError('Expected tableName to be a string, got: ' + typeof tableName); + } foreignData.inTable = tableName; return returnObj; }, @@ -3399,7 +3518,7 @@ return /******/ (function(modules) { // webpackBootstrap return returnObj; }, _columnBuilder: function _columnBuilder(builder) { - _.extend(builder, returnObj); + (0, _lodash.extend)(builder, returnObj); returnObj = builder; return builder; } @@ -3433,7 +3552,7 @@ return /******/ (function(modules) { // webpackBootstrap this._statements.push({ grouping: 'alterTable', method: 'dropColumn', - args: _.toArray(arguments) + args: (0, _lodash.toArray)(arguments) }); return this; }; @@ -3441,7 +3560,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = TableBuilder; /***/ }, -/* 22 */ +/* 24 */ /***/ function(module, exports, __webpack_require__) { @@ -3449,9 +3568,10 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var _ = __webpack_require__(11); - var helpers = __webpack_require__(62); - var normalizeArr = __webpack_require__(2).normalizeArr; + var _lodash = __webpack_require__(1); + + var helpers = __webpack_require__(54); + var normalizeArr = __webpack_require__(3).normalizeArr; function TableCompiler(client, tableBuilder) { this.client = client; @@ -3459,7 +3579,7 @@ return /******/ (function(modules) { // webpackBootstrap this.schemaNameRaw = tableBuilder._schemaName; this.tableNameRaw = tableBuilder._tableName; this.single = tableBuilder._single; - this.grouped = _.groupBy(tableBuilder._statements, 'grouping'); + this.grouped = (0, _lodash.groupBy)(tableBuilder._statements, 'grouping'); this.formatter = client.formatter(); this.sequence = []; this._formatting = client.config && client.config.formatting; @@ -3530,7 +3650,7 @@ return /******/ (function(modules) { // webpackBootstrap // Get all of the column sql & bindings individually for building the table queries. TableCompiler.prototype.getColumnTypes = function (columns) { - return _.reduce(_.map(columns, _.first), function (memo, column) { + return (0, _lodash.reduce)((0, _lodash.map)(columns, _lodash.first), function (memo, column) { memo.sql.push(column.sql); memo.bindings.concat(column.bindings); return memo; @@ -3539,8 +3659,8 @@ return /******/ (function(modules) { // webpackBootstrap // Adds all of the additional queries from the "column" TableCompiler.prototype.columnQueries = function (columns) { - var queries = _.reduce(_.map(columns, _.rest), function (memo, column) { - if (!_.isEmpty(column)) return memo.concat(column); + var queries = (0, _lodash.reduce)((0, _lodash.map)(columns, _lodash.tail), function (memo, column) { + if (!(0, _lodash.isEmpty)(column)) return memo.concat(column); return memo; }, []); for (var i = 0, l = queries.length; i < l; i++) { @@ -3553,10 +3673,12 @@ return /******/ (function(modules) { // webpackBootstrap // All of the columns to "add" for the query TableCompiler.prototype.addColumns = function (columns) { + var _this = this; + if (columns.sql.length > 0) { - var columnSql = _.map(columns.sql, function (column) { - return this.addColumnsPrefix + column; - }, this); + var columnSql = (0, _lodash.map)(columns.sql, function (column) { + return _this.addColumnsPrefix + column; + }); this.pushQuery({ sql: (this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + columnSql.join(', '), bindings: columns.bindings @@ -3604,7 +3726,7 @@ return /******/ (function(modules) { // webpackBootstrap this.grouped.alterTable = []; for (var i = 0, l = alterTable.length; i < l; i++) { var statement = alterTable[i]; - if (_.indexOf(this.createAlterTableMethods, statement.method) < 0) { + if ((0, _lodash.indexOf)(this.createAlterTableMethods, statement.method) < 0) { this.grouped.alterTable.push(statement); continue; } @@ -3632,10 +3754,12 @@ return /******/ (function(modules) { // webpackBootstrap TableCompiler.prototype.dropColumnPrefix = 'drop column '; TableCompiler.prototype.dropColumn = function () { + var _this2 = this; + var columns = normalizeArr.apply(null, arguments); - var drops = _.map(_.isArray(columns) ? columns : [columns], function (column) { - return this.dropColumnPrefix + this.formatter.wrap(column); - }, this); + var drops = (0, _lodash.map)((0, _lodash.isArray)(columns) ? columns : [columns], function (column) { + return _this2.dropColumnPrefix + _this2.formatter.wrap(column); + }); this.pushQuery((this.lowerCase ? 'alter table ' : 'ALTER TABLE ') + this.tableName() + ' ' + drops.join(', ')); }; @@ -3643,20 +3767,21 @@ return /******/ (function(modules) { // webpackBootstrap // convention of the table name, followed by the columns, followed by an // index type, such as primary or index, which makes the index unique. TableCompiler.prototype._indexCommand = function (type, tableName, columns) { - if (!_.isArray(columns)) columns = columns ? [columns] : []; + if (!(0, _lodash.isArray)(columns)) columns = columns ? [columns] : []; var table = tableName.replace(/\.|-/g, '_'); - return (table + '_' + columns.join('_') + '_' + type).toLowerCase(); + var indexName = (table + '_' + columns.join('_') + '_' + type).toLowerCase(); + return this.formatter.wrap(indexName); }; module.exports = TableCompiler; /***/ }, -/* 23 */ +/* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _ = __webpack_require__(11); + var _lodash = __webpack_require__(1); // The chainable interface off the original "column" method. function ColumnBuilder(client, tableBuilder, type, args) { @@ -3671,30 +3796,30 @@ return /******/ (function(modules) { // webpackBootstrap // If we're altering the table, extend the object // with the available "alter" methods. if (tableBuilder._method === 'alter') { - _.extend(this, AlterMethods); + (0, _lodash.extend)(this, AlterMethods); } } // All of the modifier methods that can be used to modify the current query. - var modifiers = ['default', 'defaultsTo', 'defaultTo', 'unsigned', 'nullable', 'notNull', 'notNullable', 'first', 'after', 'comment']; + var modifiers = ['default', 'defaultsTo', 'defaultTo', 'unsigned', 'nullable', 'notNull', 'notNullable', 'first', 'after', 'comment', 'collate']; // If we call any of the modifiers (index or otherwise) on the chainable, we pretend // as though we're calling `table.method(column)` directly. - _.each(modifiers, function (method) { + (0, _lodash.each)(modifiers, function (method) { ColumnBuilder.prototype[method] = function () { if (aliasMethod[method]) { method = aliasMethod[method]; } if (method === 'notNullable') return this.nullable(false); - this._modifiers[method] = _.toArray(arguments); + this._modifiers[method] = (0, _lodash.toArray)(arguments); return this; }; }); - _.each(['index', 'primary', 'unique'], function (method) { + (0, _lodash.each)(['index', 'primary', 'unique'], function (method) { ColumnBuilder.prototype[method] = function () { if (this._type.toLowerCase().indexOf('increments') === -1) { - this._tableBuilder[method].apply(this._tableBuilder, [this._args[0]].concat(_.toArray(arguments))); + this._tableBuilder[method].apply(this._tableBuilder, [this._args[0]].concat((0, _lodash.toArray)(arguments))); } return this; }; @@ -3745,7 +3870,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = ColumnBuilder; /***/ }, -/* 24 */ +/* 26 */ /***/ function(module, exports, __webpack_require__) { @@ -3755,9 +3880,10 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var _ = __webpack_require__(11); - var Raw = __webpack_require__(1); - var helpers = __webpack_require__(62); + var _lodash = __webpack_require__(1); + + var Raw = __webpack_require__(2); + var helpers = __webpack_require__(54); function ColumnCompiler(client, tableCompiler, columnBuilder) { this.client = client; @@ -3765,7 +3891,7 @@ return /******/ (function(modules) { // webpackBootstrap this.columnBuilder = columnBuilder; this.args = columnBuilder._args; this.type = columnBuilder._type.toLowerCase(); - this.grouped = _.groupBy(columnBuilder._statements, 'grouping'); + this.grouped = (0, _lodash.groupBy)(columnBuilder._statements, 'grouping'); this.modified = columnBuilder._modifiers; this.isIncrements = this.type.indexOf('increments') !== -1; this.formatter = client.formatter(); @@ -3793,7 +3919,7 @@ return /******/ (function(modules) { // webpackBootstrap // Assumes the autoincrementing key is named `id` if not otherwise specified. ColumnCompiler.prototype.getColumnName = function () { - var value = _.first(this.args); + var value = (0, _lodash.first)(this.args); if (value) return value; if (this.isIncrements) { return 'id'; @@ -3804,7 +3930,7 @@ return /******/ (function(modules) { // webpackBootstrap ColumnCompiler.prototype.getColumnType = function () { var type = this[this.type]; - return typeof type === 'function' ? type.apply(this, _.rest(this.args)) : type; + return typeof type === 'function' ? type.apply(this, (0, _lodash.tail)(this.args)) : type; }; ColumnCompiler.prototype.getModifiers = function () { @@ -3812,7 +3938,7 @@ return /******/ (function(modules) { // webpackBootstrap if (this.type.indexOf('increments') === -1) { for (var i = 0, l = this.modifiers.length; i < l; i++) { var modifier = this.modifiers[i]; - if (_.has(this.modified, modifier)) { + if ((0, _lodash.has)(this.modified, modifier)) { var val = this[modifier].apply(this, this.modified[modifier]); if (val) modifiers.push(val); } @@ -3873,7 +3999,7 @@ return /******/ (function(modules) { // webpackBootstrap } else if (this.type === 'bool') { if (value === 'false') value = 0; value = "'" + (value ? 1 : 0) + "'"; - } else if (this.type === 'json' && _.isObject(value)) { + } else if (this.type === 'json' && (0, _lodash.isObject)(value)) { return JSON.stringify(value); } else { value = "'" + value + "'"; @@ -3889,7 +4015,7 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = ColumnCompiler; /***/ }, -/* 25 */ +/* 27 */ /***/ function(module, exports, __webpack_require__) { "use strict"; @@ -3897,18 +4023,18 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = function () {}; /***/ }, -/* 26 */ +/* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; var SqlString = exports; - var helpers = __webpack_require__(2); + var helpers = __webpack_require__(3); SqlString.escape = function (val, timeZone) { - // Cant do require on top of file beacuse Raw is not yet initialized when this file is - // executed for the first time - var Raw = __webpack_require__(1); + // Can't do require on top of file because Raw has not yet been initialized + // when this file is executed for the first time. + var Raw = __webpack_require__(2); if (val === null || val === undefined) { return 'NULL'; @@ -4038,420 +4164,237 @@ return /******/ (function(modules) { // webpackBootstrap } return false; } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 27 */ +/* 29 */ /***/ function(module, exports, __webpack_require__) { - // FunctionHelper + // MariaSQL Client // ------- 'use strict'; - function FunctionHelper(client) { - this.client = client; - } - - FunctionHelper.prototype.now = function () { - return this.client.raw('CURRENT_TIMESTAMP'); - }; - - module.exports = FunctionHelper; - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - - - // All properties we can use to start a query chain - // from the `knex` object, e.g. `knex.select('*').from(...` - 'use strict'; + var _lodash = __webpack_require__(1); - module.exports = ['select', 'as', 'columns', 'column', 'from', 'fromJS', 'into', 'withSchema', 'table', 'distinct', 'join', 'joinRaw', 'innerJoin', 'leftJoin', 'leftOuterJoin', 'rightJoin', 'rightOuterJoin', 'outerJoin', 'fullOuterJoin', 'crossJoin', 'where', 'andWhere', 'orWhere', 'whereNot', 'orWhereNot', 'whereRaw', 'whereWrapped', 'havingWrapped', 'orWhereRaw', 'whereExists', 'orWhereExists', 'whereNotExists', 'orWhereNotExists', 'whereIn', 'orWhereIn', 'whereNotIn', 'orWhereNotIn', 'whereNull', 'orWhereNull', 'whereNotNull', 'orWhereNotNull', 'whereBetween', 'whereNotBetween', 'orWhereBetween', 'orWhereNotBetween', 'groupBy', 'groupByRaw', 'orderBy', 'orderByRaw', 'union', 'unionAll', 'having', 'havingRaw', 'orHaving', 'orHavingRaw', 'offset', 'limit', 'count', 'countDistinct', 'min', 'max', 'sum', 'sumDistinct', 'avg', 'avgDistinct', 'increment', 'decrement', 'first', 'debug', 'pluck', 'insert', 'update', 'returning', 'del', 'delete', 'truncate', 'transacting', 'connection']; + var inherits = __webpack_require__(51); + var Client_MySQL = __webpack_require__(31); + var Promise = __webpack_require__(9); + var SqlString = __webpack_require__(28); + var helpers = __webpack_require__(3); + var Transaction = __webpack_require__(55); -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { + function Client_MariaSQL(config) { + Client_MySQL.call(this, config); + } + inherits(Client_MariaSQL, Client_MySQL); - var assignWith = __webpack_require__(63), - baseAssign = __webpack_require__(64), - createAssigner = __webpack_require__(65); + (0, _lodash.assign)(Client_MariaSQL.prototype, { - /** - * Assigns own enumerable properties of source object(s) to the destination - * object. Subsequent sources overwrite property assignments of previous sources. - * If `customizer` is provided it's invoked to produce the assigned values. - * The `customizer` is bound to `thisArg` and invoked with five arguments: - * (objectValue, sourceValue, key, object, source). - * - * **Note:** This method mutates `object` and is based on - * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign). - * - * @static - * @memberOf _ - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {Object} Returns `object`. - * @example - * - * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); - * // => { 'user': 'fred', 'age': 40 } - * - * // using a customizer callback - * var defaults = _.partialRight(_.assign, function(value, other) { - * return _.isUndefined(value) ? other : value; - * }); - * - * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); - * // => { 'user': 'barney', 'age': 36 } - */ - var assign = createAssigner(function(object, source, customizer) { - return customizer - ? assignWith(object, source, customizer) - : baseAssign(object, source); - }); + dialect: 'mariadb', - module.exports = assign; + driverName: 'mariasql', + Transaction: Transaction, -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { + _driver: function _driver() { + return __webpack_require__(42); + }, - var arrayReduce = __webpack_require__(71), - baseEach = __webpack_require__(72), - createReduce = __webpack_require__(73); + // Get a raw connection, called by the `pool` whenever a new + // connection needs to be added to the pool. + acquireRawConnection: function acquireRawConnection() { + var connection = new this.driver(); + connection.connect((0, _lodash.assign)({ metadata: true }, this.connectionSettings)); + return new Promise(function (resolver, rejecter) { + connection.on('ready', function () { + connection.removeAllListeners('end'); + connection.removeAllListeners('error'); + resolver(connection); + }).on('error', rejecter); + }); + }, - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` through `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not provided the first element of `collection` is used as the initial - * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`, - * and `sortByOrder` - * - * @static - * @memberOf _ - * @alias foldl, inject - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {*} Returns the accumulated value. - * @example - * - * _.reduce([1, 2], function(total, n) { - * return total + n; - * }); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { - * result[key] = n * 3; - * return result; - * }, {}); - * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) - */ - var reduce = createReduce(arrayReduce, baseEach); + // Used to explicitly close a connection, called internally by the pool + // when a connection times out or the pool is shutdown. + destroyRawConnection: function destroyRawConnection(connection, cb) { + connection.end(); + cb(); + }, - module.exports = reduce; + // Return the database for the MariaSQL client. + database: function database() { + return this.connectionSettings.db; + }, + // Grab a connection, run the query via the MariaSQL streaming interface, + // and pass that through to the stream we've sent back to the client. + _stream: function _stream(connection, sql, stream) { + return new Promise(function (resolver, rejecter) { + connection.query(sql.sql, sql.bindings).on('result', function (res) { + res.on('error', rejecter).on('end', function () { + resolver(res.info); + }).on('data', function (data) { + stream.write(handleRow(data, res.info.metadata)); + }); + }).on('error', rejecter); + }); + }, -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { - - var baseForIn = __webpack_require__(68), - isArguments = __webpack_require__(69), - isObjectLike = __webpack_require__(70); - - /** `Object#toString` result references. */ - var objectTag = '[object Object]'; - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; + // Runs the query on the specified connection, providing the bindings + // and any other necessary prep work. + _query: function _query(connection, obj) { + var tz = this.connectionSettings.timezone || 'local'; + return new Promise(function (resolver, rejecter) { + if (!obj.sql) return resolver(); + var sql = SqlString.format(obj.sql, obj.bindings, tz); + connection.query(sql, function (err, rows) { + if (err) { + return rejecter(err); + } + handleRows(rows, rows.info.metadata); + obj.response = [rows, rows.info]; + resolver(obj); + }); + }); + }, - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * **Note:** This method assumes objects created by the `Object` constructor - * have no inherited enumerable properties. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - var Ctor; + // Process the response as returned from the query. + processResponse: function processResponse(obj, runner) { + var response = obj.response; + var method = obj.method; + var rows = response[0]; + var data = response[1]; + if (obj.output) return obj.output.call(runner, rows /*, fields*/); + switch (method) { + case 'select': + case 'pluck': + case 'first': + var resp = helpers.skim(rows); + if (method === 'pluck') return (0, _lodash.map)(resp, obj.pluck); + return method === 'first' ? resp[0] : resp; + case 'insert': + return [data.insertId]; + case 'del': + case 'update': + case 'counter': + return parseInt(data.affectedRows, 10); + default: + return response; + } + }, - // Exit early for non `Object` objects. - if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) || - (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { - return false; + ping: function ping(resource, callback) { + resource.query('SELECT 1', callback); } - // IE < 9 iterates inherited properties before own properties. If the first - // iterated property is an object's own property then there are no inherited - // enumerable properties. - var result; - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - baseForIn(value, function(subValue, key) { - result = key; - }); - return result === undefined || hasOwnProperty.call(value, result); - } - - module.exports = isPlainObject; - - -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { - - var baseClone = __webpack_require__(66), - bindCallback = __webpack_require__(67); - - /** - * Creates a deep clone of `value`. If `customizer` is provided it's invoked - * to produce the cloned values. If `customizer` returns `undefined` cloning - * is handled by the method instead. The `customizer` is bound to `thisArg` - * and invoked with up to three argument; (value [, index|key, object]). - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). - * The enumerable properties of `arguments` objects and objects created by - * constructors other than `Object` are cloned to plain `Object` objects. An - * empty object is returned for uncloneable values such as functions, DOM nodes, - * Maps, Sets, and WeakMaps. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {*} Returns the deep cloned value. - * @example - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * var deep = _.cloneDeep(users); - * deep[0] === users[0]; - * // => false - * - * // using a customizer callback - * var el = _.cloneDeep(document.body, function(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * }); - * - * el === document.body - * // => false - * el.nodeName - * // => BODY - * el.childNodes.length; - * // => 20 - */ - function cloneDeep(value, customizer, thisArg) { - return typeof customizer == 'function' - ? baseClone(value, true, bindCallback(customizer, thisArg, 3)) - : baseClone(value, true); - } - - module.exports = cloneDeep; - - -/***/ }, -/* 33 */ -/***/ function(module, exports, __webpack_require__) { - var baseToString = __webpack_require__(74); - - /** Used to generate unique IDs. */ - var idCounter = 0; + }); - /** - * Generates a unique ID. If `prefix` is provided the ID is appended to it. - * - * @static - * @memberOf _ - * @category Utility - * @param {string} [prefix] The value to prefix the ID with. - * @returns {string} Returns the unique ID. - * @example - * - * _.uniqueId('contact_'); - * // => 'contact_104' - * - * _.uniqueId(); - * // => '105' - */ - function uniqueId(prefix) { - var id = ++idCounter; - return baseToString(prefix) + id; + function parseType(value, type) { + switch (type) { + case 'DATETIME': + case 'TIMESTAMP': + return new Date(value); + case 'INTEGER': + return parseInt(value, 10); + default: + return value; + } } - module.exports = uniqueId; - - -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var makeKnex = __webpack_require__(5); - var Promise = __webpack_require__(8); - var helpers = __webpack_require__(2); - var inherits = __webpack_require__(47); - var EventEmitter = __webpack_require__(43).EventEmitter; - - function Transaction_WebSQL(client, container) { - helpers.warn('WebSQL transactions will run queries, but do not commit or rollback'); - var trx = this; - this._promise = Promise['try'](function () { - container(makeKnex(makeClient(trx, client))); - }); + function handleRow(row, metadata) { + var keys = Object.keys(metadata); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var type = metadata[key].type; + row[key] = parseType(row[key], type); + } + return row; } - inherits(Transaction_WebSQL, EventEmitter); - - function makeClient(trx, client) { - - var trxClient = Object.create(client.constructor.prototype); - trxClient.config = client.config; - trxClient.connectionSettings = client.connectionSettings; - trxClient.transacting = true; - - trxClient.on('query', function (arg) { - trx.emit('query', arg); - client.emit('query', arg); - }); - trxClient.commit = function () {}; - trxClient.rollback = function () {}; - return trxClient; + function handleRows(rows, metadata) { + for (var i = 0; i < rows.length; i++) { + var row = rows[i]; + handleRow(row, metadata); + } + return rows; } - var promiseInterface = ['then', 'bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'nodeify', 'exec']; - - // Creates a method which "coerces" to a promise, by calling a - // "then" method on the current `Target` - promiseInterface.forEach(function (method) { - Transaction_WebSQL.prototype[method] = function () { - return this._promise = this._promise[method].apply(this._promise, arguments); - }; - }); - - module.exports = Transaction_WebSQL; + module.exports = Client_MariaSQL; /***/ }, -/* 35 */ +/* 30 */ /***/ function(module, exports, __webpack_require__) { - // SQLite3 + // MSSQL Client // ------- 'use strict'; - var _ = __webpack_require__(11); - var Promise = __webpack_require__(8); + var _lodash = __webpack_require__(1); - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - var pluck = __webpack_require__(75); + var inherits = __webpack_require__(51); - var Client = __webpack_require__(3); - var helpers = __webpack_require__(2); + var Formatter = __webpack_require__(61); + var Client = __webpack_require__(4); + var Promise = __webpack_require__(9); + var helpers = __webpack_require__(3); - var QueryCompiler = __webpack_require__(76); - var SchemaCompiler = __webpack_require__(77); - var ColumnCompiler = __webpack_require__(78); - var TableCompiler = __webpack_require__(79); - var SQLite3_DDL = __webpack_require__(80); + var Transaction = __webpack_require__(62); + var QueryCompiler = __webpack_require__(63); + var SchemaCompiler = __webpack_require__(64); + var TableCompiler = __webpack_require__(65); + var ColumnCompiler = __webpack_require__(66); - function Client_SQLite3(config) { - Client.call(this, config); - if (_.isUndefined(config.useNullAsDefault)) { - helpers.warn('sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).'); + // Always initialize with the "QueryBuilder" and "QueryCompiler" + // objects, which extend the base 'lib/query/builder' and + // 'lib/query/compiler', respectively. + function Client_MSSQL(config) { + //#1235 mssql module wants 'server', not 'host'. This is to enforce the same options object across all dialects. + if (config && config.connection && config.connection.host) { + config.connection.server = config.connection.host; } + Client.call(this, config); } - inherits(Client_SQLite3, Client); + inherits(Client_MSSQL, Client); - assign(Client_SQLite3.prototype, { + (0, _lodash.assign)(Client_MSSQL.prototype, { - dialect: 'sqlite3', + dialect: 'mssql', - driverName: 'sqlite3', + driverName: 'mssql', _driver: function _driver() { - return __webpack_require__(49); + return __webpack_require__(44); }, - SchemaCompiler: SchemaCompiler, + Transaction: Transaction, + + Formatter: Formatter, QueryCompiler: QueryCompiler, - ColumnCompiler: ColumnCompiler, + SchemaCompiler: SchemaCompiler, TableCompiler: TableCompiler, - ddl: function ddl(compiler, pragma, connection) { - return new SQLite3_DDL(this, compiler, pragma, connection); + ColumnCompiler: ColumnCompiler, + + wrapIdentifier: function wrapIdentifier(value) { + return value !== '*' ? '[' + value.replace(/\[/g, '\[') + ']' : '*'; }, - // Get a raw connection from the database, returning a promise with the connection object. + // Get a raw connection, called by the `pool` whenever a new + // connection needs to be added to the pool. acquireRawConnection: function acquireRawConnection() { var client = this; - return new Promise(function (resolve, reject) { - var db = new client.driver.Database(client.connectionSettings.filename, function (err) { - if (err) return reject(err); - resolve(db); + var connection = new this.driver.Connection(this.connectionSettings); + return new Promise(function (resolver, rejecter) { + connection.connect(function (err) { + if (err) return rejecter(err); + connection.on('error', connectionErrorHandler.bind(null, client, connection)); + connection.on('end', connectionErrorHandler.bind(null, client, connection)); + resolver(connection); }); }); }, @@ -4459,189 +4402,230 @@ return /******/ (function(modules) { // webpackBootstrap // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. destroyRawConnection: function destroyRawConnection(connection, cb) { - connection.close(); - cb(); + connection.close(cb); }, - // Runs the query on the specified connection, providing the bindings and any other necessary prep work. - _query: function _query(connection, obj) { - var method = obj.method; - var callMethod; - switch (method) { - case 'insert': - case 'update': - case 'counter': - case 'del': - callMethod = 'run'; - break; - default: - callMethod = 'all'; - } - return new Promise(function (resolver, rejecter) { - if (!connection || !connection[callMethod]) { - return rejecter(new Error('Error calling ' + callMethod + ' on connection.')); - } - connection[callMethod](obj.sql, obj.bindings, function (err, response) { - if (err) return rejecter(err); - obj.response = response; - - // We need the context here, as it contains - // the "this.lastID" or "this.changes" - obj.context = this; - return resolver(obj); - }); + // Position the bindings for the query. + positionBindings: function positionBindings(sql) { + var questionCount = -1; + return sql.replace(/\?/g, function () { + questionCount += 1; + return '@p' + questionCount; }); }, - _stream: function _stream(connection, sql, stream) { - var client = this; - return new Promise(function (resolver, rejecter) { - stream.on('error', rejecter); + prepBindings: function prepBindings(bindings) { + var _this = this; + + return (0, _lodash.map)(bindings, function (value) { + if (value === undefined) { + return _this.valueForUndefined; + } + return value; + }); + }, + + // Grab a connection, run the query via the MSSQL streaming interface, + // and pass that through to the stream we've sent back to the client. + _stream: function _stream(connection, obj, stream, options) { + options = options || {}; + if (!obj || typeof obj === 'string') obj = { sql: obj }; + // convert ? params into positional bindings (@p1) + obj.sql = this.positionBindings(obj.sql); + return new Promise(function (resolver, rejecter) { + stream.on('error', rejecter); stream.on('end', resolver); - return client._query(connection, sql).then(function (obj) { - return obj.response; - }).map(function (row) { - stream.write(row); - })['catch'](function (err) { - stream.emit('error', err); - }).then(function () { - stream.end(); - }); + var sql = obj.sql; + if (!sql) return resolver(); + if (obj.options) sql = (0, _lodash.assign)({ sql: sql }, obj.options).sql; + var req = (connection.tx_ || connection).request(); + //req.verbose = true; + req.multiple = true; + req.stream = true; + if (obj.bindings) { + for (var i = 0; i < obj.bindings.length; i++) { + req.input('p' + i, obj.bindings[i]); + } + } + req.pipe(stream); + req.query(sql); }); }, - prepBindings: function prepBindings(bindings) { - return _.map(bindings, function (binding) { - if (binding === undefined && this.valueForUndefined !== null) { - throw new TypeError("`sqlite` does not support inserting default values. Specify values explicitly or use the `useNullAsDefault` config flag. (see docs http://knexjs.org/#Builder-insert)."); - } else { - return binding; + // Runs the query on the specified connection, providing the bindings + // and any other necessary prep work. + _query: function _query(connection, obj) { + if (!obj || typeof obj === 'string') obj = { sql: obj }; + // convert ? params into positional bindings (@p1) + obj.sql = this.positionBindings(obj.sql); + return new Promise(function (resolver, rejecter) { + var sql = obj.sql; + if (!sql) return resolver(); + if (obj.options) sql = (0, _lodash.assign)({ sql: sql }, obj.options).sql; + var req = (connection.tx_ || connection).request(); + // req.verbose = true; + req.multiple = true; + if (obj.bindings) { + for (var i = 0; i < obj.bindings.length; i++) { + req.input('p' + i, obj.bindings[i]); + } } - }, this); + req.query(sql, function (err, recordset) { + if (err) return rejecter(err); + obj.response = recordset[0]; + resolver(obj); + }); + }); }, - // Ensures the response is returned in the same format as other clients. + // Process the response as returned from the query. processResponse: function processResponse(obj, runner) { - var ctx = obj.context; + if (obj == null) return; var response = obj.response; + var method = obj.method; if (obj.output) return obj.output.call(runner, response); - switch (obj.method) { + switch (method) { case 'select': case 'pluck': case 'first': response = helpers.skim(response); - if (obj.method === 'pluck') response = pluck(response, obj.pluck); - return obj.method === 'first' ? response[0] : response; + if (method === 'pluck') return (0, _lodash.map)(response, obj.pluck); + return method === 'first' ? response[0] : response; case 'insert': - return [ctx.lastID]; case 'del': case 'update': case 'counter': - return ctx.changes; + if (obj.returning) { + if (obj.returning === '@@rowcount') { + return response[0]['']; + } + if (Array.isArray(obj.returning) && obj.returning.length > 1 || obj.returning[0] === '*') { + return response; + } + // return an array with values if only one returning value was specified + return (0, _lodash.flatten)((0, _lodash.map)(response, _lodash.values)); + } + return response; default: return response; } }, - poolDefaults: function poolDefaults(config) { - return assign(Client.prototype.poolDefaults.call(this, config), { - min: 1, - max: 1 - }); + ping: function ping(resource, callback) { + resource.request().query('SELECT 1', callback); } }); - module.exports = Client_SQLite3; + // MSSQL Specific error handler + function connectionErrorHandler(client, connection, err) { + if (connection && err && err.fatal) { + if (connection.__knex__disposed) return; + connection.__knex__disposed = true; + client.pool.destroy(connection); + } + } + + module.exports = Client_MSSQL; /***/ }, -/* 36 */ +/* 31 */ /***/ function(module, exports, __webpack_require__) { - // MariaSQL Client + // MySQL Client // ------- 'use strict'; - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - var Client_MySQL = __webpack_require__(38); - var Promise = __webpack_require__(8); - var SqlString = __webpack_require__(26); - var helpers = __webpack_require__(2); - var pluck = __webpack_require__(75); - var Transaction = __webpack_require__(86); + var _lodash = __webpack_require__(1); - function Client_MariaSQL(config) { - Client_MySQL.call(this, config); + // Always initialize with the "QueryBuilder" and "QueryCompiler" + // objects, which extend the base 'lib/query/builder' and + // 'lib/query/compiler', respectively. + var inherits = __webpack_require__(51); + + var Client = __webpack_require__(4); + var Promise = __webpack_require__(9); + var helpers = __webpack_require__(3); + + var Transaction = __webpack_require__(56); + var QueryCompiler = __webpack_require__(57); + var SchemaCompiler = __webpack_require__(58); + var TableCompiler = __webpack_require__(59); + var ColumnCompiler = __webpack_require__(60); + + function Client_MySQL(config) { + Client.call(this, config); } - inherits(Client_MariaSQL, Client_MySQL); + inherits(Client_MySQL, Client); - assign(Client_MariaSQL.prototype, { + (0, _lodash.assign)(Client_MySQL.prototype, { - dialect: 'mariadb', + dialect: 'mysql', - driverName: 'mariasql', + driverName: 'mysql', + + _driver: function _driver() { + return __webpack_require__(43); + }, + + QueryCompiler: QueryCompiler, + + SchemaCompiler: SchemaCompiler, + + TableCompiler: TableCompiler, + + ColumnCompiler: ColumnCompiler, Transaction: Transaction, - _driver: function _driver() { - return __webpack_require__(51); + wrapIdentifier: function wrapIdentifier(value) { + return value !== '*' ? '`' + value.replace(/`/g, '``') + '`' : '*'; }, // Get a raw connection, called by the `pool` whenever a new // connection needs to be added to the pool. acquireRawConnection: function acquireRawConnection() { - var connection = new this.driver(); - connection.connect(assign({ metadata: true }, this.connectionSettings)); + var client = this; + var connection = this.driver.createConnection(this.connectionSettings); return new Promise(function (resolver, rejecter) { - connection.on('ready', function () { - connection.removeAllListeners('end'); - connection.removeAllListeners('error'); + connection.connect(function (err) { + if (err) return rejecter(err); + connection.on('error', client._connectionErrorHandler.bind(null, client, connection)); + connection.on('end', client._connectionErrorHandler.bind(null, client, connection)); resolver(connection); - }).on('error', rejecter); + }); }); }, // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. destroyRawConnection: function destroyRawConnection(connection, cb) { - connection.end(); - cb(); - }, - - // Return the database for the MariaSQL client. - database: function database() { - return this.connectionSettings.db; + connection.end(cb); }, - // Grab a connection, run the query via the MariaSQL streaming interface, + // Grab a connection, run the query via the MySQL streaming interface, // and pass that through to the stream we've sent back to the client. - _stream: function _stream(connection, sql, stream) { + _stream: function _stream(connection, obj, stream, options) { + options = options || {}; return new Promise(function (resolver, rejecter) { - connection.query(sql.sql, sql.bindings).on('result', function (res) { - res.on('error', rejecter).on('end', function () { - resolver(res.info); - }).on('data', function (data) { - stream.write(handleRow(data, res.info.metadata)); - }); - }).on('error', rejecter); + stream.on('error', rejecter); + stream.on('end', resolver); + connection.query(obj.sql, obj.bindings).stream(options).pipe(stream); }); }, // Runs the query on the specified connection, providing the bindings // and any other necessary prep work. _query: function _query(connection, obj) { - var tz = this.connectionSettings.timezone || 'local'; + if (!obj || typeof obj === 'string') obj = { sql: obj }; return new Promise(function (resolver, rejecter) { - if (!obj.sql) return resolver(); - var sql = SqlString.format(obj.sql, obj.bindings, tz); - connection.query(sql, function (err, rows) { - if (err) { - return rejecter(err); - } - handleRows(rows, rows.info.metadata); - obj.response = [rows, rows.info]; + var sql = obj.sql; + if (!sql) return resolver(); + if (obj.options) sql = (0, _lodash.assign)({ sql: sql }, obj.options); + connection.query(sql, obj.bindings, function (err, rows, fields) { + if (err) return rejecter(err); + obj.response = [rows, fields]; resolver(obj); }); }); @@ -4649,326 +4633,219 @@ return /******/ (function(modules) { // webpackBootstrap // Process the response as returned from the query. processResponse: function processResponse(obj, runner) { + if (obj == null) return; var response = obj.response; var method = obj.method; var rows = response[0]; - var data = response[1]; - if (obj.output) return obj.output.call(runner, rows /*, fields*/); + var fields = response[1]; + if (obj.output) return obj.output.call(runner, rows, fields); switch (method) { case 'select': case 'pluck': case 'first': var resp = helpers.skim(rows); - if (method === 'pluck') return pluck(resp, obj.pluck); + if (method === 'pluck') return (0, _lodash.map)(resp, obj.pluck); return method === 'first' ? resp[0] : resp; case 'insert': - return [data.insertId]; + return [rows.insertId]; case 'del': case 'update': case 'counter': - return parseInt(data.affectedRows, 10); + return rows.affectedRows; default: return response; } - } - - }); + }, - function parseType(value, type) { - switch (type) { - case 'DATETIME': - case 'TIMESTAMP': - return new Date(value); - case 'INTEGER': - return parseInt(value, 10); - default: - return value; - } - } + // MySQL Specific error handler + _connectionErrorHandler: function _connectionErrorHandler(client, connection, err) { + if (connection && err && err.fatal && !connection.__knex__disposed) { + connection.__knex__disposed = true; + client.pool.destroy(connection); + } + }, - function handleRow(row, metadata) { - var keys = Object.keys(metadata); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var type = metadata[key].type; - row[key] = parseType(row[key], type); + ping: function ping(resource, callback) { + resource.query('SELECT 1', callback); } - return row; - } - function handleRows(rows, metadata) { - for (var i = 0; i < rows.length; i++) { - var row = rows[i]; - handleRow(row, metadata); - } - return rows; - } + }); - module.exports = Client_MariaSQL; + module.exports = Client_MySQL; /***/ }, -/* 37 */ +/* 32 */ /***/ function(module, exports, __webpack_require__) { - // MSSQL Client + // MySQL2 Client // ------- 'use strict'; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); + + var inherits = __webpack_require__(51); + var Client_MySQL = __webpack_require__(31); + var Promise = __webpack_require__(9); + var helpers = __webpack_require__(3); - var Formatter = __webpack_require__(87); - var Client = __webpack_require__(3); - var Promise = __webpack_require__(8); - var helpers = __webpack_require__(2); + var Transaction = __webpack_require__(67); - var Transaction = __webpack_require__(88); - var QueryCompiler = __webpack_require__(89); - var SchemaCompiler = __webpack_require__(90); - var TableCompiler = __webpack_require__(91); - var ColumnCompiler = __webpack_require__(92); + var configOptions = ['isServer', 'stream', 'host', 'port', 'localAddress', 'socketPath', 'user', 'password', 'passwordSha1', 'database', 'connectTimeout', 'insecureAuth', 'supportBigNumbers', 'bigNumberStrings', 'decimalNumbers', 'dateStrings', 'debug', 'trace', 'stringifyObjects', 'timezone', 'flags', 'queryFormat', 'pool', 'ssl', 'multipleStatements', 'namedPlaceholders', 'typeCast', 'charsetNumber', 'compress']; // Always initialize with the "QueryBuilder" and "QueryCompiler" // objects, which extend the base 'lib/query/builder' and // 'lib/query/compiler', respectively. - function Client_MSSQL(config) { - Client.call(this, config); + function Client_MySQL2(config) { + Client_MySQL.call(this, config); } - inherits(Client_MSSQL, Client); + inherits(Client_MySQL2, Client_MySQL); - assign(Client_MSSQL.prototype, { + (0, _lodash.assign)(Client_MySQL2.prototype, { - dialect: 'mssql', + // The "dialect", for reference elsewhere. + driverName: 'mysql2', - driverName: 'mssql', + Transaction: Transaction, _driver: function _driver() { - return __webpack_require__(52); - }, - - Transaction: Transaction, - - Formatter: Formatter, - - QueryCompiler: QueryCompiler, - - SchemaCompiler: SchemaCompiler, - - TableCompiler: TableCompiler, - - ColumnCompiler: ColumnCompiler, - - wrapIdentifier: function wrapIdentifier(value) { - return value !== '*' ? '[' + value.replace(/\[/g, '\[') + ']' : '*'; + return __webpack_require__(45); }, // Get a raw connection, called by the `pool` whenever a new // connection needs to be added to the pool. acquireRawConnection: function acquireRawConnection() { var client = this; - var connection = new this.driver.Connection(this.connectionSettings); + var connection = this.driver.createConnection((0, _lodash.pick)(this.connectionSettings, configOptions)); return new Promise(function (resolver, rejecter) { connection.connect(function (err) { if (err) return rejecter(err); - connection.on('error', connectionErrorHandler.bind(null, client, connection)); - connection.on('end', connectionErrorHandler.bind(null, client, connection)); + connection.on('error', client._connectionErrorHandler.bind(null, client, connection)); resolver(connection); }); }); }, - // Used to explicitly close a connection, called internally by the pool - // when a connection times out or the pool is shutdown. - destroyRawConnection: function destroyRawConnection(connection, cb) { - connection.close(cb); - }, - - // Position the bindings for the query. - positionBindings: function positionBindings(sql) { - var questionCount = -1; - return sql.replace(/\?/g, function () { - questionCount += 1; - return '@p' + questionCount; - }); - }, - - prepBindings: function prepBindings(bindings) { - return _.map(bindings, function (value) { - if (value === undefined) { - return this.valueForUndefined; - } - return value; - }, this); - }, - - // Grab a connection, run the query via the MSSQL streaming interface, - // and pass that through to the stream we've sent back to the client. - _stream: function _stream(connection, obj, stream, options) { - options = options || {}; - if (!obj || typeof obj === 'string') obj = { sql: obj }; - // convert ? params into positional bindings (@p1) - obj.sql = this.positionBindings(obj.sql); - obj.bindings = this.prepBindings(obj.bindings) || []; - return new Promise(function (resolver, rejecter) { - stream.on('error', rejecter); - stream.on('end', resolver); - var sql = obj.sql; - if (!sql) return resolver(); - if (obj.options) sql = assign({ sql: sql }, obj.options).sql; - var req = (connection.tx_ || connection).request(); - //req.verbose = true; - req.multiple = true; - req.stream = true; - if (obj.bindings) { - for (var i = 0; i < obj.bindings.length; i++) { - req.input('p' + i, obj.bindings[i]); - } - } - req.pipe(stream); - req.query(sql); - }); - }, - - // Runs the query on the specified connection, providing the bindings - // and any other necessary prep work. - _query: function _query(connection, obj) { - if (!obj || typeof obj === 'string') obj = { sql: obj }; - // convert ? params into positional bindings (@p1) - obj.sql = this.positionBindings(obj.sql); - obj.bindings = this.prepBindings(obj.bindings) || []; - return new Promise(function (resolver, rejecter) { - var sql = obj.sql; - if (!sql) return resolver(); - if (obj.options) sql = assign({ sql: sql }, obj.options).sql; - var req = (connection.tx_ || connection).request(); - // req.verbose = true; - req.multiple = true; - if (obj.bindings) { - for (var i = 0; i < obj.bindings.length; i++) { - req.input('p' + i, obj.bindings[i]); - } - } - req.query(sql, function (err, recordset) { - if (err) return rejecter(err); - obj.response = recordset[0]; - resolver(obj); - }); - }); - }, - - // Process the response as returned from the query. processResponse: function processResponse(obj, runner) { - if (obj == null) return; var response = obj.response; var method = obj.method; - if (obj.output) return obj.output.call(runner, response); + var rows = response[0]; + var fields = response[1]; + if (obj.output) return obj.output.call(runner, rows, fields); switch (method) { case 'select': case 'pluck': case 'first': - response = helpers.skim(response); - if (method === 'pluck') return _.pluck(response, obj.pluck); - return method === 'first' ? response[0] : response; + var resp = helpers.skim(rows); + if (method === 'pluck') return (0, _lodash.map)(resp, obj.pluck); + return method === 'first' ? resp[0] : resp; case 'insert': + return [rows.insertId]; case 'del': case 'update': case 'counter': - if (obj.returning) { - if (obj.returning === '@@rowcount') { - return response[0]['']; - } - if (Array.isArray(obj.returning) && obj.returning.length > 1 || obj.returning[0] === '*') { - return response; - } - // return an array with values if only one returning value was specified - return _.flatten(_.map(response, _.values)); - } - return response; + return rows.affectedRows; default: return response; } + }, + + ping: function ping(resource, callback) { + resource.query('SELECT 1', callback); } }); - // MSSQL Specific error handler - function connectionErrorHandler(client, connection, err) { - if (connection && err && err.fatal) { - if (connection.__knex__disposed) return; - connection.__knex__disposed = true; - client.pool.destroy(connection); - } - } - - module.exports = Client_MSSQL; + module.exports = Client_MySQL2; /***/ }, -/* 38 */ +/* 33 */ /***/ function(module, exports, __webpack_require__) { - - // MySQL Client + /* WEBPACK VAR INJECTION */(function(Buffer) { + // Oracle Client // ------- 'use strict'; - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - var Client = __webpack_require__(3); - var Promise = __webpack_require__(8); - var helpers = __webpack_require__(2); + var inherits = __webpack_require__(51); + var Formatter = __webpack_require__(68); + var Client = __webpack_require__(4); + var Promise = __webpack_require__(9); + var helpers = __webpack_require__(3); + var SqlString = __webpack_require__(28); - var Transaction = __webpack_require__(81); - var QueryCompiler = __webpack_require__(82); - var SchemaCompiler = __webpack_require__(83); - var TableCompiler = __webpack_require__(84); - var ColumnCompiler = __webpack_require__(85); - var pluck = __webpack_require__(75); + var Transaction = __webpack_require__(69); + var QueryCompiler = __webpack_require__(70); + var SchemaCompiler = __webpack_require__(71); + var ColumnBuilder = __webpack_require__(72); + var ColumnCompiler = __webpack_require__(73); + var TableCompiler = __webpack_require__(74); + var OracleQueryStream = __webpack_require__(75); + var ReturningHelper = __webpack_require__(76).ReturningHelper; // Always initialize with the "QueryBuilder" and "QueryCompiler" // objects, which extend the base 'lib/query/builder' and // 'lib/query/compiler', respectively. - function Client_MySQL(config) { + function Client_Oracle(config) { Client.call(this, config); } - inherits(Client_MySQL, Client); + inherits(Client_Oracle, Client); - assign(Client_MySQL.prototype, { + (0, _lodash.assign)(Client_Oracle.prototype, { - dialect: 'mysql', + dialect: 'oracle', - driverName: 'mysql', + driverName: 'oracle', _driver: function _driver() { - return __webpack_require__(50); + return __webpack_require__(46); }, + Transaction: Transaction, + + Formatter: Formatter, + QueryCompiler: QueryCompiler, SchemaCompiler: SchemaCompiler, - TableCompiler: TableCompiler, + ColumnBuilder: ColumnBuilder, ColumnCompiler: ColumnCompiler, - Transaction: Transaction, + TableCompiler: TableCompiler, - wrapIdentifier: function wrapIdentifier(value) { - return value !== '*' ? '`' + value.replace(/`/g, '``') + '`' : '*'; + prepBindings: function prepBindings(bindings) { + var _this = this; + + return (0, _lodash.map)(bindings, function (value) { + // returning helper uses always ROWID as string + if (value instanceof ReturningHelper && _this.driver) { + return new _this.driver.OutParam(_this.driver.OCCISTRING); + } else if (typeof value === 'boolean') { + return value ? 1 : 0; + } else if (Buffer.isBuffer(value)) { + return SqlString.bufferToString(value); + } else if (value === undefined) { + return _this.valueForUndefined; + } + return value; + }); }, // Get a raw connection, called by the `pool` whenever a new // connection needs to be added to the pool. acquireRawConnection: function acquireRawConnection() { var client = this; - var connection = this.driver.createConnection(this.connectionSettings); return new Promise(function (resolver, rejecter) { - connection.connect(function (err) { + client.driver.connect(client.connectionSettings, function (err, connection) { if (err) return rejecter(err); - connection.on('error', connectionErrorHandler.bind(null, client, connection)); - connection.on('end', connectionErrorHandler.bind(null, client, connection)); + Promise.promisifyAll(connection); + if (client.connectionSettings.prefetchRowCount) { + connection.setPrefetchRowCount(client.connectionSettings.prefetchRowCount); + } resolver(connection); }); }); @@ -4977,355 +4854,114 @@ return /******/ (function(modules) { // webpackBootstrap // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. destroyRawConnection: function destroyRawConnection(connection, cb) { - connection.end(cb); + connection.close(); + cb(); + }, + + // Return the database for the Oracle client. + database: function database() { + return this.connectionSettings.database; + }, + + // Position the bindings for the query. + positionBindings: function positionBindings(sql) { + var questionCount = 0; + return sql.replace(/\?/g, function () { + questionCount += 1; + return ':' + questionCount; + }); }, - // Grab a connection, run the query via the MySQL streaming interface, - // and pass that through to the stream we've sent back to the client. _stream: function _stream(connection, obj, stream, options) { - options = options || {}; + obj.sql = this.positionBindings(obj.sql); return new Promise(function (resolver, rejecter) { stream.on('error', rejecter); stream.on('end', resolver); - connection.query(obj.sql, obj.bindings).stream(options).pipe(stream); + var queryStream = new OracleQueryStream(connection, obj.sql, obj.bindings, options); + queryStream.pipe(stream); }); }, // Runs the query on the specified connection, providing the bindings // and any other necessary prep work. _query: function _query(connection, obj) { - if (!obj || typeof obj === 'string') obj = { sql: obj }; - return new Promise(function (resolver, rejecter) { - var sql = obj.sql; - if (!sql) return resolver(); - if (obj.options) sql = assign({ sql: sql }, obj.options); - connection.query(sql, obj.bindings, function (err, rows, fields) { - if (err) return rejecter(err); - obj.response = [rows, fields]; - resolver(obj); + + // convert ? params into positional bindings (:1) + obj.sql = this.positionBindings(obj.sql); + + if (!obj.sql) throw new Error('The query is empty'); + + return connection.executeAsync(obj.sql, obj.bindings).then(function (response) { + if (!obj.returning) return response; + var rowIds = obj.outParams.map(function (v, i) { + return response['returnParam' + (i ? i : '')]; }); + return connection.executeAsync(obj.returningSql, rowIds); + }).then(function (response) { + obj.response = response; + return obj; }); }, // Process the response as returned from the query. processResponse: function processResponse(obj, runner) { - if (obj == null) return; var response = obj.response; var method = obj.method; - var rows = response[0]; - var fields = response[1]; - if (obj.output) return obj.output.call(runner, rows, fields); + if (obj.output) return obj.output.call(runner, response); switch (method) { case 'select': case 'pluck': case 'first': - var resp = helpers.skim(rows); - if (method === 'pluck') return pluck(resp, obj.pluck); - return method === 'first' ? resp[0] : resp; + response = helpers.skim(response); + if (obj.method === 'pluck') response = (0, _lodash.map)(response, obj.pluck); + return obj.method === 'first' ? response[0] : response; case 'insert': - return [rows.insertId]; case 'del': case 'update': case 'counter': - return rows.affectedRows; + if (obj.returning) { + if (obj.returning.length > 1 || obj.returning[0] === '*') { + return response; + } + // return an array with values if only one returning value was specified + return (0, _lodash.flatten)((0, _lodash.map)(response, _lodash.values)); + } + return response.updateCount; default: return response; } + }, + + ping: function ping(resource, callback) { + resource.execute('SELECT 1', [], callback); } }); - // MySQL Specific error handler - function connectionErrorHandler(client, connection, err) { - if (connection && err && err.fatal) { - if (connection.__knex__disposed) return; - connection.__knex__disposed = true; - client.pool.destroy(connection); - } - } - - module.exports = Client_MySQL; + module.exports = Client_Oracle; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 39 */ +/* 34 */ /***/ function(module, exports, __webpack_require__) { - - // MySQL2 Client + /* WEBPACK VAR INJECTION */(function(process) { + // PostgreSQL // ------- 'use strict'; - var inherits = __webpack_require__(47); - var Client_MySQL = __webpack_require__(38); - var Promise = __webpack_require__(8); - var helpers = __webpack_require__(2); - var pick = __webpack_require__(93); - var pluck = __webpack_require__(75); - var assign = __webpack_require__(29); - var Transaction = __webpack_require__(94); - - var configOptions = ['isServer', 'stream', 'host', 'port', 'localAddress', 'socketPath', 'user', 'password', 'passwordSha1', 'database', 'connectTimeout', 'insecureAuth', 'supportBigNumbers', 'bigNumberStrings', 'decimalNumbers', 'dateStrings', 'debug', 'trace', 'stringifyObjects', 'timezone', 'flags', 'queryFormat', 'pool', 'ssl', 'multipleStatements', 'namedPlaceholders', 'typeCast', 'charsetNumber', 'compress']; + var _lodash = __webpack_require__(1); - // Always initialize with the "QueryBuilder" and "QueryCompiler" - // objects, which extend the base 'lib/query/builder' and - // 'lib/query/compiler', respectively. - function Client_MySQL2(config) { - Client_MySQL.call(this, config); - } - inherits(Client_MySQL2, Client_MySQL); + var inherits = __webpack_require__(51); + var Client = __webpack_require__(4); + var Promise = __webpack_require__(9); + var utils = __webpack_require__(77); - assign(Client_MySQL2.prototype, { - - // The "dialect", for reference elsewhere. - driverName: 'mysql2', - - Transaction: Transaction, - - _driver: function _driver() { - return __webpack_require__(53); - }, - - // Get a raw connection, called by the `pool` whenever a new - // connection needs to be added to the pool. - acquireRawConnection: function acquireRawConnection() { - var connection = this.driver.createConnection(pick(this.connectionSettings, configOptions)); - return new Promise(function (resolver, rejecter) { - connection.connect(function (err) { - if (err) return rejecter(err); - resolver(connection); - }); - }); - }, - - processResponse: function processResponse(obj, runner) { - var response = obj.response; - var method = obj.method; - var rows = response[0]; - var fields = response[1]; - if (obj.output) return obj.output.call(runner, rows, fields); - switch (method) { - case 'select': - case 'pluck': - case 'first': - var resp = helpers.skim(rows); - if (method === 'pluck') return pluck(resp, obj.pluck); - return method === 'first' ? resp[0] : resp; - case 'insert': - return [rows.insertId]; - case 'del': - case 'update': - case 'counter': - return rows.affectedRows; - default: - return response; - } - } - - }); - - module.exports = Client_MySQL2; - -/***/ }, -/* 40 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) { - // Oracle Client - // ------- - 'use strict'; - - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - - var Formatter = __webpack_require__(95); - var Client = __webpack_require__(3); - var Promise = __webpack_require__(8); - var helpers = __webpack_require__(2); - var SqlString = __webpack_require__(26); - - var Transaction = __webpack_require__(96); - var QueryCompiler = __webpack_require__(97); - var SchemaCompiler = __webpack_require__(98); - var ColumnBuilder = __webpack_require__(99); - var ColumnCompiler = __webpack_require__(100); - var TableCompiler = __webpack_require__(101); - var OracleQueryStream = __webpack_require__(102); - var ReturningHelper = __webpack_require__(103).ReturningHelper; - - // Always initialize with the "QueryBuilder" and "QueryCompiler" - // objects, which extend the base 'lib/query/builder' and - // 'lib/query/compiler', respectively. - function Client_Oracle(config) { - Client.call(this, config); - } - inherits(Client_Oracle, Client); - - assign(Client_Oracle.prototype, { - - dialect: 'oracle', - - driverName: 'oracle', - - _driver: function _driver() { - return __webpack_require__(54); - }, - - Transaction: Transaction, - - Formatter: Formatter, - - QueryCompiler: QueryCompiler, - - SchemaCompiler: SchemaCompiler, - - ColumnBuilder: ColumnBuilder, - - ColumnCompiler: ColumnCompiler, - - TableCompiler: TableCompiler, - - prepBindings: function prepBindings(bindings) { - return _.map(bindings, function (value) { - // returning helper uses always ROWID as string - if (value instanceof ReturningHelper && this.driver) { - return new this.driver.OutParam(this.driver.OCCISTRING); - } else if (typeof value === 'boolean') { - return value ? 1 : 0; - } else if (Buffer.isBuffer(value)) { - return SqlString.bufferToString(value); - } else if (value === undefined) { - return this.valueForUndefined; - } - return value; - }, this); - }, - - // Get a raw connection, called by the `pool` whenever a new - // connection needs to be added to the pool. - acquireRawConnection: function acquireRawConnection() { - var client = this; - return new Promise(function (resolver, rejecter) { - client.driver.connect(client.connectionSettings, function (err, connection) { - if (err) return rejecter(err); - Promise.promisifyAll(connection); - if (client.connectionSettings.prefetchRowCount) { - connection.setPrefetchRowCount(client.connectionSettings.prefetchRowCount); - } - resolver(connection); - }); - }); - }, - - // Used to explicitly close a connection, called internally by the pool - // when a connection times out or the pool is shutdown. - destroyRawConnection: function destroyRawConnection(connection, cb) { - connection.close(); - cb(); - }, - - // Return the database for the Oracle client. - database: function database() { - return this.connectionSettings.database; - }, - - // Position the bindings for the query. - positionBindings: function positionBindings(sql) { - var questionCount = 0; - return sql.replace(/\?/g, function () { - questionCount += 1; - return ':' + questionCount; - }); - }, - - _stream: function _stream(connection, obj, stream, options) { - obj.sql = this.positionBindings(obj.sql); - return new Promise(function (resolver, rejecter) { - stream.on('error', rejecter); - stream.on('end', resolver); - var queryStream = new OracleQueryStream(connection, obj.sql, obj.bindings, options); - queryStream.pipe(stream); - }); - }, - - // Runs the query on the specified connection, providing the bindings - // and any other necessary prep work. - _query: function _query(connection, obj) { - - // convert ? params into positional bindings (:1) - obj.sql = this.positionBindings(obj.sql); - - obj.bindings = this.prepBindings(obj.bindings) || []; - - if (!obj.sql) throw new Error('The query is empty'); - - return connection.executeAsync(obj.sql, obj.bindings).then(function (response) { - if (!obj.returning) return response; - var rowIds = obj.outParams.map(function (v, i) { - return response['returnParam' + (i ? i : '')]; - }); - return connection.executeAsync(obj.returningSql, rowIds); - }).then(function (response) { - obj.response = response; - return obj; - }); - }, - - // Process the response as returned from the query. - processResponse: function processResponse(obj, runner) { - var response = obj.response; - var method = obj.method; - if (obj.output) return obj.output.call(runner, response); - switch (method) { - case 'select': - case 'pluck': - case 'first': - response = helpers.skim(response); - if (obj.method === 'pluck') response = _.pluck(response, obj.pluck); - return obj.method === 'first' ? response[0] : response; - case 'insert': - case 'del': - case 'update': - case 'counter': - if (obj.returning) { - if (obj.returning.length > 1 || obj.returning[0] === '*') { - return response; - } - // return an array with values if only one returning value was specified - return _.flatten(_.map(response, _.values)); - } - return response.updateCount; - default: - return response; - } - } - - }); - - module.exports = Client_Oracle; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) - -/***/ }, -/* 41 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(process) { - // PostgreSQL - // ------- - 'use strict'; - - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var Client = __webpack_require__(3); - var Promise = __webpack_require__(8); - var utils = __webpack_require__(104); - var assign = __webpack_require__(29); - - var QueryCompiler = __webpack_require__(105); - var ColumnCompiler = __webpack_require__(106); - var TableCompiler = __webpack_require__(107); - var SchemaCompiler = __webpack_require__(108); - var PGQueryStream; + var QueryCompiler = __webpack_require__(78); + var ColumnCompiler = __webpack_require__(79); + var TableCompiler = __webpack_require__(80); + var SchemaCompiler = __webpack_require__(81); + var PGQueryStream; function Client_PG(config) { Client.apply(this, arguments); @@ -5339,7 +4975,7 @@ return /******/ (function(modules) { // webpackBootstrap } inherits(Client_PG, Client); - assign(Client_PG.prototype, { + (0, _lodash.assign)(Client_PG.prototype, { QueryCompiler: QueryCompiler, @@ -5354,7 +4990,7 @@ return /******/ (function(modules) { // webpackBootstrap driverName: 'pg', _driver: function _driver() { - return __webpack_require__(55); + return __webpack_require__(47); }, wrapIdentifier: function wrapIdentifier(value) { @@ -5366,9 +5002,11 @@ return /******/ (function(modules) { // webpackBootstrap // Prep the bindings as needed by PostgreSQL. prepBindings: function prepBindings(bindings, tz) { - return _.map(bindings, function (binding) { - return utils.prepareValue(binding, tz, this.valueForUndefined); - }, this); + var _this = this; + + return (0, _lodash.map)(bindings, function (binding) { + return utils.prepareValue(binding, tz, _this.valueForUndefined); + }); }, // Get a raw connection, called by the `pool` whenever a new @@ -5407,7 +5045,7 @@ return /******/ (function(modules) { // webpackBootstrap return new Promise(function (resolver, rejecter) { connection.query('select version();', function (err, resp) { if (err) return rejecter(err); - resolver(/^PostgreSQL (.*?) /.exec(resp.rows[0].version)[1]); + resolver(/^PostgreSQL (.*?)( |$)/.exec(resp.rows[0].version)[1]); }); }); }, @@ -5440,7 +5078,7 @@ return /******/ (function(modules) { // webpackBootstrap }, _stream: function _stream(connection, obj, stream, options) { - PGQueryStream = process.browser ? undefined : __webpack_require__(56); + PGQueryStream = process.browser ? undefined : __webpack_require__(48); var sql = obj.sql = this.positionBindings(obj.sql); return new Promise(function (resolver, rejecter) { var queryStream = connection.query(new PGQueryStream(sql, obj.bindings, options)); @@ -5457,7 +5095,7 @@ return /******/ (function(modules) { // webpackBootstrap // and any other necessary prep work. _query: function _query(connection, obj) { var sql = obj.sql = this.positionBindings(obj.sql); - if (obj.options) sql = _.extend({ text: sql }, obj.options); + if (obj.options) sql = (0, _lodash.extend)({ text: sql }, obj.options); return new Promise(function (resolver, rejecter) { connection.query(sql, obj.bindings, function (err, response) { if (err) return rejecter(err); @@ -5475,7 +5113,7 @@ return /******/ (function(modules) { // webpackBootstrap var returning = obj.returning; if (resp.command === 'SELECT') { if (obj.method === 'first') return resp.rows[0]; - if (obj.method === 'pluck') return _.pluck(resp.rows, obj.pluck); + if (obj.method === 'pluck') return (0, _lodash.map)(resp.rows, obj.pluck); return resp.rows; } if (returning) { @@ -5502,64 +5140,287 @@ return /******/ (function(modules) { // webpackBootstrap connection.__knex__disposed = true; this.pool.destroy(connection); } + }, + + ping: function ping(resource, callback) { + resource.query('SELECT 1', [], callback); } }); module.exports = Client_PG; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) /***/ }, -/* 42 */ +/* 35 */ /***/ function(module, exports, __webpack_require__) { - // Oracle Client + // SQLite3 // ------- 'use strict'; - var inherits = __webpack_require__(47); - var Client_Oracle = __webpack_require__(40); + var _lodash = __webpack_require__(1); - function Client_StrongOracle() { - Client_Oracle.apply(this, arguments); - } - inherits(Client_StrongOracle, Client_Oracle); + var Promise = __webpack_require__(9); - Client_StrongOracle.prototype._driver = function () { - return __webpack_require__(57)(); - }; + var inherits = __webpack_require__(51); - Client_StrongOracle.prototype.driverName = 'strong-oracle'; + var Client = __webpack_require__(4); + var helpers = __webpack_require__(3); - module.exports = Client_StrongOracle; + var QueryCompiler = __webpack_require__(82); + var SchemaCompiler = __webpack_require__(83); + var ColumnCompiler = __webpack_require__(84); + var TableCompiler = __webpack_require__(85); + var SQLite3_DDL = __webpack_require__(86); -/***/ }, -/* 43 */ -/***/ function(module, exports, __webpack_require__) { + function Client_SQLite3(config) { + Client.call(this, config); + if ((0, _lodash.isUndefined)(config.useNullAsDefault)) { + helpers.warn('sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs http://knexjs.org/#Builder-insert).'); + } + } + inherits(Client_SQLite3, Client); - // 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. + (0, _lodash.assign)(Client_SQLite3.prototype, { - function EventEmitter() { + dialect: 'sqlite3', + + driverName: 'sqlite3', + + _driver: function _driver() { + return __webpack_require__(49); + }, + + SchemaCompiler: SchemaCompiler, + + QueryCompiler: QueryCompiler, + + ColumnCompiler: ColumnCompiler, + + TableCompiler: TableCompiler, + + ddl: function ddl(compiler, pragma, connection) { + return new SQLite3_DDL(this, compiler, pragma, connection); + }, + + // Get a raw connection from the database, returning a promise with the connection object. + acquireRawConnection: function acquireRawConnection() { + var client = this; + return new Promise(function (resolve, reject) { + var db = new client.driver.Database(client.connectionSettings.filename, function (err) { + if (err) return reject(err); + resolve(db); + }); + }); + }, + + // Used to explicitly close a connection, called internally by the pool + // when a connection times out or the pool is shutdown. + destroyRawConnection: function destroyRawConnection(connection, cb) { + connection.close(); + cb(); + }, + + // Runs the query on the specified connection, providing the bindings and any other necessary prep work. + _query: function _query(connection, obj) { + var method = obj.method; + var callMethod; + switch (method) { + case 'insert': + case 'update': + case 'counter': + case 'del': + callMethod = 'run'; + break; + default: + callMethod = 'all'; + } + return new Promise(function (resolver, rejecter) { + if (!connection || !connection[callMethod]) { + return rejecter(new Error('Error calling ' + callMethod + ' on connection.')); + } + connection[callMethod](obj.sql, obj.bindings, function (err, response) { + if (err) return rejecter(err); + obj.response = response; + + // We need the context here, as it contains + // the "this.lastID" or "this.changes" + obj.context = this; + return resolver(obj); + }); + }); + }, + + _stream: function _stream(connection, sql, stream) { + var client = this; + return new Promise(function (resolver, rejecter) { + stream.on('error', rejecter); + stream.on('end', resolver); + return client._query(connection, sql).then(function (obj) { + return obj.response; + }).map(function (row) { + stream.write(row); + })['catch'](function (err) { + stream.emit('error', err); + }).then(function () { + stream.end(); + }); + }); + }, + + prepBindings: function prepBindings(bindings) { + var _this = this; + + return (0, _lodash.map)(bindings, function (binding) { + if (binding === undefined && _this.valueForUndefined !== null) { + throw new TypeError("`sqlite` does not support inserting default values. Specify values explicitly or use the `useNullAsDefault` config flag. (see docs http://knexjs.org/#Builder-insert)."); + } else { + return binding; + } + }); + }, + + // Ensures the response is returned in the same format as other clients. + processResponse: function processResponse(obj, runner) { + var ctx = obj.context; + var response = obj.response; + if (obj.output) return obj.output.call(runner, response); + switch (obj.method) { + case 'select': + case 'pluck': + case 'first': + response = helpers.skim(response); + if (obj.method === 'pluck') response = (0, _lodash.map)(response, obj.pluck); + return obj.method === 'first' ? response[0] : response; + case 'insert': + return [ctx.lastID]; + case 'del': + case 'update': + case 'counter': + return ctx.changes; + default: + return response; + } + }, + + poolDefaults: function poolDefaults(config) { + return (0, _lodash.assign)(Client.prototype.poolDefaults.call(this, config), { + min: 1, + max: 1 + }); + }, + + ping: function ping(resource, callback) { + resource.each('SELECT 1', callback); + } + + }); + + module.exports = Client_SQLite3; + +/***/ }, +/* 36 */ +/***/ function(module, exports, __webpack_require__) { + + + // Oracle Client + // ------- + 'use strict'; + + var inherits = __webpack_require__(51); + var Client_Oracle = __webpack_require__(33); + + function Client_StrongOracle() { + Client_Oracle.apply(this, arguments); + } + inherits(Client_StrongOracle, Client_Oracle); + + Client_StrongOracle.prototype._driver = function () { + return __webpack_require__(50)(); + }; + + Client_StrongOracle.prototype.driverName = 'strong-oracle'; + + module.exports = Client_StrongOracle; + +/***/ }, +/* 37 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var makeKnex = __webpack_require__(6); + var Promise = __webpack_require__(9); + var helpers = __webpack_require__(3); + var inherits = __webpack_require__(51); + var EventEmitter = __webpack_require__(38).EventEmitter; + + function Transaction_WebSQL(client, container) { + helpers.warn('WebSQL transactions will run queries, but do not commit or rollback'); + var trx = this; + this._promise = Promise['try'](function () { + container(makeKnex(makeClient(trx, client))); + }); + } + inherits(Transaction_WebSQL, EventEmitter); + + function makeClient(trx, client) { + + var trxClient = Object.create(client.constructor.prototype); + trxClient.config = client.config; + trxClient.connectionSettings = client.connectionSettings; + trxClient.transacting = true; + + trxClient.on('query', function (arg) { + trx.emit('query', arg); + client.emit('query', arg); + }); + trxClient.commit = function () {}; + trxClient.rollback = function () {}; + + return trxClient; + } + + var promiseInterface = ['then', 'bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'exec', 'reflect']; + + // Creates a method which "coerces" to a promise, by calling a + // "then" method on the current `Target` + promiseInterface.forEach(function (method) { + Transaction_WebSQL.prototype[method] = function () { + return this._promise = this._promise[method].apply(this._promise, arguments); + }; + }); + + module.exports = Transaction_WebSQL; + +/***/ }, +/* 38 */ +/***/ function(module, exports, __webpack_require__) { + + // 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. + + function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } @@ -5839,154 +5700,31 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 44 */ +/* 39 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var escapeStringRegexp = __webpack_require__(113); - var ansiStyles = __webpack_require__(114); - var stripAnsi = __webpack_require__(115); - var hasAnsi = __webpack_require__(116); - var supportsColor = __webpack_require__(141); - var defineProps = Object.defineProperties; - var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); - - function Chalk(options) { - // detect mode if not set manually - this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; - } + // 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 bright blue on Windows as the normal blue color is illegible - if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001b[94m'; - } - - var styles = (function () { - var ret = {}; - - Object.keys(ansiStyles).forEach(function (key) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - ret[key] = { - get: function () { - return build.call(this, this._styles.concat(key)); - } - }; - }); - - return ret; - })(); - - var proto = defineProps(function chalk() {}, styles); - - function build(_styles) { - var builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder.enabled = this.enabled; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - /* eslint-disable no-proto */ - builder.__proto__ = proto; - - return builder; - } - - function applyStyle() { - // support varags, but simply cast to string in case there's only one arg - var args = arguments; - var argsLen = args.length; - var str = argsLen !== 0 && String(arguments[0]); - - if (argsLen > 1) { - // don't slice `arguments`, it prevents v8 optimizations - for (var a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || !str) { - return str; - } - - var nestedStyles = this._styles; - var i = nestedStyles.length; - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - var originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { - ansiStyles.dim.open = ''; - } - - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - } - - // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. - ansiStyles.dim.open = originalDim; - - return str; - } - - function init() { - var ret = {}; - - Object.keys(styles).forEach(function (name) { - ret[name] = { - get: function () { - return build.call(this, [name]); - } - }; - }); - - return ret; - } - - defineProps(Chalk.prototype, init()); - - module.exports = new Chalk(); - module.exports.styles = ansiStyles; - module.exports.hasColor = hasAnsi; - module.exports.stripColor = stripAnsi; - module.exports.supportsColor = supportsColor; - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) - -/***/ }, -/* 45 */ -/***/ function(module, exports, __webpack_require__) { - - // 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 = __webpack_require__(127); + var punycode = __webpack_require__(97); exports.parse = urlParse; exports.resolve = urlResolve; @@ -6058,7 +5796,7 @@ return /******/ (function(modules) { // webpackBootstrap 'gopher:': true, 'file:': true }, - querystring = __webpack_require__(128); + querystring = __webpack_require__(91); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject(url) && url instanceof Url) return url; @@ -6675,12 +6413,135 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 46 */ +/* 40 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(process) {'use strict'; + var escapeStringRegexp = __webpack_require__(93); + var ansiStyles = __webpack_require__(92); + var stripAnsi = __webpack_require__(94); + var hasAnsi = __webpack_require__(96); + var supportsColor = __webpack_require__(95); + var defineProps = Object.defineProperties; + var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); + + function Chalk(options) { + // detect mode if not set manually + this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; + } + + // use bright blue on Windows as the normal blue color is illegible + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001b[94m'; + } + + var styles = (function () { + var ret = {}; + + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + + ret[key] = { + get: function () { + return build.call(this, this._styles.concat(key)); + } + }; + }); + + return ret; + })(); + + var proto = defineProps(function chalk() {}, styles); + + function build(_styles) { + var builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder.enabled = this.enabled; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + /* eslint-disable no-proto */ + builder.__proto__ = proto; + + return builder; + } + + function applyStyle() { + // support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); + + if (argsLen > 1) { + // don't slice `arguments`, it prevents v8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || !str) { + return str; + } + + var nestedStyles = this._styles; + var i = nestedStyles.length; + + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + var originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { + ansiStyles.dim.open = ''; + } + + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } + + // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. + ansiStyles.dim.open = originalDim; + + return str; + } + + function init() { + var ret = {}; + + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build.call(this, [name]); + } + }; + }); + + return ret; + } + + defineProps(Chalk.prototype, init()); + + module.exports = new Chalk(); + module.exports.styles = ansiStyles; + module.exports.hasColor = hasAnsi; + module.exports.stripColor = stripAnsi; + module.exports.supportsColor = supportsColor; + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }, +/* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var url = __webpack_require__(45); + var url = __webpack_require__(39); //Parse method copied from https://github.com/brianc/node-postgres //Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com) @@ -6743,20 +6604,74 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 47 */ +/* 42 */ /***/ function(module, exports, __webpack_require__) { - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } + /* (ignored) */ + +/***/ }, +/* 43 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 44 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 45 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 46 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 47 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 48 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 49 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 50 */ +/***/ function(module, exports, __webpack_require__) { + + /* (ignored) */ + +/***/ }, +/* 51 */ +/***/ function(module, exports, __webpack_require__) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } }); }; } else { @@ -6772,7 +6687,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 48 */ +/* 52 */ /***/ function(module, exports, __webpack_require__) { @@ -6782,7 +6697,7 @@ return /******/ (function(modules) { // webpackBootstrap * Expose `debug()` as the module. */ - exports = module.exports = __webpack_require__(112); + exports = module.exports = __webpack_require__(90); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; @@ -6945,67 +6860,13 @@ return /******/ (function(modules) { // webpackBootstrap } -/***/ }, -/* 49 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 52 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - /***/ }, /* 53 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 54 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 55 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 56 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 57 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); // JoinClause // ------- @@ -7020,7 +6881,7 @@ return /******/ (function(modules) { // webpackBootstrap this.clauses = []; } - assign(JoinClause.prototype, { + (0, _lodash.assign)(JoinClause.prototype, { grouping: 'join', @@ -7096,188 +6957,18 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = JoinClause; /***/ }, -/* 59 */ -/***/ function(module, exports, __webpack_require__) { - - var baseClone = __webpack_require__(66), - bindCallback = __webpack_require__(67), - isIterateeCall = __webpack_require__(117); - - /** - * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, - * otherwise they are assigned by reference. If `customizer` is provided it's - * invoked to produce the cloned values. If `customizer` returns `undefined` - * cloning is handled by the method instead. The `customizer` is bound to - * `thisArg` and invoked with up to three argument; (value [, index|key, object]). - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). - * The enumerable properties of `arguments` objects and objects created by - * constructors other than `Object` are cloned to plain `Object` objects. An - * empty object is returned for uncloneable values such as functions, DOM nodes, - * Maps, Sets, and WeakMaps. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {*} Returns the cloned value. - * @example - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * var shallow = _.clone(users); - * shallow[0] === users[0]; - * // => true - * - * var deep = _.clone(users, true); - * deep[0] === users[0]; - * // => false - * - * // using a customizer callback - * var el = _.clone(document.body, function(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * }); - * - * el === document.body - * // => false - * el.nodeName - * // => BODY - * el.childNodes.length; - * // => 0 - */ - function clone(value, isDeep, customizer, thisArg) { - if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { - isDeep = false; - } - else if (typeof isDeep == 'function') { - thisArg = customizer; - customizer = isDeep; - isDeep = false; - } - return typeof customizer == 'function' - ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 3)) - : baseClone(value, isDeep); - } - - module.exports = clone; - - -/***/ }, -/* 60 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Checks if `value` is `undefined`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ - function isUndefined(value) { - return value === undefined; - } - - module.exports = isUndefined; - - -/***/ }, -/* 61 */ -/***/ function(module, exports, __webpack_require__) { - - var arrayEach = __webpack_require__(119), - baseCallback = __webpack_require__(120), - baseCreate = __webpack_require__(121), - baseForOwn = __webpack_require__(122), - isArray = __webpack_require__(123), - isFunction = __webpack_require__(124), - isObject = __webpack_require__(125), - isTypedArray = __webpack_require__(126); - - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own enumerable - * properties through `iteratee`, with each invocation potentially mutating - * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked - * with four arguments: (accumulator, value, key, object). Iteratee functions - * may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @category Object - * @param {Array|Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { - * result[key] = n * 3; - * }); - * // => { 'a': 3, 'b': 6 } - */ - function transform(object, iteratee, accumulator, thisArg) { - var isArr = isArray(object) || isTypedArray(object); - iteratee = baseCallback(iteratee, thisArg, 4); - - if (accumulator == null) { - if (isArr || isObject(object)) { - var Ctor = object.constructor; - if (isArr) { - accumulator = isArray(object) ? new Ctor : []; - } else { - accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined); - } - } else { - accumulator = {}; - } - } - (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } - - module.exports = transform; - - -/***/ }, -/* 62 */ +/* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var _ = __webpack_require__(11); + var _lodash = __webpack_require__(1); // Push a new query onto the compiled "sequence" stack, // creating a new formatter, returning the compiler. exports.pushQuery = function (query) { if (!query) return; - if (_.isString(query)) { + if ((0, _lodash.isString)(query)) { query = { sql: query }; } else { query = query; @@ -7292,1158 +6983,836 @@ return /******/ (function(modules) { // webpackBootstrap // Used in cases where we need to push some additional column specific statements. exports.pushAdditional = function (fn) { var child = new this.constructor(this.client, this.tableCompiler, this.columnBuilder); - fn.call(child, _.rest(arguments)); + fn.call(child, (0, _lodash.tail)(arguments)); this.sequence.additional = (this.sequence.additional || []).concat(child.sequence); }; /***/ }, -/* 63 */ +/* 55 */ /***/ function(module, exports, __webpack_require__) { - var keys = __webpack_require__(118); + 'use strict'; - /** - * A specialized version of `_.assign` for customizing assigned values without - * support for argument juggling, multiple sources, and `this` binding `customizer` - * functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - */ - function assignWith(object, source, customizer) { - var index = -1, - props = keys(source), - length = props.length; + var _lodash = __webpack_require__(1); + + var Transaction = __webpack_require__(18); + var inherits = __webpack_require__(51); + var debug = __webpack_require__(52)('knex:tx'); + var helpers = __webpack_require__(3); + + function Transaction_Maria() { + Transaction.apply(this, arguments); + } + inherits(Transaction_Maria, Transaction); - while (++index < length) { - var key = props[index], - value = object[key], - result = customizer(value, source[key], key, object, source); + (0, _lodash.assign)(Transaction_Maria.prototype, { - if ((result === result ? (result !== value) : (value === value)) || - (value === undefined && !(key in object))) { - object[key] = result; + query: function query(conn, sql, status, value) { + var t = this; + var q = this.trxClient.query(conn, sql)['catch'](function (err) { + return err.code === 1305; + }, function () { + helpers.warn('Transaction was implicitly committed, do not mix transactions and DDL with MariaDB (#805)'); + })['catch'](function (err) { + status = 2; + value = err; + t._completed = true; + debug('%s error running transaction query', t.txid); + }).tap(function () { + if (status === 1) t._resolver(value); + if (status === 2) t._rejecter(value); + }); + if (status === 1 || status === 2) { + t._completed = true; } + return q; } - return object; - } - module.exports = assignWith; + }); + module.exports = Transaction_Maria; /***/ }, -/* 64 */ +/* 56 */ /***/ function(module, exports, __webpack_require__) { - var baseCopy = __webpack_require__(129), - keys = __webpack_require__(118); - - /** - * The base implementation of `_.assign` without support for argument juggling, - * multiple sources, and `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return source == null - ? object - : baseCopy(source, keys(source), object); - } + 'use strict'; - module.exports = baseAssign; + var _lodash = __webpack_require__(1); + var Transaction = __webpack_require__(18); + var inherits = __webpack_require__(51); + var debug = __webpack_require__(52)('knex:tx'); + var helpers = __webpack_require__(3); -/***/ }, -/* 65 */ -/***/ function(module, exports, __webpack_require__) { + function Transaction_MySQL() { + Transaction.apply(this, arguments); + } + inherits(Transaction_MySQL, Transaction); - var bindCallback = __webpack_require__(67), - isIterateeCall = __webpack_require__(117), - restParam = __webpack_require__(130); + (0, _lodash.assign)(Transaction_MySQL.prototype, { - /** - * Creates a `_.assign`, `_.defaults`, or `_.merge` function. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return restParam(function(object, sources) { - var index = -1, - length = object == null ? 0 : sources.length, - customizer = length > 2 ? sources[length - 2] : undefined, - guard = length > 2 ? sources[2] : undefined, - thisArg = length > 1 ? sources[length - 1] : undefined; - - if (typeof customizer == 'function') { - customizer = bindCallback(customizer, thisArg, 5); - length -= 2; - } else { - customizer = typeof thisArg == 'function' ? thisArg : undefined; - length -= (customizer ? 1 : 0); - } - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, customizer); - } + query: function query(conn, sql, status, value) { + var t = this; + var q = this.trxClient.query(conn, sql)['catch'](function (err) { + return err.errno === 1305; + }, function () { + helpers.warn('Transaction was implicitly committed, do not mix transactions and DDL with MySQL (#805)'); + })['catch'](function (err) { + status = 2; + value = err; + t._completed = true; + debug('%s error running transaction query', t.txid); + }).tap(function () { + if (status === 1) t._resolver(value); + if (status === 2) t._rejecter(value); + }); + if (status === 1 || status === 2) { + t._completed = true; } - return object; - }); - } + return q; + } - module.exports = createAssigner; + }); + module.exports = Transaction_MySQL; /***/ }, -/* 66 */ +/* 57 */ /***/ function(module, exports, __webpack_require__) { - var arrayCopy = __webpack_require__(131), - arrayEach = __webpack_require__(119), - baseAssign = __webpack_require__(64), - baseForOwn = __webpack_require__(122), - initCloneArray = __webpack_require__(132), - initCloneByTag = __webpack_require__(133), - initCloneObject = __webpack_require__(134), - isArray = __webpack_require__(123), - isObject = __webpack_require__(125); - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = - cloneableTags[dateTag] = cloneableTags[float32Tag] = - cloneableTags[float64Tag] = cloneableTags[int8Tag] = - cloneableTags[int16Tag] = cloneableTags[int32Tag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[stringTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[mapTag] = cloneableTags[setTag] = - cloneableTags[weakMapTag] = false; - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; - - /** - * The base implementation of `_.clone` without support for argument juggling - * and `this` binding `customizer` functions. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The object `value` belongs to. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates clones with source counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { - var result; - if (customizer) { - result = object ? customizer(value, key, object) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return arrayCopy(value, result); - } - } else { - var tag = objToString.call(value), - isFunc = tag == funcTag; + + // MySQL Query Compiler + // ------ + 'use strict'; - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return baseAssign(result, value); - } - } else { - return cloneableTags[tag] - ? initCloneByTag(value, tag, isDeep) - : (object ? value : {}); - } - } - // Check for circular references and return its corresponding clone. - stackA || (stackA = []); - stackB || (stackB = []); + var _lodash = __webpack_require__(1); - var length = stackA.length; - while (length--) { - if (stackA[length] == value) { - return stackB[length]; - } - } - // Add the source value to the stack of traversed objects and associate it with its clone. - stackA.push(value); - stackB.push(result); + var inherits = __webpack_require__(51); + var QueryCompiler = __webpack_require__(20); - // Recursively populate clone (susceptible to call stack limits). - (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { - result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); - }); - return result; + function QueryCompiler_MySQL(client, builder) { + QueryCompiler.call(this, client, builder); } + inherits(QueryCompiler_MySQL, QueryCompiler); - module.exports = baseClone; - - -/***/ }, -/* 67 */ -/***/ function(module, exports, __webpack_require__) { + (0, _lodash.assign)(QueryCompiler_MySQL.prototype, { - var identity = __webpack_require__(135); + _emptyInsertValue: '() values ()', - /** - * A specialized version of `baseCallback` which only supports `this` binding - * and specifying the number of arguments to provide to `func`. - * - * @private - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {number} [argCount] The number of arguments to provide to `func`. - * @returns {Function} Returns the callback. - */ - function bindCallback(func, thisArg, argCount) { - if (typeof func != 'function') { - return identity; - } - if (thisArg === undefined) { - return func; - } - switch (argCount) { - case 1: return function(value) { - return func.call(thisArg, value); - }; - case 3: return function(value, index, collection) { - return func.call(thisArg, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - case 5: return function(value, other, key, object, source) { - return func.call(thisArg, value, other, key, object, source); - }; - } - return function() { - return func.apply(thisArg, arguments); - }; - } + // Update method, including joins, wheres, order & limits. + update: function update() { + var join = this.join(); + var updates = this._prepUpdate(this.single.update); + var where = this.where(); + var order = this.order(); + var limit = this.limit(); + return 'update ' + this.tableName + (join ? ' ' + join : '') + ' set ' + updates.join(', ') + (where ? ' ' + where : '') + (order ? ' ' + order : '') + (limit ? ' ' + limit : ''); + }, - module.exports = bindCallback; + forUpdate: function forUpdate() { + return 'for update'; + }, + forShare: function forShare() { + return 'lock in share mode'; + }, -/***/ }, -/* 68 */ -/***/ function(module, exports, __webpack_require__) { + // Compiles a `columnInfo` query. + columnInfo: function columnInfo() { + var column = this.single.columnInfo; + return { + sql: 'select * from information_schema.columns where table_name = ? and table_schema = ?', + bindings: [this.single.table, this.client.database()], + output: function output(resp) { + var out = resp.reduce(function (columns, val) { + columns[val.COLUMN_NAME] = { + defaultValue: val.COLUMN_DEFAULT, + type: val.DATA_TYPE, + maxLength: val.CHARACTER_MAXIMUM_LENGTH, + nullable: val.IS_NULLABLE === 'YES' + }; + return columns; + }, {}); + return column && out[column] || out; + } + }; + }, - var baseFor = __webpack_require__(136), - keysIn = __webpack_require__(137); + limit: function limit() { + var noLimit = !this.single.limit && this.single.limit !== 0; + if (noLimit && !this.single.offset) return ''; - /** - * The base implementation of `_.forIn` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForIn(object, iteratee) { - return baseFor(object, iteratee, keysIn); - } + // Workaround for offset only, see http://stackoverflow.com/questions/255517/mysql-offset-infinite-rows + return 'limit ' + (this.single.offset && noLimit ? '18446744073709551615' : this.formatter.parameter(this.single.limit)); + } - module.exports = baseForIn; + }); + // Set the QueryBuilder & QueryCompiler on the client object, + // in case anyone wants to modify things to suit their own purposes. + module.exports = QueryCompiler_MySQL; /***/ }, -/* 69 */ +/* 58 */ /***/ function(module, exports, __webpack_require__) { - var isArrayLike = __webpack_require__(138), - isObjectLike = __webpack_require__(70); - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Native method references. */ - var propertyIsEnumerable = objectProto.propertyIsEnumerable; - - /** - * Checks if `value` is classified as an `arguments` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - return isObjectLike(value) && isArrayLike(value) && - hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); - } - - module.exports = isArguments; + + // MySQL Schema Compiler + // ------- + 'use strict'; + var _lodash = __webpack_require__(1); -/***/ }, -/* 70 */ -/***/ function(module, exports, __webpack_require__) { + var inherits = __webpack_require__(51); + var SchemaCompiler = __webpack_require__(22); - /** - * Checks if `value` is object-like. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; + function SchemaCompiler_MySQL(client, builder) { + SchemaCompiler.call(this, client, builder); } + inherits(SchemaCompiler_MySQL, SchemaCompiler); - module.exports = isObjectLike; - + (0, _lodash.assign)(SchemaCompiler_MySQL.prototype, { -/***/ }, -/* 71 */ -/***/ function(module, exports, __webpack_require__) { + // Rename a table on the schema. + renameTable: function renameTable(tableName, to) { + this.pushQuery('rename table ' + this.formatter.wrap(tableName) + ' to ' + this.formatter.wrap(to)); + }, - /** - * A specialized version of `_.reduce` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initFromArray] Specify using the first element of `array` - * as the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initFromArray) { - var index = -1, - length = array.length; + // Check whether a table exists on the query. + hasTable: function hasTable(tableName) { + this.pushQuery({ + sql: 'show tables like ' + this.formatter.parameter(tableName), + output: function output(resp) { + return resp.length > 0; + } + }); + }, - if (initFromArray && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); + // Check whether a column exists on the schema. + hasColumn: function hasColumn(tableName, column) { + this.pushQuery({ + sql: 'show columns from ' + this.formatter.wrap(tableName) + ' like ' + this.formatter.parameter(column), + output: function output(resp) { + return resp.length > 0; + } + }); } - return accumulator; - } - module.exports = arrayReduce; + }); + module.exports = SchemaCompiler_MySQL; /***/ }, -/* 72 */ +/* 59 */ /***/ function(module, exports, __webpack_require__) { - var baseForOwn = __webpack_require__(122), - createBaseEach = __webpack_require__(139); - - /** - * The base implementation of `_.forEach` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object|string} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - module.exports = baseEach; + + // MySQL Table Builder & Compiler + // ------- + 'use strict'; + var _lodash = __webpack_require__(1); -/***/ }, -/* 73 */ -/***/ function(module, exports, __webpack_require__) { + // Table Compiler + // ------ - var baseCallback = __webpack_require__(120), - baseReduce = __webpack_require__(140), - isArray = __webpack_require__(123); + var inherits = __webpack_require__(51); + var TableCompiler = __webpack_require__(24); + var helpers = __webpack_require__(3); + var Promise = __webpack_require__(9); - /** - * Creates a function for `_.reduce` or `_.reduceRight`. - * - * @private - * @param {Function} arrayFunc The function to iterate over an array. - * @param {Function} eachFunc The function to iterate over a collection. - * @returns {Function} Returns the new each function. - */ - function createReduce(arrayFunc, eachFunc) { - return function(collection, iteratee, accumulator, thisArg) { - var initFromArray = arguments.length < 3; - return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) - ? arrayFunc(collection, iteratee, accumulator, initFromArray) - : baseReduce(collection, baseCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); - }; + function TableCompiler_MySQL() { + TableCompiler.apply(this, arguments); } + inherits(TableCompiler_MySQL, TableCompiler); - module.exports = createReduce; - + (0, _lodash.assign)(TableCompiler_MySQL.prototype, { -/***/ }, -/* 74 */ -/***/ function(module, exports, __webpack_require__) { + createQuery: function createQuery(columns, ifNot) { + var createStatement = ifNot ? 'create table if not exists ' : 'create table '; + var client = this.client, + conn = {}, + sql = createStatement + this.tableName() + ' (' + columns.sql.join(', ') + ')'; - /** - * Converts `value` to a string if it's not one. An empty string is returned - * for `null` or `undefined` values. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - return value == null ? '' : (value + ''); - } + // Check if the connection settings are set. + if (client.connectionSettings) { + conn = client.connectionSettings; + } - module.exports = baseToString; + var charset = this.single.charset || conn.charset || ''; + var collation = this.single.collate || conn.collate || ''; + var engine = this.single.engine || ''; + // var conn = builder.client.connectionSettings; + if (charset) sql += ' default character set ' + charset; + if (collation) sql += ' collate ' + collation; + if (engine) sql += ' engine = ' + engine; -/***/ }, -/* 75 */ -/***/ function(module, exports, __webpack_require__) { + if (this.single.comment) { + var comment = this.single.comment || ''; + if (comment.length > 60) helpers.warn('The max length for a table comment is 60 characters'); + sql += " comment = '" + comment + "'"; + } - var map = __webpack_require__(142), - property = __webpack_require__(143); + this.pushQuery(sql); + }, - /** - * Gets the property value of `path` from all elements in `collection`. - * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|string} path The path of the property to pluck. - * @returns {Array} Returns the property values. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * _.pluck(users, 'user'); - * // => ['barney', 'fred'] - * - * var userIndex = _.indexBy(users, 'user'); - * _.pluck(userIndex, 'age'); - * // => [36, 40] (iteration order is not guaranteed) - */ - function pluck(collection, path) { - return map(collection, property(path)); - } + addColumnsPrefix: 'add ', - module.exports = pluck; + dropColumnPrefix: 'drop ', + // Compiles the comment on the table. + comment: function comment(_comment) { + this.pushQuery('alter table ' + this.tableName() + " comment = '" + _comment + "'"); + }, -/***/ }, -/* 76 */ -/***/ function(module, exports, __webpack_require__) { + changeType: function changeType() { + // alter table + table + ' modify ' + wrapped + '// type'; + }, - - // SQLite3 Query Builder & Compiler + // Renames a column on the table. + renameColumn: function renameColumn(from, to) { + var compiler = this; + var table = this.tableName(); + var wrapped = this.formatter.wrap(from) + ' ' + this.formatter.wrap(to); - 'use strict'; + this.pushQuery({ + sql: 'show fields from ' + table + ' where field = ' + this.formatter.parameter(from), + output: function output(resp) { + var column = resp[0]; + var runner = this; + return compiler.getFKRefs(runner).get(0).then(function (refs) { + return Promise['try'](function () { + if (!refs.length) { + return; + } + return compiler.dropFKRefs(runner, refs); + }).then(function () { + var sql = 'alter table ' + table + ' change ' + wrapped + ' ' + column.Type; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var QueryCompiler = __webpack_require__(18); - var assign = __webpack_require__(29); + if (String(column.Null).toUpperCase() !== 'YES') { + sql += ' NOT NULL'; + } + if (column.Default !== void 0 && column.Default !== null) { + sql += ' DEFAULT \'' + column.Default + '\''; + } - function QueryCompiler_SQLite3(client, builder) { - QueryCompiler.call(this, client, builder); - } - inherits(QueryCompiler_SQLite3, QueryCompiler); - - assign(QueryCompiler_SQLite3.prototype, { - - // The locks are not applicable in SQLite3 - forShare: emptyStr, - - forUpdate: emptyStr, + return runner.query({ + sql: sql + }); + }).then(function () { + if (!refs.length) { + return; + } + return compiler.createFKRefs(runner, refs.map(function (ref) { + if (ref.REFERENCED_COLUMN_NAME === from) { + ref.REFERENCED_COLUMN_NAME = to; + } + if (ref.COLUMN_NAME === from) { + ref.COLUMN_NAME = to; + } + return ref; + })); + }); + }); + } + }); + }, - // SQLite requires us to build the multi-row insert as a listing of select with - // unions joining them together. So we'll build out this list of columns and - // then join them all together with select unions to complete the queries. - insert: function insert() { - var insertValues = this.single.insert || []; - var sql = 'insert into ' + this.tableName + ' '; + getFKRefs: function getFKRefs(runner) { + var formatter = this.client.formatter(); + var sql = 'SELECT KCU.CONSTRAINT_NAME, KCU.TABLE_NAME, KCU.COLUMN_NAME, ' + ' KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, ' + ' RC.UPDATE_RULE, RC.DELETE_RULE ' + 'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ' + 'JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC ' + ' USING(CONSTRAINT_NAME)' + 'WHERE KCU.REFERENCED_TABLE_NAME = ' + formatter.parameter(this.tableNameRaw) + ' ' + ' AND KCU.CONSTRAINT_SCHEMA = ' + formatter.parameter(this.client.database()) + ' ' + ' AND RC.CONSTRAINT_SCHEMA = ' + formatter.parameter(this.client.database()); - if (Array.isArray(insertValues)) { - if (insertValues.length === 0) { - return ''; - } else if (insertValues.length === 1 && insertValues[0] && _.isEmpty(insertValues[0])) { - return sql + this._emptyInsertValue; - } - } else if (typeof insertValues === 'object' && _.isEmpty(insertValues)) { - return sql + this._emptyInsertValue; - } + return runner.query({ + sql: sql, + bindings: formatter.bindings + }); + }, - var insertData = this._prepInsert(insertValues); + dropFKRefs: function dropFKRefs(runner, refs) { + var formatter = this.client.formatter(); - if (_.isString(insertData)) { - return sql + insertData; - } + return Promise.all(refs.map(function (ref) { + var constraintName = formatter.wrap(ref.CONSTRAINT_NAME); + var tableName = formatter.wrap(ref.TABLE_NAME); + return runner.query({ + sql: 'alter table ' + tableName + ' drop foreign key ' + constraintName + }); + })); + }, + createFKRefs: function createFKRefs(runner, refs) { + var formatter = this.client.formatter(); - if (insertData.columns.length === 0) { - return ''; - } + return Promise.all(refs.map(function (ref) { + var tableName = formatter.wrap(ref.TABLE_NAME); + var keyName = formatter.wrap(ref.CONSTRAINT_NAME); + var column = formatter.columnize(ref.COLUMN_NAME); + var references = formatter.columnize(ref.REFERENCED_COLUMN_NAME); + var inTable = formatter.wrap(ref.REFERENCED_TABLE_NAME); + var onUpdate = ' ON UPDATE ' + ref.UPDATE_RULE; + var onDelete = ' ON DELETE ' + ref.DELETE_RULE; - sql += '(' + this.formatter.columnize(insertData.columns) + ')'; + return runner.query({ + sql: 'alter table ' + tableName + ' add constraint ' + keyName + ' ' + 'foreign key (' + column + ') references ' + inTable + ' (' + references + ')' + onUpdate + onDelete + }); + })); + }, + index: function index(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + " add index " + indexName + "(" + this.formatter.columnize(columns) + ")"); + }, - if (insertData.values.length === 1) { - return sql + ' values (' + this.formatter.parameterize(insertData.values[0]) + ')'; - } + primary: function primary(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('primary', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + " add primary key " + indexName + "(" + this.formatter.columnize(columns) + ")"); + }, - var blocks = []; - var i = -1; - while (++i < insertData.values.length) { - var i2 = -1, - block = blocks[i] = []; - var current = insertData.values[i]; - while (++i2 < insertData.columns.length) { - block.push(this.formatter.alias(this.formatter.parameter(current[i2]), this.formatter.wrap(insertData.columns[i2]))); - } - blocks[i] = block.join(', '); - } - return sql + ' select ' + blocks.join(' union all select '); + unique: function unique(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + " add unique " + indexName + "(" + this.formatter.columnize(columns) + ")"); }, - // Compile a truncate table statement into SQL. - truncate: function truncate() { - var table = this.tableName; - return { - sql: 'delete from ' + table, - output: function output() { - return this.query({ sql: 'delete from sqlite_sequence where name = ' + table })['catch'](function () {}); - } - }; + // Compile a drop index command. + dropIndex: function dropIndex(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' drop index ' + indexName); }, - // Compiles a `columnInfo` query - columnInfo: function columnInfo() { - var column = this.single.columnInfo; - return { - sql: 'PRAGMA table_info(' + this.single.table + ')', - output: function output(resp) { - var maxLengthRegex = /.*\((\d+)\)/; - var out = _.reduce(resp, function (columns, val) { - var type = val.type; - var maxLength = (maxLength = type.match(maxLengthRegex)) && maxLength[1]; - type = maxLength ? type.split('(')[0] : type; - columns[val.name] = { - type: type.toLowerCase(), - maxLength: maxLength, - nullable: !val.notnull, - defaultValue: val.dflt_value - }; - return columns; - }, {}); - return column && out[column] || out; - } - }; + // Compile a drop foreign key command. + dropForeign: function dropForeign(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' drop foreign key ' + indexName); }, - limit: function limit() { - var noLimit = !this.single.limit && this.single.limit !== 0; - if (noLimit && !this.single.offset) return ''; + // Compile a drop primary key command. + dropPrimary: function dropPrimary() { + this.pushQuery('alter table ' + this.tableName() + ' drop primary key'); + }, - // Workaround for offset only, - // see http://stackoverflow.com/questions/10491492/sqllite-with-skip-offset-only-not-limit - return 'limit ' + this.formatter.parameter(noLimit ? -1 : this.single.limit); + // Compile a drop unique key command. + dropUnique: function dropUnique(column, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, column); + this.pushQuery('alter table ' + this.tableName() + ' drop index ' + indexName); } }); - function emptyStr() { - return ''; - } - - module.exports = QueryCompiler_SQLite3; + module.exports = TableCompiler_MySQL; /***/ }, -/* 77 */ +/* 60 */ /***/ function(module, exports, __webpack_require__) { - // SQLite3: Column Builder & Compiler + // MySQL Column Compiler // ------- 'use strict'; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var SchemaCompiler = __webpack_require__(20); + var _lodash = __webpack_require__(1); - // Schema Compiler - // ------- + var inherits = __webpack_require__(51); + var ColumnCompiler = __webpack_require__(26); + var helpers = __webpack_require__(3); - function SchemaCompiler_SQLite3() { - SchemaCompiler.apply(this, arguments); + function ColumnCompiler_MySQL() { + ColumnCompiler.apply(this, arguments); + this.modifiers = ['unsigned', 'nullable', 'defaultTo', 'first', 'after', 'comment', 'collate']; } - inherits(SchemaCompiler_SQLite3, SchemaCompiler); - - // Compile the query to determine if a table exists. - SchemaCompiler_SQLite3.prototype.hasTable = function (tableName) { - this.pushQuery({ - sql: "select * from sqlite_master where type = 'table' and name = " + this.formatter.parameter(tableName), - output: function output(resp) { - return resp.length > 0; - } - }); - }; + inherits(ColumnCompiler_MySQL, ColumnCompiler); - // Compile the query to determine if a column exists. - SchemaCompiler_SQLite3.prototype.hasColumn = function (tableName, column) { - this.pushQuery({ - sql: 'PRAGMA table_info(' + this.formatter.wrap(tableName) + ')', - output: function output(resp) { - return _.some(resp, { name: column }); - } - }); - }; + // Types + // ------ - // Compile a rename table command. - SchemaCompiler_SQLite3.prototype.renameTable = function (from, to) { - this.pushQuery('alter table ' + this.formatter.wrap(from) + ' rename to ' + this.formatter.wrap(to)); - }; + (0, _lodash.assign)(ColumnCompiler_MySQL.prototype, { - module.exports = SchemaCompiler_SQLite3; + increments: 'int unsigned not null auto_increment primary key', -/***/ }, -/* 78 */ -/***/ function(module, exports, __webpack_require__) { + bigincrements: 'bigint unsigned not null auto_increment primary key', - 'use strict'; + bigint: 'bigint', - var inherits = __webpack_require__(47); - var ColumnCompiler = __webpack_require__(24); + double: function double(precision, scale) { + if (!precision) return 'double'; + return 'double(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; + }, - // Column Compiler - // ------- + integer: function integer(length) { + length = length ? '(' + this._num(length, 11) + ')' : ''; + return 'int' + length; + }, - function ColumnCompiler_SQLite3() { - this.modifiers = ['nullable', 'defaultTo']; - ColumnCompiler.apply(this, arguments); - } - inherits(ColumnCompiler_SQLite3, ColumnCompiler); + mediumint: 'mediumint', - // Types - // ------- + smallint: 'smallint', - ColumnCompiler_SQLite3.prototype.double = ColumnCompiler_SQLite3.prototype.decimal = ColumnCompiler_SQLite3.prototype.floating = 'float'; - ColumnCompiler_SQLite3.prototype.timestamp = 'datetime'; + tinyint: function tinyint(length) { + length = length ? '(' + this._num(length, 1) + ')' : ''; + return 'tinyint' + length; + }, - module.exports = ColumnCompiler_SQLite3; + text: function text(column) { + switch (column) { + case 'medium': + case 'mediumtext': + return 'mediumtext'; + case 'long': + case 'longtext': + return 'longtext'; + default: + return 'text'; + } + }, -/***/ }, -/* 79 */ -/***/ function(module, exports, __webpack_require__) { + mediumtext: function mediumtext() { + return this.text('medium'); + }, - 'use strict'; + longtext: function longtext() { + return this.text('long'); + }, - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var TableCompiler = __webpack_require__(22); + enu: function enu(allowed) { + return "enum('" + allowed.join("', '") + "')"; + }, - // Table Compiler - // ------- + datetime: 'datetime', - function TableCompiler_SQLite3() { - TableCompiler.apply(this, arguments); - this.primaryKey = void 0; - } - inherits(TableCompiler_SQLite3, TableCompiler); + timestamp: 'timestamp', - // Create a new table. - TableCompiler_SQLite3.prototype.createQuery = function (columns, ifNot) { - var createStatement = ifNot ? 'create table if not exists ' : 'create table '; - var sql = createStatement + this.tableName() + ' (' + columns.sql.join(', '); + bit: function bit(length) { + return length ? 'bit(' + this._num(length) + ')' : 'bit'; + }, - // SQLite forces primary keys to be added when the table is initially created - // so we will need to check for a primary key commands and add the columns - // to the table's declaration here so they can be created on the tables. - sql += this.foreignKeys() || ''; - sql += this.primaryKeys() || ''; - sql += ')'; + binary: function binary(length) { + return length ? 'varbinary(' + this._num(length) + ')' : 'blob'; + }, - this.pushQuery(sql); - }; + // Modifiers + // ------ - TableCompiler_SQLite3.prototype.addColumns = function (columns) { - for (var i = 0, l = columns.sql.length; i < l; i++) { - this.pushQuery({ - sql: 'alter table ' + this.tableName() + ' add column ' + columns.sql[i], - bindings: columns.bindings[i] - }); - } - }; + defaultTo: function defaultTo(value) { + /*jshint unused: false*/ + var defaultVal = ColumnCompiler_MySQL.super_.prototype.defaultTo.apply(this, arguments); + if (this.type !== 'blob' && this.type.indexOf('text') === -1) { + return defaultVal; + } + return ''; + }, - // Compile a drop unique key command. - TableCompiler_SQLite3.prototype.dropUnique = function (columns, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, columns); - this.pushQuery('drop index ' + indexName); - }; + unsigned: function unsigned() { + return 'unsigned'; + }, - TableCompiler_SQLite3.prototype.dropIndex = function (columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('drop index ' + indexName); - }; + first: function first() { + return 'first'; + }, - // Compile a unique key command. - TableCompiler_SQLite3.prototype.unique = function (columns, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, columns); - columns = this.formatter.columnize(columns); - this.pushQuery('create unique index ' + indexName + ' on ' + this.tableName() + ' (' + columns + ')'); - }; + after: function after(column) { + return 'after ' + this.formatter.wrap(column); + }, - // Compile a plain index key command. - TableCompiler_SQLite3.prototype.index = function (columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - columns = this.formatter.columnize(columns); - this.pushQuery('create index ' + indexName + ' on ' + this.tableName() + ' (' + columns + ')'); - }; + comment: function comment(_comment) { + if (_comment && _comment.length > 255) { + helpers.warn('Your comment is longer than the max comment length for MySQL'); + } + return _comment && "comment '" + _comment + "'"; + }, - TableCompiler_SQLite3.prototype.primary = TableCompiler_SQLite3.prototype.foreign = function () { - if (this.method !== 'create' && this.method !== 'createIfNot') { - console.warn('SQLite3 Foreign & Primary keys may only be added on create'); + collate: function collate(collation) { + return collation && "collate '" + collation + "'"; } - }; - TableCompiler_SQLite3.prototype.primaryKeys = function () { - var pks = _.where(this.grouped.alterTable || [], { method: 'primary' }); - if (pks.length > 0 && pks[0].args.length > 0) { - var args = Array.isArray(pks[0].args[0]) ? pks[0].args[0] : pks[0].args; - return ', primary key (' + this.formatter.columnize(args) + ')'; - } - }; + }); - TableCompiler_SQLite3.prototype.foreignKeys = function () { - var sql = ''; - var foreignKeys = _.where(this.grouped.alterTable || [], { method: 'foreign' }); - for (var i = 0, l = foreignKeys.length; i < l; i++) { - var foreign = foreignKeys[i].args[0]; - var column = this.formatter.columnize(foreign.column); - var references = this.formatter.columnize(foreign.references); - var foreignTable = this.formatter.wrap(foreign.inTable); - sql += ', foreign key(' + column + ') references ' + foreignTable + '(' + references + ')'; - if (foreign.onDelete) sql += ' on delete ' + foreign.onDelete; - if (foreign.onUpdate) sql += ' on update ' + foreign.onUpdate; - } - return sql; - }; + module.exports = ColumnCompiler_MySQL; - TableCompiler_SQLite3.prototype.createTableBlock = function () { - return this.getColumns().concat().join(','); - }; +/***/ }, +/* 61 */ +/***/ function(module, exports, __webpack_require__) { - // Compile a rename column command... very complex in sqlite - TableCompiler_SQLite3.prototype.renameColumn = function (from, to) { - var compiler = this; - this.pushQuery({ - sql: 'PRAGMA table_info(' + this.tableName() + ')', - output: function output(pragma) { - return compiler.client.ddl(compiler, pragma, this.connection).renameColumn(from, to); - } - }); - }; + 'use strict'; - TableCompiler_SQLite3.prototype.dropColumn = function (column) { - var compiler = this; - this.pushQuery({ - sql: 'PRAGMA table_info(' + this.tableName() + ')', - output: function output(pragma) { - return compiler.client.ddl(compiler, pragma, this.connection).dropColumn(column); + var _lodash = __webpack_require__(1); + + var inherits = __webpack_require__(51); + var Formatter = __webpack_require__(17); + + function MSSQL_Formatter(client) { + Formatter.call(this, client); + } + inherits(MSSQL_Formatter, Formatter); + + (0, _lodash.assign)(MSSQL_Formatter.prototype, { + + // Accepts a string or array of columns to wrap as appropriate. + columnizeWithPrefix: function columnizeWithPrefix(prefix, target) { + var columns = typeof target === 'string' ? [target] : target; + var str = '', + i = -1; + while (++i < columns.length) { + if (i > 0) str += ', '; + str += prefix + this.wrap(columns[i]); } - }); - }; + return str; + } - module.exports = TableCompiler_SQLite3; + }); + + module.exports = MSSQL_Formatter; /***/ }, -/* 80 */ +/* 62 */ /***/ function(module, exports, __webpack_require__) { - - // SQLite3_DDL - // - // All of the SQLite3 specific DDL helpers for renaming/dropping - // columns and changing datatypes. - // ------- - 'use strict'; - var _ = __webpack_require__(11); - var Promise = __webpack_require__(8); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - // So altering the schema in SQLite3 is a major pain. - // We have our own object to deal with the renaming and altering the types - // for sqlite3 things. - function SQLite3_DDL(client, tableCompiler, pragma, connection) { - this.client = client; - this.tableCompiler = tableCompiler; - this.pragma = pragma; - this.tableName = this.tableCompiler.tableNameRaw; - this.alteredName = _.uniqueId('_knex_temp_alter'); - this.connection = connection; - } + var inherits = __webpack_require__(51); + var Promise = __webpack_require__(9); + var Transaction = __webpack_require__(18); + var debug = __webpack_require__(52)('knex:tx'); - assign(SQLite3_DDL.prototype, { + function Transaction_MSSQL() { + Transaction.apply(this, arguments); + } + inherits(Transaction_MSSQL, Transaction); - getColumn: Promise.method(function (column) { - var currentCol = _.findWhere(this.pragma, { name: column }); - if (!currentCol) throw new Error('The column ' + column + ' is not in the ' + this.tableName + ' table'); - return currentCol; - }), + (0, _lodash.assign)(Transaction_MSSQL.prototype, { - getTableSql: function getTableSql() { - return this.trx.raw('SELECT name, sql FROM sqlite_master WHERE type="table" AND name="' + this.tableName + '"'); + begin: function begin(conn) { + debug('%s: begin', this.txid); + return conn.tx_.begin().then(this._resolver, this._rejecter); }, - renameTable: Promise.method(function () { - return this.trx.raw('ALTER TABLE "' + this.tableName + '" RENAME TO "' + this.alteredName + '"'); - }), + savepoint: function savepoint(conn) { + var _this = this; - dropOriginal: function dropOriginal() { - return this.trx.raw('DROP TABLE "' + this.tableName + '"'); + debug('%s: savepoint at', this.txid); + return Promise.resolve().then(function () { + return _this.query(conn, 'SAVE TRANSACTION ' + _this.txid); + }); }, - dropTempTable: function dropTempTable() { - return this.trx.raw('DROP TABLE "' + this.alteredName + '"'); - }, + commit: function commit(conn, value) { + var _this2 = this; - copyData: function copyData() { - return this.trx.raw('SELECT * FROM "' + this.tableName + '"').bind(this).then(this.insertChunked(20, this.alteredName)); + this._completed = true; + debug('%s: commit', this.txid); + return conn.tx_.commit().then(function () { + return _this2._resolver(value); + }, this._rejecter); }, - reinsertData: function reinsertData(iterator) { - return function () { - return this.trx.raw('SELECT * FROM "' + this.alteredName + '"').bind(this).then(this.insertChunked(20, this.tableName, iterator)); - }; + release: function release(conn, value) { + return this._resolver(value); }, - insertChunked: function insertChunked(amount, target, iterator) { - iterator = iterator || function (noop) { - return noop; - }; - return function (result) { - var batch = []; - var ddl = this; - return Promise.reduce(result, function (memo, row) { - memo++; - batch.push(row); - if (memo % 20 === 0 || memo === result.length) { - return ddl.trx.queryBuilder().table(target).insert(_.map(batch, iterator)).then(function () { - batch = []; - }).thenReturn(memo); - } - return memo; - }, 0); - }; - }, + rollback: function rollback(conn, error) { + var _this3 = this; - createTempTable: function createTempTable(createTable) { - return function () { - return this.trx.raw(createTable.sql.replace(this.tableName, this.alteredName)); - }; + this._completed = true; + debug('%s: rolling back', this.txid); + return conn.tx_.rollback().then(function () { + return _this3._rejecter(error); + }); }, - _doReplace: function _doReplace(sql, from, to) { - var matched = sql.match(/^CREATE TABLE (\S+) \((.*)\)/); + rollbackTo: function rollbackTo(conn, error) { + var _this4 = this; - var tableName = matched[1], - defs = matched[2]; + debug('%s: rolling backTo', this.txid); + return Promise.resolve().then(function () { + return _this4.query(conn, 'ROLLBACK TRANSACTION ' + _this4.txid, 2, error); + }).then(function () { + return _this4._rejecter(error); + }); + }, - if (!defs) { - throw new Error('No column definitions in this statement!'); - } - - var parens = 0, - args = [], - ptr = 0; - for (var i = 0, x = defs.length; i < x; i++) { - switch (defs[i]) { - case '(': - parens++; - break; - case ')': - parens--; - break; - case ',': - if (parens === 0) { - args.push(defs.slice(ptr, i)); - ptr = i + 1; - } - break; - case ' ': - if (ptr === i) { - ptr = i + 1; - } - break; + // Acquire a connection and create a disposer - either using the one passed + // via config or getting one off the client. The disposer will be called once + // the original promise is marked completed. + acquireConnection: function acquireConnection(config) { + var t = this; + var configConnection = config && config.connection; + return Promise['try'](function () { + return (t.outerTx ? t.outerTx.conn : null) || configConnection || t.client.acquireConnection(); + }).tap(function (conn) { + if (!t.outerTx) { + t.conn = conn; + conn.tx_ = conn.transaction(); } - } - args.push(defs.slice(ptr, i)); - - args = args.map(function (item) { - var split = item.split(' '); - - if (split[0] === from) { - // column definition - if (to) { - split[0] = to; - return split.join(' '); + }).disposer(function (conn) { + if (t.outerTx) return; + if (conn.tx_) { + if (!t._completed) { + debug('%s: unreleased transaction', t.txid); + conn.tx_.rollback(); } - return ''; // for deletions - } - - // skip constraint name - var idx = /constraint/i.test(split[0]) ? 2 : 0; - - // primary key and unique constraints have one or more - // columns from this table listed between (); replace - // one if it matches - if (/primary|unique/i.test(split[idx])) { - return item.replace(/\(.*\)/, function (columns) { - return columns.replace(from, to); - }); + conn.tx_ = null; } - - // foreign keys have one or more columns from this table - // listed between (); replace one if it matches - // foreign keys also have a 'references' clause - // which may reference THIS table; if it does, replace - // column references in that too! - if (/foreign/.test(split[idx])) { - split = item.split(/ references /i); - // the quoted column names save us from having to do anything - // other than a straight replace here - split[0] = split[0].replace(from, to); - - if (split[1].slice(0, tableName.length) === tableName) { - split[1] = split[1].replace(/\(.*\)/, function (columns) { - return columns.replace(from, to); - }); - } - return split.join(' references '); + t.conn = null; + if (!configConnection) { + debug('%s: releasing connection', t.txid); + t.client.releaseConnection(conn); + } else { + debug('%s: not releasing external connection', t.txid); } - - return item; - }); - return sql.replace(/\(.*\)/, function () { - return '(' + args.join(', ') + ')'; - }).replace(/,\s*([,)])/, '$1'); - }, - - // Boy, this is quite a method. - renameColumn: Promise.method(function (from, to) { - var currentCol; - - return this.client.transaction((function (trx) { - this.trx = trx; - return this.getColumn(from).bind(this).tap(function (col) { - currentCol = col; - }).then(this.getTableSql).then(function (sql) { - var a = this.client.wrapIdentifier(from); - var b = this.client.wrapIdentifier(to); - var createTable = sql[0]; - var newSql = this._doReplace(createTable.sql, a, b); - if (sql === newSql) { - throw new Error('Unable to find the column to change'); - } - return Promise.bind(this).then(this.createTempTable(createTable)).then(this.copyData).then(this.dropOriginal).then(function () { - return this.trx.raw(newSql); - }).then(this.reinsertData(function (row) { - row[to] = row[from]; - return _.omit(row, from); - })).then(this.dropTempTable); - }); - }).bind(this), { connection: this.connection }); - }), - - dropColumn: Promise.method(function (column) { - var currentCol; - - return this.client.transaction((function (trx) { - this.trx = trx; - return this.getColumn(column).tap(function (col) { - currentCol = col; - }).bind(this).then(this.getTableSql).then(function (sql) { - var createTable = sql[0]; - var a = this.client.wrapIdentifier(column); - var newSql = this._doReplace(createTable.sql, a, ''); - if (sql === newSql) { - throw new Error('Unable to find the column to change'); - } - return Promise.bind(this).then(this.createTempTable(createTable)).then(this.copyData).then(this.dropOriginal).then(function () { - return this.trx.raw(newSql); - }).then(this.reinsertData(function (row) { - return _.omit(row, column); - })).then(this.dropTempTable); - }); - }).bind(this), { connection: this.connection }); - }) - - }); - - module.exports = SQLite3_DDL; - -/***/ }, -/* 81 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var Transaction = __webpack_require__(16); - var assign = __webpack_require__(29); - var inherits = __webpack_require__(47); - var debug = __webpack_require__(48)('knex:tx'); - var helpers = __webpack_require__(2); - - function Transaction_MySQL() { - Transaction.apply(this, arguments); - } - inherits(Transaction_MySQL, Transaction); - - assign(Transaction_MySQL.prototype, { - - query: function query(conn, sql, status, value) { - var t = this; - var q = this.trxClient.query(conn, sql)['catch'](function (err) { - return err.errno === 1305; - }, function () { - helpers.warn('Transaction was implicitly committed, do not mix transactions and DDL with MySQL (#805)'); - })['catch'](function (err) { - status = 2; - value = err; - t._completed = true; - debug('%s error running transaction query', t.txid); - }).tap(function () { - if (status === 1) t._resolver(value); - if (status === 2) t._rejecter(value); }); - if (status === 1 || status === 2) { - t._completed = true; - } - return q; } }); - module.exports = Transaction_MySQL; + module.exports = Transaction_MSSQL; /***/ }, -/* 82 */ +/* 63 */ /***/ function(module, exports, __webpack_require__) { - // MySQL Query Compiler + // MSSQL Query Compiler // ------ 'use strict'; - var inherits = __webpack_require__(47); - var QueryCompiler = __webpack_require__(18); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - function QueryCompiler_MySQL(client, builder) { + var inherits = __webpack_require__(51); + var QueryCompiler = __webpack_require__(20); + + function QueryCompiler_MSSQL(client, builder) { QueryCompiler.call(this, client, builder); } - inherits(QueryCompiler_MySQL, QueryCompiler); + inherits(QueryCompiler_MSSQL, QueryCompiler); - assign(QueryCompiler_MySQL.prototype, { + (0, _lodash.assign)(QueryCompiler_MSSQL.prototype, { - _emptyInsertValue: '() values ()', + _emptyInsertValue: 'default values', - // Update method, including joins, wheres, order & limits. + // Compiles an "insert" query, allowing for multiple + // inserts using a single query statement. + insert: function insert() { + var insertValues = this.single.insert || []; + var sql = 'insert into ' + this.tableName + ' '; + var returning = this.single.returning; + var returningSql = returning ? this._returning('insert', returning) + ' ' : ''; + + if (Array.isArray(insertValues)) { + if (insertValues.length === 0) { + return ''; + } + } else if (typeof insertValues === 'object' && (0, _lodash.isEmpty)(insertValues)) { + return { + sql: sql + returningSql + this._emptyInsertValue, + returning: returning + }; + } + + var insertData = this._prepInsert(insertValues); + if (typeof insertData === 'string') { + sql += insertData; + } else { + if (insertData.columns.length) { + sql += '(' + this.formatter.columnize(insertData.columns); + sql += ') ' + returningSql + 'values ('; + var i = -1; + while (++i < insertData.values.length) { + if (i !== 0) sql += '), ('; + sql += this.formatter.parameterize(insertData.values[i]); + } + sql += ')'; + } else if (insertValues.length === 1 && insertValues[0]) { + sql += returningSql + this._emptyInsertValue; + } else { + sql = ''; + } + } + return { + sql: sql, + returning: returning + }; + }, + + // Compiles an `update` query, allowing for a return value. update: function update() { - var join = this.join(); var updates = this._prepUpdate(this.single.update); + var join = this.join(); var where = this.where(); var order = this.order(); - var limit = this.limit(); - return 'update ' + this.tableName + (join ? ' ' + join : '') + ' set ' + updates.join(', ') + (where ? ' ' + where : '') + (order ? ' ' + order : '') + (limit ? ' ' + limit : ''); - }, - - forUpdate: function forUpdate() { - return 'for update'; + var top = this.top(); + var returning = this.single.returning; + return { + sql: 'update ' + (top ? top + ' ' : '') + this.tableName + (join ? ' ' + join : '') + ' set ' + updates.join(', ') + (returning ? ' ' + this._returning('update', returning) : '') + (where ? ' ' + where : '') + (order ? ' ' + order : '') + (!returning ? this._returning('rowcount', '@@rowcount') : ''), + returning: returning || '@@rowcount' + }; }, - forShare: function forShare() { - return 'lock in share mode'; + // Compiles a `delete` query. + del: function del() { + // Make sure tableName is processed by the formatter first. + var tableName = this.tableName; + var wheres = this.where(); + var returning = this.single.returning; + return { + sql: 'delete from ' + tableName + (returning ? ' ' + this._returning('del', returning) : '') + (wheres ? ' ' + wheres : '') + (!returning ? this._returning('rowcount', '@@rowcount') : ''), + returning: returning || '@@rowcount' + }; + }, + + // Compiles the columns in the query, specifying if an item was distinct. + columns: function columns() { + var distinct = false; + if (this.onlyUnions()) return ''; + var columns = this.grouped.columns || []; + var i = -1, + sql = []; + if (columns) { + while (++i < columns.length) { + var stmt = columns[i]; + if (stmt.distinct) distinct = true; + if (stmt.type === 'aggregate') { + sql.push(this.aggregate(stmt)); + } else if (stmt.value && stmt.value.length > 0) { + sql.push(this.formatter.columnize(stmt.value)); + } + } + } + if (sql.length === 0) sql = ['*']; + var top = this.top(); + return 'select ' + (distinct ? 'distinct ' : '') + (top ? top + ' ' : '') + sql.join(', ') + (this.tableName ? ' from ' + this.tableName : ''); + }, + + _returning: function _returning(method, value) { + switch (method) { + case 'update': + case 'insert': + return value ? 'output ' + this.formatter.columnizeWithPrefix('inserted.', value) : ''; + case 'del': + return value ? 'output ' + this.formatter.columnizeWithPrefix('deleted.', value) : ''; + case 'rowcount': + return value ? ';select @@rowcount' : ''; + } + }, + + // Compiles a `truncate` query. + truncate: function truncate() { + return 'truncate table ' + this.tableName; + }, + + forUpdate: function forUpdate() { + return 'with (READCOMMITTEDLOCK)'; + }, + + forShare: function forShare() { + return 'with (NOLOCK)'; }, // Compiles a `columnInfo` query. columnInfo: function columnInfo() { var column = this.single.columnInfo; return { - sql: 'select * from information_schema.columns where table_name = ? and table_schema = ?', - bindings: [this.single.table, this.client.database()], + sql: 'select * from information_schema.columns where table_name = ? and table_schema = \'dbo\'', + bindings: [this.single.table], output: function output(resp) { var out = resp.reduce(function (columns, val) { columns[val.COLUMN_NAME] = { @@ -8459,22 +7828,36 @@ return /******/ (function(modules) { // webpackBootstrap }; }, - limit: function limit() { + top: function top() { var noLimit = !this.single.limit && this.single.limit !== 0; - if (noLimit && !this.single.offset) return ''; + var noOffset = !this.single.offset; + if (noLimit || !noOffset) return ''; + return 'top (' + this.formatter.parameter(this.single.limit) + ')'; + }, - // Workaround for offset only, see http://stackoverflow.com/questions/255517/mysql-offset-infinite-rows - return 'limit ' + (this.single.offset && noLimit ? '18446744073709551615' : this.formatter.parameter(this.single.limit)); + limit: function limit() { + return ''; + }, + + offset: function offset() { + var noLimit = !this.single.limit && this.single.limit !== 0; + var noOffset = !this.single.offset; + if (noOffset) return ''; + var offset = 'offset ' + (noOffset ? '0' : this.formatter.parameter(this.single.offset)) + ' rows'; + if (!noLimit) { + offset += ' fetch next ' + this.formatter.parameter(this.single.limit) + ' rows only'; + } + return offset; } }); // Set the QueryBuilder & QueryCompiler on the client object, - // incase anyone wants to modify things to suit their own purposes. - module.exports = QueryCompiler_MySQL; + // in case anyone wants to modify things to suit their own purposes. + module.exports = QueryCompiler_MSSQL; /***/ }, -/* 83 */ +/* 64 */ /***/ function(module, exports, __webpack_require__) { @@ -8482,26 +7865,33 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var inherits = __webpack_require__(47); - var SchemaCompiler = __webpack_require__(20); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - function SchemaCompiler_MySQL(client, builder) { + var inherits = __webpack_require__(51); + var SchemaCompiler = __webpack_require__(22); + + function SchemaCompiler_MSSQL(client, builder) { SchemaCompiler.call(this, client, builder); } - inherits(SchemaCompiler_MySQL, SchemaCompiler); + inherits(SchemaCompiler_MSSQL, SchemaCompiler); + + (0, _lodash.assign)(SchemaCompiler_MSSQL.prototype, { - assign(SchemaCompiler_MySQL.prototype, { + dropTablePrefix: 'DROP TABLE ', + dropTableIfExists: function dropTableIfExists(tableName) { + var name = this.formatter.wrap(prefixedTableName(this.schema, tableName)); + this.pushQuery('if object_id(\'' + name + '\', \'U\') is not null DROP TABLE ' + name); + }, // Rename a table on the schema. renameTable: function renameTable(tableName, to) { - this.pushQuery('rename table ' + this.formatter.wrap(tableName) + ' to ' + this.formatter.wrap(to)); + this.pushQuery('exec sp_rename ' + this.formatter.parameter(tableName) + ', ' + this.formatter.parameter(to)); }, // Check whether a table exists on the query. hasTable: function hasTable(tableName) { this.pushQuery({ - sql: 'show tables like ' + this.formatter.parameter(tableName), + sql: 'select object_id from sys.tables where object_id = object_id(' + this.formatter.parameter(this.formatter.wrap(tableName)) + ')', output: function output(resp) { return resp.length > 0; } @@ -8511,7 +7901,7 @@ return /******/ (function(modules) { // webpackBootstrap // Check whether a column exists on the schema. hasColumn: function hasColumn(tableName, column) { this.pushQuery({ - sql: 'show columns from ' + this.formatter.wrap(tableName) + ' like ' + this.formatter.parameter(column), + sql: 'select object_id from sys.columns where name = ' + this.formatter.parameter(column) + ' and object_id = object_id(' + this.formatter.parameter(this.formatter.wrap(tableName)) + ')', output: function output(resp) { return resp.length > 0; } @@ -8520,133 +7910,74 @@ return /******/ (function(modules) { // webpackBootstrap }); - module.exports = SchemaCompiler_MySQL; + function prefixedTableName(prefix, table) { + return prefix ? prefix + '.' + table : table; + } + + module.exports = SchemaCompiler_MSSQL; /***/ }, -/* 84 */ +/* 65 */ /***/ function(module, exports, __webpack_require__) { - // MySQL Table Builder & Compiler + // MSSQL Table Builder & Compiler // ------- 'use strict'; - var inherits = __webpack_require__(47); - var TableCompiler = __webpack_require__(22); - var helpers = __webpack_require__(2); - var Promise = __webpack_require__(8); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); // Table Compiler // ------ - function TableCompiler_MySQL() { + var inherits = __webpack_require__(51); + var TableCompiler = __webpack_require__(24); + var helpers = __webpack_require__(3); + var Promise = __webpack_require__(9); + + function TableCompiler_MSSQL() { TableCompiler.apply(this, arguments); } - inherits(TableCompiler_MySQL, TableCompiler); + inherits(TableCompiler_MSSQL, TableCompiler); - assign(TableCompiler_MySQL.prototype, { + (0, _lodash.assign)(TableCompiler_MSSQL.prototype, { + createAlterTableMethods: ['foreign', 'primary', 'unique'], createQuery: function createQuery(columns, ifNot) { - var createStatement = ifNot ? 'create table if not exists ' : 'create table '; - var client = this.client, - conn = {}, - sql = createStatement + this.tableName() + ' (' + columns.sql.join(', ') + ')'; - - // Check if the connection settings are set. - if (client.connectionSettings) { - conn = client.connectionSettings; - } - - var charset = this.single.charset || conn.charset || ''; - var collation = this.single.collate || conn.collate || ''; - var engine = this.single.engine || ''; - - // var conn = builder.client.connectionSettings; - if (charset) sql += ' default character set ' + charset; - if (collation) sql += ' collate ' + collation; - if (engine) sql += ' engine = ' + engine; + var createStatement = ifNot ? 'if object_id(\'' + this.tableName() + '\', \'U\') is null CREATE TABLE ' : 'CREATE TABLE '; + var sql = createStatement + this.tableName() + (this._formatting ? ' (\n ' : ' (') + columns.sql.join(this._formatting ? ',\n ' : ', ') + ')'; if (this.single.comment) { var comment = this.single.comment || ''; if (comment.length > 60) helpers.warn('The max length for a table comment is 60 characters'); - sql += " comment = '" + comment + "'"; } this.pushQuery(sql); }, - addColumnsPrefix: 'add ', + lowerCase: false, - dropColumnPrefix: 'drop ', + addColumnsPrefix: 'ADD ', + + dropColumnPrefix: 'DROP COLUMN ', // Compiles the comment on the table. - comment: function comment(_comment) { - this.pushQuery('alter table ' + this.tableName() + " comment = '" + _comment + "'"); - }, + comment: function comment() {}, - changeType: function changeType() { - // alter table + table + ' modify ' + wrapped + '// type'; - }, + changeType: function changeType() {}, // Renames a column on the table. renameColumn: function renameColumn(from, to) { - var compiler = this; - var table = this.tableName(); - var wrapped = this.formatter.wrap(from) + ' ' + this.formatter.wrap(to); - - this.pushQuery({ - sql: 'show fields from ' + table + ' where field = ' + this.formatter.parameter(from), - output: function output(resp) { - var column = resp[0]; - var runner = this; - return compiler.getFKRefs(runner).get(0).then(function (refs) { - return Promise['try'](function () { - if (!refs.length) { - return; - } - return compiler.dropFKRefs(runner, refs); - }).then(function () { - return runner.query({ - sql: 'alter table ' + table + ' change ' + wrapped + ' ' + column.Type - }); - }).then(function () { - if (!refs.length) { - return; - } - return compiler.createFKRefs(runner, refs.map(function (ref) { - if (ref.REFERENCED_COLUMN_NAME === from) { - ref.REFERENCED_COLUMN_NAME = to; - } - if (ref.COLUMN_NAME === from) { - ref.COLUMN_NAME = to; - } - return ref; - })); - }); - }); - } - }); - }, - - getFKRefs: function getFKRefs(runner) { - var formatter = this.client.formatter(); - var sql = 'SELECT KCU.CONSTRAINT_NAME, KCU.TABLE_NAME, KCU.COLUMN_NAME, ' + ' KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, ' + ' RC.UPDATE_RULE, RC.DELETE_RULE ' + 'FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU ' + 'JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC ' + ' USING(CONSTRAINT_NAME)' + 'WHERE KCU.REFERENCED_TABLE_NAME = ' + formatter.parameter(this.tableNameRaw) + ' ' + ' AND KCU.CONSTRAINT_SCHEMA = ' + formatter.parameter(this.client.database()) + ' ' + ' AND RC.CONSTRAINT_SCHEMA = ' + formatter.parameter(this.client.database()); - - return runner.query({ - sql: sql, - bindings: formatter.bindings - }); + this.pushQuery('exec sp_rename ' + this.formatter.parameter(this.tableName() + '.' + from) + ', ' + this.formatter.parameter(to) + ', \'COLUMN\''); }, dropFKRefs: function dropFKRefs(runner, refs) { var formatter = this.client.formatter(); - return Promise.all(refs.map(function (ref) { var constraintName = formatter.wrap(ref.CONSTRAINT_NAME); var tableName = formatter.wrap(ref.TABLE_NAME); return runner.query({ - sql: 'alter table ' + tableName + ' drop foreign key ' + constraintName + sql: 'ALTER TABLE ' + tableName + ' DROP CONSTRAINT ' + constraintName }); })); }, @@ -8663,54 +7994,63 @@ return /******/ (function(modules) { // webpackBootstrap var onDelete = ' ON DELETE ' + ref.DELETE_RULE; return runner.query({ - sql: 'alter table ' + tableName + ' add constraint ' + keyName + ' ' + 'foreign key (' + column + ') references ' + inTable + ' (' + references + ')' + onUpdate + onDelete + sql: 'ALTER TABLE ' + tableName + ' ADD CONSTRAINT ' + keyName + ' FOREIGN KEY (' + column + ') REFERENCES ' + inTable + ' (' + references + ')' + onUpdate + onDelete }); })); }, + index: function index(columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + " add index " + indexName + "(" + this.formatter.columnize(columns) + ")"); + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('CREATE INDEX ' + indexName + ' ON ' + this.tableName() + ' (' + this.formatter.columnize(columns) + ')'); }, primary: function primary(columns, indexName) { - indexName = indexName || this._indexCommand('primary', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + " add primary key " + indexName + "(" + this.formatter.columnize(columns) + ")"); + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('primary', this.tableNameRaw, columns); + if (!this.forCreate) { + this.pushQuery('ALTER TABLE ' + this.tableName() + ' ADD PRIMARY KEY (' + this.formatter.columnize(columns) + ')'); + } else { + this.pushQuery('CONSTRAINT ' + indexName + ' PRIMARY KEY (' + this.formatter.columnize(columns) + ')'); + } }, unique: function unique(columns, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + " add unique " + indexName + "(" + this.formatter.columnize(columns) + ")"); + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + if (!this.forCreate) { + this.pushQuery('CREATE UNIQUE INDEX ' + indexName + ' ON ' + this.tableName() + ' (' + this.formatter.columnize(columns) + ')'); + } else { + this.pushQuery('CONSTRAINT ' + indexName + ' UNIQUE (' + this.formatter.columnize(columns) + ')'); + } }, // Compile a drop index command. dropIndex: function dropIndex(columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' drop index ' + indexName); + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('DROP INDEX ' + indexName + ' ON ' + this.tableName()); }, // Compile a drop foreign key command. dropForeign: function dropForeign(columns, indexName) { - indexName = indexName || this._indexCommand('foreign', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' drop foreign key ' + indexName); + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns); + this.pushQuery('ALTER TABLE ' + this.tableName() + ' DROP CONSTRAINT ' + indexName); }, // Compile a drop primary key command. dropPrimary: function dropPrimary() { - this.pushQuery('alter table ' + this.tableName() + ' drop primary key'); + this.pushQuery('ALTER TABLE ' + this.tableName() + ' DROP PRIMARY KEY'); }, // Compile a drop unique key command. dropUnique: function dropUnique(column, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, column); - this.pushQuery('alter table ' + this.tableName() + ' drop index ' + indexName); + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, column); + this.pushQuery('ALTER TABLE ' + this.tableName() + ' DROP CONSTRAINT ' + indexName); } }); - module.exports = TableCompiler_MySQL; + module.exports = TableCompiler_MSSQL; /***/ }, -/* 85 */ +/* 66 */ /***/ function(module, exports, __webpack_require__) { @@ -8718,25 +8058,26 @@ return /******/ (function(modules) { // webpackBootstrap // ------- 'use strict'; - var inherits = __webpack_require__(47); - var ColumnCompiler = __webpack_require__(24); - var helpers = __webpack_require__(2); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - function ColumnCompiler_MySQL() { + var inherits = __webpack_require__(51); + var ColumnCompiler = __webpack_require__(26); + var helpers = __webpack_require__(3); + + function ColumnCompiler_MSSQL() { ColumnCompiler.apply(this, arguments); - this.modifiers = ['unsigned', 'nullable', 'defaultTo', 'first', 'after', 'comment']; + this.modifiers = ['nullable', 'defaultTo', 'first', 'after', 'comment']; } - inherits(ColumnCompiler_MySQL, ColumnCompiler); + inherits(ColumnCompiler_MSSQL, ColumnCompiler); // Types // ------ - assign(ColumnCompiler_MySQL.prototype, { + (0, _lodash.assign)(ColumnCompiler_MSSQL.prototype, { - increments: 'int unsigned not null auto_increment primary key', + increments: 'int identity(1,1) not null primary key', - bigincrements: 'bigint unsigned not null auto_increment primary key', + bigincrements: 'bigint identity(1,1) not null primary key', bigint: 'bigint', @@ -8759,34 +8100,23 @@ return /******/ (function(modules) { // webpackBootstrap return 'tinyint' + length; }, - text: function text(column) { - switch (column) { - case 'medium': - case 'mediumtext': - return 'mediumtext'; - case 'long': - case 'longtext': - return 'longtext'; - default: - return 'text'; - } + varchar: function varchar(length) { + return 'nvarchar(' + this._num(length, 255) + ')'; }, - mediumtext: function mediumtext() { - return this.text('medium'); - }, + text: 'nvarchar(max)', - longtext: function longtext() { - return this.text('long'); - }, + mediumtext: 'nvarchar(max)', - enu: function enu(allowed) { - return "enum('" + allowed.join("', '") + "')"; - }, + longtext: 'nvarchar(max)', + + enu: 'nvarchar(100)', + + uuid: 'uniqueidentifier', datetime: 'datetime', - timestamp: 'timestamp', + timestamp: 'datetime', bit: function bit(length) { return length ? 'bit(' + this._num(length) + ')' : 'bit'; @@ -8796,22 +8126,20 @@ return /******/ (function(modules) { // webpackBootstrap return length ? 'varbinary(' + this._num(length) + ')' : 'blob'; }, + bool: 'bit', + // Modifiers // ------ defaultTo: function defaultTo(value) { /*jshint unused: false*/ - var defaultVal = ColumnCompiler_MySQL.super_.prototype.defaultTo.apply(this, arguments); + var defaultVal = ColumnCompiler_MSSQL.super_.prototype.defaultTo.apply(this, arguments); if (this.type !== 'blob' && this.type.indexOf('text') === -1) { return defaultVal; } return ''; }, - unsigned: function unsigned() { - return 'unsigned'; - }, - first: function first() { return 'first'; }, @@ -8822,40 +8150,41 @@ return /******/ (function(modules) { // webpackBootstrap comment: function comment(_comment) { if (_comment && _comment.length > 255) { - helpers.warn('Your comment is longer than the max comment length for MySQL'); + helpers.warn('Your comment is longer than the max comment length for MSSQL'); } - return _comment && "comment '" + _comment + "'"; + return ''; } }); - module.exports = ColumnCompiler_MySQL; + module.exports = ColumnCompiler_MSSQL; /***/ }, -/* 86 */ +/* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var Transaction = __webpack_require__(16); - var assign = __webpack_require__(29); - var inherits = __webpack_require__(47); - var debug = __webpack_require__(48)('knex:tx'); - var helpers = __webpack_require__(2); + var _lodash = __webpack_require__(1); - function Transaction_Maria() { + var Transaction = __webpack_require__(18); + var inherits = __webpack_require__(51); + var debug = __webpack_require__(52)('knex:tx'); + var helpers = __webpack_require__(3); + + function Transaction_MySQL2() { Transaction.apply(this, arguments); } - inherits(Transaction_Maria, Transaction); + inherits(Transaction_MySQL2, Transaction); - assign(Transaction_Maria.prototype, { + (0, _lodash.assign)(Transaction_MySQL2.prototype, { query: function query(conn, sql, status, value) { var t = this; var q = this.trxClient.query(conn, sql)['catch'](function (err) { - return err.code === 1305; + return err.code === 'ER_SP_DOES_NOT_EXIST'; }, function () { - helpers.warn('Transaction was implicitly committed, do not mix transactions and DDL with MariaDB (#805)'); + helpers.warn('Transaction was implicitly committed, do not mix transactions and DDL with MySQL (#805)'); })['catch'](function (err) { status = 2; value = err; @@ -8873,271 +8202,231 @@ return /******/ (function(modules) { // webpackBootstrap }); - module.exports = Transaction_Maria; + module.exports = Transaction_MySQL2; /***/ }, -/* 87 */ +/* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - var Formatter = __webpack_require__(15); + var _lodash = __webpack_require__(1); - function MSSQL_Formatter(client) { + var inherits = __webpack_require__(51); + var Formatter = __webpack_require__(17); + var ReturningHelper = __webpack_require__(76).ReturningHelper; + + function Oracle_Formatter(client) { Formatter.call(this, client); } - inherits(MSSQL_Formatter, Formatter); + inherits(Oracle_Formatter, Formatter); - assign(MSSQL_Formatter.prototype, { + (0, _lodash.assign)(Oracle_Formatter.prototype, { - // Accepts a string or array of columns to wrap as appropriate. - columnizeWithPrefix: function columnizeWithPrefix(prefix, target) { - var columns = typeof target === 'string' ? [target] : target; - var str = '', - i = -1; - while (++i < columns.length) { - if (i > 0) str += ', '; - str += prefix + this.wrap(columns[i]); + alias: function alias(first, second) { + return first + ' ' + second; + }, + + parameter: function parameter(value, notSetValue) { + // Returning helper uses always ROWID as string + if (value instanceof ReturningHelper && this.client.driver) { + value = new this.client.driver.OutParam(this.client.driver.OCCISTRING); + } else if (typeof value === 'boolean') { + value = value ? 1 : 0; } - return str; + return Formatter.prototype.parameter.call(this, value, notSetValue); } }); - module.exports = MSSQL_Formatter; + module.exports = Oracle_Formatter; /***/ }, -/* 88 */ +/* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - var Promise = __webpack_require__(8); - var Transaction = __webpack_require__(16); - var debug = __webpack_require__(48)('knex:tx'); + var _lodash = __webpack_require__(1); - function Transaction_MSSQL() { - Transaction.apply(this, arguments); - } - inherits(Transaction_MSSQL, Transaction); + var inherits = __webpack_require__(51); + var Promise = __webpack_require__(9); + var Transaction = __webpack_require__(18); + var debugTx = __webpack_require__(52)('knex:tx'); - assign(Transaction_MSSQL.prototype, { - - begin: function begin(conn) { - debug('%s: begin', this.txid); - return conn.tx_.begin().then(this._resolver, this._rejecter); - }, + function Oracle_Transaction(client, container, config, outerTx) { + Transaction.call(this, client, container, config, outerTx); + } + inherits(Oracle_Transaction, Transaction); - savepoint: function savepoint(conn) { - var _this = this; + (0, _lodash.assign)(Oracle_Transaction.prototype, { - debug('%s: savepoint at', this.txid); - return Promise.resolve().then(function () { - return _this.query(conn, 'SAVE TRANSACTION ' + _this.txid); - }); + // disable autocommit to allow correct behavior (default is true) + begin: function begin() { + return Promise.resolve(); }, commit: function commit(conn, value) { - var _this2 = this; - this._completed = true; - debug('%s: commit', this.txid); - return conn.tx_.commit().then(function () { - return _this2._resolver(value); - }, this._rejecter); + return conn.commitAsync()['return'](value).then(this._resolver, this._rejecter); }, release: function release(conn, value) { return this._resolver(value); }, - rollback: function rollback(conn, error) { - var _this3 = this; - + rollback: function rollback(conn, err) { this._completed = true; - debug('%s: rolling back', this.txid); - return conn.tx_.rollback().then(function () { - return _this3._rejecter(error); - }); - }, - - rollbackTo: function rollbackTo(conn, error) { - var _this4 = this; - - debug('%s: rolling backTo', this.txid); - return Promise.resolve().then(function () { - return _this4.query(conn, 'ROLLBACK TRANSACTION ' + _this4.txid, 2, error); - }).then(function () { - return _this4._rejecter(error); - }); + debugTx('%s: rolling back', this.txid); + return conn.rollbackAsync()['throw'](err)['catch'](this._rejecter); }, - // Acquire a connection and create a disposer - either using the one passed - // via config or getting one off the client. The disposer will be called once - // the original promise is marked completed. acquireConnection: function acquireConnection(config) { var t = this; - var configConnection = config && config.connection; return Promise['try'](function () { - return (t.outerTx ? t.outerTx.conn : null) || configConnection || t.client.acquireConnection(); - }).tap(function (conn) { + return config.connection || t.client.acquireConnection(); + }).tap(function (connection) { if (!t.outerTx) { - t.conn = conn; - conn.tx_ = conn.transaction(); - } - }).disposer(function (conn) { - if (t.outerTx) return; - if (conn.tx_) { - if (!t._completed) { - debug('%s: unreleased transaction', t.txid); - conn.tx_.rollback(); - } - conn.tx_ = null; + connection.setAutoCommit(false); } - t.conn = null; - if (!configConnection) { - debug('%s: releasing connection', t.txid); - t.client.releaseConnection(conn); + }).disposer(function (connection) { + debugTx('%s: releasing connection', t.txid); + connection.setAutoCommit(true); + if (!config.connection) { + t.client.releaseConnection(connection); } else { - debug('%s: not releasing external connection', t.txid); + debugTx('%s: not releasing external connection', t.txid); } }); } }); - module.exports = Transaction_MSSQL; + module.exports = Oracle_Transaction; /***/ }, -/* 89 */ +/* 70 */ /***/ function(module, exports, __webpack_require__) { - // MSSQL Query Compiler + // Oracle Query Builder & Compiler // ------ 'use strict'; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var QueryCompiler = __webpack_require__(18); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - function QueryCompiler_MSSQL(client, builder) { + var inherits = __webpack_require__(51); + var QueryCompiler = __webpack_require__(20); + var helpers = __webpack_require__(3); + var ReturningHelper = __webpack_require__(76).ReturningHelper; + + // Query Compiler + // ------- + + // Set the "Formatter" to use for the queries, + // ensuring that all parameterized values (even across sub-queries) + // are properly built into the same query. + function QueryCompiler_Oracle(client, builder) { QueryCompiler.call(this, client, builder); } - inherits(QueryCompiler_MSSQL, QueryCompiler); - - assign(QueryCompiler_MSSQL.prototype, { + inherits(QueryCompiler_Oracle, QueryCompiler); - _emptyInsertValue: 'default values', + (0, _lodash.assign)(QueryCompiler_Oracle.prototype, { // Compiles an "insert" query, allowing for multiple // inserts using a single query statement. insert: function insert() { + var _this = this; + var insertValues = this.single.insert || []; - var sql = 'insert into ' + this.tableName + ' '; var returning = this.single.returning; - var returningSql = returning ? this._returning('insert', returning) + ' ' : ''; - if (Array.isArray(insertValues)) { - if (insertValues.length === 0) { - return ''; - } - } else if (typeof insertValues === 'object' && _.isEmpty(insertValues)) { - return { - sql: sql + returningSql + this._emptyInsertValue, - returning: returning - }; + if (!Array.isArray(insertValues) && (0, _lodash.isPlainObject)(this.single.insert)) { + insertValues = [this.single.insert]; } - var insertData = this._prepInsert(insertValues); - if (typeof insertData === 'string') { - sql += insertData; - } else { - if (insertData.columns.length) { - sql += '(' + this.formatter.columnize(insertData.columns); - sql += ') ' + returningSql + 'values ('; - var i = -1; - while (++i < insertData.values.length) { - if (i !== 0) sql += '), ('; - sql += this.formatter.parameterize(insertData.values[i]); - } - sql += ')'; - } else if (insertValues.length === 1 && insertValues[0]) { - sql += returningSql + this._emptyInsertValue; - } else { - sql = ''; - } + // always wrap returning argument in array + if (returning && !Array.isArray(returning)) { + returning = [returning]; } - return { - sql: sql, - returning: returning - }; - }, - // Compiles an `update` query, allowing for a return value. - update: function update() { - var updates = this._prepUpdate(this.single.update); - var join = this.join(); - var where = this.where(); - var order = this.order(); - var top = this.top(); - var returning = this.single.returning; - return { - sql: 'update ' + (top ? top + ' ' : '') + this.tableName + (join ? ' ' + join : '') + ' set ' + updates.join(', ') + (returning ? ' ' + this._returning('update', returning) : '') + (where ? ' ' + where : '') + (order ? ' ' + order : '') + (!returning ? this._returning('rowcount', '@@rowcount') : ''), - returning: returning || '@@rowcount' - }; - }, + if (Array.isArray(insertValues) && insertValues.length === 1 && (0, _lodash.isEmpty)(insertValues[0])) { + return this._addReturningToSqlAndConvert('insert into ' + this.tableName + ' (' + this.formatter.wrap(this.single.returning) + ') values (default)', returning, this.tableName); + } - // Compiles a `delete` query. - del: function del() { - // Make sure tableName is processed by the formatter first. - var tableName = this.tableName; - var wheres = this.where(); - var returning = this.single.returning; - return { - sql: 'delete from ' + tableName + (returning ? ' ' + this._returning('del', returning) : '') + (wheres ? ' ' + wheres : '') + (!returning ? this._returning('rowcount', '@@rowcount') : ''), - returning: returning || '@@rowcount' - }; - }, + if ((0, _lodash.isEmpty)(this.single.insert) && typeof this.single.insert !== 'function') { + return ''; + } - // Compiles the columns in the query, specifying if an item was distinct. - columns: function columns() { - var distinct = false; - if (this.onlyUnions()) return ''; - var columns = this.grouped.columns || []; - var i = -1, - sql = []; - if (columns) { - while (++i < columns.length) { - var stmt = columns[i]; - if (stmt.distinct) distinct = true; - if (stmt.type === 'aggregate') { - sql.push(this.aggregate(stmt)); - } else if (stmt.value && stmt.value.length > 0) { - sql.push(this.formatter.columnize(stmt.value)); - } + var insertData = this._prepInsert(insertValues); + + var sql = {}; + + if ((0, _lodash.isString)(insertData)) { + return this._addReturningToSqlAndConvert('insert into ' + this.tableName + ' ' + insertData, returning); + } + + if (insertData.values.length === 1) { + return this._addReturningToSqlAndConvert('insert into ' + this.tableName + ' (' + this.formatter.columnize(insertData.columns) + ') values (' + this.formatter.parameterize(insertData.values[0]) + ')', returning, this.tableName); + } + + var insertDefaultsOnly = insertData.columns.length === 0; + + sql.sql = 'begin ' + (0, _lodash.map)(insertData.values, function (value) { + var returningHelper; + var parameterizedValues = !insertDefaultsOnly ? _this.formatter.parameterize(value) : ''; + var returningValues = Array.isArray(returning) ? returning : [returning]; + var subSql = 'insert into ' + _this.tableName + ' '; + + if (returning) { + returningHelper = new ReturningHelper(returningValues.join(':')); + sql.outParams = (sql.outParams || []).concat(returningHelper); + } + + if (insertDefaultsOnly) { + // no columns given so only the default value + subSql += '(' + _this.formatter.wrap(_this.single.returning) + ') values (default)'; + } else { + subSql += '(' + _this.formatter.columnize(insertData.columns) + ') values (' + parameterizedValues + ')'; } + subSql += returning ? ' returning ROWID into ' + _this.formatter.parameter(returningHelper) : ''; + + // pre bind position because subSql is an execute immediate parameter + // later position binding will only convert the ? params + subSql = _this.formatter.client.positionBindings(subSql); + return 'execute immediate \'' + subSql.replace(/'/g, "''") + (parameterizedValues || returning ? '\' using ' : '') + parameterizedValues + (parameterizedValues && returning ? ', ' : '') + (returning ? 'out ?' : '') + ';'; + }).join(' ') + 'end;'; + + if (returning) { + sql.returning = returning; + // generate select statement with special order by to keep the order because 'in (..)' may change the order + sql.returningSql = 'select ' + this.formatter.columnize(returning) + ' from ' + this.tableName + ' where ROWID in (' + sql.outParams.map(function (v, i) { + return ':' + (i + 1); + }).join(', ') + ')' + ' order by case ROWID ' + sql.outParams.map(function (v, i) { + return 'when CHARTOROWID(:' + (i + 1) + ') then ' + i; + }).join(' ') + ' end'; } - if (sql.length === 0) sql = ['*']; - var top = this.top(); - return 'select ' + (distinct ? 'distinct ' : '') + (top ? top + ' ' : '') + sql.join(', ') + (this.tableName ? ' from ' + this.tableName : ''); + + return sql; }, - _returning: function _returning(method, value) { - switch (method) { - case 'update': - case 'insert': - return value ? 'output ' + this.formatter.columnizeWithPrefix('inserted.', value) : ''; - case 'del': - return value ? 'output ' + this.formatter.columnizeWithPrefix('deleted.', value) : ''; - case 'rowcount': - return value ? ';select @@rowcount' : ''; + // Update method, including joins, wheres, order & limits. + update: function update() { + var updates = this._prepUpdate(this.single.update); + var where = this.where(); + var returning = this.single.returning; + var sql = 'update ' + this.tableName + ' set ' + updates.join(', ') + (where ? ' ' + where : ''); + + if (!returning) { + return sql; + } + + // always wrap returning argument in array + if (returning && !Array.isArray(returning)) { + returning = [returning]; } + + return this._addReturningToSqlAndConvert(sql, returning, this.tableName); }, // Compiles a `truncate` query. @@ -9146,26 +8435,28 @@ return /******/ (function(modules) { // webpackBootstrap }, forUpdate: function forUpdate() { - return 'with (READCOMMITTEDLOCK)'; + return 'for update'; }, forShare: function forShare() { - return 'with (NOLOCK)'; + // lock for share is not directly supported by oracle + // use LOCK TABLE .. IN SHARE MODE; instead + helpers.warn('lock for share is not supported by oracle dialect'); + return ''; }, // Compiles a `columnInfo` query. columnInfo: function columnInfo() { var column = this.single.columnInfo; return { - sql: 'select * from information_schema.columns where table_name = ? and table_schema = \'dbo\'', + sql: 'select COLUMN_NAME, DATA_TYPE, CHAR_COL_DECL_LENGTH, NULLABLE from USER_TAB_COLS where TABLE_NAME = :1', bindings: [this.single.table], output: function output(resp) { - var out = resp.reduce(function (columns, val) { + var out = (0, _lodash.reduce)(resp, function (columns, val) { columns[val.COLUMN_NAME] = { - defaultValue: val.COLUMN_DEFAULT, type: val.DATA_TYPE, - maxLength: val.CHARACTER_MAXIMUM_LENGTH, - nullable: val.IS_NULLABLE === 'YES' + maxLength: val.CHAR_COL_DECL_LENGTH, + nullable: val.NULLABLE === 'Y' }; return columns; }, {}); @@ -9174,638 +8465,687 @@ return /******/ (function(modules) { // webpackBootstrap }; }, - top: function top() { - var noLimit = !this.single.limit && this.single.limit !== 0; - var noOffset = !this.single.offset; - if (noLimit || !noOffset) return ''; - return 'top (' + this.formatter.parameter(this.single.limit) + ')'; - }, + select: function select() { + var _this2 = this; - limit: function limit() { - return ''; + var statements = (0, _lodash.map)(components, function (component) { + return _this2[component](); + }); + var query = (0, _lodash.compact)(statements).join(' '); + return this._surroundQueryWithLimitAndOffset(query); }, - offset: function offset() { - var noLimit = !this.single.limit && this.single.limit !== 0; - var noOffset = !this.single.offset; - if (noOffset) return ''; - var offset = 'offset ' + (noOffset ? '0' : this.formatter.parameter(this.single.offset)) + ' rows'; - if (!noLimit) { - offset += ' fetch next ' + this.formatter.parameter(this.single.limit) + ' rows only'; + aggregate: function aggregate(stmt) { + var val = stmt.value; + var splitOn = val.toLowerCase().indexOf(' as '); + var distinct = stmt.aggregateDistinct ? 'distinct ' : ''; + // Allows us to speciy an alias for the aggregate types. + if (splitOn !== -1) { + var col = val.slice(0, splitOn); + var alias = val.slice(splitOn + 4); + return stmt.method + '(' + distinct + this.formatter.wrap(col) + ') ' + this.formatter.wrap(alias); } - return offset; - } - - }); - - // Set the QueryBuilder & QueryCompiler on the client object, - // incase anyone wants to modify things to suit their own purposes. - module.exports = QueryCompiler_MSSQL; - -/***/ }, -/* 90 */ -/***/ function(module, exports, __webpack_require__) { + return stmt.method + '(' + distinct + this.formatter.wrap(val) + ')'; + }, - - // MySQL Schema Compiler - // ------- - 'use strict'; + // for single commands only + _addReturningToSqlAndConvert: function _addReturningToSqlAndConvert(sql, returning, tableName) { + var res = { + sql: sql + }; - var inherits = __webpack_require__(47); - var SchemaCompiler = __webpack_require__(20); - var assign = __webpack_require__(29); + if (!returning) { + return res; + } - function SchemaCompiler_MSSQL(client, builder) { - SchemaCompiler.call(this, client, builder); - } - inherits(SchemaCompiler_MSSQL, SchemaCompiler); + var returningValues = Array.isArray(returning) ? returning : [returning]; + var returningHelper = new ReturningHelper(returningValues.join(':')); + res.sql = sql + ' returning ROWID into ' + this.formatter.parameter(returningHelper); + res.returningSql = 'select ' + this.formatter.columnize(returning) + ' from ' + tableName + ' where ROWID = :1'; + res.outParams = [returningHelper]; + res.returning = returning; + return res; + }, - assign(SchemaCompiler_MSSQL.prototype, { + _surroundQueryWithLimitAndOffset: function _surroundQueryWithLimitAndOffset(query) { + var limit = this.single.limit; + var offset = this.single.offset; + var hasLimit = limit || limit === 0 || limit === '0'; + limit = +limit; - dropTablePrefix: 'DROP TABLE ', - dropTableIfExists: function dropTableIfExists(tableName) { - var name = this.formatter.wrap(prefixedTableName(this.schema, tableName)); - this.pushQuery('if object_id(\'' + name + '\', \'U\') is not null DROP TABLE ' + name); - }, + if (!hasLimit && !offset) return query; + query = query || ""; - // Rename a table on the schema. - renameTable: function renameTable(tableName, to) { - this.pushQuery('exec sp_rename ' + this.formatter.parameter(tableName) + ', ' + this.formatter.parameter(to)); - }, + if (hasLimit && !offset) { + return "select * from (" + query + ") where rownum <= " + this.formatter.parameter(limit); + } - // Check whether a table exists on the query. - hasTable: function hasTable(tableName) { - this.pushQuery({ - sql: 'select object_id from sys.tables where object_id = object_id(' + this.formatter.parameter(this.formatter.wrap(tableName)) + ')', - output: function output(resp) { - return resp.length > 0; - } - }); - }, + var endRow = +offset + (hasLimit ? limit : 10000000000000); - // Check whether a column exists on the schema. - hasColumn: function hasColumn(tableName, column) { - this.pushQuery({ - sql: 'select object_id from sys.columns where name = ' + this.formatter.parameter(column) + ' and object_id = object_id(' + this.formatter.parameter(this.formatter.wrap(tableName)) + ')', - output: function output(resp) { - return resp.length > 0; - } - }); + return "select * from " + "(select row_.*, ROWNUM rownum_ from (" + query + ") row_ " + "where rownum <= " + this.formatter.parameter(endRow) + ") " + "where rownum_ > " + this.formatter.parameter(offset); } }); - function prefixedTableName(prefix, table) { - return prefix ? prefix + '.' + table : table; - } + // Compiles the `select` statement, or nested sub-selects + // by calling each of the component compilers, trimming out + // the empties, and returning a generated query string. + QueryCompiler_Oracle.prototype.first = QueryCompiler_Oracle.prototype.select; - module.exports = SchemaCompiler_MSSQL; + var components = ['columns', 'join', 'where', 'union', 'group', 'having', 'order', 'lock']; + + module.exports = QueryCompiler_Oracle; /***/ }, -/* 91 */ +/* 71 */ /***/ function(module, exports, __webpack_require__) { - // MSSQL Table Builder & Compiler + // Oracle Schema Compiler // ------- 'use strict'; - var inherits = __webpack_require__(47); - var TableCompiler = __webpack_require__(22); - var helpers = __webpack_require__(2); - var Promise = __webpack_require__(8); - var assign = __webpack_require__(29); + var inherits = __webpack_require__(51); + var SchemaCompiler = __webpack_require__(22); + var utils = __webpack_require__(76); - // Table Compiler - // ------ - - function TableCompiler_MSSQL() { - TableCompiler.apply(this, arguments); + function SchemaCompiler_Oracle() { + SchemaCompiler.apply(this, arguments); } - inherits(TableCompiler_MSSQL, TableCompiler); - - assign(TableCompiler_MSSQL.prototype, { + inherits(SchemaCompiler_Oracle, SchemaCompiler); - createAlterTableMethods: ['foreign', 'primary', 'unique'], - createQuery: function createQuery(columns, ifNot) { - var createStatement = ifNot ? 'if object_id(\'' + this.tableName() + '\', \'U\') is not null CREATE TABLE ' : 'CREATE TABLE '; - var sql = createStatement + this.tableName() + (this._formatting ? ' (\n ' : ' (') + columns.sql.join(this._formatting ? ',\n ' : ', ') + ')'; + // Rename a table on the schema. + SchemaCompiler_Oracle.prototype.renameTable = function (tableName, to) { + this.pushQuery('rename ' + this.formatter.wrap(tableName) + ' to ' + this.formatter.wrap(to)); + }; - if (this.single.comment) { - var comment = this.single.comment || ''; - if (comment.length > 60) helpers.warn('The max length for a table comment is 60 characters'); + // Check whether a table exists on the query. + SchemaCompiler_Oracle.prototype.hasTable = function (tableName) { + this.pushQuery({ + sql: 'select TABLE_NAME from USER_TABLES where TABLE_NAME = ' + this.formatter.parameter(tableName), + output: function output(resp) { + return resp.length > 0; } + }); + }; - this.pushQuery(sql); - }, + // Check whether a column exists on the schema. + SchemaCompiler_Oracle.prototype.hasColumn = function (tableName, column) { + this.pushQuery({ + sql: 'select COLUMN_NAME from USER_TAB_COLUMNS where TABLE_NAME = ' + this.formatter.parameter(tableName) + ' and COLUMN_NAME = ' + this.formatter.parameter(column), + output: function output(resp) { + return resp.length > 0; + } + }); + }; - lowerCase: false, + SchemaCompiler_Oracle.prototype.dropSequenceIfExists = function (sequenceName) { + this.pushQuery(utils.wrapSqlWithCatch("drop sequence " + this.formatter.wrap(sequenceName), -2289)); + }; - addColumnsPrefix: 'ADD ', + SchemaCompiler_Oracle.prototype._dropRelatedSequenceIfExists = function (tableName) { + // removing the sequence that was possibly generated by increments() column + var sequenceName = utils.generateCombinedName('seq', tableName); + this.dropSequenceIfExists(sequenceName); + }; - dropColumnPrefix: 'DROP COLUMN ', + SchemaCompiler_Oracle.prototype.dropTable = function (tableName) { + this.pushQuery('drop table ' + this.formatter.wrap(tableName)); - // Compiles the comment on the table. - comment: function comment() {}, - - changeType: function changeType() {}, - - // Renames a column on the table. - renameColumn: function renameColumn(from, to) { - this.pushQuery('exec sp_rename ' + this.formatter.parameter(this.tableName() + '.' + from) + ', ' + this.formatter.parameter(to) + ', \'COLUMN\''); - }, - - dropFKRefs: function dropFKRefs(runner, refs) { - var formatter = this.client.formatter(); - return Promise.all(refs.map(function (ref) { - var constraintName = formatter.wrap(ref.CONSTRAINT_NAME); - var tableName = formatter.wrap(ref.TABLE_NAME); - return runner.query({ - sql: 'ALTER TABLE ' + tableName + ' DROP CONSTRAINT ' + constraintName - }); - })); - }, - createFKRefs: function createFKRefs(runner, refs) { - var formatter = this.client.formatter(); - - return Promise.all(refs.map(function (ref) { - var tableName = formatter.wrap(ref.TABLE_NAME); - var keyName = formatter.wrap(ref.CONSTRAINT_NAME); - var column = formatter.columnize(ref.COLUMN_NAME); - var references = formatter.columnize(ref.REFERENCED_COLUMN_NAME); - var inTable = formatter.wrap(ref.REFERENCED_TABLE_NAME); - var onUpdate = ' ON UPDATE ' + ref.UPDATE_RULE; - var onDelete = ' ON DELETE ' + ref.DELETE_RULE; + // removing the sequence that was possibly generated by increments() column + this._dropRelatedSequenceIfExists(tableName); + }; - return runner.query({ - sql: 'ALTER TABLE ' + tableName + ' ADD CONSTRAINT ' + keyName + ' FOREIGN KEY (' + column + ') REFERENCES ' + inTable + ' (' + references + ')' + onUpdate + onDelete - }); - })); - }, + SchemaCompiler_Oracle.prototype.dropTableIfExists = function (tableName) { + this.pushQuery(utils.wrapSqlWithCatch("drop table " + this.formatter.wrap(tableName), -942)); - index: function index(columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('CREATE INDEX ' + indexName + ' ON ' + this.tableName() + ' (' + this.formatter.columnize(columns) + ')'); - }, + // removing the sequence that was possibly generated by increments() column + this._dropRelatedSequenceIfExists(tableName); + }; - primary: function primary(columns, indexName) { - indexName = indexName || this._indexCommand('primary', this.tableNameRaw, columns); - if (!this.forCreate) { - this.pushQuery('ALTER TABLE ' + this.tableName() + ' ADD PRIMARY KEY (' + this.formatter.columnize(columns) + ')'); - } else { - this.pushQuery('CONSTRAINT ' + indexName + ' PRIMARY KEY (' + this.formatter.columnize(columns) + ')'); - } - }, + module.exports = SchemaCompiler_Oracle; - unique: function unique(columns, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, columns); - if (!this.forCreate) { - this.pushQuery('CREATE UNIQUE INDEX ' + indexName + ' ON ' + this.tableName() + ' (' + this.formatter.columnize(columns) + ')'); - } else { - this.pushQuery('CONSTRAINT ' + indexName + ' UNIQUE (' + this.formatter.columnize(columns) + ')'); - } - }, +/***/ }, +/* 72 */ +/***/ function(module, exports, __webpack_require__) { - // Compile a drop index command. - dropIndex: function dropIndex(columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('DROP INDEX ' + indexName + ' ON ' + this.tableName()); - }, + 'use strict'; - // Compile a drop foreign key command. - dropForeign: function dropForeign(columns, indexName) { - indexName = indexName || this._indexCommand('foreign', this.tableNameRaw, columns); - this.pushQuery('ALTER TABLE ' + this.tableName() + ' DROP CONSTRAINT ' + indexName); - }, + var _lodash = __webpack_require__(1); - // Compile a drop primary key command. - dropPrimary: function dropPrimary() { - this.pushQuery('ALTER TABLE ' + this.tableName() + ' DROP PRIMARY KEY'); - }, + var inherits = __webpack_require__(51); + var ColumnBuilder = __webpack_require__(25); - // Compile a drop unique key command. - dropUnique: function dropUnique(column, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, column); - this.pushQuery('ALTER TABLE ' + this.tableName() + ' DROP CONSTRAINT ' + indexName); - } + function ColumnBuilder_Oracle() { + ColumnBuilder.apply(this, arguments); + } + inherits(ColumnBuilder_Oracle, ColumnBuilder); - }); + // checkIn added to the builder to allow the column compiler to change the + // order via the modifiers ("check" must be after "default") + ColumnBuilder_Oracle.prototype.checkIn = function () { + this._modifiers.checkIn = (0, _lodash.toArray)(arguments); + return this; + }; - module.exports = TableCompiler_MSSQL; + module.exports = ColumnBuilder_Oracle; /***/ }, -/* 92 */ +/* 73 */ /***/ function(module, exports, __webpack_require__) { - - // MySQL Column Compiler - // ------- 'use strict'; - var inherits = __webpack_require__(47); - var ColumnCompiler = __webpack_require__(24); - var helpers = __webpack_require__(2); - var assign = __webpack_require__(29); + var _lodash = __webpack_require__(1); - function ColumnCompiler_MSSQL() { + var inherits = __webpack_require__(51); + var utils = __webpack_require__(76); + var Raw = __webpack_require__(2); + var ColumnCompiler = __webpack_require__(26); + + // Column Compiler + // ------- + + function ColumnCompiler_Oracle() { + this.modifiers = ['defaultTo', 'checkIn', 'nullable', 'comment']; ColumnCompiler.apply(this, arguments); - this.modifiers = ['nullable', 'defaultTo', 'first', 'after', 'comment']; } - inherits(ColumnCompiler_MSSQL, ColumnCompiler); + inherits(ColumnCompiler_Oracle, ColumnCompiler); - // Types - // ------ + (0, _lodash.assign)(ColumnCompiler_Oracle.prototype, { - assign(ColumnCompiler_MSSQL.prototype, { + // helper function for pushAdditional in increments() and bigincrements() + _createAutoIncrementTriggerAndSequence: function _createAutoIncrementTriggerAndSequence() { + // TODO Add warning that sequence etc is created + this.pushAdditional(function () { + var sequenceName = this.tableCompiler._indexCommand('seq', this.tableCompiler.tableNameRaw); + var triggerName = this.tableCompiler._indexCommand('trg', this.tableCompiler.tableNameRaw, this.getColumnName()); + var tableName = this.tableCompiler.tableName(); + var columnName = this.formatter.wrap(this.getColumnName()); + var createTriggerSQL = 'create or replace trigger ' + triggerName + ' before insert on ' + tableName + ' for each row' + ' when (new.' + columnName + ' is null) ' + ' begin' + ' select ' + sequenceName + '.nextval into :new.' + columnName + ' from dual;' + ' end;'; + this.pushQuery(utils.wrapSqlWithCatch('create sequence ' + sequenceName, -955)); + this.pushQuery(createTriggerSQL); + }); + }, - increments: 'int identity(1,1) not null primary key', + increments: function increments() { + this._createAutoIncrementTriggerAndSequence(); + return 'integer not null primary key'; + }, - bigincrements: 'bigint identity(1,1) not null primary key', + bigincrements: function bigincrements() { + this._createAutoIncrementTriggerAndSequence(); + return 'number(20, 0) not null primary key'; + }, - bigint: 'bigint', + floating: function floating(precision) { + var parsedPrecision = this._num(precision, 0); + return 'float' + (parsedPrecision ? '(' + parsedPrecision + ')' : ''); + }, double: function double(precision, scale) { - if (!precision) return 'double'; - return 'double(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; + // if (!precision) return 'number'; // TODO: Check If default is ok + return 'number(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; }, integer: function integer(length) { - length = length ? '(' + this._num(length, 11) + ')' : ''; - return 'int' + length; + return length ? 'number(' + this._num(length, 11) + ')' : 'integer'; }, - mediumint: 'mediumint', + tinyint: 'smallint', smallint: 'smallint', - tinyint: function tinyint(length) { - length = length ? '(' + this._num(length, 1) + ')' : ''; - return 'tinyint' + length; - }, - - varchar: function varchar(length) { - return 'nvarchar(' + this._num(length, 255) + ')'; - }, - - text: 'nvarchar(max)', + mediumint: 'integer', - mediumtext: 'nvarchar(max)', + biginteger: 'number(20, 0)', - longtext: 'nvarchar(max)', + text: 'clob', - enu: 'nvarchar(100)', + enu: function enu(allowed) { + allowed = (0, _lodash.uniq)(allowed); + var maxLength = (allowed || []).reduce(function (maxLength, name) { + return Math.max(maxLength, String(name).length); + }, 1); - uuid: 'uniqueidentifier', + // implicitly add the enum values as checked values + this.columnBuilder._modifiers.checkIn = [allowed]; - datetime: 'datetime', + return "varchar2(" + maxLength + ")"; + }, - timestamp: 'datetime', + time: 'timestamp with time zone', - bit: function bit(length) { - return length ? 'bit(' + this._num(length) + ')' : 'bit'; + datetime: function datetime(without) { + return without ? 'timestamp' : 'timestamp with time zone'; }, - binary: function binary(length) { - return length ? 'varbinary(' + this._num(length) + ')' : 'blob'; + timestamp: function timestamp(without) { + return without ? 'timestamp' : 'timestamp with time zone'; }, - bool: 'bit', + bit: 'clob', - // Modifiers - // ------ + json: 'clob', - defaultTo: function defaultTo(value) { - /*jshint unused: false*/ - var defaultVal = ColumnCompiler_MSSQL.super_.prototype.defaultTo.apply(this, arguments); - if (this.type !== 'blob' && this.type.indexOf('text') === -1) { - return defaultVal; - } - return ''; + bool: function bool() { + // implicitly add the check for 0 and 1 + this.columnBuilder._modifiers.checkIn = [[0, 1]]; + return 'number(1, 0)'; }, - first: function first() { - return 'first'; + varchar: function varchar(length) { + return 'varchar2(' + this._num(length, 255) + ')'; }, - after: function after(column) { - return 'after ' + this.formatter.wrap(column); - }, + // Modifiers + // ------ comment: function comment(_comment) { - if (_comment && _comment.length > 255) { - helpers.warn('Your comment is longer than the max comment length for MSSQL'); + this.pushAdditional(function () { + this.pushQuery('comment on column ' + this.tableCompiler.tableName() + '.' + this.formatter.wrap(this.args[0]) + " is '" + (_comment || '') + "'"); + }, _comment); + }, + + checkIn: function checkIn(value) { + // TODO: Maybe accept arguments also as array + // TODO: value(s) should be escaped properly + if (value === undefined) { + return ''; + } else if (value instanceof Raw) { + value = value.toQuery(); + } else if (Array.isArray(value)) { + value = (0, _lodash.map)(value, function (v) { + return "'" + v + "'"; + }).join(', '); + } else { + value = "'" + value + "'"; } - return ''; + return 'check (' + this.formatter.wrap(this.args[0]) + ' in (' + value + '))'; } }); - module.exports = ColumnCompiler_MSSQL; + module.exports = ColumnCompiler_Oracle; /***/ }, -/* 93 */ +/* 74 */ /***/ function(module, exports, __webpack_require__) { - var baseFlatten = __webpack_require__(145), - bindCallback = __webpack_require__(67), - pickByArray = __webpack_require__(146), - pickByCallback = __webpack_require__(147), - restParam = __webpack_require__(130); - - /** - * Creates an object composed of the picked `object` properties. Property - * names may be specified as individual arguments or as arrays of property - * names. If `predicate` is provided it's invoked for each property of `object` - * picking the properties `predicate` returns truthy for. The predicate is - * bound to `thisArg` and invoked with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {Function|...(string|string[])} [predicate] The function invoked per - * iteration or property names to pick, specified as individual property - * names or arrays of property names. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'user': 'fred', 'age': 40 }; - * - * _.pick(object, 'user'); - * // => { 'user': 'fred' } - * - * _.pick(object, _.isString); - * // => { 'user': 'fred' } - */ - var pick = restParam(function(object, props) { - if (object == null) { - return {}; - } - return typeof props[0] == 'function' - ? pickByCallback(object, bindCallback(props[0], props[1], 3)) - : pickByArray(object, baseFlatten(props)); - }); + 'use strict'; - module.exports = pick; + var _lodash = __webpack_require__(1); + // Table Compiler + // ------ -/***/ }, -/* 94 */ -/***/ function(module, exports, __webpack_require__) { + var inherits = __webpack_require__(51); + var utils = __webpack_require__(76); + var TableCompiler = __webpack_require__(24); + var helpers = __webpack_require__(3); - 'use strict'; + function TableCompiler_Oracle() { + TableCompiler.apply(this, arguments); + } + inherits(TableCompiler_Oracle, TableCompiler); - var Transaction = __webpack_require__(16); - var assign = __webpack_require__(29); - var inherits = __webpack_require__(47); - var debug = __webpack_require__(48)('knex:tx'); - var helpers = __webpack_require__(2); + (0, _lodash.assign)(TableCompiler_Oracle.prototype, { - function Transaction_MySQL2() { - Transaction.apply(this, arguments); - } - inherits(Transaction_MySQL2, Transaction); + // Compile a rename column command. + renameColumn: function renameColumn(from, to) { + return this.pushQuery({ + sql: 'alter table ' + this.tableName() + ' rename column ' + this.formatter.wrap(from) + ' to ' + this.formatter.wrap(to) + }); + }, - assign(Transaction_MySQL2.prototype, { + compileAdd: function compileAdd(builder) { + var table = this.formatter.wrap(builder); + var columns = this.prefixArray('add column', this.getColumns(builder)); + return this.pushQuery({ + sql: 'alter table ' + table + ' ' + columns.join(', ') + }); + }, - query: function query(conn, sql, status, value) { - var t = this; - var q = this.trxClient.query(conn, sql)['catch'](function (err) { - return err.code === 'ER_SP_DOES_NOT_EXIST'; - }, function () { - helpers.warn('Transaction was implicitly committed, do not mix transactions and DDL with MySQL (#805)'); - })['catch'](function (err) { - status = 2; - value = err; - t._completed = true; - debug('%s error running transaction query', t.txid); - }).tap(function () { - if (status === 1) t._resolver(value); - if (status === 2) t._rejecter(value); + // Adds the "create" query to the query sequence. + createQuery: function createQuery(columns, ifNot) { + var sql = 'create table ' + this.tableName() + ' (' + columns.sql.join(', ') + ')'; + this.pushQuery({ + // catch "name is already used by an existing object" for workaround for "if not exists" + sql: ifNot ? utils.wrapSqlWithCatch(sql, -955) : sql, + bindings: columns.bindings }); - if (status === 1 || status === 2) { - t._completed = true; - } - return q; - } + if (this.single.comment) this.comment(this.single.comment); + }, - }); + // Compiles the comment on the table. + comment: function comment(_comment) { + this.pushQuery('comment on table ' + this.tableName() + ' is ' + "'" + (_comment || '') + "'"); + }, - module.exports = Transaction_MySQL2; + addColumnsPrefix: 'add ', -/***/ }, -/* 95 */ -/***/ function(module, exports, __webpack_require__) { + dropColumn: function dropColumn() { + var columns = helpers.normalizeArr.apply(null, arguments); + this.pushQuery('alter table ' + this.tableName() + ' drop (' + this.formatter.columnize(columns) + ')'); + }, - 'use strict'; + changeType: function changeType() { + // alter table + table + ' modify ' + wrapped + '// type'; + }, + + _indexCommand: function _indexCommand(type, tableName, columns) { + return this.formatter.wrap(utils.generateCombinedName(type, tableName, columns)); + }, - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - var Formatter = __webpack_require__(15); - var ReturningHelper = __webpack_require__(103).ReturningHelper; + primary: function primary(columns) { + this.pushQuery('alter table ' + this.tableName() + " add primary key (" + this.formatter.columnize(columns) + ")"); + }, - function Oracle_Formatter(client) { - Formatter.call(this, client); - } - inherits(Oracle_Formatter, Formatter); + dropPrimary: function dropPrimary() { + this.pushQuery('alter table ' + this.tableName() + ' drop primary key'); + }, - assign(Oracle_Formatter.prototype, { + index: function index(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('create index ' + indexName + ' on ' + this.tableName() + ' (' + this.formatter.columnize(columns) + ')'); + }, - alias: function alias(first, second) { - return first + ' ' + second; + dropIndex: function dropIndex(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('drop index ' + indexName); }, - parameter: function parameter(value, notSetValue) { - // Returning helper uses always ROWID as string - if (value instanceof ReturningHelper && this.client.driver) { - value = new this.client.driver.OutParam(this.client.driver.OCCISTRING); - } else if (typeof value === 'boolean') { - value = value ? 1 : 0; - } - return Formatter.prototype.parameter.call(this, value, notSetValue); + unique: function unique(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' add constraint ' + indexName + ' unique (' + this.formatter.columnize(columns) + ')'); + }, + + dropUnique: function dropUnique(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); + }, + + dropForeign: function dropForeign(columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); } }); - module.exports = Oracle_Formatter; + module.exports = TableCompiler_Oracle; /***/ }, -/* 96 */ +/* 75 */ /***/ function(module, exports, __webpack_require__) { + /* WEBPACK VAR INJECTION */(function(process) { + /*jslint node:true, nomen: true*/ 'use strict'; - var inherits = __webpack_require__(47); - var Promise = __webpack_require__(8); - var Transaction = __webpack_require__(16); - var assign = __webpack_require__(29); - var debugTx = __webpack_require__(48)('knex:tx'); + var _lodash = __webpack_require__(1); - function Oracle_Transaction(client, container, config, outerTx) { - Transaction.call(this, client, container, config, outerTx); - } - inherits(Oracle_Transaction, Transaction); - - assign(Oracle_Transaction.prototype, { - - // disable autocommit to allow correct behavior (default is true) - begin: function begin() { - return Promise.resolve(); - }, - - commit: function commit(conn, value) { - this._completed = true; - return conn.commitAsync()['return'](value).then(this._resolver, this._rejecter); - }, + var inherits = __webpack_require__(51); + var Readable = __webpack_require__(98).Readable; - release: function release(conn, value) { - return this._resolver(value); - }, + function OracleQueryStream(connection, sql, bindings, options) { + Readable.call(this, (0, _lodash.merge)({}, { + objectMode: true, + highWaterMark: 1000 + }, options)); + this.oracleReader = connection.reader(sql, bindings || []); + } + inherits(OracleQueryStream, Readable); - rollback: function rollback(conn, err) { - this._completed = true; - debugTx('%s: rolling back', this.txid); - return conn.rollbackAsync()['throw'](err)['catch'](this._rejecter); - }, + OracleQueryStream.prototype._read = function () { + var _this = this; - acquireConnection: function acquireConnection(config) { - var t = this; - return Promise['try'](function () { - return config.connection || t.client.acquireConnection(); - }).tap(function (connection) { - if (!t.outerTx) { - connection.setAutoCommit(false); - } - }).disposer(function (connection) { - debugTx('%s: releasing connection', t.txid); - connection.setAutoCommit(true); - if (!config.connection) { - t.client.releaseConnection(connection); + var pushNull = function pushNull() { + process.nextTick(function () { + _this.push(null); + }); + }; + try { + this.oracleReader.nextRows(function (err, rows) { + if (err) return _this.emit('error', err); + if (rows.length === 0) { + pushNull(); } else { - debugTx('%s: not releasing external connection', t.txid); + for (var i = 0; i < rows.length; i++) { + if (rows[i]) { + _this.push(rows[i]); + } else { + pushNull(); + } + } } }); + } catch (e) { + // Catch Error: invalid state: reader is busy with another nextRows call + // and return false to rate limit stream. + if (e.message === 'invalid state: reader is busy with another nextRows call') { + return false; + } else { + this.emit('error', e); + } } + }; - }); - - module.exports = Oracle_Transaction; + module.exports = OracleQueryStream; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) /***/ }, -/* 97 */ +/* 76 */ /***/ function(module, exports, __webpack_require__) { - - // Oracle Query Builder & Compiler - // ------ 'use strict'; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var QueryCompiler = __webpack_require__(18); - var helpers = __webpack_require__(2); - var assign = __webpack_require__(29); - var ReturningHelper = __webpack_require__(103).ReturningHelper; + var helpers = __webpack_require__(3); - // Query Compiler - // ------- + function generateCombinedName(postfix, name, subNames) { + var crypto = __webpack_require__(99); + var limit = 30; + if (!Array.isArray(subNames)) subNames = subNames ? [subNames] : []; + var table = name.replace(/\.|-/g, '_'); + var subNamesPart = subNames.join('_'); + var result = (table + '_' + (subNamesPart.length ? subNamesPart + '_' : '') + postfix).toLowerCase(); + if (result.length > limit) { + helpers.warn('Automatically generated name "' + result + '" exceeds ' + limit + ' character limit for Oracle. Using base64 encoded sha1 of that name instead.'); + // generates the sha1 of the name and encode it with base64 + result = crypto.createHash('sha1').update(result).digest('base64').replace('=', ''); + } + return result; + } - // Set the "Formatter" to use for the queries, - // ensuring that all parameterized values (even across sub-queries) - // are properly built into the same query. - function QueryCompiler_Oracle(client, builder) { - QueryCompiler.call(this, client, builder); + function wrapSqlWithCatch(sql, errorNumberToCatch) { + return "begin execute immediate '" + sql.replace(/'/g, "''") + "'; exception when others then if sqlcode != " + errorNumberToCatch + " then raise; end if; end;"; } - inherits(QueryCompiler_Oracle, QueryCompiler); - assign(QueryCompiler_Oracle.prototype, { + function ReturningHelper(columnName) { + this.columnName = columnName; + } - // Compiles an "insert" query, allowing for multiple - // inserts using a single query statement. - insert: function insert() { - var insertValues = this.single.insert || []; - var returning = this.single.returning; + ReturningHelper.prototype.toString = function () { + return '[object ReturningHelper:' + this.columnName + ']'; + }; - if (!Array.isArray(insertValues) && _.isPlainObject(this.single.insert)) { - insertValues = [this.single.insert]; - } + module.exports = { + generateCombinedName: generateCombinedName, + wrapSqlWithCatch: wrapSqlWithCatch, + ReturningHelper: ReturningHelper + }; - // always wrap returning argument in array - if (returning && !Array.isArray(returning)) { - returning = [returning]; - } +/***/ }, +/* 77 */ +/***/ function(module, exports, __webpack_require__) { - if (Array.isArray(insertValues) && insertValues.length === 1 && _.isEmpty(insertValues[0])) { - return this._addReturningToSqlAndConvert('insert into ' + this.tableName + ' (' + this.formatter.wrap(this.single.returning) + ') values (default)', returning, this.tableName); - } + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - if (_.isEmpty(this.single.insert) && typeof this.single.insert !== 'function') { - return ''; + function dateToString(date) { + function pad(number, digits) { + number = number.toString(); + while (number.length < digits) { + number = "0" + number; } + return number; + } - var insertData = this._prepInsert(insertValues); + var offset = -date.getTimezoneOffset(); + var ret = pad(date.getFullYear(), 4) + '-' + pad(date.getMonth() + 1, 2) + '-' + pad(date.getDate(), 2) + 'T' + pad(date.getHours(), 2) + ':' + pad(date.getMinutes(), 2) + ':' + pad(date.getSeconds(), 2) + '.' + pad(date.getMilliseconds(), 3); - var sql = {}; + if (offset < 0) { + ret += "-"; + offset *= -1; + } else { + ret += "+"; + } - if (_.isString(insertData)) { - return this._addReturningToSqlAndConvert('insert into ' + this.tableName + ' ' + insertData, returning); + return ret + pad(Math.floor(offset / 60), 2) + ":" + pad(offset % 60, 2); + } + + var prepareObject; + var arrayString; + + // converts values from javascript types + // to their 'raw' counterparts for use as a postgres parameter + // note: you can override this function to provide your own conversion mechanism + // for complex types, etc... + var prepareValue = function prepareValue(val, seen, valueForUndefined) { + if (val instanceof Buffer) { + return val; + } + if (val instanceof Date) { + return dateToString(val); + } + if (Array.isArray(val)) { + return arrayString(val); + } + if (val === null) { + return null; + } + if (val === undefined) { + return valueForUndefined; + } + if (typeof val === 'object') { + return prepareObject(val, seen); + } + return val.toString(); + }; + + prepareObject = function prepareObject(val, seen) { + if (val && typeof val.toPostgres === 'function') { + seen = seen || []; + if (seen.indexOf(val) !== -1) { + throw new Error('circular reference detected while preparing "' + val + '" for query'); } + seen.push(val); - if (insertData.values.length === 1) { - return this._addReturningToSqlAndConvert('insert into ' + this.tableName + ' (' + this.formatter.columnize(insertData.columns) + ') values (' + this.formatter.parameterize(insertData.values[0]) + ')', returning, this.tableName); + return prepareValue(val.toPostgres(prepareValue), seen); + } + return JSON.stringify(val); + }; + + // convert a JS array to a postgres array literal + // uses comma separator so won't work for types like box that use + // a different array separator. + arrayString = function arrayString(val) { + return '{' + val.map(function (elem) { + if (elem === null || elem === undefined) { + return 'NULL'; + } + if (Array.isArray(elem)) { + return arrayString(elem); + } + return JSON.stringify(prepareValue(elem)); + }).join(',') + '}'; + }; + + function normalizeQueryConfig(config, values, callback) { + //can take in strings or config objects + config = typeof config === 'string' ? { text: config } : config; + if (values) { + if (typeof values === 'function') { + config.callback = values; + } else { + config.values = values; } + } + if (callback) { + config.callback = callback; + } + return config; + } - var insertDefaultsOnly = insertData.columns.length === 0; + module.exports = { + prepareValue: prepareValue, + normalizeQueryConfig: normalizeQueryConfig + }; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) - sql.sql = 'begin ' + _.map(insertData.values, function (value) { - var returningHelper; - var parameterizedValues = !insertDefaultsOnly ? this.formatter.parameterize(value) : ''; - var returningValues = Array.isArray(returning) ? returning : [returning]; - var subSql = 'insert into ' + this.tableName + ' '; +/***/ }, +/* 78 */ +/***/ function(module, exports, __webpack_require__) { - if (returning) { - returningHelper = new ReturningHelper(returningValues.join(':')); - sql.outParams = (sql.outParams || []).concat(returningHelper); - } + + // PostgreSQL Query Builder & Compiler + // ------ + 'use strict'; - if (insertDefaultsOnly) { - // no columns given so only the default value - subSql += '(' + this.formatter.wrap(this.single.returning) + ') values (default)'; - } else { - subSql += '(' + this.formatter.columnize(insertData.columns) + ') values (' + parameterizedValues + ')'; - } - subSql += returning ? ' returning ROWID into ' + this.formatter.parameter(returningHelper) : ''; + var _lodash = __webpack_require__(1); - // pre bind position because subSql is an execute immediate parameter - // later position binding will only convert the ? params - subSql = this.formatter.client.positionBindings(subSql); - return 'execute immediate \'' + subSql.replace(/'/g, "''") + (parameterizedValues || returning ? '\' using ' : '') + parameterizedValues + (parameterizedValues && returning ? ', ' : '') + (returning ? 'out ?' : '') + ';'; - }, this).join(' ') + 'end;'; + var inherits = __webpack_require__(51); - if (returning) { - sql.returning = returning; - // generate select statement with special order by to keep the order because 'in (..)' may change the order - sql.returningSql = 'select ' + this.formatter.columnize(returning) + ' from ' + this.tableName + ' where ROWID in (' + sql.outParams.map(function (v, i) { - return ':' + (i + 1); - }).join(', ') + ')' + ' order by case ROWID ' + sql.outParams.map(function (v, i) { - return 'when CHARTOROWID(:' + (i + 1) + ') then ' + i; - }).join(' ') + ' end'; - } + var QueryCompiler = __webpack_require__(20); - return sql; + function QueryCompiler_PG(client, builder) { + QueryCompiler.call(this, client, builder); + } + inherits(QueryCompiler_PG, QueryCompiler); + + (0, _lodash.assign)(QueryCompiler_PG.prototype, { + + // Compiles a truncate query. + truncate: function truncate() { + return 'truncate ' + this.tableName + ' restart identity'; }, - // Update method, including joins, wheres, order & limits. + // is used if the an array with multiple empty values supplied + _defaultInsertValue: 'default', + + // Compiles an `insert` query, allowing for multiple + // inserts using a single query statement. + insert: function insert() { + var sql = QueryCompiler.prototype.insert.call(this); + if (sql === '') return sql; + var returning = this.single.returning; + return { + sql: sql + this._returning(returning), + returning: returning + }; + }, + + // Compiles an `update` query, allowing for a return value. update: function update() { - var updates = this._prepUpdate(this.single.update); - var where = this.where(); - return 'update ' + this.tableName + ' set ' + updates.join(', ') + (where ? ' ' + where : ''); + var updateData = this._prepUpdate(this.single.update); + var wheres = this.where(); + var returning = this.single.returning; + return { + sql: 'update ' + this.tableName + ' set ' + updateData.join(', ') + (wheres ? ' ' + wheres : '') + this._returning(returning), + returning: returning + }; }, - // Compiles a `truncate` query. - truncate: function truncate() { - return 'truncate table ' + this.tableName; + // Compiles an `update` query, allowing for a return value. + del: function del() { + var sql = QueryCompiler.prototype.del.apply(this, arguments); + var returning = this.single.returning; + return { + sql: sql + this._returning(returning), + returning: returning + }; + }, + + _returning: function _returning(value) { + return value ? ' returning ' + this.formatter.columnize(value) : ''; }, forUpdate: function forUpdate() { @@ -9813,2427 +9153,2278 @@ return /******/ (function(modules) { // webpackBootstrap }, forShare: function forShare() { - // lock for share is not directly supported by oracle - // use LOCK TABLE .. IN SHARE MODE; instead - helpers.warn('lock for share is not supported by oracle dialect'); - return ''; + return 'for share'; }, - // Compiles a `columnInfo` query. + // Compiles a columnInfo query columnInfo: function columnInfo() { var column = this.single.columnInfo; + + var sql = 'select * from information_schema.columns where table_name = ? and table_catalog = ?'; + var bindings = [this.single.table, this.client.database()]; + + if (this.single.schema) { + sql += ' and table_schema = ?'; + bindings.push(this.single.schema); + } else { + sql += ' and table_schema = current_schema'; + } + return { - sql: 'select COLUMN_NAME, DATA_TYPE, CHAR_COL_DECL_LENGTH, NULLABLE from USER_TAB_COLS where TABLE_NAME = :1', - bindings: [this.single.table], + sql: sql, + bindings: bindings, output: function output(resp) { - var out = _.reduce(resp, function (columns, val) { - columns[val.COLUMN_NAME] = { - type: val.DATA_TYPE, - maxLength: val.CHAR_COL_DECL_LENGTH, - nullable: val.NULLABLE === 'Y' + var out = (0, _lodash.reduce)(resp.rows, function (columns, val) { + columns[val.column_name] = { + type: val.data_type, + maxLength: val.character_maximum_length, + nullable: val.is_nullable === 'YES', + defaultValue: val.column_default }; return columns; }, {}); return column && out[column] || out; } }; - }, + } - select: function select() { - var statements = _.map(components, function (component) { - return this[component](); - }, this); - var query = _.compact(statements).join(' '); - return this._surroundQueryWithLimitAndOffset(query); - }, + }); - aggregate: function aggregate(stmt) { - var val = stmt.value; - var splitOn = val.toLowerCase().indexOf(' as '); - var distinct = stmt.aggregateDistinct ? 'distinct ' : ''; - // Allows us to speciy an alias for the aggregate types. - if (splitOn !== -1) { - var col = val.slice(0, splitOn); - var alias = val.slice(splitOn + 4); - return stmt.method + '(' + distinct + this.formatter.wrap(col) + ') ' + this.formatter.wrap(alias); - } - return stmt.method + '(' + distinct + this.formatter.wrap(val) + ')'; - }, + module.exports = QueryCompiler_PG; - // for single commands only - _addReturningToSqlAndConvert: function _addReturningToSqlAndConvert(sql, returning, tableName) { - var res = { - sql: sql - }; +/***/ }, +/* 79 */ +/***/ function(module, exports, __webpack_require__) { - if (!returning) { - return res; - } + + // PostgreSQL Column Compiler + // ------- - var returningValues = Array.isArray(returning) ? returning : [returning]; - var returningHelper = new ReturningHelper(returningValues.join(':')); - res.sql = sql + ' returning ROWID into ' + this.formatter.parameter(returningHelper); - res.returningSql = 'select ' + this.formatter.columnize(returning) + ' from ' + tableName + ' where ROWID = :1'; - res.outParams = [returningHelper]; - res.returning = returning; - return res; - }, + 'use strict'; - _surroundQueryWithLimitAndOffset: function _surroundQueryWithLimitAndOffset(query) { - var limit = this.single.limit; - var offset = this.single.offset; - var hasLimit = limit || limit === 0 || limit === '0'; - limit = +limit; + var _lodash = __webpack_require__(1); - if (!hasLimit && !offset) return query; - query = query || ""; + var inherits = __webpack_require__(51); + var ColumnCompiler = __webpack_require__(26); + var helpers = __webpack_require__(3); - if (hasLimit && !offset) { - return "select * from (" + query + ") where rownum <= " + this.formatter.parameter(limit); - } + function ColumnCompiler_PG() { + ColumnCompiler.apply(this, arguments); + this.modifiers = ['nullable', 'defaultTo', 'comment']; + } + inherits(ColumnCompiler_PG, ColumnCompiler); - var endRow = +offset + (hasLimit ? limit : 10000000000000); + (0, _lodash.assign)(ColumnCompiler_PG.prototype, { - return "select * from " + "(select row_.*, ROWNUM rownum_ from (" + query + ") row_ " + "where rownum <= " + this.formatter.parameter(endRow) + ") " + "where rownum_ > " + this.formatter.parameter(offset); + // Types + // ------ + bigincrements: 'bigserial primary key', + bigint: 'bigint', + binary: 'bytea', + + bit: function bit(column) { + return column.length !== false ? 'bit(' + column.length + ')' : 'bit'; + }, + + bool: 'boolean', + + // Create the column definition for an enum type. + // Using method "2" here: http://stackoverflow.com/a/10984951/525714 + enu: function enu(allowed) { + return 'text check (' + this.formatter.wrap(this.args[0]) + " in ('" + allowed.join("', '") + "'))"; + }, + + double: 'double precision', + floating: 'real', + increments: 'serial primary key', + json: function json(jsonb) { + if (jsonb) helpers.deprecate('json(true)', 'jsonb()'); + return jsonColumn(this.client, jsonb); + }, + jsonb: function jsonb() { + return jsonColumn(this.client, true); + }, + smallint: 'smallint', + tinyint: 'smallint', + datetime: function datetime(without) { + return without ? 'timestamp' : 'timestamptz'; + }, + timestamp: function timestamp(without) { + return without ? 'timestamp' : 'timestamptz'; + }, + uuid: 'uuid', + + // Modifiers: + // ------ + comment: function comment(_comment) { + this.pushAdditional(function () { + this.pushQuery('comment on column ' + this.tableCompiler.tableName() + '.' + this.formatter.wrap(this.args[0]) + " is " + (_comment ? "'" + _comment + "'" : 'NULL')); + }, _comment); } }); - // Compiles the `select` statement, or nested sub-selects - // by calling each of the component compilers, trimming out - // the empties, and returning a generated query string. - QueryCompiler_Oracle.prototype.first = QueryCompiler_Oracle.prototype.select; + function jsonColumn(client, jsonb) { + if (!client.version || parseFloat(client.version) >= 9.2) return jsonb ? 'jsonb' : 'json'; + return 'text'; + } - var components = ['columns', 'join', 'where', 'union', 'group', 'having', 'order', 'lock']; + module.exports = ColumnCompiler_PG; - module.exports = QueryCompiler_Oracle; +/***/ }, +/* 80 */ +/***/ function(module, exports, __webpack_require__) { + + // PostgreSQL Table Builder & Compiler + // ------- + + 'use strict'; + + var _lodash = __webpack_require__(1); + + var inherits = __webpack_require__(51); + var TableCompiler = __webpack_require__(24); + + function TableCompiler_PG() { + TableCompiler.apply(this, arguments); + } + inherits(TableCompiler_PG, TableCompiler); + + // Compile a rename column command. + TableCompiler_PG.prototype.renameColumn = function (from, to) { + return this.pushQuery({ + sql: 'alter table ' + this.tableName() + ' rename ' + this.formatter.wrap(from) + ' to ' + this.formatter.wrap(to) + }); + }; + + TableCompiler_PG.prototype.compileAdd = function (builder) { + var table = this.formatter.wrap(builder); + var columns = this.prefixArray('add column', this.getColumns(builder)); + return this.pushQuery({ + sql: 'alter table ' + table + ' ' + columns.join(', ') + }); + }; + + // Adds the "create" query to the query sequence. + TableCompiler_PG.prototype.createQuery = function (columns, ifNot) { + var createStatement = ifNot ? 'create table if not exists ' : 'create table '; + var sql = createStatement + this.tableName() + ' (' + columns.sql.join(', ') + ')'; + if (this.single.inherits) sql += ' inherits (' + this.formatter.wrap(this.single.inherits) + ')'; + this.pushQuery({ + sql: sql, + bindings: columns.bindings + }); + var hasComment = (0, _lodash.has)(this.single, 'comment'); + if (hasComment) this.comment(this.single.comment); + }; + + // Compiles the comment on the table. + TableCompiler_PG.prototype.comment = function (comment) { + /*jshint unused: false*/ + this.pushQuery('comment on table ' + this.tableName() + ' is ' + "'" + (this.single.comment || '') + "'"); + }; + + // Indexes: + // ------- + + TableCompiler_PG.prototype.primary = function (columns) { + this.pushQuery('alter table ' + this.tableName() + " add primary key (" + this.formatter.columnize(columns) + ")"); + }; + TableCompiler_PG.prototype.unique = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' add constraint ' + indexName + ' unique (' + this.formatter.columnize(columns) + ')'); + }; + TableCompiler_PG.prototype.index = function (columns, indexName, indexType) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('create index ' + indexName + ' on ' + this.tableName() + (indexType && ' using ' + indexType || '') + ' (' + this.formatter.columnize(columns) + ')'); + }; + TableCompiler_PG.prototype.dropPrimary = function () { + var constraintName = this.formatter.wrap(this.tableNameRaw + '_pkey'); + this.pushQuery('alter table ' + this.tableName() + " drop constraint " + constraintName); + }; + TableCompiler_PG.prototype.dropIndex = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('drop index ' + indexName); + }; + TableCompiler_PG.prototype.dropUnique = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); + }; + TableCompiler_PG.prototype.dropForeign = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns); + this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); + }; + + module.exports = TableCompiler_PG; /***/ }, -/* 98 */ +/* 81 */ /***/ function(module, exports, __webpack_require__) { - - // Oracle Schema Compiler + // PostgreSQL Schema Compiler // ------- + 'use strict'; - var inherits = __webpack_require__(47); - var SchemaCompiler = __webpack_require__(20); - var utils = __webpack_require__(103); + var inherits = __webpack_require__(51); + var SchemaCompiler = __webpack_require__(22); - function SchemaCompiler_Oracle() { + function SchemaCompiler_PG() { SchemaCompiler.apply(this, arguments); } - inherits(SchemaCompiler_Oracle, SchemaCompiler); + inherits(SchemaCompiler_PG, SchemaCompiler); - // Rename a table on the schema. - SchemaCompiler_Oracle.prototype.renameTable = function (tableName, to) { - this.pushQuery('rename ' + this.formatter.wrap(tableName) + ' to ' + this.formatter.wrap(to)); - }; + // Check whether the current table + SchemaCompiler_PG.prototype.hasTable = function (tableName) { + var sql = 'select * from information_schema.tables where table_name = ?'; + var bindings = [tableName]; + + if (this.schema) { + sql += ' and table_schema = ?'; + bindings.push(this.schema); + } else { + sql += ' and table_schema = current_schema'; + } - // Check whether a table exists on the query. - SchemaCompiler_Oracle.prototype.hasTable = function (tableName) { this.pushQuery({ - sql: 'select TABLE_NAME from USER_TABLES where TABLE_NAME = ' + this.formatter.parameter(tableName), + sql: sql, + bindings: bindings, output: function output(resp) { - return resp.length > 0; + return resp.rows.length > 0; } }); }; - // Check whether a column exists on the schema. - SchemaCompiler_Oracle.prototype.hasColumn = function (tableName, column) { + // Compile the query to determine if a column exists in a table. + SchemaCompiler_PG.prototype.hasColumn = function (tableName, columnName) { + var sql = 'select * from information_schema.columns where table_name = ? and column_name = ?'; + var bindings = [tableName, columnName]; + + if (this.schema) { + sql += ' and table_schema = ?'; + bindings.push(this.schema); + } else { + sql += ' and table_schema = current_schema'; + } + this.pushQuery({ - sql: 'select COLUMN_NAME from USER_TAB_COLUMNS where TABLE_NAME = ' + this.formatter.parameter(tableName) + ' and COLUMN_NAME = ' + this.formatter.parameter(column), + sql: sql, + bindings: bindings, output: function output(resp) { - return resp.length > 0; + return resp.rows.length > 0; } }); }; - SchemaCompiler_Oracle.prototype.dropSequenceIfExists = function (sequenceName) { - this.pushQuery(utils.wrapSqlWithCatch("drop sequence " + this.formatter.wrap(sequenceName), -2289)); + SchemaCompiler_PG.prototype.qualifiedTableName = function (tableName) { + var name = this.schema ? this.schema + '.' + tableName : tableName; + return this.formatter.wrap(name); }; - SchemaCompiler_Oracle.prototype._dropRelatedSequenceIfExists = function (tableName) { - // removing the sequence that was possibly generated by increments() column - var sequenceName = utils.generateCombinedName('seq', tableName); - this.dropSequenceIfExists(sequenceName); + // Compile a rename table command. + SchemaCompiler_PG.prototype.renameTable = function (from, to) { + this.pushQuery('alter table ' + this.qualifiedTableName(from) + ' rename to ' + this.qualifiedTableName(to)); }; - SchemaCompiler_Oracle.prototype.dropTable = function (tableName) { - this.pushQuery('drop table ' + this.formatter.wrap(tableName)); - - // removing the sequence that was possibly generated by increments() column - this._dropRelatedSequenceIfExists(tableName); + SchemaCompiler_PG.prototype.createSchema = function (schemaName) { + this.pushQuery('create schema ' + this.formatter.wrap(schemaName)); }; - SchemaCompiler_Oracle.prototype.dropTableIfExists = function (tableName) { - this.pushQuery(utils.wrapSqlWithCatch("drop table " + this.formatter.wrap(tableName), -942)); - - // removing the sequence that was possibly generated by increments() column - this._dropRelatedSequenceIfExists(tableName); + SchemaCompiler_PG.prototype.createSchemaIfNotExists = function (schemaName) { + this.pushQuery('create schema if not exists ' + this.formatter.wrap(schemaName)); }; - module.exports = SchemaCompiler_Oracle; + SchemaCompiler_PG.prototype.dropSchema = function (schemaName) { + this.pushQuery('drop schema ' + this.formatter.wrap(schemaName)); + }; -/***/ }, -/* 99 */ -/***/ function(module, exports, __webpack_require__) { + SchemaCompiler_PG.prototype.dropSchemaIfExists = function (schemaName) { + this.pushQuery('drop schema if exists ' + this.formatter.wrap(schemaName)); + }; - 'use strict'; + SchemaCompiler_PG.prototype.dropExtension = function (extensionName) { + this.pushQuery('drop extension ' + this.formatter.wrap(extensionName)); + }; - var inherits = __webpack_require__(47); - var ColumnBuilder = __webpack_require__(23); - var _ = __webpack_require__(11); + SchemaCompiler_PG.prototype.dropExtensionIfExists = function (extensionName) { + this.pushQuery('drop extension if exists ' + this.formatter.wrap(extensionName)); + }; - function ColumnBuilder_Oracle() { - ColumnBuilder.apply(this, arguments); - } - inherits(ColumnBuilder_Oracle, ColumnBuilder); + SchemaCompiler_PG.prototype.createExtension = function (extensionName) { + this.pushQuery('create extension ' + this.formatter.wrap(extensionName)); + }; - // checkIn added to the builder to allow the column compiler to change the - // order via the modifiers ("check" must be after "default") - ColumnBuilder_Oracle.prototype.checkIn = function () { - this._modifiers.checkIn = _.toArray(arguments); - return this; + SchemaCompiler_PG.prototype.createExtensionIfNotExists = function (extensionName) { + this.pushQuery('create extension if not exists ' + this.formatter.wrap(extensionName)); }; - module.exports = ColumnBuilder_Oracle; + module.exports = SchemaCompiler_PG; /***/ }, -/* 100 */ +/* 82 */ /***/ function(module, exports, __webpack_require__) { + + // SQLite3 Query Builder & Compiler + 'use strict'; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var assign = __webpack_require__(29); - var utils = __webpack_require__(103); - var Raw = __webpack_require__(1); - var ColumnCompiler = __webpack_require__(24); + var _lodash = __webpack_require__(1); - // Column Compiler - // ------- + var inherits = __webpack_require__(51); + var QueryCompiler = __webpack_require__(20); - function ColumnCompiler_Oracle() { - this.modifiers = ['defaultTo', 'checkIn', 'nullable', 'comment']; - ColumnCompiler.apply(this, arguments); + function QueryCompiler_SQLite3(client, builder) { + QueryCompiler.call(this, client, builder); } - inherits(ColumnCompiler_Oracle, ColumnCompiler); + inherits(QueryCompiler_SQLite3, QueryCompiler); - assign(ColumnCompiler_Oracle.prototype, { + (0, _lodash.assign)(QueryCompiler_SQLite3.prototype, { - // helper function for pushAdditional in increments() and bigincrements() - _createAutoIncrementTriggerAndSequence: function _createAutoIncrementTriggerAndSequence() { - // TODO Add warning that sequence etc is created - this.pushAdditional(function () { - var sequenceName = this.tableCompiler._indexCommand('seq', this.tableCompiler.tableNameRaw); - var triggerName = this.tableCompiler._indexCommand('trg', this.tableCompiler.tableNameRaw, this.getColumnName()); - var tableName = this.tableCompiler.tableName(); - var columnName = this.formatter.wrap(this.getColumnName()); - var createTriggerSQL = 'create or replace trigger ' + triggerName + ' before insert on ' + tableName + ' for each row' + ' when (new.' + columnName + ' is null) ' + ' begin' + ' select ' + sequenceName + '.nextval into :new.' + columnName + ' from dual;' + ' end;'; - this.pushQuery(utils.wrapSqlWithCatch('create sequence ' + sequenceName, -955)); - this.pushQuery(createTriggerSQL); - }); - }, + // The locks are not applicable in SQLite3 + forShare: emptyStr, - increments: function increments() { - this._createAutoIncrementTriggerAndSequence(); - return 'integer not null primary key'; - }, + forUpdate: emptyStr, - bigincrements: function bigincrements() { - this._createAutoIncrementTriggerAndSequence(); - return 'number(20, 0) not null primary key'; - }, + // SQLite requires us to build the multi-row insert as a listing of select with + // unions joining them together. So we'll build out this list of columns and + // then join them all together with select unions to complete the queries. + insert: function insert() { + var insertValues = this.single.insert || []; + var sql = 'insert into ' + this.tableName + ' '; - floating: function floating(precision) { - var parsedPrecision = this._num(precision, 0); - return 'float' + (parsedPrecision ? '(' + parsedPrecision + ')' : ''); - }, + if (Array.isArray(insertValues)) { + if (insertValues.length === 0) { + return ''; + } else if (insertValues.length === 1 && insertValues[0] && (0, _lodash.isEmpty)(insertValues[0])) { + return sql + this._emptyInsertValue; + } + } else if (typeof insertValues === 'object' && (0, _lodash.isEmpty)(insertValues)) { + return sql + this._emptyInsertValue; + } - double: function double(precision, scale) { - // if (!precision) return 'number'; // TODO: Check If default is ok - return 'number(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; - }, + var insertData = this._prepInsert(insertValues); - integer: function integer(length) { - return length ? 'number(' + this._num(length, 11) + ')' : 'integer'; - }, + if ((0, _lodash.isString)(insertData)) { + return sql + insertData; + } - tinyint: 'smallint', + if (insertData.columns.length === 0) { + return ''; + } - smallint: 'smallint', + sql += '(' + this.formatter.columnize(insertData.columns) + ')'; - mediumint: 'integer', + if (insertData.values.length === 1) { + return sql + ' values (' + this.formatter.parameterize(insertData.values[0]) + ')'; + } - biginteger: 'number(20, 0)', + var blocks = []; + var i = -1; + while (++i < insertData.values.length) { + var i2 = -1, + block = blocks[i] = []; + var current = insertData.values[i]; + while (++i2 < insertData.columns.length) { + block.push(this.formatter.alias(this.formatter.parameter(current[i2]), this.formatter.wrap(insertData.columns[i2]))); + } + blocks[i] = block.join(', '); + } + return sql + ' select ' + blocks.join(' union all select '); + }, - text: 'clob', + // Compile a truncate table statement into SQL. + truncate: function truncate() { + var table = this.tableName; + return { + sql: 'delete from ' + table, + output: function output() { + return this.query({ sql: 'delete from sqlite_sequence where name = ' + table })['catch'](function () {}); + } + }; + }, - enu: function enu(allowed) { - allowed = _.uniq(allowed); - var maxLength = (allowed || []).reduce(function (maxLength, name) { - return Math.max(maxLength, String(name).length); - }, 1); + // Compiles a `columnInfo` query + columnInfo: function columnInfo() { + var column = this.single.columnInfo; + return { + sql: 'PRAGMA table_info(' + this.single.table + ')', + output: function output(resp) { + var maxLengthRegex = /.*\((\d+)\)/; + var out = (0, _lodash.reduce)(resp, function (columns, val) { + var type = val.type; + var maxLength = (maxLength = type.match(maxLengthRegex)) && maxLength[1]; + type = maxLength ? type.split('(')[0] : type; + columns[val.name] = { + type: type.toLowerCase(), + maxLength: maxLength, + nullable: !val.notnull, + defaultValue: val.dflt_value + }; + return columns; + }, {}); + return column && out[column] || out; + } + }; + }, - // implicitly add the enum values as checked values - this.columnBuilder._modifiers.checkIn = [allowed]; + limit: function limit() { + var noLimit = !this.single.limit && this.single.limit !== 0; + if (noLimit && !this.single.offset) return ''; - return "varchar2(" + maxLength + ")"; - }, + // Workaround for offset only, + // see http://stackoverflow.com/questions/10491492/sqllite-with-skip-offset-only-not-limit + return 'limit ' + this.formatter.parameter(noLimit ? -1 : this.single.limit); + } - time: 'timestamp with time zone', + }); - datetime: function datetime(without) { - return without ? 'timestamp' : 'timestamp with time zone'; - }, + function emptyStr() { + return ''; + } - timestamp: function timestamp(without) { - return without ? 'timestamp' : 'timestamp with time zone'; - }, + module.exports = QueryCompiler_SQLite3; - bit: 'clob', +/***/ }, +/* 83 */ +/***/ function(module, exports, __webpack_require__) { - json: 'clob', + + // SQLite3: Column Builder & Compiler + // ------- + 'use strict'; - bool: function bool() { - // implicitly add the check for 0 and 1 - this.columnBuilder._modifiers.checkIn = [[0, 1]]; - return 'number(1, 0)'; - }, + var _lodash = __webpack_require__(1); - varchar: function varchar(length) { - return 'varchar2(' + this._num(length, 255) + ')'; - }, + // Schema Compiler + // ------- - // Modifiers - // ------ + var inherits = __webpack_require__(51); + var SchemaCompiler = __webpack_require__(22); - comment: function comment(_comment) { - this.pushAdditional(function () { - this.pushQuery('comment on column ' + this.tableCompiler.tableName() + '.' + this.formatter.wrap(this.args[0]) + " is '" + (_comment || '') + "'"); - }, _comment); - }, + function SchemaCompiler_SQLite3() { + SchemaCompiler.apply(this, arguments); + } + inherits(SchemaCompiler_SQLite3, SchemaCompiler); - checkIn: function checkIn(value) { - // TODO: Maybe accept arguments also as array - // TODO: value(s) should be escaped properly - if (value === undefined) { - return ''; - } else if (value instanceof Raw) { - value = value.toQuery(); - } else if (Array.isArray(value)) { - value = _.map(value, function (v) { - return "'" + v + "'"; - }).join(', '); - } else { - value = "'" + value + "'"; + // Compile the query to determine if a table exists. + SchemaCompiler_SQLite3.prototype.hasTable = function (tableName) { + this.pushQuery({ + sql: "select * from sqlite_master where type = 'table' and name = " + this.formatter.parameter(tableName), + output: function output(resp) { + return resp.length > 0; } - return 'check (' + this.formatter.wrap(this.args[0]) + ' in (' + value + '))'; - } + }); + }; - }); + // Compile the query to determine if a column exists. + SchemaCompiler_SQLite3.prototype.hasColumn = function (tableName, column) { + this.pushQuery({ + sql: 'PRAGMA table_info(' + this.formatter.wrap(tableName) + ')', + output: function output(resp) { + return (0, _lodash.some)(resp, { name: column }); + } + }); + }; - module.exports = ColumnCompiler_Oracle; + // Compile a rename table command. + SchemaCompiler_SQLite3.prototype.renameTable = function (from, to) { + this.pushQuery('alter table ' + this.formatter.wrap(from) + ' rename to ' + this.formatter.wrap(to)); + }; + + module.exports = SchemaCompiler_SQLite3; /***/ }, -/* 101 */ +/* 84 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var inherits = __webpack_require__(47); - var utils = __webpack_require__(103); - var TableCompiler = __webpack_require__(22); - var helpers = __webpack_require__(2); - var assign = __webpack_require__(29); + var inherits = __webpack_require__(51); + var ColumnCompiler = __webpack_require__(26); - // Table Compiler - // ------ + // Column Compiler + // ------- - function TableCompiler_Oracle() { - TableCompiler.apply(this, arguments); + function ColumnCompiler_SQLite3() { + this.modifiers = ['nullable', 'defaultTo']; + ColumnCompiler.apply(this, arguments); } - inherits(TableCompiler_Oracle, TableCompiler); + inherits(ColumnCompiler_SQLite3, ColumnCompiler); - assign(TableCompiler_Oracle.prototype, { + // Types + // ------- - // Compile a rename column command. - renameColumn: function renameColumn(from, to) { - return this.pushQuery({ - sql: 'alter table ' + this.tableName() + ' rename column ' + this.formatter.wrap(from) + ' to ' + this.formatter.wrap(to) - }); - }, + ColumnCompiler_SQLite3.prototype.double = ColumnCompiler_SQLite3.prototype.decimal = ColumnCompiler_SQLite3.prototype.floating = 'float'; + ColumnCompiler_SQLite3.prototype.timestamp = 'datetime'; - compileAdd: function compileAdd(builder) { - var table = this.formatter.wrap(builder); - var columns = this.prefixArray('add column', this.getColumns(builder)); - return this.pushQuery({ - sql: 'alter table ' + table + ' ' + columns.join(', ') - }); - }, + module.exports = ColumnCompiler_SQLite3; - // Adds the "create" query to the query sequence. - createQuery: function createQuery(columns, ifNot) { - var sql = 'create table ' + this.tableName() + ' (' + columns.sql.join(', ') + ')'; - this.pushQuery({ - // catch "name is already used by an existing object" for workaround for "if not exists" - sql: ifNot ? utils.wrapSqlWithCatch(sql, -955) : sql, - bindings: columns.bindings - }); - if (this.single.comment) this.comment(this.single.comment); - }, +/***/ }, +/* 85 */ +/***/ function(module, exports, __webpack_require__) { - // Compiles the comment on the table. - comment: function comment(_comment) { - this.pushQuery('comment on table ' + this.tableName() + ' is ' + "'" + (_comment || '') + "'"); - }, + 'use strict'; - addColumnsPrefix: 'add ', + var _lodash = __webpack_require__(1); - dropColumn: function dropColumn() { - var columns = helpers.normalizeArr.apply(null, arguments); - this.pushQuery('alter table ' + this.tableName() + ' drop (' + this.formatter.columnize(columns) + ')'); - }, + // Table Compiler + // ------- - changeType: function changeType() { - // alter table + table + ' modify ' + wrapped + '// type'; - }, - - _indexCommand: function _indexCommand(type, tableName, columns) { - return this.formatter.wrap(utils.generateCombinedName(type, tableName, columns)); - }, + var inherits = __webpack_require__(51); + var TableCompiler = __webpack_require__(24); - primary: function primary(columns) { - this.pushQuery('alter table ' + this.tableName() + " add primary key (" + this.formatter.columnize(columns) + ")"); - }, + function TableCompiler_SQLite3() { + TableCompiler.apply(this, arguments); + this.primaryKey = void 0; + } + inherits(TableCompiler_SQLite3, TableCompiler); - dropPrimary: function dropPrimary() { - this.pushQuery('alter table ' + this.tableName() + ' drop primary key'); - }, + // Create a new table. + TableCompiler_SQLite3.prototype.createQuery = function (columns, ifNot) { + var createStatement = ifNot ? 'create table if not exists ' : 'create table '; + var sql = createStatement + this.tableName() + ' (' + columns.sql.join(', '); - index: function index(columns, indexName) { - indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('create index ' + indexName + ' on ' + this.tableName() + ' (' + this.formatter.columnize(columns) + ')'); - }, + // SQLite forces primary keys to be added when the table is initially created + // so we will need to check for a primary key commands and add the columns + // to the table's declaration here so they can be created on the tables. + sql += this.foreignKeys() || ''; + sql += this.primaryKeys() || ''; + sql += ')'; - dropIndex: function dropIndex(columns, indexName) { - indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('drop index ' + indexName); - }, + this.pushQuery(sql); + }; - unique: function unique(columns, indexName) { - indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' add constraint ' + indexName + ' unique (' + this.formatter.columnize(columns) + ')'); - }, + TableCompiler_SQLite3.prototype.addColumns = function (columns) { + for (var i = 0, l = columns.sql.length; i < l; i++) { + this.pushQuery({ + sql: 'alter table ' + this.tableName() + ' add column ' + columns.sql[i], + bindings: columns.bindings[i] + }); + } + }; - dropUnique: function dropUnique(columns, indexName) { - indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); - }, + // Compile a drop unique key command. + TableCompiler_SQLite3.prototype.dropUnique = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + this.pushQuery('drop index ' + indexName); + }; - dropForeign: function dropForeign(columns, indexName) { - indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('foreign', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); - } + TableCompiler_SQLite3.prototype.dropIndex = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + this.pushQuery('drop index ' + indexName); + }; - }); + // Compile a unique key command. + TableCompiler_SQLite3.prototype.unique = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('unique', this.tableNameRaw, columns); + columns = this.formatter.columnize(columns); + this.pushQuery('create unique index ' + indexName + ' on ' + this.tableName() + ' (' + columns + ')'); + }; - module.exports = TableCompiler_Oracle; + // Compile a plain index key command. + TableCompiler_SQLite3.prototype.index = function (columns, indexName) { + indexName = indexName ? this.formatter.wrap(indexName) : this._indexCommand('index', this.tableNameRaw, columns); + columns = this.formatter.columnize(columns); + this.pushQuery('create index ' + indexName + ' on ' + this.tableName() + ' (' + columns + ')'); + }; -/***/ }, -/* 102 */ -/***/ function(module, exports, __webpack_require__) { + TableCompiler_SQLite3.prototype.primary = TableCompiler_SQLite3.prototype.foreign = function () { + if (this.method !== 'create' && this.method !== 'createIfNot') { + console.warn('SQLite3 Foreign & Primary keys may only be added on create'); + } + }; - /* WEBPACK VAR INJECTION */(function(process) { - /*jslint node:true, nomen: true*/ - 'use strict'; + TableCompiler_SQLite3.prototype.primaryKeys = function () { + var pks = (0, _lodash.filter)(this.grouped.alterTable || [], { method: 'primary' }); + if (pks.length > 0 && pks[0].args.length > 0) { + var args = Array.isArray(pks[0].args[0]) ? pks[0].args[0] : pks[0].args; + return ', primary key (' + this.formatter.columnize(args) + ')'; + } + }; - var inherits = __webpack_require__(47); - var merge = __webpack_require__(144); - var Readable = __webpack_require__(148).Readable; + TableCompiler_SQLite3.prototype.foreignKeys = function () { + var sql = ''; + var foreignKeys = (0, _lodash.filter)(this.grouped.alterTable || [], { method: 'foreign' }); + for (var i = 0, l = foreignKeys.length; i < l; i++) { + var foreign = foreignKeys[i].args[0]; + var column = this.formatter.columnize(foreign.column); + var references = this.formatter.columnize(foreign.references); + var foreignTable = this.formatter.wrap(foreign.inTable); + sql += ', foreign key(' + column + ') references ' + foreignTable + '(' + references + ')'; + if (foreign.onDelete) sql += ' on delete ' + foreign.onDelete; + if (foreign.onUpdate) sql += ' on update ' + foreign.onUpdate; + } + return sql; + }; - function OracleQueryStream(connection, sql, bindings, options) { - Readable.call(this, merge({}, { - objectMode: true, - highWaterMark: 1000 - }, options)); - this.oracleReader = connection.reader(sql, bindings || []); - } - inherits(OracleQueryStream, Readable); + TableCompiler_SQLite3.prototype.createTableBlock = function () { + return this.getColumns().concat().join(','); + }; - OracleQueryStream.prototype._read = function () { - var _this = this; + // Compile a rename column command... very complex in sqlite + TableCompiler_SQLite3.prototype.renameColumn = function (from, to) { + var compiler = this; + this.pushQuery({ + sql: 'PRAGMA table_info(' + this.tableName() + ')', + output: function output(pragma) { + return compiler.client.ddl(compiler, pragma, this.connection).renameColumn(from, to); + } + }); + }; - var pushNull = function pushNull() { - process.nextTick(function () { - _this.push(null); - }); - }; - try { - this.oracleReader.nextRows(function (err, rows) { - if (err) return _this.emit('error', err); - if (rows.length === 0) { - pushNull(); - } else { - for (var i = 0; i < rows.length; i++) { - if (rows[i]) { - _this.push(rows[i]); - } else { - pushNull(); - } - } - } - }); - } catch (e) { - // Catch Error: invalid state: reader is busy with another nextRows call - // and return false to rate limit stream. - if (e.message === 'invalid state: reader is busy with another nextRows call') { - return false; - } else { - this.emit('error', e); + TableCompiler_SQLite3.prototype.dropColumn = function (column) { + var compiler = this; + this.pushQuery({ + sql: 'PRAGMA table_info(' + this.tableName() + ')', + output: function output(pragma) { + return compiler.client.ddl(compiler, pragma, this.connection).dropColumn(column); } - } + }); }; - module.exports = OracleQueryStream; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) + module.exports = TableCompiler_SQLite3; /***/ }, -/* 103 */ +/* 86 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + + // SQLite3_DDL + // + // All of the SQLite3 specific DDL helpers for renaming/dropping + // columns and changing datatypes. + // ------- - var helpers = __webpack_require__(2); + 'use strict'; - function generateCombinedName(postfix, name, subNames) { - var crypto = __webpack_require__(149); - var limit = 30; - if (!Array.isArray(subNames)) subNames = subNames ? [subNames] : []; - var table = name.replace(/\.|-/g, '_'); - var subNamesPart = subNames.join('_'); - var result = (table + '_' + (subNamesPart.length ? subNamesPart + '_' : '') + postfix).toLowerCase(); - if (result.length > limit) { - helpers.warn('Automatically generated name "' + result + '" exceeds ' + limit + ' character limit for Oracle. Using base64 encoded sha1 of that name instead.'); - // generates the sha1 of the name and encode it with base64 - result = crypto.createHash('sha1').update(result).digest('base64').replace('=', ''); - } - return result; - } + var _lodash = __webpack_require__(1); - function wrapSqlWithCatch(sql, errorNumberToCatch) { - return "begin execute immediate '" + sql.replace(/'/g, "''") + "'; exception when others then if sqlcode != " + errorNumberToCatch + " then raise; end if; end;"; + // So altering the schema in SQLite3 is a major pain. + // We have our own object to deal with the renaming and altering the types + // for sqlite3 things. + var Promise = __webpack_require__(9); + function SQLite3_DDL(client, tableCompiler, pragma, connection) { + this.client = client; + this.tableCompiler = tableCompiler; + this.pragma = pragma; + this.tableName = this.tableCompiler.tableNameRaw; + this.alteredName = (0, _lodash.uniqueId)('_knex_temp_alter'); + this.connection = connection; } - function ReturningHelper(columnName) { - this.columnName = columnName; - } + (0, _lodash.assign)(SQLite3_DDL.prototype, { - ReturningHelper.prototype.toString = function () { - return '[object ReturningHelper:' + this.columnName + ']'; - }; + getColumn: Promise.method(function (column) { + var currentCol = (0, _lodash.find)(this.pragma, { name: column }); + if (!currentCol) throw new Error('The column ' + column + ' is not in the ' + this.tableName + ' table'); + return currentCol; + }), - module.exports = { - generateCombinedName: generateCombinedName, - wrapSqlWithCatch: wrapSqlWithCatch, - ReturningHelper: ReturningHelper - }; + getTableSql: function getTableSql() { + return this.trx.raw('SELECT name, sql FROM sqlite_master WHERE type="table" AND name="' + this.tableName + '"'); + }, -/***/ }, -/* 104 */ -/***/ function(module, exports, __webpack_require__) { + renameTable: Promise.method(function () { + return this.trx.raw('ALTER TABLE "' + this.tableName + '" RENAME TO "' + this.alteredName + '"'); + }), - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + dropOriginal: function dropOriginal() { + return this.trx.raw('DROP TABLE "' + this.tableName + '"'); + }, - function dateToString(date) { - function pad(number, digits) { - number = number.toString(); - while (number.length < digits) { - number = "0" + number; - } - return number; - } + dropTempTable: function dropTempTable() { + return this.trx.raw('DROP TABLE "' + this.alteredName + '"'); + }, - var offset = -date.getTimezoneOffset(); - var ret = pad(date.getFullYear(), 4) + '-' + pad(date.getMonth() + 1, 2) + '-' + pad(date.getDate(), 2) + 'T' + pad(date.getHours(), 2) + ':' + pad(date.getMinutes(), 2) + ':' + pad(date.getSeconds(), 2) + '.' + pad(date.getMilliseconds(), 3); + copyData: function copyData() { + return this.trx.raw('SELECT * FROM "' + this.tableName + '"').bind(this).then(this.insertChunked(20, this.alteredName)); + }, - if (offset < 0) { - ret += "-"; - offset *= -1; - } else { - ret += "+"; - } + reinsertData: function reinsertData(iterator) { + return function () { + return this.trx.raw('SELECT * FROM "' + this.alteredName + '"').bind(this).then(this.insertChunked(20, this.tableName, iterator)); + }; + }, - return ret + pad(Math.floor(offset / 60), 2) + ":" + pad(offset % 60, 2); - } - - var prepareObject; - var arrayString; + insertChunked: function insertChunked(amount, target, iterator) { + iterator = iterator || function (noop) { + return noop; + }; + return function (result) { + var batch = []; + var ddl = this; + return Promise.reduce(result, function (memo, row) { + memo++; + batch.push(row); + if (memo % 20 === 0 || memo === result.length) { + return ddl.trx.queryBuilder().table(target).insert((0, _lodash.map)(batch, iterator)).then(function () { + batch = []; + }).thenReturn(memo); + } + return memo; + }, 0); + }; + }, - // converts values from javascript types - // to their 'raw' counterparts for use as a postgres parameter - // note: you can override this function to provide your own conversion mechanism - // for complex types, etc... - var prepareValue = function prepareValue(val, seen, valueForUndefined) { - if (val instanceof Buffer) { - return val; - } - if (val instanceof Date) { - return dateToString(val); - } - if (Array.isArray(val)) { - return arrayString(val); - } - if (val === null) { - return null; - } - if (val === undefined) { - return valueForUndefined; - } - if (typeof val === 'object') { - return prepareObject(val, seen); - } - return val.toString(); - }; + createTempTable: function createTempTable(createTable) { + return function () { + return this.trx.raw(createTable.sql.replace(this.tableName, this.alteredName)); + }; + }, - prepareObject = function prepareObject(val, seen) { - if (val && typeof val.toPostgres === 'function') { - seen = seen || []; - if (seen.indexOf(val) !== -1) { - throw new Error('circular reference detected while preparing "' + val + '" for query'); - } - seen.push(val); + _doReplace: function _doReplace(sql, from, to) { + var matched = sql.match(/^CREATE TABLE (\S+) \((.*)\)/); - return prepareValue(val.toPostgres(prepareValue), seen); - } - return JSON.stringify(val); - }; + var tableName = matched[1], + defs = matched[2]; - // convert a JS array to a postgres array literal - // uses comma separator so won't work for types like box that use - // a different array separator. - arrayString = function arrayString(val) { - return '{' + val.map(function (elem) { - if (elem === null || elem === undefined) { - return 'NULL'; - } - if (Array.isArray(elem)) { - return arrayString(elem); + if (!defs) { + throw new Error('No column definitions in this statement!'); } - return JSON.stringify(prepareValue(elem)); - }).join(',') + '}'; - }; - function normalizeQueryConfig(config, values, callback) { - //can take in strings or config objects - config = typeof config === 'string' ? { text: config } : config; - if (values) { - if (typeof values === 'function') { - config.callback = values; - } else { - config.values = values; + var parens = 0, + args = [], + ptr = 0; + for (var i = 0, x = defs.length; i < x; i++) { + switch (defs[i]) { + case '(': + parens++; + break; + case ')': + parens--; + break; + case ',': + if (parens === 0) { + args.push(defs.slice(ptr, i)); + ptr = i + 1; + } + break; + case ' ': + if (ptr === i) { + ptr = i + 1; + } + break; + } } - } - if (callback) { - config.callback = callback; - } - return config; - } - - module.exports = { - prepareValue: prepareValue, - normalizeQueryConfig: normalizeQueryConfig - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + args.push(defs.slice(ptr, i)); -/***/ }, -/* 105 */ -/***/ function(module, exports, __webpack_require__) { + args = args.map(function (item) { + var split = item.split(' '); - - // PostgreSQL Query Builder & Compiler - // ------ - 'use strict'; + if (split[0] === from) { + // column definition + if (to) { + split[0] = to; + return split.join(' '); + } + return ''; // for deletions + } - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); + // skip constraint name + var idx = /constraint/i.test(split[0]) ? 2 : 0; - var QueryCompiler = __webpack_require__(18); - var assign = __webpack_require__(29); + // primary key and unique constraints have one or more + // columns from this table listed between (); replace + // one if it matches + if (/primary|unique/i.test(split[idx])) { + return item.replace(/\(.*\)/, function (columns) { + return columns.replace(from, to); + }); + } - function QueryCompiler_PG(client, builder) { - QueryCompiler.call(this, client, builder); - } - inherits(QueryCompiler_PG, QueryCompiler); + // foreign keys have one or more columns from this table + // listed between (); replace one if it matches + // foreign keys also have a 'references' clause + // which may reference THIS table; if it does, replace + // column references in that too! + if (/foreign/.test(split[idx])) { + split = item.split(/ references /i); + // the quoted column names save us from having to do anything + // other than a straight replace here + split[0] = split[0].replace(from, to); - assign(QueryCompiler_PG.prototype, { + if (split[1].slice(0, tableName.length) === tableName) { + split[1] = split[1].replace(/\(.*\)/, function (columns) { + return columns.replace(from, to); + }); + } + return split.join(' references '); + } - // Compiles a truncate query. - truncate: function truncate() { - return 'truncate ' + this.tableName + ' restart identity'; + return item; + }); + return sql.replace(/\(.*\)/, function () { + return '(' + args.join(', ') + ')'; + }).replace(/,\s*([,)])/, '$1'); }, - // is used if the an array with multiple empty values supplied - _defaultInsertValue: 'default', + // Boy, this is quite a method. + renameColumn: Promise.method(function (from, to) { + var currentCol; - // Compiles an `insert` query, allowing for multiple - // inserts using a single query statement. - insert: function insert() { - var sql = QueryCompiler.prototype.insert.call(this); - if (sql === '') return sql; - var returning = this.single.returning; - return { - sql: sql + this._returning(returning), - returning: returning - }; - }, + return this.client.transaction((function (trx) { + this.trx = trx; + return this.getColumn(from).bind(this).tap(function (col) { + currentCol = col; + }).then(this.getTableSql).then(function (sql) { + var a = this.client.wrapIdentifier(from); + var b = this.client.wrapIdentifier(to); + var createTable = sql[0]; + var newSql = this._doReplace(createTable.sql, a, b); + if (sql === newSql) { + throw new Error('Unable to find the column to change'); + } + return Promise.bind(this).then(this.createTempTable(createTable)).then(this.copyData).then(this.dropOriginal).then(function () { + return this.trx.raw(newSql); + }).then(this.reinsertData(function (row) { + row[to] = row[from]; + return (0, _lodash.omit)(row, from); + })).then(this.dropTempTable); + }); + }).bind(this), { connection: this.connection }); + }), - // Compiles an `update` query, allowing for a return value. - update: function update() { - var updateData = this._prepUpdate(this.single.update); - var wheres = this.where(); - var returning = this.single.returning; - return { - sql: 'update ' + this.tableName + ' set ' + updateData.join(', ') + (wheres ? ' ' + wheres : '') + this._returning(returning), - returning: returning - }; - }, + dropColumn: Promise.method(function (column) { + var currentCol; - // Compiles an `update` query, allowing for a return value. - del: function del() { - var sql = QueryCompiler.prototype.del.apply(this, arguments); - var returning = this.single.returning; - return { - sql: sql + this._returning(returning), - returning: returning - }; - }, - - _returning: function _returning(value) { - return value ? ' returning ' + this.formatter.columnize(value) : ''; - }, - - forUpdate: function forUpdate() { - return 'for update'; - }, - - forShare: function forShare() { - return 'for share'; - }, - - // Compiles a columnInfo query - columnInfo: function columnInfo() { - var column = this.single.columnInfo; - - var sql = 'select * from information_schema.columns where table_name = ? and table_catalog = ?'; - var bindings = [this.single.table, this.client.database()]; - - if (this.single.schema) { - sql += ' and table_schema = ?'; - bindings.push(this.single.schema); - } else { - sql += ' and table_schema = current_schema'; - } - - return { - sql: sql, - bindings: bindings, - output: function output(resp) { - var out = _.reduce(resp.rows, function (columns, val) { - columns[val.column_name] = { - type: val.data_type, - maxLength: val.character_maximum_length, - nullable: val.is_nullable === 'YES', - defaultValue: val.column_default - }; - return columns; - }, {}); - return column && out[column] || out; - } - }; - } + return this.client.transaction((function (trx) { + this.trx = trx; + return this.getColumn(column).tap(function (col) { + currentCol = col; + }).bind(this).then(this.getTableSql).then(function (sql) { + var createTable = sql[0]; + var a = this.client.wrapIdentifier(column); + var newSql = this._doReplace(createTable.sql, a, ''); + if (sql === newSql) { + throw new Error('Unable to find the column to change'); + } + return Promise.bind(this).then(this.createTempTable(createTable)).then(this.copyData).then(this.dropOriginal).then(function () { + return this.trx.raw(newSql); + }).then(this.reinsertData(function (row) { + return (0, _lodash.omit)(row, column); + })).then(this.dropTempTable); + }); + }).bind(this), { connection: this.connection }); + }) }); - module.exports = QueryCompiler_PG; + module.exports = SQLite3_DDL; /***/ }, -/* 106 */ +/* 87 */ /***/ function(module, exports, __webpack_require__) { - - // PostgreSQL Column Compiler - // ------- + // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 + // + // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! + // + // Originally from narwhal.js (http://narwhaljs.org) + // Copyright (c) 2009 Thomas Robinson <280north.com> + // + // 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 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'; + // when used in node, this will actually load the util module we depend on + // versus loading the builtin util module as happens otherwise + // this is a bug in node module loading as far as I am concerned + var util = __webpack_require__(105); - var inherits = __webpack_require__(47); - var ColumnCompiler = __webpack_require__(24); - var assign = __webpack_require__(29); - var helpers = __webpack_require__(2); + var pSlice = Array.prototype.slice; + var hasOwn = Object.prototype.hasOwnProperty; - function ColumnCompiler_PG() { - ColumnCompiler.apply(this, arguments); - this.modifiers = ['nullable', 'defaultTo', 'comment']; - } - inherits(ColumnCompiler_PG, ColumnCompiler); + // 1. The assert module provides functions that throw + // AssertionError's when particular conditions are not met. The + // assert module must conform to the following interface. - assign(ColumnCompiler_PG.prototype, { + var assert = module.exports = ok; - // Types - // ------ - bigincrements: 'bigserial primary key', - bigint: 'bigint', - binary: 'bytea', + // 2. The AssertionError is defined in assert. + // new assert.AssertionError({ message: message, + // actual: actual, + // expected: expected }) - bit: function bit(column) { - return column.length !== false ? 'bit(' + column.length + ')' : 'bit'; - }, + assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; - bool: 'boolean', + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; - // Create the column definition for an enum type. - // Using method "2" here: http://stackoverflow.com/a/10984951/525714 - enu: function enu(allowed) { - return 'text check (' + this.formatter.wrap(this.args[0]) + " in ('" + allowed.join("', '") + "'))"; - }, + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } - double: 'double precision', - floating: 'real', - increments: 'serial primary key', - json: function json(jsonb) { - if (jsonb) helpers.deprecate('json(true)', 'jsonb()'); - return jsonColumn(this.client, jsonb); - }, - jsonb: function jsonb() { - return jsonColumn(this.client, true); - }, - smallint: 'smallint', - tinyint: 'smallint', - datetime: function datetime(without) { - return without ? 'timestamp' : 'timestamptz'; - }, - timestamp: function timestamp(without) { - return without ? 'timestamp' : 'timestamptz'; - }, - uuid: 'uuid', + this.stack = out; + } + } + }; - // Modifiers: - // ------ - comment: function comment(_comment) { - this.pushAdditional(function () { - this.pushQuery('comment on column ' + this.tableCompiler.tableName() + '.' + this.formatter.wrap(this.args[0]) + " is " + (_comment ? "'" + _comment + "'" : 'NULL')); - }, _comment); + // assert.AssertionError instanceof Error + util.inherits(assert.AssertionError, Error); + + function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && !isFinite(value)) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); } + return value; + } - }); + function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } + } - function jsonColumn(client, jsonb) { - if (!client.version || parseFloat(client.version) >= 9.2) return jsonb ? 'jsonb' : 'json'; - return 'text'; + function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); } - module.exports = ColumnCompiler_PG; + // At present only the three keys mentioned above are used and + // understood by the spec. Implementations or sub modules can pass + // other keys to the AssertionError's constructor - they will be + // ignored. -/***/ }, -/* 107 */ -/***/ function(module, exports, __webpack_require__) { + // 3. All of the following functions must throw an AssertionError + // when a corresponding condition is not met, with a message that + // may be undefined if not provided. All assertion methods provide + // both the actual and expected values to the assertion error for + // display purposes. - // PostgreSQL Table Builder & Compiler - // ------- + function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); + } - 'use strict'; + // EXTENSION! allows for well behaved errors defined elsewhere. + assert.fail = fail; - var _ = __webpack_require__(11); - var inherits = __webpack_require__(47); - var TableCompiler = __webpack_require__(22); + // 4. Pure assertion tests whether a value is truthy, as determined + // by !!guard. + // assert.ok(guard, message_opt); + // This statement is equivalent to assert.equal(true, !!guard, + // message_opt);. To test strictly for the value true, use + // assert.strictEqual(true, guard, message_opt);. - function TableCompiler_PG() { - TableCompiler.apply(this, arguments); + function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); } - inherits(TableCompiler_PG, TableCompiler); + assert.ok = ok; - // Compile a rename column command. - TableCompiler_PG.prototype.renameColumn = function (from, to) { - return this.pushQuery({ - sql: 'alter table ' + this.tableName() + ' rename ' + this.formatter.wrap(from) + ' to ' + this.formatter.wrap(to) - }); + // 5. The equality assertion tests shallow, coercive equality with + // ==. + // assert.equal(actual, expected, message_opt); + + assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; - TableCompiler_PG.prototype.compileAdd = function (builder) { - var table = this.formatter.wrap(builder); - var columns = this.prefixArray('add column', this.getColumns(builder)); - return this.pushQuery({ - sql: 'alter table ' + table + ' ' + columns.join(', ') - }); + // 6. The non-equality assertion tests for whether two objects are not equal + // with != assert.notEqual(actual, expected, message_opt); + + assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } }; - // Adds the "create" query to the query sequence. - TableCompiler_PG.prototype.createQuery = function (columns, ifNot) { - var createStatement = ifNot ? 'create table if not exists ' : 'create table '; - this.pushQuery({ - sql: createStatement + this.tableName() + ' (' + columns.sql.join(', ') + ')', - bindings: columns.bindings - }); - var hasComment = _.has(this.single, 'comment'); - if (hasComment) this.comment(this.single.comment); - }; + // 7. The equivalence assertion tests a deep equality relation. + // assert.deepEqual(actual, expected, message_opt); - // Compiles the comment on the table. - TableCompiler_PG.prototype.comment = function (comment) { - /*jshint unused: false*/ - this.pushQuery('comment on table ' + this.tableName() + ' is ' + "'" + (this.single.comment || '') + "'"); + assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } }; - // Indexes: - // ------- + function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; - TableCompiler_PG.prototype.primary = function (columns) { - this.pushQuery('alter table ' + this.tableName() + " add primary key (" + this.formatter.columnize(columns) + ")"); - }; - TableCompiler_PG.prototype.unique = function (columns, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' add constraint ' + indexName + ' unique (' + this.formatter.columnize(columns) + ')'); - }; - TableCompiler_PG.prototype.index = function (columns, indexName, indexType) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('create index ' + indexName + ' on ' + this.tableName() + (indexType && ' using ' + indexType || '') + ' (' + this.formatter.columnize(columns) + ')'); - }; - TableCompiler_PG.prototype.dropPrimary = function () { - var constraintName = this.formatter.wrap(this.tableNameRaw + '_pkey'); - this.pushQuery('alter table ' + this.tableName() + " drop constraint " + constraintName); - }; - TableCompiler_PG.prototype.dropIndex = function (columns, indexName) { - indexName = indexName || this._indexCommand('index', this.tableNameRaw, columns); - this.pushQuery('drop index ' + indexName); - }; - TableCompiler_PG.prototype.dropUnique = function (columns, indexName) { - indexName = indexName || this._indexCommand('unique', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); - }; - TableCompiler_PG.prototype.dropForeign = function (columns, indexName) { - indexName = indexName || this._indexCommand('foreign', this.tableNameRaw, columns); - this.pushQuery('alter table ' + this.tableName() + ' drop constraint ' + indexName); - }; + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; - module.exports = TableCompiler_PG; + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } -/***/ }, -/* 108 */ -/***/ function(module, exports, __webpack_require__) { + return true; - // PostgreSQL Schema Compiler - // ------- + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); - 'use strict'; + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; - var inherits = __webpack_require__(47); - var SchemaCompiler = __webpack_require__(20); + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; - function SchemaCompiler_PG() { - SchemaCompiler.apply(this, arguments); + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } } - inherits(SchemaCompiler_PG, SchemaCompiler); - // Check whether the current table - SchemaCompiler_PG.prototype.hasTable = function (tableName) { - var sql = 'select * from information_schema.tables where table_name = ?'; - var bindings = [tableName]; + function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; + } - if (this.schema) { - sql += ' and table_schema = ?'; - bindings.push(this.schema); - } else { - sql += ' and table_schema = current_schema'; + function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) { + return a === b; + } + var aIsArgs = isArguments(a), + bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + var ka = objectKeys(a), + kb = objectKeys(b), + key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; } + return true; + } - this.pushQuery({ - sql: sql, - bindings: bindings, - output: function output(resp) { - return resp.rows.length > 0; - } - }); + // 8. The non-equivalence assertion tests for any deep inequality. + // assert.notDeepEqual(actual, expected, message_opt); + + assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } }; - // Compile the query to determine if a column exists in a table. - SchemaCompiler_PG.prototype.hasColumn = function (tableName, columnName) { - var sql = 'select * from information_schema.columns where table_name = ? and column_name = ?'; - var bindings = [tableName, columnName]; + // 9. The strict equality assertion tests strict equality, as determined by ===. + // assert.strictEqual(actual, expected, message_opt); - if (this.schema) { - sql += ' and table_schema = ?'; - bindings.push(this.schema); - } else { - sql += ' and table_schema = current_schema'; + assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); } - - this.pushQuery({ - sql: sql, - bindings: bindings, - output: function output(resp) { - return resp.rows.length > 0; - } - }); }; - SchemaCompiler_PG.prototype.qualifiedTableName = function (tableName) { - var name = this.schema ? this.schema + '.' + tableName : tableName; - return this.formatter.wrap(name); - }; + // 10. The strict non-equality assertion tests for strict inequality, as + // determined by !==. assert.notStrictEqual(actual, expected, message_opt); - // Compile a rename table command. - SchemaCompiler_PG.prototype.renameTable = function (from, to) { - this.pushQuery('alter table ' + this.qualifiedTableName(from) + ' rename to ' + this.qualifiedTableName(to)); + assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } }; - SchemaCompiler_PG.prototype.createSchema = function (schemaName) { - this.pushQuery('create schema ' + this.formatter.wrap(schemaName)); - }; + function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } - SchemaCompiler_PG.prototype.createSchemaIfNotExists = function (schemaName) { - this.pushQuery('create schema if not exists ' + this.formatter.wrap(schemaName)); - }; + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } - SchemaCompiler_PG.prototype.dropSchema = function (schemaName) { - this.pushQuery('drop schema ' + this.formatter.wrap(schemaName)); - }; + return false; + } - SchemaCompiler_PG.prototype.dropSchemaIfExists = function (schemaName) { - this.pushQuery('drop schema if exists ' + this.formatter.wrap(schemaName)); - }; + function _throws(shouldThrow, block, expected, message) { + var actual; - SchemaCompiler_PG.prototype.dropExtension = function (extensionName) { - this.pushQuery('drop extension ' + this.formatter.wrap(extensionName)); - }; + if (util.isString(expected)) { + message = expected; + expected = null; + } - SchemaCompiler_PG.prototype.dropExtensionIfExists = function (extensionName) { - this.pushQuery('drop extension if exists ' + this.formatter.wrap(extensionName)); - }; + try { + block(); + } catch (e) { + actual = e; + } - SchemaCompiler_PG.prototype.createExtension = function (extensionName) { - this.pushQuery('create extension ' + this.formatter.wrap(extensionName)); - }; + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); - SchemaCompiler_PG.prototype.createExtensionIfNotExists = function (extensionName) { - this.pushQuery('create extension if not exists ' + this.formatter.wrap(extensionName)); - }; + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } - module.exports = SchemaCompiler_PG; + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } -/***/ }, -/* 109 */ -/***/ function(module, exports, __webpack_require__) { + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } + } - // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 - // - // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! - // - // Originally from narwhal.js (http://narwhaljs.org) - // Copyright (c) 2009 Thomas Robinson <280north.com> - // - // 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 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. + // 11. Expected to throw an error: + // assert.throws(block, Error_opt, message_opt); - // when used in node, this will actually load the util module we depend on - // versus loading the builtin util module as happens otherwise - // this is a bug in node module loading as far as I am concerned - var util = __webpack_require__(155); + assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); + }; - var pSlice = Array.prototype.slice; - var hasOwn = Object.prototype.hasOwnProperty; + // EXTENSION! This is annoying to write outside this module. + assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); + }; - // 1. The assert module provides functions that throw - // AssertionError's when particular conditions are not met. The - // assert module must conform to the following interface. + assert.ifError = function(err) { if (err) {throw err;}}; - var assert = module.exports = ok; + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; + }; - // 2. The AssertionError is defined in assert. - // new assert.AssertionError({ message: message, - // actual: actual, - // expected: expected }) - assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; +/***/ }, +/* 88 */ +/***/ function(module, exports, __webpack_require__) { - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; + /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } + 'use strict' - this.stack = out; - } + var base64 = __webpack_require__(110) + var ieee754 = __webpack_require__(106) + var isArray = __webpack_require__(109) + + 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 } - }; + } - // assert.AssertionError instanceof Error - util.inherits(assert.AssertionError, Error); + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } - function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; + /** + * 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 (util.isNumber(value) && !isFinite(value)) { - return value.toString(); + + if (!Buffer.TYPED_ARRAY_SUPPORT) { + this.length = 0 + this.parent = undefined } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); + + // Common case. + if (typeof arg === 'number') { + return fromNumber(this, arg) } - return value; - } - function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } - } - function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); + // Unusual. + return fromObject(this, arg) } - // At present only the three keys mentioned above are used and - // understood by the spec. Implementations or sub modules can pass - // other keys to the AssertionError's constructor - they will be - // ignored. - - // 3. All of the following functions must throw an AssertionError - // when a corresponding condition is not met, with a message that - // may be undefined if not provided. All assertion methods provide - // both the actual and expected values to the assertion error for - // display purposes. - - function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); + 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 } - // EXTENSION! allows for well behaved errors defined elsewhere. - assert.fail = fail; + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' - // 4. Pure assertion tests whether a value is truthy, as determined - // by !!guard. - // assert.ok(guard, message_opt); - // This statement is equivalent to assert.equal(true, !!guard, - // message_opt);. To test strictly for the value true, use - // assert.strictEqual(true, guard, message_opt);. + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) - function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); + that.write(string, encoding) + return that } - assert.ok = ok; - // 5. The equality assertion tests shallow, coercive equality with - // ==. - // assert.equal(actual, expected, message_opt); + function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) - assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); - }; + if (isArray(object)) return fromArray(that, object) - // 6. The non-equality assertion tests for whether two objects are not equal - // with != assert.notEqual(actual, expected, message_opt); - - assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } - }; - - // 7. The equivalence assertion tests a deep equality relation. - // assert.deepEqual(actual, expected, message_opt); - - assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') } - }; - function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; + if (typeof ArrayBuffer !== 'undefined') { + if (object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) } + if (object instanceof ArrayBuffer) { + return fromArrayBuffer(that, object) + } + } - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); + if (object.length) return fromArrayLike(that, object) - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; + return fromJsonObject(that, object) + } - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; + function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that + } - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); + 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 } - function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; + // 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 objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) { - return a === b; - } - var aIsArgs = isArguments(a), - bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - var ka = objectKeys(a), - kb = objectKeys(b), - key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; + 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)) } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; + 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 true; + return that } - // 8. The non-equivalence assertion tests for any deep inequality. - // assert.notDeepEqual(actual, expected, message_opt); + // 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 - assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + if (object.type === 'Buffer' && isArray(object.data)) { + array = object.data + length = checked(array.length) | 0 } - }; - - // 9. The strict equality assertion tests strict equality, as determined by ===. - // assert.strictEqual(actual, expected, message_opt); + that = allocate(that, length) - assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } - }; + return that + } - // 10. The strict non-equality assertion tests for strict inequality, as - // determined by !==. assert.notStrictEqual(actual, expected, message_opt); + 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 + } - assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); + 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 } - }; - function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } + var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 + if (fromPool) that.parent = rootParent - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; + 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 + } - return false; + function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf } - function _throws(shouldThrow, block, expected, message) { - var actual; + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } - if (util.isString(expected)) { - message = expected; - expected = null; + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - try { - block(); - } catch (e) { - actual = e; - } + if (a === b) return 0 - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + var x = a.length + var y = b.length - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } + var i = 0 + var len = Math.min(x, y) + while (i < len) { + if (a[i] !== b[i]) break - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); + ++i } - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; + if (i !== len) { + x = a[i] + y = b[i] } + + if (x < y) return -1 + if (y < x) return 1 + return 0 } - // 11. Expected to throw an error: - // assert.throws(block, Error_opt, message_opt); + 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 + } + } - assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); - }; + Buffer.concat = function concat (list, length) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') - // EXTENSION! This is annoying to write outside this module. - assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); - }; + if (list.length === 0) { + return new Buffer(0) + } - assert.ifError = function(err) { if (err) {throw err;}}; + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length + } + } - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); + 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 keys; - }; + return buf + } + function byteLength (string, encoding) { + if (typeof string !== 'string') string = '' + string -/***/ }, -/* 110 */ -/***/ function(module, exports, __webpack_require__) { + var len = string.length + if (len === 0) return 0 - /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ + // 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 - var base64 = __webpack_require__(177) - var ieee754 = __webpack_require__(160) - var isArray = __webpack_require__(159) + function slowToString (encoding, start, end) { + var loweredCase = false - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - Buffer.poolSize = 8192 // not used by this implementation + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 - var rootParent = {} + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' - /** - * 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. + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - * 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() + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - 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 - } - } + case 'ascii': + return asciiSlice(this, start, end) - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } + case 'binary': + return binarySlice(this, start, end) - /** - * 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) - } + case 'base64': + return base64Slice(this, start, end) - this.length = 0 - this.parent = undefined + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - // Common case. - if (typeof arg === 'number') { - return fromNumber(this, arg) + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } } + } - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') - } + 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) + } - // Unusual. - return fromObject(this, arg) + 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 } - 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 - } + 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 that + return '' } - 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 + 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) } - 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') - } + Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) + 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) } - if (object.length) return fromArrayLike(that, object) + 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 + } - return fromJsonObject(that, object) + throw new TypeError('val must be string, number or Buffer') } - function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that + // `get` is deprecated + Buffer.prototype.get = function get (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) } - 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 + // `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) } - // 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 + 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 + } } - 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)) + // 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 } - return that + 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 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 + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } - // 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 + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 - } - that = allocate(that, length) + function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) } - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - 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 + 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 { - // Fallback: Return an object instance of the Buffer class - that.length = length - that._isBuffer = true + var swap = encoding + encoding = offset + offset = length | 0 + length = swap } - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent - - return that - } + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining - 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') + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') } - return length | 0 - } - function SlowBuffer (subject, encoding) { - if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + if (!encoding) encoding = 'utf8' - var buf = new Buffer(subject, encoding) - delete buf.parent - return buf - } + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + case 'ascii': + return asciiWrite(this, string, offset, length) - if (a === b) return 0 + case 'binary': + return binaryWrite(this, string, offset, length) - var x = a.length - var y = b.length + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - var i = 0 - var len = Math.min(x, y) - while (i < len) { - if (a[i] !== b[i]) break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - ++i + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } } + } - if (i !== len) { - x = a[i] - y = b[i] + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } - - 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 + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) } } - Buffer.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] - if (list.length === 0) { - return new Buffer(0) - } + 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 - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; i++) { - length += list[i].length + 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 + } + } + } } - } - 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 + 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 buf + + return decodeCodePointsArray(res) } - function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string + // 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 - var len = string.length - if (len === 0) return 0 + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - // 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 - } + // 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 } - Buffer.byteLength = byteLength - // pre-set for values that may exist in the future - Buffer.prototype.length = undefined - Buffer.prototype.parent = undefined + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - function slowToString (encoding, start, end) { - var loweredCase = false + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 + function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret + } - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) + function hexSlice (buf, start, end) { + var len = buf.length - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len - case 'ascii': - return asciiSlice(this, start, end) + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out + } - case 'binary': - return binarySlice(this, start, end) + 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 + } - case 'base64': - return base64Slice(this, start, end) + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true + 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] } } - } - 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) - } + if (newBuf.length) newBuf.parent = this.parent || this - 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 + return newBuf } - 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) + /* + * 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.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + return val + } - 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) + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) } - 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 + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul } - 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) + return val } - // `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) + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[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 + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) } - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] } - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) } - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) } - 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 + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul } + mul *= 0x80 - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + return val + } - case 'ascii': - return asciiWrite(this, string, offset, length) + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - case 'binary': - return binaryWrite(this, string, offset, length) + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + return val + } - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } + 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.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } + 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 } - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } + 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 } - 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() - } + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - // 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 + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) } - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) } - 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 + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) } - 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 + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) } - 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.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) } - 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 + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) } - /* - * 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') + 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.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) - var val = this[offset] var mul = 1 var i = 0 + this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul + this[offset + i] = (value / mul) & 0xFF } - return val + return offset + byteLength } - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) - var val = this[offset + --byteLength] + var i = byteLength - 1 var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF } - return val + return offset + byteLength } - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] + 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 } - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) + 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.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.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) { @@ -12661,7 +11852,7 @@ return /******/ (function(modules) { // webpackBootstrap } // valid surrogate pair - codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 + 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) @@ -12739,23 +11930,23 @@ return /******/ (function(modules) { // webpackBootstrap return i } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer, (function() { return this; }()))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer, (function() { return this; }()))) /***/ }, -/* 111 */ +/* 89 */ /***/ function(module, exports, __webpack_require__) { - exports = module.exports = __webpack_require__(150); - exports.Stream = __webpack_require__(148); + exports = module.exports = __webpack_require__(100); + exports.Stream = __webpack_require__(98); exports.Readable = exports; - exports.Writable = __webpack_require__(151); - exports.Duplex = __webpack_require__(152); - exports.Transform = __webpack_require__(153); - exports.PassThrough = __webpack_require__(154); + exports.Writable = __webpack_require__(101); + exports.Duplex = __webpack_require__(102); + exports.Transform = __webpack_require__(103); + exports.PassThrough = __webpack_require__(104); /***/ }, -/* 112 */ +/* 90 */ /***/ function(module, exports, __webpack_require__) { @@ -12771,7 +11962,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.disable = disable; exports.enable = enable; exports.enabled = enabled; - exports.humanize = __webpack_require__(178); + exports.humanize = __webpack_require__(111); /** * The currently active debug mode names, and names to skip. @@ -12958,33 +12149,50 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 113 */ +/* 91 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - - module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); - }; + exports.decode = exports.parse = __webpack_require__(107); + exports.encode = exports.stringify = __webpack_require__(108); /***/ }, -/* 114 */ +/* 92 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {'use strict'; + var colorConvert = __webpack_require__(113); + + function wrapAnsi16(fn, offset) { + return function () { + var code = fn.apply(colorConvert, arguments); + return '\u001b[' + (code + offset) + 'm'; + }; + } + + function wrapAnsi256(fn, offset) { + return function () { + var code = fn.apply(colorConvert, arguments); + return '\u001b[' + (38 + offset) + ';5;' + code + 'm'; + }; + } - function assembleStyles () { + function wrapAnsi16m(fn, offset) { + return function () { + var rgb = fn.apply(colorConvert, arguments); + return '\u001b[' + (38 + offset) + ';2;' + + rgb[0] + ';' + rgb[1] + ';' + rgb[2] + 'm'; + }; + } + + function assembleStyles() { var styles = { - modifiers: { + modifier: { reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], @@ -12992,7 +12200,7 @@ return /******/ (function(modules) { // webpackBootstrap hidden: [8, 28], strikethrough: [9, 29] }, - colors: { + color: { black: [30, 39], red: [31, 39], green: [32, 39], @@ -13003,7 +12211,7 @@ return /******/ (function(modules) { // webpackBootstrap white: [37, 39], gray: [90, 39] }, - bgColors: { + bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], @@ -13016,7 +12224,7 @@ return /******/ (function(modules) { // webpackBootstrap }; // fix humans - styles.colors.grey = styles.colors.gray; + styles.color.grey = styles.color.gray; Object.keys(styles).forEach(function (groupName) { var group = styles[groupName]; @@ -13036,6 +12244,48 @@ return /******/ (function(modules) { // webpackBootstrap }); }); + function rgb2rgb(r, g, b) { + return [r, g, b]; + } + + styles.color.close = '\u001b[39m'; + styles.bgColor.close = '\u001b[49m'; + + styles.color.ansi = {}; + styles.color.ansi256 = {}; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = {}; + styles.bgColor.ansi256 = {}; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (var key in colorConvert) { + if (!colorConvert.hasOwnProperty(key) || typeof colorConvert[key] !== 'object') { + continue; + } + + var suite = colorConvert[key]; + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + return styles; } @@ -13044,442 +12294,106 @@ return /******/ (function(modules) { // webpackBootstrap get: assembleStyles }); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(181)(module))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(124)(module))) /***/ }, -/* 115 */ +/* 93 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var ansiRegex = __webpack_require__(179)(); + + var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; module.exports = function (str) { - return typeof str === 'string' ? str.replace(ansiRegex, '') : str; + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); }; /***/ }, -/* 116 */ +/* 94 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; - var ansiRegex = __webpack_require__(179); - var re = new RegExp(ansiRegex().source); // remove the `g` flag - module.exports = re.test.bind(re); + var ansiRegex = __webpack_require__(114)(); + + module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; + }; /***/ }, -/* 117 */ +/* 95 */ /***/ function(module, exports, __webpack_require__) { - var isArrayLike = __webpack_require__(138), - isIndex = __webpack_require__(156), - isObject = __webpack_require__(125); - - /** - * Checks if the provided arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. - */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object)) { - var other = object[index]; - return value === value ? (value === other) : (other !== other); - } - return false; - } + /* WEBPACK VAR INJECTION */(function(process) {'use strict'; + var argv = process.argv; - module.exports = isIterateeCall; + var terminator = argv.indexOf('--'); + var hasFlag = function (flag) { + flag = '--' + flag; + var pos = argv.indexOf(flag); + return pos !== -1 && (terminator !== -1 ? pos < terminator : true); + }; + module.exports = (function () { + if ('FORCE_COLOR' in process.env) { + return true; + } -/***/ }, -/* 118 */ -/***/ function(module, exports, __webpack_require__) { - - var getNative = __webpack_require__(157), - isArrayLike = __webpack_require__(138), - isObject = __webpack_require__(125), - shimKeys = __webpack_require__(158); - - /* Native method references for those with the same name as other `lodash` methods. */ - var nativeKeys = getNative(Object, 'keys'); - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) - * for more details. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - var keys = !nativeKeys ? shimKeys : function(object) { - var Ctor = object == null ? undefined : object.constructor; - if ((typeof Ctor == 'function' && Ctor.prototype === object) || - (typeof object != 'function' && isArrayLike(object))) { - return shimKeys(object); - } - return isObject(object) ? nativeKeys(object) : []; - }; - - module.exports = keys; - - -/***/ }, -/* 119 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * A specialized version of `_.forEach` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - module.exports = arrayEach; - - -/***/ }, -/* 120 */ -/***/ function(module, exports, __webpack_require__) { - - var baseMatches = __webpack_require__(161), - baseMatchesProperty = __webpack_require__(162), - bindCallback = __webpack_require__(67), - identity = __webpack_require__(135), - property = __webpack_require__(143); - - /** - * The base implementation of `_.callback` which supports specifying the - * number of arguments to provide to `func`. - * - * @private - * @param {*} [func=_.identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {number} [argCount] The number of arguments to provide to `func`. - * @returns {Function} Returns the callback. - */ - function baseCallback(func, thisArg, argCount) { - var type = typeof func; - if (type == 'function') { - return thisArg === undefined - ? func - : bindCallback(func, thisArg, argCount); - } - if (func == null) { - return identity; - } - if (type == 'object') { - return baseMatches(func); - } - return thisArg === undefined - ? property(func) - : baseMatchesProperty(func, thisArg); - } - - module.exports = baseCallback; - - -/***/ }, -/* 121 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(125); - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(prototype) { - if (isObject(prototype)) { - object.prototype = prototype; - var result = new object; - object.prototype = undefined; - } - return result || {}; - }; - }()); - - module.exports = baseCreate; - - -/***/ }, -/* 122 */ -/***/ function(module, exports, __webpack_require__) { - - var baseFor = __webpack_require__(136), - keys = __webpack_require__(118); - - /** - * The base implementation of `_.forOwn` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return baseFor(object, iteratee, keys); - } - - module.exports = baseForOwn; - - -/***/ }, -/* 123 */ -/***/ function(module, exports, __webpack_require__) { - - var getNative = __webpack_require__(157), - isLength = __webpack_require__(163), - isObjectLike = __webpack_require__(70); - - /** `Object#toString` result references. */ - var arrayTag = '[object Array]'; - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; - - /* Native method references for those with the same name as other `lodash` methods. */ - var nativeIsArray = getNative(Array, 'isArray'); - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(function() { return arguments; }()); - * // => false - */ - var isArray = nativeIsArray || function(value) { - return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; - }; - - module.exports = isArray; - - -/***/ }, -/* 124 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(125); - - /** `Object#toString` result references. */ - var funcTag = '[object Function]'; - - /** Used for native method references. */ - var objectProto = Object.prototype; + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + return false; + } - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; + if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + return true; + } - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in older versions of Chrome and Safari which return 'function' for regexes - // and Safari 8 which returns 'object' for typed array constructors. - return isObject(value) && objToString.call(value) == funcTag; - } + if (process.stdout && !process.stdout.isTTY) { + return false; + } - module.exports = isFunction; + if (process.platform === 'win32') { + return true; + } + if ('COLORTERM' in process.env) { + return true; + } -/***/ }, -/* 125 */ -/***/ function(module, exports, __webpack_require__) { + if (process.env.TERM === 'dumb') { + return false; + } - /** - * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. - * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(1); - * // => false - */ - function isObject(value) { - // Avoid a V8 JIT bug in Chrome 19-20. - // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } - module.exports = isObject; + return false; + })(); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) /***/ }, -/* 126 */ +/* 96 */ /***/ function(module, exports, __webpack_require__) { - var isLength = __webpack_require__(163), - isObjectLike = __webpack_require__(70); - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dateTag] = typedArrayTags[errorTag] = - typedArrayTags[funcTag] = typedArrayTags[mapTag] = - typedArrayTags[numberTag] = typedArrayTags[objectTag] = - typedArrayTags[regexpTag] = typedArrayTags[setTag] = - typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - function isTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; - } - - module.exports = isTypedArray; + 'use strict'; + var ansiRegex = __webpack_require__(114); + var re = new RegExp(ansiRegex().source); // remove the `g` flag + module.exports = re.test.bind(re); /***/ }, -/* 127 */ +/* 97 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/punycode v1.3.2 by @mathias */ @@ -14011,1960 +12925,1648 @@ return /******/ (function(modules) { // webpackBootstrap }(this)); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(181)(module), (function() { return this; }()))) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(124)(module), (function() { return this; }()))) /***/ }, -/* 128 */ +/* 98 */ /***/ function(module, exports, __webpack_require__) { - 'use strict'; + // 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. - exports.decode = exports.parse = __webpack_require__(168); - exports.encode = exports.stringify = __webpack_require__(169); + module.exports = Stream; + var EE = __webpack_require__(38).EventEmitter; + var inherits = __webpack_require__(51); -/***/ }, -/* 129 */ -/***/ function(module, exports, __webpack_require__) { + inherits(Stream, EE); + Stream.Readable = __webpack_require__(89); + Stream.Writable = __webpack_require__(116); + Stream.Duplex = __webpack_require__(117); + Stream.Transform = __webpack_require__(118); + Stream.PassThrough = __webpack_require__(119); - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property names to copy. - * @param {Object} [object={}] The object to copy properties to. - * @returns {Object} Returns `object`. - */ - function baseCopy(source, props, object) { - object || (object = {}); + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; - var index = -1, - length = props.length; - while (++index < length) { - var key = props[index]; - object[key] = source[key]; - } - return object; - } - module.exports = baseCopy; + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + function Stream() { + EE.call(this); + } -/***/ }, -/* 130 */ -/***/ function(module, exports, __webpack_require__) { + Stream.prototype.pipe = function(dest, options) { + var source = this; - /** Used as the `TypeError` message for "Functions" methods. */ - var FUNC_ERROR_TEXT = 'Expected a function'; + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } - /* Native method references for those with the same name as other `lodash` methods. */ - var nativeMax = Math.max; + source.on('data', ondata); - /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as an array. - * - * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.restParam(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function restParam(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } } - start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - rest = Array(length); - - while (++index < length) { - rest[index] = args[start + index]; - } - switch (start) { - case 0: return func.call(this, rest); - case 1: return func.call(this, args[0], rest); - case 2: return func.call(this, args[0], args[1], rest); - } - var otherArgs = Array(start + 1); - index = -1; - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = rest; - return func.apply(this, otherArgs); - }; - } - - module.exports = restParam; + dest.on('drain', ondrain); -/***/ }, -/* 131 */ -/***/ function(module, exports, __webpack_require__) { + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function arrayCopy(source, array) { - var index = -1, - length = source.length; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; + dest.end(); } - return array; - } - - module.exports = arrayCopy; -/***/ }, -/* 132 */ -/***/ function(module, exports, __webpack_require__) { + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - /** Used for native method references. */ - var objectProto = Object.prototype; + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; + source.on('error', onerror); + dest.on('error', onerror); - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - // Add array properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; + dest.removeListener('close', cleanup); } - return result; - } - module.exports = initCloneArray; + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; /***/ }, -/* 133 */ +/* 99 */ /***/ function(module, exports, __webpack_require__) { - var bufferClone = __webpack_require__(164); - - /** `Object#toString` result references. */ - var boolTag = '[object Boolean]', - dateTag = '[object Date]', - numberTag = '[object Number]', - regexpTag = '[object RegExp]', - stringTag = '[object String]'; - - var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; + /* WEBPACK VAR INJECTION */(function(Buffer) {var rng = __webpack_require__(120) - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return bufferClone(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - var buffer = object.buffer; - return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - var result = new Ctor(object.source, reFlags.exec(object)); - result.lastIndex = object.lastIndex; - } - return result; + function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\n')) } - module.exports = initCloneByTag; + exports.createHash = __webpack_require__(121) + exports.createHmac = __webpack_require__(122) -/***/ }, -/* 134 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - var Ctor = object.constructor; - if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { - Ctor = Object; + exports.randomBytes = function(size, callback) { + if (callback && callback.call) { + try { + callback.call(this, undefined, new Buffer(rng(size))) + } catch (err) { callback(err) } + } else { + return new Buffer(rng(size)) } - return new Ctor; } - module.exports = initCloneObject; + function each(a, f) { + for(var i in a) + f(a[i], i) + } + exports.getHashes = function () { + return ['sha1', 'sha256', 'sha512', 'md5', 'rmd160'] + } -/***/ }, -/* 135 */ -/***/ function(module, exports, __webpack_require__) { + var p = __webpack_require__(123)(exports) + exports.pbkdf2 = p.pbkdf2 + exports.pbkdf2Sync = p.pbkdf2Sync - /** - * This method returns the first argument provided to it. - * - * @static - * @memberOf _ - * @category Utility - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'user': 'fred' }; - * - * _.identity(object) === object; - * // => true - */ - function identity(value) { - return value; - } - module.exports = identity; + // the least I can do is make error messages for the rest of the node.js/crypto api. + each(['createCredentials' + , 'createCipher' + , 'createCipheriv' + , 'createDecipher' + , 'createDecipheriv' + , 'createSign' + , 'createVerify' + , 'createDiffieHellman' + ], function (name) { + exports[name] = function () { + error('sorry,', name, 'is not implemented yet') + } + }) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 136 */ +/* 100 */ /***/ function(module, exports, __webpack_require__) { - var createBaseFor = __webpack_require__(165); + /* WEBPACK VAR INJECTION */(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. - /** - * The base implementation of `baseForIn` and `baseForOwn` which iterates - * over `object` properties returned by `keysFunc` invoking `iteratee` for - * each property. Iteratee functions may exit iteration early by explicitly - * returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); + module.exports = Readable; - module.exports = baseFor; + /**/ + var isArray = __webpack_require__(115); + /**/ -/***/ }, -/* 137 */ -/***/ function(module, exports, __webpack_require__) { + /**/ + var Buffer = __webpack_require__(88).Buffer; + /**/ - var isArguments = __webpack_require__(69), - isArray = __webpack_require__(123), - isIndex = __webpack_require__(156), - isLength = __webpack_require__(163), - isObject = __webpack_require__(125); + Readable.ReadableState = ReadableState; - /** Used for native method references. */ - var objectProto = Object.prototype; + var EE = __webpack_require__(38).EventEmitter; - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; + /**/ + if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; + }; + /**/ - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ - function keysIn(object) { - if (object == null) { - return []; - } - if (!isObject(object)) { - object = Object(object); - } - var length = object.length; - length = (length && isLength(length) && - (isArray(object) || isArguments(object)) && length) || 0; + var Stream = __webpack_require__(98); - var Ctor = object.constructor, - index = -1, - isProto = typeof Ctor == 'function' && Ctor.prototype === object, - result = Array(length), - skipIndexes = length > 0; + /**/ + var util = __webpack_require__(130); + util.inherits = __webpack_require__(51); + /**/ - while (++index < length) { - result[index] = (index + ''); - } - for (var key in object) { - if (!(skipIndexes && isIndex(key, length)) && - !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; + var StringDecoder; + + + /**/ + var debug = __webpack_require__(112); + if (debug && debug.debuglog) { + debug = debug.debuglog('stream'); + } else { + debug = function () {}; } + /**/ - module.exports = keysIn; + util.inherits(Readable, Stream); -/***/ }, -/* 138 */ -/***/ function(module, exports, __webpack_require__) { + function ReadableState(options, stream) { + var Duplex = __webpack_require__(102); - var getLength = __webpack_require__(166), - isLength = __webpack_require__(163); + options = options || {}; - /** - * Checks if `value` is array-like. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - */ - function isArrayLike(value) { - return value != null && isLength(getLength(value)); - } + // 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; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; - module.exports = isArrayLike; + // 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, because 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; -/***/ }, -/* 139 */ -/***/ function(module, exports, __webpack_require__) { - var getLength = __webpack_require__(166), - isLength = __webpack_require__(163), - toObject = __webpack_require__(167); + // 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; - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - var length = collection ? getLength(collection) : 0; - if (!isLength(length)) { - return eachFunc(collection, iteratee); - } - var index = fromRight ? length : -1, - iterable = toObject(collection); + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } + // 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'; - module.exports = createBaseEach; + // 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; -/***/ }, -/* 140 */ -/***/ function(module, exports, __webpack_require__) { + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - /** - * The base implementation of `_.reduce` and `_.reduceRight` without support - * for callback shorthands and `this` binding, which iterates over `collection` - * using the provided `eachFunc`. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initFromCollection Specify using the first or last element - * of `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initFromCollection - ? (initFromCollection = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = __webpack_require__(125).StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } } - module.exports = baseReduce; + function Readable(options) { + var Duplex = __webpack_require__(102); + if (!(this instanceof Readable)) + return new Readable(options); -/***/ }, -/* 141 */ -/***/ function(module, exports, __webpack_require__) { + this._readableState = new ReadableState(options, this); - /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - var argv = process.argv; + // legacy + this.readable = true; - var terminator = argv.indexOf('--'); - var hasFlag = function (flag) { - flag = '--' + flag; - var pos = argv.indexOf(flag); - return pos !== -1 && (terminator !== -1 ? pos < terminator : true); - }; - - module.exports = (function () { - if ('FORCE_COLOR' in process.env) { - return true; - } - - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return false; - } - - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return true; - } + Stream.call(this); + } - if (process.stdout && !process.stdout.isTTY) { - return false; - } + // 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 (process.platform === 'win32') { - return true; - } + if (util.isString(chunk) && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } - if ('COLORTERM' in process.env) { - return true; - } + return readableAddChunk(this, state, chunk, encoding, false); + }; - if (process.env.TERM === 'dumb') { - return 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); + }; - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (util.isNullOrUndefined(chunk)) { + 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); - return false; - })(); + if (!addToFront) + state.reading = false; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) + state.buffer.unshift(chunk); + else + state.buffer.push(chunk); -/***/ }, -/* 142 */ -/***/ function(module, exports, __webpack_require__) { + if (state.needReadable) + emitReadable(stream); + } - var arrayMap = __webpack_require__(170), - baseCallback = __webpack_require__(120), - baseMap = __webpack_require__(171), - isArray = __webpack_require__(123); + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - /** - * Creates an array of values by running each element in `collection` through - * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three - * arguments: (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, - * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, - * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, - * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, - * `sum`, `uniq`, and `words` - * - * @static - * @memberOf _ - * @alias collect - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new mapped array. - * @example - * - * function timesThree(n) { - * return n * 3; - * } - * - * _.map([1, 2], timesThree); - * // => [3, 6] - * - * _.map({ 'a': 1, 'b': 2 }, timesThree); - * // => [3, 6] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // using the `_.property` callback shorthand - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee, thisArg) { - var func = isArray(collection) ? arrayMap : baseMap; - iteratee = baseCallback(iteratee, thisArg, 3); - return func(collection, iteratee); + return needMoreData(state); } - module.exports = map; - - -/***/ }, -/* 143 */ -/***/ function(module, exports, __webpack_require__) { - var baseProperty = __webpack_require__(173), - basePropertyDeep = __webpack_require__(174), - isKey = __webpack_require__(175); - /** - * Creates a function that returns the property value at `path` on a - * given object. - * - * @static - * @memberOf _ - * @category Utility - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new function. - * @example - * - * var objects = [ - * { 'a': { 'b': { 'c': 2 } } }, - * { 'a': { 'b': { 'c': 1 } } } - * ]; - * - * _.map(objects, _.property('a.b.c')); - * // => [2, 1] - * - * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); - * // => [1, 2] - */ - function property(path) { - return isKey(path) ? baseProperty(path) : basePropertyDeep(path); + // 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); } - module.exports = property; - - -/***/ }, -/* 144 */ -/***/ function(module, exports, __webpack_require__) { - - var baseMerge = __webpack_require__(172), - createAssigner = __webpack_require__(65); - - /** - * Recursively merges own enumerable properties of the source object(s), that - * don't resolve to `undefined` into the destination object. Subsequent sources - * overwrite property assignments of previous sources. If `customizer` is - * provided it's invoked to produce the merged values of the destination and - * source properties. If `customizer` returns `undefined` merging is handled - * by the method instead. The `customizer` is bound to `thisArg` and invoked - * with five arguments: (objectValue, sourceValue, key, object, source). - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {Object} Returns `object`. - * @example - * - * var users = { - * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] - * }; - * - * var ages = { - * 'data': [{ 'age': 36 }, { 'age': 40 }] - * }; - * - * _.merge(users, ages); - * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } - * - * // using a customizer callback - * var object = { - * 'fruits': ['apple'], - * 'vegetables': ['beet'] - * }; - * - * var other = { - * 'fruits': ['banana'], - * 'vegetables': ['carrot'] - * }; - * - * _.merge(object, other, function(a, b) { - * if (_.isArray(a)) { - * return a.concat(b); - * } - * }); - * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } - */ - var merge = createAssigner(baseMerge); - - module.exports = merge; - - -/***/ }, -/* 145 */ -/***/ function(module, exports, __webpack_require__) { - - var arrayPush = __webpack_require__(176), - isArguments = __webpack_require__(69), - isArray = __webpack_require__(123), - isArrayLike = __webpack_require__(138), - isObjectLike = __webpack_require__(70); + // backwards compatibility. + Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = __webpack_require__(125).StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; - /** - * The base implementation of `_.flatten` with added support for restricting - * flattening and specifying the start index. - * - * @private - * @param {Array} array The array to flatten. - * @param {boolean} [isDeep] Specify a deep flatten. - * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, isDeep, isStrict, result) { - result || (result = []); - - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index]; - if (isObjectLike(value) && isArrayLike(value) && - (isStrict || isArray(value) || isArguments(value))) { - if (isDeep) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, isDeep, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } + // 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 result; + return n; } - module.exports = baseFlatten; - + function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; -/***/ }, -/* 146 */ -/***/ function(module, exports, __webpack_require__) { + if (state.objectMode) + return n === 0 ? 0 : 1; - var toObject = __webpack_require__(167); + if (isNaN(n) || util.isNull(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } - /** - * A specialized version of `_.pick` which picks `object` properties specified - * by `props`. - * - * @private - * @param {Object} object The source object. - * @param {string[]} props The property names to pick. - * @returns {Object} Returns the new object. - */ - function pickByArray(object, props) { - object = toObject(object); + if (n <= 0) + return 0; - var index = -1, - length = props.length, - result = {}; + // 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); - while (++index < length) { - var key = props[index]; - if (key in object) { - result[key] = object[key]; - } + // 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 result; - } - - module.exports = pickByArray; - -/***/ }, -/* 147 */ -/***/ function(module, exports, __webpack_require__) { + return n; + } - var baseForIn = __webpack_require__(68); + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function(n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; - /** - * A specialized version of `_.pick` which picks `object` properties `predicate` - * returns truthy for. - * - * @private - * @param {Object} object The source object. - * @param {Function} predicate The function invoked per iteration. - * @returns {Object} Returns the new object. - */ - function pickByCallback(object, predicate) { - var result = {}; - baseForIn(object, function(value, key, object) { - if (predicate(value, key, object)) { - result[key] = value; - } - }); - return result; - } + if (!util.isNumber(n) || n > 0) + state.emittedReadable = false; - module.exports = pickByCallback; + // 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)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) + endReadable(this); + else + emitReadable(this); + return null; + } + n = howMuchToRead(n, state); -/***/ }, -/* 148 */ -/***/ function(module, exports, __webpack_require__) { + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) + endReadable(this); + return null; + } - // 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. + // 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. - module.exports = Stream; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - var EE = __webpack_require__(43).EventEmitter; - var inherits = __webpack_require__(47); + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } - inherits(Stream, EE); - Stream.Readable = __webpack_require__(111); - Stream.Writable = __webpack_require__(182); - Stream.Duplex = __webpack_require__(183); - Stream.Transform = __webpack_require__(184); - Stream.PassThrough = __webpack_require__(185); + // 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; + debug('reading or ended', doRead); + } - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; + if (doRead) { + debug('do read'); + 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 pushed data 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); + var ret; + if (n > 0) + ret = fromList(n, state); + else + ret = null; - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. + if (util.isNull(ret)) { + state.needReadable = true; + n = 0; + } - function Stream() { - EE.call(this); - } + state.length -= n; - Stream.prototype.pipe = function(dest, options) { - var source = this; + // 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; - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) + endReadable(this); - source.on('data', ondata); + if (!util.isNull(ret)) + this.emit('data', ret); - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } + return er; + } - dest.on('drain', ondrain); - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); + 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; - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } - dest.end(); + // 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) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); } + } + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - if (typeof dest.destroy === 'function') dest.destroy(); + // 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); + }); } + } - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; } + state.readingMore = false; + } - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + // 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')); + }; - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; - dest.removeListener('close', cleanup); + 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; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; - - -/***/ }, -/* 149 */ -/***/ function(module, exports, __webpack_require__) { + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); - /* WEBPACK VAR INJECTION */(function(Buffer) {var rng = __webpack_require__(186) + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } - function error () { - var m = [].slice.call(arguments).join(' ') - throw new Error([ - m, - 'we accept pull requests', - 'http://github.com/dominictarr/crypto-browserify' - ].join('\n')) - } + function onend() { + debug('onend'); + dest.end(); + } - exports.createHash = __webpack_require__(187) + // 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); - exports.createHmac = __webpack_require__(188) + function cleanup() { + debug('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); + src.removeListener('data', ondata); - exports.randomBytes = function(size, callback) { - if (callback && callback.call) { - try { - callback.call(this, undefined, new Buffer(rng(size))) - } catch (err) { callback(err) } - } else { - return new Buffer(rng(size)) + // 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 (state.awaitDrain && + (!dest._writableState || dest._writableState.needDrain)) + ondrain(); } - } - function each(a, f) { - for(var i in a) - f(a[i], i) - } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + debug('false write response, pause', + src._readableState.awaitDrain); + src._readableState.awaitDrain++; + src.pause(); + } + } - exports.getHashes = function () { - return ['sha1', 'sha256', 'sha512', 'md5', 'rmd160'] - } + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('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]; - var p = __webpack_require__(189)(exports) - exports.pbkdf2 = p.pbkdf2 - exports.pbkdf2Sync = p.pbkdf2Sync - // the least I can do is make error messages for the rest of the node.js/crypto api. - each(['createCredentials' - , 'createCipher' - , 'createCipheriv' - , 'createDecipher' - , 'createDecipheriv' - , 'createSign' - , 'createVerify' - , 'createDiffieHellman' - ], function (name) { - exports[name] = function () { - error('sorry,', name, 'is not implemented yet') + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - }) + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } -/***/ }, -/* 150 */ -/***/ function(module, exports, __webpack_require__) { + // tell the dest that it's being piped to + dest.emit('pipe', src); - /* WEBPACK VAR INJECTION */(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. + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - module.exports = Readable; + return dest; + }; - /**/ - var isArray = __webpack_require__(200); - /**/ + function pipeOnDrain(src) { + return function() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } - /**/ - var Buffer = __webpack_require__(110).Buffer; - /**/ + Readable.prototype.unpipe = function(dest) { + var state = this._readableState; - Readable.ReadableState = ReadableState; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; - var EE = __webpack_require__(43).EventEmitter; + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; - /**/ - if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; - }; - /**/ + if (!dest) + dest = state.pipes; - var Stream = __webpack_require__(148); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } - /**/ - var util = __webpack_require__(204); - util.inherits = __webpack_require__(47); - /**/ + // slow case. multiple pipe destinations. - var StringDecoder; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } - /**/ - var debug = __webpack_require__(180); - if (debug && debug.debuglog) { - debug = debug.debuglog('stream'); - } else { - debug = function () {}; - } - /**/ + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; - util.inherits(Readable, Stream); + dest.emit('unpipe', this); - function ReadableState(options, stream) { - var Duplex = __webpack_require__(152); + return this; + }; - options = options || {}; + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); - // 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; - var defaultHwm = options.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = 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, because 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; - - if (stream instanceof Duplex) - this.objectMode = this.objectMode || !!options.readableObjectMode; - - // 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; + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + var self = this; + process.nextTick(function() { + debug('readable nexttick read 0'); + self.read(0); + }); + } else if (state.length) { + emitReadable(this, state); + } + } + } - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function() { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + if (!state.reading) { + debug('resume read 0'); + this.read(0); + } + resume(this, state); + } + return this; + }; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = __webpack_require__(201).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(function() { + resume_(stream, state); + }); } } - function Readable(options) { - var Duplex = __webpack_require__(152); - - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); + function resume_(stream, state) { + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) + stream.read(0); } - // 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 (util.isString(chunk) && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } + Readable.prototype.pause = function() { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); } - - return readableAddChunk(this, state, chunk, encoding, false); + return this; }; - // Unshift should *always* be something directly out of read() - Readable.prototype.unshift = function(chunk) { + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function(stream) { var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; + var paused = false; - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (util.isNullOrUndefined(chunk)) { - 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); + var self = this; + stream.on('end', function() { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } - if (!addToFront) - state.reading = false; + self.push(null); + }); - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) - state.buffer.unshift(chunk); - else - state.buffer.push(chunk); + stream.on('data', function(chunk) { + debug('wrapped data'); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !chunk.length) + return; - if (state.needReadable) - emitReadable(stream); - } + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - maybeReadMore(stream, state); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); } - } else if (!addToFront) { - state.reading = false; } - return needMoreData(state); - } + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return self; + }; - // 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 = __webpack_require__(201).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; - // 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; - } + // exposed for testing purposes only. + Readable._fromList = fromList; - function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; - if (state.objectMode) - return n === 0 ? 0 : 1; + // nothing in the list, definitely empty. + if (list.length === 0) + return null; - if (isNaN(n) || util.isNull(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); else - return state.length; - } + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); - if (n <= 0) - return 0; + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); - // 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); + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); - // 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; + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } } - return n; + return ret; } - // you can override either this method, or the async _read(n) below. - Readable.prototype.read = function(n) { - debug('read', n); - var state = this._readableState; - var nOrig = n; + function endReadable(stream) { + var state = stream._readableState; - if (!util.isNumber(n) || n > 0) - state.emittedReadable = false; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); - // 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)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) - endReadable(this); - else - emitReadable(this); - return null; + if (!state.endEmitted) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); } + } - n = howMuchToRead(n, state); + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) - endReadable(this); - return null; + function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } + return -1; + } - // 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. + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +/***/ }, +/* 101 */ +/***/ function(module, exports, __webpack_require__) { - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + /* WEBPACK VAR INJECTION */(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. - // 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; - debug('reading or ended', doRead); - } + // A bit simpler than readable streams. + // Implement an async ._write(chunk, cb), and it'll handle all + // the drain event emission and buffering. - if (doRead) { - debug('do read'); - 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; - } + module.exports = Writable; - // If _read pushed data 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); + /**/ + var Buffer = __webpack_require__(88).Buffer; + /**/ - var ret; - if (n > 0) - ret = fromList(n, state); - else - ret = null; + Writable.WritableState = WritableState; - if (util.isNull(ret)) { - state.needReadable = true; - n = 0; - } - state.length -= n; + /**/ + var util = __webpack_require__(130); + util.inherits = __webpack_require__(51); + /**/ - // 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; + var Stream = __webpack_require__(98); - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended && state.length === 0) - endReadable(this); + util.inherits(Writable, Stream); - if (!util.isNull(ret)) - this.emit('data', ret); + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + } - return ret; - }; + function WritableState(options, stream) { + var Duplex = __webpack_require__(102); - function chunkInvalid(state, chunk) { - var er = null; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; - } + options = options || {}; + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; - 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; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); - } + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; - // 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) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } - } + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); - } + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - // 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); - }); - } - } + // 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'; - function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; - } + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - // 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')); - }; + // a flag to see when we're in the middle of a write. + this.writing = false; - Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; + // when true all writes will be buffered until .uncork() call + this.corked = 0; - 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; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + // 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, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - function onend() { - debug('onend'); - dest.end(); - } + // the amount that is being written when _write is called. + this.writelen = 0; - // 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); + this.buffer = []; - function cleanup() { - debug('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); - src.removeListener('data', ondata); + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - // 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 (state.awaitDrain && - (!dest._writableState || dest._writableState.needDrain)) - ondrain(); - } + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - if (false === ret) { - debug('false write response, pause', - src._readableState.awaitDrain); - src._readableState.awaitDrain++; - src.pause(); - } - } + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('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]; + function Writable(options) { + var Duplex = __webpack_require__(102); + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + this._writableState = new WritableState(options, this); - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); + // legacy. + this.writable = true; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; - }; - - function pipeOnDrain(src) { - return function() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) - state.awaitDrain--; - if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; + Stream.call(this); } + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); + }; - Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; + function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + } - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; + } - if (!dest) - dest = state.pipes; + Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; + if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; } - // slow case. multiple pipe destinations. + if (util.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; + if (!util.isFunction(cb)) + cb = function() {}; - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); } - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; + return ret; + }; - dest.emit('unpipe', this); + Writable.prototype.cork = function() { + var state = this._writableState; - return this; + state.corked++; }; - // set up data events if they are asked for - // Ensure readable listeners eventually get something - Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); + Writable.prototype.uncork = function() { + var state = this._writableState; - // If listening to data, and it has not explicitly been paused, - // then call resume to start the flow of data on the next tick. - if (ev === 'data' && false !== this._readableState.flowing) { - this.resume(); - } + if (state.corked) { + state.corked--; - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - var self = this; - process.nextTick(function() { - debug('readable nexttick read 0'); - self.read(0); - }); - } else if (state.length) { - emitReadable(this, state); - } - } + if (!state.writing && + !state.corked && + !state.finished && + !state.bufferProcessing && + state.buffer.length) + clearBuffer(this, state); } - - return res; }; - Readable.prototype.addListener = Readable.prototype.on; - // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - Readable.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - if (!state.reading) { - debug('resume read 0'); - this.read(0); - } - resume(this, state); + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + util.isString(chunk)) { + chunk = new Buffer(chunk, encoding); } - return this; - }; + return chunk; + } - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(function() { - resume_(stream, state); - }); - } + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (util.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing || state.corked) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, false, len, chunk, encoding, cb); + + return ret; } - function resume_(stream, state) { - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; } - Readable.prototype.pause = function() { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); + function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + state.pendingcb--; + cb(er); + }); + else { + state.pendingcb--; + cb(er); } - return this; - }; - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - if (state.flowing) { - do { - var chunk = stream.read(); - } while (null !== chunk && state.flowing); - } + stream._writableState.errorEmitted = true; + stream.emit('error', er); } - // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } - var self = this; - stream.on('end', function() { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - self.push(null); - }); + onwriteStateUpdate(state); - stream.on('data', function(chunk) { - debug('wrapped data'); - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); + if (!finished && + !state.corked && + !state.bufferProcessing && + state.buffer.length) { + clearBuffer(stream, state); } - }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); } } + } - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; - }; + function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } - // exposed for testing purposes only. - Readable._fromList = fromList; + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; - // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; + if (stream._writev && state.buffer.length > 1) { + // Fast case, write everything using _writev() + var cbs = []; + for (var c = 0; c < state.buffer.length; c++) + cbs.push(state.buffer[c].callback); - // nothing in the list, definitely empty. - if (list.length === 0) - return null; + // count the one we are adding, as well. + // TODO(isaacs) clean this up + state.pendingcb++; + doWrite(stream, state, true, state.length, state.buffer, '', function(err) { + for (var i = 0; i < cbs.length; i++) { + state.pendingcb--; + cbs[i](err); + } + }); - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; + // Clear buffer + state.buffer = []; } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); + // Slow case, write chunks one-by-one + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); + doWrite(stream, state, false, len, chunk, encoding, cb); - c += cpy; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; } } + + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; } - return ret; + state.bufferProcessing = false; } - function endReadable(stream) { - var state = stream._readableState; + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); + }; - if (!state.endEmitted) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); + Writable.prototype._writev = null; + + Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (util.isFunction(chunk)) { + cb = chunk; + chunk = null; + encoding = null; + } else if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; } - } - function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + if (!util.isNullOrUndefined(chunk)) + this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); + }; + + + function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); } - function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); } - return -1; } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) - -/***/ }, -/* 151 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. + function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else + prefinish(stream, state); + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; + } + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) + +/***/ }, +/* 102 */ +/***/ function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(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 @@ -15985,470 +14587,349 @@ return /******/ (function(modules) { // webpackBootstrap // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. - // A bit simpler than readable streams. - // Implement an async ._write(chunk, cb), and it'll handle all - // the drain event emission and buffering. + // 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 = Writable; + module.exports = Duplex; /**/ - var Buffer = __webpack_require__(110).Buffer; + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; + } /**/ - Writable.WritableState = WritableState; - /**/ - var util = __webpack_require__(204); - util.inherits = __webpack_require__(47); + var util = __webpack_require__(130); + util.inherits = __webpack_require__(51); /**/ - var Stream = __webpack_require__(148); + var Readable = __webpack_require__(100); + var Writable = __webpack_require__(101); - util.inherits(Writable, Stream); + util.inherits(Duplex, Readable); - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - } + forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; + }); - function WritableState(options, stream) { - var Duplex = __webpack_require__(152); + function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); - options = options || {}; + Readable.call(this, options); + Writable.call(this, options); - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = options.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + if (options && options.readable === false) + this.readable = false; - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + if (options && options.writable === false) + this.writable = false; - if (stream instanceof Duplex) - this.objectMode = this.objectMode || !!options.writableObjectMode; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + this.once('end', onend); + } - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + // 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; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); + } - // 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'; + function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) - // a flag to see when we're in the middle of a write. - this.writing = false; +/***/ }, +/* 103 */ +/***/ function(module, exports, __webpack_require__) { - // when true all writes will be buffered until .uncork() call - this.corked = 0; + // 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 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, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; + module.exports = Transform; - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + var Duplex = __webpack_require__(102); - // the amount that is being written when _write is called. - this.writelen = 0; + /**/ + var util = __webpack_require__(130); + util.inherits = __webpack_require__(51); + /**/ - this.buffer = []; + util.inherits(Transform, Duplex); - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; } - function Writable(options) { - var Duplex = __webpack_require__(152); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - this._writableState = new WritableState(options, this); + var cb = ts.writecb; - // legacy. - this.writable = true; + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); - Stream.call(this); - } + ts.writechunk = null; + ts.writecb = null; - // Otherwise people can pipe Writable streams, which is just wrong. - Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); - }; + if (!util.isNullOrUndefined(data)) + stream.push(data); + if (cb) + cb(er); - function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - } - - // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); } - return valid; } - Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } + function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); - if (util.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; + Duplex.call(this, options); - if (!util.isFunction(cb)) - cb = function() {}; + this._transformState = new TransformState(options, this); - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } + // when the writable side finishes, then flush out anything remaining. + var stream = this; - return ret; - }; + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - Writable.prototype.cork = function() { - var state = this._writableState; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - state.corked++; - }; + this.once('prefinish', function() { + if (util.isFunction(this._flush)) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); + } - Writable.prototype.uncork = function() { - var state = this._writableState; + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; - if (state.corked) { - state.corked--; + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); + }; - if (!state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.buffer.length) - clearBuffer(this, state); + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); } }; - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - util.isString(chunk)) { - chunk = new Buffer(chunk, encoding); + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } - return chunk; - } + }; - // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (util.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - state.length += len; + function done(stream, er) { + if (er) + return stream.emit('error', er); - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; - if (state.writing || state.corked) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, false, len, chunk, encoding, cb); + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); - return ret; - } + if (ts.transforming) + throw new Error('calling transform done when still transforming'); - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) - stream._writev(chunk, state.onwrite); - else - stream._write(chunk, encoding, state.onwrite); - state.sync = false; + return stream.push(null); } - function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - state.pendingcb--; - cb(er); - }); - else { - state.pendingcb--; - cb(er); - } - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } +/***/ }, +/* 104 */ +/***/ function(module, exports, __webpack_require__) { - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } + // 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. - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. - onwriteStateUpdate(state); + module.exports = PassThrough; - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); + var Transform = __webpack_require__(103); - if (!finished && - !state.corked && - !state.bufferProcessing && - state.buffer.length) { - clearBuffer(stream, state); - } + /**/ + var util = __webpack_require__(130); + util.inherits = __webpack_require__(51); + /**/ - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } + util.inherits(PassThrough, Transform); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); } - function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } - - // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } - - - // if there's something in the buffer waiting, then process it - function clearBuffer(stream, state) { - state.bufferProcessing = true; - - if (stream._writev && state.buffer.length > 1) { - // Fast case, write everything using _writev() - var cbs = []; - for (var c = 0; c < state.buffer.length; c++) - cbs.push(state.buffer[c].callback); - - // count the one we are adding, as well. - // TODO(isaacs) clean this up - state.pendingcb++; - doWrite(stream, state, true, state.length, state.buffer, '', function(err) { - for (var i = 0; i < cbs.length; i++) { - state.pendingcb--; - cbs[i](err); - } - }); - - // Clear buffer - state.buffer = []; - } else { - // Slow case, write chunks one-by-one - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } - - state.bufferProcessing = false; - } - - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); - - }; - - Writable.prototype._writev = null; - - Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (util.isFunction(chunk)) { - cb = chunk; - chunk = null; - encoding = null; - } else if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } - - if (!util.isNullOrUndefined(chunk)) - this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); }; - function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); - } - - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } - - function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else - prefinish(stream, state); - } - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) - /***/ }, -/* 152 */ +/* 105 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. + /* WEBPACK VAR INJECTION */(function(global, 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 @@ -16469,349 +14950,669 @@ return /******/ (function(modules) { // webpackBootstrap // 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. + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } - module.exports = Duplex; + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; - /**/ - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; - } - /**/ + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } - /**/ - var util = __webpack_require__(204); - util.inherits = __webpack_require__(47); - /**/ + if (process.noDeprecation === true) { + return fn; + } - var Readable = __webpack_require__(150); - var Writable = __webpack_require__(151); + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - util.inherits(Duplex, Readable); + return deprecated; + }; - 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); + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; - Readable.call(this, options); - Writable.call(this, options); - if (options && options.readable === false) - this.readable = false; + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; - if (options && options.writable === false) - this.writable = false; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; - this.once('end', onend); - } + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; - // 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 stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; } } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) -/***/ }, -/* 153 */ -/***/ function(module, exports, __webpack_require__) { + function stylizeNoColor(str, styleType) { + return str; + } - // 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. + function arrayToHash(array) { + var hash = {}; - // a transform stream is a readable/writable stream where you do - // something with the data. Sometimes it's called a "filter", - // but that's not a great name for it, since that implies a thing where - // some bits pass through, and others are simply ignored. (That would - // be a valid example of a transform, of course.) - // - // While the output is causally related to the input, it's not a - // necessarily symmetric or synchronous transformation. For example, - // a zlib stream might take multiple plain-text writes(), and then - // emit a single compressed chunk some time in the future. - // - // Here's how this works: - // - // The Transform stream has all the aspects of the readable and writable - // stream classes. When you write(chunk), that calls _write(chunk,cb) - // internally, and returns false if there's a lot of pending writes - // buffered up. When you call read(), that calls _read(n) until - // there's enough pending readable data buffered up. - // - // In a transform stream, the written data is placed in a buffer. When - // _read(n) is called, it transforms the queued up data, calling the - // buffered _write cb's as it consumes chunks. If consuming a single - // written chunk would result in multiple output chunks, then the first - // outputted bit calls the readcb, and subsequent chunks just go into - // the read buffer, and will cause it to emit 'readable' if necessary. - // - // This way, back-pressure is actually determined by the reading side, - // since _read has to be called to start processing a new chunk. However, - // a pathological inflate type of transform can cause excessive buffering - // here. For example, imagine a stream where every byte of input is - // interpreted as an integer from 0-255, and then results in that many - // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in - // 1kb of data being output. In this case, you could write a very small - // amount of input, and end up with a very large amount of output. In - // such a pathological inflating mechanism, there'd be no way to tell - // the system to stop doing the transform. A single 4MB write could - // cause the system to run out of memory. - // - // However, even in such a pathological case, only a single written chunk - // would be consumed, and then the rest would wait (un-transformed) until - // the results of the previous transformed chunk were consumed. + array.forEach(function(val, idx) { + hash[val] = true; + }); - module.exports = Transform; + return hash; + } - var Duplex = __webpack_require__(152); - /**/ - var util = __webpack_require__(204); - util.inherits = __webpack_require__(47); - /**/ + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } - util.inherits(Transform, Duplex); + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - } + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } - var cb = ts.writecb; + var base = '', array = false, braces = ['{', '}']; - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } - ts.writechunk = null; - ts.writecb = null; + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - if (!util.isNullOrUndefined(data)) - stream.push(data); + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } - if (cb) - cb(er); + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); } - } + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } - Duplex.call(this, options); + ctx.seen.push(value); - this._transformState = new TransformState(options, this); + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } - // when the writable side finishes, then flush out anything remaining. - var stream = this; + ctx.seen.pop(); - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; + return reduceToSingleString(output, base, braces); + } - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - this.once('prefinish', function() { - if (util.isFunction(this._flush)) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); } - Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); - }; + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } - Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } } - }; + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } - // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - Transform.prototype._read = function(n) { - var ts = this._transformState; - if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } } - }; - - function done(stream, er) { - if (er) - return stream.emit('error', er); + return name + ': ' + str; + } - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - if (ts.transforming) - throw new Error('calling transform done when still transforming'); + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - return stream.push(null); + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } -/***/ }, -/* 154 */ -/***/ function(module, exports, __webpack_require__) { + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; - // 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. + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; - // a passthrough stream. - // basically just the most minimal sort of Transform stream. - // Every written chunk gets output as-is. + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; - module.exports = PassThrough; + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; - var Transform = __webpack_require__(153); + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; - /**/ - var util = __webpack_require__(204); - util.inherits = __webpack_require__(47); - /**/ + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; - util.inherits(PassThrough, Transform); + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; - function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; - Transform.call(this, options); + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; } + exports.isRegExp = isRegExp; - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(126); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(51); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; }; + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(11))) /***/ }, -/* 155 */ +/* 106 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + 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 + } + + +/***/ }, +/* 107 */ +/***/ function(module, exports, __webpack_require__) { + + // 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 @@ -16832,1018 +15633,699 @@ return /******/ (function(modules) { // webpackBootstrap // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; + '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); + } - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; + module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; } - if (process.noDeprecation === true) { - return fn; + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; } - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } - return deprecated; - }; + 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 = ''; + } - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); } else { - debugs[set] = function() {}; + obj[k] = [obj[k], v]; } } - return debugs[set]; + + return obj; }; - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; +/***/ }, +/* 108 */ +/***/ function(module, exports, __webpack_require__) { + // 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. - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; + 'use strict'; - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + case 'boolean': + return v ? 'true' : 'false'; - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + case 'number': + return isFinite(v) ? v : ''; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + default: + return ''; } - } + }; + module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } - function stylizeNoColor(str, styleType) { - return str; - } + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + } - function arrayToHash(array) { - var hash = {}; + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; - array.forEach(function(val, idx) { - hash[val] = true; - }); - return hash; - } +/***/ }, +/* 109 */ +/***/ function(module, exports, __webpack_require__) { + var toString = {}.toString; - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); +/***/ }, +/* 110 */ +/***/ function(module, exports, __webpack_require__) { - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + ;(function (exports) { + 'use strict'; - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array - var base = '', array = false, braces = ['{', '}']; + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + // 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 - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + var L = 0 - ctx.seen.push(value); + function push (v) { + arr[L++] = v + } - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } + 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) + } - ctx.seen.pop(); + 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 reduceToSingleString(output, base, braces); - } + return arr + } + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } + 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) + } - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } + // 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 + } - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } + return output + } + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 + }(false ? (this.base64js = {}) : exports)) - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); +/***/ }, +/* 111 */ +/***/ function(module, exports, __webpack_require__) { - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + /** + * Helpers. + */ - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var y = d * 365.25; + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; + module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options.long + ? long(val) + : short(val); + }; - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - function isNull(arg) { - return arg === null; + function parse(str) { + str = '' + str; + if (str.length > 10000) return; + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + } } - exports.isNull = isNull; - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - function isNumber(arg) { - return typeof arg === 'number'; + function short(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; } - exports.isNumber = isNumber; - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - function isSymbol(arg) { - return typeof arg === 'symbol'; + function long(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; } - exports.isSymbol = isSymbol; - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; + /** + * Pluralization helper. + */ - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; } - exports.isRegExp = isRegExp; - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; +/***/ }, +/* 112 */ +/***/ function(module, exports, __webpack_require__) { - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; + /* (ignored) */ - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; +/***/ }, +/* 113 */ +/***/ function(module, exports, __webpack_require__) { - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; + var conversions = __webpack_require__(128); + var route = __webpack_require__(129); - exports.isBuffer = __webpack_require__(202); + var convert = {}; - function objectToString(o) { - return Object.prototype.toString.call(o); - } + var models = Object.keys(conversions); + function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + return fn(args); + }; - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); + return wrappedFn; } + function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + var result = fn(args); - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(47); + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + return result; + }; - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); + return wrappedFn; } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(10))) + models.forEach(function (fromModel) { + convert[fromModel] = {}; -/***/ }, -/* 156 */ -/***/ function(module, exports, __webpack_require__) { - - /** Used to detect unsigned integer values. */ - var reIsUint = /^\d+$/; + var routes = route(fromModel); + var routeModels = Object.keys(routes); - /** - * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) - * of an array-like value. - */ - var MAX_SAFE_INTEGER = 9007199254740991; + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; - length = length == null ? MAX_SAFE_INTEGER : length; - return value > -1 && value % 1 == 0 && value < length; - } + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); - module.exports = isIndex; + module.exports = convert; /***/ }, -/* 157 */ +/* 114 */ /***/ function(module, exports, __webpack_require__) { - var isNative = __webpack_require__(190); - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = object == null ? undefined : object[key]; - return isNative(value) ? value : undefined; - } - - module.exports = getNative; + 'use strict'; + module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; + }; /***/ }, -/* 158 */ +/* 115 */ /***/ function(module, exports, __webpack_require__) { - var isArguments = __webpack_require__(69), - isArray = __webpack_require__(123), - isIndex = __webpack_require__(156), - isLength = __webpack_require__(163), - keysIn = __webpack_require__(137); - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * A fallback implementation of `Object.keys` which creates an array of the - * own enumerable property names of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function shimKeys(object) { - var props = keysIn(object), - propsLength = props.length, - length = propsLength && object.length; - - var allowIndexes = !!length && isLength(length) && - (isArray(object) || isArguments(object)); + module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; + }; - var index = -1, - result = []; - while (++index < propsLength) { - var key = props[index]; - if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { - result.push(key); - } - } - return result; - } +/***/ }, +/* 116 */ +/***/ function(module, exports, __webpack_require__) { - module.exports = shimKeys; + module.exports = __webpack_require__(101) /***/ }, -/* 159 */ +/* 117 */ /***/ function(module, exports, __webpack_require__) { - - /** - * isArray - */ - - var isArray = Array.isArray; + module.exports = __webpack_require__(102) - /** - * toString - */ - var str = Object.prototype.toString; - - /** - * Whether or not the given `val` - * is an array. - * - * example: - * - * isArray([]); - * // > true - * isArray(arguments); - * // > false - * isArray(''); - * // > false - * - * @param {mixed} val - * @return {bool} - */ +/***/ }, +/* 118 */ +/***/ function(module, exports, __webpack_require__) { - module.exports = isArray || function (val) { - return !! val && '[object Array]' == str.call(val); - }; + module.exports = __webpack_require__(103) /***/ }, -/* 160 */ +/* 119 */ /***/ function(module, exports, __webpack_require__) { - 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 + module.exports = __webpack_require__(104) - 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) {} +/***/ }, +/* 120 */ +/***/ function(module, exports, __webpack_require__) { - 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 + /* WEBPACK VAR INJECTION */(function(global, Buffer) {(function() { + var g = ('undefined' === typeof window ? global : window) || {} + _crypto = ( + g.crypto || g.msCrypto || __webpack_require__(127) + ) + module.exports = function(size) { + // Modern Browsers + if(_crypto.getRandomValues) { + var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array + /* This will not work in older browsers. + * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + */ + + _crypto.getRandomValues(bytes); + return bytes; + } + else if (_crypto.randomBytes) { + return _crypto.randomBytes(size) + } + else + throw new Error( + 'secure random number generation not supported by this browser\n'+ + 'use chrome, FireFox or Internet Explorer 11' + ) } - 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 + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(88).Buffer)) - value = Math.abs(value) +/***/ }, +/* 121 */ +/***/ function(module, exports, __webpack_require__) { - 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 - } + /* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(132) - 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 + var md5 = toConstructor(__webpack_require__(131)) + var rmd160 = toConstructor(__webpack_require__(135)) + + function toConstructor (fn) { + return function () { + var buffers = [] + var m= { + update: function (data, enc) { + if(!Buffer.isBuffer(data)) data = new Buffer(data, enc) + buffers.push(data) + return this + }, + digest: function (enc) { + var buf = Buffer.concat(buffers) + var r = fn(buf) + buffers = null + return enc ? r.toString(enc) : r + } } + return m } + } - 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 + module.exports = function (alg) { + if('md5' === alg) return new md5() + if('rmd160' === alg) return new rmd160() + return createHash(alg) } + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 161 */ +/* 122 */ /***/ function(module, exports, __webpack_require__) { - var baseIsMatch = __webpack_require__(191), - getMatchData = __webpack_require__(192), - toObject = __webpack_require__(167); + /* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(121) - /** - * The base implementation of `_.matches` which does not clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - var key = matchData[0][0], - value = matchData[0][1]; - - return function(object) { - if (object == null) { - return false; - } - return object[key] === value && (value !== undefined || (key in toObject(object))); - }; - } - return function(object) { - return baseIsMatch(object, matchData); - }; - } + var zeroBuffer = new Buffer(128) + zeroBuffer.fill(0) - module.exports = baseMatches; + module.exports = Hmac + function Hmac (alg, key) { + if(!(this instanceof Hmac)) return new Hmac(alg, key) + this._opad = opad + this._alg = alg -/***/ }, -/* 162 */ -/***/ function(module, exports, __webpack_require__) { + var blocksize = (alg === 'sha512') ? 128 : 64 - var baseGet = __webpack_require__(193), - baseIsEqual = __webpack_require__(194), - baseSlice = __webpack_require__(195), - isArray = __webpack_require__(123), - isKey = __webpack_require__(175), - isStrictComparable = __webpack_require__(196), - last = __webpack_require__(197), - toObject = __webpack_require__(167), - toPath = __webpack_require__(198); + key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key - /** - * The base implementation of `_.matchesProperty` which does not clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to compare. - * @returns {Function} Returns the new function. - */ - function baseMatchesProperty(path, srcValue) { - var isArr = isArray(path), - isCommon = isKey(path) && isStrictComparable(srcValue), - pathKey = (path + ''); - - path = toPath(path); - return function(object) { - if (object == null) { - return false; - } - var key = pathKey; - object = toObject(object); - if ((isArr || !isCommon) && !(key in object)) { - object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); - if (object == null) { - return false; - } - key = last(path); - object = toObject(object); - } - return object[key] === srcValue - ? (srcValue !== undefined || (key in object)) - : baseIsEqual(srcValue, object[key], undefined, true); - }; - } + if(key.length > blocksize) { + key = createHash(alg).update(key).digest() + } else if(key.length < blocksize) { + key = Buffer.concat([key, zeroBuffer], blocksize) + } - module.exports = baseMatchesProperty; + var ipad = this._ipad = new Buffer(blocksize) + var opad = this._opad = new Buffer(blocksize) + for(var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } -/***/ }, -/* 163 */ -/***/ function(module, exports, __webpack_require__) { + this._hash = createHash(alg).update(ipad) + } - /** - * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) - * of an array-like value. - */ - var MAX_SAFE_INTEGER = 9007199254740991; + Hmac.prototype.update = function (data, enc) { + this._hash.update(data, enc) + return this + } - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - */ - function isLength(value) { - return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + Hmac.prototype.digest = function (enc) { + var h = this._hash.digest() + return createHash(this._alg).update(this._opad).update(h).digest(enc) } - module.exports = isLength; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 164 */ +/* 123 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(global) {/** Native method references. */ - var ArrayBuffer = global.ArrayBuffer, - Uint8Array = global.Uint8Array; + var pbkdf2Export = __webpack_require__(133) - /** - * Creates a clone of the given array buffer. - * - * @private - * @param {ArrayBuffer} buffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function bufferClone(buffer) { - var result = new ArrayBuffer(buffer.byteLength), - view = new Uint8Array(result); + module.exports = function (crypto, exports) { + exports = exports || {} - view.set(new Uint8Array(buffer)); - return result; - } + var exported = pbkdf2Export(crypto) + + exports.pbkdf2 = exported.pbkdf2 + exports.pbkdf2Sync = exported.pbkdf2Sync - module.exports = bufferClone; + return exports + } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, -/* 165 */ +/* 124 */ /***/ function(module, exports, __webpack_require__) { - var toObject = __webpack_require__(167); - - /** - * Creates a base function for `_.forIn` or `_.forInRight`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var iterable = toObject(object), - props = keysFunc(object), - length = props.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length)) { - var key = props[index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - module.exports = createBaseFor; - - -/***/ }, -/* 166 */ -/***/ function(module, exports, __webpack_require__) { - - var baseProperty = __webpack_require__(173); - - /** - * Gets the "length" property value of `object`. - * - * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) - * that affects Safari on at least iOS 8.1-8.3 ARM64. - * - * @private - * @param {Object} object The object to query. - * @returns {*} Returns the "length" value. - */ - var getLength = baseProperty('length'); - - module.exports = getLength; - - -/***/ }, -/* 167 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(125); - - /** - * Converts `value` to an object if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Object} Returns the object. - */ - function toObject(value) { - return isObject(value) ? value : Object(value); - } - - module.exports = toObject; + module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + } /***/ }, -/* 168 */ +/* 125 */ /***/ function(module, exports, __webpack_require__) { // Copyright Joyent, Inc. and other Node contributors. @@ -17867,1473 +16349,931 @@ return /******/ (function(modules) { // webpackBootstrap // 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 Buffer = __webpack_require__(88).Buffer; - var regexp = /\+/g; - qs = qs.split(sep); + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } - 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; + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); } + } - 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 (Array.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; } - return obj; + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; }; -/***/ }, -/* 169 */ -/***/ function(module, exports, __webpack_require__) { - - // 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. + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. // - // 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'; + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; - case 'number': - return isFinite(v) ? v : ''; + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; - default: + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... return ''; - } - }; - - module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return Object.keys(obj).map(function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (Array.isArray(obj[k])) { - return obj[k].map(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)); - }; + } + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); -/***/ }, -/* 170 */ -/***/ function(module, exports, __webpack_require__) { + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - /** - * A specialized version of `_.map` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array.length, - result = Array(length); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; - while (++index < length) { - result[index] = iteratee(array[index], index, array); + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; } - return result; - } - module.exports = arrayMap; - - -/***/ }, -/* 171 */ -/***/ function(module, exports, __webpack_require__) { - - var baseEach = __webpack_require__(72), - isArrayLike = __webpack_require__(138); + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); - /** - * The base implementation of `_.map` without support for callback shorthands - * and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } - - module.exports = baseMap; - - -/***/ }, -/* 172 */ -/***/ function(module, exports, __webpack_require__) { - - var arrayEach = __webpack_require__(119), - baseMergeDeep = __webpack_require__(199), - isArray = __webpack_require__(123), - isArrayLike = __webpack_require__(138), - isObject = __webpack_require__(125), - isObjectLike = __webpack_require__(70), - isTypedArray = __webpack_require__(126), - keys = __webpack_require__(118); - - /** - * The base implementation of `_.merge` without support for argument juggling, - * multiple sources, and `this` binding `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} [customizer] The function to customize merged values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - * @returns {Object} Returns `object`. - */ - function baseMerge(object, source, customizer, stackA, stackB) { - if (!isObject(object)) { - return object; - } - var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), - props = isSrcArr ? undefined : keys(source); - - arrayEach(props || source, function(srcValue, key) { - if (props) { - key = srcValue; - srcValue = source[key]; - } - if (isObjectLike(srcValue)) { - stackA || (stackA = []); - stackB || (stackB = []); - baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); - } - else { - var value = object[key], - result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = result === undefined; - - if (isCommon) { - result = srcValue; - } - if ((result !== undefined || (isSrcArr && !(key in object))) && - (isCommon || (result === result ? (result !== value) : (value === value)))) { - object[key] = result; - } - } - }); - return object; - } - - module.exports = baseMerge; - - -/***/ }, -/* 173 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - module.exports = baseProperty; - - -/***/ }, -/* 174 */ -/***/ function(module, exports, __webpack_require__) { - - var baseGet = __webpack_require__(193), - toPath = __webpack_require__(198); - - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new function. - */ - function basePropertyDeep(path) { - var pathKey = (path + ''); - path = toPath(path); - return function(object) { - return baseGet(object, path, pathKey); - }; - } - - module.exports = basePropertyDeep; - - -/***/ }, -/* 175 */ -/***/ function(module, exports, __webpack_require__) { - - var isArray = __webpack_require__(123), - toObject = __webpack_require__(167); - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - - /** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ - function isKey(value, object) { - var type = typeof value; - if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { - return true; - } - if (isArray(value)) { - return false; - } - var result = !reIsDeepProp.test(value); - return result || (object != null && value in toObject(object)); - } - - module.exports = isKey; - - -/***/ }, -/* 176 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - module.exports = arrayPush; - - -/***/ }, -/* 177 */ -/***/ function(module, exports, __webpack_require__) { - - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - ;(function (exports) { - 'use strict'; - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) - - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS || - code === PLUS_URL_SAFE) - return 62 // '+' - if (code === SLASH || - code === SLASH_URL_SAFE) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } - - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - - if (b64.length % 4 > 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 - }(false ? (this.base64js = {}) : exports)) - - -/***/ }, -/* 178 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Helpers. - */ - - var s = 1000; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var y = d * 365.25; - - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - - module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options.long - ? long(val) - : short(val); - }; - - /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - - function parse(str) { - str = '' + str; - if (str.length > 10000) return; - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - } - } - - /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - - function short(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; - } - - /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - - function long(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; - } - - /** - * Pluralization helper. - */ - - function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; - } + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + charStr += buffer.toString(this.encoding, 0, end); -/***/ }, -/* 179 */ -/***/ function(module, exports, __webpack_require__) { + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } - 'use strict'; - module.exports = function () { - return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; + // or just emit the charStr + return charStr; }; + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; -/***/ }, -/* 180 */ -/***/ function(module, exports, __webpack_require__) { - - /* (ignored) */ - -/***/ }, -/* 181 */ -/***/ function(module, exports, __webpack_require__) { + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; - module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - module.children = []; - module.webpackPolyfill = 1; - } - return module; - } + // See http://en.wikipedia.org/wiki/UTF-8#Description + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } -/***/ }, -/* 182 */ -/***/ function(module, exports, __webpack_require__) { + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - module.exports = __webpack_require__(151) + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); -/***/ }, -/* 183 */ -/***/ function(module, exports, __webpack_require__) { + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } - module.exports = __webpack_require__(152) + return res; + }; + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } -/***/ }, -/* 184 */ -/***/ function(module, exports, __webpack_require__) { + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } - module.exports = __webpack_require__(153) + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } /***/ }, -/* 185 */ +/* 126 */ /***/ function(module, exports, __webpack_require__) { - module.exports = __webpack_require__(154) - + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } /***/ }, -/* 186 */ +/* 127 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(global, Buffer) {(function() { - var g = ('undefined' === typeof window ? global : window) || {} - _crypto = ( - g.crypto || g.msCrypto || __webpack_require__(203) - ) - module.exports = function(size) { - // Modern Browsers - if(_crypto.getRandomValues) { - var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array - /* This will not work in older browsers. - * See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - */ - - _crypto.getRandomValues(bytes); - return bytes; - } - else if (_crypto.randomBytes) { - return _crypto.randomBytes(size) - } - else - throw new Error( - 'secure random number generation not supported by this browser\n'+ - 'use chrome, FireFox or Internet Explorer 11' - ) - } - }()) - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(110).Buffer)) + /* (ignored) */ /***/ }, -/* 187 */ +/* 128 */ /***/ function(module, exports, __webpack_require__) { - /* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(209) - - var md5 = toConstructor(__webpack_require__(205)) - var rmd160 = toConstructor(__webpack_require__(211)) + /* MIT license */ + var cssKeywords = __webpack_require__(134); - function toConstructor (fn) { - return function () { - var buffers = [] - var m= { - update: function (data, enc) { - if(!Buffer.isBuffer(data)) data = new Buffer(data, enc) - buffers.push(data) - return this - }, - digest: function (enc) { - var buf = Buffer.concat(buffers) - var r = fn(buf) - buffers = null - return enc ? r.toString(enc) : r - } - } - return m - } - } + // NOTE: conversions should only return primitive values (i.e. arrays, or + // values that give correct `typeof` results). + // do not use box values types (i.e. Number(), String(), etc.) - module.exports = function (alg) { - if('md5' === alg) return new md5() - if('rmd160' === alg) return new rmd160() - return createHash(alg) + var reverseKeywords = {}; + for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key].join()] = key; + } } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) - -/***/ }, -/* 188 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {var createHash = __webpack_require__(187) - - var zeroBuffer = new Buffer(128) - zeroBuffer.fill(0) - - module.exports = Hmac + var convert = module.exports = { + rgb: {}, + hsl: {}, + hsv: {}, + hwb: {}, + cmyk: {}, + xyz: {}, + lab: {}, + lch: {}, + hex: {}, + keyword: {}, + ansi16: {}, + ansi256: {} + }; - function Hmac (alg, key) { - if(!(this instanceof Hmac)) return new Hmac(alg, key) - this._opad = opad - this._alg = alg + convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } - var blocksize = (alg === 'sha512') ? 128 : 64 + h = Math.min(h * 60, 360); - key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key + if (h < 0) { + h += 360; + } - if(key.length > blocksize) { - key = createHash(alg).update(key).digest() - } else if(key.length < blocksize) { - key = Buffer.concat([key, zeroBuffer], blocksize) - } + l = (min + max) / 2; - var ipad = this._ipad = new Buffer(blocksize) - var opad = this._opad = new Buffer(blocksize) + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } - for(var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } + return [h, s * 100, l * 100]; + }; - this._hash = createHash(alg).update(ipad) - } + convert.rgb.hsv = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var v; + + if (max === 0) { + s = 0; + } else { + s = (delta / max * 1000) / 10; + } - Hmac.prototype.update = function (data, enc) { - this._hash.update(data, enc) - return this - } + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } - Hmac.prototype.digest = function (enc) { - var h = this._hash.digest() - return createHash(this._alg).update(this._opad).update(h).digest(enc) - } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + v = ((max / 255) * 1000) / 10; -/***/ }, -/* 189 */ -/***/ function(module, exports, __webpack_require__) { + return [h, s, v]; + }; - var pbkdf2Export = __webpack_require__(210) + convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); - module.exports = function (crypto, exports) { - exports = exports || {} + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - var exported = pbkdf2Export(crypto) + return [h, w * 100, b * 100]; + }; - exports.pbkdf2 = exported.pbkdf2 - exports.pbkdf2Sync = exported.pbkdf2Sync + convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; + }; - return exports - } + convert.rgb.keyword = function (rgb) { + return reverseKeywords[rgb.join()]; + }; + convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; + }; -/***/ }, -/* 190 */ -/***/ function(module, exports, __webpack_require__) { + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; - var isFunction = __webpack_require__(124), - isObjectLike = __webpack_require__(70); + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); - /** Used to detect host constructors (Safari > 5). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - /** Used for native method references. */ - var objectProto = Object.prototype; + return [x * 100, y * 100, z * 100]; + }; - /** Used to resolve the decompiled source of functions. */ - var fnToString = Function.prototype.toString; + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; + x /= 95.047; + y /= 100; + z /= 108.883; - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - /** - * Checks if `value` is a native function. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ - function isNative(value) { - if (value == null) { - return false; - } - if (isFunction(value)) { - return reIsNative.test(fnToString.call(value)); - } - return isObjectLike(value) && reIsHostCtor.test(value); - } + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); - module.exports = isNative; + return [l, a, b]; + }; + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } -/***/ }, -/* 191 */ -/***/ function(module, exports, __webpack_require__) { + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } - var baseIsEqual = __webpack_require__(194), - toObject = __webpack_require__(167); + t1 = 2 * l - t2; - /** - * The base implementation of `_.isMatch` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} matchData The propery names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparing objects. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } - if (object == null) { - return !length; - } - object = toObject(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var result = customizer ? customizer(objValue, srcValue, key) : undefined; - if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { - return false; - } - } - } - return true; - } + rgb[i] = val * 255; + } - module.exports = baseIsMatch; + return rgb; + }; + convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var sv; + var v; + + if (l === 0) { + // no need to do calc on black + // also avoids divide by 0 error + return [0, 0, 0]; + } -/***/ }, -/* 192 */ -/***/ function(module, exports, __webpack_require__) { + l *= 2; + s *= (l <= 1) ? l : 2 - l; + v = (l + s) / 2; + sv = (2 * s) / (l + s); - var isStrictComparable = __webpack_require__(196), - pairs = __webpack_require__(206); + return [h, sv * 100, v * 100]; + }; - /** - * Gets the propery names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = pairs(object), - length = result.length; + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; - while (length--) { - result[length][2] = isStrictComparable(result[length][1]); - } - return result; - } + convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var sl; + var l; - module.exports = getMatchData; + l = (2 - s) * v; + sl = s * v; + sl /= (l <= 1) ? l : 2 - l; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; + }; -/***/ }, -/* 193 */ -/***/ function(module, exports, __webpack_require__) { + // http://dev.w3.org/csswg/css-color/#hwb-to-rgb + convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } - var toObject = __webpack_require__(167); + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; - /** - * The base implementation of `get` without support for string paths - * and default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path of the property to get. - * @param {string} [pathKey] The key representation of path. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path, pathKey) { - if (object == null) { - return; - } - if (pathKey !== undefined && pathKey in toObject(object)) { - path = [pathKey]; - } - var index = 0, - length = path.length; + if ((i & 0x01) !== 0) { + f = 1 - f; + } - while (object != null && index < length) { - object = object[path[index++]]; - } - return (index && index == length) ? object : undefined; - } + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } - module.exports = baseGet; + return [r * 255, g * 255, b * 255]; + }; + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; -/***/ }, -/* 194 */ -/***/ function(module, exports, __webpack_require__) { + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); - var baseIsEqualDeep = __webpack_require__(207), - isObject = __webpack_require__(125), - isObjectLike = __webpack_require__(70); + return [r * 255, g * 255, b * 255]; + }; - /** - * The base implementation of `_.isEqual` without support for `this` binding - * `customizer` functions. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparing values. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); - } + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; - module.exports = baseIsEqual; + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r *= 12.92; -/***/ }, -/* 195 */ -/***/ function(module, exports, __webpack_require__) { + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g *= 12.92; - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b *= 12.92; - start = start == null ? 0 : (+start || 0); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : (+end || 0); - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } + return [r * 255, g * 255, b * 255]; + }; - module.exports = baseSlice; + convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; -/***/ }, -/* 196 */ -/***/ function(module, exports, __webpack_require__) { + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - var isObject = __webpack_require__(125); + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); - /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } + return [l, a, b]; + }; - module.exports = isStrictComparable; + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + var y2; + + if (l <= 8) { + y = (l * 100) / 903.3; + y2 = (7.787 * (y / 100)) + (16 / 116); + } else { + y = 100 * Math.pow((l + 16) / 116, 3); + y2 = Math.pow(y / 100, 1 / 3); + } + x = x / 95.047 <= 0.008856 + ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 + : 95.047 * Math.pow((a / 500) + y2, 3); + z = z / 108.883 <= 0.008859 + ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 + : 108.883 * Math.pow(y2 - (b / 200), 3); -/***/ }, -/* 197 */ -/***/ function(module, exports, __webpack_require__) { + return [x, y, z]; + }; - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ - function last(array) { - var length = array ? array.length : 0; - return length ? array[length - 1] : undefined; - } + convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; - module.exports = last; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } -/***/ }, -/* 198 */ -/***/ function(module, exports, __webpack_require__) { + c = Math.sqrt(a * a + b * b); - var baseToString = __webpack_require__(74), - isArray = __webpack_require__(123); + return [l, c, h]; + }; - /** Used to match property names within property paths. */ - var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); - /** - * Converts `value` to property path array if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Array} Returns the property path array. - */ - function toPath(value) { - if (isArray(value)) { - return value; - } - var result = []; - baseToString(value).replace(rePropName, function(match, number, quote, string) { - result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - } + return [l, a, b]; + }; - module.exports = toPath; + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + value = Math.round(value / 50); -/***/ }, -/* 199 */ -/***/ function(module, exports, __webpack_require__) { + if (value === 0) { + return 30; + } - var arrayCopy = __webpack_require__(131), - isArguments = __webpack_require__(69), - isArray = __webpack_require__(123), - isArrayLike = __webpack_require__(138), - isPlainObject = __webpack_require__(31), - isTypedArray = __webpack_require__(126), - toPlainObject = __webpack_require__(208); + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize merged values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { - var length = stackA.length, - srcValue = source[key]; + if (value === 2) { + ansi += 60; + } - while (length--) { - if (stackA[length] == srcValue) { - object[key] = stackB[length]; - return; - } - } - var value = object[key], - result = customizer ? customizer(value, srcValue, key, object, source) : undefined, - isCommon = result === undefined; + return ansi; + }; - if (isCommon) { - result = srcValue; - if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { - result = isArray(value) - ? value - : (isArrayLike(value) ? arrayCopy(value) : []); - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - result = isArguments(value) - ? toPlainObject(value) - : (isPlainObject(value) ? value : {}); - } - else { - isCommon = false; - } - } - // Add the source value to the stack of traversed objects and associate - // it with its merged value. - stackA.push(srcValue); - stackB.push(result); + convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); - } else if (result === result ? (result !== value) : (value === value)) { - object[key] = result; - } - } + convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; - module.exports = baseMergeDeep; + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + if (r > 248) { + return 231; + } -/***/ }, -/* 200 */ -/***/ function(module, exports, __webpack_require__) { + return Math.round(((r - 8) / 247) * 24) + 232; + } - module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; - }; + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + return ansi; + }; -/***/ }, -/* 201 */ -/***/ function(module, exports, __webpack_require__) { + convert.ansi16.rgb = function (args) { + var color = args % 10; - // 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. + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } - var Buffer = __webpack_require__(110).Buffer; + color = color / 10.5 * 255; - var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } + return [color, color, color]; + } + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } + return [r, g, b]; + }; - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; + return [r, g, b]; + }; - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}/i); + if (!match) { + return [0, 0, 0]; + } - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + var integer = parseInt(match[0], 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + return [r, g, b]; + }; - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); +/***/ }, +/* 129 */ +/***/ function(module, exports, __webpack_require__) { - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } + var conversions = __webpack_require__(128); - charStr += buffer.toString(this.encoding, 0, end); + /* + this function routes a model to all other models. - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). - // or just emit the charStr - return charStr; - }; + conversions that are not possible simply are not included. + */ - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; + function buildGraph() { + var graph = {}; - // See http://en.wikipedia.org/wiki/UTF-8#Description + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + return graph; + } - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + // https://en.wikipedia.org/wiki/Breadth-first_search + function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; + graph[fromModel].distance = 0; - StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; - return res; - }; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); + return graph; } - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; + function link(from, to) { + return function (args) { + return to(from(args)); + }; } - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; + function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; } + module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; -/***/ }, -/* 202 */ -/***/ function(module, exports, __webpack_require__) { + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; + }; -/***/ }, -/* 203 */ -/***/ function(module, exports, __webpack_require__) { - /* (ignored) */ /***/ }, -/* 204 */ +/* 130 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. @@ -19359,8 +17299,12 @@ return /******/ (function(modules) { // webpackBootstrap // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); + + function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; @@ -19400,7 +17344,7 @@ return /******/ (function(modules) { // webpackBootstrap exports.isUndefined = isUndefined; function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; @@ -19410,13 +17354,12 @@ return /******/ (function(modules) { // webpackBootstrap exports.isObject = isObject; function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; + return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); + return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; @@ -19435,18 +17378,16 @@ return /******/ (function(modules) { // webpackBootstrap } exports.isPrimitive = isPrimitive; - function isBuffer(arg) { - return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; + exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 205 */ +/* 131 */ /***/ function(module, exports, __webpack_require__) { /* @@ -19458,7 +17399,7 @@ return /******/ (function(modules) { // webpackBootstrap * See http://pajhome.org.uk/crypt/md5 for more info. */ - var helpers = __webpack_require__(212); + var helpers = __webpack_require__(136); /* * Calculate the MD5 of an array of little-endian words, and a bit length @@ -19607,191 +17548,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 206 */ -/***/ function(module, exports, __webpack_require__) { - - var keys = __webpack_require__(118), - toObject = __webpack_require__(167); - - /** - * Creates a two dimensional array of the key-value pairs for `object`, - * e.g. `[[key1, value1], [key2, value2]]`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the new array of key-value pairs. - * @example - * - * _.pairs({ 'barney': 36, 'fred': 40 }); - * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) - */ - function pairs(object) { - object = toObject(object); - - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - var key = props[index]; - result[index] = [key, object[key]]; - } - return result; - } - - module.exports = pairs; - - -/***/ }, -/* 207 */ -/***/ function(module, exports, __webpack_require__) { - - var equalArrays = __webpack_require__(213), - equalByTag = __webpack_require__(214), - equalObjects = __webpack_require__(215), - isArray = __webpack_require__(123), - isTypedArray = __webpack_require__(126); - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - objectTag = '[object Object]'; - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objToString = objectProto.toString; - - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing objects. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA=[]] Tracks traversed `value` objects. - * @param {Array} [stackB=[]] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = arrayTag, - othTag = arrayTag; - - if (!objIsArr) { - objTag = objToString.call(object); - if (objTag == argsTag) { - objTag = objectTag; - } else if (objTag != objectTag) { - objIsArr = isTypedArray(object); - } - } - if (!othIsArr) { - othTag = objToString.call(other); - if (othTag == argsTag) { - othTag = objectTag; - } else if (othTag != objectTag) { - othIsArr = isTypedArray(other); - } - } - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && !(objIsArr || objIsObj)) { - return equalByTag(object, other, objTag); - } - if (!isLoose) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); - } - } - if (!isSameTag) { - return false; - } - // Assume cyclic values are equal. - // For more information on detecting circular references see https://es5.github.io/#JO. - stackA || (stackA = []); - stackB || (stackB = []); - - var length = stackA.length; - while (length--) { - if (stackA[length] == object) { - return stackB[length] == other; - } - } - // Add `object` and `other` to the stack of traversed objects. - stackA.push(object); - stackB.push(other); - - var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); - - stackA.pop(); - stackB.pop(); - - return result; - } - - module.exports = baseIsEqualDeep; - - -/***/ }, -/* 208 */ -/***/ function(module, exports, __webpack_require__) { - - var baseCopy = __webpack_require__(129), - keysIn = __webpack_require__(137); - - /** - * Converts `value` to a plain object flattening inherited enumerable - * properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return baseCopy(value, keysIn(value)); - } - - module.exports = toPlainObject; - - -/***/ }, -/* 209 */ +/* 132 */ /***/ function(module, exports, __webpack_require__) { var exports = module.exports = function (alg) { @@ -19800,16 +17557,16 @@ return /******/ (function(modules) { // webpackBootstrap return new Alg() } - var Buffer = __webpack_require__(110).Buffer - var Hash = __webpack_require__(216)(Buffer) + var Buffer = __webpack_require__(88).Buffer + var Hash = __webpack_require__(137)(Buffer) - exports.sha1 = __webpack_require__(217)(Buffer, Hash) - exports.sha256 = __webpack_require__(218)(Buffer, Hash) - exports.sha512 = __webpack_require__(219)(Buffer, Hash) + exports.sha1 = __webpack_require__(138)(Buffer, Hash) + exports.sha256 = __webpack_require__(139)(Buffer, Hash) + exports.sha512 = __webpack_require__(140)(Buffer, Hash) /***/ }, -/* 210 */ +/* 133 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = function(crypto) { @@ -19897,10 +17654,167 @@ return /******/ (function(modules) { // webpackBootstrap } } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) + +/***/ }, +/* 134 */ +/***/ function(module, exports, __webpack_require__) { + + module.exports = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50] + }; + + /***/ }, -/* 211 */ +/* 135 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) { @@ -20109,10 +18023,10 @@ return /******/ (function(modules) { // webpackBootstrap - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 212 */ +/* 136 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {var intSize = 4; @@ -20150,194 +18064,10 @@ return /******/ (function(modules) { // webpackBootstrap module.exports = { hash: hash }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(110).Buffer)) - -/***/ }, -/* 213 */ -/***/ function(module, exports, __webpack_require__) { - - var arraySome = __webpack_require__(220); - - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing arrays. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { - var index = -1, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isLoose && othLength > arrLength)) { - return false; - } - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index], - result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; - - if (result !== undefined) { - if (result) { - continue; - } - return false; - } - // Recursively compare arrays (susceptible to call stack limits). - if (isLoose) { - if (!arraySome(other, function(othValue) { - return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); - })) { - return false; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { - return false; - } - } - return true; - } - - module.exports = equalArrays; - - -/***/ }, -/* 214 */ -/***/ function(module, exports, __webpack_require__) { - - /** `Object#toString` result references. */ - var boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - numberTag = '[object Number]', - regexpTag = '[object RegExp]', - stringTag = '[object String]'; - - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag) { - switch (tag) { - case boolTag: - case dateTag: - // Coerce dates and booleans to numbers, dates to milliseconds and booleans - // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. - return +object == +other; - - case errorTag: - return object.name == other.name && object.message == other.message; - - case numberTag: - // Treat `NaN` vs. `NaN` as equal. - return (object != +object) - ? other != +other - : object == +other; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings primitives and string - // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. - return object == (other + ''); - } - return false; - } - - module.exports = equalByTag; - - -/***/ }, -/* 215 */ -/***/ function(module, exports, __webpack_require__) { - - var keys = __webpack_require__(118); - - /** Used for native method references. */ - var objectProto = Object.prototype; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing values. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { - var objProps = keys(object), - objLength = objProps.length, - othProps = keys(other), - othLength = othProps.length; - - if (objLength != othLength && !isLoose) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var skipCtor = isLoose; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key], - result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; - - // Recursively compare objects (susceptible to call stack limits). - if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { - return false; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (!skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - return false; - } - } - return true; - } - - module.exports = equalObjects; - + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(88).Buffer)) /***/ }, -/* 216 */ +/* 137 */ /***/ function(module, exports, __webpack_require__) { module.exports = function (Buffer) { @@ -20420,7 +18150,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 217 */ +/* 138 */ /***/ function(module, exports, __webpack_require__) { /* @@ -20432,7 +18162,7 @@ return /******/ (function(modules) { // webpackBootstrap * See http://pajhome.org.uk/crypt/md5 for details. */ - var inherits = __webpack_require__(155).inherits + var inherits = __webpack_require__(105).inherits module.exports = function (Buffer, Hash) { @@ -20564,7 +18294,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 218 */ +/* 139 */ /***/ function(module, exports, __webpack_require__) { @@ -20576,7 +18306,7 @@ return /******/ (function(modules) { // webpackBootstrap * */ - var inherits = __webpack_require__(155).inherits + var inherits = __webpack_require__(105).inherits module.exports = function (Buffer, Hash) { @@ -20717,10 +18447,10 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }, -/* 219 */ +/* 140 */ /***/ function(module, exports, __webpack_require__) { - var inherits = __webpack_require__(155).inherits + var inherits = __webpack_require__(105).inherits module.exports = function (Buffer, Hash) { var K = [ @@ -20966,35 +18696,6 @@ return /******/ (function(modules) { // webpackBootstrap } -/***/ }, -/* 220 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * A specialized version of `_.some` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - module.exports = arraySome; - - /***/ } /******/ ]) }); diff --git a/package.json b/package.json index 9712af135f..87a35a270f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "knex", - "version": "0.10.0", + "version": "0.11.0", "description": "A batteries-included SQL query & schema builder for Postgres, MySQL and SQLite3 and the Browser", "main": "knex.js", "dependencies": {