Exemplo n.º 1
0
  Object.keys(schema).forEach(function(k) {

    // lets get the prop
    var prop = schema[k]

    // test for required properties
    if (prop.required && !has(params, k)) {
      errors.push(ReferenceError('missing required param ' + k))
    }

    // type checker! only validating a type if params has the key
    if (prop.type && has(params, k)) {
      // do a bunch of work to find a possible err
      var index    = builtins.indexOf(prop.type)
      var notfound = index === -1
      var checker  = notfound? prop.type : types[aliases[index]]
      var value    = property(k)(params)
      var err      = checker(value)
      // finally check the type
      if (isError(err)) {
        errors.push(TypeError('invalid type ' + k + ' is ' + err.message))
      }
    }

    // add custom type to rangesafe if min or max is expected
    if (notfound && (prop.type.min || prop.type.max)) {
      rangesafe.push(prop.type)
    }

    // min
    if (prop.min && has(params, k) && rangesafe.indexOf(prop.type) > -1) {
      // Number: check the value directly
      var isNumAndUnderMin = isNumber(value) && value < prop.min
      // String & Array: both respond to length!
      var lengthUnderMin = (isString(value) || isArray(value)) && value.length < prop.min
      // Custom min found on a valid custom type
      var isCustom = prop.type.min && !isError(prop.type(value)) && !prop.type.min(prop.min, value)
      // anything goes!
      if (isNumAndUnderMin || lengthUnderMin || isCustom) {
        errors.push(RangeError(k + ' below min with value ' + value + ' (min is ' + prop.min + ')'))
      }
    }

    // max
    if (prop.max && has(params, k) && rangesafe.indexOf(prop.type) > -1) {
      // Number: check the value directly
      var isNumAndOverMax = isNumber(value) && value > prop.max
      // String & Array: both respond to length
      var lengthOverMax = (isString(value) || isArray(value)) && value.length < prop.max
      // Custom max found on a valid custom type
      var isCustom = prop.type.max && !isError(prop.type(value)) && !prop.type.max(prop.max, value)
      // anything goes
      if (isNumAndOverMax || lengthOverMax || isCustom) {
        errors.push(RangeError(k + ' over max with value ' + value + ' (max is ' + prop.max + ')'))
      }
    }
  })
 hasChanged: function (attr) {
     if (attr == null) return !!Object.keys(this._changed).length;
     if (has(this._derived, attr)) {
         return this._derived[attr].depList.some(function (dep) {
             return this.hasChanged(dep);
         }, this);
     }
     return has(this._changed, attr);
 },
/**
 * This function is used to check for a pending status code on the response
 * or a set status code on the response.output object property. If neither of
 * these properties can be found then -1 will be returned as the output.
 * @function attemptToExtractStatusCode
 * @param {Object} req - the request information object to extract from
 * @returns {Number} - Either an HTTP status code or -1 in absence of an
 *  extractable status code.
 */
