<commit_before>var toReference = require('./helpers/to-reference');

var createElementExpression = "template.createElement";
var createTextNodeExpression = "template.createTextNode";
var createEmptyTextNodeExpression = "template.createEmptyTextNode()";
var addAttributesExpression = "template.addAttributes";
var addPropsExpression = "template.addProps";
var appendChildExpression = "appendChild";

//t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.TEXT_DIRECT"))

function constructTemplateValue(t, templateElem, elemName, root, templateFunc, singleChild, parentElemName, level, index) {
	var valueName;
	var elementName;
	var typeName;

	if(root.templateValues && root.templateValues.length > 1) {
		valueName = "fragment.templateValues[" + templateElem.index + "]";
		elementName = "fragment.templateElements[" + templateElem.index + "]";
		typeName = "fragment.templateTypes[" + templateElem.index + "]";
	} else {
		valueName = "fragment.templateValue";
		elementName = "fragment.templateElement";
		typeName = "fragment.templateType";
	}

	if(singleChild) {
		templateFunc.push(
			t.IfStatement(
				t.binaryExpression("!==", t.identifier("typeof " + valueName), t.StringLiteral("object")),
				t.BlockStatement([
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elemName + ".textContent"), t.identifier(valueName))),
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName), t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.TEXT"))))
				]),
				t.BlockStatement([
					t.ExpressionStatement(
						t.AssignmentExpression("=", t.identifier(typeName), t.identifier(
							"(" + valueName + ".constructor === Array ? Inferno.FragmentValueTypes.LIST : Inferno.FragmentValueTypes.FRAGMENT)")
						)
					)
				])
			)
		);
	} else {
		var elemName = "child_" + level + "_" + index;
		templateFunc.push(
			t.variableDeclaration("var", [
				t.variableDeclarator(
					t.identifier(elemName)
				)
			])
		);
		templateFunc.push(
			t.IfStatement(
				t.binaryExpression("!==", t.identifier("typeof " + valueName), t.StringLiteral("object")),
				t.BlockStatement([
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elemName), t.memberExpression(t.identifier("Inferno"), t.identifier(createTextNodeExpression + `(${ valueName })`)))),
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName), t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.TEXT_DIRECT"))))
				]),
				t.BlockStatement([
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elemName), t.memberExpression(t.identifier("Inferno"), t.identifier(createEmptyTextNodeExpression)))),
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName), t.identifier(
							"(" + valueName + ".constructor === Array ? Inferno.FragmentValueTypes.LIST_REPLACE : Inferno.FragmentValueTypes.FRAGMENT_REPLACE)")
					))
				])
			)
		);
	}
	templateFunc.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elementName), t.identifier(elemName)))
	);
	templateFunc.push(
		t.ExpressionStatement(
			t.callExpression(
				t.memberExpression(t.identifier(parentElemName), t.identifier(appendChildExpression)),
				[t.identifier(elemName)]
			)
		)
	);
}

function constructTemplateComponentValue(t, templateElem, elemName, templateFunc, root) {
	templateFunc.push(t.variableDeclaration("var", [
		t.variableDeclarator(
			t.identifier(elemName),
			t.memberExpression(t.identifier("Inferno"), t.identifier(createEmptyTextNodeExpression))
		)
	]));
	var typeName;
	var elementName;
	if(root.templateValues.length > 1) {
		typeName = "fragment.templateTypes[" + templateElem.component.index + "]";
		elementName = "fragment.templateElements[" + templateElem.component.index + "]";
	} else {
		typeName = "fragment.templateType";
		elementName = "fragment.templateElement";
	}

	templateFunc.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName),
			t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.COMPONENT"))
		))
	);
	templateFunc.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elementName), t.identifier(elemName)))
	);
}

function constructTemplate(t, templateElem, parentElem, templateFunc, root, parentElemName, level, index) {
	var elemName;
	if (parentElem === null) {
		elemName = "root";
		//create the root: e.g. var root = Inferno.template.createElement("foo");
		if(templateElem.component) {
			//debugger;
		} else {
			templateFunc.push(t.variableDeclaration("var", [
				t.variableDeclarator(
					t.identifier(elemName),
					t.callExpression(t.memberExpression(t.identifier("Inferno"), t.identifier(createElementExpression)), [t.StringLiteral(templateElem.tag)])
				)
			]));
		}
		//assign the root to the fragment.dom
		templateFunc.push(t.ExpressionStatement(t.AssignmentExpression("=", t.identifier("fragment.dom"), t.identifier("root"))));
		level = 0;
	} else {
		elemName = "child_" + level + "_" + index;
		if(templateElem.component) {
			constructTemplateComponentValue(t, templateElem, elemName, templateFunc, root);
		} else {
			templateFunc.push(t.variableDeclaration("var", [
				t.variableDeclarator(
					t.identifier(elemName),
					t.callExpression(t.memberExpression(t.identifier("Inferno"), t.identifier(createElementExpression)), [t.StringLiteral(templateElem.tag)])
				)
			]));
		}
		templateFunc.push(
			t.ExpressionStatement(
				t.callExpression(t.memberExpression(t.identifier(parentElemName), t.identifier(appendChildExpression)), [t.identifier(elemName)])
			)
		);
		level++;
	}

	if (templateElem.children) {
		var child;
		if (templateElem.children.length > 1) {
			for (var i = 0; i < templateElem.children.length; i++) {
				var child = templateElem.children[i];
				if(typeof child === "string") {
					child = child.replace(/(\r\n|\n|\r|\t)/gm,"");
					if(child !== '') {
						templateFunc.push(
							t.ExpressionStatement(
								t.callExpression(
									t.memberExpression(t.identifier(elemName), t.identifier(appendChildExpression)),
									[t.memberExpression(t.identifier("Inferno"), t.identifier(createTextNodeExpression + `("${ child }")`))]
								)
							)
						);
					}
				} else if (child.index !== undefined) {
					constructTemplateValue(t, child, elemName, root, templateFunc, false, parentElemName, level, i);
				} else {
					constructTemplate(t, templateElem.children[i], templateElem, templateFunc, root, elemName, level, i);
				}
			}
		} else if (typeof (child = templateElem.children[0]) !== "object") {
			if(child !== undefined) {
				templateFunc.push(
					t.ExpressionStatement(
						t.AssignmentExpression("=", t.identifier(elemName + ".textContent"), t.StringLiteral(templateElem.children[0]))
					)
				);
			}
		} else if (child.index !== undefined) {
			constructTemplateValue(t, child, elemName, root, templateFunc, true, parentElemName);
		} else if (typeof child !== "object") {
			//debugger;
		} else {
			constructTemplate(t, child, templateElem, templateFunc, root, elemName, level, 0);
		}
	}

	if (templateElem.attrs && Object.keys(templateElem.attrs).length > 0) {
		//valueNam/e
		//t.identifier(templateElem.attrs)
		var attrs = t.ObjectExpression(Object.keys(templateElem.attrs).map(function(attrName) {
			var attrVal = templateElem.attrs[attrName];
			var val;
			if(attrVal && attrVal.index !== undefined) {
				val =  "fragment.templateValues[" + attrVal.index + "]";
				return t.ObjectProperty(t.identifier(attrName), t.identifier(val));
			}
			var propVal;

			if (typeof attrVal === 'string') {
				propVal = t.StringLiteral(attrVal);
			} else if (typeof attrVal === 'number') {
				propVal = t.NumericLiteral(attrVal);
			} else if (attrVal === null) {
				propVal = t.identifier('null');
			} else if (attrVal === false) {
				propVal = t.identifier('false');
			} else if (attrVal === true) {
				propVal = t.identifier('true');
			} else if (attrVal.type === 'BinaryExpression') {
				propVal = attrVal;
			} else {
				propVal = t.identifier(attrVal);
			}
			return t.ObjectProperty(t.identifier(attrName), propVal);
		}));

		templateFunc.push(
			t.ExpressionStatement(
				t.callExpression(
					t.memberExpression(t.identifier("Inferno"), t.identifier(templateElem.component ? addPropsExpression : addAttributesExpression)),
					[t.identifier(elemName), attrs, t.identifier("fragment")]
				)
			)
		);
	}
}

module.exports = function addTemplatesToModule(t, node, templateKey, root) {
	var templateFunc = [];
	constructTemplate(t, root.templateElem, null, templateFunc, root, 'root');
	node.body.push(
		t.FunctionExpression(t.identifier(templateKey), [toReference(t, "fragment")], t.BlockStatement(templateFunc))
	);
	node.body.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(templateKey + ".key"), t.StringLiteral(templateKey)))
	);
	node.body.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(templateKey + ".type"), t.memberExpression(t.identifier("Inferno"), t.identifier("TemplateTypes.TEMPLATE_API"))))
	);
}<commit_msg>refactored to use template param passed into templates<commit_after>var toReference = require('./helpers/to-reference');

var createElementExpression = "createElement";
var createTextNodeExpression = "createTextNode";
var createEmptyTextNodeExpression = "createEmptyTextNode()";
var addAttributesExpression = "addAttributes";
var addPropsExpression = "addProps";
var appendChildExpression = "appendChild";

