示例#1
0
test('makeConfig works', t => {
  const title = 'JavaScript'
  const description = '.js'
  const enums = [ 'JavaScript', 'ES6' ]
  const config = makeConfig(title, description, enums)

  t.ok(isObject(config), 'config is not an object')
  t.ok(isArray(config.properties.icon.enum), 'enum is not an array')
  t.same(
    config.properties.icon.enum,
    [ 'JavaScript', 'ES6' ],
    'enum is not correct'
  )
  t.ok(isString(config.properties.icon.default), 'default is not a string')
  t.ok(
    config.properties.icon.default === 'JavaScript', 'default is not correct'
  )
  t.ok(
    isString(config.properties.icon.description),
    'description is not a string'
  )
  t.ok(
    config.properties.icon.description === '.js',
    'description is not correct'
  )
  t.ok(isString(config.properties.overlay.title), 'title is not a string')
  t.ok(
    config.properties.overlay.title === 'JavaScript Overlay',
    'overlay title is not correct'
  )
  t.ok(isString(config.title), 'title is not a string')
  t.ok(config.title === 'JavaScript', 'title is not correct')
})
示例#2
0
文件: index.js 项目: 4gekkman/R5
function expandPath(pathObj, defaultObj) {
  if (!isPlainObject(defaultObj)) {
    defaultObj = {};
  }

  if (isString(pathObj)) {
    pathObj = { path: pathObj };
  }

  if (!isPlainObject(pathObj)) {
    pathObj = {};
  }

  pathObj = defaults(pathObj, defaultObj);

  var filePath;
  if (!isString(pathObj.path)) {
    return null;
  }
  // Execution of toString is for a String object.
  if (isString(pathObj.name) && pathObj.name) {
    if (pathObj.path) {
      filePath = expandTilde(pathObj.path.toString());
      filePath = path.join(filePath, pathObj.name.toString());
    } else {
      filePath = pathObj.name.toString();
    }
  } else {
    filePath = expandTilde(pathObj.path.toString());
  }

  var extArr = createExtensionArray(pathObj.extensions);
  var extMap = createExtensionMap(pathObj.extensions);

  var basedir = isString(pathObj.cwd) ? pathObj.cwd.toString() : '.';
  basedir = path.resolve(expandTilde(basedir));

  var findUp = !!pathObj.findUp;

  var parsed = parsePath(filePath);
  if (parsed.isAbsolute) {
    filePath = filePath.slice(parsed.root.length);
    findUp = false;
    basedir = parsed.root;
  } else if (parsed.root) { // Expanded path has a drive letter on Windows.
    filePath = filePath.slice(parsed.root.length);
    basedir = path.resolve(parsed.root);
  }

  return {
    path: filePath,
    basedir: basedir,
    findUp: findUp,
    extArr: extArr,
    extMap: extMap,
  };
}
示例#3
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 + ')'))
      }
    }
  })
 renderWithTemplate: function (context, templateArg) {
     var template = templateArg || this.template;
     if (!template) throw new Error('Template string or function needed.');
     var newDom = isString(template) ? template : template.call(this, context || this);
     if (isString(newDom)) newDom = domify(newDom);
     var parent = this.el && this.el.parentNode;
     if (parent) parent.replaceChild(newDom, this.el);
     if (newDom.nodeName === '#document-fragment') throw new Error('Views can only have one root element, including comment nodes.');
     this.el = newDom;
     return this;
 },
