<commit_before>var parser = require('raml-1-parser'),
    Endpoint = require('../entities/endpoint'),
    Importer = require('./importer'),
    Project = require('../entities/project'),
    jsonHelper = require('../utils/json'),
    ramlHelper = require('../helpers/raml'),
    url = require('url'),
    _ = require('lodash');

var toJSONOptions = {
	serializeMetadata: false
};
var parseOptions = {
	attributeDefaults: false
};

//TODO multi file support isn't justified

function RAML() {
  this.schemas = [];
}
RAML.prototype = new Importer();

RAML.prototype._getSecuritySchemeSettingsByName = function(schemeName) {
  var securitySchemes = this.data.securitySchemes;
  for(var i in securitySchemes) {
		if (!securitySchemes.hasOwnProperty(i)) continue;

		var entries = _.entries(securitySchemes[i]);
		for (var index = 0; index < entries.length; index++) {
			var entry = entries[index];
			var key = entry[0];
			var value = entry[1];

			if (schemeName === key) {
				return value;
			}
		}
  }
};

RAML.prototype._mapSecuritySchemes = function (securitySchemes) {
  var slSecurityScheme = {};
  for(var i in securitySchemes) {
    if (!securitySchemes.hasOwnProperty(i)) continue;
    var securityScheme = securitySchemes[i];
    for (var name in securityScheme) {
      if (!securityScheme.hasOwnProperty(name)) continue;
      var scheme = securityScheme[name];
      switch(scheme.type) {
        case 'OAuth 2.0':
          var oauth = {
            name: name, //not used in stoplight designer
            authorizationUrl: scheme.settings.authorizationUri || '',
            tokenUrl: scheme.settings.accessTokenUri || '',
            scopes: []
          };
          if (Array.isArray(scheme.scopes)) {
            for(var scopeIndex in scheme.scopes) {
              if (!scheme.scopes.hasOwnProperty(scopeIndex)) continue;
              oauth.scopes.push({
                name: scheme.scopes[scopeIndex],
                value: ''
              });
            }
          }
          //authorizationGrants are flow, only one supported in stoplight
          var flow = !_.isEmpty(scheme.settings.authorizationGrants) ? scheme.settings.authorizationGrants[0]:'code';

          switch(flow) {
            case 'code':
              oauth.flow = 'accessCode';
              break;
            case 'token':
              oauth.flow = 'implicit';
              break;
            case 'owner':
              oauth.flow = 'application';
              break;
            case 'credentials':
              oauth.flow = 'password';
              break;
          }
          slSecurityScheme['oauth2'] = oauth;
          break;
        case 'Basic Authentication':
          slSecurityScheme['basic'] = {
            name: name,
            value: '',
            description: scheme.description || ''
          };
          break;
        default:
          //TODO not supported
      }
    }
  }
  return slSecurityScheme;
};

RAML.prototype._mapRequestBody = function (methodBody) {
  return this.mapRequestBody(methodBody);
};

RAML.prototype._mapQueryString = function(queryParameters) {
  var queryString = {type:'object', properties: {}, required: []};
  for (var key in queryParameters) {
    if (!queryParameters.hasOwnProperty(key)) continue;
    var qp = queryParameters[key];
    queryString.properties[key] = ramlHelper.setParameterFields(qp, {});
    if (qp.required) {
      queryString.required.push(key);
    }
  }
  return queryString;
};

RAML.prototype._mapRequestHeaders = function (data) {
  return this._mapQueryString(data);
};

RAML.prototype._mapURIParams = function (uriParams) {
  var pathParams = {type:'object', properties: {}, required: []};

  for (var i in uriParams) {
    if (!uriParams.hasOwnProperty(i)) continue;
    var key = uriParams[i];

    pathParams.properties[key.name] = {
      description: key.displayName || key.description || '',
      type: key.type || 'string'
    };
  }
  return pathParams;
};