//t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.TEXT_DIRECT"))

function constructTemplateValue(t, templateElem, elemName, root, templateFunc, singleChild, parentElemName, level, index) {
	var valueName;
	var elementName;
	var typeName;

	if(root.templateValues && root.templateValues.length > 1) {
		valueName = "fragment.templateValues[" + templateElem.index + "]";
		elementName = "fragment.templateElements[" + templateElem.index + "]";
		typeName = "fragment.templateTypes[" + templateElem.index + "]";
	} else {
		valueName = "fragment.templateValue";
		elementName = "fragment.templateElement";
		typeName = "fragment.templateType";
	}

	if(singleChild) {
		templateFunc.push(
			t.IfStatement(
				t.binaryExpression("!==", t.identifier("typeof " + valueName), t.StringLiteral("object")),
				t.BlockStatement([
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elemName + ".textContent"), t.identifier(valueName))),
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName), t.memberExpression(t.identifier("template"), t.identifier("FragmentValueTypes.TEXT"))))
				]),
				t.BlockStatement([
					t.ExpressionStatement(
						t.AssignmentExpression("=", t.identifier(typeName), t.identifier(
							"(" + valueName + ".constructor === Array ? Inferno.FragmentValueTypes.LIST : Inferno.FragmentValueTypes.FRAGMENT)")
						)
					)
				])
			)
		);
	} else {
		var elemName = "child_" + level + "_" + index;
		templateFunc.push(
			t.variableDeclaration("var", [
				t.variableDeclarator(
					t.identifier(elemName)
				)
			])
		);
		templateFunc.push(
			t.IfStatement(
				t.binaryExpression("!==", t.identifier("typeof " + valueName), t.StringLiteral("object")),
				t.BlockStatement([
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elemName), t.memberExpression(t.identifier("template"), t.identifier(createTextNodeExpression + `(${ valueName })`)))),
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName), t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.TEXT_DIRECT"))))
				]),
				t.BlockStatement([
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elemName), t.memberExpression(t.identifier("template"), t.identifier(createEmptyTextNodeExpression)))),
					t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName), t.identifier(
							"(" + valueName + ".constructor === Array ? Inferno.FragmentValueTypes.LIST_REPLACE : Inferno.FragmentValueTypes.FRAGMENT_REPLACE)")
					))
				])
			)
		);
	}
	templateFunc.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elementName), t.identifier(elemName)))
	);
	templateFunc.push(
		t.ExpressionStatement(
			t.callExpression(
				t.memberExpression(t.identifier(parentElemName), t.identifier(appendChildExpression)),
				[t.identifier(elemName)]
			)
		)
	);
}

function constructTemplateComponentValue(t, templateElem, elemName, templateFunc, root) {
	templateFunc.push(t.variableDeclaration("var", [
		t.variableDeclarator(
			t.identifier(elemName),
			t.memberExpression(t.identifier("template"), t.identifier(createEmptyTextNodeExpression))
		)
	]));
	var typeName;
	var elementName;
	if(root.templateValues.length > 1) {
		typeName = "fragment.templateTypes[" + templateElem.component.index + "]";
		elementName = "fragment.templateElements[" + templateElem.component.index + "]";
	} else {
		typeName = "fragment.templateType";
		elementName = "fragment.templateElement";
	}

	templateFunc.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(typeName),
			t.memberExpression(t.identifier("Inferno"), t.identifier("FragmentValueTypes.COMPONENT"))
		))
	);
	templateFunc.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(elementName), t.identifier(elemName)))
	);
}

function constructTemplate(t, templateElem, parentElem, templateFunc, root, parentElemName, level, index) {
	var elemName;
	if (parentElem === null) {
		elemName = "root";
		//create the root: e.g. var root = Inferno.template.createElement("foo");
		if(templateElem.component) {
			//debugger;
		} else {
			templateFunc.push(t.variableDeclaration("var", [
				t.variableDeclarator(
					t.identifier(elemName),
					t.callExpression(t.memberExpression(t.identifier("template"), t.identifier(createElementExpression)), [t.StringLiteral(templateElem.tag)])
				)
			]));
		}
		//assign the root to the fragment.dom
		templateFunc.push(t.ExpressionStatement(t.AssignmentExpression("=", t.identifier("fragment.dom"), t.identifier("root"))));
		level = 0;
	} else {
		elemName = "child_" + level + "_" + index;
		if(templateElem.component) {
			constructTemplateComponentValue(t, templateElem, elemName, templateFunc, root);
		} else {
			templateFunc.push(t.variableDeclaration("var", [
				t.variableDeclarator(
					t.identifier(elemName),
					t.callExpression(t.memberExpression(t.identifier("template"), t.identifier(createElementExpression)), [t.StringLiteral(templateElem.tag)])
				)
			]));
		}
		templateFunc.push(
			t.ExpressionStatement(
				t.callExpression(t.memberExpression(t.identifier(parentElemName), t.identifier(appendChildExpression)), [t.identifier(elemName)])
			)
		);
		level++;
	}

	if (templateElem.children) {
		var child;
		if (templateElem.children.length > 1) {
			for (var i = 0; i < templateElem.children.length; i++) {
				var child = templateElem.children[i];
				if(typeof child === "string") {
					child = child.replace(/(\r\n|\n|\r|\t)/gm,"");
					if(child !== '') {
						templateFunc.push(
							t.ExpressionStatement(
								t.callExpression(
									t.memberExpression(t.identifier(elemName), t.identifier(appendChildExpression)),
									[t.memberExpression(t.identifier("template"), t.identifier(createTextNodeExpression + `("${ child }")`))]
								)
							)
						);
					}
				} else if (child.index !== undefined) {
					constructTemplateValue(t, child, elemName, root, templateFunc, false, parentElemName, level, i);
				} else {
					constructTemplate(t, templateElem.children[i], templateElem, templateFunc, root, elemName, level, i);
				}
			}
		} else if (typeof (child = templateElem.children[0]) !== "object") {
			if(child !== undefined) {
				templateFunc.push(
					t.ExpressionStatement(
						t.AssignmentExpression("=", t.identifier(elemName + ".textContent"), t.StringLiteral(templateElem.children[0]))
					)
				);
			}
		} else if (child.index !== undefined) {
			constructTemplateValue(t, child, elemName, root, templateFunc, true, parentElemName);
		} else if (typeof child !== "object") {
			//debugger;
		} else {
			constructTemplate(t, child, templateElem, templateFunc, root, elemName, level, 0);
		}
	}

	if (templateElem.attrs && Object.keys(templateElem.attrs).length > 0) {
		//valueNam/e
		//t.identifier(templateElem.attrs)
		var attrs = t.ObjectExpression(Object.keys(templateElem.attrs).map(function(attrName) {
			var attrVal = templateElem.attrs[attrName];
			var val;
			if(attrVal && attrVal.index !== undefined) {
				val =  "fragment.templateValues[" + attrVal.index + "]";
				return t.ObjectProperty(t.identifier(attrName), t.identifier(val));
			}
			var propVal;

			if (typeof attrVal === 'string') {
				propVal = t.StringLiteral(attrVal);
			} else if (typeof attrVal === 'number') {
				propVal = t.NumericLiteral(attrVal);
			} else if (attrVal === null) {
				propVal = t.identifier('null');
			} else if (attrVal === false) {
				propVal = t.identifier('false');
			} else if (attrVal === true) {
				propVal = t.identifier('true');
			} else if (attrVal.type === 'BinaryExpression') {
				propVal = attrVal;
			} else {
				propVal = t.identifier(attrVal);
			}
			return t.ObjectProperty(t.identifier(attrName), propVal);
		}));

		templateFunc.push(
			t.ExpressionStatement(
				t.callExpression(
					t.memberExpression(t.identifier("template"), t.identifier(templateElem.component ? addPropsExpression : addAttributesExpression)),
					[t.identifier(elemName), attrs, t.identifier("fragment")]
				)
			)
		);
	}
}

module.exports = function addTemplatesToModule(t, node, templateKey, root) {
	var templateFunc = [];
	constructTemplate(t, root.templateElem, null, templateFunc, root, 'root');
	node.body.push(
		t.FunctionExpression(t.identifier(templateKey), [toReference(t, "fragment"), toReference(t, "template")], t.BlockStatement(templateFunc))
	);
	node.body.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(templateKey + ".key"), t.StringLiteral(templateKey)))
	);
	node.body.push(
		t.ExpressionStatement(t.AssignmentExpression("=", t.identifier(templateKey + ".type"), t.memberExpression(t.identifier("Inferno"), t.identifier("TemplateTypes.TEMPLATE_API"))))
	);
}<|endoftext|>


<commit_before>var osmXml = require('./osmXml'),
config = require('../config'),
errorList = require('./errorList');

var getParams = function(req) {
  // Deal with any params after a question mark
  var newParamsRaw = req._parsedUrl.query ? req._parsedUrl.query.split('&') : [];
  var newParams = {};
  newParamsRaw.map(function(params) {
    var param = params.split(/=(.*)/, 2);
    if (param.length === 2) {
      newParams[param[0].toLowerCase()] = param[1];
    }
  });
  return newParams;
};

