exports = module.exports = function swaggerMetadataMiddleware (rlOrSO, apiDeclarations) {
  debug('Initializing swagger-metadata middleware');

  var apiCache = processSwaggerDocuments(rlOrSO, apiDeclarations);
  var swaggerVersion = cHelpers.getSwaggerVersion(rlOrSO);

  if (_.isUndefined(rlOrSO)) {
    throw new Error('rlOrSO is required');
  } else if (!_.isPlainObject(rlOrSO)) {
    throw new TypeError('rlOrSO must be an object');
  }

  if (swaggerVersion === '1.2') {
    if (_.isUndefined(apiDeclarations)) {
      throw new Error('apiDeclarations is required');
    } else if (!_.isArray(apiDeclarations)) {
      throw new TypeError('apiDeclarations must be an array');
    }
  }

  return function swaggerMetadata (req, res, next) {
    var method = req.method.toLowerCase();
    var path = parseurl(req).pathname;
    var cacheEntry;
    var match;
    var metadata;

    cacheEntry = apiCache[path] || _.find(apiCache, function (metadata) {
      match = metadata.re.exec(path);
      return _.isArray(match);
    });

    debug('%s %s', req.method, req.url);
    debug('  Is a Swagger path: %s', !_.isUndefined(cacheEntry));

    // Request does not match an API defined in the Swagger document(s)
    if (!cacheEntry) {
      return next();
    }

    metadata = swaggerVersion === '1.2' ?
      {
        api: cacheEntry.api,
        apiDeclaration: cacheEntry.apiDeclaration,
        apiIndex: cacheEntry.apiIndex,
        params: {},
        resourceIndex: cacheEntry.resourceIndex,
        resourceListing: cacheEntry.resourceListing
      } :
    {
      apiPath : cacheEntry.apiPath,
      path: cacheEntry.path,
      params: {},
      swaggerObject: cacheEntry.swaggerObject.resolved
    };

    if (_.isPlainObject(cacheEntry.operations[method])) {
      metadata.operation = cacheEntry.operations[method].operation;
      metadata.operationPath = cacheEntry.operations[method].operationPath;

      if (swaggerVersion === '1.2') {
        metadata.authorizations = metadata.operation.authorizations || cacheEntry.apiDeclaration.authorizations;
      } else {
        metadata.operationParameters = cacheEntry.operations[method].operationParameters;
        metadata.security = metadata.operation.security || metadata.swaggerObject.security || [];
      }
    }

    metadata.swaggerVersion = swaggerVersion;

    req.swagger = metadata;

    debug('  Is a Swagger operation: %s', !_.isUndefined(metadata.operation));

    if (metadata.operation) {
      // Process the operation parameters
      return processOperationParameters(swaggerVersion, cacheEntry.keys, match, req, res, next, debug);
    } else {
      return next();
    }
  };
};
Example #2
0
File: app.js Project: yawo/pepeto
ngModule.config(function (authProvider) {
  if (_.isPlainObject(global.config) && global.config.user) {
    authProvider.initUser(global.config.user);
  }
});
Example #3
0
 _.map(definition.args.concat(args), function(arg) {
   if (_.isPlainObject(arg)) { return _.toPairs(arg); }
   return arg;
 })
var isObject = function (object) {
  return _.isArray(object) ||  _.isPlainObject(object);
}
Example #5
0
      this[level] = function(...args) {
        this.logLine(level, ...args);
      };
    });
  },
  configure(loggerObj) {
    this.loggerObj = loggerObj;
    this.configured = true;
    this.selfConfigured = false;
  },
  withFields(extraFields) {
    return Object.assign({}, this, { extraFields: { ...this.extraFields, ...extraFields } });
  },
  logLine(level, ...args) {
    const argsToLog = [...args];
    const extraFieldsFromArgsExist = _.isPlainObject(_.first(args));
    const extraFieldsFromArgs = extraFieldsFromArgsExist ? args[0] : {};
    if (extraFieldsFromArgsExist) {
      argsToLog.shift();
    }
    const extraFields = { ...extraFieldsFromArgs, ...this.extraFields };
    if (!_.isEmpty(extraFields)) {
      argsToLog.unshift(extraFields);
    }
    this.loggerObj[level](...argsToLog);
  },
};

logger.init(LEVELS);

export default logger;
Example #6
0
 _.each(bindings, (val, key) => {
   if (_.isFunction(val)) _.merge(this.templates, { [key]: val });
   if (_.isPlainObject(val)) _.merge(this.rewriters, { [key]: val });
 });
 req.check = function(param, failMsg) {
   if (_.isPlainObject(param)) {
     return validateSchema(param, req, 'any', options);
   }
   return new ValidatorChain(param, failMsg, req, locate(req, param), options);
 };