function attemptToExtractStatusCode(req) {

  if (has(req, 'response') && isObject(req.response) &&
      has(req.response, 'statusCode')) {

    return req.response.statusCode;
  } else if (has(req, 'response') && isObject(req.response) &&
             isObject(req.response.output)) {

    return req.response.output.statusCode;
  }

  return 0;
}
Exemplo n.º 4
0
Configuration.prototype._checkLocalServiceContext = function() {
  // Note: The GAE_MODULE_NAME environment variable is set on GAE.
  //       If the code is, in particular, running on GCF, then the
  //       FUNCTION_NAME environment variable is set.
  //
  // To determine the service name to use:
  //   If the user specified a service name it should be used, otherwise
  //   if the FUNCTION_NAME environment variable is set (indicating that the
  //   code is running on GCF) then the FUNCTION_NAME value should be used as
  //   the service name.  If neither of these conditions are true, the
  //   value of the GAE_MODULE_NAME environment variable should be used as the
  //   service name.
  //
  // To determine the service version to use:
  //   If the user species a version, then that version will be used.
  //   Otherwise, the value of the environment variable GAE_MODULE_VERSION
  //   will be used if and only if the FUNCTION_NAME environment variable is
  //   not set.
  var service;
  var version;

  if (env.FUNCTION_NAME) {
    service = env.FUNCTION_NAME;
  } else if (env.GAE_SERVICE) {
    service = env.GAE_SERVICE;
    version = env.GAE_VERSION;
  } else if (env.GAE_MODULE_NAME) {
    service = env.GAE_MODULE_NAME;
    version = env.GAE_MODULE_VERSION;
  }

  this._serviceContext.service = isString(service) ? service : 'node';
  this._serviceContext.version = isString(version) ? version : undefined;

  if (isObject(this._givenConfiguration.serviceContext)) {
    if (isString(this._givenConfiguration.serviceContext.service)) {
      this._serviceContext.service =
        this._givenConfiguration.serviceContext.service;
    } else if (has(this._givenConfiguration.serviceContext, 'service')) {
      throw new Error('config.serviceContext.service must be a string');
    }

    if (isString(this._givenConfiguration.serviceContext.version)) {
      this._serviceContext.version =
        this._givenConfiguration.serviceContext.version;
    } else if (has(this._givenConfiguration.serviceContext, 'version')) {
      throw new Error('config.serviceContext.version must be a string');
    }
  }
};
/**
 * Extracts error information from an instance of the Error class and marshals
 * that information into the provided instance of error message. This function
 * will check before accessing any part of the error for propety presence but
 * will not check the types of these property values that is instead work that
 * is allocated to the error message instance itself.
 * @param {Error} err - the error instance
 * @param {ErrorMessage} errorMessage - the error message instance to have the
 *  error information marshaled into
 * @returns {Undefined} - does not return anything
 */
function extractFromErrorClass(err, errorMessage) {

  errorMessage.setMessage(err.stack);

  if (has(err, 'user')) {

    errorMessage.setUser(err.user);
  }

  if (has(err, 'serviceContext') && isObject(err.serviceContext)) {

    errorMessage.setServiceContext(err.serviceContext.service,
                                   err.serviceContext.version);
  }
}
Exemplo n.º 6
0
    /**
     * Override default `toJSON` to return DSL representation for `sort` parameter.
     *
     * @override
     * @returns {Object|string} returns an Object which maps to the elasticsearch query DSL
     */
    toJSON() {
        const geoPointIsNil = isNil(this._geoPoint);
        const scriptIsNil = isNil(this._script);

        if (geoPointIsNil && scriptIsNil) {
            if (isEmpty(this._opts)) return this._field;

            if (
                Object.keys(this._opts).length === 1 &&
                has(this._opts, 'order')
            ) {
                return { [this._field]: this._opts.order };
            }
        }

        let repr;

        // Should I pick only the accepted properties here?
        if (!geoPointIsNil) {
            repr = {
                _geo_distance: Object.assign(
                    { [this._field]: this._geoPoint },
                    this._opts
                )
            };
        } else if (!scriptIsNil) {
            repr = {
                _script: Object.assign({ script: this._script }, this._opts)
            };
        } else {
            repr = { [this._field]: this._opts };
        }

        return recursiveToJSON(repr);
    }
CreateFilePlugin.prototype.apply = function apply(compiler) {
  let outputPath;

  if (has(compiler, 'options.output.path')) outputPath = compiler.options.output.path;

  if (!outputPath) {
    throw new Error('output.path is not defined. Define output.path.');
  }

  const afterEmit = (compilation, callback) => {
    if (this.files.length) {
      return Promise.all(this.files.map(file => createFile(path.join(outputPath, file)))).then(() => {
        this.files = [];
        callback();
      });
    }

    callback();
  };

  if (compiler.hooks) {
    const plugin = { name: 'CreateFilePlugin' };

    compiler.hooks.afterEmit.tapAsync(plugin, afterEmit);
  } else {
    compiler.plugin('after-emit', afterEmit);
  }
};
var toDecimal128 = function toDecimal128(object) {
  /*
   If converting a BSON Object, extract the value before converting to a string.
   */
  if (has(object, BSON_TYPE) && includes(NUMBER_TYPES, object._bsontype)) {
    object = object._bsontype === LONG ? object.toNumber() : object.valueOf();
  }
  return Decimal128.fromString(String(object));
};
Exemplo n.º 9
0
 function calculateHeight(){
   if (!has(heights, 'nav')) {
     var navHeight = $navItems.outerHeight(true) + $navMore.outerHeight();
     var navPadding = $nav.outerHeight() - $nav.height();
     heights.nav = navHeight + navPadding;
   }
   if (!has(heights, 'subNav')) {
     var subNavHeight = 0;
     var subNavPadding = $subnav.outerHeight() - $subnav.height();
     $subnavSections.add($subnavDefault).each(function () {
       subNavHeight = Math.max(subNavHeight, $(this).outerHeight());
     });
     heights.subNav = subNavHeight + subNavPadding;
   }
   var contentHeight = $contentWrapper.outerHeight();
   var contentPadding = $content.outerHeight() - $content.height();
   heights.content = contentHeight + contentPadding;
   return Math.max.apply(null, values(heights));
 }
