<commit_before>import { Router } from 'express';
import Groups from 'models/groupModel';
import IDCard from 'models/idcardModel';
import PWS from 'models/pwsModel';
import { ensureAPIAuth, ensureAuthOrToken, getAuthToken, idaaRedirectUrl, developmentMode, tokenToSession } from '../utils/helpers';
import { API, Routes } from 'Routes';
import csv from 'csv-express'; // required for csv route even though shown as unused

let api = Router();

const IDAACHECK = process.env.IDAACHECK;
const IDAAGROUPID = process.env.IDAAGROUPID;
const BASE_GROUP = process.env.BASE_GROUP;

api.get(API.GetMembers, ensureAuthOrToken, tokenToSession, async (req, res) => {
  let groupName = req.session.group.groupName;
  let confidential = req.session.group.confidential;
  let response = {
    groupName,
    confidential,
    members: []
  };

  if (confidential && !req.isAuthenticated() && !developmentMode) {
    return res.status(200).json(response);
  }
  let result = await Groups.GetMembers(groupName);
  let members = await PWS.GetMany(result.Payload);
  let verbose = await IDCard.GetManyPhotos(members);
  response.members = verbose;
  return res.status(result.Status).json(response);
});

api.put(API.RegisterMember, ensureAuthOrToken, tokenToSession, async (req, res) => {
  let identifier = req.body.identifier;
  let displayId = req.body.displayId;
  let validCard = IDCard.ValidCard(identifier);
  let groupName = req.session.group.groupName;
  let netidAllowed = req.session.group.netidAllowed;
  let confidential = req.session.group.confidential;

  if (!validCard && netidAllowed == 'false') {
    // if not a valid card and netid auth not allowed, 404
    return res.sendStatus(404);
  }

  if (validCard) {
    identifier = await IDCard.Get(validCard);
    identifier = (await PWS.Get(identifier)).UWNetID;
  }

  let result = await Groups.AddMember(groupName, identifier);

  if (result.Status === 200 && confidential) {
    res.sendStatus(201);
  }

  if (result.Status === 200 && !confidential) {
    let user = await PWS.Get(identifier);

    user.displayId = displayId;
    user.Base64Image = await IDCard.GetPhoto(user.UWRegID);
    res.status(result.Status).json(user);
  } else {
    res.sendStatus(result.Status);
  }
});

api.get(API.GetToken, ensureAPIAuth, (req, res) => {
  let groupName = req.query.groupName;
  let netidAllowed = req.query.netidAllowed;
  let tokenTTL = req.query.tokenTTL;

  let token = getAuthToken(req, groupName, netidAllowed, tokenTTL);
  if (token) {
    return res.status(200).json({ token });
  } else {
    return res.status(401).json({ token: '' });
  }
});

api.get(API.Logout, (req, res) => {
  req.logout();
  req.session.destroy();
  res.clearCookie('connect.sid', { path: Routes.Welcome });
  res.sendStatus(200);
});

api.delete(API.RemoveMember, ensureAPIAuth, async (req, res) => {
  let result = await Groups.RemoveMember(req.params.group, req.params.identifier);
  return res.status(result.Status).json(result.Payload);
});

api.get(API.GetSubgroups, ensureAPIAuth, async (req, res) => {
  let result = await Groups.SearchGroups(req.params.group, true);
  return res.status(result.Status).json(result.Payload);
});

api.delete(API.RemoveSubgroup, ensureAPIAuth, async (req, res) => {
  let result = await Groups.DeleteGroup(req.params.group);
  return res.status(result.Status).json(result.Payload);
});

api.post(API.CreateGroup, ensureAPIAuth, async (req, res) => {
  let confidential = req.query.confidential;
  let description = req.query.description;
  let email = req.query.email;

  let result = await Groups.CreateGroup(req.params.group, confidential, description, email);
  return res.status(result.Status).json(result.Payload);
});

api.get(API.CheckAuth, async (req, res) => {
  let redirectBack = IDAACHECK + idaaRedirectUrl(req);
  let auth = { Authenticated: req.isAuthenticated(), IAAAAuth: false, IAARedirect: redirectBack };

  if (!req.session) {
    return res.sendStatus(500);
  }

  if (req.isAuthenticated()) {
    if (!req.session.IAAAgreed) {
      let found = false;
      let members = (await Groups.GetMembers(IDAAGROUPID)).Payload;
      if (members.find(u => u.id === req.user.UWNetID)) {
        found = true;
      }

      if (!found) {
        members = (await Groups.GetMembers(IDAAGROUPID, true)).Payload;
        if (members.find(u => u.id === req.user.UWNetID)) {
          found = true;
        }
      } else {
        req.session.IAAAgreed = true;
        auth.IAAAAuth = true;
      }
    } else {
      auth.IAAAAuth = true;
    }
  }
  return res.status(200).json(auth);
});

api.get(API.Config, (req, res) => {
  res.status(200).json({ groupNameBase: BASE_GROUP });
});

api.get(API.CSV, async (req, res) => {
  let members = await Groups.GetMembers(req.params.group);
  let csvWhitelist = ['DisplayName', 'UWNetID', 'UWRegID'];
  let verboseMembers = await PWS.GetMany(members.Payload, csvWhitelist);
  let mergedMembers = await Groups.GetMemberHistory(verboseMembers, req.params.group);
  res.csv(mergedMembers, true);
});

export default api;
<commit_msg>requiring auth for csv endpoint<commit_after>import { Router } from 'express';
import Groups from 'models/groupModel';
import IDCard from 'models/idcardModel';
import PWS from 'models/pwsModel';
import { ensureAPIAuth, ensureAuthOrToken, getAuthToken, idaaRedirectUrl, developmentMode, tokenToSession } from '../utils/helpers';
import { API, Routes } from 'Routes';
import csv from 'csv-express'; // required for csv route even though shown as unused

let api = Router();

const IDAACHECK = process.env.IDAACHECK;
const IDAAGROUPID = process.env.IDAAGROUPID;
const BASE_GROUP = process.env.BASE_GROUP;

api.get(API.GetMembers, ensureAuthOrToken, tokenToSession, async (req, res) => {
  let groupName = req.session.group.groupName;
  let confidential = req.session.group.confidential;
  let response = {
    groupName,
    confidential,
    members: []
  };

  if (confidential && !req.isAuthenticated() && !developmentMode) {
    return res.status(200).json(response);
  }
  let result = await Groups.GetMembers(groupName);
  let members = await PWS.GetMany(result.Payload);
  let verbose = await IDCard.GetManyPhotos(members);
  response.members = verbose;
  return res.status(result.Status).json(response);
});

api.put(API.RegisterMember, ensureAuthOrToken, tokenToSession, async (req, res) => {
  let identifier = req.body.identifier;
  let displayId = req.body.displayId;
  let validCard = IDCard.ValidCard(identifier);
  let groupName = req.session.group.groupName;
  let netidAllowed = req.session.group.netidAllowed;
  let confidential = req.session.group.confidential;

  if (!validCard && netidAllowed == 'false') {
    // if not a valid card and netid auth not allowed, 404
    return res.sendStatus(404);
  }

  if (validCard) {
    identifier = await IDCard.Get(validCard);
    identifier = (await PWS.Get(identifier)).UWNetID;
  }

  let result = await Groups.AddMember(groupName, identifier);

  if (result.Status === 200 && confidential) {
    res.sendStatus(201);
  }

  if (result.Status === 200 && !confidential) {
    let user = await PWS.Get(identifier);

    user.displayId = displayId;
    user.Base64Image = await IDCard.GetPhoto(user.UWRegID);
    res.status(result.Status).json(user);
  } else {
    res.sendStatus(result.Status);
  }
});

api.get(API.GetToken, ensureAPIAuth, (req, res) => {
  let groupName = req.query.groupName;
  let netidAllowed = req.query.netidAllowed;
  let tokenTTL = req.query.tokenTTL;

  let token = getAuthToken(req, groupName, netidAllowed, tokenTTL);
  if (token) {
    return res.status(200).json({ token });
  } else {
    return res.status(401).json({ token: '' });
  }
});

api.get(API.Logout, (req, res) => {
  req.logout();
  req.session.destroy();
  res.clearCookie('connect.sid', { path: Routes.Welcome });
  res.sendStatus(200);
});

api.delete(API.RemoveMember, ensureAPIAuth, async (req, res) => {
  let result = await Groups.RemoveMember(req.params.group, req.params.identifier);
  return res.status(result.Status).json(result.Payload);
});

api.get(API.GetSubgroups, ensureAPIAuth, async (req, res) => {
  let result = await Groups.SearchGroups(req.params.group, true);
  return res.status(result.Status).json(result.Payload);
});

api.delete(API.RemoveSubgroup, ensureAPIAuth, async (req, res) => {
  let result = await Groups.DeleteGroup(req.params.group);
  return res.status(result.Status).json(result.Payload);
});

api.post(API.CreateGroup, ensureAPIAuth, async (req, res) => {
  let confidential = req.query.confidential;
  let description = req.query.description;
  let email = req.query.email;

  let result = await Groups.CreateGroup(req.params.group, confidential, description, email);
  return res.status(result.Status).json(result.Payload);
});

api.get(API.CheckAuth, async (req, res) => {
  let redirectBack = IDAACHECK + idaaRedirectUrl(req);
  let auth = { Authenticated: req.isAuthenticated(), IAAAAuth: false, IAARedirect: redirectBack };

  if (!req.session) {
    return res.sendStatus(500);
  }

  if (req.isAuthenticated()) {
    if (!req.session.IAAAgreed) {
      let found = false;
      let members = (await Groups.GetMembers(IDAAGROUPID)).Payload;
      if (members.find(u => u.id === req.user.UWNetID)) {
        found = true;
      }

      if (!found) {
        members = (await Groups.GetMembers(IDAAGROUPID, true)).Payload;
        if (members.find(u => u.id === req.user.UWNetID)) {
          found = true;
        }
      } else {
        req.session.IAAAgreed = true;
        auth.IAAAAuth = true;
      }
    } else {
      auth.IAAAAuth = true;
    }
  }
  return res.status(200).json(auth);
});

api.get(API.Config, (req, res) => {
  res.status(200).json({ groupNameBase: BASE_GROUP });
});

api.get(API.CSV, ensureAPIAuth, async (req, res) => {
  let members = await Groups.GetMembers(req.params.group);
  let csvWhitelist = ['DisplayName', 'UWNetID', 'UWRegID'];
  let verboseMembers = await PWS.GetMany(members.Payload, csvWhitelist);
  let mergedMembers = await Groups.GetMemberHistory(verboseMembers, req.params.group);
  res.csv(mergedMembers, true);
});

export default api;
<|endoftext|>