var modifiedResults = function(req, res) {
  return {
    send: function(inData) {
      var contentType,
      indent = getParams(req).pretty ? 2 : null;

      // All OSM data is wrapped in an OSM tag
      // http://wiki.openstreetmap.org/wiki/API_v0.6#XML_Format
      var result = {
        'osm': JSON.parse(JSON.stringify(config.appInfo))
      };

      // Replace the 'name' field with 'generator'
      result.osm.generator = result.osm.name;
      delete result.osm.name;

      // Add the data to the wrapper
      for (var key in inData) {
        if (inData.hasOwnProperty(key)) {
          result.osm[key] = inData[key];
        }
      }

      if (req.params && req.params.format === 'json' || req.params.format === 'jsonp') {
        // Pretty Print JSON
        result = JSON.stringify(result,null,indent);
        contentType = 'application/json';

        // Check for jsonp
        if (getParams(req).callback) {
          contentType = 'application/javascript';
          result = [getParams(req).callback, '(', result, ');'].join('');
        }
      } else {
        // OSM XML
        contentType = 'application/xml';
        result = osmXml.convert(result, {'prettyPrint': indent});
      }

      res.set('Content-Type', contentType);
      res.send(result);
    },
    status: function(statusCode, description) {
      var returnLines = [],
      contentType = 'text/html';

      // Create a description page (this will need to be updated to use our normal template)
      if (errorList[statusCode]) {
        returnLines.push('
' + statusCode + ': ' + errorList[statusCode] + '
');
      } else {
        returnLines.push('
 Error: ' + statusCode + '
');
      }
      if (description) {
        returnLines.push('

Description:' + description + '
');
      }
      res.set('Content-Type', contentType);
      res.status(statusCode).send(returnLines.join(''));
    }
  };
};

var addMethod = function(method, path, callback, app) {

  //Extends the API calls to allow for more modification

  // Add the version number to the path
  var newPath = ['/', config.appInfo.version, '/', path, '.:format?'].join('');
  console.log(newPath);

  //create the get request
  method = method.toLowerCase();
  app[method](newPath, function(req, res) {

    // Modify the req and the res to add extra features
    var newRes = {};
    newRes.send = modifiedResults(req, res).send;
    newRes.status = modifiedResults(req, res).status;

    // Callback the original request
    callback(req, newRes);
  });
};

exports = module.exports = function(app) {
  return {
    getParams: getParams,
    allow: function(method, path, callback) {addMethod(method, path, callback, app);}
  };
};

<commit_msg>Change XML suport to xmljs_translate and add 'suppress_status_codes' options<commit_after>var xmlJs = require('../../xmljs_translator'),
config = require('../config'),
errorList = require('./errorList');

var getParams = function(req) {
  // Deal with any params after a question mark
  var newParamsRaw = req._parsedUrl.query ? req._parsedUrl.query.split('&') : [];
  var newParams = {};
  newParamsRaw.map(function(params) {
    var param = params.split(/=(.*)/, 2);
    if (param.length === 2) {
      newParams[param[0].toLowerCase()] = param[1];
    }
  });
  return newParams;
};

var modifiedResults = function(req, res) {

    var buildResponse = function(result) {
      // Converts the JSON response to pretty print, jsonp, or XML
      var indent = getParams(req).pretty ? 2 : null,
      response = {};

      if (req.params && req.params.format === 'json' || req.params.format === 'jsonp') {
        // Pretty Print JSON
        response.result = JSON.stringify(result,null,indent);
        response.contentType = 'application/json';

        // Check for jsonp
        if (getParams(req).callback) {
          response.contentType = 'application/javascript';
          response.result = [getParams(req).callback, '(', result, ');'].join('');
        }
      } else {
        // OSM XML
        response.contentType = 'application/xml';
        response.result = xmlJs.xmlify(result, {'prettyPrint': indent});
      }

      return response;
    };

  return {
    send: function(inData) {
      // Send is used to report data back to the browser
      var result, response;

      // All OSM data is wrapped in an OSM tag
      // http://wiki.openstreetmap.org/wiki/API_v0.6#XML_Format
      result = {
        'osm': JSON.parse(JSON.stringify(config.appInfo))
      };

      // Replace the 'name' field with 'generator'
      result.osm.generator = result.osm.name;
      delete result.osm.name;

      // Add the data to the wrapper
      for (var key in inData) {
        if (inData.hasOwnProperty(key)) {
          result.osm[key] = inData[key];
        }
      }

      response = buildResponse(result);
      res.set('Content-Type', response.contentType);
      res.send(response.result);
    },
    status: function(statusCode, description) {
      // Status is used for error reporting
      var result,
      contentType = 'text/html';

      // Build a description of the error
      result = {
        "error" : {
          "message": errorList[statusCode],
          "status": statusCode
        },
        parameters: getParams(req)
      };

      // Ignore the status code if the 'suppress_response_codes' tag is set
      if (getParams(req).suppress_status_codes) {
        statusCode = 200;
      }

      response = buildResponse(result);
      res.set('Content-Type', response.contentType);
      res.status(statusCode).send(response.result);
    }
  };
};

var addMethod = function(method, path, callback, app) {

  //Extends the API calls to allow for more modification

  // Add the version number to the path
  var newPath = ['/', config.appInfo.version, '/', path, '.:format?'].join('');
  console.log('addMethod', newPath);

  //create the get request
  method = method.toLowerCase();
  app[method](newPath, function(req, res) {

    // Modify the req and the res to add extra features
    var newRes = {};
    newRes.send = modifiedResults(req, res).send;
    newRes.status = modifiedResults(req, res).status;

    // Callback the original request
    callback(req, newRes);
  });
};

exports = module.exports = function(app) {
  return {
    getParams: getParams,
    allow: function(method, path, callback) {addMethod(method, path, callback, app);}
  };
};

<|endoftext|>


<commit_before>(function( $ ) {
    $.fn.select2entity = function (options) {
        this.each(function () {
            var request;

            // Keep a reference to the element so we can keep the cache local to this instance and so we can
            // fetch config settings since select2 doesn't expose its options to the transport method.
            var $s2 = $(this),
                limit = $s2.data('page-limit') || 0,
                scroll = $s2.data('scroll'),
                prefix = Date.now(),
                cache = [];

            var reqParams = $s2.data('req_params');
            if (reqParams) {
                $.each(reqParams, function (key, value) {
                    $('*[name="'+value+'"]').on('change', function () {
                        $s2.val(null);
                        $s2.trigger('change');
                    });
                });
            }

            // Deep-merge the options
            $s2.select2($.extend(true, {
                // Tags support
                createTag: function (data) {
                    if ($s2.data('tags') && data.term.length > 0) {
                        var text = data.term + $s2.data('tags-text');
                        return {id: $s2.data('new-tag-prefix') + data.term, text: text};
                    }
                },
                ajax: {
                    url: $s2.data('ajax--url') || null,
                    transport: function (params, success, failure) {
                        // is caching enabled?
                        if ($s2.data('ajax--cache')) {
                            // try to make the key unique to make it less likely for a page+q to match a real query
                            var key = prefix + ' page:' + (params.data.page || 1) + ' ' + params.data.q,
                                cacheTimeout = $s2.data('ajax--cacheTimeout');
                            // no cache entry for 'term' or the cache has timed out?
                            if (typeof cache[key] == 'undefined' || (cacheTimeout && Date.now() >= cache[key].time)) {
                                $.ajax(params).fail(failure).done(function (data) {
                                    cache[key] = {
                                        data: data,
                                        time: cacheTimeout ? Date.now() + cacheTimeout : null
                                    };
                                    success(data);
                                });
                            } else {
                                // return cached data with no ajax request
                                success(cache[key].data);
                            }
                        } else {
                            // no caching enabled. just do the ajax request
                            if (request) {
                                request.abort();
                            }
                            request = $.ajax(params).fail(failure).done(success).always(function () {
                                request = undefined;
                            });

                            return request;
                        }
                    },
                    data: function (params) {
                        var ret = {
                            'q': params.term,
                            'field_name': $s2.data('name'),
                            'class_type': $s2.data('classtype')
                        };

                        var reqParams = $s2.data('req_params');
                        if (reqParams) {
                            $.each(reqParams, function (key, value) {
                                ret[key] = $('*[name="'+value+'"]').val()
                            });
                        }

                        // only send the 'page' parameter if scrolling is enabled
                        if (scroll) {
                            ret['page'] = params.page || 1;
                        }

                        return ret;
                    },
                    processResults: function (data, params) {
                        var results, more = false, response = {};
                        params.page = params.page || 1;

                        if ($.isArray(data)) {
                            results = data;
                        } else if (typeof data == 'object') {
                            // assume remote result was proper object
                            results = data.results;
                            more = data.more;
                        } else {
                            // failsafe
                            results = [];
                        }

                        if (scroll) {
                            response.pagination = {more: more};
                        }
                        response.results = results;

                        return response;
                    }
                }
            }, options || {}));
        });
        return this;
    };
})( jQuery );

(function( $ ) {
    $(document).ready(function () {
        $('.select2entity[data-autostart="true"]').select2entity();
    });
})( jQuery );
<commit_msg>Return request object.<commit_after>(function( $ ) {
    $.fn.select2entity = function (options) {
        this.each(function () {
            var request;

            // Keep a reference to the element so we can keep the cache local to this instance and so we can
            // fetch config settings since select2 doesn't expose its options to the transport method.
            var $s2 = $(this),
                limit = $s2.data('page-limit') || 0,
                scroll = $s2.data('scroll'),
                prefix = Date.now(),
                cache = [];

            var reqParams = $s2.data('req_params');
            if (reqParams) {
                $.each(reqParams, function (key, value) {
                    $('*[name="'+value+'"]').on('change', function () {
                        $s2.val(null);
                        $s2.trigger('change');
                    });
                });
            }

            // Deep-merge the options
            $s2.select2($.extend(true, {
                // Tags support
                createTag: function (data) {
                    if ($s2.data('tags') && data.term.length > 0) {
                        var text = data.term + $s2.data('tags-text');
                        return {id: $s2.data('new-tag-prefix') + data.term, text: text};
                    }
                },
                ajax: {
                    url: $s2.data('ajax--url') || null,
                    transport: function (params, success, failure) {
                        // is caching enabled?
                        if ($s2.data('ajax--cache')) {
                            // try to make the key unique to make it less likely for a page+q to match a real query
                            var key = prefix + ' page:' + (params.data.page || 1) + ' ' + params.data.q,
                                cacheTimeout = $s2.data('ajax--cacheTimeout');
                            // no cache entry for 'term' or the cache has timed out?
                            if (typeof cache[key] == 'undefined' || (cacheTimeout && Date.now() >= cache[key].time)) {
                                return $.ajax(params).fail(failure).done(function (data) {
                                    cache[key] = {
                                        data: data,
                                        time: cacheTimeout ? Date.now() + cacheTimeout : null
                                    };
                                    success(data);
                                });
                            } else {
                                // return cached data with no ajax request
                                success(cache[key].data);
                            }
                        } else {
                            // no caching enabled. just do the ajax request
                            if (request) {
                                request.abort();
                            }
                            request = $.ajax(params).fail(failure).done(success).always(function () {
                                request = undefined;
                            });

                            return request;
                        }
                    },
                    data: function (params) {
                        var ret = {
                            'q': params.term,
                            'field_name': $s2.data('name'),
                            'class_type': $s2.data('classtype')
                        };

                        var reqParams = $s2.data('req_params');
                        if (reqParams) {
                            $.each(reqParams, function (key, value) {
                                ret[key] = $('*[name="'+value+'"]').val()
                            });
                        }

                        // only send the 'page' parameter if scrolling is enabled
                        if (scroll) {
                            ret['page'] = params.page || 1;
                        }

                        return ret;
                    },
                    processResults: function (data, params) {
                        var results, more = false, response = {};
                        params.page = params.page || 1;

                        if ($.isArray(data)) {
                            results = data;
                        } else if (typeof data == 'object') {
                            // assume remote result was proper object
                            results = data.results;
                            more = data.more;
                        } else {
                            // failsafe
                            results = [];
                        }

                        if (scroll) {
                            response.pagination = {more: more};
                        }
                        response.results = results;

                        return response;
                    }
                }
            }, options || {}));
        });
        return this;
    };
})( jQuery );

(function( $ ) {
    $(document).ready(function () {
        $('.select2entity[data-autostart="true"]').select2entity();
    });
})( jQuery );
<|endoftext|>


<commit_before>/* jshint node:true */
var path = require("path");
var webpack = require("webpack");

module.exports = {
  entry: "./demo/index.js",
  output: {
    path: path.join(__dirname, "demo"),
    filename: "bundle.js",
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: "babel?loose=all", exclude: [/rx\.lite\.js$/] },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      {
        test: /\.(otf|eot|svg|ttf|woff)/,
        loader: "url-loader"
      }
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      "__DEV__": true,
      "__RX_PLAYER_VERSION_PLACEHOLDER__": JSON.stringify("0.0.0-demo"),
    }),
  ]
};
<commit_msg>webpack: add resolveLoader fallback<commit_after>/* jshint node:true */
var path = require("path");
var webpack = require("webpack");