Example #8
0
CriteriaProcessor.prototype._in = function _in(key, val) {

  var self = this;

  // Set case sensitive by default
  var caseSensitivity = true;

  // Set lower logic to false
  var lower = false;

  // Check if key is a string
  var schema = self.currentSchema && self.currentSchema[key];
  if(!_.isPlainObject(schema)) {
    schema = { type: schema };
  }

  if(schema && schema.type === 'text' || schema.type === 'string') {
    caseSensitivity = false;
    lower = true;
  }

  // Override caseSensitivity for databases that don't support it
  if(this.caseSensitive) {
    caseSensitivity = false;
  }

  // Add support for overriding case sensitivity with WL Next features
  if(hop(self.wlNext, 'caseSensitive') && self.wlNext.caseSensitive) {
    caseSensitivity = true;
  }

  // Check case sensitivity to decide if LOWER logic is used
  if(!caseSensitivity) {
    if(lower) {
      key = 'LOWER(' + utils.escapeName(self.getTableAlias(), self.escapeCharacter) + '.' + utils.escapeName(key, self.escapeCharacter) + ')';
    } else {
      key = utils.escapeName(self.getTableAlias(), self.escapeCharacter) + '.' + utils.escapeName(key, self.escapeCharacter);
    }
    self.queryString += key + ' IN (';
  } else {
    self.queryString += utils.escapeName(self.getTableAlias(), self.escapeCharacter) + '.' + utils.escapeName(key, self.escapeCharacter) + ' IN (';
  }

  // Append each value to query
  val.forEach(function(value) {

    // If case sensitivity if off lowercase the value
    if(!caseSensitivity && _.isString(value)) {
      value = value.toLowerCase();
    }

    // Use either a paramterized value or escaped value
    if(self.parameterized) {
      self.queryString += '$' + self.paramCount + ',';
      self.paramCount++;
    }
    else {
      if(_.isString(value)) {
        value = '"' + utils.escapeString(value) + '"';
      }

      self.queryString += value + ',';
    }

    self.values.push(value);
  });

  // Strip last comma and close criteria
  self.queryString = self.queryString.slice(0, -1) + ')';

  self.queryString += ' AND ';
};
Example #9
0
var HasMany = function(source, target, options) {
  Association.call(this);

  this.associationType = 'HasMany';
  this.source = source;
  this.target = target;
  this.targetAssociation = null;
  this.options = options || {};
  this.sequelize = source.modelManager.sequelize;
  this.through = options.through;
  this.scope = options.scope;
  this.isMultiAssociation = true;
  this.isSelfAssociation = this.source === this.target;
  this.as = this.options.as;
  this.foreignKeyAttribute = {};

  if (this.options.through) {
    throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
  }


  /*
   * If self association, this is the target association
   */
  if (this.isSelfAssociation) {
    this.targetAssociation = this;
  }

  if (this.as) {
    this.isAliased = true;

    if (_.isPlainObject(this.as)) {
      this.options.name = this.as;
      this.as = this.as.plural;
    } else {
      this.options.name = {
        plural: this.as,
        singular: Utils.singularize(this.as)
      };
    }
  } else {
    this.as = this.target.options.name.plural;
    this.options.name = this.target.options.name;
  }

  /*
   * Foreign key setup
   */
  if (_.isObject(this.options.foreignKey)) {
    this.foreignKeyAttribute = this.options.foreignKey;
    this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
  } else if (this.options.foreignKey) {
    this.foreignKey = this.options.foreignKey;
  }

  if (!this.foreignKey) {
    this.foreignKey = Utils.camelizeIf(
      [
        Utils.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
        this.source.primaryKeyAttribute
      ].join('_'),
      !this.source.options.underscored
    );
  }

  if (this.target.rawAttributes[this.foreignKey]) {
    this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
    this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
  }

  this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
  this.sourceKeyField = this.target.rawAttributes[this.sourceKey].field || this.sourceKey;

  this.sourceIdentifier = this.sourceKey;
  this.associationAccessor = this.as;

  // Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
  var plural = Utils.uppercaseFirst(this.options.name.plural)
    , singular = Utils.uppercaseFirst(this.options.name.singular);

  this.accessors = {
    /**
     * Get everything currently associated with this, using an optional where clause.
     *
     * @param {Object} [options]
     * @param {Object} [options.where] An optional where clause to limit the associated models
     * @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
     * @param {String} [options.schema] Apply a schema on the related model
     * @return {Promise<Array<Instance>>}
     * @method getAssociations
     */
    get: 'get' + plural,
    /**
     * Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
     *
     * @param {Array<Instance|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
     * @param {Object} [options] Options passed to `target.findAll` and `update`.
     * @param {Object} [options.validate] Run validation for the join model
     * @return {Promise}
     * @method setAssociations
     */
    set: 'set' + plural,
    /**
     * Associate several persisted instances with this.
     *
     * @param {Array<Instance|String|Number>} [newAssociations] An array of persisted instances or primary key of instances to associate with this.
     * @param {Object} [options] Options passed to `target.update`.
     * @param {Object} [options.validate] Run validation for the join model.
     * @return {Promise}
     * @method addAssociations
     */
    addMultiple: 'add' + plural,
    /**
     * Associate a persisted instance with this.
     *
     * @param {Instance|String|Number} [newAssociation] A persisted instance or primary key of instance to associate with this.
     * @param {Object} [options] Options passed to `target.update`.
     * @param {Object} [options.validate] Run validation for the join model.
     * @return {Promise}
     * @method addAssociation
     */
    add: 'add' + singular,
    /**
     * Create a new instance of the associated model and associate it with this.
     *
     * @param {Object} [values]
     * @param {Object} [options] Options passed to `target.create`.
     * @return {Promise}
     * @method createAssociation
     */
    create: 'create' + singular,
    /**
     * Un-associate the instance.
     *
     * @param {Instance|String|Number} [oldAssociated] Can be an Instance or its primary key
     * @param {Object} [options] Options passed to `target.update`
     * @return {Promise}
     * @method removeAssociation
     */
    remove: 'remove' + singular,
    /**
     * Un-associate several instances.
     *
     * @param {Array<Instance|String|Number>} [oldAssociatedArray] Can be an array of instances or their primary keys
     * @param {Object} [options] Options passed to `through.destroy`
     * @return {Promise}
     * @method removeAssociations
     */
    removeMultiple: 'remove' + plural,
    /**
     * Check if an instance is associated with this.
     *
     * @param {Instance|String|Number} [instance] Can be an Instance or its primary key
     * @param {Object} [options] Options passed to getAssociations
     * @return {Promise}
     * @method hasAssociation
     */
    hasSingle: 'has' + singular,
    /**
     * Check if all instances are associated with this.
     *
     * @param {Array<Instance|String|Number>} [instances] Can be an array of instances or their primary keys
     * @param {Object} [options] Options passed to getAssociations
     * @return {Promise}
     * @method hasAssociations
     */
    hasAll: 'has' + plural,
    /**
     * Count everything currently associated with this, using an optional where clause.
     *
     * @param {Object} [options]
     * @param {Object} [options.where] An optional where clause to limit the associated models
     * @param {String|Boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
     * @return {Promise<Int>}
     * @method countAssociations
     */
    count: 'count' + plural
  };

  if (this.options.counterCache) {
    new CounterCache(this, this.options.counterCache !== true ? this.options.counterCache : {});
    delete this.accessors.count;
  }
};
Example #10
0
Query.prototype.parseExpression = function parseExpression(field, expression) {
  "use strict";
  var self = this;

  // Recursively parse nested unless value is a date
  if (_.isPlainObject(expression) && !_.isDate(expression)) {
    return _.reduce(expression, function (obj, val, modifier) {

      // Handle `not` by transforming to $not, $ne or $nin
      if (modifier === '!' || modifier.toLowerCase() === 'not') {

        if (_.isPlainObject(val) && !_.has(val, '_bsontype')) {
          obj['$not'] = self.parseExpression(field, val);
          return obj;
        }

        modifier = _.isArray(val) ? '$nin' : '$ne';
        val = self.parseValue(field, modifier, val);
        obj[modifier] = val;
        return obj;
      }

      // WQL Evaluation Modifiers for String
      if (_.isString(val)) {
        // Handle `contains` by building up a case insensitive regex
        if(modifier === 'contains') {
          val = utils.caseInsensitive(val);
          val =  '.*' + val + '.*';
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }

        // Handle `like`
        if(modifier === 'like') {
          val = utils.caseInsensitive(val);
          val = val.replace(/%/g, '.*');
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }

        // Handle `startsWith` by setting a case-insensitive regex
        if(modifier === 'startsWith') {
          val = utils.caseInsensitive(val);
          val =  val + '.*';
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }

        // Handle `endsWith` by setting a case-insensitive regex
        if(modifier === 'endsWith') {
          val = utils.caseInsensitive(val);
          val =  '.*' + val;
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }
      }

      // Handle `lessThan` by transforming to $lt
      if(modifier === '<' || modifier === 'lessThan' || modifier.toLowerCase() === 'lt') {
        obj['$lt'] = self.parseValue(field, modifier, val);
        return obj;
      }

      // Handle `lessThanOrEqual` by transforming to $lte
      if(modifier === '<=' || modifier === 'lessThanOrEqual' || modifier.toLowerCase() === 'lte') {
        obj['$lte'] = self.parseValue(field, modifier, val);
        return obj;
      }

      // Handle `greaterThan` by transforming to $gt
      if(modifier === '>' || modifier === 'greaterThan' || modifier.toLowerCase() === 'gt') {
        obj['$gt'] = self.parseValue(field, modifier, val);
        return obj;
      }

      // Handle `greaterThanOrEqual` by transforming to $gte
      if(modifier === '>=' || modifier === 'greaterThanOrEqual' || modifier.toLowerCase() === 'gte') {
        obj['$gte'] = self.parseValue(field, modifier, val);
        return obj;
      }

      obj[modifier] = self.parseValue(field, modifier, val);
      return obj;
    }, {});
  }

  // <expression> ::= [value, ...], normalize array into mongo $in operator expression
  if (_.isArray(expression)) {
    return { $in: self.parseValue(field, '$in', expression) };
  }

  // <expression> ::= <value>, default equal expression
  return self.parseValue(field, undefined, expression);
};
Example #11
0
    return _.reduce(expression, function (obj, val, modifier) {

      // Handle `not` by transforming to $not, $ne or $nin
      if (modifier === '!' || modifier.toLowerCase() === 'not') {

        if (_.isPlainObject(val) && !_.has(val, '_bsontype')) {
          obj['$not'] = self.parseExpression(field, val);
          return obj;
        }

        modifier = _.isArray(val) ? '$nin' : '$ne';
        val = self.parseValue(field, modifier, val);
        obj[modifier] = val;
        return obj;
      }

      // WQL Evaluation Modifiers for String
      if (_.isString(val)) {
        // Handle `contains` by building up a case insensitive regex
        if(modifier === 'contains') {
          val = utils.caseInsensitive(val);
          val =  '.*' + val + '.*';
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }

        // Handle `like`
        if(modifier === 'like') {
          val = utils.caseInsensitive(val);
          val = val.replace(/%/g, '.*');
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }

        // Handle `startsWith` by setting a case-insensitive regex
        if(modifier === 'startsWith') {
          val = utils.caseInsensitive(val);
          val =  val + '.*';
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }

        // Handle `endsWith` by setting a case-insensitive regex
        if(modifier === 'endsWith') {
          val = utils.caseInsensitive(val);
          val =  '.*' + val;
          obj['$regex'] = new RegExp('^' + val + '$', 'i');
          return obj;
        }
      }

      // Handle `lessThan` by transforming to $lt
      if(modifier === '<' || modifier === 'lessThan' || modifier.toLowerCase() === 'lt') {
        obj['$lt'] = self.parseValue(field, modifier, val);
        return obj;
      }

      // Handle `lessThanOrEqual` by transforming to $lte
      if(modifier === '<=' || modifier === 'lessThanOrEqual' || modifier.toLowerCase() === 'lte') {
        obj['$lte'] = self.parseValue(field, modifier, val);
        return obj;
      }

      // Handle `greaterThan` by transforming to $gt
      if(modifier === '>' || modifier === 'greaterThan' || modifier.toLowerCase() === 'gt') {
        obj['$gt'] = self.parseValue(field, modifier, val);
        return obj;
      }

      // Handle `greaterThanOrEqual` by transforming to $gte
      if(modifier === '>=' || modifier === 'greaterThanOrEqual' || modifier.toLowerCase() === 'gte') {
        obj['$gte'] = self.parseValue(field, modifier, val);
        return obj;
      }

      obj[modifier] = self.parseValue(field, modifier, val);
      return obj;
    }, {});
Example #12
0
    build: function(inputFilePath, outputFilePath, outputCharset, depFile, traverse){
        var self = this,
            targets = [],
            result = {
                'success': true,
                'files': []
            },
            combo = [];
        if(_.isString(inputFilePath)){
            var target = path.resolve(inputFilePath);
            if(fs.existsSync(target)){
                if(fs.statSync(target).isDirectory()){
//                    var files = fs.readdirSync(target);
                    _.forEach(utils.traverseDirSync(target, traverse), function(file){
                        var inputFile = path.resolve(target, file),
                            outputFile = path.resolve(outputFilePath, path.relative(target, file));
                        if(path.extname(inputFile) === '.js'){
                            targets.push({
                                src: inputFile,
                                dest: outputFile
                            });
                        }
                    });
                }else{
                    targets.push({
                        src: target,
                        dest: outputFilePath
                    });
                }
            }else{
                // MC.build('pkgName/abc');
                // in this case, package must be configured.
                var modulePath = getModulePath(inputFilePath, self._config);
                if(modulePath){
                    targets.push({
                        src: modulePath,
                        dest: outputFilePath
                    });
                }
            }
        }else if(_.isPlainObject(inputFilePath)){
            _.forEach(inputFilePath, function(file){
                if(fs.src){
                    targets.push({
                        src: file.src,
                        dest: file.dest ? file.dest : path.dirname(file.src)
                    });
                }
            });
        }else if(_.isArray(inputFilePath)){
            var destIsArray = _.isArray(outputFilePath) ? outputFilePath : false;
            _.forEach(inputFilePath, function(file, index){
                targets.push({
                    src: file,
                    dest: destIsArray && outputFilePath[index] ? outputFilePath[index] : outputFilePath
                });
            });
        }

        _.forEach(targets, function(file, index){
            self._config = parseConfig.check(self._config, file.src);
            var config = _.cloneDeep(self._config);
            var kmc = new Compiler(config);
            var re = kmc.build(file.src, file.dest, outputCharset);
            re.modules = kmc.modules;
            depFile && combo.push(re.autoCombo);
            result.files.push(re);
        });
        result.success = result.files.length !== 0;

        if(depFile){
            utils.writeFileSync(path.resolve(path.dirname(outputFilePath), depFile), utils.joinCombo(combo), outputCharset);
        }

        return result;
    },