<commit_before>///
/// Class: functionBuilder
///
/// [INTERNAL] A collection of functionNodes.
///
/// This handles all the raw state, converted state, etc. Of a single function.
///
/// Properties:
/// 	nodeMap - {Object} Object map, where nodeMap[function] = functionNode;
///
var functionBuilder = (function() {

	///
	/// Function: functionBuilder
	///
	/// [Constructor] Blank constructor, which initializes the properties
	///
	function functionBuilder() {
		this.nodeMap = {};
	}

	///
	/// Function: addFunction
	///
	/// Creates the functionNode, and add it to the nodeMap
	///
	/// Parameters:
	/// 	functionName    - {String}       Function name to assume, if its null, it attempts to extract from the function
	/// 	jsFunction      - {JS Function}  JS Function to do conversion
	/// 	paramTypeArray  - {[String,...]} Parameter type array, assumes all parameters are "float" if null
	/// 	returnType      - {String}       The return type, assumes "float" if null
	///
	function addFunction( functionName, jsFunction, paramTypeArray, returnType ) {
		this.addFunctionNode( new functionNode( functionName, jsFunction, paramTypeArray, returnType ) );
	}
	functionBuilder.prototype.addFunction = addFunction;

	///
	/// Function: addFunctionNode
	///
	/// Add the funciton node directly
	///
	/// Parameters:
	/// 	inNode    - {functionNode}       functionNode to add
	///
	function addFunctionNode( inNode ) {
		this.nodeMap[ inNode.functionName ] = inNode;
	}
	functionBuilder.prototype.addFunctionNode = addFunctionNode;

	///
	/// Function: traceFunctionCalls
	///
	/// Trace all the depending functions being called, from a single function
	///
	/// This allow for "uneeded" functions to be automatically optimized out.
	/// Note that the 0-index, is the starting function trace.
	///
	/// Parameters:
	/// 	functionName  - {String}        Function name to trace from, default to "kernel"
	/// 	retList       - {[String,...]}  Returning list of function names that is traced. Including itself.
	///
	/// Returns:
	/// 	{[String,...]}  Returning list of function names that is traced. Including itself.
	function traceFunctionCalls( functionName, retList ) {
		functionName = functionName || "kernel";
		retList = retList || [];

		var fNode = this.nodeMap[functionName];
		if( fNode ) {
			// Check if function already exists
			if( retList.indexOf(functionName) >= 0 ) {
				// Does nothing if already traced
			} else {
				retList.push(functionName);

				fNode.getWebglFunctionString(); //ensure JS trace is done
				for(var i=0; i<fNode.calledFunctions.length; ++i) {
					this.traceFunctionCalls( fNode.calledFunctions[i], retList );
				}
			}
		}

		return retList;
	}
	functionBuilder.prototype.traceFunctionCalls = traceFunctionCalls;

	///
	/// Function: webglString_fromFunctionNames
	///
	/// Parameters:
	/// 	functionList  - {[String,...]} List of function to build the webgl string.
	///
	/// Returns:
	/// 	{String} The full webgl string, of all the various functions. Trace optimized if functionName given
	///
	function webglString_fromFunctionNames(functionList) {
		var ret = [];
		for(var i=0; i<functionList.length; ++i) {
			ret.push( this.nodeMap[functionList[i]].getWebglFunctionString() );
		}
		return ret.join("\n");
	}
	functionBuilder.prototype.webglString_fromFunctionNames = webglString_fromFunctionNames;

	///
	/// Function: webglString
	///
	/// Parameters:
	/// 	functionName  - {String} Function name to trace from. If null, it returns the WHOLE builder stack
	///
	/// Returns:
	/// 	{String} The full webgl string, of all the various functions. Trace optimized if functionName given
	///
	function webglString(functionName) {
		if(functionName) {
			return this.webglString_fromFunctionNames( this.traceFunctionCalls(functionName, []).reverse() );
		}
		return this.webglString_fromFunctionNames(Object.keys(this.nodeMap));
	}
	functionBuilder.prototype.webglString = webglString;

	return functionBuilder;
})();
<commit_msg>Added silent failure, for calling pre-existing math function<commit_after>///
/// Class: functionBuilder
///
/// [INTERNAL] A collection of functionNodes.
///
/// This handles all the raw state, converted state, etc. Of a single function.
///
/// Properties:
/// 	nodeMap - {Object} Object map, where nodeMap[function] = functionNode;
///
var functionBuilder = (function() {

	///
	/// Function: functionBuilder
	///
	/// [Constructor] Blank constructor, which initializes the properties
	///
	function functionBuilder() {
		this.nodeMap = {};
	}

	///
	/// Function: addFunction
	///
	/// Creates the functionNode, and add it to the nodeMap
	///
	/// Parameters:
	/// 	functionName    - {String}       Function name to assume, if its null, it attempts to extract from the function
	/// 	jsFunction      - {JS Function}  JS Function to do conversion
	/// 	paramTypeArray  - {[String,...]} Parameter type array, assumes all parameters are "float" if null
	/// 	returnType      - {String}       The return type, assumes "float" if null
	///
	function addFunction( functionName, jsFunction, paramTypeArray, returnType ) {
		this.addFunctionNode( new functionNode( functionName, jsFunction, paramTypeArray, returnType ) );
	}
	functionBuilder.prototype.addFunction = addFunction;

	///
	/// Function: addFunctionNode
	///
	/// Add the funciton node directly
	///
	/// Parameters:
	/// 	inNode    - {functionNode}       functionNode to add
	///
	function addFunctionNode( inNode ) {
		this.nodeMap[ inNode.functionName ] = inNode;
	}
	functionBuilder.prototype.addFunctionNode = addFunctionNode;

	///
	/// Function: traceFunctionCalls
	///
	/// Trace all the depending functions being called, from a single function
	///
	/// This allow for "uneeded" functions to be automatically optimized out.
	/// Note that the 0-index, is the starting function trace.
	///
	/// Parameters:
	/// 	functionName  - {String}        Function name to trace from, default to "kernel"
	/// 	retList       - {[String,...]}  Returning list of function names that is traced. Including itself.
	///
	/// Returns:
	/// 	{[String,...]}  Returning list of function names that is traced. Including itself.
	function traceFunctionCalls( functionName, retList ) {
		functionName = functionName || "kernel";
		retList = retList || [];

		var fNode = this.nodeMap[functionName];
		if( fNode ) {
			// Check if function already exists
			if( retList.indexOf(functionName) >= 0 ) {
				// Does nothing if already traced
			} else {
				retList.push(functionName);

				fNode.getWebglFunctionString(); //ensure JS trace is done
				for(var i=0; i<fNode.calledFunctions.length; ++i) {
					this.traceFunctionCalls( fNode.calledFunctions[i], retList );
				}
			}
		}

		return retList;
	}
	functionBuilder.prototype.traceFunctionCalls = traceFunctionCalls;

	///
	/// Function: webglString_fromFunctionNames
	///
	/// Parameters:
	/// 	functionList  - {[String,...]} List of function to build the webgl string.
	///
	/// Returns:
	/// 	{String} The full webgl string, of all the various functions. Trace optimized if functionName given
	///
	function webglString_fromFunctionNames(functionList) {
		var ret = [];
		for(var i=0; i<functionList.length; ++i) {
			var node = this.nodeMap[functionList[i]];
			if(node) {
				ret.push( this.nodeMap[functionList[i]].getWebglFunctionString() );
			}
		}
		return ret.join("\n");
	}
	functionBuilder.prototype.webglString_fromFunctionNames = webglString_fromFunctionNames;

	///
	/// Function: webglString
	///
	/// Parameters:
	/// 	functionName  - {String} Function name to trace from. If null, it returns the WHOLE builder stack
	///
	/// Returns:
	/// 	{String} The full webgl string, of all the various functions. Trace optimized if functionName given
	///
	function webglString(functionName) {
		if(functionName) {
			return this.webglString_fromFunctionNames( this.traceFunctionCalls(functionName, []).reverse() );
		}
		return this.webglString_fromFunctionNames(Object.keys(this.nodeMap));
	}
	functionBuilder.prototype.webglString = webglString;

	//---------------------------------------------------------
	//
	//  Polyfill stuff
	//
	//---------------------------------------------------------

	// Round function used in polyfill
	function round(a) { return Math.floor( a + 0.5 ); }

	///
	/// Function: polyfillStandardFunctions
	///
	/// Polyfill in the missing Math funcitons (round)
	///
	function polyfillStandardFunctions() {
		this.addFunction(null, round);
	}
	functionBuilder.prototype.polyfillStandardFunctions = polyfillStandardFunctions;

	return functionBuilder;
})();
<|endoftext|>


<commit_before>"use strict";

define(['logManager',
        'text!./ProjectTitleTmpl.html'], function (logManager,
                                                   projectTitleTmpl) {

    var ProjectTitleView;

    ProjectTitleView = function (container) {
        this._initializeUI(container);

        if (this._el.length === 0) {
            this._logger.error("ProjectTitleView can not be created");
            return undefined;
        }

        this._logger = logManager.create("ProjectTitleView");
        this._logger.debug("Created");
    };

    ProjectTitleView.prototype._initializeUI = function (containerElement) {

        //get container first
        this._el = $("#" + containerElement);
        if (this._el.length === 0) {
            this._logger.warning("ProjectTitleView's container control with id:'" + containerElement + "' could not be found");
            return undefined;
        }

        this._el.html(projectTitleTmpl);

        this._projectTitle = this._el.find(".title");
    };

    ProjectTitleView.prototype.refresh = function (client) {
        var actualProject = client.getActiveProject(),
            actualBranch = client.getActualBranch(),
            readOnly = client.isReadOnly(),
            titleText = actualProject + " @ " + actualBranch;

        this._projectTitle.text(titleText);

        if (readOnly) {
            this._el.addClass("read-only");
        } else {
            this._el.removeClass("read-only");
        }
    };

    return ProjectTitleView;
});<commit_msg>update document title when project changes<commit_after>"use strict";

define(['logManager',
        'text!./ProjectTitleTmpl.html'], function (logManager,
                                                   projectTitleTmpl) {

    var ProjectTitleView;

    ProjectTitleView = function (container) {
        this._initializeUI(container);

        if (this._el.length === 0) {
            this._logger.error("ProjectTitleView can not be created");
            return undefined;
        }

        this._logger = logManager.create("ProjectTitleView");
        this._logger.debug("Created");
    };

    ProjectTitleView.prototype._initializeUI = function (containerElement) {

        //get container first
        this._el = $("#" + containerElement);
        if (this._el.length === 0) {
            this._logger.warning("ProjectTitleView's container control with id:'" + containerElement + "' could not be found");
            return undefined;
        }

        this._el.html(projectTitleTmpl);

        this._projectTitle = this._el.find(".title");
    };

    ProjectTitleView.prototype.refresh = function (client) {
        var actualProject = client.getActiveProject(),
            actualBranch = client.getActualBranch(),
            readOnly = client.isReadOnly(),
            titleText = actualProject + " @ " + actualBranch,
            documentTitle = titleText + (readOnly ? " [READ-ONLY]": "");

        //change header title
        this._projectTitle.text(titleText);

        //change document title (browser tab)
        document.title = '-= ' + documentTitle + ' =- WebGME';

        if (readOnly) {
            this._el.addClass("read-only");
        } else {
            this._el.removeClass("read-only");
        }
    };

    return ProjectTitleView;
});<|endoftext|>


<commit_before>/**
 * @flow
 */

import type {MakeItem, MakeRawItem, MakeDefine, MakeRule} from '../Makefile';
import type {Sandbox, PackageInfo} from '../Sandbox';
import type {EnvironmentGroup} from '../PackageEnvironment';

const mkdirp = require('mkdirp').sync;
const childProcess = require('child_process');
const fs = require('fs');
const crypto  = require('crypto');
const path = require('path');
const outdent = require('outdent');
const {flattenArray} = require('../Utility');

const RUNTIME = fs.readFileSync(require.resolve('./runtime.sh'), 'utf8');

const {
  traversePackageDependencyTree,
  collectTransitiveDependencies,
  packageInfoKey,
} = require('../Sandbox');
const PackageEnvironment = require('../PackageEnvironment');
const Makefile = require('../Makefile');

const curWorkingDirectory = process.cwd();