module.exports = {
  entry: "./demo/index.js",
  output: {
    path: path.join(__dirname, "demo"),
    filename: "bundle.js",
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: "babel?loose=all", exclude: [/rx\.lite\.js$/] },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      {
        test: /\.(otf|eot|svg|ttf|woff)/,
        loader: "url-loader"
      }
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      "__DEV__": true,
      "__RX_PLAYER_VERSION_PLACEHOLDER__": JSON.stringify("0.0.0-demo"),
    }),
  ],
  resolveLoader: {
    fallback: path.join(__dirname, "node_modules")
  }
};
<|endoftext|>


<commit_before>// NOTE: Don't use this config by itself! It is just a parent for the dev and production configs.

const _ = require('lodash')
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const glob = require('glob')
require('coffee-script')
require('coffee-script/register')
const CompileStaticTemplatesPlugin = require('./compile-static-templates')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

console.log('Starting Webpack...')

// Main webpack config
module.exports = (env) => {
  if (!env) env = {}
  return {
    context: path.resolve(__dirname),
    entry: {
      // NOTE: If you add an entrypoint, consider updating ViewLoadTimer to track its loading.
      app: './app/app.js',
      world: glob.sync('./app/lib/world/**/*.*').concat([ // For worker_world
        './app/lib/worldLoader',
        './app/core/CocoClass.coffee',
        './app/core/utils.coffee',
        './vendor/scripts/string_score.js',
        './bower_components/underscore.string',
        './vendor/scripts/coffeescript.js'
      ]),
      lodash: 'lodash', // For worker_world
      aether: './app/lib/aether/aether.coffee' // For worker_world
      // esper: './bower_components/esper.js/esper.js',
      // vendor: './app/vendor.js'
    },
    output: {
      filename: 'javascripts/[name].js', // TODO: Use chunkhash in layout.static.pug's script tags instead of GIT_SHA
      // chunkFilename is determined by build type
      path: path.resolve(__dirname, 'public'),
      publicPath: '/' // Base URL path webpack tries to load other bundles from
    },
    module: {
      noParse: function (name) { // These are already built into commonjs bundles
        return _.any([
          /vendor.*coffeescript/,
          /bower_components.*aether/,
          /bower_components.*jsondiffpatch.*\.js$/,
          /fuzzaldrin/
        ], (regex) => { return regex.test(name) })
      },
      rules: [
        { test: require.resolve('cookieconsent'), use: 'exports-loader?cookieconsent' },
        { test: /\.vue$/, use: [{ loader: 'vue-loader' }] },
        { test: /vendor\/scripts\/async.js/, use: [ { loader: 'imports-loader?root=>window' } ] },
        { test: /\.js$/,
          exclude: /(node_modules|bower_components|vendor)/,
          use: [{
            loader: 'babel-loader'
          }]
        },
        { test: /\.coffee$/,
          use: [
            { loader: 'coffee-loader' }
          ] },
        { test: /\.pug$/,
          oneOf: [
            // applies to <template lang="pug"> in Vue components
            {
              resourceQuery: /^\?vue/,
              //use: ['pug-plain-loader']
              use: ['vue-pug-loader']
            },
            // applies to all other pug imports
            {
              use: { loader: 'pug-loader', options: { root: path.resolve('./app') } }
            }
          ]
        },
        { test: /\.jade$/,
          use: [{ loader: 'jade-loader', options: { root: path.resolve('./app') } }]
        },
        {
          oneOf: [
            { test: /jquery-ui.*css$/,
              use: [ // So we can ignore the images it references that we are missing
                { loader: 'style-loader' },
                { loader: 'css-loader', options: { url: false } }
              ] },
            { test: /\.css$/,
              use: [
                { loader: 'style-loader' },
                {
                  loader: MiniCssExtractPlugin.loader,
                  options: {
                    esModule: false
                  }
                },
                {
                  loader: 'css-loader',
                  options: {
                    url: false
                  }
                },
              ] }
          ]
        },
        { test: /\.sass$/,
          use: [
            'vue-style-loader',
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                esModule: false
              }
            },
            {
              loader: 'css-loader',
              options: {
                url: false
              }
            },
            {
              loader: 'sass-loader',
              options: {
                implementation: require("sass"),
                sassOptions: {
                  indentedSyntax: true
                }
              }
            },
            { loader: 'import-glob-loader' }
          ]
        },
        { test: /\.scss$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                esModule: false
              }
            },
            {
              loader: 'css-loader',
              options: {
                url: false
              }
            },
            {
              loader: 'sass-loader',
              options: {
                implementation: require("sass"),
              }
            }
          ]
        },
        {
          test: /\.mjs$/, // https://github.com/formatjs/formatjs/issues/1395#issuecomment-518823361
          include: /node_modules/,
          type: "javascript/auto"
        }
      ]
    },
    resolve: {
      modules: [ // This section denotes what folders you can use as a root in a require statement
        path.resolve('./app'), // eg require('vendor.js') gets /app/vendor.js
        path.resolve('./app/assets'), // eg require('images/favicon/favicon.ico') gets /app/assets/images/favicon/favicon.ico
        path.resolve('./'), // Or you can use the full path /app/whatever
        'node_modules' // Or maybe require('foo') for the Node module "foo".
      ],
      extensions: ['.web.coffee', '.web.js', '.coffee', '.js', '.jade', '.pug', '.sass', '.vue'],
      alias: { // Replace Backbone's underscore with lodash
        'underscore': 'lodash'
      },
      // https://github.com/facebook/create-react-app/issues/11756#issuecomment-1047253186
      fallback: {
        util: require.resolve('util/'), // because of 'console-browserify' package used by jshint, details: https://github.com/facebook/create-react-app/issues/11756
        assert: require.resolve('assert/'), // because of 'console-browserify'
      }
    },
    externals: {
      'esper.js': 'esper'
    },
    plugins: [
      new webpack.ProgressPlugin({ profile: false }), // Always show build progress
      new MiniCssExtractPlugin({ // Move CSS into external file
        filename: 'stylesheets/[name].css',
        chunkFilename: 'stylesheets/[name]-[contenthash].css',
        ignoreOrder: true
      }),
      new webpack.ProvidePlugin({ // So Bootstrap can use the global jQuery
        $: 'jquery',
        jQuery: 'jquery',
        application: path.resolve(__dirname, 'app/core/application')
      }),
      new webpack.IgnorePlugin({ resourceRegExp: /\/fonts\/bootstrap\/.*$/ }), // Ignore Bootstrap's fonts
      new webpack.IgnorePlugin({ resourceRegExp: /^memwatch$/ }), // Just used by the headless client on the server side
      new webpack.IgnorePlugin({ resourceRegExp: /.DS_Store$/ }),

      // Enable IgnorePlugins for development to speed webpack
      // new webpack.IgnorePlugin(/\!locale/),
      // new webpack.IgnorePlugin(/\/admin\//),
      // new webpack.IgnorePlugin(/\/artisan\//),
      // new webpack.IgnorePlugin(/\/clans\//),
      // new webpack.IgnorePlugin(/\/contribute\//),
      // new webpack.IgnorePlugin(/\/courses\//),
      // new webpack.IgnorePlugin(/\/editor\//),
      // new webpack.IgnorePlugin(/\/ladder\//),
      // new webpack.IgnorePlugin(/\/teachers\//),
      // new webpack.IgnorePlugin(/\/play\//),
      new CopyWebpackPlugin({
        patterns: [
          // NOTE: If you add a static asset, consider updating ViewLoadTimer to track its loading.
          { // Static assets
            // Let's use file-loader down the line, but for now, just use URL references.
            from: 'app/assets',
            to: '.'
          }, { // Ace
            context: 'bower_components/ace-builds/src-min-noconflict',
            from: '**/*',
            to: 'javascripts/ace'
          }, { // Esper
            from: 'bower_components/esper.js/esper.js',
            to: 'javascripts/esper.js'
          }, {
            from: 'bower_components/esper.js/esper-modern.js',
            to: 'javascripts/esper.modern.js'
          }, {
            from: 'vendor/esper-plugin-lang-java-modern.js',
            to: 'javascripts/app/vendor/aether-java.modern.js'
          }, {
            from: 'vendor/esper-plugin-lang-cpp-modern.js',
            to: 'javascripts/app/vendor/aether-cpp.modern.js'
          }
        ]
      }),
      new CompileStaticTemplatesPlugin({
        locals: { shaTag: process.env.GIT_SHA || 'dev', chinaInfra: process.env.COCO_CHINA_INFRASTRUCTURE || false }
      }),
      new VueLoaderPlugin(),
      new webpack.ProvidePlugin({
        process: 'process/browser' // because of algoliasearch which needs access to process: https://github.com/algolia/docsearch/issues/980
      })
    ],
    stats: 'minimal'
  }
}
<commit_msg>fix jquery-ui css not loading (#6563)<commit_after>// NOTE: Don't use this config by itself! It is just a parent for the dev and production configs.

const _ = require('lodash')
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const glob = require('glob')
require('coffee-script')
require('coffee-script/register')
const CompileStaticTemplatesPlugin = require('./compile-static-templates')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

console.log('Starting Webpack...')

// Main webpack config
module.exports = (env) => {
  if (!env) env = {}
  return {
    context: path.resolve(__dirname),
    entry: {
      // NOTE: If you add an entrypoint, consider updating ViewLoadTimer to track its loading.
      app: './app/app.js',
      world: glob.sync('./app/lib/world/**/*.*').concat([ // For worker_world
        './app/lib/worldLoader',
        './app/core/CocoClass.coffee',
        './app/core/utils.coffee',
        './vendor/scripts/string_score.js',
        './bower_components/underscore.string',
        './vendor/scripts/coffeescript.js'
      ]),
      lodash: 'lodash', // For worker_world
      aether: './app/lib/aether/aether.coffee' // For worker_world
      // esper: './bower_components/esper.js/esper.js',
      // vendor: './app/vendor.js'
    },
    output: {
      filename: 'javascripts/[name].js', // TODO: Use chunkhash in layout.static.pug's script tags instead of GIT_SHA
      // chunkFilename is determined by build type
      path: path.resolve(__dirname, 'public'),
      publicPath: '/' // Base URL path webpack tries to load other bundles from
    },
    module: {
      noParse: function (name) { // These are already built into commonjs bundles
        return _.any([
          /vendor.*coffeescript/,
          /bower_components.*aether/,
          /bower_components.*jsondiffpatch.*\.js$/,
          /fuzzaldrin/
        ], (regex) => { return regex.test(name) })
      },
      rules: [
        { test: require.resolve('cookieconsent'), use: 'exports-loader?cookieconsent' },
        { test: /\.vue$/, use: [{ loader: 'vue-loader' }] },
        { test: /vendor\/scripts\/async.js/, use: [ { loader: 'imports-loader?root=>window' } ] },
        { test: /\.js$/,
          exclude: /(node_modules|bower_components|vendor)/,
          use: [{
            loader: 'babel-loader'
          }]
        },
        { test: /\.coffee$/,
          use: [
            { loader: 'coffee-loader' }
          ] },
        { test: /\.pug$/,
          oneOf: [
            // applies to <template lang="pug"> in Vue components
            {
              resourceQuery: /^\?vue/,
              //use: ['pug-plain-loader']
              use: ['vue-pug-loader']
            },
            // applies to all other pug imports
            {
              use: { loader: 'pug-loader', options: { root: path.resolve('./app') } }
            }
          ]
        },
        { test: /\.jade$/,
          use: [{ loader: 'jade-loader', options: { root: path.resolve('./app') } }]
        },
        {
          oneOf: [
            { test: /jquery-ui.*css$/,
              use: [ // So we can ignore the images it references that we are missing
                { loader: 'style-loader' },
                {
                  loader: MiniCssExtractPlugin.loader,
                  options: {
                    esModule: false
                  }
                },
                { loader: 'css-loader', options: { url: false } }
              ] },
            { test: /\.css$/,
              use: [
                { loader: 'style-loader' },
                {
                  loader: MiniCssExtractPlugin.loader,
                  options: {
                    esModule: false
                  }
                },
                {
                  loader: 'css-loader',
                  options: {
                    url: false
                  }
                },
              ] }
          ]
        },
        { test: /\.sass$/,
          use: [
            'vue-style-loader',
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                esModule: false
              }
            },
            {
              loader: 'css-loader',
              options: {
                url: false
              }
            },
            {
              loader: 'sass-loader',
              options: {
                implementation: require("sass"),
                sassOptions: {
                  indentedSyntax: true
                }
              }
            },
            { loader: 'import-glob-loader' }
          ]
        },
        { test: /\.scss$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
              options: {
                esModule: false
              }
            },
            {
              loader: 'css-loader',
              options: {
                url: false
              }
            },
            {
              loader: 'sass-loader',
              options: {
                implementation: require("sass"),
              }
            }
          ]
        },
        {
          test: /\.mjs$/, // https://github.com/formatjs/formatjs/issues/1395#issuecomment-518823361
          include: /node_modules/,
          type: "javascript/auto"
        }
      ]
    },
    resolve: {
      modules: [ // This section denotes what folders you can use as a root in a require statement
        path.resolve('./app'), // eg require('vendor.js') gets /app/vendor.js
        path.resolve('./app/assets'), // eg require('images/favicon/favicon.ico') gets /app/assets/images/favicon/favicon.ico
        path.resolve('./'), // Or you can use the full path /app/whatever
        'node_modules' // Or maybe require('foo') for the Node module "foo".
      ],
      extensions: ['.web.coffee', '.web.js', '.coffee', '.js', '.jade', '.pug', '.sass', '.vue'],
      alias: { // Replace Backbone's underscore with lodash
        'underscore': 'lodash'
      },
      // https://github.com/facebook/create-react-app/issues/11756#issuecomment-1047253186
      fallback: {
        util: require.resolve('util/'), // because of 'console-browserify' package used by jshint, details: https://github.com/facebook/create-react-app/issues/11756
        assert: require.resolve('assert/'), // because of 'console-browserify'
      }
    },
    externals: {
      'esper.js': 'esper'
    },
    plugins: [
      new webpack.ProgressPlugin({ profile: false }), // Always show build progress
      new MiniCssExtractPlugin({ // Move CSS into external file
        filename: 'stylesheets/[name].css',
        chunkFilename: 'stylesheets/[name]-[contenthash].css',
        ignoreOrder: true
      }),
      new webpack.ProvidePlugin({ // So Bootstrap can use the global jQuery
        $: 'jquery',
        jQuery: 'jquery',
        application: path.resolve(__dirname, 'app/core/application')
      }),
      new webpack.IgnorePlugin({ resourceRegExp: /\/fonts\/bootstrap\/.*$/ }), // Ignore Bootstrap's fonts
      new webpack.IgnorePlugin({ resourceRegExp: /^memwatch$/ }), // Just used by the headless client on the server side
      new webpack.IgnorePlugin({ resourceRegExp: /.DS_Store$/ }),

      // Enable IgnorePlugins for development to speed webpack
      // new webpack.IgnorePlugin(/\!locale/),
      // new webpack.IgnorePlugin(/\/admin\//),
      // new webpack.IgnorePlugin(/\/artisan\//),
      // new webpack.IgnorePlugin(/\/clans\//),
      // new webpack.IgnorePlugin(/\/contribute\//),
      // new webpack.IgnorePlugin(/\/courses\//),
      // new webpack.IgnorePlugin(/\/editor\//),
      // new webpack.IgnorePlugin(/\/ladder\//),
      // new webpack.IgnorePlugin(/\/teachers\//),
      // new webpack.IgnorePlugin(/\/play\//),
      new CopyWebpackPlugin({
        patterns: [
          // NOTE: If you add a static asset, consider updating ViewLoadTimer to track its loading.
          { // Static assets
            // Let's use file-loader down the line, but for now, just use URL references.
            from: 'app/assets',
            to: '.'
          }, { // Ace
            context: 'bower_components/ace-builds/src-min-noconflict',
            from: '**/*',
            to: 'javascripts/ace'
          }, { // Esper
            from: 'bower_components/esper.js/esper.js',
            to: 'javascripts/esper.js'
          }, {
            from: 'bower_components/esper.js/esper-modern.js',
            to: 'javascripts/esper.modern.js'
          }, {
            from: 'vendor/esper-plugin-lang-java-modern.js',
            to: 'javascripts/app/vendor/aether-java.modern.js'
          }, {
            from: 'vendor/esper-plugin-lang-cpp-modern.js',
            to: 'javascripts/app/vendor/aether-cpp.modern.js'
          }
        ]
      }),
      new CompileStaticTemplatesPlugin({
        locals: { shaTag: process.env.GIT_SHA || 'dev', chinaInfra: process.env.COCO_CHINA_INFRASTRUCTURE || false }
      }),
      new VueLoaderPlugin(),
      new webpack.ProvidePlugin({
        process: 'process/browser' // because of algoliasearch which needs access to process: https://github.com/algolia/docsearch/issues/980
      })
    ],
    stats: 'minimal'
  }
}
<|endoftext|>