Example #13
0
  /**
   * @name requestObject
   * @api public
   */
  requestObject(request = {}, algorithms = {}) {
    assert(_.isPlainObject(request), 'pass a plain object as the first argument');

    _.defaults(algorithms, {
      sign: this.request_object_signing_alg,
      encrypt: {
        alg: this.request_object_encryption_alg,
        enc: this.request_object_encryption_enc,
      },
    }, {
      sign: 'none',
    });

    const signed = (() => {
      const alg = algorithms.sign;
      const header = { alg, typ: 'JWT' };
      const payload = JSON.stringify(_.defaults({}, request, {
        iss: this.client_id,
        aud: this.issuer.issuer,
        client_id: this.client_id,
      }));

      if (alg === 'none') {
        return Promise.resolve([
          base64url.encode(JSON.stringify(header)),
          base64url.encode(payload),
          '',
        ].join('.'));
      }

      const symmetrical = alg.startsWith('HS');

      const getKey = (() => {
        if (symmetrical) return this.joseSecret();
        const { keystore } = instance(this);

        assert(keystore, `no keystore present for client, cannot sign using ${alg}`);
        const key = keystore.get({ alg, use: 'sig' });
        assert(key, `no key to sign with found for ${alg}`);
        return Promise.resolve(key);
      })();

      return getKey
        .then(key => jose.JWS.createSign({
          fields: header,
          format,
        }, { key, reference: !symmetrical }))
        .then(sign => sign.update(payload).final());
    })();

    if (!algorithms.encrypt.alg) return signed;
    const fields = { alg: algorithms.encrypt.alg, enc: algorithms.encrypt.enc, cty: 'JWT' };

    let keystoreOrSecret;
    if (fields.alg.match(/^(RSA|ECDH)/)) {
      keystoreOrSecret = this.issuer.key({
        alg: fields.alg,
        enc: fields.enc,
        use: 'enc',
      }, true);
    } else {
      keystoreOrSecret = this.joseSecret(fields.alg);
    }

    /* eslint-disable arrow-body-style */
    return keystoreOrSecret.then((key) => {
      return signed.then((cleartext) => {
        return jose.JWE.createEncrypt({ format, fields }, { key, reference: key.kty !== 'oct' })
          .update(cleartext)
          .final();
      });
    });
    /* eslint-enable arrow-body-style */
  }
  return function swaggerMetadata (req, res, next) {
    var method = req.method.toLowerCase();
    var path = parseurl(req).pathname;
    var cacheEntry;
    var match;
    var metadata;

    cacheEntry = apiCache[path] || _.find(apiCache, function (metadata) {
      match = metadata.re.exec(path);
      return _.isArray(match);
    });

    debug('%s %s', req.method, req.url);
    debug('  Is a Swagger path: %s', !_.isUndefined(cacheEntry));

    // Request does not match an API defined in the Swagger document(s)
    if (!cacheEntry) {
      return next();
    }

    metadata = swaggerVersion === '1.2' ?
      {
        api: cacheEntry.api,
        apiDeclaration: cacheEntry.apiDeclaration,
        apiIndex: cacheEntry.apiIndex,
        params: {},
        resourceIndex: cacheEntry.resourceIndex,
        resourceListing: cacheEntry.resourceListing
      } :
    {
      apiPath : cacheEntry.apiPath,
      path: cacheEntry.path,
      params: {},
      swaggerObject: cacheEntry.swaggerObject.resolved
    };

    if (_.isPlainObject(cacheEntry.operations[method])) {
      metadata.operation = cacheEntry.operations[method].operation;
      metadata.operationPath = cacheEntry.operations[method].operationPath;

      if (swaggerVersion === '1.2') {
        metadata.authorizations = metadata.operation.authorizations || cacheEntry.apiDeclaration.authorizations;
      } else {
        metadata.operationParameters = cacheEntry.operations[method].operationParameters;
        metadata.security = metadata.operation.security || metadata.swaggerObject.security || [];
      }
    }

    metadata.swaggerVersion = swaggerVersion;

    req.swagger = metadata;

    debug('  Is a Swagger operation: %s', !_.isUndefined(metadata.operation));

    if (metadata.operation) {
      // Process the operation parameters
      return processOperationParameters(swaggerVersion, cacheEntry.keys, match, req, res, next, debug);
    } else {
      return next();
    }
  };
Example #15
0
  constructor(source, target, options) {
    super(source, target, options);

    this.associationType = 'HasMany';
    this.targetAssociation = null;
    this.sequelize = source.sequelize;
    this.isMultiAssociation = true;
    this.foreignKeyAttribute = {};

    if (this.options.through) {
      throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
    }

    /*
    * If self association, this is the target association
    */
    if (this.isSelfAssociation) {
      this.targetAssociation = this;
    }

    if (this.as) {
      this.isAliased = true;

      if (_.isPlainObject(this.as)) {
        this.options.name = this.as;
        this.as = this.as.plural;
      } else {
        this.options.name = {
          plural: this.as,
          singular: Utils.singularize(this.as)
        };
      }
    } else {
      this.as = this.target.options.name.plural;
      this.options.name = this.target.options.name;
    }

    /*
     * Foreign key setup
     */
    if (_.isObject(this.options.foreignKey)) {
      this.foreignKeyAttribute = this.options.foreignKey;
      this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
    } else if (this.options.foreignKey) {
      this.foreignKey = this.options.foreignKey;
    }

    if (!this.foreignKey) {
      this.foreignKey = Utils.camelize(
        [
          this.source.options.name.singular,
          this.source.primaryKeyAttribute
        ].join('_')
      );
    }

    if (this.target.rawAttributes[this.foreignKey]) {
      this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
      this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
    }

    /*
     * Source key setup
     */
    this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;

    if (this.source.rawAttributes[this.sourceKey]) {
      this.sourceKeyAttribute = this.sourceKey;
      this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
      if(this.sequelize.options.dialect === 'db2' && 
         !this.source.rawAttributes[this.sourceKey].primaryKey) {
          this.source.rawAttributes[this.sourceKey].allowNull=false;
          this.source.rawAttributes[this.sourceKey].unique = true;
      }
    } else {
      this.sourceKeyAttribute = this.source.primaryKeyAttribute;
      this.sourceKeyField = this.source.primaryKeyField;
    }

    // Get singular and plural names
    // try to uppercase the first letter, unless the model forbids it
    const plural = _.upperFirst(this.options.name.plural);
    const singular = _.upperFirst(this.options.name.singular);

    this.associationAccessor = this.as;
    this.accessors = {
      get: 'get' + plural,
      set: 'set' + plural,
      addMultiple: 'add' + plural,
      add: 'add' + singular,
      create: 'create' + singular,
      remove: 'remove' + singular,
      removeMultiple: 'remove' + plural,
      hasSingle: 'has' + singular,
      hasAll: 'has' + plural,
      count: 'count' + plural
    };
  }
Example #16
0
Compiler.prototype.analyze = function(inputFilePath){
    var self = this,
        mod = null,
        modRequires,
        modName,
        modPkg,
        modType,
        modVersion,
        modRealPath;
    if(!inputFilePath) return null;
    // analyze module package
    modPkg = self._getPackage(inputFilePath);
    switch (modPkg){
        case null:
            !self.config.silent && console.log('cannot get package for %s, use the first path in require path instead.', inputFilePath);
            mod = {
                name: inputFilePath,
                pkg: self._getModuleNameFromRequire(inputFilePath),
                status: 'missing'
            };
            self.modules[mod.name] = mod;
            break;
        case 'kissy':
            mod = {
                name: inputFilePath,
                pkg: 'kissy',
                status: 'ok'
            };
            self.modules[mod.name] = mod;
            break;
        case 'gallery':
            mod = {
                name: inputFilePath,
                pkg: 'gallery',
                status: 'ok'
            };
            self.modules[mod.name] = mod;
            break;
        default :
            // get module real path based on package path.
            modRealPath = self._getModuleRealPathByPkg(inputFilePath, modPkg);
            if(!self._isFileIgnored(modRealPath)){
                modName = self._moduleName(modRealPath, modPkg);
                // map module names if user configured map rules.
                modName = self._mapModuleName(modName);
                var modAlias = self._alias(modName);
                if(modAlias){
                    modName = modAlias.name;
                    modPkg = modAlias.pkg;
                    modRealPath = modAlias.path;
                }
                if(_.indexOf(self.fileList, modRealPath) === -1){
                    // to avoid recursive analyze.
                    self.fileList.push(modRealPath);
                    if(!modRealPath.match(/\.css$/)){
                        // get this file's dependencies.
                        modRequires = dependencies.getRequiresFromFn(modRealPath, !self.config.silent);
                        if(modRequires.length){
                            modVersion = '1.4+';
                        }else{
                            modRequires = dependencies.requires(modRealPath);
                        }
                        // if user named module himself, use his name. map rules will not work then.
                        if(_.isPlainObject(modRequires) && modRequires.name){
                            modName = modRequires.name;
                            modRequires = modRequires.deps;
                        }
                        modType = 'js';
                    }else{
                        modRequires = [];
                        modType = 'css';
                    }
                    var isModExcluded = self._isModuleExcluded(modName);
                    // add this module to list.
                    mod = {
                        name: modName,
                        pkg: modPkg,
                        status: isModExcluded ? 'excluded' : 'ok',
                        path: modRealPath,
                        requires: modRequires,
                        dependencies: [],
                        dependencyTree: {},
                        charset: modPkg.charset,
                        type: modType,
                        version: modVersion
                    };
                    self.modules[modName] = mod;

                    if(modType === 'js'){
                        // analyze sub modules' dependencies recursively.
                        _.forEach(modRequires, function(subModPath){
                            var subMod = self.analyze(self._getModuleRealPathByParent(subModPath, mod));
                            if(subMod){
                                mod.dependencies.push(subMod);
                                mod.dependencyTree[subMod.name] = subMod.dependencyTree;
                            }
                        });

                        !isModExcluded && self.analyzedModules.push(modName);
                    }
                }else{
                    mod = self.modules[modName];
                }
            }
            break;
    }
    return mod;
};
Example #17
0
 associations.models = _.filter(associations.models, function(model) {
   var vals = valuesObject.originalValues[model];
   return _.isPlainObject(vals) || Array.isArray(vals) ? true : false;
 });
