<commit_before>"use strict";

var RegExpType = require("./types").RegExp;
var Types = require("./types").Types;
var flatten = require("./utils").flatten;
var error = require("http-error");

module.exports = function Route(route, options, handler, types) {

    // options is optional
    if (typeof options == "function" || Array.isArray(options)) {
        types = handler;
        handler = options;
        options = {};
    }

    options.route = route;
    types = types || new Types();

    this.middlewares = flatten(handler);

    this.middlewares = this.middlewares.map(function(handler) {
        if (handler.length == 2) {
            handler = wrapHandler(handler);
        }
        return handler;
    });

    this.middlewares.unshift(decodeParams);

    this.method = (options.method || "GET").toLowerCase();

    var self = this;
    var keys = [];
    var params = options.params || {};
    var routeRe = normalizePath(options.route, keys, params);
    params = normalizeParams(params);

    function wrapHandler(handler) {
        return function(req, res, next) {
            handler(req.params || {}, function(err, json, headers, code) {
                if (err) return next(err);

                res.json(json, headers, code);
            });
        };
    }

    /**
     * Creates a rgular expression to match this route.
     * Url param names are stored in `keys` and the `params` are completed with
     * the default values for url parameters.
     */
    function normalizePath(path, keys, params) {
        for (var name in params) {
            var param = params[name];
            if (typeof param == "string" || param instanceof RegExp)
                params[name] = { type: param};
        }

        path = path
            .replace(/\/:([\w\.\-\_]+)(\*?)/g, function(match, key, wildcard) {
                keys.push(key);
                if (!params[key]) {
                    params[key] = {};
                }
                // url params default to type string and optional=false
                var param = params[key];
                param.type = param.type || "string";

                if (!param.source || param.source == "url")
                    param.source = "url";
                else
                    throw new Error("Url parameters must have 'url' as source but found '" + param.source + "'");
                if (wildcard)
                    return "(/*)";
                else
                    return "/([^\\/]+)";
            })
            .replace(/([\/.])/g, '\\$1')
            .replace(/\*/g, '(.*)');

        return new RegExp('^' + path + '$');
    }

    function normalizeParams(params) {
        for (var name in params) {
            var param = params[name];

            if (param.source == "query") {
                // query params default to string
                param.type = param.type || "string";
            }
            else if (!param.source || param.source == "body") {
                // body params default to json
                param.type = param.type || "json";
                param.source = "body";
            }
            else if (param.source === "url") {
                param.type = param.type || "string";
            }
            else {
                throw new Error("parameter source muste be 'url', 'query' or 'body'");
            }

            // optional defaults to false
            param.optional = !!param.optional;

            // allow regular expressions as types
            if (param.type instanceof RegExp)
                param.type = new RegExpType(param.type);

            // convert all types to type objects
            param.type = types.get(param.type);
        }

        return params;
    }

    /**
     * Check if the given path matched the route regular expression. If
     * the regular expression doesn't match or parsing fails `match` will
     * return `false`
     **/
    this.match = function(req, path) {
        var m = path.match(routeRe);
        if (!m) return false;

        var match = {};
        for (var i = 0; i < keys.length; i++) {
            var value = m[i+1];
            var key = keys[i];
            var param = params[key];
            var type = param.type;
            try {
                value = type.parse(value);
            } catch (e) {
                return false;
            }
            if (!type.check(value)) {
                return false;
            }
            match[key] = value;
        }
        req.match = match;
        return true;
    };

    /**
     * Middleware to validate the parameters. It will take `req.match` for
     * url params, decode the query and body parameters. If validation passes
     * the decoded and validated parameters are stored in `req.params`
     * otherwhise an error is returned.
     */
    function decodeParams(req, res, next) {
        var urlParams = req.match;
        if (!urlParams) return;

        var body = req.body || {};
        var query = req.parsedUrl.query;

        req.params = req.params || {};
        var errors = [];

        // marker object
        var EMPTY = {};

        // 1. check if all required params are there
        for (var key in params) {
            var param = params[key];
            if (
                (!param.optional) && (
                    (param.source == "body" && !(key in body)) ||
                    (param.source == "query" && !(key in query)) ||
                    (param.source == "url" && !(key in urlParams))
                )
            ) {
                errors.push({
                    "resource": self.name || "root",
                    "field": key,
                    "source": param.source,
                    "code": "missing_field"
                });
            }
            else {
                var type = param.type;
                var value = EMPTY;
                var isValid = true;
                switch(param.source) {
                    case "body":
                        if (param.optional && !(key in body))
                            break;

                        value = body[key]; // body is already JSON parsed
                        isValid = type.check(value);
                        break;
                    case "query":
                        if (param.optional && !(key in query))
                            break;

                        try {
                            value = type.parse(query[key]);
                        } catch(e) {
                            isValid = false;
                        }
                        isValid = isValid === false ? false : type.check(value);
                        break;
                    case "url":
                        if (param.optional && !(key in urlParams))
                            break;

                        value = urlParams[key]; // is already parsed and checked
                        isValid = true;
                        break;
                }

                if (!isValid) {
                    errors.push({
                        "resource": self.name || "root",
                        "field": key,
                        "type_expected": type.toString(),
                        "code": "invalid"
                    });
                }
                else {
                    if (value !== EMPTY)
                        req.params[key] = value;
                    else if ("default" in param)
                        req.params[key] = param.default;

                }
            }
        }

        if (errors.length) {
            var err = new error.UnprocessableEntity("Validation failed");
            err.errors = errors;
            return next(err);
        }
        next();
    }

    this.describe = function() {
        var route = {
            route: options.route,
            method: this.method
        };

        if (options.name)
            route.name = options.name;

        if (options.description)
            route.description = options.description;

        route.params = {};
        for (var name in params) {
            var param = params[name];
            route.params[name] = {
                name: param.name,
                type: param.type.toString(),
                source: param.source,
                optional: param.optional
            };
            if (param.description)
                route.params[name].description = param.description;
        }

        if (!Object.keys(route.params).length)
            delete route.params;

        return route;
    };
};<commit_msg>Remove strict routing<commit_after>"use strict";

var RegExpType = require("./types").RegExp;
var Types = require("./types").Types;
var flatten = require("./utils").flatten;
var error = require("http-error");

module.exports = function Route(route, options, handler, types) {

    // options is optional
    if (typeof options == "function" || Array.isArray(options)) {
        types = handler;
        handler = options;
        options = {};
    }

    options.route = route;
    types = types || new Types();

    this.middlewares = flatten(handler);

    this.middlewares = this.middlewares.map(function(handler) {
        if (handler.length == 2) {
            handler = wrapHandler(handler);
        }
        return handler;
    });

    this.middlewares.unshift(decodeParams);

    this.method = (options.method || "GET").toLowerCase();

    var self = this;
    var keys = [];
    var params = options.params || {};
    var routeRe = normalizePath(options.route, keys, params);
    params = normalizeParams(params);

    function wrapHandler(handler) {
        return function(req, res, next) {
            handler(req.params || {}, function(err, json, headers, code) {
                if (err) return next(err);

                res.json(json, headers, code);
            });
        };
    }

    /**
     * Creates a rgular expression to match this route.
     * Url param names are stored in `keys` and the `params` are completed with
     * the default values for url parameters.
     */
    function normalizePath(path, keys, params) {
        for (var name in params) {
            var param = params[name];
            if (typeof param == "string" || param instanceof RegExp)
                params[name] = { type: param};
        }

        path = path
            .concat("/?")
            .replace(/\/:([\w\.\-\_]+)(\*?)/g, function(match, key, wildcard) {
                keys.push(key);
                if (!params[key]) {
                    params[key] = {};
                }
                // url params default to type string and optional=false
                var param = params[key];
                param.type = param.type || "string";

                if (!param.source || param.source == "url")
                    param.source = "url";
                else
                    throw new Error("Url parameters must have 'url' as source but found '" + param.source + "'");
                if (wildcard)
                    return "(/*)";
                else
                    return "/([^\\/]+)";
            })
            .replace(/([\/.])/g, '\\$1')
            .replace(/\*/g, '(.*)');

        return new RegExp('^' + path + '$');
    }

    function normalizeParams(params) {
        for (var name in params) {
            var param = params[name];

            if (param.source == "query") {
                // query params default to string
                param.type = param.type || "string";
            }
            else if (!param.source || param.source == "body") {
                // body params default to json
                param.type = param.type || "json";
                param.source = "body";
            }
            else if (param.source === "url") {
                param.type = param.type || "string";
            }
            else {
                throw new Error("parameter source muste be 'url', 'query' or 'body'");
            }

            // optional defaults to false
            param.optional = !!param.optional;

            // allow regular expressions as types
            if (param.type instanceof RegExp)
                param.type = new RegExpType(param.type);

            // convert all types to type objects
            param.type = types.get(param.type);
        }

        return params;
    }

    /**
     * Check if the given path matched the route regular expression. If
     * the regular expression doesn't match or parsing fails `match` will
     * return `false`
     **/
    this.match = function(req, path) {
        var m = path.match(routeRe);
        if (!m) return false;

        var match = {};
        for (var i = 0; i < keys.length; i++) {
            var value = m[i+1];
            var key = keys[i];
            var param = params[key];
            var type = param.type;
            try {
                value = type.parse(value);
            } catch (e) {
                return false;
            }
            if (!type.check(value)) {
                return false;
            }
            match[key] = value;
        }
        req.match = match;
        return true;
    };

    /**
     * Middleware to validate the parameters. It will take `req.match` for
     * url params, decode the query and body parameters. If validation passes
     * the decoded and validated parameters are stored in `req.params`
     * otherwhise an error is returned.
     */
    function decodeParams(req, res, next) {
        var urlParams = req.match;
        if (!urlParams) return;

        var body = req.body || {};
        var query = req.parsedUrl.query;

        req.params = req.params || {};
        var errors = [];

        // marker object
        var EMPTY = {};

        // 1. check if all required params are there
        for (var key in params) {
            var param = params[key];
            if (
                (!param.optional) && (
                    (param.source == "body" && !(key in body)) ||
                    (param.source == "query" && !(key in query)) ||
                    (param.source == "url" && !(key in urlParams))
                )
            ) {
                errors.push({
                    "resource": self.name || "root",
                    "field": key,
                    "source": param.source,
                    "code": "missing_field"
                });
            }
            else {
                var type = param.type;
                var value = EMPTY;
                var isValid = true;
                switch(param.source) {
                    case "body":
                        if (param.optional && !(key in body))
                            break;

                        value = body[key]; // body is already JSON parsed
                        isValid = type.check(value);
                        break;
                    case "query":
                        if (param.optional && !(key in query))
                            break;

                        try {
                            value = type.parse(query[key]);
                        } catch(e) {
                            isValid = false;
                        }
                        isValid = isValid === false ? false : type.check(value);
                        break;
                    case "url":
                        if (param.optional && !(key in urlParams))
                            break;

                        value = urlParams[key]; // is already parsed and checked
                        isValid = true;
                        break;
                }

                if (!isValid) {
                    errors.push({
                        "resource": self.name || "root",
                        "field": key,
                        "type_expected": type.toString(),
                        "code": "invalid"
                    });
                }
                else {
                    if (value !== EMPTY)
                        req.params[key] = value;
                    else if ("default" in param)
                        req.params[key] = param.default;

                }
            }
        }

        if (errors.length) {
            var err = new error.UnprocessableEntity("Validation failed");
            err.errors = errors;
            return next(err);
        }
        next();
    }

    this.describe = function() {
        var route = {
            route: options.route,
            method: this.method
        };

        if (options.name)
            route.name = options.name;

        if (options.description)
            route.description = options.description;

        route.params = {};
        for (var name in params) {
            var param = params[name];
            route.params[name] = {
                name: param.name,
                type: param.type.toString(),
                source: param.source,
                optional: param.optional
            };
            if (param.description)
                route.params[name].description = param.description;
        }

        if (!Object.keys(route.params).length)
            delete route.params;

        return route;
    };
};<|endoftext|>