function buildEjectCommand(
  sandbox: Sandbox,
  ...args: Array<string>
) {

  let defaultEjectDirectory = path.join(sandbox.packageInfo.rootDirectory, '_esy');
  let [
    ejectDirectory = defaultEjectDirectory
  ] = args;

  function emitFile(file: {filename: Array<string>; contents: string, executable?: boolean}) {
    let filename = path.join(ejectDirectory, ...file.filename);
    console.log('ejecting:', path.relative(curWorkingDirectory, filename));
    mkdirp(path.dirname(filename));
    fs.writeFileSync(filename, file.contents);
    if (file.executable) {
      let mode = fs.constants.S_IRWXU;
      fs.chmodSync(filename, mode);
    }
  }

  let sandboxPackageName = sandbox.packageInfo.packageJson.name;

  let sandboxPath = (packageInfo, tree: '_install' | '_build' | '_insttmp', ...path) => {
    let packageName = packageInfo.packageJson.name;
    let packageKey = packageInfoKey(sandbox.env, packageInfo);
    let isRootPackage = packageName === sandbox.packageInfo.packageJson.name;
    if (isRootPackage) {
      return ['$ESY__SANDBOX', tree, ...path].join('/');
    }
    return ['$ESY__STORE', tree, packageKey, ...path].join('/');
  };

  let sourcePath = (packageInfo) => {
    let isRootPackage = packageInfo.packageJson.name === sandbox.packageInfo.packageJson.name;
    if (isRootPackage) {
      return '$ESY__SANDBOX';
    } else {
      let rel = path.relative(sandbox.packageInfo.rootDirectory, packageInfo.rootDirectory);
      return `$ESY__SANDBOX/${rel}`;
    }
  };

  let buildPath = (packageInfo, ...path) =>
    sandboxPath(packageInfo, '_build', ...path);

  let installPath = (packageInfo, ...path) =>
    sandboxPath(packageInfo, '_install', ...path);

  let installTmpPath = (packageInfo, ...path) =>
    sandboxPath(packageInfo, '_insttmp', ...path);

  let prelude: Array<MakeDefine | MakeRawItem> = [

    {
      type: 'raw',
      value: `SHELL = ${sandbox.env.SHELL}`,
    },

    // ESY__ROOT is the root directory of the ejected Esy build
    // environment.
    {
      type: 'raw',
      value: 'ESY__ROOT := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))'
    },

    // ESY__STORE is the directory where build artifacts should be stored.
    {
      type: 'raw',
      value: 'ESY__STORE ?= $(HOME)/.esy',
    },

    // ESY__SANDBOX is the sandbox directory, the directory where the root
    // package resides.
    {
      type: 'raw',
      value: 'ESY__SANDBOX ?= $(CURDIR)',
    },

  ];

  let rules: Array<MakeItem> = [

    // These are public API

    {
      type: 'rule',
      target: 'build',
      phony: true,
      dependencies: [`${sandboxPackageName}.build`],
    },
    {
      type: 'rule',
      target: 'shell',
      phony: true,
      dependencies: [`${sandboxPackageName}.shell`],
    },
    {
      type: 'rule',
      target: 'clean',
      phony: true,
      command: 'rm -rf $(ESY__SANDBOX)/_build $(ESY__SANDBOX)/_install $(ESY__SANDBOX)/_insttmp',
    },

    // Create store directory structure
    {
      type: 'rule',
      target: '$(ESY__STORE)/_install $(ESY__STORE)/_build $(ESY__STORE)/_insttmp',
      command: 'mkdir -p $(@)',
    },
    {
      type: 'rule',
      target: 'esy-store',
      phony: true,
      dependencies: ['$(ESY__STORE)/_install',  '$(ESY__STORE)/_build', '$(ESY__STORE)/_insttmp'],
    },
    {
      type: 'rule',
      target: '$(ESY__ROOT)/bin/realpath',
      dependencies: ['$(ESY__ROOT)/bin/realpath.c'],
      shell: '/bin/bash',
      command: 'gcc -o $(@) -x c $(<) 2> /dev/null',
    },
    {
      type: 'rule',
      target: 'esy-root',
      phony: true,
      dependencies: ['$(ESY__ROOT)/bin/realpath'],
    },
  ];

  traversePackageDependencyTree(
    sandbox.packageInfo,
    (packageInfo) => {
      let {normalizedName, packageJson, rootDirectory} = packageInfo;
      let isRootPackage = packageJson.name === sandboxPackageName;
      let buildHash = packageInfoKey(sandbox.env, packageInfo);

      let packagePath = isRootPackage
        ? []
        : path.relative(sandbox.packageInfo.rootDirectory, rootDirectory).split(path.sep);

      let buildCommand: ?string = null;
      if (packageJson.esy.build != null) {
        if (Array.isArray(packageJson.esy.build)) {
          buildCommand = packageJson.esy.build.join(' && ');
        } else {
          buildCommand = packageJson.esy.build;
        }
      }

      function emitPackageFile({filename, contents}) {
        emitFile({filename: packagePath.concat(filename), contents});
      }

      function definePackageRule(rule: {
        target: string;
        dependencies?: Array<string>;
        command?: ?string;
      }) {
        let {
          target,
          command,
          dependencies = []
        } = rule;
        rules.push({
          type: 'rule',
          target: packageTarget(target),
          dependencies: ['esy-store', 'esy-root', ...dependencies],
          phony: true,
          command: [
            outdent`
              $(shell_env_for__${normalizedName}) source $(ESY__ROOT)/bin/runtime.sh
              cd $esy_build__source_root
            `,
            command,
          ]
        });
      }

      function packageTarget(target, packageName = packageJson.name) {
        return `${packageName}.${target}`;
      }

      let buildEnvironment = PackageEnvironment.calculateEnvironment(
        sandbox,
        packageInfo,
        {installDirectory: installTmpPath(packageInfo)}
      );

      let dependencies = Object
        .keys(packageInfo.dependencyTree)
        .map(dep => packageTarget('build', dep));
      let allDependencies = collectTransitiveDependencies(packageInfo);

      let packageEnv = `${packageJson.name}__env`;

      emitPackageFile({
        filename: 'env',
        contents: renderEnv(buildEnvironment),
      });

      emitPackageFile({
        filename: 'findlib.conf.in',
        contents: outdent`
          path = "${allDependencies.map(dep => installPath(dep, 'lib')).join(':')}"
          destdir = "${installTmpPath(packageInfo, 'lib')}"
          ldconf = "ignore"
          ocamlc = "ocamlc.opt"
          ocamldep = "ocamldep.opt"
          ocamldoc = "ocamldoc.opt"
          ocamllex = "ocamllex.opt"
          ocamlopt = "ocamlopt.opt"
        `
      });

      // Generate macOS sandbox configuration (sandbox-exec command)
      // TODO: Right now the only thing this sandbox configuration does is it
      // disallows writing into locations other than $cur__root,
      // $cur__target_dir and $cur__install. We should implement proper out of
      // source builds and also disallow $cur__root.
      // TODO: Try to use (deny default) and pick a set of rules for builds to
      // proceed (it chokes on xcodebuild for now if we disable reading "/" and
      // networking).
      emitPackageFile({
        filename: 'sandbox.sb.in',
        contents: outdent`
          (version 1.0)
          (allow default)

          (deny file-write*
            (subpath "/"))

          (allow file-write*
            (literal "/dev/null")

            (subpath "$TMPDIR_GLOBAL")
            (subpath "$TMPDIR")

            ; cur__root
            ; We don't really need to write into cur__root but some build systems
            ; can put .merlin files there so we allow that.
            (subpath "${sourcePath(packageInfo)}")

            ; cur__target_dir
            (subpath "${buildPath(packageInfo)}")

            ; cur__install
            (subpath "${installTmpPath(packageInfo)}")
          )

          (deny file-write*
            (subpath "${sourcePath(packageInfo)}/node_modules")
          )
        `
      });

      rules.push({
        type: 'define',
        name: `shell_env_for__${normalizedName}`,
        value: [
          {
            'CI': process.env.CI ? process.env.CI : null,
            'TMPDIR': '$(TMPDIR)',
            'ESY__STORE': '$(ESY__STORE)',
            'ESY__SANDBOX': '$(ESY__SANDBOX)',
            'ESY__ROOT': '$(ESY__ROOT)',
          },
          `source $(ESY__ROOT)/${packagePath.join('/')}/env`,
          {
            'esy_build__eject': `$(ESY__ROOT)/${packagePath.join('/')}`,
            'esy_build__type': packageInfo.packageJson.esy.buildsInSource
              ? 'in-source'
              : 'out-of-source',
            'esy_build__key': buildHash,
            'esy_build__source': packageInfo.source,
            'esy_build__source_type': packageInfo.sourceType,
            'esy_build__command': buildCommand || 'true',
            'esy_build__source_root': sourcePath(packageInfo),
            'esy_build__install': installPath(packageInfo),
          },
        ],
      });

      definePackageRule({
        target: 'clean',
        command: 'esy-clean'
      });

      definePackageRule({
        target: 'shell',
        dependencies,
        command: 'esy-shell'
      });

      definePackageRule({
        target: 'build',
        dependencies,
        command: 'esy-build'
      });
    });

  let allRules = [].concat(prelude).concat(rules);

  emitFile({
    filename: ['bin', 'realpath.c'],
    contents: outdent`
      #include<stdlib.h>

      main(int cc, char**vargs) {
        puts(realpath(vargs[1], 0));
      }
    `,
  });

  emitFile({
    filename: ['bin/render-env'],
    executable: true,
    contents: outdent`
      #!/bin/bash

      set -e
      set -o pipefail

      _TMPDIR_GLOBAL=$($ESY__ROOT/bin/realpath "/tmp")

      if [ -d "$TMPDIR" ]; then
        _TMPDIR=$($ESY__ROOT/bin/realpath "$TMPDIR")
      else
        _TMPDIR="/does/not/exist"
      fi

      sed \\
        -e "s|\\$ESY__STORE|$ESY__STORE|g"          \\
        -e "s|\\$ESY__SANDBOX|$ESY__SANDBOX|g"      \\
        -e "s|\\$TMPDIR_GLOBAL|$_TMPDIR_GLOBAL|g"   \\
        -e "s|\\$TMPDIR|$_TMPDIR|g"                 \\
        $1 > $2
    `
  });

  emitFile({
    filename: ['bin/replace-string'],
    executable: true,
    contents: outdent`
      #!/usr/bin/env python

      import sys
      import os
      import stat

      filename, src, dest = sys.argv[1:4]
      filename_stage = filename + '.esy_rewrite'

      filestat = os.stat(filename)

      # TODO: we probably should handle symlinks too in a special way,
      # to modify their location to a rewritten path

      with open(filename, 'r') as input_file:
        data = input_file.read()

      data = data.replace(src, dest)

      with open(filename_stage, 'w') as output_file:
        output_file.write(data)

      os.rename(filename_stage, filename)
      os.chmod(filename, stat.S_IMODE(filestat.st_mode))
    `
  });

  emitFile({
    filename: ['bin', 'runtime.sh'],
    contents: RUNTIME
  });

  emitFile({
    filename: ['Makefile'],
    contents: Makefile.renderMakefile(allRules),
  });
}

function hash(value: string): string {
  return crypto.createHash('sha1').update(value).digest('hex');
}

function renderEnv(groups: Array<EnvironmentGroup>): string {
  let env = flattenArray(groups.map(group => group.envVars));
  return env
    .filter(env => env.value != null)
    // $FlowFixMe: make sure env.value is refined above
    .map(env => `export ${env.name}="${env.value}";`)
    .join('\n');
}

module.exports = buildEjectCommand;
<commit_msg>build-eject: expose package's own path in findlib config<commit_after>/**
 * @flow
 */

import type {MakeItem, MakeRawItem, MakeDefine, MakeRule} from '../Makefile';
import type {Sandbox, PackageInfo} from '../Sandbox';
import type {EnvironmentGroup} from '../PackageEnvironment';