<commit_before>const path = require('path')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
  mode: 'development',
  devtool: 'source-map',
  entry: './src/index.tsx',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'public'),
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    plugins: [
      new TsconfigPathsPlugin({
        configFile: './tsconfig.json',
      }),
    ],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
        },
        exclude: /node_modules/,
      },
    ],
  },
}
<commit_msg>Reduce bundle size<commit_after>const path = require('path')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
  mode: 'production',
  entry: './src/index.tsx',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'public'),
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    plugins: [
      new TsconfigPathsPlugin({
        configFile: './tsconfig.json',
      }),
    ],
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
        },
        exclude: /node_modules/,
      },
    ],
  },
}
<|endoftext|>


<commit_before>/* eslint-disable */
var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var jade = require('jade')

// load env vars first
require('dotenv').load({ silent: process.env.NODE_ENV === 'production' })

module.exports = {
  entry: {
    main: './src/main',
  },
  output: {
    path: path.join(__dirname, 'public/static'),
    filename: '[name].entry.js',
    chunkFilename: '[id].chunk.js',
    hash: true,
    publicPath: '/static/',
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      ENV: JSON.stringify(require(path.join(__dirname, './env.js'))),
    }),
    new ExtractTextPlugin('bundle.css'),
    new webpack.optimize.CommonsChunkPlugin('commons'),
    new HtmlWebpackPlugin({
      filename: '../index.html',
      chunks: ['commons', 'main'],
      templateContent: jade.renderFile('public/template.jade', { pretty: true }),
      hash:true,
      inject: 'body',
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true)
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      include: path.join(__dirname, 'src'),
      exclude: /node_modules/,
    },
    {
      test: /\.sass$/,
      loader: ExtractTextPlugin.extract(
          'css!autoprefixer!sass?indentedSyntax'
      )
    }]
  }
}
<commit_msg>Tell redux it's production so it'll shut up<commit_after>/* eslint-disable */
var path = require('path')
var webpack = require('webpack')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var jade = require('jade')