<commit_before>var step = require("step"),
outcome = require("outcome"),
request = require("request"),
fs = require("fs"),
mkdirp = require("mkdirp"),
path = require("path"),
child_process = require("child_process"),
exec = child_process.exec,
spawn = child_process.spawn,
sprintf = require("sprintf").sprintf,
ncp = require("ncp").ncp,
sardines = require("sardines");

/**
 */

exports.compile = function(args, next) {

	var on = outcome.error(next);

	args.input = require.resolve(args.input);

	step(

		/**
		 * 1. download node
		 */

		function() {
			downloadNode(args.runtime, args.temp, this);
		},

		/**
		 * 2. build the script into ONE file
		 */

		on.success(function(node) {
			console.log("making application bundle with %s", args.input);
			this.node = node;

			sardines({ entries: [args.input], platform: "node" }, this);
		}),

		on.success(function(content) {
			console.log("writing application bundle: \n\n%s\n\n", content);
			fs.writeFile(this.nexePath = path.join(this.node.dir, "lib", "nexe.js"), content, "utf8", this);
		}),

		/**
		 * 4. monkeypatch the node entry
		 */

		on.success(function() {
			console.log("monkey patching node.js file");
			monkeyPatchNodejs(this.node, this);
		}),

		/**
		 * 5. bundle it all together
		 */

		on.success(function() {
			console.log("building node.js");
			this.node.make(this);
		}),

		/**
		 * 6. copy the executable
		 */

		on.success(function() {
			console.log("copying binary to output directory to %s", args.output);

			mkdirp(path.dirname(args.output), this);
		}),

		/**
		 */

		function() {
			ncp(this.node.releasePath, args.output, this);
		},

		/**
		 */

		next

	);
};

/**
 */

function downloadNode(version, temp, next) {

	var tmpPath = path.join(temp, "node-" + version + ".tar.gz"),
	srcDr       = tmpPath.replace(/\.tar.gz$/, "");

	try {

		mkdirp.sync(path.dirname(tmpPath));

	//an error will usually occur when the dir already exists.
	} catch(e) { }

	step(

		/**
		 * download
		 */

		function() {

			//zip exists?
			if(fs.existsSync(tmpPath) || fs.existsSync(srcDr)) return this();

			console.log("downloading node %s", version);

			var output = fs.createWriteStream(tmpPath, { "flags": "w+" }),
			req = request("http://nodejs.org/dist/node-" + version + ".tar.gz").pipe(output);

			output.on("close", this);
		},

		/**
		 * untar
		 */

		function() {

			//source dir exists?
			if(fs.existsSync(srcDr)) return this();

			console.log("unzipping node source");

			//TODO - use native zlib library for this
			exec(sprintf("tar -xf '%s'", tmpPath), { cwd: path.dirname(tmpPath) }, this);
		},

		/**
		 * cleanup the node.js file
		 */

		function() {
			fs.unlink(tmpfile, this);
		},

		/**
		 * return make script
		 */

		function() {
			next(null, {

				//the directory to the node.js file
				dir: srcDr,

				releasePath: path.join(srcDr, "out/Release/node"),

				//makes node.js
				make: function(next) {
					var configure = spawn('./configure', [], { cwd: srcDr });
					configure.stdout.on('data', function(data) {
						process.stdout.write(data.toString());
					});
					configure.stderr.on('data', function(data) {
						process.stderr.write(data.toString());
					});
					configure.on('close', function() {
						var make = spawn('make', [], { cwd: srcDr });
						make.stdout.on('data', function(data) {
							process.stdout.write(data.toString());
						});
						make.stderr.on('data', function(data) {
							process.stderr.write(data.toString());
						});
						make.on('close', next);
					});
				}
			});
		}
	);
}

/**
 */