Example #18
0
 it('clones to an object', function () {
   expect(_.isPlainObject(_.clone(reg))).to.be(true);
   expect(_.isArray(_.clone(reg))).to.be(false);
 });
 req['check' + _.capitalize(location)] = function(param, failMsg) {
   if (_.isPlainObject(param)) {
     return validateSchema(param, req, location, options);
   }
   return new ValidatorChain(param, failMsg, req, location, options);
 };
Example #20
0
  readEvent(event) {
    const data = {
      type: event.event,
      '@timestamp': event.timestamp,
      tags: [].concat(event.tags || []),
      pid: event.pid
    };

    if (data.type === 'response') {
      _.defaults(data, _.pick(event, [
        'method',
        'statusCode'
      ]));

      data.req = {
        url: event.path,
        method: event.method,
        headers: event.headers,
        remoteAddress: event.source.remoteAddress,
        userAgent: event.source.remoteAddress,
        referer: event.source.referer
      };

      let contentLength = 0;
      if (typeof event.responsePayload === 'object') {
        contentLength = stringify(event.responsePayload).length;
      } else {
        contentLength = String(event.responsePayload).length;
      }

      data.res = {
        statusCode: event.statusCode,
        responseTime: event.responseTime,
        contentLength: contentLength
      };

      const query = querystring.stringify(event.query);
      if (query) data.req.url += '?' + query;


      data.message  = data.req.method.toUpperCase() + ' ';
      data.message += data.req.url;
      data.message += ' ';
      data.message += levelColor(data.res.statusCode);
      data.message += ' ';
      data.message += ansicolors.brightBlack(data.res.responseTime + 'ms');
      data.message += ansicolors.brightBlack(' - ' + numeral(contentLength).format('0.0b'));
    }
    else if (data.type === 'ops') {
      _.defaults(data, _.pick(event, [
        'pid',
        'os',
        'proc',
        'load'
      ]));
      data.message  = ansicolors.brightBlack('memory: ');
      data.message += numeral(data.proc.mem.heapUsed).format('0.0b');
      data.message += ' ';
      data.message += ansicolors.brightBlack('uptime: ');
      data.message += numeral(data.proc.uptime).format('00:00:00');
      data.message += ' ';
      data.message += ansicolors.brightBlack('load: [');
      data.message += data.os.load.map(function (val) {
        return numeral(val).format('0.00');
      }).join(' ');
      data.message += ansicolors.brightBlack(']');
      data.message += ' ';
      data.message += ansicolors.brightBlack('delay: ');
      data.message += numeral(data.proc.delay).format('0.000');
    }
    else if (data.type === 'error') {
      data.level = 'error';
      data.message = event.error.message;
      data.error = serializeError(event.error);
      data.url = event.url;
    }
    else if (event.data instanceof Error) {
      data.level = _.contains(event.tags, 'fatal') ? 'fatal' : 'error';
      data.message = event.data.message;
      data.error = serializeError(event.data);
    }
    else if (_.isPlainObject(event.data) && event.data.tmpl) {
      _.assign(data, event.data);
      data.tmpl = undefined;
      data.message = _.template(event.data.tmpl)(event.data);
    }
    else {
      data.message = _.isString(event.data) ? event.data : inspect(event.data);
    }
    return data;
  }
Example #21
0
function validateObject(object) {
  if (!(_.isPlainObject(object) || _.isArray(object))) {
    throw new Error('Specified object should be an Object or Array');
  }
}
 .transform(function(data) {
   if (_.isPlainObject(data)) { return analysisConfig.parse(data); }
 })
Example #23
0
  function validate({ possible, actual, optional }) {
    const nothingPossible = !possible || (Array.isArray(possible) && !possible.length)

    if (nothingPossible && actual === true) { return }

    if (actual == null) {
      if (nothingPossible || optional) { return }
      complain(`Expected option value for rule "${ruleName}"`)
      return
    } else if (nothingPossible) {
      complain(`Unexpected option value "${actual}" for rule "${ruleName}"`)
      return
    }

    // If `possible` is a function ...
    if (isFunction(possible)) {
      if (!possible(actual)) {
        complain(`Invalid option "${JSON.stringify(actual)}" for rule ${ruleName}`)
      }
      return
    }

    // If `possible` is an array instead of an object ...
    if (!isPlainObject(possible)) {
      [].concat(actual).forEach(a => {
        if (isValid(possible, a)) { return }
        complain(`Invalid option value "${a}" for rule "${ruleName}"`)
      })
      return
    }

    // If possible is an object ...
    if (!isPlainObject(actual)) {
      complain(
        `Invalid option value ${JSON.stringify(actual)} for rule "${ruleName}": ` +
        `should be an object`
      )
      return
    }

    Object.keys(actual).forEach(optionName => {
      if (ignoredOptions.indexOf(optionName) !== -1) { return }

      if (!possible[optionName]) {
        complain(`Invalid option name "${optionName}" for rule "${ruleName}"`)
        return
      }

      const actualOptionValue = actual[optionName]

      ;[].concat(actualOptionValue).forEach(a => {
        if (isValid(possible[optionName], a)) { return }
        complain(`Invalid value "${a}" for option "${optionName}" of rule "${ruleName}"`)
      })
    })

    function complain(message) {
      noErrors = false
      result.warn(message)
    }
  }
Example #24
0
Outgoing.prototype.reqMktData = function (tickerId, contract, genericTickList, snapshot) {
  if (this._controller._serverVersion < C.MIN_SERVER_VER.SNAPSHOT_MKT_DATA && snapshot) {
    return this._controller.emitError('It does not support snapshot market data requests.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.UNDER_COMP) {
    return this._controller.emitError('It does not support delta-neutral orders.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.REQ_MKT_DATA_CONID) {
    return this._controller.emitError('It does not support conId parameter.');
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRADING_CLASS) {
    if (!_.isEmpty(contract.tradingClass)) {
      return this._controller.emitError('It does not support tradingClass parameter in reqMarketData.');
    }
  }

  var version = 10;

  var args = [C.OUTGOING.REQ_MKT_DATA, version, tickerId];

  // send contract fields
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.REQ_MKT_DATA_CONID) {
    args.push(contract.conId);
  }
  args.push(contract.symbol);
  args.push(contract.secType);
  args.push(contract.expiry);
  args.push(contract.strike);
  args.push(contract.right);

  if (this._controller._serverVersion >= 15) {
    args.push(contract.multiplier);
  }

  args.push(contract.exchange);

  if (this._controller._serverVersion >= 14) {
    args.push(contract.primaryExch);
  }

  args.push(contract.currency);

  if (this._controller._serverVersion >= 2) {
    args.push(contract.localSymbol);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRADING_CLASS) {
    args.push(contract.tradingClass);
  }

  if (this._controller._serverVersion >= 8 &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(contract.comboLegs)) {
      args.push(0);
    } else {
      args.push(contract.comboLegs.length);
      contract.comboLegs.forEach(function (comboLeg) {
        args.push(comboLeg.conId);
        args.push(comboLeg.ratio);
        args.push(comboLeg.action);
        args.push(comboLeg.exchange);
      });
    }
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.UNDER_COMP) {
    if (_.isPlainObject(contract.underComp)) {
      args.push(true);
      args.push(contract.underComp.conId);
      args.push(contract.underComp.delta);
      args.push(contract.underComp.price);
    } else {
      args.push(false);
    }
  }

  if (this._controller._serverVersion >= 31) {
    /*
     * Note: Even though SHORTABLE tick type supported only
     *       starting server version 33 it would be relatively
     *       expensive to expose this restriction here.
     *
     *       Therefore we are relying on TWS doing validation.
     */
    args.push(genericTickList);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SNAPSHOT_MKT_DATA) {
    args.push(snapshot);
  }

  this._send(args);
};
Example #25
0
File: app.js Project: yawo/pepeto
 onEnter: function () {
   if (_.isPlainObject(global.config) && !!global.config.catchAll) {
     global.location.replace('/404.html');
   }
 }
