Define default properties on the given schema.

@param {Schema} schema
@return {Function}
174646
function defineSchemaTable(schema) {
  return function (table) {
    table.timestamps();
    (schema.build || _.noop)(table);
  };
}
814109
function func(schema, defaults, options) {
  if (kindOf(schema) !== 'function') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Function structs must be defined as a function, but you passed: ${schema}`
      )
    } else {
      throw new Error(`Invalid schema: ${schema}`)
    }
  }

  const name = 'function'
  const type = '<function>'
  const validate = (value = resolveDefaults(defaults), data) => {
    const result = schema(value, data)
    let failure = { path: [], reason: null }
    let isValid

    switch (kindOf(result)) {
      case 'boolean': {
        isValid = result
        break
      }
      case 'string': {
        isValid = false
        failure.reason = result
        break
      }
      case 'object': {
        isValid = false
        failure = { ...failure, ...result }
        break
      }
      default: {
        if (process.env.NODE_ENV !== 'production') {
          throw new Error(
            `Validator functions must return a boolean, an error reason string or an error reason object, but you passed: ${schema}`
          )
        } else {
          throw new Error(`Invalid result: ${result}`)
        }
      }
    }

    return isValid
      ? [undefined, value]
      : [{ type, value, data: value, ...failure }]
  }

  return new Kind(name, type, validate)
}
571701
function (name, value, schema, options, callback) {

    var err
        , nullable = false
        , valCount = 0;

    // Set default values
    if (options && options.partial !== true) {
        if (schema.hasOwnProperty('default') && value === undefined) {
            if ((_.isString(schema.default) || _.isBoolean(schema.default) || _.isNumber(schema.default)) || (schema.hasOwnProperty('nullable') && schema.nullable === true && _.isNull(schema.default))) {
                value = schema.default;
            }
            else {
                if (_.isFunction(schema.default)) {
                    value = (schema.default)();
                }
                else {
                    err = _.assign({
                        code: 'UnexpectedDefaultValue',
                        'id': name,
                        msg: name + ' default value is faulty. ' + typeof(schema.default) + ' given but not expected'
                    }, err);
                }
            }
        }
    }
    if (value !== undefined) {

        // Check if null value set and is allowed
        if ((schema.hasOwnProperty('nullable') && schema.nullable === true) && value == null) {
            value = null;
        }
        else {
            //Check type
            if (schema.hasOwnProperty('type')) {
                var type = schema.type;
                if (_.isFunction(type) && type.name.toLowerCase()) {
                    type = type.name.toLowerCase();
                }
                var validValue = validationRule.checkType(type, value);
                if (validValue === undefined) {
                    err = _.assign({
                        code: 'UnexpectedType',
                        'id': name,
                        msg: name + ' is unexpected type. ' + typeof(value) + ' given ' + type.toLowerCase() + ' expected'
                    }, err);
                }
                else {
                    value = validValue;
                }
            }

            //Validate single value
            if ((_.isString(value) || _.isBoolean(value) || _.isNumber(value))) {

                //Check minLength
                if (schema.hasOwnProperty('minLength')) {
                    if (validationRule.minLength(schema.minLength, value) == false) {
                        err = _.assign({
                            code: 'MinLengthUnderachieved',
                            'id': name,
                            msg: name + ' length is less than ' + schema.minLength + ' chars'
                        }, err);
                    }
                }

                //Check maxLength
                if (schema.hasOwnProperty('maxLength')) {
                    if (validationRule.maxLength(schema.maxLength, value) == false) {
                        err = _.assign({
                            code: 'MaxLengthExceeded',
                            'id': name,
                            msg: name + ' length is more than ' + schema.maxLength + ' chars'
                        }, err);
                    }
                }


                //Check min
                if (schema.hasOwnProperty('min')) {
                    if (typeof(value) == 'number') {
                        if (validationRule.min(schema.min, value) == false) {
                            err = _.assign({
                                code: 'MinValueUnderachived',
                                'id': name,
                                msg: name + ' value is less than ' + schema.min
                            }, err);
                        }
                    }
                }

                //Check max
                if (schema.hasOwnProperty('max')) {
                    if (typeof(value) == 'number') {
                        if (validationRule.max(schema.max, value) == false) {
                            err = _.assign({
                                code: 'MaxValueExceeded',
                                'id': name,
                                msg: name + ' value is more than ' + schema.max
                            }, err);
                        }
                    }
                }

                //Check allow
                if (schema.hasOwnProperty('allow')) {
                    if (typeof(value) == 'number' || typeof(value) == 'string') {
                        if (validationRule.allow(schema.allow, value) == false) {
                            err = _.assign({
                                code: 'ValueNotAllowed',
                                'id': name,
                                msg: name + ' value \'' + value + '\' is not allowed. Use one of the following values: ' + (schema.allow).join(",")
                            }, err);
                        }
                    }
                }

                //Check deny
                if (schema.hasOwnProperty('deny')) {
                    if (typeof(value) == 'number' || typeof(value) == 'string') {
                        if (validationRule.deny(schema.deny, value) == false) {
                            err = _.assign({
                                code: 'ValueNotAllowed',
                                'id': name,
                                msg: name + ' value \'' + value + '\' is not allowed. Do not use one of the following values: ' + (schema.deny).join(",")
                            });
                        }
                    }
                }

                //Check match
                if (schema.hasOwnProperty('match')) {
                    if (validationRule.match(schema.match, value) == false) {
                        err = _.assign({
                            code: 'PatternMismatch',
                            'id': name,
                            msg: name + ' does not match pattern ' + schema.match + ''
                        }, err);
                    }
                }


                // Convert values
                value = convert.convertValue(schema, value);
            }
        }

        //Validate Array
        if (_.isArray(value)) {
            for (var thisVal in value) {
                valCount++;
                // Check if null value set and is allowed
                if ((schema.hasOwnProperty('nullable') && schema.nullable === true) && value == null) {
                    value = null;
                }
                else {
                    //Check type
                    if (schema.hasOwnProperty('subType')) {
                        if (_.isFunction(schema.subType) && (schema.subType.name).toLowerCase()) {
                            schema.subType = (schema.subType.name).toLowerCase();
                        }
                        var validSubValue = validationRule.checkType(schema.subType, value[thisVal]);
                        if (validSubValue === undefined) {
                            err = _.assign({
                                code: 'UnexpectedType',
                                'id': name,
                                msg: name + '[' + valCount + ']' + ' is unexpected type. ' + typeof(value[thisVal]) + ' given ' + (schema.subType).toLowerCase() + ' expected'
                            }, err);
                        }
                        else {
                            value[thisVal] = validSubValue;
                        }
                    }

                    //Check minLength
                    if (schema.hasOwnProperty('minLength')) {
                        if (validationRule.minLength(schema.minLength, value[thisVal]) == false) {
                            err = _.assign({
                                code: 'MinLengthUnderachieved',
                                'id': name,
                                msg: name + '[' + valCount + ']' + ' length is less than ' + schema.minLength + ' chars'
                            }, err);
                        }
                    }

                    //Check maxLength
                    if (schema.hasOwnProperty('maxLength')) {
                        if (validationRule.maxLength(schema.maxLength, value[thisVal]) == false) {
                            err = _.assign({
                                code: 'MaxLengthExceeded',
                                'id': name,
                                msg: name + '[' + valCount + ']' + ' length is more than ' + schema.maxLength + ' chars'
                            }, err);
                        }
                    }


                    //Check min
                    if (schema.hasOwnProperty('min')) {
                        if (typeof(value) == 'number') {
                            if (validationRule.min(schema.min, value[thisVal]) == false) {
                                err = _.assign({
                                    code: 'MinValueUnderachived',
                                    'id': name,
                                    msg: name + '[' + valCount + ']' + ' value is less than ' + schema.min
                                }, err);
                            }
                        }
                    }

                    //Check max
                    if (schema.hasOwnProperty('max')) {
                        if (typeof(value) == 'number') {
                            if (validationRule.max(schema.max, value[thisVal]) == false) {
                                err = _.assign({
                                    code: 'MaxValueExceeded',
                                    'id': name,
                                    msg: name + '[' + valCount + ']' + ' value is more than ' + schema.max
                                }, err);
                            }
                        }
                    }

                    //Check allow
                    if (schema.hasOwnProperty('allow')) {
                        if (typeof(value) == 'number' || typeof(value[thisVal]) == 'string') {
                            if (validationRule.allow(schema.allow, value[thisVal]) == false) {
                                err = _.assign({
                                    code: 'ValueNotAllowed',
                                    'id': name,
                                    msg: name + '[' + valCount + ']' + ' value \'' + value[thisVal] + '\' is not allowed. Use one of the following values: ' + (schema.allow).join(",")
                                }, err);
                            }
                        }
                    }

                    //Check deny
                    if (schema.hasOwnProperty('deny')) {
                        if (typeof(value) == 'number' || typeof(value[thisVal]) == 'string') {
                            if (validationRule.deny(schema.deny, value[thisVal]) == false) {
                                err = _.assign({
                                    code: 'ValueNotAllowed',
                                    'id': name,
                                    msg: name + '[' + valCount + ']' + ' value \'' + value[thisVal] + '\' is not allowed. Do not use one of the following values: ' + (schema.deny).join(",")
                                });
                            }
                        }
                    }

                    //Check match
                    if (schema.hasOwnProperty('match')) {
                        if (validationRule.match(schema.match, value[thisVal]) == false) {
                            err = _.assign({
                                code: 'PatternMismatch',
                                'id': name,
                                msg: name + '[' + valCount + ']' + ' does not match pattern ' + schema.match + ''
                            }, err);
                        }
                    }
                    // Convert values
                    value[thisVal] = convert.convertValue(schema, value[thisVal]);
                }
            }
        }
    }


    //Check required
    if (schema.hasOwnProperty('required')) {
        if (options && options.partial !== true) {
            if (schema.required == true && (value == undefined || value == "")) {
                if ((schema.hasOwnProperty('public') && schema.public.hasOwnProperty('set') && schema.public.set == false) || (schema.hasOwnProperty('nullable') && schema.nullable === true && _.isNull(value))) {

                }
                else {
                    err = _.assign({
                        code: 'MissingRequiredParameter',
                        id: name,
                        msg: name + ' is required but invalid value or no value given'
                    }, err);
                }
            }
        }
    }

    //Check public
    if (schema.hasOwnProperty('public')) {
        if (schema.public == false || ((schema.public.hasOwnProperty('get') && schema.public.get != true))) {
            value = undefined;
        }
    }
    callback(err, value);
}
1198097
function _generate(schemaName) {
  var schema = generateSchema(schemaName, this._instructions, this._macros, this._opts.strict);
  this.ajv.removeSchema(schema.id);
  return schema;
}
383692
function (schema) {
		if (!schema.key || schema.key === 'base' || !Array.isArray(schema.fields)) {
			return null;
			// throw exception?
		}
		// store it for later reference
		Schemas[schema.key] = schema;
		// add this schema to the NPC object so we can use it as a constructor
		// this could overwrite is that ok?
		const Base = NPC[schema.key] = function () {
			// in case we add something to NPC constructor that we need to call?
			// NPC.Base.call(this);
		};
		Base.prototype = new NPC.Base();
		Base.prototype.constructor = Base;
		Base.prototype.schema = schema.key;
		Base.prototype.fields = [];
		Base.prototype.helpers = {};
		
		// initialize schema properties...
		schema.fields.forEach((f) => {
			let default_ = null;
			switch (f.type) {
				case 'string':
				case 'text':
					default_ = '';
					break;
				case 'array':
					default_ = [];
					break;
				case 'number':
				case 'modifier':
					default_ = 0;
					break;
				case undefined:
					// ?
					break;
			}
			Base.prototype.fields[f.key] = default_;
		});
		
		if (!schema.helpers || typeof schema.helpers !== 'object') { return; }
		const helpers = Object.keys(schema.helpers);
		helpers.forEach((h) => {
			// if (typeof schema.helpers[h] === 'function') {
			//	Base.prototype.helpers[h] = schema.helpers[h];
			// }
			// create a function from the array
			Base.prototype.helpers[h] = new Function(...schema.helpers[h]);
		});
	}
201816
function convertLegacyPluginSchema(schema) {
      var result = {properties: {}, type: 'object'};
      Object.keys(schema.fields).forEach(function (propertyName) {
        result.properties[propertyName] = {
          type: schema.fields[propertyName].type
        };
        if (schema.fields[propertyName].enum) {
          result.properties[propertyName].enum = schema.fields[propertyName].enum;
        }
        if (schema.fields[propertyName].hasOwnProperty('default')) {
          result.properties[propertyName].default = schema.fields[propertyName].default;
        }
        if (schema.fields[propertyName].hasOwnProperty('required')) {
          result.properties[propertyName].required = schema.fields[propertyName].required;
        }
        if (result.properties[propertyName].type === 'table') {
          result.properties[propertyName].type = 'object';
          if (schema.fields[propertyName].schema.flexible) {
            result.properties[propertyName].additionalProperties = convertLegacyPluginSchema(schema.fields[propertyName].schema);
          } else {
            result.properties[propertyName].properties = convertLegacyPluginSchema(schema.fields[propertyName].schema).properties;
          }
        }

        if (result.properties[propertyName].type === 'array') {
          // by default, assuming the elements of a property of type array is a string, since it's
          // the case most of the time, and Kong doesn't provide the types of the elements of array properties :(
          result.properties[propertyName].items = {type: 'string'}
        }

      });
      return result;
    }
400265
function findDefinition(schema, ref) {
  var propertyPath = ref.split('/').slice(1); // Ignore the #/uri at the beginning.
  var currentProperty = propertyPath.splice(0, 1)[0];

  var currentValue = schema;

  while (currentProperty) {
    currentValue = currentValue[currentProperty];
    currentProperty = propertyPath.splice(0, 1)[0];
  }

  return currentValue;
}
1028340
function initJsonSchema (args) {
    // get global validator instance
    var validator = this.global().validator
    // get schema id based on model name - must be globally unique
    this.schemaId = '/model/'+this.name
    // set option to perform schema validation on created/update
    this.validateSchema = args.validate === false ? false : true
    // create schema for model
    var schema = this.schemaMeta = {
        id: this.schemaId,
        properties: {},
        required: [],
        type: 'object',
    }
    // get data column
    var dataColumn = this.columnName('data')
    // create entry in schema for data if model has data
    if (dataColumn) {
        // schema id for data only
        this.schemaDataId = '/model/'+this.name+'/data'
        // create data schema - meta and data schemas are compiled without
        // ref so that the complete schemas can be easily sent to clients
        var schemaData = this.schemaData = schema.properties[dataColumn] = {
            additionalProperties: args.additionalProperties,
            id: this.schemaDataId,
            properties: {},
            type: 'object',
        }
        // merge schema from args over data schema
        _.merge(schemaData.properties, args.properties)
        // if required properties are set then add
        if (args.required) {
            // required must be array
            if (typeof args.required === 'string') {
                args.required = [args.required]
            }
            // throw error if not array
            assert.ok(Array.isArray(args.required), 'required must be array or string')
            // add list of required properties
            schemaData.required = args.required
        }
        // add data schema
        validator.addSchema(schemaData, this.schemaDataId)
    }
    // create schema for each default column
    _.each(this.defaultColumns, (defaultName, columnName) => {
        // skip data column which is already specified
        if (defaultName === 'data') {
            return
        }
        // get column spec
        var column = this.columns[columnName]
        // if there is not schema for type then skip
        if (!defaultSchemas[column.type]) {
            return
        }
        // get column schema
        var columnSchema = _.cloneDeep(defaultSchemas[column.type])
        // set default schema based on type
        schema.properties[columnName] = columnSchema
        // make property required unless nullable
        if (column.null === false) {
            schema.required.push(columnName)
        }
    })
    // add schema
    validator.addSchema(schema, this.schemaId)
}
907022
function Schema(options, descriptors) {

    if (!descriptors) {
        descriptors = options;
        options = null;
    }

    function opt(name, type) {
        var value = options[name];
        if (value !== undefined) {
            if (typeof value === type) return value;
            else throw new TypeError(current + 'options : ' + name + ': "' +
                value + '" is not of type [' + type + ']');
        }
        else return false;
    }

    var current = 'Schema: arguments: ',
        defaults = { required: false };

    if (hasValue(options)) {
        if (type(options) === 'object') {
            defaults.required = opt('required', 'boolean');
            if (opt('validator', 'function')) defaults.validator = options.validator;
        }
        else throw new TypeError(current + 'options: must be of type [object]');
    }

    current += 'descriptors: ';
    if (typeof descriptors !== 'object')
        throw new TypeError(current + 'must be of type [object]');
    if (!Array.isArray(descriptors)) {
        descriptors = this.toDescriptors(descriptors, defaults);
    }
    if (options && options.extends instanceof Schema) {
        descriptors = this.extendDescriptors(descriptors, options.extends.descriptors);
    }
    if (!descriptors.length)
        throw new TypeError(current + 'contains no values');
    else if (!(descriptors[0] instanceof Descriptor)) {
        throw new TypeError(current + 'must be instances of Descriptor class');
    }
    var instance = this;
    this.descriptors = descriptors;

}
452522
public function visitSchema(Schema $schema)
    {
        return new Schema(
            $this->transformConstraintArray($schema->constraints()),
            $schema->defaultValue(),
            $schema->title(),
            $schema->description()
        );
    }
1080414
function addAnother(schema) {

    var config = {
        properties: {
            another: {
                description: 'Add another collection? (y/n)'.magenta
            }
        }
    };

    prompt.start();
    prompt.message = ' > ';
    prompt.delimiter = '';

    return new Promise(function(resolve, reject) {
        prompt.get(config, function(err, result) {

            if (err) return reject(err);

            switch (result.another.toLowerCase()) {
                case 'n':
                    return resolve({
                        answer: false,
                        schema: schema
                    });
                case 'y':
                default:
                    return resolve({
                        answer: true,
                        schema: schema
                    });
            }
        });
    });
}
819904
function dynamic(createSchema, defaults, options) {
  if (kindOf(createSchema) !== 'function') {
    if (process.env.NODE_ENV !== 'production') {
      throw new Error(
        `Dynamic structs must be defined as a function, but you passed: ${createSchema}`
      )
    } else {
      throw new Error(`Invalid schema: ${createSchema}`)
    }
  }

  const name = 'dynamic'
  const type = 'dynamic...'
  const validate = (value = resolveDefaults(defaults), data) => {
    const schema = createSchema(value, data)

    if (kindOf(schema) !== 'function') {
      if (process.env.NODE_ENV !== 'production') {
        throw new Error(
          `Dynamic structs must return a schema, but you passed: ${schema}`
        )
      } else {
        throw new Error(`Invalid schema: ${schema}`)
      }
    }

    const [error, result] = schema.validate(value)

    if (error) {
      return [error]
    }

    return [undefined, result]
  }

  return new Kind(name, type, validate)
}
486085
function setOptions(schema, options) {
  function setDefaults(array) {
    if (!array.length) {
      if (options.find) { array.push('find'); }
      if (options.findOne || !options.find) { array.push('findOne'); }
    }
  }

  options = options || {};

  options.only = options.only || [];
  options.validateBeforeSave = options.validateBeforeSave === undefined
                                ? schema.options.validateBeforeSave
                                : Boolean(options.validateBeforeSave);

  ['virtual', 'attach', 'modify'].filter(prop => options[prop])
    .forEach(
      prop => {
        if (typeof options[prop] !== 'object') {
          options[prop] = {};
        }
        options[prop].properties = options[prop].properties || {};
        options[prop].only = options[prop].only || Object.keys(options[prop].properties);
      }
    );

  if (options.modify) {
    delete options.modify.properties;
    options.modify.on = options.modify.on || [];
    setDefaults(options.modify.on);
  }
  if (options.attach) {
    Object.keys(options.attach.properties).forEach(property => {
      options.attach.properties[property].on = options.attach.properties[property].on || [];
      setDefaults(options.attach.properties[property].on);
    });
  }

  return options;
}
705818
function instantiate(schema, options) {
  options = options || {};

  /**
   * Visits each sub-object using recursion.
   * If it reaches a primitive, instantiate it.
   * @param obj - The object that represents the schema.
   * @param name - The name of the current object.
   * @param data - The instance data that represents the current object.
   */
  function visit(obj, name, data) {
    if (!obj) {
      return;
    }

    var i;
    var type = getObjectType(obj);

    // We want non-primitives objects (primitive === object w/o properties).
    if (type === 'object' && obj.properties) {
      data[name] = data[name] || { };

      // Visit each property.
      for (var property in obj.properties) {
        if (obj.properties.hasOwnProperty(property)) {
          if (shouldVisit(property, obj, options)) {
            visit(obj.properties[property], property, data[name]);
          }
        }
      }
    } else if (obj.allOf) {
      for (i = 0; i < obj.allOf.length; i++) {
        visit(obj.allOf[i], name, data);
      }
    } else if (obj.$ref) {
      obj = findDefinition(schema, obj.$ref);
      visit(obj, name, data);
    } else if (type === 'array') {
      data[name] = [];
      var len = 0;
      if (obj.minItems || obj.minItems > 0) {
        len = obj.minItems;
      }

      // Instantiate 'len' items.
      for (i = 0; i < len; i++) {
        visit(obj.items, i, data[name]);
      }
    } else if (isEnum(obj)) {
      data[name] = instantiateEnum(obj);
    } else if (isPrimitive(obj)) {
      data[name] = instantiatePrimitive(obj);
    }
  }

  var data = {};
  visit(schema, 'kek', data);
  return data['kek'];
}
644201
public function initDefaultProperties()
    {
        if (!empty($this->schema->properties)) {
            foreach ($this->schema->properties as $property_name => $property) {
                if ($this->setPropertyDefaultValue($property)) {
                    $this->property_values->$property_name = $this->getFactory()->create($property, $this->schema_path);
                }
            }
        }
    }
404042
def schema():
        """"""
        return Schema({
            'script': And(Or(type(' '), type(u' ')), len),
            Optional('title', default=''): str,
            Optional('model', default={}): {Optional(And(str, len)): object},
            Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
            Optional('item', default=None): object,
            Optional('dry_run', default=False): bool,
            Optional('debug', default=False): bool,
            Optional('strict', default=False): bool,
            Optional('variables', default={}): {
                Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
                    Or(type(' '), type(u' '))
            },
            Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
            Optional('internal', default=False): bool
        })
5049
function requireValidSchema (schema) {
    // throw error on invalid schema object
    assert.equal(typeof schema, 'object', 'schema must be object')
    assert.equal(typeof schema.columns, 'object', 'schema columns must be object')
    assert.ok(Array.isArray(schema.indexes), 'schema indexes must be array')
    // require validated schema
    return schema
}