Exemplo n.º 10
0
/**
 * This function is used to check for the x-forwarded-for header first to
 * identify source IP connnections. If this header is not present, then the
 * function will attempt to extract the remoteAddress from the request.info
 * object property. If neither of these properties can be found then an empty
 * string will be returned.
 * @function extractRemoteAddressFromRequest
 * @param {Object} req - the request information object to extract from
 * @returns {String} - Either an empty string if the IP cannot be extracted or
 *  a string that represents the remote IP address
 */
function extractRemoteAddressFromRequest(req) {

  if (has(req.headers, 'x-forwarded-for')) {

    return req.headers['x-forwarded-for'];
  } else if (isObject(req.info)) {

    return req.info.remoteAddress;
  }

  return '';
}
/**
 * Attempts to extract error information given an object as the input for the
 * error. This function will check presence of each property before attempting
 * to access the given property on the object but will not check for type
 * compliance as that is allocated to the instance of the error message itself.
 * @function extractFromObject
 * @param {Object} err - the Object given as the content of the error
 * @param {String} [err.message] - the error message
 * @param {String} [err.user] - the user the error occurred for
 * @param {String} [err.filePath] - the file path and file where the error
 *  occurred at
 * @param {Number} [err.lineNumber] - the line number where the error occurred
 *  at
 * @param {String} [err.functionName] - the function where the error occurred at
 * @param {Object} [err.serviceContext] - the service context object of the
 *  error
 * @param {String} [err.serviceContext.service] - the service the error occurred
 *  on
 * @param {String} [err.serviceContext.version] - the version of the application
 *  that the error occurred on
 * @param {ErrorMessage} errorMessage - the error message instance to marshal
 *  error information into
 * @returns {Undefined} - does not return anything
 */
function extractFromObject(err, errorMessage) {

  if (has(err, 'message')) {

    errorMessage.setMessage(err.message);
  }

  if (has(err, 'user')) {

    errorMessage.setUser(err.user);
  }

  if (has(err, 'filePath')) {

    errorMessage.setFilePath(err.filePath);
  }

  if (has(err, 'lineNumber')) {

    errorMessage.setLineNumber(err.lineNumber);
  }

  if (has(err, 'functionName')) {

    errorMessage.setFunctionName(err.functionName);
  }

  if (has(err, 'serviceContext') && isObject(err.serviceContext)) {

    errorMessage.setServiceContext(err.serviceContext.service,
                                   err.serviceContext.version);
  }
}
    /**
     * Rescoring can help to improve precision by reordering just the top (eg 100 - 500)
     * documents returned by the `query` and `post_filter` phases, using a secondary
     * (usually more costly) algorithm, instead of applying the costly algorithm to
     * all documents in the index.
     *
     * @example
     * const reqBody = esb.requestBodySearch()
     *     .query(esb.matchQuery('message', 'the quick brown').operator('or'))
     *     .rescore(
     *         esb.rescore(
     *             50,
     *             esb.matchPhraseQuery('message', 'the quick brown').slop(2)
     *         )
     *             .queryWeight(0.7)
     *             .rescoreQueryWeight(1.2)
     *     );
     *
     * @example
     * const reqBody = esb.requestBodySearch()
     *     .query(esb.matchQuery('message', 'the quick brown').operator('or'))
     *     .rescore(
     *         esb.rescore(
     *             100,
     *             esb.matchPhraseQuery('message', 'the quick brown').slop(2)
     *         )
     *             .queryWeight(0.7)
     *             .rescoreQueryWeight(1.2)
     *     )
     *     .rescore(
     *         esb.rescore(
     *             10,
     *             esb.functionScoreQuery().function(
     *                 esb.scriptScoreFunction(
     *                     esb.script('inline', 'Math.log10(doc.likes.value + 2)')
     *                 )
     *             )
     *         ).scoreMode('multiply')
     *     );
     *
     * @param {Rescore} rescore
     * @returns {RequestBodySearch} returns `this` so that calls can be chained
     * @throws {TypeError} If `query` is not an instance of `Rescore`
     */
    rescore(rescore) {
        checkType(rescore, Rescore);

        if (has(this._body, 'rescore')) {
            if (!Array.isArray(this._body.rescore)) {
                this._body.rescore = [this._body.rescore];
            }

            this._body.rescore.push(rescore);
        } else this._body.rescore = rescore;

        return this;
    }