// load env vars first
require('dotenv').load({ silent: process.env.NODE_ENV === 'production' })

const nodeEnv = process.env.NODE_ENV || 'development'

module.exports = {
  entry: {
    main: './src/main',
  },
  output: {
    path: path.join(__dirname, 'public/static'),
    filename: '[name].entry.js',
    chunkFilename: '[id].chunk.js',
    hash: true,
    publicPath: '/static/',
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      ENV: JSON.stringify(require(path.join(__dirname, './env.js'))),
      'process.env': { NODE_ENV: JSON.stringify(nodeEnv) },
    }),
    new ExtractTextPlugin('bundle.css'),
    new webpack.optimize.CommonsChunkPlugin('commons'),
    new HtmlWebpackPlugin({
      filename: '../index.html',
      chunks: ['commons', 'main'],
      templateContent: jade.renderFile('public/template.jade', { pretty: true }),
      hash:true,
      inject: 'body',
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true)
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      include: path.join(__dirname, 'src'),
      exclude: /node_modules/,
    },
    {
      test: /\.sass$/,
      loader: ExtractTextPlugin.extract(
          'css!autoprefixer!sass?indentedSyntax'
      )
    }]
  }
}
<|endoftext|>


<commit_before>var webpack = require('webpack');
var common = require('./webpack.common.config.js');

module.exports = {
    // Split code chunks by page
    entry: common.entry,
    resolve: common.resolve,
    externals: common.externals,
    output: common.output,
    debug: true,
    plugins: common.plugins.concat([
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.AggressiveMergingPlugin(),
        new webpack.optimize.UglifyJsPlugin({exclude: /conference(\.\w+)?\.js$/})
    ])
};
<commit_msg>Fix uglify ignore regex.<commit_after>var webpack = require('webpack');
var common = require('./webpack.common.config.js');

module.exports = {
    // Split code chunks by page
    entry: common.entry,
    resolve: common.resolve,
    externals: common.externals,
    output: common.output,
    debug: true,
    plugins: common.plugins.concat([
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.AggressiveMergingPlugin(),
        new webpack.optimize.UglifyJsPlugin({exclude: /conference.*?\.js$/})
    ])
};
<|endoftext|>


<commit_before>var path = require('path');

// currently, this is for bower
var config = {
  devtool: 'sourcemap',
  entry: {
    index: './src/react-treeview.jsx',
  },
  output: {
    path: path.join(__dirname, 'build'),
    publicPath: 'build/',
    filename: 'react-treeview.js',
    sourceMapFilename: 'react-treeview.map',
    library: 'TreeView',
    libraryTarget: 'umd',
  },
  module: {
    loaders: [{
      test: /\.(js|jsx)/,
      loader: 'babel',
    }],
  },
  plugins: [],
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  externals: {
    'react': {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react',
    },
  },
};

module.exports = config;
<commit_msg>Delete webpack.prod.config.js<commit_after><|endoftext|>


<commit_before>const webpack = require('webpack');
const Merge = require('webpack-merge');
const SentryWebpackPlugin = require('@sentry/webpack-plugin');

const CommonConfig = require('./config.common.js');
const { buildDir } = require('./paths');

const config = Merge(CommonConfig, {
  mode: 'production',

  devtool: 'source-map',

  plugins: [new webpack.HashedModuleIdsPlugin()],
});

/*
 Releasing requires the following env variables:
 - SENTRY_AUTH_TOKEN
 - SENTRY_ORG
 - SENTRY_PROJECT

 No need to have these variables in your local environment
 because we'll only ever want to do releases during a prod build.

 Given that, it's also important to have ENABLE_SENTRY_RELEASE=False
 set in your local environment.
*/

/* if (process.env.ENABLE_SENTRY_RELEASE.toLowerCase() === 'true') {
  config.plugins.push(
    new SentryWebpackPlugin({
      release: Date.now().toString(),
      include: buildDir,
    })
  );
} */

module.exports = config;
<commit_msg>uncomment<commit_after>const webpack = require('webpack');
const Merge = require('webpack-merge');
const SentryWebpackPlugin = require('@sentry/webpack-plugin');

const CommonConfig = require('./config.common.js');
const { buildDir } = require('./paths');