const mkdirp = require('mkdirp').sync;
const childProcess = require('child_process');
const fs = require('fs');
const crypto  = require('crypto');
const path = require('path');
const outdent = require('outdent');
const {flattenArray} = require('../Utility');

const RUNTIME = fs.readFileSync(require.resolve('./runtime.sh'), 'utf8');

const {
  traversePackageDependencyTree,
  collectTransitiveDependencies,
  packageInfoKey,
} = require('../Sandbox');
const PackageEnvironment = require('../PackageEnvironment');
const Makefile = require('../Makefile');

const curWorkingDirectory = process.cwd();

function buildEjectCommand(
  sandbox: Sandbox,
  ...args: Array<string>
) {

  let defaultEjectDirectory = path.join(sandbox.packageInfo.rootDirectory, '_esy');
  let [
    ejectDirectory = defaultEjectDirectory
  ] = args;

  function emitFile(file: {filename: Array<string>; contents: string, executable?: boolean}) {
    let filename = path.join(ejectDirectory, ...file.filename);
    console.log('ejecting:', path.relative(curWorkingDirectory, filename));
    mkdirp(path.dirname(filename));
    fs.writeFileSync(filename, file.contents);
    if (file.executable) {
      let mode = fs.constants.S_IRWXU;
      fs.chmodSync(filename, mode);
    }
  }

  let sandboxPackageName = sandbox.packageInfo.packageJson.name;

  let sandboxPath = (packageInfo, tree: '_install' | '_build' | '_insttmp', ...path) => {
    let packageName = packageInfo.packageJson.name;
    let packageKey = packageInfoKey(sandbox.env, packageInfo);
    let isRootPackage = packageName === sandbox.packageInfo.packageJson.name;
    if (isRootPackage) {
      return ['$ESY__SANDBOX', tree, ...path].join('/');
    }
    return ['$ESY__STORE', tree, packageKey, ...path].join('/');
  };

  let sourcePath = (packageInfo) => {
    let isRootPackage = packageInfo.packageJson.name === sandbox.packageInfo.packageJson.name;
    if (isRootPackage) {
      return '$ESY__SANDBOX';
    } else {
      let rel = path.relative(sandbox.packageInfo.rootDirectory, packageInfo.rootDirectory);
      return `$ESY__SANDBOX/${rel}`;
    }
  };

  let buildPath = (packageInfo, ...path) =>
    sandboxPath(packageInfo, '_build', ...path);

  let installPath = (packageInfo, ...path) =>
    sandboxPath(packageInfo, '_install', ...path);

  let installTmpPath = (packageInfo, ...path) =>
    sandboxPath(packageInfo, '_insttmp', ...path);

  let prelude: Array<MakeDefine | MakeRawItem> = [

    {
      type: 'raw',
      value: `SHELL = ${sandbox.env.SHELL}`,
    },

    // ESY__ROOT is the root directory of the ejected Esy build
    // environment.
    {
      type: 'raw',
      value: 'ESY__ROOT := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))'
    },

    // ESY__STORE is the directory where build artifacts should be stored.
    {
      type: 'raw',
      value: 'ESY__STORE ?= $(HOME)/.esy',
    },

    // ESY__SANDBOX is the sandbox directory, the directory where the root
    // package resides.
    {
      type: 'raw',
      value: 'ESY__SANDBOX ?= $(CURDIR)',
    },

  ];

  let rules: Array<MakeItem> = [

    // These are public API

    {
      type: 'rule',
      target: 'build',
      phony: true,
      dependencies: [`${sandboxPackageName}.build`],
    },
    {
      type: 'rule',
      target: 'shell',
      phony: true,
      dependencies: [`${sandboxPackageName}.shell`],
    },
    {
      type: 'rule',
      target: 'clean',
      phony: true,
      command: 'rm -rf $(ESY__SANDBOX)/_build $(ESY__SANDBOX)/_install $(ESY__SANDBOX)/_insttmp',
    },

    // Create store directory structure
    {
      type: 'rule',
      target: '$(ESY__STORE)/_install $(ESY__STORE)/_build $(ESY__STORE)/_insttmp',
      command: 'mkdir -p $(@)',
    },
    {
      type: 'rule',
      target: 'esy-store',
      phony: true,
      dependencies: ['$(ESY__STORE)/_install',  '$(ESY__STORE)/_build', '$(ESY__STORE)/_insttmp'],
    },
    {
      type: 'rule',
      target: '$(ESY__ROOT)/bin/realpath',
      dependencies: ['$(ESY__ROOT)/bin/realpath.c'],
      shell: '/bin/bash',
      command: 'gcc -o $(@) -x c $(<) 2> /dev/null',
    },
    {
      type: 'rule',
      target: 'esy-root',
      phony: true,
      dependencies: ['$(ESY__ROOT)/bin/realpath'],
    },
  ];

  traversePackageDependencyTree(
    sandbox.packageInfo,
    (packageInfo) => {
      let {normalizedName, packageJson, rootDirectory} = packageInfo;
      let isRootPackage = packageJson.name === sandboxPackageName;
      let buildHash = packageInfoKey(sandbox.env, packageInfo);

      let packagePath = isRootPackage
        ? []
        : path.relative(sandbox.packageInfo.rootDirectory, rootDirectory).split(path.sep);

      let buildCommand: ?string = null;
      if (packageJson.esy.build != null) {
        if (Array.isArray(packageJson.esy.build)) {
          buildCommand = packageJson.esy.build.join(' && ');
        } else {
          buildCommand = packageJson.esy.build;
        }
      }

      function emitPackageFile({filename, contents}) {
        emitFile({filename: packagePath.concat(filename), contents});
      }

      function definePackageRule(rule: {
        target: string;
        dependencies?: Array<string>;
        command?: ?string;
      }) {
        let {
          target,
          command,
          dependencies = []
        } = rule;
        rules.push({
          type: 'rule',
          target: packageTarget(target),
          dependencies: ['esy-store', 'esy-root', ...dependencies],
          phony: true,
          command: [
            outdent`
              $(shell_env_for__${normalizedName}) source $(ESY__ROOT)/bin/runtime.sh
              cd $esy_build__source_root
            `,
            command,
          ]
        });
      }

      function packageTarget(target, packageName = packageJson.name) {
        return `${packageName}.${target}`;
      }

      let buildEnvironment = PackageEnvironment.calculateEnvironment(
        sandbox,
        packageInfo,
        {installDirectory: installTmpPath(packageInfo)}
      );

      let dependencies = Object
        .keys(packageInfo.dependencyTree)
        .map(dep => packageTarget('build', dep));

      let allDependencies = collectTransitiveDependencies(packageInfo);

      let packageEnv = `${packageJson.name}__env`;

      emitPackageFile({
        filename: 'env',
        contents: renderEnv(buildEnvironment),
      });

      let findLibDestination =
        installTmpPath(packageInfo, 'lib');

      // Note that some packages can query themselves via ocamlfind during its
      // own build, this is why we include `findLibDestination` in the path too.
      let findLibPath =
        allDependencies.map(dep => installPath(dep, 'lib'))
        .concat(findLibDestination)
        .join(':');

      emitPackageFile({
        filename: 'findlib.conf.in',
        contents: outdent`
          path = "${findLibPath}"
          destdir = "${findLibDestination}"
          ldconf = "ignore"
          ocamlc = "ocamlc.opt"
          ocamldep = "ocamldep.opt"
          ocamldoc = "ocamldoc.opt"
          ocamllex = "ocamllex.opt"
          ocamlopt = "ocamlopt.opt"
        `
      });

      // Generate macOS sandbox configuration (sandbox-exec command)
      // TODO: Right now the only thing this sandbox configuration does is it
      // disallows writing into locations other than $cur__root,
      // $cur__target_dir and $cur__install. We should implement proper out of
      // source builds and also disallow $cur__root.
      // TODO: Try to use (deny default) and pick a set of rules for builds to
      // proceed (it chokes on xcodebuild for now if we disable reading "/" and
      // networking).
      emitPackageFile({
        filename: 'sandbox.sb.in',
        contents: outdent`
          (version 1.0)
          (allow default)

          (deny file-write*
            (subpath "/"))

          (allow file-write*
            (literal "/dev/null")

            (subpath "$TMPDIR_GLOBAL")
            (subpath "$TMPDIR")

            ; cur__root
            ; We don't really need to write into cur__root but some build systems
            ; can put .merlin files there so we allow that.
            (subpath "${sourcePath(packageInfo)}")

            ; cur__target_dir
            (subpath "${buildPath(packageInfo)}")

            ; cur__install
            (subpath "${installTmpPath(packageInfo)}")
          )

          (deny file-write*
            (subpath "${sourcePath(packageInfo)}/node_modules")
          )
        `
      });

      rules.push({
        type: 'define',
        name: `shell_env_for__${normalizedName}`,
        value: [
          {
            'CI': process.env.CI ? process.env.CI : null,
            'TMPDIR': '$(TMPDIR)',
            'ESY__STORE': '$(ESY__STORE)',
            'ESY__SANDBOX': '$(ESY__SANDBOX)',
            'ESY__ROOT': '$(ESY__ROOT)',
          },
          `source $(ESY__ROOT)/${packagePath.join('/')}/env`,
          {
            'esy_build__eject': `$(ESY__ROOT)/${packagePath.join('/')}`,
            'esy_build__type': packageInfo.packageJson.esy.buildsInSource
              ? 'in-source'
              : 'out-of-source',
            'esy_build__key': buildHash,
            'esy_build__source': packageInfo.source,
            'esy_build__source_type': packageInfo.sourceType,
            'esy_build__command': buildCommand || 'true',
            'esy_build__source_root': sourcePath(packageInfo),
            'esy_build__install': installPath(packageInfo),
          },
        ],
      });

      definePackageRule({
        target: 'clean',
        command: 'esy-clean'
      });

      definePackageRule({
        target: 'shell',
        dependencies,
        command: 'esy-shell'
      });

      definePackageRule({
        target: 'build',
        dependencies,
        command: 'esy-build'
      });
    });

  let allRules = [].concat(prelude).concat(rules);

  emitFile({
    filename: ['bin', 'realpath.c'],
    contents: outdent`
      #include<stdlib.h>

      main(int cc, char**vargs) {
        puts(realpath(vargs[1], 0));
      }
    `,
  });

  emitFile({
    filename: ['bin/render-env'],
    executable: true,
    contents: outdent`
      #!/bin/bash

      set -e
      set -o pipefail

      _TMPDIR_GLOBAL=$($ESY__ROOT/bin/realpath "/tmp")

      if [ -d "$TMPDIR" ]; then
        _TMPDIR=$($ESY__ROOT/bin/realpath "$TMPDIR")
      else
        _TMPDIR="/does/not/exist"
      fi

      sed \\
        -e "s|\\$ESY__STORE|$ESY__STORE|g"          \\
        -e "s|\\$ESY__SANDBOX|$ESY__SANDBOX|g"      \\
        -e "s|\\$TMPDIR_GLOBAL|$_TMPDIR_GLOBAL|g"   \\
        -e "s|\\$TMPDIR|$_TMPDIR|g"                 \\
        $1 > $2
    `
  });

  emitFile({
    filename: ['bin/replace-string'],
    executable: true,
    contents: outdent`
      #!/usr/bin/env python

      import sys
      import os
      import stat

      filename, src, dest = sys.argv[1:4]
      filename_stage = filename + '.esy_rewrite'

      filestat = os.stat(filename)

      # TODO: we probably should handle symlinks too in a special way,
      # to modify their location to a rewritten path

      with open(filename, 'r') as input_file:
        data = input_file.read()

      data = data.replace(src, dest)

      with open(filename_stage, 'w') as output_file:
        output_file.write(data)

      os.rename(filename_stage, filename)
      os.chmod(filename, stat.S_IMODE(filestat.st_mode))
    `
  });

  emitFile({
    filename: ['bin', 'runtime.sh'],
    contents: RUNTIME
  });

  emitFile({
    filename: ['Makefile'],
    contents: Makefile.renderMakefile(allRules),
  });
}