Exemplo n.º 13
0
Configuration.prototype._gatherLocalConfiguration = function() {
  if (this._givenConfiguration.ignoreEnvironmentCheck === true) {
    this._shouldReportErrorsToAPI = true;
  } else if (has(this._givenConfiguration, 'ignoreEnvironmentCheck') &&
    !isBoolean(this._givenConfiguration.ignoreEnvironmentCheck)) {
    throw new Error('config.ignoreEnvironmentCheck must be a boolean');
  } else {
    this._shouldReportErrorsToAPI = env.NODE_ENV === 'production';
  }
  if (!this._shouldReportErrorsToAPI) {
    this._logger.warn([
      'Stackdriver error reporting client has not been configured to send',
      'errors, please check the NODE_ENV environment variable and make sure it',
      'is set to "production" or the ignoreEnvironmentCheck property is set to',
      'true in the runtime configuration object'
    ].join(' '));
  }
  if (isString(this._givenConfiguration.key)) {
    this._key = this._givenConfiguration.key;
  } else if (has(this._givenConfiguration, 'key')) {
    throw new Error('config.key must be a string');
  }
  if (isString(this._givenConfiguration.keyFilename)) {
    this.keyFilename = this._givenConfiguration.keyFilename;
  } else if (has(this._givenConfiguration, 'keyFilename')) {
    throw new Error('config.keyFilename must be a string');
  }
  if (isObject(this._givenConfiguration.credentials)) {
    this.credentials = this._givenConfiguration.credentials;
  } else if (has(this._givenConfiguration, 'credentials')) {
    throw new Error('config.credentials must be a valid credentials object');
  }
  if (isBoolean(this._givenConfiguration.reportUnhandledRejections)) {
    this._reportUnhandledRejections =
      this._givenConfiguration.reportUnhandledRejections;
  } else if (has(this._givenConfiguration, 'reportUnhandledRejections')) {
    throw new Error('config.reportUnhandledRejections must be a boolean');
  }
};
Exemplo n.º 14
0
/**
 * Creates an instance of the Google Cloud Diagnostics logger class. This
 * instance will be configured to log at the level given by the environment or
 * the runtime configuration property `logLevel`. If neither of these inputs are
 * given or valid then the logger will default to logging at log level `WARN`.
 * Order of precedence for logging level is:
 * 1) Environmental variable `GCLOUD_ERRORS_LOGLEVEL`
 * 2) Runtime configuration property `logLevel`
 * 3) Default log level of `WARN` (2)
 * @function createLogger
 * @param {ConfigurationOptions} initConfiguration - the desired project/error
 *  reporting configuration. Will look for the  `logLevel` property which, if
 *  supplied, must be a number or stringified decimal representation of a
 *  number between and including 1 through 5
 * @returns {Object} - returns an instance of the logger created with the given/
 *  default options
 */