示例#5
0
文件: getTask.js 项目: 4gekkman/R5
function getDescription(task) {
  if (isString(task.description)) {
    return task.description;
  }
  if (isFunction(task.unwrap)) {
    var origFn = task.unwrap();
    if (isString(origFn.description)) {
      return origFn.description;
    }
  }
  return undefined;
}
示例#6
0
文件: index.js 项目: daisywr/tmp
module.exports = (options = 'default', overrides = {}) => {
	if (!isString(options) && !isPlainObject(options)) {
		throw new TypeError('The options argument must be a String or an Object');
	}

	if (isPlainObject(options) && hasOwnProperty.call(options, 'actions') && !isPlainObject(options.actions)) {
		throw new TypeError('The options.actions property must be an Object');
	}

	if (isString(options) && !includesIgnoreCase(Object.keys(hostConfig), options)) {
		throw new TypeError(`The supported configuration are [${Object.keys(hostConfig).join(', ')}], got '${options}'`);
	}

	if (!isPlainObject(overrides)) {
		throw new TypeError('The overrides argument must be an Object');
	} else if (hasOwnProperty.call(overrides, 'actions') && !isPlainObject(overrides.actions)) {
		throw new TypeError('The overrides.actions property must be an Object');
	}

	options = isString(options) ? hostConfig[options.toLowerCase()] : options;

	const opts = Object.assign({}, hostConfig.default, options, overrides, {
		actions: Object.assign({}, hostConfig.default.actions, options.actions, overrides.actions),
	});

	normalize(opts);

	opts.hosts = opts.hosts.map(addTrailingSlash);
	opts.issueURLSegments = opts.issueURLSegments.map(addLeadingAndTrailingSlash);

	const regexp = buildRegexp(opts);
	const mentionRegexp = buildMentionRegexp(opts);

	return text => {
		if (!isString(text)) {
			throw new TypeError('The issue text must be a String');
		}

		const results = parse(text, regexp, mentionRegexp, opts);

		Reflect.defineProperty(results, 'allRefs', {
			get() {
				return uniqBy(this.refs.concat(...Object.keys(this.actions).map(key => this.actions[key])), 'raw');
			},
		});
		return results;
	};
};
示例#7
0
文件: v3.js 项目: whitelizard/jstiip
export function verifyTypes(tiip) {
  for (const k of timestampFields) {
    if (!isUndefined(tiip[k]) && !isISO6801Timestamp(tiip[k])) {
      throw new TypeError(`'${k}' should be a correct ISO 6801 date string (${tiip[k]})`);
    }
  }
  for (const k of stringFields) {
    if (!isUndefined(tiip[k]) && !isString(tiip[k])) {
      throw new TypeError(`'${k}' should be a String`);
    }
  }
  if (!isUndefined(tiip.src)) {
    if (!Array.isArray(tiip.src)) throw new TypeError("'src' should be an Array");
    if (!tiip.src.every(isString)) throw new TypeError("'src' should contain strings");
  }
  if (!isUndefined(tiip.targ)) {
    if (!Array.isArray(tiip.targ)) throw new TypeError("'targ' should be an Array");
    if (!tiip.targ.every(isString)) throw new TypeError("'targ' should contain strings");
  }
  if (!isUndefined(tiip.pl) && !Array.isArray(tiip.pl)) {
    throw new TypeError("'pl' should be an Array");
  }
  if (!isUndefined(tiip.arg) && !isObject(tiip.arg)) {
    throw new TypeError("'arg' should be an Array");
  }
  if (!isUndefined(tiip.ok) && !isBoolean(tiip.ok)) throw new TypeError("'ok' should be an Array");
}
示例#8
0
文件: v3.js 项目: whitelizard/jstiip
 set ts(v) {
   if (!isString(v)) throw new TypeError("'type' should be a String");
   if (!isISO6801Timestamp(v)) {
     throw new TypeError("'ts' should be a correct ISO 6801 date string");
   }
   this._$ts = v;
 }
示例#9
0
  Object.keys(types).forEach(key => {
    const config = types[key]

    t.ok(isObject(config), 'config is not an object')
    t.ok(isString(config.type), 'type is not a string')
    t.ok(~options.indexOf(config.type), 'type is not in options')
  })
  applyPriorityToScore(itemId, score) {
    if (!lo_isString(itemId) || itemId.length <= 0) return score;

    const itemNumberOfUse = this.itemNumberOfUses[itemId] || 0;
    const ratio = Math.min(MAX_RATIO, 1 + Math.log(1 + itemNumberOfUse));
    return score * ratio;
  }
 return selectors.map(function(selector){
   if(!isArray(selector)) {
     if(isString(selector)) return selector.split('+');
     return [selector]
   }
   return selector;
 });