function hash(value: string): string {
  return crypto.createHash('sha1').update(value).digest('hex');
}

function renderEnv(groups: Array<EnvironmentGroup>): string {
  let env = flattenArray(groups.map(group => group.envVars));
  return env
    .filter(env => env.value != null)
    // $FlowFixMe: make sure env.value is refined above
    .map(env => `export ${env.name}="${env.value}";`)
    .join('\n');
}

module.exports = buildEjectCommand;
<|endoftext|>


<commit_before>angular.module('app.dashboard').filter('sessioninfo', function () {
	return function (session) {
		if(session) {
			return session.username!=='ANONYMOUS'?session.username:session.id;
		}
		return null;
	};
});

<commit_msg>closure<commit_after>(function () {
	'use strict';
	angular.module('app.dashboard').filter('sessioninfo', function () {
		return function (session) {
			if(session) {
				return session.username!=='ANONYMOUS'?session.username:session.id;
			}
			return null;
		};
	});
})();

<|endoftext|>


<commit_before>ko.bindingHandlers.singleOrDoubleClick = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        var singleHandler = undefined,
            doubleHandler = undefined,
            delay = 250,
            clicks = 0;

        if (_.isObject(value)) {
            singleHandler = value.click;
            doubleHandler = value.dblclick;
            delay = ko.utils.unwrapObservable(value.delay) || delay;
        }
        else {
            singleHandler = value;
        }

        $(element).click(function(e) {
            var sel = getSelection().toString();
            if(sel)
                return;

            clicks++;
            if (clicks === 1) {
                $(element).style('user-select', 'none');
                setTimeout(function () {
                    $(element).style('user-select', 'auto');
                    if (clicks === 1) {
                        if (singleHandler !== undefined) {
                            singleHandler.call(this, bindingContext.$data, e);
                        }
                    } else {
                        if (doubleHandler !== undefined) {
                            doubleHandler.call(this, bindingContext.$data, e);
                        }
                    }
                    clicks = 0;
                }, delay);
            }
        });
    }
};
<commit_msg>css not style<commit_after>ko.bindingHandlers.singleOrDoubleClick = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        var singleHandler = undefined,
            doubleHandler = undefined,
            delay = 250,
            clicks = 0;

        if (_.isObject(value)) {
            singleHandler = value.click;
            doubleHandler = value.dblclick;
            delay = ko.utils.unwrapObservable(value.delay) || delay;
        }
        else {
            singleHandler = value;
        }

        $(element).click(function(e) {
            var sel = getSelection().toString();
            if(sel)
                return;

            clicks++;
            if (clicks === 1) {
                $(element).css('user-select', 'none');
                setTimeout(function () {
                    $(element).css('user-select', 'auto');
                    if (clicks === 1) {
                        if (singleHandler !== undefined) {
                            singleHandler.call(this, bindingContext.$data, e);
                        }
                    } else {
                        if (doubleHandler !== undefined) {
                            doubleHandler.call(this, bindingContext.$data, e);
                        }
                    }
                    clicks = 0;
                }, delay);
            }
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * product Schema
 */
var productSchema = new Schema({
  purchaseDate: {
    type: String, //can this be of type date???
    default: '',
    trim: true
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  orderID: {
    type: String,
    default: '',
    trim: true
  },
  sku: {
    type: String,
    default: '',
    trim: true
  },
  quantity: {
    type: String,
    default: '',
    trim: true
  },
  price: { //amount user spent on item
    type: String,
    default: '',
    trim: true
  },
  cost: { //cost of producing/company purchased item
    type: String,
    default: '0',
    trim: true
  },
  brand: {
    type: String,
    default: 'Please input brand',
    trim: true
  },
  fbaAmt: {
    type: String,
    default: '',
    trim: true
  },
  fbaPct: {
    type: String,
    default: '',
    trim: true
  },
  profitMargin: {
    type: String,
    default: '',
    trim: true
  },
  productMargin: {
    type: String,
    default: '',
    trim: true
  }
});

mongoose.model('product', productSchema);
<commit_msg>changed purchaseDate type from string to date<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * product Schema
 */
var productSchema = new Schema({
  purchaseDate: {
    type: Date
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  orderID: {
    type: String,
    default: '',
    trim: true
  },
  sku: {
    type: String,
    default: '',
    trim: true
  },
  quantity: {
    type: String,
    default: '',
    trim: true
  },
  price: { //amount user spent on item
    type: String,
    default: '',
    trim: true
  },
  cost: { //cost of producing/company purchased item
    type: String,
    default: '0',
    trim: true
  },
  brand: {
    type: String,
    default: 'Please input brand',
    trim: true
  },
  fbaAmt: {
    type: String,
    default: '',
    trim: true
  },
  fbaPct: {
    type: String,
    default: '',
    trim: true
  },
  profitMargin: {
    type: String,
    default: '',
    trim: true
  },
  productMargin: {
    type: String,
    default: '',
    trim: true
  }
});

mongoose.model('product', productSchema);
<|endoftext|>


<commit_before>import React from 'react';

import Wrapper from 'common/Wrapper';
import ItemLink from 'common/ItemLink';
import ITEMS from 'common/ITEMS';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import { Blazballs, JLassie82, Putro } from 'MAINTAINERS';

export default [
  {
    date: new Date('2017-12-26'),
    changes: <Wrapper>Added support for <ItemLink id={ITEMS.CELERITY_OF_THE_WINDRUNNERS.id} icon />, <ItemLink id={ITEMS.MAGNETIZED_BLASTING_CAP_LAUNCHER.id} icon />, <ItemLink id={ITEMS.ZEVRIMS_HUNGER.id} icon />, <ItemLink id={ITEMS.ROOTS_OF_SHALADRASSIL.id} icon />, <ItemLink id={ITEMS.CALL_OF_THE_WILD.id} icon />, <ItemLink id={ITEMS.THE_APEX_PREDATORS_CLAW.id} icon /> and <ItemLink id={ITEMS.THE_SHADOW_HUNTERS_VOODOO_MASK.id} icon />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-26'),
    changes: <Wrapper></Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-24'),
    changes: 'Updated to the new checklist format',
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-15'),
    changes: 'Reworked T21 almost from the ground up, the 4p now includes damage and procs',
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-04'),
    changes: 'Added many talents and traits. Moved them into a singular box to improve visibility.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-29'),
    changes: 'Upgraded spec completeness to great.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-29'),
    changes: <Wrapper>Updated <SpellLink id={SPELLS.TRICK_SHOT_TALENT.id} /> to properly account for both single-target and cleave damage, added support for tier 21, and fixed a bug in the <SpellLink id={SPELLS.TRUESHOT.id} /> module where it counted too many <SpellLink id={SPELLS.AIMED_SHOT.id} />s than it should.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-17'),
    changes: 'Updated changelog to new format.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-12'),
    changes: 'Upgraded spec completeness to good.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-12'),
    changes: 'Updated config information.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-12'),
    changes: <Wrapper>Added a suggestion for execute trueshots and a <SpellLink id={SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id} /> suggestion when boss has between 25 and 20% hp, so the player can better utilise <SpellLink id={SPELLS.BULLSEYE_BUFF.id} />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-08'),
    changes: 'Added cancelled cast module.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-08'),
    changes: 'Fixed large FocusChart performance bugs.',
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-11-03'),
    changes: <Wrapper>Minor update to the <SpellLink id={SPELLS.LOCK_AND_LOAD_TALENT.id} /> module and its calculation of expected procs.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-25'),
    changes: <Wrapper> Added 5 new talent modules (<SpellLink id={SPELLS.EXPLOSIVE_SHOT_TALENT.id} />, <SpellLink id={SPELLS.PIERCING_SHOT_TALENT.id} />, <SpellLink id={SPELLS.VOLLEY_ACTIVATED.id} />, <SpellLink id={SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id} />, <SpellLink id={SPELLS.TRICK_SHOT_TALENT.id} />), fixed <SpellLink id={SPELLS.TRUESHOT.id} /> CD, added Focus Dump Checker.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-25'),
    changes: <Wrapper>Updated <SpellLink id={SPELLS.TRUE_AIM_TALENT.id} /> to include damage contributed information.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-25'),
    changes: <Wrapper> Adjust <SpellLink id={SPELLS.HUNTER_MM_T20_2P_BONUS.id} /> to account for nerfs.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Updated suggestions overall, added avatar, removed <SpellLink id={SPELLS.CYCLONIC_BURST_IMPACT_TRAIT.id} /> from cooldown tracker, added suggestion to TimeFocusCapped, updated AlwaysBeCasting and CastEfficiency.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.TRUESHOT.id} /> statistic with average <SpellLink id={SPELLS.AIMED_SHOT.id} /> pr <SpellLink id={SPELLS.TRUESHOT.id} />, and average starting focus pr <SpellLink id={SPELLS.TRUESHOT.id} />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.HUNTER_MM_T20_2P_BONUS.id} /> dmg increase breakdown.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Added <ItemLink id={ITEMS.SOUL_OF_THE_HUNTMASTER.id} />, <ItemLink id={ITEMS.MKII_GYROSCOPIC_STABILIZER.id} /> and <ItemLink id={ITEMS.WAR_BELT_OF_THE_SENTINEL_ARMY.id} />support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-20'),
    changes: <Wrapper>Added <ItemLink id={ITEMS.TARNISHED_SENTINEL_MEDALLION.id} /> and <SpellLink id={SPELLS.TRUESHOT.id} /> pairing tooltip.</Wrapper>,
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-10-20'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.TRUE_AIM_TALENT.id} /> and <SpellLink id={SPELLS.LOCK_AND_LOAD_TALENT.id} /> support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-16'),
    changes: <Wrapper> Added <ItemLink id={ITEMS.ULLRS_FEATHER_SNOWSHOES.id} /> to account for the <SpellLink id={SPELLS.TRUESHOT.id} />CDR it provides.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-16'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.HUNTER_MM_T19_2P_BONUS.id} /> support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-14'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.PATIENT_SNIPER_TALENT.id} /> tracking.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-14'),
    changes: 'Added Focus Capped Statistic Box.',
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-10-08'),
    changes: 'Added FocusTracker Module and FocusTracker Graph module and additional supporting modules.',
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-10-05'),
    changes: <Wrapper> remove <SpellLink id={SPELLS.CYCLONIC_BURST_TRAIT.id} /> from Cooldown view.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-05'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.QUICK_SHOT_TRAIT.id} /> reduction for <SpellLink id={SPELLS.TRUESHOT.id} />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-04'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.AIMED_SHOT.id} /> and <SpellLink id={SPELLS.VULNERABLE.id} /> tracker.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-03'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.HUNTER_MM_T20_2P_BONUS.id} /> and <SpellLink id={SPELLS.HUNTER_MM_T20_4P_BONUS.id} /> support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('02-10-2017'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.BULLSEYE_BUFF.id} /> buff to hunter_spells for future usage.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: 'Changed dead time to stricter, and get the player to cast more (should generally always be casting something).',
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: <Wrapper>Added suggestions to <SpellLink id={SPELLS.WINDBURST.id} /> and <SpellLink id={SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id} /> under CastEfficiency.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: 'Updated CastEfficiency to not show a lot of useless utility spells, unless they were specifically cast during that fight.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: 'Added spec info aswell as spec discussion URL + some basic rotational information while the modules aren\'t completed.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-09-26'),
    changes: <Wrapper>Fixed Cooldown to not include <SpellLink id={SPELLS.WINDBURST_MOVEMENT_SPEED.id} /> buff.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-09-05'),
    changes: 'Base files added.',
    contributors: [JLassie82],
  },
];
<commit_msg>update changelog correctly<commit_after>import React from 'react';