function monkeyPatchNodejs(node, next) {

	var nodejsPath = path.join(node.dir, "src", "node.js"),
	nodegypPath    = path.join(node.dir, "node.gyp"),
	on = outcome.error(next);

	step(

		/**
		 * read the node.js file
		 */

		function() {
			fs.readFile(nodejsPath, "utf8", this);
		},

		/**
		 * inject nexe as _eval IF it hasn't already been injected
		 */

		on.success(function(content) {

			//nexe already injected?
			if(~content.indexOf('nexe')) return this();

			fs.writeFile(nodejsPath,
			content.replace(/\(function\(process\) \{/,'(function(process) {\n  process._eval = \'require("nexe");\';\n  process.argv.unshift("node");\n'),
			"utf8",
			this);
		}),

		/**
		 * next, find node.gyp and add nexe as a native lib file
		 */

		on.success(function() {
			fs.readFile(nodegypPath, "utf8", this);
		}),

		/**
		 * finally, monkeypatch node.gyp
		 */

		on.success(function(content) {

			//nexe already included as dep?
			if(~content.indexOf('lib/nexe.js')) return this();

			fs.writeFile(nodegypPath,
			content.replace("'lib/fs.js',", "'lib/fs.js', 'lib/nexe.js', "),
			"utf8",
			this);
		}),

		/**
		 */

		next
	);
}
<commit_msg>cleanup<commit_after>var step = require("step"),
outcome = require("outcome"),
request = require("request"),
fs = require("fs"),
mkdirp = require("mkdirp"),
path = require("path"),
child_process = require("child_process"),
exec = child_process.exec,
spawn = child_process.spawn,
sprintf = require("sprintf").sprintf,
ncp = require("ncp").ncp,
sardines = require("sardines");

/**
 */

exports.compile = function(args, next) {

	var on = outcome.error(next);

	args.input = require.resolve(args.input);

	step(

		/**
		 * 1. download node
		 */

		function() {
			downloadNode(args.runtime, args.temp, this);
		},

		/**
		 * 2. build the script into ONE file
		 */

		on.success(function(node) {
			console.log("making application bundle with %s", args.input);
			this.node = node;

			sardines({ entries: [args.input], platform: "node" }, this);
		}),

		on.success(function(content) {
			console.log("writing application bundle: \n\n%s\n\n", content);
			fs.writeFile(this.nexePath = path.join(this.node.dir, "lib", "nexe.js"), content, "utf8", this);
		}),

		/**
		 * 4. monkeypatch the node entry
		 */

		on.success(function() {
			console.log("monkey patching node.js file");
			monkeyPatchNodejs(this.node, this);
		}),

		/**
		 * 5. bundle it all together
		 */

		on.success(function() {
			console.log("building node.js");
			this.node.make(this);
		}),

		/**
		 * 6. copy the executable
		 */

		on.success(function() {
			console.log("copying binary to output directory to %s", args.output);

			mkdirp(path.dirname(args.output), this);
		}),

		/**
		 */

		function() {
			ncp(this.node.releasePath, args.output, this);
		},

		/**
		 */

		next

	);
};

/**
 */

function downloadNode(version, temp, next) {

	var tmpPath = path.join(temp, "node-" + version + ".tar.gz"),
	srcDr       = tmpPath.replace(/\.tar.gz$/, "");

	step(

		/**
		 * download
		 */

		function() {

			//zip exists?
			if(fs.existsSync(tmpPath) || fs.existsSync(srcDr)) return this();

			console.log("downloading node %s", version);

			var output = fs.createWriteStream(tmpPath, { "flags": "w+" }),
			req = request("http://nodejs.org/dist/node-" + version + ".tar.gz").pipe(output);

			output.on("close", this);
		},

		/**
		 * untar
		 */

		function() {

			//source dir exists?
			if(fs.existsSync(srcDr)) return this();

			try {
				mkdirp.sync(srcDr);
			} catch(e) {

			}

			//TODO - use native zlib library for this
			exec(sprintf("tar -xf '%s' -C '%s'", tmpPath, srcDr), { cwd: path.dirname(tmpPath) }, this);
		},

		/**
		 * cleanup the node.js file
		 */

		function() {
			fs.unlink(tmpfile, this);
		},

		/**
		 * return make script
		 */

		function() {

			console.log(srcDr)

			vDir = path.join(srcDr, fs.readdirSync(srcDr).filter(function(dir) {
				return !/^\./.test(dir);
			}).pop());

			next(null, {

				//the directory to the node.js file
				dir: vDir,

				releasePath: path.join(vDir, "out/Release/node"),

				//makes node.js
				make: function(next) {
					var configure = spawn('./configure', [], { cwd: vDir });
					configure.stdout.on('data', function(data) {
						process.stdout.write(data.toString());
					});
					configure.stderr.on('data', function(data) {
						process.stderr.write(data.toString());
					});
					configure.on('close', function() {
						var make = spawn('make', [], { cwd: vDir });
						make.stdout.on('data', function(data) {
							process.stdout.write(data.toString());
						});
						make.stderr.on('data', function(data) {
							process.stderr.write(data.toString());
						});
						make.on('close', next);
					});
				}
			});
		}
	);
}

/**
 */

function monkeyPatchNodejs(node, next) {

	var nodejsPath = path.join(node.dir, "src", "node.js"),
	nodegypPath    = path.join(node.dir, "node.gyp"),
	on = outcome.error(next);

	step(

		/**
		 * read the node.js file
		 */

		function() {
			fs.readFile(nodejsPath, "utf8", this);
		},

		/**
		 * inject nexe as _eval IF it hasn't already been injected
		 */

		on.success(function(content) {

			//nexe already injected?
			if(~content.indexOf('nexe')) return this();

			fs.writeFile(nodejsPath,
			content.replace(/\(function\(process\) \{/,'(function(process) {\n  process._eval = \'require("nexe");\';\n  process.argv.unshift("node");\n'),
			"utf8",
			this);
		}),

		/**
		 * next, find node.gyp and add nexe as a native lib file
		 */

		on.success(function() {
			fs.readFile(nodegypPath, "utf8", this);
		}),

		/**
		 * finally, monkeypatch node.gyp
		 */

		on.success(function(content) {

			//nexe already included as dep?
			if(~content.indexOf('lib/nexe.js')) return this();

			fs.writeFile(nodegypPath,
			content.replace("'lib/fs.js',", "'lib/fs.js', 'lib/nexe.js', "),
			"utf8",
			this);
		}),

		/**
		 */

		next
	);
}
<|endoftext|>


<commit_before>/**
 * New node file
 */
var libxmljs = require("libxmljs");
var msgq = [];

/**
 *
 * this is a sub process of Zenith server. Currently it accepts a message in
 * following format
 * { xml: string, xpath:string, nameSpace:{},regEx:string , checkRegEx:boolean,caseSense:boolean}
 * Ex.{ xml:"anyxmlstring", xpath:"//m0:request[1]/m0:symbol", nameSpace:{'m0':'http://services.samples'},checkRegEx:true, regEx:"IBM",caseSense:false}
 * And evaluates the regular expression on the element located by xpath
 * if it matches the expression returns object contains the result
 */

process.on('message', function(m) {
	        //
		var resp = {
			result : null,
			hasRegEx : false
		};
	    msgq.push(m);
	    var servMsg = msgq.shift();
		try{
			var doc = libxmljs.parseXml(servMsg.xml);
			var result;
			if(servMsg.nameSpace!=null){
				result = doc.get(servMsg.xpath,servMsg.nameSpace);
			}else{
				result = doc.get(servMsg.xpath);
			}
			var result = doc.get(servMsg.xpath,servMsg.nameSpace);
			if(result == null){
				//no value for the expath expression
				logger.debug('XMLXPathProcess', 'XML message does not contain result for'
						+ 'XPath exp : ' + servMsg.xpath);
				process.send(resp);
			}

			var regExp;

			if(servMsg.checkRegEx) {
				//code to check xml against regExp
				if(caseSensitive = false){
					regExp = new RegExp(servMsg.regEx,'i');
				}
				else{
					regExp = new RegExp(servMsg.regEx);
				}
				resp.hasRegEx =  regExp.test(result.text());
				logger.debug('XMLXPathProcess', 'RegExp evaluation result :' + resp.hasRegEx);
				process.send(resp);
			} else {
				//code to get the element value

				resp.result = result.text();
				logger.debug('XMLXPathProcess', 'Element value : ' +resp.result);
				process.send(resp);
			}

		}catch(err){
			process.send({ result: err });
		}

});
<commit_msg>edit comments<commit_after>/**
 *
 * this is a sub process of Zenith server. Currently it accepts a message in
 * following format
 * { xml: string, xpath:string, nameSpace:{},regEx:string , checkRegEx:boolean,caseSense:boolean}
 * Ex.{ xml:"anyxmlstring", xpath:"//m0:request[1]/m0:symbol", nameSpace:{'m0':'http://services.samples'},checkRegEx:true, regEx:"IBM",caseSense:false}
 * And evaluates the regular expression on the element located by xpath
 * if it matches the expression returns object contains the result
 */

var libxmljs = require("libxmljs");
var msgq = [];

process.on('message', function(m) {
	        //
		var resp = {
			result : null,
			hasRegEx : false
		};
	    msgq.push(m);
	    var servMsg = msgq.shift();
		try{
			var doc = libxmljs.parseXml(servMsg.xml);
			var result;
			if(servMsg.nameSpace!=null){
				result = doc.get(servMsg.xpath,servMsg.nameSpace);
			}else{
				result = doc.get(servMsg.xpath);
			}
			var result = doc.get(servMsg.xpath,servMsg.nameSpace);
			if(result == null){
				//no value for the expath expression
				logger.debug('XMLXPathProcess', 'XML message does not contain result for'
						+ 'XPath exp : ' + servMsg.xpath);
				process.send(resp);
			}

			var regExp;

			if(servMsg.checkRegEx) {
				//code to check xml against regExp
				if(caseSensitive = false){
					regExp = new RegExp(servMsg.regEx,'i');
				}
				else{
					regExp = new RegExp(servMsg.regEx);
				}
				resp.hasRegEx =  regExp.test(result.text());
				logger.debug('XMLXPathProcess', 'RegExp evaluation result :' + resp.hasRegEx);
				process.send(resp);
			} else {
				//code to get the element value

				resp.result = result.text();
				logger.debug('XMLXPathProcess', 'Element value : ' +resp.result);
				process.send(resp);
			}

		}catch(err){
			process.send({ result: err });
		}

});
<|endoftext|>


<commit_before>
var Nightmare =  require('nightmare');
var express = require('express');
var Promise = require('bluebird');
var _ = require('lodash');

module.exports = FontMetricsParser;

/**
 *
 * @param [options] {Object} Initial data
 * @returns {FontMetricsParser}
 * @constructor
 */
function FontMetricsParser (options) {

	if (!(this instanceof FontMetricsParser)) {
		return new FontMetricsParser(options);
	}

	options = _.isPlainObject(options) ? options : {};

	this.defaultConfiguration = {
		parser: {
			fonts: [],
			debug: false
		},
		express: {
			port: 3000
		},
		nightmare: {
			show: false,
			webPreferences: {
				experimentalCanvasFeatures: true
			}
		}
	};

	this.configuration = _.merge({}, this.defaultConfiguration, options);

	this.browser = null;
	this.canvasPageURL = 'http://localhost:' + this.configuration.express.port + '/';

}

FontMetricsParser.prototype.parse = function () {

	var self = this;

	self.createServer().then(function () {
		return self.createBrowser();
	}).then(function () {
		return self.parseFonts();
	});

};

/**
 * Create express server
 */
FontMetricsParser.prototype.createServer = function () {

	var self = this;

	console.log('createServer was called');

	return new Promise(function (resolve, reject) {

		if (self.expressApp instanceof express) {
			resolve();
		} else {
			self.expressApp = express();
			self.expressApp.use(express.static('pages'));
			self.expressApp.listen(self.configuration.express.port, function () {
				console.log('Express is running on port ' + self.configuration.express.port);
				resolve();
			});
		}

	});

};

/**
 * Create nightmare instance
 */
FontMetricsParser.prototype.createBrowser = function () {

	var self = this;

	console.log('createBrowser was called');

	return new Promise(function (resolve, reject) {

		if (self.browser instanceof Nightmare) {
			resolve();
		} else {
			self.browser = Nightmare(self.configuration.nightmare);
			resolve();
		}

	});

};

/**
 * Parse font by navigating via nightmare to html page served by express and running calculations
 */
FontMetricsParser.prototype.parseFonts = function () {

	var self = this;

	console.log('parseFonts was called.');

	return new Promise(function (resolve, reject) {
		/**
		 * @name self.browser
		 * @instanceof Nightmare
		 */
		self.browser
			.goto(self.canvasPageURL)
			.evaluate(function () {

				// TODO: inject font-face

				// TODO: calculate font-metrics

				return;

			})
			.then(function (result) {
				console.log(result, '!!!');
				// TODO: save results
			})
			// .evaluate(self.getMetricslo)
			// .then(function (result) {
			// 	self.saveResult(result);
			// })
			.catch(function (error) {
				console.error('Error:', error);
			});

	});

};

FontMetricsParser.prototype.injectFonts = function () {

	return document.querySelector('canvas').width;

};

FontMetricsParser.prototype.getMetrics = function () {

	return;

};

FontMetricsParser.prototype.saveResult = function (data) {

	console.log('save results', data);

};

function createParser () {

	var app = express();
	app.use(express.static('pages'));
	app.listen(portNumber, function () {
		console.log('Express is running on port ' + portNumber);

		var nightmare = Nightmare({
			webPreferences: {
				experimentalCanvasFeatures: true
			}
		});

	});

}

<commit_msg>Add method for writing parsed data into json file<commit_after>
var Nightmare =  require('nightmare');
var express = require('express');
var Promise = require('bluebird');
var _ = require('lodash');
var fs = require('fs');

/**
 * @name fs
 * @property writeFile
 * @property W_OK
 * @property accessSync
 */

module.exports = FontMetricsParser;

/**
 *
 * @param [options] {Object} Initial data
 * @returns {FontMetricsParser}
 * @constructor
 */
function FontMetricsParser (options) {

	if (!(this instanceof FontMetricsParser)) {
		return new FontMetricsParser(options);
	}

	options = _.isPlainObject(options) ? options : {};

	this.defaultConfiguration = {
		parser: {
			// css file containing required font-family names
			css: null,
			// font-family names
			fonts: [], // font-family names to create map for
			debug: true,
			output: './'
		},
		express: {
			port: 3000
		},
		nightmare: {
			show: false,
			webPreferences: {
				experimentalCanvasFeatures: true
			}
		}
	};

	this.configuration = _.merge({}, this.defaultConfiguration, options);

	this.browser = null;

	this.canvasPageURL = 'http://localhost:' + this.configuration.express.port + '/';

}

/**
 * Parse fonts
 */
FontMetricsParser.prototype.parse = function () {

	var self = this;

	self.validateConfiguration().then(function () {
		return self.createServer();
	}).then(function () {
		return self.createBrowser();
	}).then(function () {
		return self.parseFonts();
	}).catch(function (err) {
		console.log('Parse was rejected.');
		console.log(err);
	});

};

/**
 * Validate configuration.
 * Provide any additional checks to ensure configuration is valid for parsing.
 */
FontMetricsParser.prototype.validateConfiguration = function () {

	var self = this;

	return new Promise(function (resolve, reject) {

		var isValid = true;
		var reason = '';
		var config = self.configuration;
		var fonts = config.parser.fonts;
		var path = config.parser.output;

		// check fonts to be an array of strings
		if (!_.isArray(fonts) || !fonts.length || fonts.some(function (fontFamily) {return !_.isString(fontFamily)})) {
			isValid = false;
			reason = 'Fonts is not an array of strings.';
		}

		// output path should be a string
		if (!_.isString(path)) {
			isValid = false;
			reason = 'Output path is not a string';
		}

		// TODO: add fs.exists and fs.access validation

		isValid ? resolve() : reject(reason);

	});

};

/**
 * Create express server
 */
FontMetricsParser.prototype.createServer = function () {

	var self = this;

	return new Promise(function (resolve, reject) {

		if (self.expressApp instanceof express) {
			resolve();
		} else {
			self.expressApp = express();
			self.expressApp.use(express.static('pages'));
			self.expressApp.listen(self.configuration.express.port, function () {
				console.log('Express is running on port ' + self.configuration.express.port);
				resolve();
			});
		}

	});

};

/**
 * Create nightmare instance
 */
FontMetricsParser.prototype.createBrowser = function () {

	var self = this;

	console.log('createBrowser was called');

	return new Promise(function (resolve, reject) {

		if (self.browser instanceof Nightmare) {
			resolve();
		} else {
			self.browser = Nightmare(self.configuration.nightmare);
			resolve();
		}

	});

};

/**
 * Parse font by navigating via nightmare to html page served by express and running calculations
 */
FontMetricsParser.prototype.parseFonts = function () {

	var self = this;

	console.log('parseFonts was called.');

	return new Promise(function (resolve, reject) {
		/**
		 * @name self.browser
		 * @instanceof Nightmare
		 */
		self.browser
			.goto(self.canvasPageURL)
			.inject('css', self.configuration.parser.css)
			.evaluate(function (fonts) {

				var fontsMap = {
					__initialFonts: fonts.slice()
				};

				var canvas = document.getElementById('canvas');
				var ctx = canvas.getContext('2d');
				ctx.textBaseline = 'alphabetical';

				fonts.forEach(function (fontFamily) {
					ctx.font = '30px ' + fontFamily;
					var fontMetrics = ctx.measureText('Example');

					// TODO: find a way to merge properties from fontMetrics to new object
					// JSON, assign - doesn't work

					fontsMap[fontFamily] = {
						width: fontMetrics.width,
						actualBoundingBoxLeft: fontMetrics.actualBoundingBoxLeft,
						actualBoundingBoxRight: fontMetrics.actualBoundingBoxRight,
						fontBoundingBoxAscent: fontMetrics.fontBoundingBoxAscent,
						fontBoundingBoxDescent: fontMetrics.fontBoundingBoxDescent,
						actualBoundingBoxAscent: fontMetrics.actualBoundingBoxAscent,
						actualBoundingBoxDescent: fontMetrics.actualBoundingBoxDescent,
						emHeightAscent: fontMetrics.emHeightAscent,
						emHeightDescent: fontMetrics.emHeightDescent,
						hangingBaseline: fontMetrics.hangingBaseline,
						alphabeticBaseline: fontMetrics.alphabeticBaseline,
						ideographicBaseline: fontMetrics.ideographicBaseline
					}

				});

				return fontsMap;

			}, self.configuration.parser.fonts)
			.then(function (result) {
				self.saveResult(result);
			})
			.catch(function (error) {
				console.error('Error:', error);
			});

	});

};

FontMetricsParser.prototype.saveResult = function (data) {

	// TODO: add output path support

	fs.writeFile('fontsMap.json', JSON.stringify(data, null, 4), function (err) {
		if (err) {
			 throw new Error(err);
		}
		console.log('Done');
	});

};

<|endoftext|>


<commit_before>'use babel';
/* @flow */

import { CompositeDisposable } from 'atom';
import path from 'path';

import handleData from './message.js';
// import * as servers from './servers.js';

import type { LinterMessage } from './message';

type BufferType = {
  cachedText: string;
  getText(): string;
}

type TextEditorType = {
  getPath(): string;
  buffer: BufferType;
  isModified(): boolean;
}

type Linter = {
  grammarScopes: Array<string>;
  scope: 'file' | 'project';
  name?: string;
  lintOnFly: boolean;
  lint(TextEditor: TextEditorType): Array<LinterMessage> | Promise<Array<LinterMessage>>;
};

export default {
  config: {
    executablePath: {
      type: 'string',
      default: 'flow',
      description: 'Absolute path to the Flow executable on your system.',
    },
    enableAll: {
      type: 'boolean',
      default: false,
      description: 'Typecheck all files, not just @flow',
    },
  },

  activate(): void {
    require('atom-package-deps').install('linter-flow');

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe('linter-flow.executablePath', (pathToFlow) => {
      this.pathToFlow = pathToFlow;
    }));
    this.subscriptions.add(atom.config.observe('linter-flow.enableAll', (enableAll) => {
      this.enableAll = enableAll;
    }));
  },

  deactivate(): void {
    // servers.stop();
    this.subscriptions.dispose();
  },

  provideLinter(): Linter {
    const helpers = require('atom-linter');

    return {
      grammarScopes: [
        'source.js',
        'source.js.jsx',
        'source.babel',
        'source.js-semantic',
        'source.es6',
      ],
      scope: 'project',
      name: 'Flow',
      lintOnFly: true,
      lint: (TextEditor) => {
        const filePath = TextEditor.getPath();
        const fileText = TextEditor.buffer.cachedText;

        // Is flow enabled for current file ?
        if (fileText.indexOf('@flow') === -1 && !this.enableAll) {
          return [];
        }

        // Check if .flowconfig file is present
        const flowConfig = helpers.find(filePath, '.flowconfig');
        if (!flowConfig) {
          atom.notifications.addWarning('[Linter-Flow] Missing .flowconfig file.', {
            detail: 'To get started with Flow, run `flow init`.',
            dismissable: true,
          });
          return [];
        }

        let args;
        let options;

        // Use `check-contents` for unsaved files. and `status` for saved files.
        // if (TextEditor.isModified()) {
        //   args = ['check-contents', '--json', filePath];
        //   options = { cwd: path.dirname(filePath), stdin: fileText };
        // } else {
        args = ['status', '--json', filePath];
        options = { cwd: path.dirname(filePath) };
        // }

        // return servers.start(this.pathToFlow, flowConfig, this.enableAll).then(() =>
        return helpers
          .exec(this.pathToFlow, args, options)
          .then(JSON.parse)
          .then(handleData);
        // );
      },
    };
  },
};
<commit_msg>fix(servers): use check-contents not status<commit_after>'use babel';
/* @flow */

import { CompositeDisposable } from 'atom';
import path from 'path';

import handleData from './message.js';
// import * as servers from './servers.js';

import type { LinterMessage } from './message';

type BufferType = {
  cachedText: string;
  getText(): string;
}

type TextEditorType = {
  getPath(): string;
  buffer: BufferType;
  isModified(): boolean;
}

type Linter = {
  grammarScopes: Array<string>;
  scope: 'file' | 'project';
  name?: string;
  lintOnFly: boolean;
  lint(TextEditor: TextEditorType): Array<LinterMessage> | Promise<Array<LinterMessage>>;
};

export default {
  config: {
    executablePath: {
      type: 'string',
      default: 'flow',
      description: 'Absolute path to the Flow executable on your system.',
    },
    enableAll: {
      type: 'boolean',
      default: false,
      description: 'Typecheck all files, not just @flow',
    },
  },

  activate(): void {
    require('atom-package-deps').install('linter-flow');

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe('linter-flow.executablePath', (pathToFlow) => {
      this.pathToFlow = pathToFlow;
    }));
    this.subscriptions.add(atom.config.observe('linter-flow.enableAll', (enableAll) => {
      this.enableAll = enableAll;
    }));
  },

  deactivate(): void {
    // servers.stop();
    this.subscriptions.dispose();
  },

  provideLinter(): Linter {
    const helpers = require('atom-linter');

    return {
      grammarScopes: [
        'source.js',
        'source.js.jsx',
        'source.babel',
        'source.js-semantic',
        'source.es6',
      ],
      scope: 'project',
      name: 'Flow',
      lintOnFly: true,
      lint: (TextEditor) => {
        const filePath = TextEditor.getPath();
        const fileText = TextEditor.buffer.cachedText;

        // Is flow enabled for current file ?
        if (fileText.indexOf('@flow') === -1 && !this.enableAll) {
          return [];
        }

        // Check if .flowconfig file is present
        const flowConfig = helpers.find(filePath, '.flowconfig');
        if (!flowConfig) {
          atom.notifications.addWarning('[Linter-Flow] Missing .flowconfig file.', {
            detail: 'To get started with Flow, run `flow init`.',
            dismissable: true,
          });
          return [];
        }

        let args;
        let options;

        // Use `check-contents` for unsaved files. and `status` for saved files.
        // if (TextEditor.isModified()) {
        args = ['check-contents', '--json', filePath];
        options = { cwd: path.dirname(filePath), stdin: fileText };
        // } else {
        // args = ['status', '--json', filePath];
        // options = { cwd: path.dirname(filePath) };
        // }

        // return servers.start(this.pathToFlow, flowConfig, this.enableAll).then(() =>
        return helpers
          .exec(this.pathToFlow, args, options)
          .then(JSON.parse)
          .then(handleData);
        // );
      },
    };
  },
};
<|endoftext|>


<commit_before>var config = Bones.plugin.config;
var passport = require('passport');
var util = require('util');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

server = Bones.Server.extend({});
server.prototype.initialize = function(app) {
    var auth = passport.authenticate('mapbox', { failureRedirect: '/oauth/mapbox/fail' });
    var body = '<script type="text/javascript">parent.postMessage("done", "*");</script>';
    this.use(passport.initialize());
    this.get('/oauth/mapbox', auth);
    this.get('/oauth/mapbox/token', auth, function(req, res) {
        new models.Config().save({
            syncAccount: req.user.id,
            syncAccessToken: req.user.accessToken
        }, {
            success: function() { res.send(body); },
            error: function() { res.send(body); }
        });
    });
    this.get('/oauth/mapbox/fail', function(req, res) {
        new models.Config().save({
            syncAccount: '',
            syncAccessToken: ''
        }, {
            success: function() { res.send(body); },
            error: function() { res.send(body); }
        });
    });
    passport.use(new Strategy());
    passport.serializeUser(function(obj, done) { done(null, obj); });
    passport.deserializeUser(function(obj, done) { done(null, obj); });
};

// Add passport OAuth2 authorization.
function Strategy() {
    OAuth2Strategy.call(this, {
        authorizationURL: config.syncURL + '/oauth/authorize',
        tokenURL:         config.syncURL + '/oauth/access_token',
        clientID:         'tilemill',
        clientSecret:     'tilemill',
        callbackURL:      'http://0.0.0.0:' + config.port + '/oauth/mapbox/token'
    },
    function(accessToken, refreshToken, profile, callback) {
        profile.accessToken = accessToken;
        profile.refreshToken = refreshToken;
        return callback(null, profile);
    });
    this.name = 'mapbox';
}
util.inherits(Strategy, OAuth2Strategy);
Strategy.prototype.userProfile = function(accessToken, done) {
    this._oauth2.get(config.syncURL + '/oauth/user', accessToken, function (err, body) {
        if (err) { return done(err); }
        done(null, JSON.parse(body));
    });
};

<commit_msg>Workaround for poor error handling in upstream oauth modules.<commit_after>var config = Bones.plugin.config;
var passport = require('passport');
var util = require('util');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

server = Bones.Server.extend({});
server.prototype.initialize = function(app) {
    var auth = passport.authenticate('mapbox', {
        session: false,
        failureRedirect: '/oauth/mapbox/fail'
    });
    var body = '<script type="text/javascript">parent.postMessage("done", "*");</script>';
    this.use(passport.initialize());
    this.get('/oauth/mapbox', auth);
    this.get('/oauth/mapbox/token', auth, function(req, res) {
        // The user ID is *required* here. If it is not provided
        // (see error "handling" or lack thereof in Strategy#userProfile
        // below) we basically treat it as an error condition.
        new models.Config().save({
            syncAccount: req.user.id ? req.user.id : '',
            syncAccessToken: req.user.id ? req.user.accessToken : ''
        }, {
            success: function() { res.send(body); },
            error: function() { res.send(body); }
        });
    });
    this.get('/oauth/mapbox/fail', function(req, res) {
        new models.Config().save({
            syncAccount: '',
            syncAccessToken: ''
        }, {
            success: function() { res.send(body); },
            error: function() { res.send(body); }
        });
    });
    passport.use(new Strategy());
    passport.serializeUser(function(obj, done) { done(null, obj); });
    passport.deserializeUser(function(obj, done) { done(null, obj); });
};

// Add passport OAuth2 authorization.
function Strategy() {
    OAuth2Strategy.call(this, {
        authorizationURL: config.syncURL + '/oauth/authorize',
        tokenURL:         config.syncURL + '/oauth/access_token',
        clientID:         'tilemill',
        clientSecret:     'tilemill',
        callbackURL:      'http://0.0.0.0:' + config.port + '/oauth/mapbox/token'
    },
    function(accessToken, refreshToken, profile, callback) {
        profile.accessToken = accessToken;
        profile.refreshToken = refreshToken;
        return callback(null, profile);
    });
    this.name = 'mapbox';
}
util.inherits(Strategy, OAuth2Strategy);
Strategy.prototype.userProfile = function(accessToken, done) {
    this._oauth2.get(config.syncURL + '/oauth/user', accessToken, function (err, body) {
        // oauth2 lib seems to not handle errors in a way where
        // we can catch and handle them effectively. We attach them
        // to the profile object here for our own custom handling.
        if (err) {
            return done(null, { error:err });
        } else {
            return done(null, JSON.parse(body));
        }
    });
};

<|endoftext|>


<commit_before>var colors = require('colors/safe');

var parser;
var parsers = {
	'(': function() {
		this.parse = function(token) {
			if (token === ")") {
				return true;
			}
		};
	},

	'"': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === '"') {
				runtime.push(this.stack.join(' '));
				return true;
			} else {
				this.stack.push(token);
			}
		};
	},

	'[': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === "[") {
				throw "TOKEN [ INSIDE QUOTATION";
			} else if (token === "]") {
				runtime.push(this.stack);
				return true;
			} else {
				this.stack.push(token);
			}
		};
	},

	':': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === ":") {
				throw "TOKEN : INSIDE DEFINITION";
			} else if (token === ";") {
				if (this.stack.length === 0) {
					return true;
				}

				var name = this.stack.shift();

				if (runtime.lookup(name)) {
					throw "DUPLICATE WORD: " + name;
				}

				runtime.define(name, this.stack);
				return true;
			} else {
				this.stack.push(token);
			}
		};
	},

	'JS:': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === ";") {
				if (this.stack.length === 0) {
					return true;
				}

				var name = this.stack.shift();

				if (runtime.lookup(name)) {
					throw "DUPLICATE WORD: " + name;
				}

				eval('runtime.define("' + name + '", ' + this.stack.join(' ') + ')');

				return true;
			} else {
				this.stack.push(token);
			}
		};
	},
};