RAML.prototype._mapResponseBody = function(responses) {
	var data = [];
	for (var code in responses) {
		if (!responses.hasOwnProperty(code)) continue;
		var response = responses[code];
		var result = this._mapRequestBody(response.body);
		result.codes = [response.code];
		if (result.body) {
			result.body = jsonHelper.cleanSchema(result.body);
		}

		if (result.example) {
			result.example = jsonHelper.stringify(result.example, 4);
		}

		if (response.description) {
			result.description = jsonHelper.stringify(response.description);
		}
		data.push(result);
	}
	return data;
};

RAML.prototype._mapSchema = function(schemData) {
  return this.mapSchema(schemData);
};

RAML.prototype.isValidRefValues = function(values) {
	if (!_.isArray(values)) {
		return this.isValidRefValue(values);
	}
	var result = true;
	for (var index = 0; index < values.length && result == true; index++) {
		result = this.isValidRefValue(values[index]);
	}

	return result;
};

RAML.prototype.isValidRefValue = function (value) {
	return typeof value === 'string' && ramlHelper.getScalarTypes.indexOf(value) < 0 && value !== 'object';
};

// from type=type1 & schema=type1 to ref=type1
RAML.prototype.convertRefToModel = function(object) {
  // if the object is a string, that means it's a direct ref/type
  if (typeof object === 'string') {
    return {
      ref: object
    };
  }

  for (var id in object) {
    var isType = id == 'type';

		if (!object.hasOwnProperty(id)) continue;
		if (isType && _.isArray(object[id]) && object[id].length == 1) {
			object[id] = object[id][0];
		}
		var val = object[id];
		if (!val) continue;

		if (isType && this.isValidRefValues(val)) {
			object.ref = val;
			delete object[id];
		}
		else if (typeof val === 'object') {
			if (val.type && val.type == 'date-only') {
				object[id] = {<commit_msg>the intermediate stoplight structure expects defs<commit_after>var parser = require('raml-1-parser'),
    Endpoint = require('../entities/endpoint'),
    Importer = require('./importer'),
    Project = require('../entities/project'),
    jsonHelper = require('../utils/json'),
    ramlHelper = require('../helpers/raml'),
    url = require('url'),
    _ = require('lodash');

var toJSONOptions = {
	serializeMetadata: false
};
var parseOptions = {
	attributeDefaults: false
};

//TODO multi file support isn't justified

function RAML() {
  this.schemas = [];
}
RAML.prototype = new Importer();

RAML.prototype._getSecuritySchemeSettingsByName = function(schemeName) {
  var securitySchemes = this.data.securitySchemes;
  for(var i in securitySchemes) {
		if (!securitySchemes.hasOwnProperty(i)) continue;

		var entries = _.entries(securitySchemes[i]);
		for (var index = 0; index < entries.length; index++) {
			var entry = entries[index];
			var key = entry[0];
			var value = entry[1];

			if (schemeName === key) {
				return value;
			}
		}
  }
};

RAML.prototype._mapSecuritySchemes = function (securitySchemes) {
  var slSecurityScheme = {};
  for(var i in securitySchemes) {
    if (!securitySchemes.hasOwnProperty(i)) continue;
    var securityScheme = securitySchemes[i];
    for (var name in securityScheme) {
      if (!securityScheme.hasOwnProperty(name)) continue;
      var scheme = securityScheme[name];
      switch(scheme.type) {
        case 'OAuth 2.0':
          var oauth = {
            name: name, //not used in stoplight designer
            authorizationUrl: scheme.settings.authorizationUri || '',
            tokenUrl: scheme.settings.accessTokenUri || '',
            scopes: []
          };
          if (Array.isArray(scheme.scopes)) {
            for(var scopeIndex in scheme.scopes) {
              if (!scheme.scopes.hasOwnProperty(scopeIndex)) continue;
              oauth.scopes.push({
                name: scheme.scopes[scopeIndex],
                value: ''
              });
            }
          }
          //authorizationGrants are flow, only one supported in stoplight
          var flow = !_.isEmpty(scheme.settings.authorizationGrants) ? scheme.settings.authorizationGrants[0]:'code';

          switch(flow) {
            case 'code':
              oauth.flow = 'accessCode';
              break;
            case 'token':
              oauth.flow = 'implicit';
              break;
            case 'owner':
              oauth.flow = 'application';
              break;
            case 'credentials':
              oauth.flow = 'password';
              break;
          }
          slSecurityScheme['oauth2'] = oauth;
          break;
        case 'Basic Authentication':
          slSecurityScheme['basic'] = {
            name: name,
            value: '',
            description: scheme.description || ''
          };
          break;
        default:
          //TODO not supported
      }
    }
  }
  return slSecurityScheme;
};

RAML.prototype._mapRequestBody = function (methodBody) {
  return this.mapRequestBody(methodBody);
};

RAML.prototype._mapQueryString = function(queryParameters) {
  var queryString = {type:'object', properties: {}, required: []};
  for (var key in queryParameters) {
    if (!queryParameters.hasOwnProperty(key)) continue;
    var qp = queryParameters[key];
    queryString.properties[key] = ramlHelper.setParameterFields(qp, {});
    if (qp.required) {
      queryString.required.push(key);
    }
  }
  return queryString;
};

RAML.prototype._mapRequestHeaders = function (data) {
  return this._mapQueryString(data);
};

RAML.prototype._mapURIParams = function (uriParams) {
  var pathParams = {type:'object', properties: {}, required: []};

  for (var i in uriParams) {
    if (!uriParams.hasOwnProperty(i)) continue;
    var key = uriParams[i];

    pathParams.properties[key.name] = {
      description: key.displayName || key.description || '',
      type: key.type || 'string'
    };
  }
  return pathParams;
};

RAML.prototype._mapResponseBody = function(responses) {
	var data = [];
	for (var code in responses) {
		if (!responses.hasOwnProperty(code)) continue;
		var response = responses[code];
		var result = this._mapRequestBody(response.body);
		result.codes = [response.code];
		if (result.body) {
			result.body = jsonHelper.cleanSchema(result.body);
		}

		if (result.example) {
			result.example = jsonHelper.stringify(result.example, 4);
		}

		if (response.description) {
			result.description = jsonHelper.stringify(response.description);
		}
		data.push(result);
	}
	return data;
};

RAML.prototype._mapSchema = function(schemData) {
  return this.mapSchema(schemData);
};

RAML.prototype.isValidRefValues = function(values) {
	if (!_.isArray(values)) {
		return this.isValidRefValue(values);
	}
	var result = true;
	for (var index = 0; index < values.length && result == true; index++) {
		result = this.isValidRefValue(values[index]);
	}

	return result;
};

RAML.prototype.isValidRefValue = function (value) {
	return typeof value === 'string' && ramlHelper.getScalarTypes.indexOf(value) < 0 && value !== 'object';
};

// from type=type1 & schema=type1 to ref=type1
RAML.prototype.convertRefToModel = function(object) {
  // if the object is a string, that means it's a direct ref/type
  if (typeof object === 'string') {
    return {
      $ref: '#/definitions/' + object
    };
  }

  for (var id in object) {
    var isType = id == 'type';

		if (!object.hasOwnProperty(id)) continue;
		if (isType && _.isArray(object[id]) && object[id].length == 1) {
			object[id] = object[id][0];
		}
		var val = object[id];
		if (!val) continue;

		if (isType && this.isValidRefValues(val)) {
			object.ref = val;
			delete object[id];
		}
		else if (typeof val === 'object') {
			if (val.type && val.type == 'date-only') {
				object[id] = {
{'fraction_non_alphanumeric': 0.1378629101528947, 'fraction_numerical': 0.002748668613640268, 'mean_word_length': 2.7900390625, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2851615', 'n_tokens_mistral': 3615, 'n_tokens_neox': 3470, 'n_words': 776}