import Wrapper from 'common/Wrapper';
import ItemLink from 'common/ItemLink';
import ITEMS from 'common/ITEMS';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import { Blazballs, JLassie82, Putro } from 'MAINTAINERS';

export default [
  {
    date: new Date('2017-12-26'),
    changes: <Wrapper>Added support for <ItemLink id={ITEMS.CELERITY_OF_THE_WINDRUNNERS.id} icon />, <ItemLink id={ITEMS.MAGNETIZED_BLASTING_CAP_LAUNCHER.id} icon />, <ItemLink id={ITEMS.ZEVRIMS_HUNGER.id} icon />, <ItemLink id={ITEMS.ROOTS_OF_SHALADRASSIL.id} icon />, <ItemLink id={ITEMS.CALL_OF_THE_WILD.id} icon />, <ItemLink id={ITEMS.THE_APEX_PREDATORS_CLAW.id} icon /> and <ItemLink id={ITEMS.THE_SHADOW_HUNTERS_VOODOO_MASK.id} icon />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-26'),
    changes: 'Fix a bug with critical strike rating showing 5% too low for Marksmanship hunters.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-24'),
    changes: 'Updated to the new checklist format',
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-15'),
    changes: 'Reworked T21 almost from the ground up, the 4p now includes damage and procs',
    contributors: [Putro],
  },
  {
    date: new Date('2017-12-04'),
    changes: 'Added many talents and traits. Moved them into a singular box to improve visibility.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-29'),
    changes: 'Upgraded spec completeness to great.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-29'),
    changes: <Wrapper>Updated <SpellLink id={SPELLS.TRICK_SHOT_TALENT.id} /> to properly account for both single-target and cleave damage, added support for tier 21, and fixed a bug in the <SpellLink id={SPELLS.TRUESHOT.id} /> module where it counted too many <SpellLink id={SPELLS.AIMED_SHOT.id} />s than it should.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-17'),
    changes: 'Updated changelog to new format.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-12'),
    changes: 'Upgraded spec completeness to good.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-12'),
    changes: 'Updated config information.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-12'),
    changes: <Wrapper>Added a suggestion for execute trueshots and a <SpellLink id={SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id} /> suggestion when boss has between 25 and 20% hp, so the player can better utilise <SpellLink id={SPELLS.BULLSEYE_BUFF.id} />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-08'),
    changes: 'Added cancelled cast module.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-11-08'),
    changes: 'Fixed large FocusChart performance bugs.',
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-11-03'),
    changes: <Wrapper>Minor update to the <SpellLink id={SPELLS.LOCK_AND_LOAD_TALENT.id} /> module and its calculation of expected procs.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-25'),
    changes: <Wrapper> Added 5 new talent modules (<SpellLink id={SPELLS.EXPLOSIVE_SHOT_TALENT.id} />, <SpellLink id={SPELLS.PIERCING_SHOT_TALENT.id} />, <SpellLink id={SPELLS.VOLLEY_ACTIVATED.id} />, <SpellLink id={SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id} />, <SpellLink id={SPELLS.TRICK_SHOT_TALENT.id} />), fixed <SpellLink id={SPELLS.TRUESHOT.id} /> CD, added Focus Dump Checker.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-25'),
    changes: <Wrapper>Updated <SpellLink id={SPELLS.TRUE_AIM_TALENT.id} /> to include damage contributed information.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-25'),
    changes: <Wrapper> Adjust <SpellLink id={SPELLS.HUNTER_MM_T20_2P_BONUS.id} /> to account for nerfs.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Updated suggestions overall, added avatar, removed <SpellLink id={SPELLS.CYCLONIC_BURST_IMPACT_TRAIT.id} /> from cooldown tracker, added suggestion to TimeFocusCapped, updated AlwaysBeCasting and CastEfficiency.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.TRUESHOT.id} /> statistic with average <SpellLink id={SPELLS.AIMED_SHOT.id} /> pr <SpellLink id={SPELLS.TRUESHOT.id} />, and average starting focus pr <SpellLink id={SPELLS.TRUESHOT.id} />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.HUNTER_MM_T20_2P_BONUS.id} /> dmg increase breakdown.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-22'),
    changes: <Wrapper>Added <ItemLink id={ITEMS.SOUL_OF_THE_HUNTMASTER.id} />, <ItemLink id={ITEMS.MKII_GYROSCOPIC_STABILIZER.id} /> and <ItemLink id={ITEMS.WAR_BELT_OF_THE_SENTINEL_ARMY.id} />support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-20'),
    changes: <Wrapper>Added <ItemLink id={ITEMS.TARNISHED_SENTINEL_MEDALLION.id} /> and <SpellLink id={SPELLS.TRUESHOT.id} /> pairing tooltip.</Wrapper>,
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-10-20'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.TRUE_AIM_TALENT.id} /> and <SpellLink id={SPELLS.LOCK_AND_LOAD_TALENT.id} /> support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-16'),
    changes: <Wrapper> Added <ItemLink id={ITEMS.ULLRS_FEATHER_SNOWSHOES.id} /> to account for the <SpellLink id={SPELLS.TRUESHOT.id} />CDR it provides.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-16'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.HUNTER_MM_T19_2P_BONUS.id} /> support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-14'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.PATIENT_SNIPER_TALENT.id} /> tracking.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-14'),
    changes: 'Added Focus Capped Statistic Box.',
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-10-08'),
    changes: 'Added FocusTracker Module and FocusTracker Graph module and additional supporting modules.',
    contributors: [Blazballs],
  },
  {
    date: new Date('2017-10-05'),
    changes: <Wrapper> remove <SpellLink id={SPELLS.CYCLONIC_BURST_TRAIT.id} /> from Cooldown view.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-05'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.QUICK_SHOT_TRAIT.id} /> reduction for <SpellLink id={SPELLS.TRUESHOT.id} />.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-04'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.AIMED_SHOT.id} /> and <SpellLink id={SPELLS.VULNERABLE.id} /> tracker.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-03'),
    changes: <Wrapper>Added <SpellLink id={SPELLS.HUNTER_MM_T20_2P_BONUS.id} /> and <SpellLink id={SPELLS.HUNTER_MM_T20_4P_BONUS.id} /> support.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('02-10-2017'),
    changes: <Wrapper> Added <SpellLink id={SPELLS.BULLSEYE_BUFF.id} /> buff to hunter_spells for future usage.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: 'Changed dead time to stricter, and get the player to cast more (should generally always be casting something).',
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: <Wrapper>Added suggestions to <SpellLink id={SPELLS.WINDBURST.id} /> and <SpellLink id={SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id} /> under CastEfficiency.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: 'Updated CastEfficiency to not show a lot of useless utility spells, unless they were specifically cast during that fight.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-10-02'),
    changes: 'Added spec info aswell as spec discussion URL + some basic rotational information while the modules aren\'t completed.',
    contributors: [Putro],
  },
  {
    date: new Date('2017-09-26'),
    changes: <Wrapper>Fixed Cooldown to not include <SpellLink id={SPELLS.WINDBURST_MOVEMENT_SPEED.id} /> buff.</Wrapper>,
    contributors: [Putro],
  },
  {
    date: new Date('2017-09-05'),
    changes: 'Base files added.',
    contributors: [JLassie82],
  },
];
<|endoftext|>


<commit_before>/* eslint strict:0 */
var modules = Object.create(null);
var inGuard = false;

function define(id, factory) {
  modules[id] = {
    factory,
    module: {exports: {}},
    isInitialized: false,
    hasError: false,
  };

  if (__DEV__) { // HMR
    Object.assign(modules[id].module, {
      hot: {
        acceptCallback: null,
        accept: function(callback) {
          modules[id].module.hot.acceptCallback = callback;
        }
      }
    });
  }
}

function require(id) {
  var mod = modules[id];
  if (mod && mod.isInitialized) {
    return mod.module.exports;
  }

  return requireImpl(id);
}

function requireImpl(id) {
  if (global.ErrorUtils && !inGuard) {
    inGuard = true;
    var returnValue;
    try {
      returnValue = requireImpl.apply(this, arguments);
    } catch (e) {
      global.ErrorUtils.reportFatalError(e);
    }
    inGuard = false;
    return returnValue;
  }

  var mod = modules[id];
  if (!mod) {
    var msg = 'Requiring unknown module "' + id + '"';
    if (__DEV__) {
      msg += '. If you are sure the module is there, try restarting the packager.';
    }
    throw new Error(msg);
  }

  if (mod.hasError) {
    throw new Error(
      'Requiring module "' + id + '" which threw an exception'
    );
  }

  try {
    // We must optimistically mark mod as initialized before running the factory to keep any
    // require cycles inside the factory from causing an infinite require loop.
    mod.isInitialized = true;

    __DEV__ && Systrace().beginEvent('JS_require_' + id);

    // keep args in sync with with defineModuleCode in
    // packager/react-packager/src/Resolver/index.js
    mod.factory.call(global, global, require, mod.module, mod.module.exports);

    __DEV__ && Systrace().endEvent();
  } catch (e) {
    mod.hasError = true;
    mod.isInitialized = false;
    throw e;
  }

  return mod.module.exports;
}

const Systrace = __DEV__ && (() => {
  var _Systrace;
  try {
    _Systrace = require('Systrace');
  } catch (e) {}

  return _Systrace && _Systrace.beginEvent ?
    _Systrace : { beginEvent: () => {}, endEvent: () => {} };
});

global.__d = define;
global.require = require;

if (__DEV__) { // HMR
  function accept(id, factory) {
    var mod = modules[id];

    if (!mod) {
      define(id, factory);
      return; // new modules don't need to be accepted
    }

    if (!mod.module.hot) {
      console.warn(
        'Cannot accept module because Hot Module Replacement ' +
        'API was not installed.'
      );
      return;
    }

    if (mod.module.hot.acceptCallback) {
      mod.factory = factory;
      mod.isInitialized = false;
      require(id);

      mod.module.hot.acceptCallback();
    } else {
      console.warn(
        '[HMR] Module `' + id + '` can\'t be hot reloaded because it ' +
        'doesn\'t provide accept callback hook. Reload the app to get the updates.'
      );
    }
  }

  global.__accept = accept;
}
<commit_msg>Tweak Hot Loading yellow box wording<commit_after>/* eslint strict:0 */
var modules = Object.create(null);
var inGuard = false;

function define(id, factory) {
  modules[id] = {
    factory,
    module: {exports: {}},
    isInitialized: false,
    hasError: false,
  };

  if (__DEV__) { // HMR
    Object.assign(modules[id].module, {
      hot: {
        acceptCallback: null,
        accept: function(callback) {
          modules[id].module.hot.acceptCallback = callback;
        }
      }
    });
  }
}

function require(id) {
  var mod = modules[id];
  if (mod && mod.isInitialized) {
    return mod.module.exports;
  }

  return requireImpl(id);
}