var execute = function(tokens) {
	var tokens = tokens || [];

	for (var i = 0; i < tokens.length; i++) {
		var token = tokens[i];

		if (parser) {
			try {
				var result = parser.parse(token);
				if (result) {
					parser = null;
				}
			} catch (e) {
				return e;
			}
		} else {
			var word = runtime.lookup(token);
			if (word) {
				if (typeof(word) === 'function') {
					var error = runtime.call(word);
					if (error) {
						return error;
					}
				} else {
					var error = runtime.exec(word);
					if (error) {
						return error;
					}
				}
			} else if (parsers[token]) {
				parser = new parsers[token];
			} else if (!isNaN(token)) {
				runtime.push(Number(token));
			} else {
				return "UNKNOWN TOKEN: " + token;
			}
		}
	}
};

var runtime = {
	stack: [],
	push: function(v1) {
		this.stack.push(v1);
	},
	pop: function(n) {
		return this.stack.splice(this.stack.length - n, n);
	},
	clear: function() {
		this.stack = [];
	},

	parsing: function() {
		return parser;
	},

	namespace: {},
	define: function(word, func) {
		this.namespace[word] = func;
	},
	lookup: function(word) {
		var obj = this.namespace[word];
		if (obj) return obj;

		var s = word.split('.')
		obj = global[s.shift()];
		while (obj && s.length) obj = obj[s.shift()];
		return obj;
	},
	call: function(word) {
		var argc = word.length
		var argv = this.pop(argc);
		if (argv.length == argc) {
			try {
				var ret = word.apply(word, argv);
				if (ret) {
					this.push(ret);
				}
			} catch (err) {
				return err;
			}
		} else {
			this.stack.push.apply(this.stack, argv);
			return "stack underflow";
		}
	},
	exec: function(quote) {
		var error = execute(quote);
		if (error) {
			console.log(colors.red(error));
		}
	},

	print: function(v) {
		if (v === null) {
			return "null";
		}

		if (v === undefined) {
			return "undefined";
		}

		switch (v.constructor) {
			case String:
				return '"' + v + '"';
			case Array:
				return "[" + v.join(' ') + "]";
			default:
				return v;
		}
	},
};