Example #26
0
Outgoing.prototype.placeOrder = function (id, contract, order) {
  var comboLeg,
      orderComboLeg;

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_ORDERS) {
    if (order.scaleInitLevelSize != Number.MAX_VALUE ||
        order.scalePriceIncrement != Number.MAX_VALUE) {
      return this._controller.emitError('It does not support Scale orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SSHORT_COMBO_LEGS) {
    if (_.isArray(contract.comboLegs)) {
      contract.comboLegs.forEach(function (comboLeg) {
        if (comboLeg.shortSaleSlot !== 0 || !_.isEmpty(comboLeg.designatedLocation)) {
          return this._controller.emitError('It does not support SSHORT flag for combo legs.');
        }
      });
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.WHAT_IF_ORDERS) {
    if (order.whatIf) {
      return this._controller.emitError('It does not support what-if orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.UNDER_COMP) {
    if (contract.underComp) {
      return this._controller.emitError('It does not support delta-neutral orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_ORDERS2) {
    if (order.scaleSubsLevelSize !== Number.MAX_VALUE) {
      return this._controller.emitError('It does not support Subsequent Level Size for Scale orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.ALGO_ORDERS) {
    if (!_.isEmpty(order.algoStrategy)) {
      return this._controller.emitError('It does not support algo orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.NOT_HELD) {
    if (order.notHeld) {
      return this._controller.emitError('It does not support notHeld parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SEC_ID_TYPE) {
    if (!_.isEmpty(contract.secIdType) || !_.isEmpty(contract.secId)) {
      return this._controller.emitError('It does not support secIdType and secId parameters.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.PLACE_ORDER_CONID) {
    if (contract.conId > 0) {
      return this._controller.emitError('It does not support conId parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SSHORTX) {
    if (order.exemptCode !== -1) {
      return this._controller.emitError('It does not support exemptCode parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SSHORTX) {
    if (_.isArray(contract.comboLegs)) {
      contract.comboLegs.forEach(function (comboLeg) {
        if (comboLeg.exemptCode !== -1) {
          return this._controller.emitError('It does not support exemptCode parameter.');
        }
      });
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.HEDGE_ORDERS) {
    if (!_.isEmpty(order.hedgeType)) {
      return this._controller.emitError('It does not support hedge orders.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.OPT_OUT_SMART_ROUTING) {
    if (order.optOutSmartRouting) {
      return this._controller.emitError('It does not support optOutSmartRouting parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.DELTA_NEUTRAL_CONID) {
    if (order.deltaNeutralConId > 0 ||
        !_.isEmpty(order.deltaNeutralSettlingFirm) ||
        !_.isEmpty(order.deltaNeutralClearingAccount) ||
        !_.isEmpty(order.deltaNeutralClearingIntent)) {
      return this._controller.emitError('It does not support deltaNeutral parameters: ConId, SettlingFirm, ClearingAccount, ClearingIntent.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.DELTA_NEUTRAL_OPEN_CLOSE) {
    if (!_.isEmpty(order.deltaNeutralOpenClose) ||
        order.deltaNeutralShortSale ||
        order.deltaNeutralShortSaleSlot > 0 ||
        !_.isEmpty(order.deltaNeutralDesignatedLocation)) {
      return this._controller.emitError('It does not support deltaNeutral parameters: OpenClose, ShortSale, ShortSaleSlot, DesignatedLocation.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_ORDERS3) {
    if (order.scalePriceIncrement > 0 && order.scalePriceIncrement != Number.MAX_VALUE) {
      if (order.scalePriceAdjustValue !== Number.MAX_VALUE ||
          order.scalePriceAdjustInterval !== Number.MAX_VALUE ||
          order.scaleProfitOffset !== Number.MAX_VALUE ||
          order.scaleAutoReset ||
          order.scaleInitPosition !== Number.MAX_VALUE ||
          order.scaleInitFillQty !== Number.MAX_VALUE ||
          order.scaleRandomPercent) {
        return this._controller.emitError('It does not support Scale order parameters: PriceAdjustValue, PriceAdjustInterval, ProfitOffset, AutoReset, InitPosition, InitFillQty and RandomPercent');
      }
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.ORDER_COMBO_LEGS_PRICE &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (_.isArray(order.orderComboLegs)) {
      order.orderComboLegs.forEach(function (orderComboLeg) {
        if (orderComboLeg.price !== Number.MAX_VALUE) {
          return this._controller.emitError('It does not support per-leg prices for order combo legs.');
        }
      });
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRAILING_PERCENT) {
    if (order.trailingPercent !== Number.MAX_VALUE) {
      return this._controller.emitError('It does not support trailing percent parameter.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRADING_CLASS) {
    if (!_.isEmpty(contract.tradingClass)) {
      return this._controller.emitError('It does not support tradingClass parameters in placeOrder.');
    }
  }

  if (this._controller._serverVersion < C.MIN_SERVER_VER.SCALE_TABLE) {
    if (!_.isEmpty(order.scaleTable) ||
        !_.isEmpty(order.activeStartTime) ||
        !_.isEmpty(order.activeStopTime)) {
      return this._controller.emitError('It does not support scaleTable, activeStartTime and activeStopTime parameters.');
    }
  }

  var version = (this._controller._serverVersion < C.MIN_SERVER_VER.NOT_HELD ? 27 : 41);

  // send place order msg
  var args = [C.OUTGOING.PLACE_ORDER, version, id];

  // send contract fields
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.PLACE_ORDER_CONID) {
    args.push(contract.conId);
  }
  args.push(contract.symbol);
  args.push(contract.secType);
  args.push(contract.expiry);
  args.push(contract.strike);
  args.push(contract.right);
  if (this._controller._serverVersion >= 15) {
    args.push(contract.multiplier);
  }
  args.push(contract.exchange);
  if (this._controller._serverVersion >= 14) {
    args.push(contract.primaryExch);
  }
  args.push(contract.currency);
  if (this._controller._serverVersion >= 2) {
    args.push(contract.localSymbol);
  }
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRADING_CLASS) {
    args.push(contract.tradingClass);
  }
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SEC_ID_TYPE){
    args.push(contract.secIdType);
    args.push(contract.secId);
  }

  // send main order fields
  args.push(order.action);
  args.push(order.totalQuantity);
  args.push(order.orderType);
  if (this._controller._serverVersion < C.MIN_SERVER_VER.ORDER_COMBO_LEGS_PRICE) {
    args.push(order.lmtPrice === Number.MAX_VALUE ? 0 : order.lmtPrice);
  } else {
    args.push(_nullifyMax(order.lmtPrice));
  }
  if (this._controller._serverVersion < C.MIN_SERVER_VER.TRAILING_PERCENT) {
    args.push(order.auxPrice === Number.MAX_VALUE ? 0 : order.auxPrice);
  } else {
    args.push(_nullifyMax(order.auxPrice));
  }

  // send extended order fields
  args.push(order.tif);
  args.push(order.ocaGroup);
  args.push(order.account);
  args.push(order.openClose);
  args.push(order.origin);
  args.push(order.orderRef);
  args.push(order.transmit);
  if (this._controller._serverVersion >= 4) {
    args.push(order.parentId);
  }

  if (this._controller._serverVersion >= 5) {
    args.push(order.blockOrder);
    args.push(order.sweepToFill);
    args.push(order.displaySize);
    args.push(order.triggerMethod);
    if (this._controller._serverVersion < 38) {
      // will never happen
      args.push(/* order.ignoreRth */ false);
    } else {
      args.push(order.outsideRth);
    }
  }

  if (this._controller._serverVersion >= 7) {
    args.push(order.hidden);
  }

  // Send combo legs for BAG requests
  if (this._controller._serverVersion >= 8 &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(contract.comboLegs)) {
      args.push(0);
    } else {
      args.push(contract.comboLegs.length);

      contract.comboLegs.forEach(function (comboLeg) {
        args.push(comboLeg.conId);
        args.push(comboLeg.ratio);
        args.push(comboLeg.action);
        args.push(comboLeg.exchange);
        args.push(comboLeg.openClose);

        if (this._controller._serverVersion >= C.MIN_SERVER_VER.SSHORT_COMBO_LEGS) {
          args.push(comboLeg.shortSaleSlot);
          args.push(comboLeg.designatedLocation);
        }
        if (this._controller._serverVersion >= C.MIN_SERVER_VER.SSHORTX_OLD) {
          args.push(comboLeg.exemptCode);
        }
      });
    }
  }

  // Send order combo legs for BAG requests
  if (this._controller._serverVersion >= C.MIN_SERVER_VER.ORDER_COMBO_LEGS_PRICE &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    if (!_.isArray(order.orderComboLegs)) {
      args.push(0);
    } else {
      args.push(order.orderComboLegs.length);
      order.orderComboLegs.forEach(function (orderComboLeg) {
        args.push(_nullifyMax(orderComboLeg.price));
      });
    }
  }

  var smartComboRoutingParamsCount;

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SMART_COMBO_ROUTING_PARAMS &&
      _.isString(contract.secType) &&
      C.BAG_SEC_TYPE.toUpperCase() === contract.secType.toUpperCase()) {
    smartComboRoutingParamsCount = !_.isArray(order.smartComboRoutingParams) ? 0 : order.smartComboRoutingParams.length;
    args.push(smartComboRoutingParamsCount);

    if (smartComboRoutingParamsCount > 0) {
      order.smartComboRoutingParams.forEach(function (tagValue) {
        args.push(tagValue.tag);
        args.push(tagValue.value);
      });
    }
  }

  if (this._controller._serverVersion >= 9) {
    // send deprecated sharesAllocation field
    args.push('');
  }

  if (this._controller._serverVersion >= 10) {
    args.push(order.discretionaryAmt);
  }

  if (this._controller._serverVersion >= 11) {
    args.push(order.goodAfterTime);
  }

  if (this._controller._serverVersion >= 12) {
    args.push(order.goodTillDate);
  }

  if (this._controller._serverVersion >= 13) {
    args.push(order.faGroup);
    args.push(order.faMethod);
    args.push(order.faPercentage);
    args.push(order.faProfile);
  }

  if (this._controller._serverVersion >= 18) {  // institutional short sale slot fields.
    args.push(order.shortSaleSlot);       // 0 only for retail, 1 or 2 only for institution.
    args.push(order.designatedLocation);  // only populate when order.shortSaleSlot = 2.
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SSHORTX_OLD) {
    args.push(order.exemptCode);
  }

  var lower;
  var upper;

  if (this._controller._serverVersion >= 19) {
    args.push(order.ocaType);

    if (this._controller._serverVersion < 38) {
      // will never happen
      args.push(/* order.rthOnly */ false);
    }

    args.push(order.rule80A);
    args.push(order.settlingFirm);
    args.push(order.allOrNone);
    args.push(_nullifyMax(order.minQty));
    args.push(_nullifyMax(order.percentOffset));
    args.push(order.eTradeOnly);
    args.push(order.firmQuoteOnly);
    args.push(_nullifyMax(order.nbboPriceCap));
    args.push(_nullifyMax(order.auctionStrategy));
    args.push(_nullifyMax(order.startingPrice));
    args.push(_nullifyMax(order.stockRefPrice));
    args.push(_nullifyMax(order.delta));

    // Volatility orders had specific watermark price attribs in server version 26
    lower = ((this._controller._serverVersion == 26 && order.orderType === 'VOL') ?
        Number.MAX_VALUE :
        order.stockRangeLower);
    upper = (this._controller._serverVersion == 26 && order.orderType === 'VOL') ?
      Number.MAX_VALUE :
      order.stockRangeUpper;
    args.push(_nullifyMax(lower));
    args.push(_nullifyMax(upper));
  }

  if (this._controller._serverVersion >= 22) {
    args.push(order.overridePercentageConstraints);
  }

  if (this._controller._serverVersion >= 26) { // Volatility orders
     args.push(_nullifyMax(order.volatility));
     args.push(_nullifyMax(order.volatilityType));

    if (this._controller._serverVersion < 28) {
      args.push(order.deltaNeutralOrderType.toUpperCase() === 'MKT');
    } else {
      args.push(order.deltaNeutralOrderType);
      args.push(_nullifyMax(order.deltaNeutralAuxPrice));

      if (this._controller._serverVersion >= C.MIN_SERVER_VER.DELTA_NEUTRAL_CONID &&
          !_.isEmpty(order.deltaNeutralOrderType)){
        args.push(order.deltaNeutralConId);
        args.push(order.deltaNeutralSettlingFirm);
        args.push(order.deltaNeutralClearingAccount);
        args.push(order.deltaNeutralClearingIntent);
      }

      if (this._controller._serverVersion >= C.MIN_SERVER_VER.DELTA_NEUTRAL_OPEN_CLOSE &&
          !_.isEmpty(order.deltaNeutralOrderType)){
        args.push(order.deltaNeutralOpenClose);
        args.push(order.deltaNeutralShortSale);
        args.push(order.deltaNeutralShortSaleSlot);
        args.push(order.deltaNeutralDesignatedLocation);
      }
    }

    args.push(order.continuousUpdate);

    if (this._controller._serverVersion == 26) {
      // Volatility orders had specific watermark price attribs in server version 26
      lower = (order.orderType === 'VOL' ? order.stockRangeLower : Number.MAX_VALUE);
      upper = (order.orderType === 'VOL' ? order.stockRangeUpper : Number.MAX_VALUE);
      args.push(_nullifyMax(lower));
      args.push(_nullifyMax(upper));
    }

    args.push(_nullifyMax(order.referencePriceType));
  }

  if (this._controller._serverVersion >= 30) { // TRAIL_STOP_LIMIT stop price
    args.push(_nullifyMax(order.trailStopPrice));
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.TRAILING_PERCENT){
    args.push(_nullifyMax(order.trailingPercent));
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_ORDERS) {
    if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_ORDERS2) {
     args.push(_nullifyMax(order.scaleInitLevelSize));
     args.push(_nullifyMax(order.scaleSubsLevelSize));
    } else {
      args.push('');
      args.push(_nullifyMax(order.scaleInitLevelSize));
    }
    args.push(_nullifyMax(order.scalePriceIncrement));
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_ORDERS3 &&
      order.scalePriceIncrement > 0.0 &&
      order.scalePriceIncrement != Number.MAX_VALUE) {
    args.push(_nullifyMax(order.scalePriceAdjustValue));
    args.push(_nullifyMax(order.scalePriceAdjustInterval));
    args.push(_nullifyMax(order.scaleProfitOffset));
    args.push(order.scaleAutoReset);
    args.push(_nullifyMax(order.scaleInitPosition));
    args.push(_nullifyMax(order.scaleInitFillQty));
    args.push(order.scaleRandomPercent);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.SCALE_TABLE) {
    args.push(order.scaleTable);
    args.push(order.activeStartTime);
    args.push(order.activeStopTime);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.HEDGE_ORDERS) {
    args.push(order.hedgeType);
    if (!_.isEmpty(order.hedgeType)) {
      args.push(order.hedgeParam);
    }
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.OPT_OUT_SMART_ROUTING) {
    args.push(order.optOutSmartRouting);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.PTA_ORDERS) {
    args.push(order.clearingAccount);
    args.push(order.clearingIntent);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.NOT_HELD) {
    args.push(order.notHeld);
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.UNDER_COMP) {
    if (_.isPlainObject(contract.underComp) && !_.isEmpty(contract.underComp)) {
      args.push(true);
      args.push(contract.underComp.conId);
      args.push(contract.underComp.delta);
      args.push(contract.underComp.price);
    } else {
      args.push(false);
    }
  }

  var algoParamsCount;

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.ALGO_ORDERS) {
    args.push(order.algoStrategy);
    if (!_.isEmpty(order.algoStrategy)) {
      algoParamsCount = (!_.isArray(order.algoParams) ? 0 : order.algoParams.length);
      args.push(algoParamsCount);
      if (algoParamsCount > 0) {
        order.algoParams.forEach(function (tagValue) {
          args.push(tagValue.tag);
          args.push(tagValue.value);
        });
      }
    }
  }

  if (this._controller._serverVersion >= C.MIN_SERVER_VER.WHAT_IF_ORDERS) {
    args.push(order.whatIf);
  }

  this._send(args);
};
Example #27
0
module.exports = (ast, options) => {
  invariant(_.isPlainObject(ast), '"ast" must be a plain object')

  /**
   * @namespace QueryWrapperOptions
   */
  options = _.defaults({}, options, {
    /**
     * Return true if the node has children
     *
     * @memberof QueryWrapperOptions
     * @instance
     * @param {object} node
     * @returns {boolean}
     */
    hasChildren: (node) => Array.isArray(node.value),
    /**
     * Return an array of children for a node
     *
     * @memberof QueryWrapperOptions
     * @instance
     * @param {object} node
     * @returns {object[]}
     */
    getChildren: (node) => node.value,
    /**
     * Return a string representation of the node's type
     *
     * @memberof QueryWrapperOptions
     * @instance
     * @param {object} node
     * @returns {string}
     */
    getType: (node) => node.type,
    /**
     * Convert the node back to JSON. This usually just means merging the
     * children back into the node
     *
     * @memberof QueryWrapperOptions
     * @instance
     * @param {object} node
     * @param {object[]} [children]
     * @returns {string}
     */
    toJSON: (node, children) => {
      return Object.assign({}, node, {
        value: children || node.value
      })
    },
    /**
     * Convert the node to a string
     *
     * @memberof QueryWrapperOptions
     * @instance
     * @param {object} node
     * @returns {string}
     */
    toString: (node) => {
      return _.isString(node.value) ? node.value : ''
    }
  })

  for (let key of ['hasChildren', 'getChildren', 'getType', 'toJSON', 'toString']) {
    invariant(_.isFunction(options[key]),
      `options.${key} must be a function`)
  }

  // Commonly used options
  let { hasChildren, getChildren, getType, toJSON, toString } = options

  /**
   * Wrap an AST node to get some basic helpers / parent reference
   */
  class NodeWrapper {
    /**
     * Create a new NodeWrapper
     *
     * @param {object} node
     * @param {NodeWrapper} [parent]
     */
    constructor (node, parent) {
      /**
       * @member {object}
       */
      this.node = node
      /**
       * @member {NodeWrapper}
       */
      this.parent = parent
       /**
       * @member {NodeWrapper[]}
       */
      this.children = this.hasChildren
        ? getChildren(node).map((n) => new NodeWrapper(n, this))
        : null
      Object.freeze(this)
    }
    get hasChildren () {
      return hasChildren(this.node)
    }
    /**
     * Return the JSON representation
     *
     * @returns {object}
     */
    toJSON () {
      return toJSON(
        this.node,
        this.hasChildren ? this.children.map((n) => n.toJSON()) : null
      )
    }
    /**
     * Recursivley reduce the node and it's children
     *
     * @param {function} fn
     * @param {any} acc
     * @returns {object}
     */
    reduce (fn, acc) {
      return this.hasChildren
        ? fn(this.children.reduce((a, n) => n.reduce(fn, a), acc), this)
        : fn(acc, this)
    }
    /**
     * Create a new NodeWrapper or return the argument if it's already a NodeWrapper
     *
     * @param {object|NodeWrapper} node
     * @param {NodeWrapper} [parent]
     * @returns {NodeWrapper}
     */
    static create (node, parent) {
      if (node instanceof NodeWrapper) return node
      return new NodeWrapper(node, parent)
    }
    /**
     * Return true if the provided argument is a NodeWrapper
     *
     * @param {any} node
     * @returns {NodeWrapper}
     */
    static isNodeWrapper (node) {
      return node instanceof NodeWrapper
    }
  }

  /**
   * The root node that will be used if no argument is provided to $()
   */
  const ROOT = NodeWrapper.create(ast)

  /*
   * @typedef {string|regexp|function} Wrapper~Selector
   */

  /**
   * Return a function that will be used to filter an array of QueryWrappers
   *
   * @private
   * @param {string|function} selector
   * @param {boolean} required
   * @returns {function}
   */
  let getSelector = (selector, defaultValue) => {
    defaultValue = !_.isUndefined(defaultValue)
      ? defaultValue : (n) => true
    let isString = _.isString(selector)
    let isRegExp = _.isRegExp(selector)
    let isFunction = _.isFunction(selector)
    if (!(isString || isRegExp || isFunction)) return defaultValue
    if (isString) return (n) => getType(n.node) === selector
    if (isRegExp) return (n) => selector.test(getType(n.node))
    if (isFunction) return selector
  }

  /**
   * Convenience function to return a new Wrapper
   *
   * @private
   * @param {function|string|NodeWrapper|NodeWrapper[]} [selector]
   * @param {NodeWrapper|NodeWrapper[]} [context]
   * @returns {QueryWrapper}
   */
  let $ = (selector, context) => {
    let maybeSelector = getSelector(selector, false)
    let nodes = _.flatten([(maybeSelector ? context : selector) || ROOT])
    invariant(_.every(nodes, NodeWrapper.isNodeWrapper),
      'context must be a NodeWrapper or array of NodeWrappers')
    return maybeSelector
      ? new QueryWrapper(nodes).find(maybeSelector)
      : new QueryWrapper(nodes)
  }

  /**
   * Wrap a {@link NodeWrapper} with chainable traversal/modification functions
   */
  class QueryWrapper {
    /**
     * Create a new QueryWrapper
     *
     * @private
     * @param {NodeWrapper[]} nodes
     */
    constructor (nodes) {
      this.nodes = nodes
    }
    /**
     * Return a new wrapper filtered by a selector
     *
     * @private
     * @param {NodeWrapper[]} nodes
     * @param {function} selector
     * @returns {QueryWrapper}
     */
    $filter (nodes, selector) {
      nodes = nodes.filter(selector)
      return $(nodes)
    }
    /**
     * Return the wrapper as a JSON node or array of JSON nodes
     *
     * @param {number} [index]
     * @returns {object|object[]}
     */
    get (index) {
      return _.isInteger(index)
        ? this.nodes[index].toJSON()
        : this.nodes.map((n) => n.toJSON())
    }
    /**
     * Return the number of nodes in the wrapper
     *
     * @returns {number}
     */
    length () {
      return this.nodes.length
    }
    /**
     * Search for a given node in the set of matched nodes.
     *
     * If no argument is passed, the return value is an integer indicating
     * the position of the first node within the Wrapper relative
     * to its sibling nodes.
     *
     * If called on a collection of nodes and a NodeWrapper is passed in, the return value
     * is an integer indicating the position of the passed NodeWrapper relative
     * to the original collection.
     *
     * If a selector is passed as an argument, the return value is an integer
     * indicating the position of the first node within the Wrapper relative
     * to the nodes matched by the selector.
     *
     * If the selctor doesn't match any nodes, it will return -1.
     *
     * @param {NodeWrapper|Wrapper~Selector} [node]
     * @returns {number}
     */
    index (node) {
      if (!node) {
        let n = this.nodes[0]
        if (n) {
          let p = n.parent
          if (p && p.hasChildren) return p.children.indexOf(n)
        }
        return -1
      }
      if (NodeWrapper.isNodeWrapper(node)) {
        return this.nodes.indexOf(node)
      }
      let n = this.nodes[0]
      let p = n.parent
      if (!p.hasChildren) return -1
      let selector = getSelector(node)
      return this.$filter(p.children, selector).index(this.nodes[0])
    }
    /**
     * Insert a node after each node in the set of matched nodes
     *
     * @param {object} node
     * @returns {QueryWrapper}
     */
    after (node) {
      for (let n of this.nodes) {
        let p = n.parent
        if (!p.hasChildren) continue
        let i = $(n).index()
        if (i >= 0) p.children.splice(i + 1, 0, NodeWrapper.create(node, p))
      }
      return this
    }
    /**
     * Insert a node before each node in the set of matched nodes
     *
     * @param {object} node
     * @returns {QueryWrapper}
     */
    before (node) {
      for (let n of this.nodes) {
        let p = n.parent
        if (!p.hasChildren) continue
        let i = p.children.indexOf(n)
        if (i >= 0) p.children.splice(i, 0, NodeWrapper.create(node, p))
      }
      return this
    }
    /**
     * Remove the set of matched nodes
     *
     * @returns {QueryWrapper}
     */
    remove () {
      for (let n of this.nodes) {
        let p = n.parent
        if (!p.hasChildren) continue
        let i = p.children.indexOf(n)
        if (i >= 0) p.children.splice(i, 1)
      }
      return this
    }
    /**
     * Replace each node in the set of matched nodes by returning a new node
     * for each node that will be replaced
     *
     * @param {function} fn
     * @returns {QueryWrapper}
     */
    replace (fn) {
      for (let n of this.nodes) {
        let p = n.parent
        if (!p.hasChildren) continue
        let i = p.children.indexOf(n)
        if (i >= 0) p.children.splice(i, 1, NodeWrapper.create(fn(n), p))
      }
      return this
    }
    /**
     * Map the set of matched nodes
     *
     * @param {function} fn
     * @returns {array}
     */
    map (fn) {
      return this.nodes.map(fn)
    }
    /**
     * Reduce the set of matched nodes
     *
     * @param {function} fn
     * @param {any} acc
     * @returns {any}
     */
    reduce (fn, acc) {
      return this.nodes.reduce(fn, acc)
    }
    /**
     * Combine the nodes of two QueryWrappers
     *
     * @param {QueryWrapper} wrapper
     * @returns {any}
     */
    concat (wrapper) {
      invariant(wrapper instanceof QueryWrapper,
        'concat requires a QueryWrapper')
      return $(this.nodes.concat(wrapper.nodes))
    }
    /**
     * Get the children of each node in the set of matched nodes,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    children (selector) {
      selector = getSelector(selector)
      let nodes = _.flatMap(this.nodes, (n) => n.hasChildren ? n.children : [])
      return this.$filter(nodes, selector)
    }
    /**
     * For each node in the set of matched nodes, get the first node that matches
     * the selector by testing the node itself and traversing up through its ancestors
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    closest (selector) {
      selector = getSelector(selector)
      let nodes = _.uniq(_.flatMap(this.nodes, (n) => {
        let parent = n
        while (parent) {
          if (selector(parent)) break
          parent = parent.parent
        }
        return parent || []
      }))
      return $(nodes)
    }
    /**
     * Reduce the set of matched nodes to the one at the specified index
     *
     * @param {number} index
     * @returns {QueryWrapper}
     */
    eq (index) {
      invariant(_.isInteger(index),
        'eq() requires an index')
      return $(this.nodes[index] || [])
    }
    /**
     * Get the descendants of each node in the set of matched nodes,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    find (selector) {
      selector = getSelector(selector)
      let nodes = _.uniq(_.flatMap(this.nodes, (n) =>
        n.reduce((a, n) => selector(n) ? a.concat(n) : a, [])))
      return $(nodes)
    }
    /**
     * Reduce the set of matched nodes to those that match the selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    filter (selector) {
      selector = getSelector(selector)
      return this.$filter(this.nodes, selector)
    }
    /**
     * Reduce the set of matched nodes to the first in the set.
     *
     * @returns {QueryWrapper}
     */
    first () {
      return this.eq(0)
    }
    /**
     * Reduce the set of matched nodes to those that have a descendant
     * that matches the selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    has (selector) {
      let filter = (n) => $(n).find(selector).length() > 0
      return this.$filter(this.nodes, filter)
    }
    /**
     * Reduce the set of matched nodes to those that have a parent
     * that matches the selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    hasParent (selector) {
      let filter = (n) => $(n).parent(selector).length() > 0
      return this.$filter(this.nodes, filter)
    }
    /**
     * Reduce the set of matched nodes to those that have an ancestor
     * that matches the selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    hasParents (selector) {
      let filter = (n) => $(n).parents(selector).length() > 0
      return this.$filter(this.nodes, filter)
    }
    /**
     * Reduce the set of matched nodes to the final one in the set
     *
     * @returns {QueryWrapper}
     */
    last () {
      return this.eq(this.length() - 1)
    }
    /**
     * Get the immediately following sibling of each node in the set of matched nodes,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    next (selector) {
      selector = getSelector(selector)
      let nodes = _.flatMap(this.nodes, (n) => {
        let index = this.index()
        return index >= 0 && index < n.parent.children.length - 1
          ? n.parent.children[index + 1] : []
      })
      return this.$filter(nodes, selector)
    }
    /**
     * Get all following siblings of each node in the set of matched nodes,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    nextAll (selector) {
      selector = getSelector(selector)
      let nodes = _.flatMap(this.nodes, (n) => {
        let index = this.index()
        return index >= 0 && index < n.parent.children.length - 1
          ? _.drop(n.parent.children, index + 1) : []
      })
      return this.$filter(nodes, selector)
    }
    /**
     * Get the parent of each nodes in the current set of matched nodess,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    parent (selector) {
      selector = getSelector(selector)
      let nodes = this.nodes.map((n) => n.parent)
      return this.$filter(nodes, selector)
    }
    /**
     * Get the ancestors of each nodes in the current set of matched nodess,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    parents (selector) {
      selector = getSelector(selector)
      let nodes = _.uniq(_.flatMap(this.nodes, (n) => {
        let parents = []
        let parent = n.parent
        while (parent) {
          parents.push(parent)
          parent = parent.parent
        }
        return parents
      }))
      return this.$filter(nodes, selector)
    }
    /**
     * Get the ancestors of each node in the set of matched nodes,
     * up to but not including the node matched by the selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    parentsUntil (selector) {
      selector = getSelector(selector)
      let nodes = _.uniq(_.flatMap(this.nodes, (n) => {
        let parents = []
        let parent = n.parent
        while (parent && !selector(parent)) {
          parents.push(parent)
          parent = parent.parent
        }
        return parents
      }))
      return $(nodes)
    }
    /**
     * Get the immediately preceding sibling of each node in the set of matched nodes,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    prev (selector) {
      selector = getSelector(selector)
      let nodes = _.flatMap(this.nodes, (n) => {
        let index = this.index()
        return index > 0 ? n.parent.children[index - 1] : []
      })
      return this.$filter(nodes, selector)
    }
    /**
     * Get all preceding siblings of each node in the set of matched nodes,
     * optionally filtered by a selector
     *
     * @param {Wrapper~Selector} [selector]
     * @returns {QueryWrapper}
     */
    prevAll (selector) {
      selector = getSelector(selector)
      let nodes = _.flatMap(this.nodes, (n) => {
        let index = this.index()
        return index > 0 ? _.take(n.parent.children, index).reverse() : []
      })
      return this.$filter(nodes, selector)
    }
    /**
     * Get the combined string contents of each node in the set of matched nodes,
     * including their descendants
     */
    value () {
      return this.nodes.reduce((v, n) => {
        return n.reduce((v, n) => {
          return v + toString(n.node)
        }, v)
      }, '')
    }
  }

  return $
}
 var isArrayOfObjects = _.isArray(arrayOfIndexes) && ! arrayOfIndexes.some(function(index) {
         return ! _.isPlainObject(index);
 });
Example #29
0
GruntfileEditor.prototype.registerTask = function (name, desc, tasks, options) {
  name = _.isString(name) && name.trim() ? name : false;
  assert(name, 'You must provide a task group name');

  if (options == null) {
    if ((tasks == null) || _.isPlainObject(tasks)) {
      options = tasks;
      tasks = desc;
      desc = '';
    }
  }

  assert(_.isString(desc), 'The description shall be a string');

  if (_.isString(tasks)) {
    tasks = tasks.trim() || false;
  }
  if (_.isArray(tasks)) {
    tasks = tasks.length > 0 && tasks || false;
  }
  if (!(_.isString(tasks) || _.isArray(tasks))) {
    tasks = false;
  }
  assert(tasks, 'You must provide a task or an array of tasks');

  if (options != null && !_.isPlainObject(options)) {
    assert(false, 'If you provide options, they must be as an Object');
  }

  options = _.extend({
    duplicates: false
  }, options);

  var current = this.gruntfile.callExpression('grunt.registerTask')
    .filter(function (node) {
      return node.arguments[0].value === name;
    });

  tasks = _.isArray(tasks) ? tasks : tasks.replace(/ /g, '').split(',');

  if (current.length) {
    var argCount = current.arguments.nodes[0].elements.length;
    var argList = current.arguments.at(argCount - 1);
    var currentTasks = argList.nodes[0].elements.map(function (list) {
      return list.value;
    });

    tasks.forEach(function (task) {
      if (currentTasks.indexOf(task) === -1 || options.duplicates) {
        argList.push('"' + task + '"');
      }
    });

    if (desc.length > 0) {
      if (argCount === 2) {
        // insert a new description element
        current.arguments.unshift('"' + name + '"');
      }
      current.arguments.at(1).value('"' + desc + '"');
    }
  } else {
    if (desc.length > 0) {
      desc = '"' + desc + '", ';
    }
    this.gruntfile.assignment('module.exports').value().body.append(
      'grunt.registerTask("' + name + '", ' + desc + '["' + tasks.join('","') + '"])'
    );
  }

  return this;
};
var processSwaggerDocuments = function processSwaggerDocuments (rlOrSO, apiDeclarations) {
  if (_.isUndefined(rlOrSO)) {
    throw new Error('rlOrSO is required');
  } else if (!_.isPlainObject(rlOrSO)) {
    throw new TypeError('rlOrSO must be an object');
  }

  var spec = cHelpers.getSpec(cHelpers.getSwaggerVersion(rlOrSO), true);
  var apiCache = {};
  var composeParameters = function composeParameters (apiPath, method, path, operation) {
    var cParams = [];
    var seenParams = [];

    _.each(operation.parameters, function (parameter, index) {
      cParams.push({
        path: apiPath.concat([method, 'parameters', index.toString()]),
        schema: parameter
      });

      seenParams.push(parameter.name + ':' + parameter.in);
    });

    _.each(path.parameters, function (parameter, index) {
      if (seenParams.indexOf(parameter.name + ':' + parameter.in) === -1) {
        cParams.push({
          path: apiPath.concat(['parameters', index.toString()]),
          schema: parameter
        });
      }
    });

    return cParams;
  };
  var createCacheEntry = function createCacheEntry (adOrSO, apiOrPath, indexOrName, indent) {
    var apiPath = spec.version === '1.2' ? apiOrPath.path : indexOrName;
    var expressPath = expressStylePath(adOrSO.basePath, spec.version === '1.2' ? apiOrPath.path: indexOrName);
    var keys = [];
    var handleSubPaths = !(rlOrSO.paths && rlOrSO.paths[apiPath]['x-swagger-router-handle-subpaths']);
    var re = pathToRegexp(expressPath, keys, { end: handleSubPaths });
    var cacheKey = re.toString();
    var cacheEntry;

    // This is an absolute path, use it as the cache key
    if (expressPath.indexOf('{') === -1) {
      cacheKey = expressPath;
    }

    debug(new Array(indent + 1).join(' ') + 'Found %s: %s',
          (spec.version === '1.2' ? 'API' : 'Path'),
          apiPath);

    cacheEntry = apiCache[cacheKey] = spec.version === '1.2' ?
      {
        api: apiOrPath,
        apiDeclaration: adOrSO,
        apiIndex: indexOrName,
        keys: keys,
        params: {},
        re: re,
        operations: {},
        resourceListing: rlOrSO
      } :
      {
        apiPath: indexOrName,
        path: apiOrPath,
        keys: keys,
        re: re,
        operations: {},
        swaggerObject: {
          original: rlOrSO,
          resolved: adOrSO
        }
      };

    return cacheEntry;
  };

  debug('  Identified Swagger version: %s', spec.version);

  if (spec.version === '1.2') {
    if (_.isUndefined(apiDeclarations)) {
      throw new Error('apiDeclarations is required');
    } else if (!_.isArray(apiDeclarations)) {
      throw new TypeError('apiDeclarations must be an array');
    }

    debug('  Number of API Declarations: %d', apiDeclarations.length);

    _.each(apiDeclarations, function (apiDeclaration, adIndex) {
      debug('  Processing API Declaration %d', adIndex);

      _.each(apiDeclaration.apis, function (api, apiIndex) {
        var cacheEntry = createCacheEntry(apiDeclaration, api, apiIndex, 4);

        cacheEntry.resourceIndex = adIndex;

        _.each(api.operations, function (operation, operationIndex) {
          cacheEntry.operations[operation.method.toLowerCase()] = {
            operation: operation,
            operationPath: ['apis', apiIndex.toString(), 'operations', operationIndex.toString()],
            operationParameters: operation.parameters
          };
        });
      });
    });
  } else {
    // To avoid running into issues with references throughout the Swagger object we will use the resolved version.
    // Getting the resolved version is an asynchronous process but since initializeMiddleware caches the resolved document
    // this is a synchronous action at this point.
    spec.resolve(rlOrSO, function (err, resolved) {
      // Gather the paths, their path regex patterns and the corresponding operations
      _.each(resolved.paths, function (path, pathName) {
        var cacheEntry = createCacheEntry(resolved, path, pathName, 2);

        _.each(['get', 'put', 'post', 'delete', 'options', 'head', 'patch'], function (method) {
          var operation = path[method];

          if (!_.isUndefined(operation)) {
            cacheEntry.operations[method] = {
              operation: operation,
              operationPath: ['paths', pathName, method],
              // Required since we have to compose parameters based on the operation and the path
              operationParameters: composeParameters(['paths', pathName], method, path, operation)
            };
          }
        });
      });
    });
  }

  return apiCache;
};