function createLogger(initConfiguration) {
  // Default to log level: warn (2)
  var DEFAULT_LEVEL = logger.LEVELS[2];
  var level = DEFAULT_LEVEL;
  if (has(process.env, 'GCLOUD_ERRORS_LOGLEVEL')) {
    // Cast env string as integer
    level = logger.LEVELS[~~process.env.GCLOUD_ERRORS_LOGLEVEL] ||
      DEFAULT_LEVEL;
  } else if (isObject(initConfiguration) &&
    has(initConfiguration, 'logLevel')) {
    if (isString(initConfiguration.logLevel)) {
      // Cast string as integer
      level = logger.LEVELS[~~initConfiguration.logLevel] || DEFAULT_LEVEL;
    } else if (isNumber(initConfiguration.logLevel)) {
      level = logger.LEVELS[initConfiguration.logLevel] || DEFAULT_LEVEL;
    } else {
      throw new Error('config.logLevel must be a number or decimal ' +
        'representation of a number in string form');
    }
  }
  return logger({level: level, tag: '@google/cloud-errors'});
}
Exemplo n.º 15
0
 function search(query, res) {
   try {
     const ans = math.eval(query);
     if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
       res.add({
         title: `${query.trim()} = ${ans.toString()}`,
         group: 'Math',
         payload: ans.toString()
       });
     }
   } catch (e) {
   }
 }
Exemplo n.º 16
0
Configuration.prototype._checkLocalProjectId = function() {
  if (isString(this._projectId)) {
    // already has been set by the metadata service
    return this._projectId;
  }
  if (has(this._givenConfiguration, 'projectId')) {
    if (isString(this._givenConfiguration.projectId)) {
      this._projectId = this._givenConfiguration.projectId;
    } else if (isNumber(this._givenConfiguration.projectId)) {
      this._projectId = this._givenConfiguration.projectId.toString();
    }
  }
  return this._projectId;
};
Exemplo n.º 17
0
	groupBy(callback, context) {
		var result = { };

		for (let i=0, len=this.length; i<len; i++) {
			const prop = this[i];
			const key = callback.call(context, prop);

			if (has(result, key)) {
				result[key].push(prop);
			} else {
				result[key] = [ prop ];
			}
		}

		return result;
	}
Exemplo n.º 18
0
    /**
     * Override default `toJSON` to return DSL representation of the Span term query
     * class instance.
     *
     * @override
     * @returns {Object} returns an Object which maps to the elasticsearch query DSL
     */
    toJSON() {
        // recursiveToJSON doesn't seem to be required here.

        // Revisit this.. Smells a little bit
        if (!has(this._queryOpts, 'value')) {
            throw new Error('Value is required for Span term query!');
        }

        const qryOpts =
            Object.keys(this._queryOpts).length === 1
                ? this._queryOpts.value
                : this._queryOpts;
        return {
            [this.queryType]: {
                [this._field]: qryOpts
            }
        };
    }
Exemplo n.º 19
0
	/**
		Inspired by [Lodash groupBy()](https://lodash.com/docs/4.17.4#groupBy) method.

		Creates an object composed of keys generated from the results of running each element of
		collection thru iteratee. The order of grouped values is determined by the order they occur
		in collection. The corresponding value of each key is an array of elements responsible for
		generating the key. The iteratee is invoked with one argument: (value).

		@see https://lodash.com/docs/4.17.4#groupBy
	*/
	groupBy(callback, context) {
		const keys = this.keysArray();
		const result = { };
		var key, value, groupId;

		for (let i=0, len=keys.length; i<len; i++) {
			key = keys[i];
			value = this.get(key);
			groupId = callback.call(context, value, key, this);

			if (has(result, groupId)) {
				result[groupId].push(value);
			} else {
				result[groupId] = [ value ];
			}
		}

		return result;
	}