module.exports = runtime;
<commit_msg>Improve pretty printer<commit_after>var colors = require('colors/safe');

var parser;
var parsers = {
	'(': function() {
		this.parse = function(token) {
			if (token === ")") {
				return true;
			}
		};
	},

	'"': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === '"') {
				runtime.push(this.stack.join(' '));
				return true;
			} else {
				this.stack.push(token);
			}
		};
	},

	'[': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === "[") {
				throw "TOKEN [ INSIDE QUOTATION";
			} else if (token === "]") {
				runtime.push(this.stack);
				return true;
			} else {
				this.stack.push(token);
			}
		};
	},

	':': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === ":") {
				throw "TOKEN : INSIDE DEFINITION";
			} else if (token === ";") {
				if (this.stack.length === 0) {
					return true;
				}

				var name = this.stack.shift();

				if (runtime.lookup(name)) {
					throw "DUPLICATE WORD: " + name;
				}

				runtime.define(name, this.stack);
				return true;
			} else {
				this.stack.push(token);
			}
		};
	},

	'JS:': function() {
		this.stack = [];

		this.parse = function(token) {
			if (token === ";") {
				if (this.stack.length === 0) {
					return true;
				}

				var name = this.stack.shift();

				if (runtime.lookup(name)) {
					throw "DUPLICATE WORD: " + name;
				}

				eval('runtime.define("' + name + '", ' + this.stack.join(' ') + ')');

				return true;
			} else {
				this.stack.push(token);
			}
		};
	},
};

var execute = function(tokens) {
	var tokens = tokens || [];

	for (var i = 0; i < tokens.length; i++) {
		var token = tokens[i];

		if (parser) {
			try {
				var result = parser.parse(token);
				if (result) {
					parser = null;
				}
			} catch (e) {
				return e;
			}
		} else {
			var word = runtime.lookup(token);
			if (word) {
				if (typeof(word) === 'function') {
					var error = runtime.call(word);
					if (error) {
						return error;
					}
				} else {
					var error = runtime.exec(word);
					if (error) {
						return error;
					}
				}
			} else if (parsers[token]) {
				parser = new parsers[token];
			} else if (!isNaN(token)) {
				runtime.push(Number(token));
			} else {
				return "UNKNOWN TOKEN: " + token;
			}
		}
	}
};

var runtime = {
	stack: [],
	push: function(v1) {
		this.stack.push(v1);
	},
	pop: function(n) {
		return this.stack.splice(this.stack.length - n, n);
	},
	clear: function() {
		this.stack = [];
	},

	parsing: function() {
		return parser;
	},

	namespace: {},
	define: function(word, func) {
		this.namespace[word] = func;
	},
	lookup: function(word) {
		var obj = this.namespace[word];
		if (obj) return obj;

		var s = word.split('.')
		obj = global[s.shift()];
		while (obj && s.length) obj = obj[s.shift()];
		return obj;
	},
	call: function(word) {
		var argc = word.length
		var argv = this.pop(argc);
		if (argv.length == argc) {
			try {
				var ret = word.apply(word, argv);
				if (ret) {
					this.push(ret);
				}
			} catch (err) {
				return err;
			}
		} else {
			this.stack.push.apply(this.stack, argv);
			return "stack underflow";
		}
	},
	exec: function(quote) {
		var error = execute(quote);
		if (error) {
			console.log(colors.red(error));
		}
	},

	print: function(v) {
		switch (v.constructor) {
			case String:
				return '"' + v + '"';
			case Array:
				return "[" + v.join(' ') + "]";
			default:
				return String(v);
		}
	},
};