function requireImpl(id) {
  if (global.ErrorUtils && !inGuard) {
    inGuard = true;
    var returnValue;
    try {
      returnValue = requireImpl.apply(this, arguments);
    } catch (e) {
      global.ErrorUtils.reportFatalError(e);
    }
    inGuard = false;
    return returnValue;
  }

  var mod = modules[id];
  if (!mod) {
    var msg = 'Requiring unknown module "' + id + '"';
    if (__DEV__) {
      msg += '. If you are sure the module is there, try restarting the packager.';
    }
    throw new Error(msg);
  }

  if (mod.hasError) {
    throw new Error(
      'Requiring module "' + id + '" which threw an exception'
    );
  }

  try {
    // We must optimistically mark mod as initialized before running the factory to keep any
    // require cycles inside the factory from causing an infinite require loop.
    mod.isInitialized = true;

    __DEV__ && Systrace().beginEvent('JS_require_' + id);

    // keep args in sync with with defineModuleCode in
    // packager/react-packager/src/Resolver/index.js
    mod.factory.call(global, global, require, mod.module, mod.module.exports);

    __DEV__ && Systrace().endEvent();
  } catch (e) {
    mod.hasError = true;
    mod.isInitialized = false;
    throw e;
  }

  return mod.module.exports;
}

const Systrace = __DEV__ && (() => {
  var _Systrace;
  try {
    _Systrace = require('Systrace');
  } catch (e) {}

  return _Systrace && _Systrace.beginEvent ?
    _Systrace : { beginEvent: () => {}, endEvent: () => {} };
});

global.__d = define;
global.require = require;

if (__DEV__) { // HMR
  function accept(id, factory) {
    var mod = modules[id];

    if (!mod) {
      define(id, factory);
      return; // new modules don't need to be accepted
    }

    if (!mod.module.hot) {
      console.warn(
        'Cannot accept module because Hot Module Replacement ' +
        'API was not installed.'
      );
      return;
    }

    if (mod.module.hot.acceptCallback) {
      mod.factory = factory;
      mod.isInitialized = false;
      require(id);

      mod.module.hot.acceptCallback();
    } else {
      console.warn(
        '[HMR] Module `' + id + '` can\'t be hot reloaded because it\'s not a ' +
        'React component. To get the changes reload the JS bundle.'
      );
    }
  }

  global.__accept = accept;
}
<|endoftext|>


<commit_before>import fse from 'fs-extra'
import extend from 'extend'
import mkdirp from 'mkdirp'
import xss from 'xss'
import {Promise} from 'bluebird'
import path from 'path'

import {
  cmsOperations,
  cmsData,
  config,
  Page,
  cmsTemplates,
  abeExtend,
  coreUtils
} from '../../'