const config = Merge(CommonConfig, {
  mode: 'production',

  devtool: 'source-map',

  plugins: [new webpack.HashedModuleIdsPlugin()],
});

/*
 Releasing requires the following env variables:
 - SENTRY_AUTH_TOKEN
 - SENTRY_ORG
 - SENTRY_PROJECT

 No need to have these variables in your local environment
 because we'll only ever want to do releases during a prod build.

 Given that, it's also important to have ENABLE_SENTRY_RELEASE=False
 set in your local environment.
*/

if (process.env.ENABLE_SENTRY_RELEASE.toLowerCase() === 'true') {
  config.plugins.push(
    new SentryWebpackPlugin({
      release: Date.now().toString(),
      include: buildDir,
    })
  );
}

module.exports = config;
<|endoftext|>


<commit_before>var OAuth1Strategy = require('passport-oauth1');
var request = require('request');

function TrelloStrategy(options, verify) {
	options = options || {};
	options.requestTokenURL = options.requestTokenURL || 'https://trello.com/1/OAuthGetRequestToken';
	options.accessTokenURL = options.accessTokenURL || 'https://trello.com/1/OAuthGetAccessToken';
	options.userAuthorizationURL = options.userAuthorizationURL || 'https://trello.com/1/OAuthAuthorizeToken';
	options.sessionKey = options.sessionKey || 'trello';

	OAuth1Strategy.call(this, options, (req, accessToken, refreshToken, profile, done) => {
		request(
			'https://api.trello.com/1/members/me?key='+options.clientID+'&token='+accessToken,
			function (error, response, body) {
				if(error) {
					return done(error);
				}
				var profile = JSON.parse(body);
				var namePieces = profile.fullName.split(' ');
				verify(req, accessToken, refreshToken, {
					id: profile.id,
					firstName: namePieces.shift(),
					lastName: namePieces.join(' '),
					email: null
				}, done);
			}
		);
	});
	this.name = 'trello';
};
TrelloStrategy.prototype = Object.create(OAuth1Strategy.prototype);

module.exports = {
	translateProfile: (token, tokenSecret, profile, cb) => { cb(null, profile); },
	strategy: TrelloStrategy
};
<commit_msg>rename customerKey and clientID to provide consistent interface<commit_after>var OAuth1Strategy = require('passport-oauth1');
var request = require('request');

function TrelloStrategy(options, verify) {
	OAuth1Strategy.call(this, Object.assign({
		requestTokenURL: 'https://trello.com/1/OAuthGetRequestToken',
		accessTokenURL: 'https://trello.com/1/OAuthGetAccessToken',
		userAuthorizationURL: 'https://trello.com/1/OAuthAuthorizeToken',
		sessionKey: 'trello',
		consumerKey: options.clientID,
		consumerSecret: options.clientSecret
	}, options), (req, accessToken, refreshToken, profile, done) => {
		console.log(accessToken);
		request(`https://api.trello.com/1/members/me?key=${options.clientID}&token=${accessToken}`,
			(err, response, body) => {
				if (err) return done(err);
				var profile = JSON.parse(body);
				var namePieces = profile.fullName.split(' ');
				console.log(profile.id);
				verify(req, accessToken, refreshToken, {
					id: profile.id,
					firstName: namePieces.shift(),
					lastName: namePieces.join(' '),
					email: null
				}, done);
			}
		);
	});
	this.name = 'trello';
};
TrelloStrategy.prototype = Object.create(OAuth1Strategy.prototype);

module.exports = {
	translateProfile: (token, tokenSecret, profile, cb) => { cb(null, profile); },
	strategy: TrelloStrategy
};
<|endoftext|>


<commit_before>/**
 * Given a resource bridge, load a resource.
 *
 * Params:
 * - resourceBridge: an instance of a webdav.ResourceBridge (REQUIRED)
 * - name: If given, the name of the resource. If this is not specified,
 *   the request path will be used.
 * - addDatasource: If this is set to `true` then the resource will be
 *   added as a datasource, which makes it usable in `from()` clauses.
 */

var pronto = require('pronto');

function LoadResource() {
}
module.exports = LoadResource;
pronto.inheritsCommand(LoadResource);

LoadResource.prototype.execute = function (cxt, params) {
  this.required(params, ['resourceBridge']);

  var bridge = params.resourceBridge;
  var name = params.name || cxt.getDatasource('request').parsedUrl.pathname;
  var addDatasource= params.addDatasource || false;

  var cmd = this;
  bridge.load(name, function (e, resource) {
    // FIXME: What should be done here?
    if (e) {
      console.log(e);
      cxt.log("Load error: " + e.message, 'info');

      if (!e.code) {
        cxt.log('No code was set: ' + e.message, 'warning');
        cmd.reroute('@500');
        return;
      }

      // Are errno integers standard? POSIX def seems to only have the
      // code.
      switch (e.code) {
        // 34: NOENT, no such file
        // Current strategy is to return empty (undefined) data,
        // which all implementors seem to handle. This will result
        // in a 404 for GET, while others assume this means no such
        // resource.
        case 'ENOENT':
          break;
        // EACCESS, not allowed
        // This indicates that the current user has no READ permission
        // on the file, or no execute perm on a directory. We liken this
        // to a 403.
        case 'EACCES':
          cmd.reroute('@403');
          return;
        // All other errors are deemed "internal" and will result in a
        // 500.
        default:
          cxt.log('A low level i/o error occured: ' + e.message, 'warning');
          cmd.reroute('@500');
          return;
      }
    }

    // If we should add a datasource, put the resource in as a
    // datasource with the name of the command. This makes
    // `from('resource:stream')` work.
    if (addDatasource) {
      cxt.addDatasource(cmd.name, resource);
    }
    cmd.done(resource);
  });

}
<commit_msg>Switched resource to use HTTP status codes, not POSIX.<commit_after>/**
 * Given a resource bridge, load a resource.
 *
 * Params:
 * - resourceBridge: an instance of a webdav.ResourceBridge (REQUIRED)
 * - name: If given, the name of the resource. If this is not specified,
 *   the request path will be used.
 * - addDatasource: If this is set to `true` then the resource will be
 *   added as a datasource, which makes it usable in `from()` clauses.
 */

var pronto = require('pronto');

function LoadResource() {
}
module.exports = LoadResource;
pronto.inheritsCommand(LoadResource);

LoadResource.prototype.execute = function (cxt, params) {
  this.required(params, ['resourceBridge']);

  var bridge = params.resourceBridge;
  var name = params.name || cxt.getDatasource('request').parsedUrl.pathname;
  var addDatasource= params.addDatasource || false;

  var cmd = this;
  bridge.load(name, function (e, resource) {
    // FIXME: What should be done here?
    if (e) {
      console.log(e);
      cxt.log("Load error: " + e.message, 'info');

      if (!e.status) {
        cxt.log('No code was set: ' + e.message, 'warning');
        cmd.reroute('@500');
        return;
      }

      switch (e.status) {
        case 404:
          break;
        case 403:
          cmd.reroute('@403');
          return;
        case 500:
        default:
          cxt.log('A low level i/o error occured: ' + e.message, 'warning');
          cmd.reroute('@500');
          return;
      }
    }

    // If we should add a datasource, put the resource in as a
    // datasource with the name of the command. This makes
    // `from('resource:stream')` work.
    if (addDatasource) {
      cxt.addDatasource(cmd.name, resource);
    }
    cmd.done(resource);
  });

}
<|endoftext|>


<commit_before>/*
 * Package: context.js
 *
 * A handful of functions for drawing entities in different contexts.
 */

if ( typeof bbopx == "undefined" ){ var bbopx = {}; }
if ( typeof bbopx.noctua == "undefined" ){ bbopx.noctua = {}; }

// var bbopx.noctua.categorize = function(in_type){

//     var ret = {
// 	category: 'unknown',
// 	text: '???'
//     };

//     var t = in_type['type'];
//     if( t == 'Class' ){
// 	var i = in_type['id'];
// 	var l = in_type['label'];
// 	ret['category'] = 'instance_of';
// 	ret['text'] = l + ' (' + i + ')';
//     }else if( t == 'Restriction' ){
// 	var thing = in_type['someValuesFrom']['id'];
// 	var thing_rel = in_type['onProperty']['id'];
// 	ret['category'] = thing_rel;
// 	ret['text'] = thing_rel + ' (' + thing + ')';
//     }

//     return ret;
// };

/*
 * Function: type_to_minimal
 *
 * Return a single-line text-only one-level representation of a type.
 */
bbopx.noctua.type_to_minimal = function(in_type, aid){

    var ret = '[???]';

    var t = in_type.type();
    var f = in_type.frame();

    if( t == 'class' ){
	ret = in_type.class_label();
    }else if( t == 'union' || t == 'intersection' ){
	ret = t + '[' + f.length + ']';
    }else{
	// SVF a little harder.
	var ctype = in_type.category();
	var ctype_r = aid.readable(ctype);

	// Probe it a bit.
	var ce = in_type.svf_class_expression();
	var cetype = ce.type();

	var inner_lbl = '???';
	if( cetype == 'class' ){
	    inner_lbl = ce.class_label();
	}else if( cetype == 'union' || cetype == 'intersection' ){
	    var cef = ce.frame();
	    inner_lbl = cetype + '[' + cef.length + ']';
	}else{
	    inner_lbl = '[SVF]';
	}

	//var cr = aid.readable(cat);
	ret = ctype_r + '(' + inner_lbl + ')';
    }

    // A little special "hi" for inferred types.
    if( in_type.inferred_p() ){
	ret = '[' + ret + ']';
    }

    return ret;
};