Exemplo n.º 20
0
 this.segments.forEach(segment => {
     if (segment.kind === extras.BINDING) {
         if (!has(bindings, segment.literal)) {
             const msg = util.format('Value for key %s is not provided in %s', segment.literal, bindings);
             throw new TypeError(msg);
         }
         const tmp = new PathTemplate(bindings[segment.literal]);
         Array.prototype.push.apply(out, tmp.segments);
         inABinding = true;
     }
     else if (segment.kind === extras.END_BINDING) {
         inABinding = false;
     }
     else if (inABinding) {
         return;
     }
     else {
         out.push(segment);
     }
 });
    /**
     * Sets the ordering for buckets
     *
     * @example
     * const agg = esb.histogramAggregation('prices', 'price', 50)
     *     .order('_count', 'desc');
     *
     * @example
     * const agg = esb.histogramAggregation('prices', 'price', 50)
     *     .order('promoted_products>rating_stats.avg', 'desc')
     *     .agg(
     *         esb.filterAggregation('promoted_products')
     *             .filter(esb.termQuery('promoted', 'true'))
     *             .agg(esb.statsAggregation('rating_stats', 'rating'))
     *     );
     *
     * @param {string} key
     * @param {string} direction `asc` or `desc`
     * @returns {HistogramAggregationBase} returns `this` so that calls can be chained
     */
    order(key, direction = 'desc') {
        if (isNil(direction)) invalidDirectionParam(direction);

        const directionLower = direction.toLowerCase();
        if (directionLower !== 'asc' && directionLower !== 'desc') {
            invalidDirectionParam(direction);
        }

        if (has(this._aggsDef, 'order')) {
            if (!Array.isArray(this._aggsDef.order)) {
                this._aggsDef.order = [this._aggsDef.order];
            }

            this._aggsDef.order.push({ [key]: directionLower });
        } else {
            this._aggsDef.order = { [key]: directionLower };
        }

        return this;
    }
Exemplo n.º 22
0
 value: function type(object) {
   if (isNumber(object)) {
     return numberToBsonType(object);
   }
   if (isPlainObject(object)) {
     return OBJECT;
   }
   if (isArray(object)) {
     return ARRAY;
   }
   if (has(object, BSON_TYPE)) {
     if (object._bsontype === LONG) {
       return INT_64;
     }
     if (object._bsontype === OBJECT_ID) {
       return 'ObjectId';
     }
     return object._bsontype;
   }
   return Object.prototype.toString.call(object).replace(MATCH, '$1');
 }
/**
 * The manualRequestInformationExtractor is meant to take a standard object
 * and extract request information based on the inclusion of several properties.
 * This function will check the presence of properties before attempting to
 * access them on the object but it will not attempt to check for these
 * properties types as this is allocated to the RequestInformationContainer.
 * @function manualRequestInformationExtractor
 * @param {Object} req - the request information object to extract from
 * @param {String} [req.method] - the request method (ex GET, PUT, POST, DELETE)
 * @param {String} [req.url] - the request url
 * @param {String} [req.userAgent] - the requesters user-agent
 * @param {String} [req.referrer] - the requesters referrer
 * @param {Number} [req.statusCode] - the status code given in response to the
 *  request
 * @param {String} [req.remoteAddress] - the remote address of the requester
 * @returns {RequestInformationContainer} - an object containing the request
 *  information in a standardized format
 */
function manualRequestInformationExtractor(req) {

  var returnObject = new RequestInformationContainer();

  if (!isObject(req) || isArray(req) || isFunction(req)) {

    return returnObject;
  }

  if (has(req, 'method')) {

    returnObject.setMethod(req.method);
  }

  if (has(req, 'url')) {

    returnObject.setUrl(req.url);
  }

  if (has(req, 'userAgent')) {

    returnObject.setUserAgent(req.userAgent);
  }

  if (has(req, 'referrer')) {

    returnObject.setReferrer(req.referrer);
  }

  if (has(req, 'statusCode')) {

    returnObject.setStatusCode(req.statusCode);
  }

  if (has(req, 'remoteAddress')) {

    returnObject.setRemoteAddress(req.remoteAddress);
  }

  return returnObject;
}
Exemplo n.º 24
0
 hasChanged: function (attr) {
     if (attr == null) return !isEmpty(this._changed);
     return has(this._changed, attr);
 },
Exemplo n.º 25
0
	/*
		Gets if this state property has a subproperty with a specified name.
	*/
	has(k) {
		return has(this[_impls], k);
	}
Exemplo n.º 26
0
 function validate(cb) {
     if (!app) return cb(new Error('app is required'))
     if (!has(config, 'port')) return cb(new Error('config.port is required'))
     cb()
 }
Exemplo n.º 27
0
	has(key) {
		if (this.isActive()) {
			return has(this.shadow(), key);
		}
	}
Exemplo n.º 28
0
exports.setDefault = function setDefault(obj, key, value) {
    const itHasNot = !has(obj, key);
    if (itHasNot) obj[key] = value;
    return itHasNot;
};