export function checkRequired(text, json) {
  var regAbe = /{{abe[\S\s].*?key=['|"]([\S\s].*?['|"| ]}})/g
  var matches = text.match(regAbe)
  var requiredValue = 0
  var complete = 0
  if(typeof matches !== 'undefined' && matches !== null){
    Array.prototype.forEach.call(matches, (match) => {
      if(typeof match !== 'undefined' && match !== null) {

        var keyAttr = cmsData.regex.getAttr(match, 'key')
        var requiredAttr = cmsData.regex.getAttr(match, 'required')
        if(requiredAttr === 'true') {
          requiredValue++

          var minAttr = cmsData.regex.getAttr(match, 'min-length')
          minAttr = (minAttr !== '') ? minAttr : 0

          if(typeof json[keyAttr] !== 'undefined' && json[keyAttr] !== null && json[keyAttr] !== '') {
            if(minAttr > 0) {
              if(json[keyAttr].length >= minAttr) {
                complete++
              }
            }else {
              complete++
            }
          }
        }
      }
    })
  }

  return Math.round((requiredValue > 0) ? complete * 100 / requiredValue : 100)
}

export function save(url, tplPath = null, json = null, text = '', type = '', previousSave = null, realType = 'draft', publishAll = false) {
  url = coreUtils.slug.clean(url)

  var p = new Promise((resolve) => {
    var isRejectedDoc = false
    if(type === 'reject'){
      isRejectedDoc = true
      url = abeExtend.hooks.instance.trigger('beforeReject', url)
      type = 'draft'
      realType = 'draft'
      url = abeExtend.hooks.instance.trigger('afterReject', url)
    }
    var tplUrl = cmsData.file.fromUrl(url)
    type = type || 'draft'
    var pathIso = dateIso(tplUrl, type)
    if(typeof previousSave !== 'undefined' && previousSave !== null){
      pathIso.jsonPath = path.join(config.root, previousSave.jsonPath.replace(config.root, '')).replace(/-abe-d/, `-abe-${realType[0]}`)
      pathIso.htmlPath = path.join(config.root, previousSave.htmlPath.replace(config.root, '')).replace(/-abe-d/, `-abe-${realType[0]}`)
    }

    if(typeof json === 'undefined' || json === null) {
      json = cmsData.file.get(tplUrl.json.path)
    }

    if (tplPath == null) {
      tplPath = json.abe_meta.template
    }else if (tplPath.indexOf('.') > -1) {
      tplPath = tplPath.replace(/\..+$/, '')
    }
    var tpl = tplPath.replace(config.root, '')
    var fullTpl = path.join(config.root, config.templates.url, tpl) + '.' + config.files.templates.extension

    var ext = {
      template: tpl.replace(/^\/+/, ''),
      link: tplUrl.publish.link,
      complete: 0,
      type: type
    }
    let meta = config.meta.name
    json[meta] = extend(json[meta], ext)
    var date = cmsData.fileAttr.get(pathIso.jsonPath).d

    if (publishAll) {
      if(typeof json[meta].publish !== 'undefined' && json[meta].publish !== null) {
        date = json[meta].publish.date
      }
    }else {
      if(typeof date === 'undefined' || date === null || date === '') {
        date = new Date()
      }else {
        date = new Date(date)
      }
    }

    cmsData.metas.add(tpl, json, type, {}, date, realType)

    if(typeof text === 'undefined' || text === null || text === '') {
      text = cmsTemplates.template.getTemplate(fullTpl)
    }

    cmsData.source.getDataList(path.dirname(tplUrl.publish.link), text, json)
        .then(() => {
          json = abeExtend.hooks.instance.trigger('afterGetDataListOnSave', json)
          for(var prop in json){
            if(typeof json[prop] === 'object' && Array.isArray(json[prop]) && json[prop].length === 1){
              var valuesAreEmpty = true
              json[prop].forEach(function (element) {
                for(var p in element) {
                  if(element[p] !== ''){
                    valuesAreEmpty = false
                  }
                }
              })
              if(valuesAreEmpty){
                delete json[prop]
              }
            }
          }

          var obj = {
            publishAll:publishAll,
            type:type,
            template:{
              path: fullTpl
            },
            html: {
              path:pathIso.htmlPath
            },
            json: {
              content: json,
              path: pathIso.jsonPath
            }
          }

          obj = abeExtend.hooks.instance.trigger('beforeSave', obj)

          obj.json.content[meta].complete = checkRequired(text, obj.json.content)

          var res = saveJsonAndHtml(tpl.replace(/^\/+/, ''), obj, text)
          if (isRejectedDoc) {
            res.reject = cmsData.fileAttr.delete(url).replace(path.join(config.root, config.draft.url), '')
          }

          abeExtend.hooks.instance.trigger('afterSave', obj)

          cmsTemplates.assets.copy()

          resolve(res)
        }).catch(function(e) {
          console.error('Save.js', e)
        })
  })

  return p
}

export function saveJsonAndHtml(templateId, obj, html) {
  var page = new Page(templateId, html, obj.json.content, true)

  if (obj.json.content.abe_meta.status === 'publish') {
    saveHtml(obj.html.path, page.html)
  }
  saveJson(obj.json.path, obj.json.content)

  return {
    json: obj.json.content,
    jsonPath: obj.json.path,
    html: page.html,
    htmlPath: obj.html.path
  }
}

export function saveJson(url, json) {
  mkdirp.sync(path.dirname(url))

  if(typeof json.abe_source !== 'undefined' && json.abe_source !== null) {
    delete json.abe_source
  }

  var eachRecursive = function (obj) {
    for (var k in obj) {
      if (typeof obj[k] === 'object' && obj[k] !== null){
        eachRecursive(obj[k])
      } else if (typeof obj[k] !== 'undefined' && obj[k] !== null){
        obj[k] = xss(obj[k].toString().replace(/"/g, '"'), { 'whiteList': config.htmlWhiteList })
      }
    }
  }

  eachRecursive(json)

  fse.writeJsonSync(url, json, {
    space: 2,
    encoding: 'utf-8'
  })
  return true
}

export function saveHtml(url, html) {
  mkdirp.sync(path.dirname(url))
  if(cmsData.fileAttr.test(url) && cmsData.fileAttr.get(url).s !== 'd'){
    cmsOperations.remove.olderRevisionByType(cmsData.fileAttr.delete(url), cmsData.fileAttr.get(url).s)
  }
  fse.writeFileSync(url, html)
}

export function dateIso(tplUrl, type = null) {
  var newDateISO
  var dateISO
  var saveJsonFile = tplUrl.json.path
  var saveFile = tplUrl['draft'].path

  switch(type) {
  case 'draft':
    newDateISO = cmsData.revision.removeStatusAndDateFromFileName((new Date().toISOString()))
    dateISO = 'd' + newDateISO
    break
  case 'publish':
    saveJsonFile = tplUrl.publish.json
    saveFile = tplUrl.publish.path
    break
  default:
    newDateISO = cmsData.revision.removeStatusAndDateFromFileName((new Date().toISOString()))
    dateISO = type[0] + newDateISO
    break
  }

  if(dateISO) {
    saveJsonFile = cmsData.fileAttr.add(saveJsonFile, dateISO)
    saveFile = cmsData.fileAttr.add(saveFile, dateISO)
  }

  return {
    jsonPath: saveJsonFile,
    htmlPath: saveFile
  }
}<commit_msg>Refactor: remove slugify url on save because create alread do it<commit_after>import fse from 'fs-extra'
import extend from 'extend'
import mkdirp from 'mkdirp'
import xss from 'xss'
import {Promise} from 'bluebird'
import path from 'path'

import {
  cmsOperations,
  cmsData,
  config,
  Page,
  cmsTemplates,
  abeExtend,
  coreUtils
} from '../../'

export function checkRequired(text, json) {
  var regAbe = /{{abe[\S\s].*?key=['|"]([\S\s].*?['|"| ]}})/g
  var matches = text.match(regAbe)
  var requiredValue = 0
  var complete = 0
  if(typeof matches !== 'undefined' && matches !== null){
    Array.prototype.forEach.call(matches, (match) => {
      if(typeof match !== 'undefined' && match !== null) {

        var keyAttr = cmsData.regex.getAttr(match, 'key')
        var requiredAttr = cmsData.regex.getAttr(match, 'required')
        if(requiredAttr === 'true') {
          requiredValue++

          var minAttr = cmsData.regex.getAttr(match, 'min-length')
          minAttr = (minAttr !== '') ? minAttr : 0

          if(typeof json[keyAttr] !== 'undefined' && json[keyAttr] !== null && json[keyAttr] !== '') {
            if(minAttr > 0) {
              if(json[keyAttr].length >= minAttr) {
                complete++
              }
            }else {
              complete++
            }
          }
        }
      }
    })
  }

  return Math.round((requiredValue > 0) ? complete * 100 / requiredValue : 100)
}

export function save(url, tplPath = null, json = null, text = '', type = '', previousSave = null, realType = 'draft', publishAll = false) {
  var p = new Promise((resolve) => {
    var isRejectedDoc = false
    if(type === 'reject'){
      isRejectedDoc = true
      url = abeExtend.hooks.instance.trigger('beforeReject', url)
      type = 'draft'
      realType = 'draft'
      url = abeExtend.hooks.instance.trigger('afterReject', url)
    }
    var tplUrl = cmsData.file.fromUrl(url)
    type = type || 'draft'
    var pathIso = dateIso(tplUrl, type)
    if(typeof previousSave !== 'undefined' && previousSave !== null){
      pathIso.jsonPath = path.join(config.root, previousSave.jsonPath.replace(config.root, '')).replace(/-abe-d/, `-abe-${realType[0]}`)
      pathIso.htmlPath = path.join(config.root, previousSave.htmlPath.replace(config.root, '')).replace(/-abe-d/, `-abe-${realType[0]}`)
    }

    if(typeof json === 'undefined' || json === null) {
      json = cmsData.file.get(tplUrl.json.path)
    }

    if (tplPath == null) {
      tplPath = json.abe_meta.template
    }else if (tplPath.indexOf('.') > -1) {
      tplPath = tplPath.replace(/\..+$/, '')
    }
    var tpl = tplPath.replace(config.root, '')
    var fullTpl = path.join(config.root, config.templates.url, tpl) + '.' + config.files.templates.extension

    var ext = {
      template: tpl.replace(/^\/+/, ''),
      link: tplUrl.publish.link,
      complete: 0,
      type: type
    }
    let meta = config.meta.name
    json[meta] = extend(json[meta], ext)
    var date = cmsData.fileAttr.get(pathIso.jsonPath).d

    if (publishAll) {
      if(typeof json[meta].publish !== 'undefined' && json[meta].publish !== null) {
        date = json[meta].publish.date
      }
    }else {
      if(typeof date === 'undefined' || date === null || date === '') {
        date = new Date()
      }else {
        date = new Date(date)
      }
    }

    cmsData.metas.add(tpl, json, type, {}, date, realType)

    if(typeof text === 'undefined' || text === null || text === '') {
      text = cmsTemplates.template.getTemplate(fullTpl)
    }

    cmsData.source.getDataList(path.dirname(tplUrl.publish.link), text, json)
        .then(() => {
          json = abeExtend.hooks.instance.trigger('afterGetDataListOnSave', json)
          for(var prop in json){
            if(typeof json[prop] === 'object' && Array.isArray(json[prop]) && json[prop].length === 1){
              var valuesAreEmpty = true
              json[prop].forEach(function (element) {
                for(var p in element) {
                  if(element[p] !== ''){
                    valuesAreEmpty = false
                  }
                }
              })
              if(valuesAreEmpty){
                delete json[prop]
              }
            }
          }

          var obj = {
            publishAll:publishAll,
            type:type,
            template:{
              path: fullTpl
            },
            html: {
              path:pathIso.htmlPath
            },
            json: {
              content: json,
              path: pathIso.jsonPath
            }
          }

          obj = abeExtend.hooks.instance.trigger('beforeSave', obj)

          obj.json.content[meta].complete = checkRequired(text, obj.json.content)

          var res = saveJsonAndHtml(tpl.replace(/^\/+/, ''), obj, text)
          if (isRejectedDoc) {
            res.reject = cmsData.fileAttr.delete(url).replace(path.join(config.root, config.draft.url), '')
          }

          abeExtend.hooks.instance.trigger('afterSave', obj)

          cmsTemplates.assets.copy()

          resolve(res)
        }).catch(function(e) {
          console.error('Save.js', e)
        })
  })

  return p
}

export function saveJsonAndHtml(templateId, obj, html) {
  var page = new Page(templateId, html, obj.json.content, true)

  if (obj.json.content.abe_meta.status === 'publish') {
    saveHtml(obj.html.path, page.html)
  }
  saveJson(obj.json.path, obj.json.content)

  return {
    json: obj.json.content,
    jsonPath: obj.json.path,
    html: page.html,
    htmlPath: obj.html.path
  }
}

export function saveJson(url, json) {
  mkdirp.sync(path.dirname(url))

  if(typeof json.abe_source !== 'undefined' && json.abe_source !== null) {
    delete json.abe_source
  }

  var eachRecursive = function (obj) {
    for (var k in obj) {
      if (typeof obj[k] === 'object' && obj[k] !== null){
        eachRecursive(obj[k])
      } else if (typeof obj[k] !== 'undefined' && obj[k] !== null){
        obj[k] = xss(obj[k].toString().replace(/"/g, '"'), { 'whiteList': config.htmlWhiteList })
      }
    }
  }

  eachRecursive(json)

  fse.writeJsonSync(url, json, {
    space: 2,
    encoding: 'utf-8'
  })
  return true
}

export function saveHtml(url, html) {
  mkdirp.sync(path.dirname(url))
  if(cmsData.fileAttr.test(url) && cmsData.fileAttr.get(url).s !== 'd'){
    cmsOperations.remove.olderRevisionByType(cmsData.fileAttr.delete(url), cmsData.fileAttr.get(url).s)
  }
  fse.writeFileSync(url, html)
}

export function dateIso(tplUrl, type = null) {
  var newDateISO
  var dateISO
  var saveJsonFile = tplUrl.json.path
  var saveFile = tplUrl['draft'].path

  switch(type) {
  case 'draft':
    newDateISO = cmsData.revision.removeStatusAndDateFromFileName((new Date().toISOString()))
    dateISO = 'd' + newDateISO
    break
  case 'publish':
    saveJsonFile = tplUrl.publish.json
    saveFile = tplUrl.publish.path
    break
  default:
    newDateISO = cmsData.revision.removeStatusAndDateFromFileName((new Date().toISOString()))
    dateISO = type[0] + newDateISO
    break
  }

  if(dateISO) {
    saveJsonFile = cmsData.fileAttr.add(saveJsonFile, dateISO)
    saveFile = cmsData.fileAttr.add(saveFile, dateISO)
  }

  return {
    jsonPath: saveJsonFile,
    htmlPath: saveFile
  }
}<|endoftext|>


<commit_before>import { ApolloServer } from 'apollo-server-express';
import cookieParser from 'cookie-parser';
import express from 'express';
import hopsConfig from 'hops-config';
// eslint-disable-next-line node/no-extraneous-import
import schema from 'hops-apollo-mock-server/schema';
// eslint-disable-next-line node/no-extraneous-import
import extendContext from 'hops-apollo-mock-server/context-extender';

const apolloAppPromise = Promise.resolve(
  typeof schema === 'function' ? schema() : schema
).then((resolvedSchema) => {
  const app = express();
  app.use(cookieParser());

  const server = new ApolloServer({
    schema: resolvedSchema,
    playground: {
      settings: {
        'request.credentials': 'same-origin',
      },
    },
    context: (context) => extendContext({ ...context, config: hopsConfig }),
  });

  server.applyMiddleware({
    app,
    path: hopsConfig.graphqlMockServerPath,
    cors: {
      credentials: true,
      origin: true,
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
      allowedHeaders: 'content-type',
    },
  });

  return app;
});

export default (req, res, next) => {
  apolloAppPromise.then((app) => app.handle(req, res, next), next);
};
<commit_msg>fix: start server for version 3<commit_after>import { ApolloServer } from 'apollo-server-express';
import cookieParser from 'cookie-parser';
import express from 'express';
import hopsConfig from 'hops-config';
// eslint-disable-next-line node/no-extraneous-import
import schema from 'hops-apollo-mock-server/schema';
// eslint-disable-next-line node/no-extraneous-import
import extendContext from 'hops-apollo-mock-server/context-extender';

const apolloAppPromise = Promise.resolve(
  typeof schema === 'function' ? schema() : schema
).then(async (resolvedSchema) => {
  const app = express();
  app.use(cookieParser());

  const server = new ApolloServer({
    schema: resolvedSchema,
    playground: {
      settings: {
        'request.credentials': 'same-origin',
      },
    },
    context: (context) => extendContext({ ...context, config: hopsConfig }),
  });

  await server.start();

  server.applyMiddleware({
    app,
    path: hopsConfig.graphqlMockServerPath,
    cors: {
      credentials: true,
      origin: true,
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
      allowedHeaders: 'content-type',
    },
  });

  return app;
});

export default (req, res, next) => {
  apolloAppPromise.then((app) => app.handle(req, res, next), next);
};
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React from 'react'
import {EditableValue, Range} from 'tocco-ui'

import editableTypeConfigs from './editableTypeConfigs'

const getEvents = (type, formField, formName, formData, events) =>
  editableTypeConfigs[type] && editableTypeConfigs[type].getEvents
    ? editableTypeConfigs[type].getEvents({formField, formName, formData, events})
    : events

const getValue = (type, formField, formName, formData, currentValue) =>
  editableTypeConfigs[type] && editableTypeConfigs[type].getValue
    ? editableTypeConfigs[type].getValue({formField, formName, formData, currentValue})
    : currentValue

const getOptions = (type, formField, formName, formData) =>
  editableTypeConfigs[type] && editableTypeConfigs[type].getOptions
    ? editableTypeConfigs[type].getOptions({formField, formName, formData})
    : {}

const EditableValueFactory = ({type, range, formField, formName, value, info, events, formData}) => {
  const formType = formField.dataType || formField.componentType
  const options = getOptions(formType, formField, formName, formData)

  events = getEvents(formType, formField, formName, formData, events)
  value = getValue(formType, formField, formName, formData, value)

  const Component = range ? Range : EditableValue

  return (
    <Component
      type={type}
      events={events}
      value={value}
      {...info}
      options={options}
      {...(range && {
        fromText: formData.intl.formatMessage({id: 'client.component.range.from'}),
        toText: formData.intl.formatMessage({id: 'client.component.range.to'})
      })}
    />
  )
}

EditableValueFactory.propTypes = {
  type: PropTypes.string,
  range: PropTypes.bool,
  formName: PropTypes.string,
  formField: PropTypes.shape({
    dataType: PropTypes.string,
    componentType: PropTypes.string
  }),
  value: PropTypes.any,
  info: PropTypes.object,
  events: PropTypes.object,
  formData: PropTypes.object
}

export default (type, range) => props => <EditableValueFactory type={type} range={range} {...props} />
<commit_msg>fix(app-extensions): try to find editableTypeConfig for mapped type<commit_after>import PropTypes from 'prop-types'
import React from 'react'
import {EditableValue, Range} from 'tocco-ui'

import editableTypeConfigs from './editableTypeConfigs'

const getEvents = (typeConfig, formField, formName, formData, events) =>
  typeConfig && typeConfig.getEvents ? typeConfig.getEvents({formField, formName, formData, events}) : events

const getValue = (typeConfig, formField, formName, formData, currentValue) =>
  typeConfig && typeConfig.getValue ? typeConfig.getValue({formField, formName, formData, currentValue}) : currentValue

const getOptions = (typeConfig, formField, formName, formData) =>
  typeConfig && typeConfig.getOptions ? typeConfig.getOptions({formField, formName, formData}) : {}

const EditableValueFactory = ({type, range, formField, formName, value, info, events, formData}) => {
  const formType = formField.dataType || formField.componentType
  const typeConfig = editableTypeConfigs[type] || editableTypeConfigs[formType]
  const options = getOptions(typeConfig, formField, formName, formData)

  events = getEvents(typeConfig, formField, formName, formData, events)
  value = getValue(typeConfig, formField, formName, formData, value)

  const Component = range ? Range : EditableValue

  return (
    <Component
      type={type}
      events={events}
      value={value}
      {...info}
      options={options}
      {...(range && {
        fromText: formData.intl.formatMessage({id: 'client.component.range.from'}),
        toText: formData.intl.formatMessage({id: 'client.component.range.to'})
      })}
    />
  )
}

EditableValueFactory.propTypes = {
  type: PropTypes.string,
  range: PropTypes.bool,
  formName: PropTypes.string,
  formField: PropTypes.shape({
    dataType: PropTypes.string,
    componentType: PropTypes.string
  }),
  value: PropTypes.any,
  info: PropTypes.object,
  events: PropTypes.object,
  formData: PropTypes.object
}

export default (type, range) => props => <EditableValueFactory type={type} range={range} {...props} />
<|endoftext|>