// /*
//  *
//  */
// var bbopx.noctua.type_to_expanded = function(in_type, aid){

//     var text = '[???]';

//     var t = in_type.type();
//     //var ft = in_type.frame_type();
//     var ft = null;
//     var f = in_type.frame();
//     if( t == 'Class' && ft == null ){
// 	text = in_type.class_label() + ' (' + in_type.class_id() + ')';
//     }else if( t == 'Restriction' && ft == null ){
// 	var thing = in_type.class_label();
// 	var thing_prop = in_type.property_label();
// 	text = aid.readable(thing_prop) + '(' + thing + ')';
//     }else if( ft == 'intersectionOf' ){
// 	var thing_prop = in_type.property_label();
// 	text = aid.readable(thing_prop) + '(' + ft + '[' + f.length + '])';
//     }else if( ft == 'unionOf' ){
// 	text = ft + '[' + f.length + ']';
//     }

//     return text;
// };

/*
 * Function: type_to_span
 *
 * Essentially, minimal rendered as a usable span, with a color
 * option.
 */
bbopx.noctua.type_to_span = function(in_type, aid, color_p){

    var min = bbopx.noctua.type_to_minimal(in_type, aid);
    //var exp = bbopx.noctua.type_to_expanded(in_type, aid);

    var text = null;
    if( color_p ){
	text = '' +
	    min + '';
    }else{
	text = '' + min + '';
    }

    return text;
};

/*
 * Function: type_to_full
 *
 * A recursive writer for when we no longer care--a table that goes on
 * and on...
 */
bbopx.noctua.type_to_full = function(in_type, aid){
    var anchor = this;
    var each = bbop.core.each;

    var text = '[???]';

    var t = in_type.type();
    if( t == 'class' ){ // if simple, the easy way out
	text = bbopx.noctua.type_to_minimal(in_type, aid);
    }else{
	// For everything else, we're gunna hafta do a little
	// lifting...
	var cache = [];
	if( t == 'union' || t == 'intersection' ){

	    // Some kind of recursion on a frame then.
	    cache = [
		'
',
		'
' + t + '
',
		//'
',
		'
',
		'
',
		'
'
	    ];
	    // cache.push('
'),
	    var frame = in_type.frame();
	    each(frame,
		 function(ftype){
		     cache.push('
'),
		     cache.push('');
		     // cache.push(''),
		     cache.push(bbopx.noctua.type_to_full(ftype, aid));
		     cache.push('	');
		     cache.push('
');
		 });
	    // cache.push('
');
	    cache.push('
');
	    cache.push('
');

	    text = cache.join('');

	}else{

	    // A little harder: need to a an SVF wrap before I recur.
	    var pid = in_type.property_id();
	    var plabel = in_type.property_label();
	    var svfce = in_type.svf_class_expression();
	    cache = [
		'
',
		'
',
		plabel,
		'
',
		'
'
	    ];
	    cache.push('
'),
	    cache.push(bbopx.noctua.type_to_full(svfce, aid));
	    cache.push('
');
	    cache.push('
');
	    cache.push('
');

	    text = cache.join('');
	}
    }

    // var min = bbopx.noctua.type_to_minimal(in_type, aid);
    // var exp = bbopx.noctua.type_to_expanded(in_type, aid);
    // var text = '' + min + '';

    return text;
};

// {
//   "type": "Class",
//   "label": "phosphatase activity",
//   "id": "GO_0016791"
// }
/////
// {
//   "someValuesFrom": {
//     "type": "Class",
//     "id": "WB_WBGene00000913"
//   },
//   "type": "Restriction",
//   "onProperty": {
//     "type": "ObjectProperty",
//     "id": "enabled_by"
//   }
/////
// {
//   "onProperty": {
//     "id": "RO:0002333",
//     "type": "ObjectProperty",
//     "label": "enabled_by"
//   },
//   "type": "Restriction",
//   "someValuesFrom": {
//     "intersectionOf": [
//       {
//         "id": "GO:0043234",
//         "type": "Class",
//         "label": "protein complex"
//       },
//       {
//         "onProperty": {
//           "id": "BFO:0000051",
//           "type": "ObjectProperty",
//           "label": "has part"
//         },
//         "type": "Restriction",
//         "someValuesFrom": {
//           "id": "UniProtKB:P0002",
//           "type": "Class"
//         }
//       },
//       {
//         "onProperty": {
//           "id": "BFO:0000051",
//           "type": "ObjectProperty",
//           "label": "has part"
//         },
//         "type": "Restriction",
//         "someValuesFrom": {
//           "id": "UniProtKB:P0003",
//           "type": "Class"
//         }
//       }
//     ]
//   }
// }

// // Support CommonJS if it looks like that's how we're rolling.
// if( typeof(exports) != 'undefined' ){
//     //exports.bbop_mme_context = bbop_mme_context;
//     //exports.bbop_type_to_tcell = bbop_type_to_tcell;
// }
<commit_msg>old code<commit_after>/*
 * Package: context.js
 *
 * A handful of functions for drawing entities in different contexts.
 */

if ( typeof bbopx == "undefined" ){ var bbopx = {}; }
if ( typeof bbopx.noctua == "undefined" ){ bbopx.noctua = {}; }

/*
 * Function: type_to_minimal
 *
 * Return a single-line text-only one-level representation of a type.
 */
bbopx.noctua.type_to_minimal = function(in_type, aid){

    var ret = '[???]';

    var t = in_type.type();
    var f = in_type.frame();

    if( t == 'class' ){
	ret = in_type.class_label();
    }else if( t == 'union' || t == 'intersection' ){
	ret = t + '[' + f.length + ']';
    }else{
	// SVF a little harder.
	var ctype = in_type.category();
	var ctype_r = aid.readable(ctype);

	// Probe it a bit.
	var ce = in_type.svf_class_expression();
	var cetype = ce.type();

	var inner_lbl = '???';
	if( cetype == 'class' ){
	    inner_lbl = ce.class_label();
	}else if( cetype == 'union' || cetype == 'intersection' ){
	    var cef = ce.frame();
	    inner_lbl = cetype + '[' + cef.length + ']';
	}else{
	    inner_lbl = '[SVF]';
	}

	//var cr = aid.readable(cat);
	ret = ctype_r + '(' + inner_lbl + ')';
    }

    // A little special "hi" for inferred types.
    if( in_type.inferred_p() ){
	ret = '[' + ret + ']';
    }

    return ret;
};

/*
 * Function: type_to_span
 *
 * Essentially, minimal rendered as a usable span, with a color
 * option.
 */
bbopx.noctua.type_to_span = function(in_type, aid, color_p){

    var min = bbopx.noctua.type_to_minimal(in_type, aid);

    var text = null;
    if( color_p ){
	text = '' +
	    min + '';
    }else{
	text = '' + min + '';
    }

    return text;
};

/*
 * Function: type_to_full
 *
 * A recursive writer for when we no longer care--a table that goes on
 * and on...
 */
bbopx.noctua.type_to_full = function(in_type, aid){
    var anchor = this;
    var each = bbop.core.each;

    var text = '[???]';

    var t = in_type.type();
    if( t == 'class' ){ // if simple, the easy way out
	text = bbopx.noctua.type_to_minimal(in_type, aid);
    }else{
	// For everything else, we're gunna hafta do a little
	// lifting...
	var cache = [];
	if( t == 'union' || t == 'intersection' ){

	    // Some kind of recursion on a frame then.
	    cache = [
		'
',
		'
' + t + '
',
		//'
',
		'
',
		'
',
		'
'
	    ];
	    // cache.push('
'),
	    var frame = in_type.frame();
	    each(frame,
		 function(ftype){
		     cache.push('
'),
		     cache.push('');
		     // cache.push(''),
		     cache.push(bbopx.noctua.type_to_full(ftype, aid));
		     cache.push('	');
		     cache.push('
');
		 });
	    // cache.push('
');
	    cache.push('
');
	    cache.push('
');

	    text = cache.join('');

	}else{

	    // A little harder: need to a an SVF wrap before I recur.
	    var pid = in_type.property_id();
	    var plabel = in_type.property_label();
	    var svfce = in_type.svf_class_expression();
	    cache = [
		'
',
		'
',
		plabel,
		'
',
		'
'
	    ];
	    cache.push('
'),
	    cache.push(bbopx.noctua.type_to_full(svfce, aid));
	    cache.push('
');
	    cache.push('
');
	    cache.push('
');

	    text = cache.join('');
	}
    }

    // var min = bbopx.noctua.type_to_minimal(in_type, aid);
    // var exp = bbopx.noctua.type_to_expanded(in_type, aid);
    // var text = '' + min + '';

    return text;
};
<|endoftext|>