module.exports = runtime;
<|endoftext|>


<commit_before>var createJob = require('./createJob');

module.exports = function (sails) {
  return {
    jobs: {},

    defaults: {cron: {}},

    initialize: function (cb) {
      var config = sails.config.cron;
      var tasks = Object.keys(config);
      tasks.forEach(function (time) {
        this.jobs[time] = createJob({
          cronTime: time,
          onTick: config[time] instanceof Function ? config[time] : config[time].onTick,
          onComplete: config[time].onComplete,
          start: typeof config[time].start === 'boolean' ? config[time].start : true,
          timezone: config[time].timezone,
          context: config[time].context
        });
      }.bind(this));

      cb();
    }
  };
};
<commit_msg>Replace schedule as a key with named job<commit_after>var createJob = require('./createJob');

module.exports = function (sails) {
  return {
    jobs: {},

    defaults: {cron: {}},

    initialize: function (cb) {
      var config = sails.config.cron;
      var tasks = Object.keys(config);
      tasks.forEach(function (name) {
        this.jobs[name] = createJob({
          cronTime: config[name].schedule,
          onTick: config[name].onTick,
          onComplete: config[name].onComplete,
          start: typeof config[name].start === 'boolean' ? config[name].start : true,
          timezone: config[name].timezone,
          context: config[name].context
        });
      }.bind(this));

      cb();
    }
  };
};
<|endoftext|>


