require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && pks[0].args.length > 0) { return ', primary key (' + this.formatter.columnize(pks[0].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; }; TableCompiler_SQLite3.prototype.createTableBlock = function() { return this.getColumns().concat().join(','); }; // 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(pragma) { return new compiler.SQLite3_DDL(this, compiler, pragma).renameColumn(from, to); } }); }; TableCompiler_SQLite3.prototype.dropColumn = function(column) { var compiler = this; this.pushQuery({ sql: 'PRAGMA table_info(' + this.tableName() + ')', output: function(pragma) { return new compiler.SQLite3_DDL(this, compiler, pragma).dropColumn(column); } }); }; client.TableBuilder = TableBuilder_SQLite3; client.TableCompiler = TableCompiler_SQLite3; }; },{"../../../schema":34,"inherits":43,"lodash":"K2RcUv"}],16:[function(require,module,exports){ // SQLite3 Transaction // ------- module.exports = function(client) { var inherits = require('inherits'); var Transaction = require('../../transaction'); function Transaction_SQLite3() { this.client = client; Transaction.apply(this, arguments); } inherits(Transaction_SQLite3, Transaction); client.Transaction = Transaction_SQLite3; }; },{"../../transaction":37,"inherits":43}],17:[function(require,module,exports){ // WebSQL // ------- var inherits = require('inherits'); var Client_SQLite3 = require('../sqlite3/index'); var Promise = require('../../promise'); function Client_WebSQL(config) { config = config || {}; Client_SQLite3.super_.apply(this, arguments); if (config.debug) this.isDebugging = true; this.name = config.name || 'knex_database'; this.initDriver(); this.initRunner(); } inherits(Client_WebSQL, Client_SQLite3); Client_WebSQL.prototype.dialect = 'websql', Client_WebSQL.prototype.initDriver = function() {}; Client_WebSQL.prototype.initPool = function() {}; Client_WebSQL.prototype.initMigrator = function() {}; // Initialize the query "runner" Client_WebSQL.prototype.initRunner = function() { require('./runner')(this); }; // Get a raw connection from the database, returning a promise with the connection object. Client_WebSQL.prototype.acquireConnection = function() { var client = this; return new Promise(function(resolve, reject) { try { var db = openDatabase(client.name, '1.0', client.name, 65536); db.transaction(function(t) { t.__cid = _.uniqueId('__cid'); resolve(t); }); } catch (e) { reject(e); } }); }; // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. Client_WebSQL.prototype.releaseConnection = Promise.method(function(connection) {}); module.exports = Client_WebSQL; },{"../../promise":23,"../sqlite3/index":5,"./runner":18,"inherits":43}],18:[function(require,module,exports){ // Runner // ------- module.exports = function(client) { var Promise = require('../../promise'); // Require the SQLite3 Runner. require('../sqlite3/runner')(client); var Runner_SQLite3 = client.Runner; var inherits = require('inherits'); // Inherit from the `Runner` constructor's prototype, // so we can add the correct `then` method. function Runner_WebSQL() { Runner_SQLite3.apply(this, arguments); } inherits(Runner_WebSQL, Runner_SQLite3); // Runs the query on the specified connection, providing the bindings and any other necessary prep work. Runner_WebSQL.prototype._query = Promise.method(function(obj) { if (this.isDebugging()) this.debug(obj); var connection = this.connection; return new Promise(function(resolver, rejecter) { if (!connection) { return rejecter(new Error('No connection provided.')); } connection.executeSql(obj.sql, obj.bindings, function(trx, response) { obj.response = response; return resolver(obj); }, function(trx, err) { console.error(err); rejecter(err); }); }); }); // Ensures the response is returned in the same format as other clients. Runner_WebSQL.prototype.processResponse = function(obj) { var resp = obj.response; if (obj.method === 'select') { var results = []; for (var i = 0, l = resp.rows.length; i < l; i++) { results[i] = _.clone(resp.rows.item(i)); } return results; } else if (obj.method === 'insert') { resp = [resp.insertId]; } else if (obj.method === 'delete' || obj.method === 'update') { resp = resp.rowsAffected; } return resp; }; // Assign the newly extended `Runner` constructor to the client object. client.Runner = Runner_WebSQL; }; },{"../../promise":23,"../sqlite3/runner":10,"inherits":43}],19:[function(require,module,exports){ // Mixed into the query compiler & schema pieces. Assumes a `grammar` // property exists on the current object. var _ = require('lodash'); var QueryBuilder = require('./query/builder'); var Raw = require('./raw'); var push = Array.prototype.push; // All operators used in the `where` clause generation. var operators = ['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike']; // Valid values for the `order by` clause generation. var orderBys = ['asc', 'desc']; // A "formatter" instance is used to both determine how wrap, bind, and // parameterize values within a query, keeping track of all bindings // added to the query. This allows us to easily keep track of raw statements // arbitrarily added to queries. function Formatter() { this.bindings = []; this.errors = []; } // Turns a list of values into a list of ?'s, joining them with commas unless // a "joining" value is specified (e.g. ' and ') Formatter.prototype.parameterize = function(values) { if (_.isFunction(values)) return this.parameter(values); values = _.isArray(values) ? values : [values]; return _.map(values, this.parameter, this).join(', '); }; // Checks whether a value is a function... if it is, we compile it // otherwise we check whether it's a raw Formatter.prototype.parameter = function(value) { if (_.isFunction(value)) { return '(' + this.compileCallback(value) + ')'; } return this.checkRaw(value, true) || '?'; }; Formatter.prototype.checkRaw = function(value, parameter) { if (value instanceof QueryBuilder) { var query = value.toSQL(); if (query.bindings) push.apply(this.bindings, query.bindings); return query.sql; } if (value instanceof Raw) { if (value.bindings) push.apply(this.bindings, value.bindings); return value.sql; } if (parameter) this.bindings.push(value); }; Formatter.prototype.rawOrFn = function(value, wrap) { var sql = ''; if (_.isFunction(value)) { sql = this.compileCallback(value); } else { sql = this.checkRaw(value); } return sql ? (wrap ? '(' + sql + ')' : sql) : ''; }; // Puts the appropriate wrapper around a value depending on the database // engine, unless it's a knex.raw value, in which case it's left alone. Formatter.prototype.wrap = function(val) { var raw; if (raw = this.checkRaw(val)) return raw; if (_.isNumber(val)) return val; return this._wrap(val + ''); }; // Coerce to string to prevent strange errors when it's not a string. Formatter.prototype._wrapString = function(value) { var segments, asIndex = value.toLowerCase().indexOf(' as '); if (asIndex !== -1) { var first = value.slice(0, asIndex); var second = value.slice(asIndex + 4); return this.wrap(first) + ' as ' + this.wrap(second); } var wrapped = []; segments = value.split('.'); for (var i = 0, l = segments.length; i < l; i = ++i) { value = segments[i]; if (i === 0 && segments.length > 1) { wrapped.push(this.wrap(value)); } else { wrapped.push(this.wrapValue(value)); } } return wrapped.join('.'); }; // Accepts a string or array of columns to wrap as appropriate. Formatter.prototype.columnize = function(target) { var columns = (_.isString(target) ? [target] : target); return _.map(columns, this.wrap, this).join(', '); }; // The operator method takes a value and returns something or other. Formatter.prototype.operator = function(value) { var raw; if (raw = this.checkRaw(value)) return raw; if (!_.contains(operators, value)) { this.errors.push(new Error('The operator "' + value + '" is not permitted')); } return value; }; // Specify the direction of the ordering. Formatter.prototype.direction = function(value) { var raw; if (raw = this.checkRaw(value)) return raw; return _.contains(orderBys, (value || '').toLowerCase()) ? value : 'asc'; }; // Compiles a callback using the MySQL query builder. Formatter.prototype.compileCallback = function(callback, method) { var client = this.client; // Build the callback var builder = new client.QueryBuilder(); callback.call(builder, builder); // Compile the callback, using the current formatter (to track all bindings). var compiler = new client.QueryCompiler(builder); compiler.formatter = this; // Return the compiled & parameterized sql. return compiler.toSQL(method || 'select').sql; }; module.exports = Formatter; },{"./query/builder":24,"./raw":28,"lodash":"K2RcUv"}],20:[function(require,module,exports){ // helpers.js // ------- // Just some common functions needed in multiple places within the library. var _ = require('lodash'); var helpers = { // Pick off the attributes from only the current layer of the object. skim: function(data) { return _.map(data, function(obj) { return _.pick(obj, _.keys(obj)); }); }, // Check if the first argument is an array, otherwise // uses all arguments as an array. normalizeArr: function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (_.isArray(args[0])) { return args[0]; } return args; }, // Used to signify deprecated functionality. deprecate: function(msg) { this.warn(msg); }, // Used to warn about incorrect use, without error'ing warn: function(msg) { if (typeof console !== "undefined" && console !== null && typeof console.warn === "function") { console.warn("Knex: " + msg); } }, // Sort the keys for the insert sortObject: function(obj) { return _.sortBy(_.pairs(obj), function(a) { return a[0]; }); } }; module.exports = helpers; },{"lodash":"K2RcUv"}],21:[function(require,module,exports){ module.exports = function(Target) { var _ = require('lodash'); var SqlString = require('mysql/lib/protocol/SqlString'); Target.prototype.toQuery = function(tz) { var data = this.toSQL(this._method); if (this._errors && this._errors.length > 0) throw this._errors[0]; if (!_.isArray(data)) data = [data]; return _.map(data, function(statement) { return this._formatQuery(statement.sql, statement.bindings, tz); }, this).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 SqlString.format(sql, bindings, true, tz); }; // Create a new instance of the `Runner`, passing in the current object. Target.prototype.then = function(onFulfilled, onRejected) { var Runner = this.client.Runner; return new Runner(this).run().then(onFulfilled, onRejected); }; // Add additional "options" to the builder. Typically used for client specific // items, like the `mysql` and `sqlite3` drivers. Target.prototype.options = function(opts) { this._options = this._options || []; this._options.push(opts); return this; }; // Sets an explicit "connnection" we wish to use for this query. Target.prototype.connection = function(connection) { this._connection = connection; return this; }; // Set a debug flag for the current schema query stack. Target.prototype.debug = function(val) { this._debug = (val == null ? true : val); return this; }; // Set the transaction object for this query. Target.prototype.transacting = function(t) { this._transacting = t; return this; }; // Initializes a stream. Target.prototype.stream = function(options) { var Runner = this.client.Runner; return new Runner(this).stream(options); }; // Creates a method which "coerces" to a promise, by calling a // "then" method on the current `Target` _.each(['bind', 'catch', 'spread', 'otherwise', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'nodeify', 'exec'], function(method) { Target.prototype[method] = function() { var then = this.then(); return then[method].apply(then, arguments); }; }); }; },{"lodash":"K2RcUv","mysql/lib/protocol/SqlString":44}],22:[function(require,module,exports){ // Pool // ------- var _ = require('lodash'); var GenericPool = require('generic-pool-redux').Pool; var Promise = require('./promise'); // The "Pool" object is a thin wrapper around the // "generic-pool-redux" library, exposing a `destroy` // method for explicitly draining the pool. The // `init` method is called internally and initializes // the pool if it doesn't already exist. var Pool = function(config) { this.config = _.clone(config) || {}; this.initialize(); }; // Typically only called internally, this initializes // a new `GenericPool` instance, based on the `config` // options passed into the constructor. Pool.prototype.initialize = function() { this.genericPool = this.genericPool || new GenericPool(_.defaults(this.config, _.result(this, 'defaults'))); }; // Some basic defaults for the pool... Pool.prototype.defaults = function() { var pool = this; return { min: 2, max: 10, create: function(callback) { pool.client.acquireRawConnection() .tap(function(connection) { connection.__cid = _.uniqueId('__cid'); if (pool.config.afterCreate) { return Promise.promisify(pool.config.afterCreate)(connection); } }).exec(callback); }, destroy: function(connection) { if (pool.config.beforeDestroy) { return pool.config.beforeDestroy(connection, function() { connection.end(); }); } connection.end(); } }; }; // Acquires a connection from the pool. Pool.prototype.acquire = function(callback, priority) { return this.genericPool.acquire(callback, priority); }; // Release a connection back to the connection pool. Pool.prototype.release = function(connection, callback) { return this.genericPool.release(connection, callback); }; // Tear down the pool, only necessary if you need it. Pool.prototype.destroy = function(callback) { var genericPool = this.genericPool; if (genericPool) { genericPool.drain(function() { genericPool.destroyAllNow(callback); }); this.genericPool = void 0; } else { callback(); } return this; }; module.exports = Pool; },{"./promise":23,"lodash":"K2RcUv"}],23:[function(require,module,exports){ var Promise = require('bluebird'); Promise.prototype.yield = Promise.prototype.thenReturn; Promise.prototype.ensure = Promise.prototype.lastly; Promise.prototype.otherwise = Promise.prototype.caught; Promise.prototype.exec = Promise.prototype.nodeify; module.exports = Promise; },{"bluebird":"EjIH/G"}],24:[function(require,module,exports){ // Builder // ------- var _ = require('lodash'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; var Raw = require('../raw'); var helpers = require('../helpers'); var JoinClause = require('./joinclause'); // Typically called from `knex.builder`, // start a new query building chain. function QueryBuilder() { this._single = {}; this._statements = []; this._errors = []; // Internal flags used in the builder. this._joinFlag = 'inner'; this._boolFlag = 'and'; } inherits(QueryBuilder, EventEmitter); // All operators used in the `where` clause generation. var operators = ['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '&&', '|', '^', '#', '<<', '>>', '@>', '<@', '||']; var nullOperators = ['is', 'is not']; // Valid values for the `order by` clause generation. var orderBys = ['asc', 'desc']; QueryBuilder.prototype.toString = function() { return this.toQuery(); }; // Convert the current query "toSQL" QueryBuilder.prototype.toSQL = function() { var QueryCompiler = this.client.QueryCompiler; return new QueryCompiler(this).toSQL(this._method || 'select'); }; // Create a shallow clone of the current query builder. // TODO: Test this!! QueryBuilder.prototype.clone = function() { var cloned = new this.constructor(); cloned._method = this._method; cloned._single = _.clone(this._single); cloned._options = _.clone(this._options); cloned._statements = this._statements.slice(); cloned._errors = this._errors.slice(); cloned._debug = this._debug; cloned._transacting = this._transacting; cloned._connection = this._connection; return cloned; }; // Select // ------ // Sets the values for a `select` query, // which is the same as specifying the columns. QueryBuilder.prototype.select = // Adds a column or columns to the list of "columns" // being selected on the query. QueryBuilder.prototype.columns = QueryBuilder.prototype.column = function() { this._statements.push({ grouping: 'columns', value: helpers.normalizeArr.apply(null, arguments) }); return this; }; // Sets the `tableName` on the query. // Alias to "from" for select and "into" for insert statements // e.g. builder.insert({a: value}).into('tableName') QueryBuilder.prototype.table = function(tableName) { this._single.table = tableName; return this; }; QueryBuilder.prototype.from = QueryBuilder.prototype.table; QueryBuilder.prototype.into = QueryBuilder.prototype.table; // Adds a `distinct` clause to the query. QueryBuilder.prototype.distinct = function() { this._statements.push({ grouping: 'columns', value: helpers.normalizeArr.apply(null, arguments), distinct: true }); return this; }; // Adds a join clause to the query, allowing for advanced joins // with an anonymous function as the second argument. QueryBuilder.prototype.join = function(table, first, operator, second) { var i, args = new Array(arguments.length); for (i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (args.length === 5) { helpers.deprecate('The five argument join syntax is now deprecated, ' + 'please check the docs and update your code.'); return this._joinType(args[4]).join(table, first, operator, second); } var join; if (_.isFunction(first)) { if (args.length > 2) { helpers.deprecate('The [table, fn, type] join syntax is deprecated, ' + 'please check the docs and update your code.'); return this._joinType(args[2]).join(table, first); } join = new JoinClause(table, this._joinType()); first.call(join, join); } else { join = new JoinClause(table, this._joinType()); join.on.apply(join, args.slice(1)); } this._statements.push(join); return this; }; // JOIN blocks: QueryBuilder.prototype.innerJoin = function() { return this._joinType('inner').join.apply(this, arguments); }; QueryBuilder.prototype.leftJoin = function() { return this._joinType('left').join.apply(this, arguments); }; QueryBuilder.prototype.leftOuterJoin = function() { return this._joinType('left outer').join.apply(this, arguments); }; QueryBuilder.prototype.rightJoin = function() { return this._joinType('right').join.apply(this, arguments); }; QueryBuilder.prototype.rightOuterJoin = function() { return this._joinType('right outer').join.apply(this, arguments); }; QueryBuilder.prototype.outerJoin = function() { return this._joinType('outer').join.apply(this, arguments); }; QueryBuilder.prototype.fullOuterJoin = function() { return this._joinType('full outer').join.apply(this, arguments); }; QueryBuilder.prototype.crossJoin = function() { return this._joinType('cross').join.apply(this, arguments); }; // The where function can be used in several ways: // The most basic is `where(key, value)`, which expands to // where key = value. QueryBuilder.prototype.where = QueryBuilder.prototype.andWhere = function(column, operator, value) { // Check if the column is a function, in which case it's // a where statement wrapped in parens. if (_.isFunction(column)) { return this.whereWrapped(column); } // Allow a raw statement to be passed along to the query. if (column instanceof Raw) return this._whereRaw(column); // Allows `where({id: 2})` syntax. if (_.isObject(column)) return this._objectWhere(column); // Enable the where('key', value) syntax, only when there // are explicitly two arguments passed, so it's not possible to // do where('key', '!=') and have that turn into where key != null if (arguments.length === 2) { value = operator; operator = '='; } // lower case the operator for comparison purposes operator = operator.toLowerCase(); // Ensure that the operator / query combo is legal. if (!_.contains(operators, operator)) { if (_.contains(nullOperators, operator)) { if (value === null || _.isString(value) && value.toLowerCase() === 'null') { return operator === 'is' ? this.whereNull(column, bool) : this.whereNull(column, bool, 'NotNull'); } this._errors.push(new Error('Invalid where in clause')); } this._errors.push(new Error('Invalid operator: ' + operator)); } // If the value is null, and the operator is equals, assume that we're // going for a `whereNull` statement here. if (value === null && operator === '=') { return this.whereNull(column); } this._statements.push({ grouping: 'where', type: 'whereBasic', column: column, operator: operator, value: value, bool: this._bool() }); return this; }; // Processes an object literal provided in a "where" clause. QueryBuilder.prototype._objectWhere = function(obj) { var boolVal = this._bool(); for (var key in obj) { this[boolVal + 'Where'](key, '=', obj[key]); } return this; }; // Adds an `or where` clause to the query. QueryBuilder.prototype.orWhere = function() { return this._bool('or').where.apply(this, arguments); }; // [Deprecated] QueryBuilder.prototype.orWhereRaw = function(sql, bindings) { return this._bool('or').whereRaw(sql, bindings); }; QueryBuilder.prototype.whereRaw = function(sql, bindings) { helpers.deprecate('Knex: .whereRaw is deprecated, please use .where(knex.raw(QUERY, [bindings]))'); return this._whereRaw(sql, bindings); }; // Adds a raw `where` clause to the query. QueryBuilder.prototype._whereRaw = function(sql, bindings) { var raw = (sql instanceof Raw ? sql : new Raw(sql, bindings)); this._statements.push({ grouping: 'where', type: 'whereRaw', value: raw, bool: this._bool() }); return this; }; // Helper for compiling any advanced `where` queries. QueryBuilder.prototype.whereWrapped = function(callback) { this._statements.push({ grouping: 'where', type: 'whereWrapped', value: callback, bool: this._bool() }); return this; }; // Adds a `where exists` clause to the query. QueryBuilder.prototype.whereExists = function(callback, not) { this._statements.push({ grouping: 'where', type: 'whereExists', value: callback, not: not || false, bool: this._bool(), }); return this; }; // Adds an `or where exists` clause to the query. QueryBuilder.prototype.orWhereExists = function(callback) { return this._bool('or').whereExists(callback); }; // Adds a `where not exists` clause to the query. QueryBuilder.prototype.whereNotExists = function(callback) { return this.whereExists(callback, true); }; // Adds a `or where not exists` clause to the query. QueryBuilder.prototype.orWhereNotExists = function(callback) { return this._bool('or').whereExists(callback, true); }; // Adds a `where in` clause to the query. QueryBuilder.prototype.whereIn = function(column, values, not) { this._statements.push({ grouping: 'where', type: 'whereIn', column: column, value: values, not: not || false, bool: this._bool() }); return this; }; // Adds a `or where in` clause to the query. QueryBuilder.prototype.orWhereIn = function(column, values) { return this._bool('or').whereIn(column, values); }; // Adds a `where not in` clause to the query. QueryBuilder.prototype.whereNotIn = function(column, values) { return this.whereIn(column, values, true); }; // Adds a `or where not in` clause to the query. QueryBuilder.prototype.orWhereNotIn = function(column, values) { return this._bool('or').whereIn(column, values, true); }; // Adds a `where null` clause to the query. QueryBuilder.prototype.whereNull = function(column, not) { this._statements.push({ grouping: 'where', type: 'whereNull', column: column, not: not || false, bool: this._bool() }); return this; }; // Adds a `or where null` clause to the query. QueryBuilder.prototype.orWhereNull = function(column) { return this._bool('or').whereNull(column); }; // Adds a `where not null` clause to the query. QueryBuilder.prototype.whereNotNull = function(column) { return this.whereNull(column, ' is not null'); }; // Adds a `or where not null` clause to the query. QueryBuilder.prototype.orWhereNotNull = function(column) { return this._bool('or').whereNull(column, ' is not null'); }; // Adds a `where between` clause to the query. QueryBuilder.prototype.whereBetween = function(column, values, not) { if (!_.isArray(values)) { return this._errors.push(new Error('The second argument to whereBetween must be an array.')); } if (values.length !== 2) { return this._errors.push(new Error('You must specify 2 values for the whereBetween clause')); } this._statements.push({ grouping: 'where', type: 'whereBetween', column: column, value: values, not: not || false, bool: this._bool() }); return this; }; // Adds a `where not between` clause to the query. QueryBuilder.prototype.whereNotBetween = function(column, values) { return this.whereBetween(column, values, true); }; // Adds a `or where between` clause to the query. QueryBuilder.prototype.orWhereBetween = function(column, values) { return this._bool('or').whereBetween(column, values); }; // Adds a `or where not between` clause to the query. QueryBuilder.prototype.orWhereNotBetween = function(column, values) { return this._bool('or').whereNotBetwen(column, values); }; // Adds a `group by` clause to the query. QueryBuilder.prototype.groupBy = function() { this._statements.push({ grouping: 'group', value: helpers.normalizeArr.apply(null, arguments) }); return this; }; // Adds a `order by` clause to the query. QueryBuilder.prototype.orderBy = function(column, direction) { if (!(direction instanceof Raw)) { if (!_.contains(orderBys, (direction || '').toLowerCase())) direction = 'asc'; } this._statements.push({ grouping: 'order', value: column, direction: direction }); return this; }; // Add a union statement to the query. QueryBuilder.prototype.union = function(callback, wrap) { if (arguments.length > 1) { var args = new Array(arguments.length); for (var i = 0, l = args.length; i < l; i++) { args[i] = arguments[i]; this.union(args[i]); } return this; } this._statements.push({ grouping: 'union', clause: 'union', value: callback, wrap: wrap || false }); return this; }; // Adds a union all statement to the query. QueryBuilder.prototype.unionAll = function(callback, wrap) { this._statements.push({ grouping: 'union', clause: 'union all', value: callback, wrap: wrap || false }); return this; }; // Adds a `having` clause to the query. QueryBuilder.prototype.having = function(column, operator, value) { if (column instanceof Raw && arguments.length === 1) { return this._havingRaw(column); } this._statements.push({ grouping: 'having', type: 'havingBasic', column: column, operator: operator, value: value, bool: this._bool() }); return this; }; // Adds an `or having` clause to the query. QueryBuilder.prototype.orHaving = function() { return this._bool('or').having.apply(this, arguments); }; // [Deprecated] QueryBuilder.prototype.havingRaw = function(sql, bindings) { helpers.deprecate('Knex: .havingRaw is deprecated, please use .having(knex.raw(QUERY, [bindings]))'); return this._havingRaw(sql, bindings); }; QueryBuilder.prototype.orHavingRaw = function(sql, bindings) { return this._bool('or').havingRaw(sql, bindings); }; // Adds a raw `having` clause to the query. QueryBuilder.prototype._havingRaw = function(sql, bindings) { var raw = (sql instanceof Raw ? sql : new Raw(sql, bindings)); this._statements.push({ grouping: 'having', type: 'havingRaw', value: raw, bool: this._bool() }); return this; }; // Only allow a single "offset" to be set for the current query. QueryBuilder.prototype.offset = function(value) { this._single.offset = value; return this; }; // Only allow a single "limit" to be set for the current query. QueryBuilder.prototype.limit = function(value) { this._single.limit = value; return this; }; // Retrieve the "count" result of the query. QueryBuilder.prototype.count = function(column) { return this._aggregate('count', (column || '*')); }; // Retrieve the minimum value of a given column. QueryBuilder.prototype.min = function(column) { return this._aggregate('min', column); }; // Retrieve the maximum value of a given column. QueryBuilder.prototype.max = function(column) { return this._aggregate('max', column); }; // Retrieve the sum of the values of a given column. QueryBuilder.prototype.sum = function(column) { return this._aggregate('sum', column); }; // Retrieve the average of the values of a given column. QueryBuilder.prototype.avg = function(column) { return this._aggregate('avg', column); }; // Increments a column's value by the specified amount. QueryBuilder.prototype.increment = function(column, amount) { return this._counter(column, amount); }; // Decrements a column's value by the specified amount. QueryBuilder.prototype.decrement = function(column, amount) { return this._counter(column, amount, '-'); }; // Sets the values for a `select` query, informing that only the first // row should be returned (limit 1). QueryBuilder.prototype.first = function() { var i, args = new Array(arguments.length); for (i = 0; i < args.length; i++) { args[i] = arguments[i]; } this.select.apply(this, args); this._method = 'first'; this.limit(1); return this; }; // Pluck a column from a query. QueryBuilder.prototype.pluck = function(column) { this._method = 'pluck'; this._statements.push({ grouping: 'column', type: 'pluck', value: column }); return this; }; // Insert & Update // ------ // Sets the values for an `insert` query. QueryBuilder.prototype.insert = function(values, returning) { this._method = 'insert'; if (!_.isEmpty(returning)) this.returning(returning); this._single.insert = values; return this; }; // Sets the values for an `update`, allowing for both // `.update(key, value, [returning])` and `.update(obj, [returning])` syntaxes. QueryBuilder.prototype.update = function(values, returning) { var ret, obj = {}; this._method = 'update'; var i, args = new Array(arguments.length); for (i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (_.isString(values)) { obj[values] = returning; if (args.length > 2) { ret = args[2]; } } else { obj = values; ret = args[1]; } if (!_.isEmpty(ret)) this.returning(ret); this._single.update = obj; return this; }; // Sets the returning value for the query. QueryBuilder.prototype.returning = function(returning) { this._single.returning = returning; return this; }; // Delete // ------ // Executes a delete statement on the query; QueryBuilder.prototype.del = QueryBuilder.prototype.delete = function(ret) { this._method = 'del'; if (!_.isEmpty(ret)) this.returning(ret); return this; }; // Truncates a table, ends the query chain. QueryBuilder.prototype.truncate = function() { this._method = 'truncate'; return this; }; // Retrieves columns for the table specified by `knex(tableName)` QueryBuilder.prototype.columnInfo = function() { this._method = 'columnInfo'; return this; }; // Set a lock for update constraint. QueryBuilder.prototype.forUpdate = function() { this._single.lock = 'forUpdate'; return this; }; // Set a lock for share constraint. QueryBuilder.prototype.forShare = function() { this._single.lock = 'forShare'; return this; }; // ---------------------------------------------------------------------- // Helper for the incrementing/decrementing queries. QueryBuilder.prototype._counter = function(column, amount, symbol) { var amt = parseInt(amount, 10); if (isNaN(amt)) amt = 1; this._method = 'counter'; this._single.counter = { column: column, amount: amt, symbol: (symbol || '+') }; return this; }; // Helper to get or set the "boolFlag" value. QueryBuilder.prototype._bool = function(val) { if (arguments.length === 1) { this._boolFlag = val; return this; } var ret = this._boolFlag; this._boolFlag = 'and'; return ret; }; // Helper to get or set the "joinFlag" value. QueryBuilder.prototype._joinType = function (val) { if (arguments.length === 1) { this._joinFlag = val; return this; } var ret = this._joinFlag || 'inner'; this._joinFlag = 'inner'; return ret; }; // Helper for compiling any aggregate queries. QueryBuilder.prototype._aggregate = function(method, column) { this._statements.push({ grouping: 'columns', type: 'aggregate', method: method, value: column }); return this; }; // Attach all of the top level promise methods that should be chainable. require('../interface')(QueryBuilder); module.exports = QueryBuilder; },{"../helpers":20,"../interface":21,"../raw":28,"./joinclause":26,"events":42,"inherits":43,"lodash":"K2RcUv"}],25:[function(require,module,exports){ // Query Compiler // ------- var _ = require('lodash'); var helpers = require('../helpers'); var Raw = require('../raw'); // 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. function QueryCompiler(queryBuilder) { this.method = queryBuilder._method || 'select'; this.options = queryBuilder._options; this.single = queryBuilder._single; this.transacting = queryBuilder._transacting; this.grouped = _.groupBy(queryBuilder._statements, 'grouping'); this.tableName = this.single.table ? this.formatter.wrap(this.single.table) : ''; } // Collapse the builder into a single object QueryCompiler.prototype.toSQL = function(method) { var val = this[method](); var defaults = { method: method, options: this.options && this.options.length > 0 ? _.extend.apply(_, this.options) : void 0, bindings: this.formatter.bindings }; if (_.isString(val)) { val = {sql: val}; } return _.extend(defaults, val); }; var components = [ 'columns', 'join', 'where', 'union', 'group', 'having', 'order', 'limit', 'offset', 'lock' ]; // 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.prototype.select = function() { var statements = []; for (var i = 0, l = components.length; i < l; i++) { var component = components[i]; statements.push(this[component](this)); } return _.compact(statements).join(' '); }; QueryCompiler.prototype.first = QueryCompiler.prototype.select; QueryCompiler.prototype.pluck = QueryCompiler.prototype.select; // Compiles an "insert" query, allowing for multiple // inserts using a single query statement. QueryCompiler.prototype.insert = function() { var sql = 'insert into ' + this.tableName + ' '; if (_.isEmpty(this.single.insert)) { sql += this._emptyInsertValue; } else { var insertData = this._prepInsert(this.single.insert); if (_.isString(insertData)) { sql += insertData; } else { sql += '(' + this.formatter.columnize(insertData.columns) + ') values (' + _.map(insertData.values, this.formatter.parameterize, this.formatter).join('), (') + ')'; } } return sql; }; // Compiles the "update" query. QueryCompiler.prototype.update = function() { obj = helpers.sortObject(obj); var vals = []; for (var i = 0; i < obj.length; i++) { var value = obj[i]; vals.push(this.formatter.wrap(value[0]) + ' = ' + this.formatter.parameter(value[1])); } if (!_.isEmpty(ret)) this.returning(ret); return { grouping: 'update', columns: vals.join(', ') }; }; // Compiles the columns in the query, specifying if an item was distinct. QueryCompiler.prototype.columns = function() { var distinct = false; if (this.onlyUnions()) return ''; var columns = this.grouped.columns || []; var sql = []; if (columns) { for (var i = 0, l = columns.length; i < l; i++) { 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.push('*'); return 'select ' + (distinct ? 'distinct ' : '') + (sql.join(', ') || '*') + (this.tableName ? ' from ' + this.tableName : ''); }; QueryCompiler.prototype.aggregate = function(stmt) { var val = stmt.value; var splitOn = val.toLowerCase().indexOf(' as '); // 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 + '(' + this.formatter.wrap(col) + ') as ' + this.formatter.wrap(alias); } return stmt.method + '(' + this.formatter.wrap(val) + ')'; }; // Compiles all each of the `join` clauses on the query, // including any nested join queries. QueryCompiler.prototype.join = function() { var joins = this.grouped.join; if (!joins) return ''; var sql = []; for (var i = 0, l = joins.length; i < l; i++) { var stmt = joins[i]; var str = stmt.joinType + ' join ' + this.formatter.wrap(stmt.table); for (var i2 = 0, l2 = stmt.clauses.length; i2 < l2; i2++) { var clause = stmt.clauses[i2]; if (i2 > 0) { str += ' ' + clause[1] + ' '; } else { str += ' on '; } str += this.formatter.wrap(clause[2]) + ' ' + this.formatter.operator(clause[3]) + ' ' + this.formatter.wrap(clause[4]); } sql.push(str); } return sql.length > 0 ? sql.join(' ') : ''; }; // Compiles all `where` statements on the query. QueryCompiler.prototype.where = function() { var wheres = this.grouped.where; if (!wheres) return; var sql = []; sql[0] = 'where'; for (var i = 0, l = wheres.length; i < l; i++) { var stmt = wheres[i]; if (i !== 0) sql.push(stmt.bool); sql.push(this[stmt.type](stmt)); } return sql.length > 1 ? sql.join(' ') : ''; }; QueryCompiler.prototype.group = function() { return this._groupsOrders('group'); }; QueryCompiler.prototype.order = function() { return this._groupsOrders('order'); }; // Compiles the `having` statements. QueryCompiler.prototype.having = function() { var havings = this.grouped.having; if (!havings) return ''; var sql = ['having']; for (var i = 0, l = havings.length; i < l; i++) { var str = '', s = havings[i]; if (i !== 0) str = s.bool + ' '; if (s.type === 'havingBasic') { sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value)); } else { sql.push(str + this.formatter.checkRaw(s.value)); } } return sql.length > 1 ? sql.join(' ') : ''; }; // Compile the "union" queries attached to the main query. QueryCompiler.prototype.union = function() { var onlyUnions = this.onlyUnions(); var unions = this.grouped.union; if (!unions) return ''; var sql = ''; for (var i = 0, l = unions.length; i < l; i++) { var union = unions[i]; if (i > 0) sql += ' '; if (i > 0 || !onlyUnions) sql += union.clause + ' '; sql += this.formatter.rawOrFn(union.value, union.wrap); } return sql; }; // If we haven't specified any columns or a `tableName`, we're assuming this // is only being used for unions. QueryCompiler.prototype.onlyUnions = function() { return (!this.grouped.columns && this.grouped.union && !this.tableName); }; QueryCompiler.prototype.limit = function() { if (this.single.limit == void 0) return ''; return 'limit ' + this.formatter.parameter(this.single.limit); }; QueryCompiler.prototype.offset = function() { if (this.single.offset == void 0) return ''; return 'offset ' + this.formatter.parameter(this.single.offset); }; // Compiles a `delete` query. QueryCompiler.prototype.del = function() { var wheres = this.where(); return 'delete from ' + this.tableName + (wheres ? ' ' + wheres : ''); }; // Compiles a `truncate` query. QueryCompiler.prototype.truncate = function() { return 'truncate ' + this.tableName; }; // Compiles the "locks". QueryCompiler.prototype.lock = function() { if (this.single.lock) { if (!this.transacting) { helpers.warn('You are attempting to perform a "lock" command outside of a transaction.'); } else { return this[this.single.lock](); } } }; // Compile the "counter". QueryCompiler.prototype.counter = function() { var counter = this.single.counter; var toUpdate = {}; toUpdate[counter.column] = new Raw(this.formatter.wrap(counter.column) + ' ' + (counter.symbol || '+') + ' ' + counter.amount); this.single.update = toUpdate; return this.update(); }; // Compiles the `order by` statements. QueryCompiler.prototype._groupsOrders = function(type) { var items = this.grouped[type]; if (!items) return ''; var sql = []; for (var i = 0, l = items.length; i < l; i++) { var item = items[i]; var str = this.formatter.columnize(item.value); if (type === 'order') { str += ' ' + this.formatter.direction(item.direction); } sql.push(str); } return sql.length > 0 ? type + ' by ' + sql.join(', ') : ''; }; // Where Clause // ------ QueryCompiler.prototype.whereIn = function(statement) { if (_.isArray(statement.column)) return this.multiWhereIn(statement); return this.formatter.wrap(statement.column) + ' ' + this._not(statement, 'in ') + this.wrap(this.formatter.parameterize(statement.value)); }; QueryCompiler.prototype.multiWhereIn = function(statement) { return '(' + _.map(statement.column, this.formatter.wrap, this.formatter) + ') ' + this._not(statement, 'in ') + '((' + _.map(statement.value, this.formatter.parameterize, this.formatter).join('),(') + '))'; }; QueryCompiler.prototype.whereNull = function(statement) { return this.formatter.wrap(statement.column) + ' is ' + this._not(statement, 'null'); }; // Compiles a basic "where" clause. QueryCompiler.prototype.whereBasic = function(statement) { return this.formatter.wrap(statement.column) + ' ' + this.formatter.operator(statement.operator) + ' ' + this.formatter.parameter(statement.value); }; QueryCompiler.prototype.whereExists = function(statement) { return this._not(statement, 'exists') + ' (' + this.formatter.compileCallback(statement.value) + ')'; }; QueryCompiler.prototype.whereWrapped = function(statement) { return '(' + this.formatter.compileCallback(statement.value, 'where').slice(6) + ')'; }; QueryCompiler.prototype.whereBetween = function(statement) { return this.formatter.wrap(statement.column) + ' ' + this._not(statement, 'between') + ' ' + _.map(statement.value, this.formatter.parameter, this.formatter).join(' and '); }; // Compiles a "whereRaw" query. QueryCompiler.prototype.whereRaw = function(statement) { return this.formatter.checkRaw(statement.value); }; QueryCompiler.prototype.wrap = function(str) { if (str.charAt(0) !== '(') return '(' + str + ')'; return str; }; // Determines whether to add a "not" prefix to the where clause. QueryCompiler.prototype._not = function(statement, str) { if (statement.not) return 'not ' + str; return str; }; // "Preps" the insert. QueryCompiler.prototype._prepInsert = function(data) { var isRaw = this.formatter.rawOrFn(data); if (isRaw) return isRaw; var values = []; var columns; if (!_.isArray(data)) data = data ? [data] : []; for (var i = 0, l = data.length; i 0 ? ' ' + modifiers.join(' ') : ''; }; // Types // ------ ColumnCompiler.prototype.increments = 'integer not null primary key autoincrement'; ColumnCompiler.prototype.bigincrements = 'integer not null primary key autoincrement'; ColumnCompiler.prototype.integer = ColumnCompiler.prototype.smallint = ColumnCompiler.prototype.mediumint = 'integer'; ColumnCompiler.prototype.biginteger = 'bigint'; ColumnCompiler.prototype.varchar = function(length) { return 'varchar(' + this._num(length, 255) + ')'; }; ColumnCompiler.prototype.text = 'text'; ColumnCompiler.prototype.tinyint = 'tinyint'; ColumnCompiler.prototype.floating = function(precision, scale) { return 'float(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; }; ColumnCompiler.prototype.decimal = function(precision, scale) { return 'decimal(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; }; ColumnCompiler.prototype.binary = 'blob'; ColumnCompiler.prototype.bool = 'boolean'; ColumnCompiler.prototype.date = 'date'; ColumnCompiler.prototype.datetime = 'datetime'; ColumnCompiler.prototype.time = 'time'; ColumnCompiler.prototype.timestamp = 'timestamp'; ColumnCompiler.prototype.enu = 'varchar'; ColumnCompiler.prototype.bit = ColumnCompiler.prototype.json = 'text'; ColumnCompiler.prototype.uuid = 'char(36)'; ColumnCompiler.prototype.specificType = function(type) { return type; }; // Modifiers // ------- ColumnCompiler.prototype.nullable = function(nullable) { return nullable === false ? 'not null' : 'null'; }; ColumnCompiler.prototype.notNullable = function() { return this.nullable(false); }; ColumnCompiler.prototype.defaultTo = function(value) { if (value === void 0) { return ''; } else if (value instanceof Raw) { value = value.toQuery(); } else if (this.method === 'bool') { if (value === 'false') value = 0; value = (value ? 1 : 0); } else if (value === true || value === false) { value = parseInt(value, 10); } else { value = "'" + value + "'"; } return 'default ' + value; }; ColumnCompiler.prototype._num = function(val, fallback) { if (val == null) return fallback; var number = parseInt(val, 10); return isNaN(number) ? fallback : number; }; module.exports = ColumnCompiler; },{"../raw":28,"lodash":"K2RcUv"}],33:[function(require,module,exports){ // 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. function SchemaCompiler(builder) { this.builder = builder; this.initCompiler(); } function buildTable(type) { return function(tableName, fn) { var TableBuilder = this.client.TableBuilder; var sql = new TableBuilder(type, tableName, fn).toSQL(); for (var i = 0, l = sql.length; i < l; i++) { this.sequence.push(sql[i]); } }; } SchemaCompiler.prototype.createTable = buildTable('create'); SchemaCompiler.prototype.alterTable = buildTable('alter'); SchemaCompiler.prototype.dropTable = function(tableName) { this.pushQuery('drop table ' + this.formatter.wrap(tableName)); }; SchemaCompiler.prototype.dropTableIfExists = function(tableName) { this.pushQuery('drop table if exists ' + this.formatter.wrap(tableName)); }; SchemaCompiler.prototype.toSQL = function() { var sequence = this.builder._sequence; for (var i = 0, l = sequence.length; i < l; i++) { var query = sequence[i]; this[query.method].apply(this, query.args); } return this.sequence; }; module.exports = SchemaCompiler; },{}],34:[function(require,module,exports){ var _ = require('lodash'); var Builder = require('./builder'); var Compiler = require('./compiler'); var TableBuilder = require('./tablebuilder'); var TableCompiler = require('./tablecompiler'); var ColumnBuilder = require('./columnbuilder'); var ColumnCompiler = require('./columncompiler'); // Initialize the compiler. Compiler.prototype.initCompiler = TableCompiler.prototype.initCompiler = ColumnCompiler.prototype.initCompiler = function() { this.formatter = new this.Formatter(); this.sequence = []; }; // Push a new query onto the compiled "sequence" stack, // creating a new formatter, returning the compiler. Compiler.prototype.pushQuery = TableCompiler.prototype.pushQuery = ColumnCompiler.prototype.pushQuery = function(query) { if (!query) return; if (_.isString(query)) { query = {sql: query}; } else { query = query; } if (!query.bindings) { query.bindings = this.formatter.bindings; } this.sequence.push(query); this.formatter = new this.Formatter(); }; module.exports = { Builder: Builder, Compiler: Compiler, TableBuilder: TableBuilder, TableCompiler: TableCompiler, ColumnBuilder: ColumnBuilder, ColumnCompiler: ColumnCompiler }; },{"./builder":30,"./columnbuilder":31,"./columncompiler":32,"./compiler":33,"./tablebuilder":35,"./tablecompiler":36,"lodash":"K2RcUv"}],35:[function(require,module,exports){ // TableBuilder // Takes the function passed to the "createTable" or "table/editTable" // functions and calls it with the "TableBuilder" as both the context and // the first argument. Inside this function we can specify what happens to the // method, pushing everything we want to do onto the "allStatements" array, // which is then compiled into sql. // ------ var _ = require('lodash'); function TableBuilder(method, tableName, fn) { this._fn = fn; this._method = method; this._tableName = tableName; this._statements = []; this._single = {}; } // Convert the current tableBuilder object "toSQL" // giving us additional methods if we're altering // rather than creating the table. TableBuilder.prototype.toSQL = function() { if (this._method === 'alter') { _.extend(this, AlterMethods); } this._fn.call(this, this); var TableCompiler = this.client.TableCompiler; return new TableCompiler(this).toSQL(); }; var AlterMethods = { // Renames the current column `from` the current // TODO: this.column(from).rename(to) renameColumn: function(from, to) { this._statements.push({ grouping: 'alterTable', method: 'renameColumn', args: [from, to] }); return this; }, dropTimestamps: function() { return this.dropColumns(['created_at', 'updated_at']); } // TODO: changeType }; // Drop a column from the current table. // TODO: Enable this.column(columnName).drop(); AlterMethods.dropColumn = AlterMethods.dropColumns = function() { this._statements.push({ grouping: 'alterTable', method: 'dropColumn', args: _.toArray(arguments) }); return this; }; _.each([ // Each of the index methods can be called individually, with the // column name to be used, e.g. table.unique('column'). 'index', 'primary', 'unique', // Key specific 'dropPrimary', 'dropUnique', 'dropIndex', 'dropForeign' ], function(method) { TableBuilder.prototype[method] = function() { this._statements.push({ grouping: 'alterTable', method: method, args: _.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) { warn('Knex only supports ' + method + ' statement with mysql.'); } if (this.__method === 'alter') { 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 // instance and push it onto the statements array. var columnTypes = [ // Numeric 'tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'decimal', 'float', 'double', 'real', 'bit', 'boolean', 'serial', // Date / Time 'date', 'datetime', 'timestamp', 'time', 'year', // String 'char', 'varchar', 'tinytext', 'tinyText', 'text', 'mediumtext', 'mediumText', 'longtext', 'longText', 'binary', 'varbinary', 'tinyblob', 'tinyBlob', 'mediumblob', 'mediumBlob', 'blob', 'longblob', 'longBlob', 'enum', 'set', // Increments, Aliases, and Additional 'bool', 'dateTime', 'increments', 'bigincrements', 'bigIncrements', 'integer', 'biginteger', 'bigInteger', 'string', 'timestamps', 'json', 'uuid', 'enu', 'specificType' ]; // 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) { TableBuilder.prototype[type] = function() { var args = _.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'); } return; } var ColumnBuilder = this.client.ColumnBuilder; var builder = new ColumnBuilder(this, type, args); this._statements.push({ grouping: 'columns', builder: builder }); return builder; }; }); // Set the comment value for a table, they're only allowed to be called // once per table. TableBuilder.prototype.comment = function(value) { this._single.comment = value; }; // Set a foreign key on the table, calling // `table.foreign('column_name').references('column').on('table').onDelete()... // Also called from the ColumnBuilder context when chaining. TableBuilder.prototype.foreign = function(column) { var foreignData = {column: column}; this._statements.push({ grouping: 'alterTable', method: 'foreign', args: [foreignData] }); var returnObj = { references: function(tableColumn) { var pieces; if (_.isString(tableColumn)) { pieces = tableColumn.split('.'); } if (!pieces || pieces.length === 1) { foreignData.references = pieces ? pieces[0] : tableColumn; return { on: function(tableName) { foreignData.inTable = tableName; return returnObj; }, inTable: function() { return this.on.apply(this, arguments); } }; } foreignData.inTable = pieces[0]; foreignData.references = pieces[1]; return returnObj; }, onUpdate: function(statement) { foreignData.onUpdate = statement; return returnObj; }, onDelete: function(statement) { foreignData.onDelete = statement; return returnObj; }, _columnBuilder: function(builder) { _.extend(builder, returnObj); returnObj = builder; return builder; } }; return returnObj; }; module.exports = TableBuilder; },{"lodash":"K2RcUv"}],36:[function(require,module,exports){ // Table Compiler // ------- var _ = require('lodash'); var helpers = require('../helpers'); function TableCompiler(tableBuilder) { this.method = tableBuilder._method; this.tableNameRaw = tableBuilder._tableName; this.single = tableBuilder._single; this.grouped = _.groupBy(tableBuilder._statements, 'grouping'); this.initCompiler(); } // Convert the tableCompiler toSQL TableCompiler.prototype.toSQL = function() { this[this.method](); return this.sequence; }; // Column Compilation // ------- // If this is a table "creation", we need to first run through all // of the columns to build them into a single string, // and then run through anything else and push it to the query sequence. TableCompiler.prototype.create = function() { var columns = this.getColumns(); var columnTypes = this.getColumnTypes(columns); this.createQuery(columnTypes); this.columnQueries(columns); this.alterTable(); }; // If we're altering the table, we need to one-by-one // go through and handle each of the queries associated // with altering the table's schema. TableCompiler.prototype.alter = function() { var columns = this.getColumns(); var columnTypes = this.getColumnTypes(columns); this.addColumns(columnTypes); this.columnQueries(columns); this.alterTable(); }; TableCompiler.prototype.foreign = function(foreignData) { if (foreignData.inTable && foreignData.references) { var keyName = this._indexCommand('foreign', this.tableNameRaw, foreignData.column); var column = this.formatter.columnize(foreignData.column); var references = this.formatter.columnize(foreignData.references); var inTable = this.formatter.wrap(foreignData.inTable); return 'alter table ' + this.tableName() + ' add constraint ' + keyName + ' ' + 'foreign key (' + column + ') references ' + inTable + ' (' + references + ')'; } }; // 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) { memo.sql.push(column.sql); memo.bindings.concat(column.bindings); return memo; }, {sql: [], bindings: []}); }; // Adds all of the additional queries from the "column" TableCompiler.prototype.columnQueries = function(columns) { var queries = _.reduce(columns, function(memo, column) { memo.concat(_.rest(column)); return memo; }, []); for (var i = 0, l = queries.length; i < l; i++) { this.pushQuery(queries[i]); } return queries; }; // Add a new column. TableCompiler.prototype.addColumnsPrefix = 'add column '; // All of the columns to "add" for the query TableCompiler.prototype.addColumns = function(columns) { if (columns.sql.length > 0) { var columnSql = _.map(columns.sql, function(column) { return this.addColumnsPrefix + column; }, this); this.pushQuery({ sql: 'alter table ' + this.tableName() + ' ' + columnSql.join(', '), bindings: columns.bindings }); } }; // Compile the columns as needed for the current create or alter table TableCompiler.prototype.getColumns = function() { var compiledColumns = [], columns = this.grouped.columns || []; var ColumnCompiler = this.client.ColumnCompiler; for (var i = 0, l = columns.length; i < l; i++) { compiledColumns.push(new ColumnCompiler(this, columns[i].builder).toSQL()); } return compiledColumns; }; TableCompiler.prototype.tableName = function() { return this.formatter.wrap(this.tableNameRaw); }; // Generate all of the alter column statements necessary for the query. TableCompiler.prototype.alterTable = function() { var alterTable = this.grouped.alterTable || []; for (var i = 0, l = alterTable.length; i < l; i++) { var statement = alterTable[i]; if (this[statement.method]) { this[statement.method].apply(this, statement.args); } else { console.error('Debug: ' + statement.method + ' does not exist'); } } }; // Drop the index on the current table. TableCompiler.prototype.dropIndex = function(value) { this.pushQuery('drop index' + value); }; // Drop the unique TableCompiler.prototype.dropUnique = TableCompiler.prototype.dropForeign = function() { throw new Error('Method implemented in the dialect driver'); }; TableCompiler.prototype.dropColumnPrefix = 'drop column '; TableCompiler.prototype.dropColumn = function() { var columns = helpers.normalizeArr.apply(null, arguments); var drops = _.map(_.isArray(columns) ? columns : [columns], function(column) { return this.dropColumnPrefix + this.formatter.wrap(column); }, this); this.pushQuery('alter table ' + this.tableName() + ' ' + drops.join(', ')); }; // If no name was specified for this index, we will create one using a basic // 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] : []; var table = tableName.replace(/\.|-/g, '_'); return (table + '_' + columns.join('_') + '_' + type).toLowerCase(); }; module.exports = TableCompiler; },{"../helpers":20,"lodash":"K2RcUv"}],37:[function(require,module,exports){ // Transaction // ------- var Promise = require('./promise'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; // Creates a new wrapper object for constructing a transaction. // Called by the `knex.transaction`, which sets the correct client // and handles the `container` object, passing along the correct // `connection` to keep all of the transactions on the correct connection. function Transaction(container) { this.container = container; } inherits(Transaction, EventEmitter); // Build the object passed around inside the transaction container. Transaction.prototype.containerObject = function(runner) { var containerObj = { commit: function(message) { return containerObj._runner.finishTransaction(0, this, message); }, rollback: function(error) { return containerObj._runner.finishTransaction(1, this, error); }, _runner: runner }; return containerObj; }; Transaction.prototype.initiateDeferred = function(containerObj) { // Initiate a deferred object, bound to the container object, // so we know when the transaction completes or fails // and can continue from there. var dfd = containerObj._dfd = Promise.pending(); // Call the container with the transaction // commit & rollback objects. this.container(containerObj); // Return the promise for the entire transaction. return dfd.promise; }; // Allow the `Transaction` object to be utilized with full access to the relevant // promise API. require('./interface')(Transaction); // Passed a `container` function, this method runs the current // transaction, returning a promise. Transaction.prototype.then = function(onFulfilled, onRejected) { var Runner = this.client.Runner; // Create a new "runner" object, passing the "runner" // object along, so we can easily keep track of every // query run on the current connection. return new Runner(this) .startTransaction() .bind(this) .then(this.containerObject) .then(this.initiateDeferred) .then(onFulfilled, onRejected); }; module.exports = Transaction; },{"./interface":21,"./promise":23,"events":42,"inherits":43}],38:[function(require,module,exports){ var _ = require('lodash'); module.exports = { // If we are running an insert with variable object keys, we need to normalize // for the missing keys, presumably setting the values to undefined. prepInsert: function(data) { if (!_.isArray(data)) return _.clone(data); var defaultObj = _.reduce(_.union.apply(_, _.map(data, function(val) { return _.keys(val); })), function(memo, key) { memo[key] = void 0; return memo; }, {}); return _.map(data, function(row) { return _.defaults(row, defaultObj); }); }, pgBindings: function(sql) { var questionCount = 0; return sql.replace(/\?/g, function() { questionCount++; return '$' + questionCount; }); } }; },{"lodash":"K2RcUv"}],39:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 /** * If `Buffer._useTypedArrays`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (compatible down to IE6) */ Buffer._useTypedArrays = (function () { // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support // because we need to be able to add all the node Buffer API methods. This is an issue // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` } catch (e) { return false } })() /** * 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 (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject // Workaround: node's base64 implementation allows for non-padded strings // while base64-js does not. if (encoding === 'base64' && type === 'string') { subject = stringtrim(subject) while (subject.length % 4 !== 0) { subject = subject + '=' } } // Find the length var length if (type === 'number') length = coerce(subject) else if (type === 'string') length = Buffer.byteLength(subject, encoding) else if (type === 'object') length = coerce(subject.length) // assume that object is array-like else throw new Error('First argument needs to be a number, array or string.') var buf if (Buffer._useTypedArrays) { // Preferred: Return an augmented `Uint8Array` instance for best performance buf = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return THIS instance of Buffer (created by `new`) buf = this buf.length = length buf._isBuffer = true } var i if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array buf._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array for (i = 0; i < length; i++) { if (Buffer.isBuffer(subject)) buf[i] = subject.readUInt8(i) else buf[i] = subject[i] } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } // STATIC METHODS // ============== Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.isBuffer = function (b) { return !!(b !== null && b !== undefined && b._isBuffer) } Buffer.byteLength = function (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'hex': ret = str.length / 2 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'ascii': case 'binary': case 'raw': ret = str.length break case 'base64': ret = base64ToBytes(str).length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break default: throw new Error('Unknown encoding') } return ret } Buffer.concat = function (list, totalLength) { assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + 'list should be an Array.') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (typeof totalLength !== 'number') { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } // BUFFER INSTANCE METHODS // ======================= 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 assert(strLen % 2 === 0, 'Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) assert(!isNaN(byte), 'Invalid hex string') buf[offset + i] = byte } Buffer._charsWritten = i * 2 return i } function _utf8Write (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function _asciiWrite (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function _binaryWrite (buf, string, offset, length) { return _asciiWrite(buf, string, offset, length) } function _base64Write (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function _utf16leWrite (buf, string, offset, length) { var charsWritten = Buffer._charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = _hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = _utf8Write(this, string, offset, length) break case 'ascii': ret = _asciiWrite(this, string, offset, length) break case 'binary': ret = _binaryWrite(this, string, offset, length) break case 'base64': ret = _base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = _utf16leWrite(this, string, offset, length) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toString = function (encoding, start, end) { var self = this encoding = String(encoding || 'utf8').toLowerCase() start = Number(start) || 0 end = (end !== undefined) ? Number(end) : end = self.length // Fastpath empty strings if (end === start) return '' var ret switch (encoding) { case 'hex': ret = _hexSlice(self, start, end) break case 'utf8': case 'utf-8': ret = _utf8Slice(self, start, end) break case 'ascii': ret = _asciiSlice(self, start, end) break case 'binary': ret = _binarySlice(self, start, end) break case 'base64': ret = _base64Slice(self, start, end) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = _utf16leSlice(self, start, end) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions assert(end >= start, 'sourceEnd < sourceStart') assert(target_start >= 0 && target_start < target.length, 'targetStart out of bounds') assert(start >= 0 && start < source.length, 'sourceStart out of bounds') assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !Buffer._useTypedArrays) { for (var i = 0; i < len; i++) target[i + target_start] = this[i + start] } else { target._set(this.subarray(start, start + len), target_start) } } function _base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function _utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function _asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) ret += String.fromCharCode(buf[i]) return ret } function _binarySlice (buf, start, end) { return _asciiSlice(buf, start, end) } function _hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function _utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i+1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = clamp(start, len, 0) end = clamp(end, len, len) if (Buffer._useTypedArrays) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return return this[offset] } function _readUInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { val = buf[offset] if (offset + 1 < len) val |= buf[offset + 1] << 8 } else { val = buf[offset] << 8 if (offset + 1 < len) val |= buf[offset + 1] } return val } Buffer.prototype.readUInt16LE = function (offset, noAssert) { return _readUInt16(this, offset, true, noAssert) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { return _readUInt16(this, offset, false, noAssert) } function _readUInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { if (offset + 2 < len) val = buf[offset + 2] << 16 if (offset + 1 < len) val |= buf[offset + 1] << 8 val |= buf[offset] if (offset + 3 < len) val = val + (buf[offset + 3] << 24 >>> 0) } else { if (offset + 1 < len) val = buf[offset + 1] << 16 if (offset + 2 < len) val |= buf[offset + 2] << 8 if (offset + 3 < len) val |= buf[offset + 3] val = val + (buf[offset] << 24 >>> 0) } return val } Buffer.prototype.readUInt32LE = function (offset, noAssert) { return _readUInt32(this, offset, true, noAssert) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { return _readUInt32(this, offset, false, noAssert) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return var neg = this[offset] & 0x80 if (neg) return (0xff - this[offset] + 1) * -1 else return this[offset] } function _readInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = _readUInt16(buf, offset, littleEndian, true) var neg = val & 0x8000 if (neg) return (0xffff - val + 1) * -1 else return val } Buffer.prototype.readInt16LE = function (offset, noAssert) { return _readInt16(this, offset, true, noAssert) } Buffer.prototype.readInt16BE = function (offset, noAssert) { return _readInt16(this, offset, false, noAssert) } function _readInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = _readUInt32(buf, offset, littleEndian, true) var neg = val & 0x80000000 if (neg) return (0xffffffff - val + 1) * -1 else return val } Buffer.prototype.readInt32LE = function (offset, noAssert) { return _readInt32(this, offset, true, noAssert) } Buffer.prototype.readInt32BE = function (offset, noAssert) { return _readInt32(this, offset, false, noAssert) } function _readFloat (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 23, 4) } Buffer.prototype.readFloatLE = function (offset, noAssert) { return _readFloat(this, offset, true, noAssert) } Buffer.prototype.readFloatBE = function (offset, noAssert) { return _readFloat(this, offset, false, noAssert) } function _readDouble (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 52, 8) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { return _readDouble(this, offset, true, noAssert) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { return _readDouble(this, offset, false, noAssert) } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'trying to write beyond buffer length') verifuint(value, 0xff) } if (offset >= this.length) return this[offset] = value } function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { _writeUInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { _writeUInt16(this, value, offset, false, noAssert) } function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffffffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { _writeUInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { _writeUInt32(this, value, offset, false, noAssert) } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to write beyond buffer length') verifsint(value, 0x7f, -0x80) } if (offset >= this.length) return if (value >= 0) this.writeUInt8(value, offset, noAssert) else this.writeUInt8(0xff + value + 1, offset, noAssert) } function _writeInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fff, -0x8000) } var len = buf.length if (offset >= len) return if (value >= 0) _writeUInt16(buf, value, offset, littleEndian, noAssert) else _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { _writeInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { _writeInt16(this, value, offset, false, noAssert) } function _writeInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fffffff, -0x80000000) } var len = buf.length if (offset >= len) return if (value >= 0) _writeUInt32(buf, value, offset, littleEndian, noAssert) else _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { _writeInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { _writeInt32(this, value, offset, false, noAssert) } function _writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 23, 4) } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { _writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { _writeFloat(this, value, offset, false, noAssert) } function _writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 7 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 52, 8) } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { _writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { _writeDouble(this, value, offset, false, noAssert) } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (typeof value === 'string') { value = value.charCodeAt(0) } assert(typeof value === 'number' && !isNaN(value), 'value is not a number') assert(end >= start, 'end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return assert(start >= 0 && start < this.length, 'start out of bounds') assert(end >= 0 && end <= this.length, 'end out of bounds') for (var i = start; i < end; i++) { this[i] = value } } Buffer.prototype.inspect = function () { var out = [] var len = this.length for (var i = 0; i < len; i++) { out[i] = toHex(this[i]) if (i === exports.INSPECT_MAX_BYTES) { out[i + 1] = '...' break } } return '' } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer._useTypedArrays) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) buf[i] = this[i] return buf.buffer } } else { throw new Error('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } // slice(start, end) function clamp (index, len, defaultValue) { if (typeof index !== 'number') return defaultValue index = ~~index; // Coerce to integer. if (index >= len) return len if (index >= 0) return index index += len if (index >= 0) return index return 0 } function coerce (length) { // Coerce length to a number (possibly NaN), round up // in case it's fractional (e.g. 123.456) then do a // double negate to coerce a NaN to 0. Easy, right? length = ~~Math.ceil(+length) return length < 0 ? 0 : length } function isArray (subject) { return (Array.isArray || function (subject) { return Object.prototype.toString.call(subject) === '[object Array]' })(subject) } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) byteArray.push(str.charCodeAt(i)) else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) byteArray.push(parseInt(h[j], 16)) } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { var pos for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } /* * We have to make sure that the value is a valid integer. This means that it * is non-negative. It has no fractional component and that it does not * exceed the maximum allowed value. */ function verifuint (value, max) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value >= 0, 'specified a negative value for writing an unsigned value') assert(value <= max, 'value is larger than maximum value for type') assert(Math.floor(value) === value, 'value has a fractional component') } function verifsint (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') assert(Math.floor(value) === value, 'value has a fractional component') } function verifIEEE754 (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') } function assert (test, message) { if (!test) throw new Error(message || 'Failed assertion') } },{"base64-js":40,"ieee754":41}],40:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var ZERO = '0'.charCodeAt(0) var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS) return 62 // '+' if (code === SLASH) 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 } module.exports.toByteArray = b64ToByteArray module.exports.fromByteArray = uint8ToBase64 }()) },{}],41:[function(require,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],42:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],43:[function(require,module,exports){ 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 { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],44:[function(require,module,exports){ (function (Buffer){ var SqlString = exports; SqlString.escapeId = function (val, forbidQualified) { if (Array.isArray(val)) { return val.map(function(v) { return SqlString.escapeId(v, forbidQualified); }).join(', '); } if (forbidQualified) { return '`' + val.replace(/`/g, '``') + '`'; } return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`'; }; SqlString.escape = function(val, stringifyObjects, timeZone) { if (val === undefined || val === null) { return 'NULL'; } switch (typeof val) { case 'boolean': return (val) ? 'true' : 'false'; case 'number': return val+''; } if (val instanceof Date) { val = SqlString.dateToString(val, timeZone || 'local'); } if (Buffer.isBuffer(val)) { return SqlString.bufferToString(val); } if (Array.isArray(val)) { return SqlString.arrayToList(val, timeZone); } if (typeof val === 'object') { if (stringifyObjects) { val = val.toString(); } else { return SqlString.objectToValues(val, timeZone); } } val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) { switch(s) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\"+s; } }); return "'"+val+"'"; }; SqlString.arrayToList = function(array, timeZone) { return array.map(function(v) { if (Array.isArray(v)) return '(' + SqlString.arrayToList(v, timeZone) + ')'; return SqlString.escape(v, true, timeZone); }).join(', '); }; SqlString.format = function(sql, values, stringifyObjects, timeZone) { values = values == null ? [] : [].concat(values); return sql.replace(/\?\??/g, function(match) { if (!values.length) { return match; } if (match == "??") { return SqlString.escapeId(values.shift()); } return SqlString.escape(values.shift(), stringifyObjects, timeZone); }); }; SqlString.dateToString = function(date, timeZone) { var dt = new Date(date); if (timeZone != 'local') { var tz = convertTimezone(timeZone); dt.setTime(dt.getTime() + (dt.getTimezoneOffset() * 60000)); if (tz !== false) { dt.setTime(dt.getTime() + (tz * 60000)); } } var year = dt.getFullYear(); var month = zeroPad(dt.getMonth() + 1, 2); var day = zeroPad(dt.getDate(), 2); var hour = zeroPad(dt.getHours(), 2); var minute = zeroPad(dt.getMinutes(), 2); var second = zeroPad(dt.getSeconds(), 2); var millisecond = zeroPad(dt.getMilliseconds(), 3); return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second + '.' + millisecond; }; SqlString.bufferToString = function(buffer) { var hex = ''; try { hex = buffer.toString('hex'); } catch (err) { // node v0.4.x does not support hex / throws unknown encoding error for (var i = 0; i < buffer.length; i++) { var byte = buffer[i]; hex += zeroPad(byte.toString(16)); } } return "X'" + hex+ "'"; }; SqlString.objectToValues = function(object, timeZone) { var values = []; for (var key in object) { var value = object[key]; if(typeof value === 'function') { continue; } values.push(this.escapeId(key) + ' = ' + SqlString.escape(value, true, timeZone)); } return values.join(', '); }; function zeroPad(number, length) { number = number.toString(); while (number.length < length) { number = '0' + number; } return number; } function convertTimezone(tz) { if (tz == "Z") return 0; var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/); if (m) { return (m[1] == '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60; } return false; } }).call(this,require("buffer").Buffer) },{"buffer":39}]},{},[])