示例#12
0
request.Request.prototype.init = function RP$initInterceptor(options) {

    var self = this;

    // Init may be called again - currently in case of redirects
    if (isPlainObject(options) && self._callback === undefined && self._rp_promise === undefined) {

        self._rp_promise = new Bluebird(function (resolve, reject) {
            self._rp_resolve = resolve;
            self._rp_reject = reject;
        });

        self._rp_callbackOrig = self.callback;
        self.callback = RP$callback;

        if (isString(options.method)) {
            options.method = options.method.toUpperCase();
        }

        options.transform = options.transform || defaultTransformations[options.method];

        self._rp_options = options;
        self._rp_options.simple = options.simple === false ? false : true;
        self._rp_options.resolveWithFullResponse = options.resolveWithFullResponse === true ? true : false;

    }

    return originalInit.apply(self, arguments);

};
示例#13
0
function fixPaths(value, base) {
  var path;

  if (isString(value)) {
    path = resolvePath(base, value);

    return isPath(path).then(function (isPath) {
      if (isPath) {
        return path;
      }
      return value;
    });
  }

  if (isObject(value)) {
    var promises = map(value, function (item, key) {
      return fixPaths(item, base).then(function (item) {
        value[key] = item;
      });
    });
    return Bluebird.all(promises).return(value);
  }

  return Bluebird.resolve(value);
}
示例#14
0
// make sure that strings are strings, numbers are numbers when JSON encoding
function brutal_hack(v){
    if(! isString(v) && ! isNaN(v) ){
        return +v
    }else{
        return v
    }
}
示例#15
0
文件: parser.js 项目: d0liver/jsctags
  return DEFAULT_TYPES.some(function (dt) {
    if (isString(dt)) {
      return type === dt;
    }

    return dt.test(type);
  });
示例#16
0
  then: function(autocrat, governor, origHandler, context) {
    var streamsHash = this.streamsHash,
        handlerSequence, isFirstHandler, deferred, handler;

    context || (context = this.governor);

    if(isFunction(origHandler)) {
      origHandler = bind(origHandler, context);
    } else if(isString(origHandler)){
      origHandler = bind(this.governor[origHandler], context);
    }

    if(autocrat.awaiting[this.streamsHash]) {
      handlerSequence = autocrat.awaiting[this.streamsHash];
    } else {
      handlerSequence = autocrat.awaiting[this.streamsHash] = [];
      isFirstHandler = true;
    }

    deferred = new HandlerDeferred(handlerSequence);
    handler = this._buildAsyncHandler(origHandler, deferred);

    if(isFirstHandler) {
      deferred.handlerIndex = 0;
      handlerSequence.push(handler);
      this.resultStream.subscribe(handler);
    } else {
      deferred.handlerIndex = handlerSequence.length;
      handlerSequence.push(handler);
    }

    // terminate chain
    return this;
  },
示例#17
0
export default function serialiseComponent(component) {
  if (_isArray(component)) {
    throw Error('Attempted to serialise an array - need React component');
  }
  if (_isString(component)) {
    return component;
  }
  let displayName = getDisplayName(component.type);
  if (displayName == 'Component') {
    throw Error('Attempted to serialise a non React component');
  }
  let {children, ...other} = component.props;
  const otherFiltered = {};
  _map(other, (val, key) => {
    if (!_isFunction(val)) {
      otherFiltered[key] = val;
    }
  });
  let props = {};
  if (children) {
    props = {children: React.Children.map(children, serialiseComponent),
      ...otherFiltered
    };
  } else {
    props = otherFiltered;
  }
  return Immutable.fromJS({
    type: displayName,
    props
  });
}
示例#18
0
// TODO:
//
// Replace the following helper with the version in sails.util:

// Attempt to parse JSON
// If the parse fails, return the error object
// If JSON is falsey, return null
// (this is so that it will be ignored if not specified)
function tryToParseJSON (json) {
  if (!isString(json)) return null;
  try {
    return JSON.parse(json);
  }
  catch (e) { return e; }
}
示例#19
0
文件: parser.js 项目: d0liver/jsctags
Parser.prototype.fnArgs = function (node) {
  if (!isString(node['!type'])) {
    return [];
  }

  var args = node['!type'].match(MATCHES.args);

  if (!Array.isArray(args) || !args.length) {
    return '';
  }

  return args.pop().split(',').map(function (arg) {
    var t = arg.match(MATCHES.arg);

    if (!Array.isArray(t) || !t.length) {
      return;
    }

    var type = t.pop();

    if (this.define[type] && this.define[type]['!type']) {
      return this.typeFn(this.define[type]['!type']);
    }

    if (type && MATCHES.arrArg.test(type)) {
      return 'Array'.concat(type);
    }

    return type;
  }, this).filter(function (type) {
    return !!type;
  });
};
示例#20
0
export function isFSA(action) {
  return (
    isPlainObject(action) &&
    (isString(action.type) || isSymbol(action.type)) &&
    Object.keys(action).every(isValidKey)
  );
}
示例#21
0
文件: parser.js 项目: d0liver/jsctags
Parser.prototype.isFn = function (node) {
  if (!isString(node['!type'])) {
    return false;
  }

  return MATCHES.fn.test(node['!type']);
};
示例#22
0
文件: parser.js 项目: d0liver/jsctags
Parser.prototype.lineno = function (node) {
  if (!isString(node['!span'])) {
    return;
  }

  return Number(node['!span'].match(MATCHES.lineno).pop()) + 1;
};
示例#23
0
    slugify: function(str) {
      if (!isString(str)) {
        return '';
      }

      var replacePattern = /[^a-zA-Z0-9\s\-\_]/g;
      return str.replace(replacePattern, '').toLowerCase().replace(/\s/g, '_');
    }
示例#24
0
文件: text-util.js 项目: rlugojr/hain
function sanitize(txtObj) {
  if (txtObj === undefined)
    return undefined;
  if (lo_isString(txtObj))
    return _sanitizeHtml(txtObj);
  return lo_assign(txtObj, {
    text: _sanitizeHtml(txtObj.text)
  });
}
示例#25
0
var createSuffixFunction = function(configValue) {
    if(isString(configValue) || isUndefined(configValue)) {
        return createSuffixFunctionFromString(configValue);
    } else if(isFunction(configValue)) {
        return configValue;
    } else {
        throw new TypeError("suffix is neither a string nor function");
    }
}
function resolveScriptObjectToString(script) {
  const scriptObj = resolveScriptObjectToScript(script)
  if (isPlainObject(scriptObj)) {
    return scriptObj.script
  } else if (isString(scriptObj)) {
    return scriptObj
  }
  return undefined
}
示例#27
0
module.exports = (object, defaultName) => {
  if (
    _isObject(object) &&
    _isString(object.name) &&
    object.name.length > 0
  ) {
    return object.name
  }

  if (
    _isString(defaultName) &&
    defaultName.length > 0
  ) {
    return defaultName
  }

  return '<anonymous>'
}
示例#28
0
文件: key-path.js 项目: JaapRood/vry
exports.parse = function(path) {
	if (_isString(path)) {
		return Immutable.List([path])
	} else if (_isArray(path)) { 
		return Immutable.List(path);
	} else {
		return path;
	}
};
示例#29
0
文件: v3.js 项目: whitelizard/jstiip
 constructor(from, loadingTiip) {
   if (isString(from)) {
     this.fromJS(JSON.parse(from), loadingTiip);
   } else if (isObject(from)) {
     this.fromJS(from, loadingTiip);
   } else {
     this.fromJS({});
   }
 }
示例#30
0
// ===================================================================

// Parses, normalizes and validates a JSON-RPC message.
//
// The returns value is an object containing the normalized fields of
// the JSON-RPC message and an additional `type` field which contains
// one of the following: `notification`, request`, `response` or
// `error`.
export default function parse (message) {
  if (isString(message)) {
    try {
      message = JSON.parse(message)
    } catch (error) {
      if (error instanceof SyntaxError) {
        throw new InvalidJson()
      }

      throw error
    }
  }

  // Properly handle array of requests.
  if (isArray(message)) {
    return map(message, message => parse(message))
  }

  const version = detectJsonRpcVersion(message)

  if (isString(message.method)) {
    const {id} = message
    if (isNotificationId(id, version)) {
      setMessageType(message, 'notification')
    } else {
      checkId(id)
      setMessageType(message, 'request')
    }

    checkParams(message.params, version)
  } else if (isErrorResponse(message, version)) {
    // The identifier of an error message can also be null.
    const {id} = message
    id !== null && checkId(id)

    checkError(message.error, version)
    setMessageType(message, 'error')
  } else {
    checkId(message.id)
    setMessageType(message, 'response')
  }

  return message
}