<commit_before>var WikiHandler = {
	blockLoc: {},
	blockLast: '',
	plugin: function(plugin) {
		//needs a little ajax magic
		if (plugin) {
			if (plugin.name) {
				var wikiPluginName = "wikiplugin_" + plugin.name.toLowerCase();
				if (window[wikiPluginName]) {
					var thisOutput = window[wikiPluginName](plugin.body);
					if (thisOutput) {
						//var newOutput = this.Parse(thisOutput);

						//return (newOutput ? newOutput : thisOutput);
					}
				}
			}
		}
		return (plugin.inline ? plugin.static : plugin.static + plugin.body + '{' + plugin.name + '}');
	},
	beginBlock: function (condition)
	{
		if (condition != this.blockLast)
			this.blockLoc[condition]++;

		this.blockLast = condition;

		return this.lexer.begin(condition);
	},
	newLine: function() {
		return '
';
	},
	bold: function (convent) {
		return "" + convent + "";
	},
	box: function (convent) {
		return "
" + convent + "
";
	},
	center: function (convent) {
		return "" + convent + "";
	},
	colortext: function (convent) {
		var text = convent.split(':');
		var color = text[0];
		var html = text[1];
		return "" + html + "";
	},
	italics: function (convent) {
		return "" + convent + "";
	},
	header: function (convent) {
		return "
" + convent + "
";
	},
	hr: function () {
		return "
";
	},
	link: function (convent) {
		var link = this.split(':', convent);
		var href = convent;

		if (this.match(/\|/, convent)) {
			href = link[0];
			convent = link[1];
		}
		return "" + convent + "";
	},
	smile: function (smile) { //this needs more tlc too
		return "";
	},
	strikethrough: function (convent) {
		return "" + convent + "";
	},
	tableParser: function (convent) {
		var tableContents = '';
		var rows = this.split('
', convent);
		for(var i = 0; i < this.size(rows); i++) {
			row = '';

			cells = this.split('|',  rows[i]);
			for(var j = 0; j < this.size(cells); j++) {
				row += this.table_td(cells[j]);
			}
			tableContents += this.table_tr(row);
		}
		return "
" + tableContents + "
";
	},
	table_tr: function (convent) {
		return "
" + convent + "
";
	},
	table_td: function (convent) {
		return "" + convent + "	";
	},
	titlebar: function (convent) {
		return "
" + convent + "
";
	},
	underscore: function (convent) {
		return "" + convent + "";
	},
	wikilink: function (convent) {
		var wikilink = this.split('|', convent);
		var href = convent;

		if (this.match('/\|/', convent)) {
			href = wikilink[0];
			convent = wikilink[1];
		}
		return "" + convent + "";
	},
	olist: function(convent) {
		return '

' + convent + '

';
	},
	ulist: function(convent) {
		return '

' + convent + '

';
	},
	html: function (convent) { //this needs some ajax tlc
		return convent;
	},
	formatContent: function (convent) {
		return convent.replace(/\n/g, '
');
	},
	substring: function(val, left, right) {
		return val.substring(left, val.length + right);
	},
	match: function(pattern, subject) {
		return subject.match(pattern);
	},
	replace: function(search, replace, subject) {
		return subject.replace(search, replace);
	},
	split: function (delimiter, string) {
		return string.split(delimiter);
	},
	join: function () {
		var result = '';
		for(var i = 0; i < arguments.length; i++) {
			if (arguments[i]) result += arguments[i];
		}
		return result;
	},
	size: function(array) {
		if (!array) array = [];
		return array.length;
	},
	pop: function(array) {
		if (!array) array = [];
		array.pop();
		return array;
	},
	push: function (array, val) {
		if (!array) array = [];
		array.push(val);
		return array;
	},
	shift: function(array) {
		if (!array) array = [];
		array.shift();
		return array;
	},
	stackPlugin: function (yytext, pluginStack) {
		var pluginName = this.match(/^\{([A-Z]+)/, yytext);
		var pluginArgs =  this.match(/[(].*?[)]/, yytext);

		return this.push(pluginStack, {
			name: pluginName[1],
			args: pluginArgs,
			body: '',
			inline: false,
			static: yytext
		});
	},
	inlinePlugin: function (yytext) {
		var pluginName = this.match(/^\{([a-z]+)/, yytext);
		var pluginArgs = this.match(/[ ].*?[}]|[/}]/, yytext);

		return {
			name: pluginName[1],
			args: pluginArgs,
			body: '',
			inline: true,
			static: yytext
		};
	},
	isPlugin: function() {
		if (!this.yy.pluginStack) this.yy.pluginStack = [];
		return (this.yy.pluginStack.length > 0);
	},
	preParse: function (val) {
		return '\n'  + val + '\n'; //here we will strip things like np and plugins, and parse them at the end and process
	},
	postParse: function (val) {
		return val; //here we will restore things like np, and plugins and parse them if needed
	},
	Parse: function(val, errors) {
		//try {
			if (this.inUse) {
				//var wiki = WikiFactory(WikiHandler);
				//return wiki.parse(val);
				return '';
			}

			this.inUse = true;
			val = this.preParse(val);
			val = this.parse(val);
			val = this.postParse(val);
			this.inUse = false;
			return val;
		/*} catch (e) {
			if (errors) {
				return e;
			}
		}*/
	},
	parseError: function() {
		return "";
	}
};

Wiki = WikiFactory();
Wiki.extend.parser(WikiHandler);<commit_msg>[FIX] Migrate to latest usage of 'factory' method<commit_after>var WikiHandler = {
	blockLoc: {},
	blockLast: '',
	plugin: function(plugin) {
		//needs a little ajax magic
		if (plugin) {
			if (plugin.name) {
				var wikiPluginName = "wikiplugin_" + plugin.name.toLowerCase();
				if (window[wikiPluginName]) {
					var thisOutput = window[wikiPluginName](plugin.body);
					if (thisOutput) {
						//var newOutput = this.Parse(thisOutput);

						//return (newOutput ? newOutput : thisOutput);
					}
				}
			}
		}
		return (plugin.inline ? plugin.static : plugin.static + plugin.body + '{' + plugin.name + '}');
	},
	beginBlock: function (condition)
	{
		if (condition != this.blockLast)
			this.blockLoc[condition]++;

		this.blockLast = condition;

		return this.lexer.begin(condition);
	},
	newLine: function() {
		return '
';
	},
	bold: function (convent) {
		return "" + convent + "";
	},
	box: function (convent) {
		return "
" + convent + "
";
	},
	center: function (convent) {
		return "" + convent + "";
	},
	colortext: function (convent) {
		var text = convent.split(':');
		var color = text[0];
		var html = text[1];
		return "" + html + "";
	},
	italics: function (convent) {
		return "" + convent + "";
	},
	header: function (convent) {
		return "
" + convent + "
";
	},
	hr: function () {
		return "
";
	},
	link: function (convent) {
		var link = this.split(':', convent);
		var href = convent;

		if (this.match(/\|/, convent)) {
			href = link[0];
			convent = link[1];
		}
		return "" + convent + "";
	},
	smile: function (smile) { //this needs more tlc too
		return "";
	},
	strikethrough: function (convent) {
		return "" + convent + "";
	},
	tableParser: function (convent) {
		var tableContents = '';
		var rows = this.split('
', convent);
		for(var i = 0; i < this.size(rows); i++) {
			row = '';

			cells = this.split('|',  rows[i]);
			for(var j = 0; j < this.size(cells); j++) {
				row += this.table_td(cells[j]);
			}
			tableContents += this.table_tr(row);
		}
		return "
" + tableContents + "
";
	},
	table_tr: function (convent) {
		return "
" + convent + "
";
	},
	table_td: function (convent) {
		return "" + convent + "	";
	},
	titlebar: function (convent) {
		return "
" + convent + "
";
	},
	underscore: function (convent) {
		return "" + convent + "";
	},
	wikilink: function (convent) {
		var wikilink = this.split('|', convent);
		var href = convent;

		if (this.match('/\|/', convent)) {
			href = wikilink[0];
			convent = wikilink[1];
		}
		return "" + convent + "";
	},
	olist: function(convent) {
		return '

' + convent + '

';
	},
	ulist: function(convent) {
		return '

' + convent + '

';
	},
	html: function (convent) { //this needs some ajax tlc
		return convent;
	},
	formatContent: function (convent) {
		return convent.replace(/\n/g, '
');
	},
	substring: function(val, left, right) {
		return val.substring(left, val.length + right);
	},
	match: function(pattern, subject) {
		return subject.match(pattern);
	},
	replace: function(search, replace, subject) {
		return subject.replace(search, replace);
	},
	split: function (delimiter, string) {
		return string.split(delimiter);
	},
	join: function () {
		var result = '';
		for(var i = 0; i < arguments.length; i++) {
			if (arguments[i]) result += arguments[i];
		}
		return result;
	},
	size: function(array) {
		if (!array) array = [];
		return array.length;
	},
	pop: function(array) {
		if (!array) array = [];
		array.pop();
		return array;
	},
	push: function (array, val) {
		if (!array) array = [];
		array.push(val);
		return array;
	},
	shift: function(array) {
		if (!array) array = [];
		array.shift();
		return array;
	},
	stackPlugin: function (yytext, pluginStack) {
		var pluginName = this.match(/^\{([A-Z]+)/, yytext);
		var pluginArgs =  this.match(/[(].*?[)]/, yytext);

		return this.push(pluginStack, {
			name: pluginName[1],
			args: pluginArgs,
			body: '',
			inline: false,
			static: yytext
		});
	},
	inlinePlugin: function (yytext) {
		var pluginName = this.match(/^\{([a-z]+)/, yytext);
		var pluginArgs = this.match(/[ ].*?[}]|[/}]/, yytext);

		return {
			name: pluginName[1],
			args: pluginArgs,
			body: '',
			inline: true,
			static: yytext
		};
	},
	isPlugin: function() {
		if (!this.yy.pluginStack) this.yy.pluginStack = [];
		return (this.yy.pluginStack.length > 0);
	},
	preParse: function (val) {
		return '\n'  + val + '\n'; //here we will strip things like np and plugins, and parse them at the end and process
	},
	postParse: function (val) {
		return val; //here we will restore things like np, and plugins and parse them if needed
	},
	Parse: function(val, errors) {
		//try {
			if (this.inUse) {
				var wiki = new Wiki.Parser();
				wiki.extend.parser(WikiHanlder);
				wiki.inUser = false;
				return wiki.parse(val);
			}

			this.inUse = true;
			val = this.preParse(val);
			val = this.parse(val);
			val = this.postParse(val);
			this.inUse = false;
			return val;
		/*} catch (e) {
			if (errors) {
				return e;
			}
		}*/
	},
	parseError: function() {
		return "";
	}
};

Wiki.extend.parser(WikiHandler);<|endoftext|>


<commit_before>'use strict';

var XmlUtils = require('../utils/xml-utils');

/**
 * Context with helper methods for load/save
 * @param {Kdbx} opts.kdbx - kdbx file
 * @param {boolean} [opts.exportXml=false] - whether we are exporting as xml
 * @constructor
 */
var KdbxContext = function(opts) {
    this.kdbx = opts.kdbx;
    this.exportXml = opts.exportXml || false;
};

/**
 * Sets XML date, respecting date saving settings
 * @param {Note} node
 * @param {Date} dt
 */
KdbxContext.prototype.setXmlDate = function(node, dt) {
    var isBinary = this.kdbx.header.versionMajor >= 4 && !this.exportXml;
    XmlUtils.setDate(node, dt, isBinary);
};

module.exports = KdbxContext;
<commit_msg>fix typo<commit_after>'use strict';

var XmlUtils = require('../utils/xml-utils');

/**
 * Context with helper methods for load/save
 * @param {Kdbx} opts.kdbx - kdbx file
 * @param {boolean} [opts.exportXml=false] - whether we are exporting as xml
 * @constructor
 */
var KdbxContext = function(opts) {
    this.kdbx = opts.kdbx;
    this.exportXml = opts.exportXml || false;
};

/**
 * Sets XML date, respecting date saving settings
 * @param {Node} node
 * @param {Date} dt
 */
KdbxContext.prototype.setXmlDate = function(node, dt) {
    var isBinary = this.kdbx.header.versionMajor >= 4 && !this.exportXml;
    XmlUtils.setDate(node, dt, isBinary);
};

module.exports = KdbxContext;
<|endoftext|>


<commit_before>'use strict'

var request = require('request')
var assert = require('assert')
var url = require('url')
var extend = require('util')._extend

module.exports = Client

function Client(opts) {
  if (!(this instanceof Client))
    return new Client(opts)

  assert(opts, 'opts is required')
  assert(opts.host, 'opts.host is required')

  this.opts = opts
  var tags = opts.tags || {}
  this.tags = typeof tags === 'object'
    ? tags
    : null

  var parsed = url.parse(opts.host)
  this.host = parsed.protocol + '//' + parsed.host

  this.db = opts.db
}

Client.prototype.setDb = function setDb(db) {
  if (typeof db !== 'string')
    throw new TypeError('db must be a string')

  this.db = db
}

Client.prototype.createDb = function createDb(name, cb) {
  if (!name)
    return cb && cb(new Error('name is required'))

  var opts = {
    uri: this.host + '/query'
  , qs: {
      q: 'CREATE DATABASE ' + name
    }
  , json: true
  }

  request.get(opts, function(err, res, body) {
    if (err) return cb && cb(err)
    var code = res.statusCode
    if (code !== 200) {
      var err = new Error('Received non-200 status code')
      err.code = code
      err.body = body
      return cb && cb(err)
    }

    if (body && body.results) {
      var results = body.results
      if (results.length === 1) {
        var r = results[0]
        if (r.error) {
          return cb && cb(new Error(r.error))
        }
      }
    }

    cb && cb()
  })
}

// write raw data
Client.prototype.write = function write(data, cb) {
  if (typeof data !== 'string' && !Buffer.isBuffer(data))
    return cb && cb(new TypeError('data must be a string or buffer'))

  var body = new Buffer(data)
  var opts = {
    uri: this.host + '/write'
  , body: body
  , qs: {
      db: this.db
    }
  }

  request.post(opts, function(err, res, body) {
    if (err) return cb && cb(err)
    var code = res.statusCode
    if (code === 204) {
      // success
      return cb && cb()
    } else if (code === 200) {
      var err = new Error('request understood, but not written')
      err.body = body
      err.code = code
      return cb && cb(err)
    } else {
      var err = new Error('request failed')
      err.body = body
      err.code = code
      return cb && cb(err)
    }
  })
}

Client.prototype.writeFloat = function writeFloat(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = 'value=' + opts.val
  var str = escape(meas)

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype.writeInt = function writeInt(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = 'value=' + opts.val + 'i'

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype.writeBool = function writeBool(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = opts.val
  var key = opts.key || 'value'
  if (typeof val !== 'string') {
    val = key + '=' + String(val)
  }

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype.writeString = function writeString(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = opts.val
  var key = opts.key || 'value'
  val = key + '=' + val

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype._write = function(name, val, tags, ts, cb) {
  var str = escape(name)
  var tags_ = extend({}, tags)
  extend(tags, tags_)
  if (tags) {
    str += objectToTags(tags)
  }

  str += ' ' + val

  if (ts) {
    str += ' ' + ts
  }

  this.write(str, cb)
}

function objectToTags(obj) {
  var keys = Object.keys(obj)
  var len = keys.length
  if (!len) return ''
  var str = ''
  for (var i = 0; i < len; i++) {
    str += keys[i] + '=' + escape(obj[keys[i]])
  }
  if (str) str = ',' + str
  return str
}

function escape(str) {
  if (str) {
    if (typeof str === 'string') {
      str = str.replace(/\s/g, '\\ ')
      str = str.replace(/\"/g, '\\"')
    }
  }

  return str
}

function cbCheck(opts, cb) {
  if (!opts || typeof opts !== 'object') {
    cb(new TypeError('opts must be an object'))
    return false
  }

  if (!opts.name) {
    cb(new Error('opts.name is required'))
    return false
  }

  if (!opts.val) {
    cb(new Error('opts.val is required'))
    return false
  }

  return true
}
<commit_msg>lib: correctly serialize value in writeBool<commit_after>'use strict'

var request = require('request')
var assert = require('assert')
var url = require('url')
var extend = require('util')._extend

module.exports = Client

function Client(opts) {
  if (!(this instanceof Client))
    return new Client(opts)

  assert(opts, 'opts is required')
  assert(opts.host, 'opts.host is required')

  this.opts = opts
  var tags = opts.tags || {}
  this.tags = typeof tags === 'object'
    ? tags
    : null

  var parsed = url.parse(opts.host)
  this.host = parsed.protocol + '//' + parsed.host

  this.db = opts.db
}

Client.prototype.setDb = function setDb(db) {
  if (typeof db !== 'string')
    throw new TypeError('db must be a string')

  this.db = db
}

Client.prototype.createDb = function createDb(name, cb) {
  if (!name)
    return cb && cb(new Error('name is required'))

  var opts = {
    uri: this.host + '/query'
  , qs: {
      q: 'CREATE DATABASE ' + name
    }
  , json: true
  }

  request.get(opts, function(err, res, body) {
    if (err) return cb && cb(err)
    var code = res.statusCode
    if (code !== 200) {
      var err = new Error('Received non-200 status code')
      err.code = code
      err.body = body
      return cb && cb(err)
    }

    if (body && body.results) {
      var results = body.results
      if (results.length === 1) {
        var r = results[0]
        if (r.error) {
          return cb && cb(new Error(r.error))
        }
      }
    }

    cb && cb()
  })
}

// write raw data
Client.prototype.write = function write(data, cb) {
  if (typeof data !== 'string' && !Buffer.isBuffer(data))
    return cb && cb(new TypeError('data must be a string or buffer'))

  var body = new Buffer(data)
  var opts = {
    uri: this.host + '/write'
  , body: body
  , qs: {
      db: this.db
    }
  }

  request.post(opts, function(err, res, body) {
    if (err) return cb && cb(err)
    var code = res.statusCode
    if (code === 204) {
      // success
      return cb && cb()
    } else if (code === 200) {
      var err = new Error('request understood, but not written')
      err.body = body
      err.code = code
      return cb && cb(err)
    } else {
      var err = new Error('request failed')
      err.body = body
      err.code = code
      return cb && cb(err)
    }
  })
}

Client.prototype.writeFloat = function writeFloat(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = 'value=' + opts.val
  var str = escape(meas)

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype.writeInt = function writeInt(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = 'value=' + opts.val + 'i'

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype.writeBool = function writeBool(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = opts.val
  var key = opts.key || 'value'
  if (typeof val !== 'string') {
    val = String(val)
  }

  val = key + '=' + val

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype.writeString = function writeString(opts, cb) {
  if (!cbCheck(opts, cb))
    return

  var meas = opts.name
  var tags = opts.tags || {}
  var val = opts.val
  var key = opts.key || 'value'
  val = key + '=' + val

  this._write(meas, val, tags, opts.ts, cb)
}

Client.prototype._write = function(name, val, tags, ts, cb) {
  var str = escape(name)
  var tags_ = extend({}, tags)
  extend(tags, tags_)
  if (tags) {
    str += objectToTags(tags)
  }

  str += ' ' + val

  if (ts) {
    str += ' ' + ts
  }

  this.write(str, cb)
}

function objectToTags(obj) {
  var keys = Object.keys(obj)
  var len = keys.length
  if (!len) return ''
  var str = ''
  for (var i = 0; i < len; i++) {
    str += keys[i] + '=' + escape(obj[keys[i]])
  }
  if (str) str = ',' + str
  return str
}

function escape(str) {
  if (str) {
    if (typeof str === 'string') {
      str = str.replace(/\s/g, '\\ ')
      str = str.replace(/\"/g, '\\"')
    }
  }

  return str
}

function cbCheck(opts, cb) {
  if (!opts || typeof opts !== 'object') {
    cb(new TypeError('opts must be an object'))
    return false
  }

  if (!opts.name) {
    cb(new Error('opts.name is required'))
    return false
  }

  if (!opts.val) {
    cb(new Error('opts.val is required'))
    return false
  }

  return true
}
<|endoftext|>


<commit_before>
var async = require("async");
var _ = require("underscore");
var common = require("../utils/common");
var cacheMap = null; //global cache
var logger = null; // global logger

exports.init = function(conf){
  logger = conf.getLogger();
  logger.debug("initialized formatter");
  cacheMap = conf.getCacheMap();
  logger.debug("formatter initailized");
}

exports.format = function(req,cb){
    if(!req) cb(new Error("error in formatter.js input to format method is null"));
    var header={};
    var display = null;
    var res = req.results["main"];

    //get Header and maps key as an attribute to itself
    if(typeof req.display === "function"){
      header=req.header;
    }
    else{
      display=_.map(req.display,function(val,key){
        header[key]=val.header;
        val.name=key;
        return val;
      });
    }

    if(req.display){
      if(typeof req.display === "object"){ //declarative case
        logger.debug("inside declarative case");
        processDisplay(display,header,res,req,update,cb);
      }else if(typeof req.display === "function"){ // imperative case
        processDisplay(display,header,res,req,rowProcessorWrapper,cb);
      }else{
        cb(new Error("Invalid display declaration, Check docs"));
      }
    }else{ // No display specified shoot out query raw results
      cb(null,constructOutput(req.results.count,res,header));
    }

 };

function rowProcessorWrapper(display,req,row,cacheMap,cb){
  var joins = req.joins;
  var joinRows={};
  var joinFlagMap={};
  for(var j in joins){
    joinRows[j] = req.results[j];
    joinFlagMap[j]= getJoinFlagFunc(joins[j].on); //wrapper over common.getJoinFlag
  }
  req.display(req.params,row,joinRows,joinFlagMap,cacheMap,cb); // display func needs row, joinRows and JoinFlagMap
}

function getJoinFlagFunc(flds){
  return function(row){
    return common.getJoinFlag(row,flds,"^")
  }
}

function processDisplay(display,header,res,req,processRow,callback){
  async.map(res,function(row,cb){
    process.nextTick(function(){
      logger.debug("update call",row);
      processRow(display,req,row,cacheMap,cb);
    });
  },
  function (err,data){
    if(err) callback(err);
    else{
      callback(null,constructOutput(req.results.count,data,header));
    }
  });
}

function constructOutput(count,res,header){
  var total = (count.length > 0) ? count.pop().total : 0;
  return {
    "data" : res,
    "header": header,
    "total" : total
  };

}

function getJoinRow(joinMap,row,joinInfo){
  var joinFlag = common.getJoinFlag(row,joinInfo.on,"^");
  return joinMap[joinFlag];
}

//TODO modify inner join logic
function update(display,req,row,cacheMap,cb){
  logger.debug("update call");
  async.map(display, function(dp,callback){
    try{
      var joinMap = null,joinRow = null, j = null;
      var returnObj ={"name": dp.name};
      if(!dp.format){ // no format case
        if(dp.join){
          joinMap = req.results[dp.join];
          j = req.joins[dp.join];
          if(joinMap){
            joinRow = getJoinRow(joinMap,row,j);
            var joinVal = joinRow[dp.key];
            //TODO add inner and outer join condition here
            returnObj.val = joinVal;
            logger.debug("first cb",dp);
            callback(null,returnObj);
          }else{
            logger.debug("second cb",dp);
            callback(new Error("join "+dp.join+" is not defined in the json file"));
          }
        }else{
          returnObj.val = row[dp.key];
            logger.debug("thrid cb",dp);
          callback(null,returnObj);
        }
      }
      else{ // format case
        if(dp.join){
          joinMap = req.results[dp.join];
          j = req.joins[dp.join];
          if(j && joinMap){
            joinRow = getJoinRow(joinMap,row,j);
          }else{
            logger.debug("fourth cb",dp);
            callback(new Error("join "+dp.join+" is not defined in the json file"));
            return;
          }
        }
        process.nextTick(function(){
            var val = (dp.key) ? ((joinRow) ? joinRow[dp.key] : row[dp.key]) : null;
            dp.format(row,req.results,val,dp.key,cacheMap,function(output){
              returnObj.val = output;
            logger.debug("fifth cb",dp);
              callback(null,returnObj);
            });
        });
      }
    }catch(err){
            logger.debug("sixth cb");
      callback(err);
    }
  },function(err,output){

    logger.debug("output call");
      if(err) cb(err);
      else{
        var obj = {};
        var dicardFlag=false;
        _.map(output,function(o){
          var buff = o.val;
          //discardFlag = (buff === undefined) ;
          obj[o.name] = (o.val !== undefined) ? o.val : null;
        });
        //if(discardFlag) cb();
        //else            cb(null,obj);
        cb(null,obj);
      }
  });

}
<commit_msg>sending req instead req.results to format functions<commit_after>
var async = require("async");
var _ = require("underscore");
var common = require("../utils/common");
var cacheMap = null; //global cache
var logger = null; // global logger

exports.init = function(conf){
  logger = conf.getLogger();
  logger.debug("initialized formatter");
  cacheMap = conf.getCacheMap();
  logger.debug("formatter initailized");
}

exports.format = function(req,cb){
    if(!req) cb(new Error("error in formatter.js input to format method is null"));
    var header={};
    var display = null;
    var res = req.results["main"];

    //get Header and maps key as an attribute to itself
    if(typeof req.display === "function"){
      header=req.header;
    }
    else{
      display=_.map(req.display,function(val,key){
        header[key]=val.header;
        val.name=key;
        return val;
      });
    }

    if(req.display){
      if(typeof req.display === "object"){ //declarative case
        logger.debug("inside declarative case");
        processDisplay(display,header,res,req,update,cb);
      }else if(typeof req.display === "function"){ // imperative case
        processDisplay(display,header,res,req,rowProcessorWrapper,cb);
      }else{
        cb(new Error("Invalid display declaration, Check docs"));
      }
    }else{ // No display specified shoot out query raw results
      cb(null,constructOutput(req.results.count,res,header));
    }

 };

function rowProcessorWrapper(display,req,row,cacheMap,cb){
  var joins = req.joins;
  var joinRows={};
  var joinFlagMap={};
  for(var j in joins){
    joinRows[j] = req.results[j];
    joinFlagMap[j]= getJoinFlagFunc(joins[j].on); //wrapper over common.getJoinFlag
  }
  req.display(req.params,row,joinRows,joinFlagMap,cacheMap,cb); // display func needs row, joinRows and JoinFlagMap
}

function getJoinFlagFunc(flds){
  return function(row){
    return common.getJoinFlag(row,flds,"^")
  }
}

function processDisplay(display,header,res,req,processRow,callback){
  async.map(res,function(row,cb){
    process.nextTick(function(){
      logger.debug("update call",row);
      processRow(display,req,row,cacheMap,cb);
    });
  },
  function (err,data){
    if(err) callback(err);
    else{
      callback(null,constructOutput(req.results.count,data,header));
    }
  });
}

function constructOutput(count,res,header){
  var total = (count.length > 0) ? count.pop().total : 0;
  return {
    "data" : res,
    "header": header,
    "total" : total
  };

}

function getJoinRow(joinMap,row,joinInfo){
  var joinFlag = common.getJoinFlag(row,joinInfo.on,"^");
  return joinMap[joinFlag];
}

//TODO modify inner join logic
function update(display,req,row,cacheMap,cb){
  logger.debug("update call");
  async.map(display, function(dp,callback){
    try{
      var joinMap = null,joinRow = null, j = null;
      var returnObj ={"name": dp.name};
      if(!dp.format){ // no format case
        if(dp.join){
          joinMap = req.results[dp.join];
          j = req.joins[dp.join];
          if(joinMap){
            joinRow = getJoinRow(joinMap,row,j);
            var joinVal = joinRow[dp.key];
            //TODO add inner and outer join condition here
            returnObj.val = joinVal;
            logger.debug("first cb",dp);
            callback(null,returnObj);
          }else{
            logger.debug("second cb",dp);
            callback(new Error("join "+dp.join+" is not defined in the json file"));
          }
        }else{
          returnObj.val = row[dp.key];
            logger.debug("thrid cb",dp);
          callback(null,returnObj);
        }
      }
      else{ // format case
        if(dp.join){
          joinMap = req.results[dp.join];
          j = req.joins[dp.join];
          if(j && joinMap){
            joinRow = getJoinRow(joinMap,row,j);
          }else{
            logger.debug("fourth cb",dp);
            callback(new Error("join "+dp.join+" is not defined in the json file"));
            return;
          }
        }
        process.nextTick(function(){
            var val = (dp.key) ? ((joinRow) ? joinRow[dp.key] : row[dp.key]) : null;
            dp.format(row,req,val,dp.key,cacheMap,function(output){
              returnObj.val = output;
            logger.debug("fifth cb",dp);
              callback(null,returnObj);
            });
        });
      }
    }catch(err){
            logger.debug("sixth cb");
      callback(err);
    }
  },function(err,output){

    logger.debug("output call");
      if(err) cb(err);
      else{
        var obj = {};
        var dicardFlag=false;
        _.map(output,function(o){
          var buff = o.val;
          //discardFlag = (buff === undefined) ;
          obj[o.name] = (o.val !== undefined) ? o.val : null;
        });
        //if(discardFlag) cb();
        //else            cb(null,obj);
        cb(null,obj);
      }
  });

}
<|endoftext|>