<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require('fs');
var colors = require("colors");
var UserAgent = require('useragent');

/**
 *
 * @param reportObj includes all information about testSessions, wsSessions and the test report itself
 * @constructor
 */
function ReportManager(reportObj) {
    var stats;
    try {
        if (reportObj.arrTestSessions) {
            this.testSessions = reportObj.arrTestSessions;
        } else {
            this.testSessions = [];
        }

        if (reportObj.arrWDSessions) {
            this.wdSessions = reportObj.arrWDSessions;
        } else {
            this.wdSessions = [];
        }
        this.reportObj = reportObj;
        if (reportObj.reportFolder) {
            stats = fs.lstatSync(reportObj.reportFolder);
            if (stats.isDirectory()) {
                this.reportFolder = reportObj.reportFolder;
            }
        }
    } catch (ex) {
        //console.log(ex);
    }
}

ReportManager.prototype.showReportOnConsole = function (result, verbose) {

//    console.log("Result: " + JSON.stringify(result));
//    console.log("Verbose " + verbose);

    var lastSuite, suite, k, k1, test, msg, m, browser,
        log = console.log;

    log("");
    browser = result.ua;
    if (result.failed) {
        log("Failed ".red +  result.name.blue + " on"  + browser);
    } else {
        log("Passed ".green + result.name.blue + " on"  + browser);
    }
    log((result.passed + " Passed").green + ", " + (result.failed + " Failed ").red + ", " + (result.ignored + " skipped ").grey);
    if (result.failed) {
        for (k in result) {
            suite = result[k];
            if ("object" === typeof suite) {
                if (suite.failed) {
                    for (k1 in suite) {
                        test = suite[k1];
                        if ("object" === typeof test) {
                            if ("fail" === test.result) {
                                if (!lastSuite || lastSuite !== suite.name) {
                                    log(" in " +  suite.name.bold);
                                    lastSuite = suite.name;
                                }
                                msg = test.message.split('\n');
                                log(" " +  test.name.bold.red + ":" +  msg[0]);
                                for (m = 1; m < msg.length; m = m + 1) {
                                    log(" " + msg[m]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    log("");
};

ReportManager.prototype.writeReports = function () {

    var i, j, k, strJunitReport, strReport, rep, results, testJson, yuiUserAgent, yuiSuiteName, browser, descTestName, sessionId, yuiTestCaseName, timePerTest,
        className, testName, totalTimeTaken, errorCount, testSuiteName, arrReport, xmlReportName, jsonReportName, errorRep,
        self = this,
        wdSessions = self.wdSessions,
        testSessions = self.testSessions,
        passCount = 0,
        failCount = 0,
        skipCount = 0,
        timeCount = 0,
        totalCount = 0,
        jsonReport = {},
        log = console.log;
        resultPresent = false;
        errorCount = 0;

    function writeFile(fileName, data) {

        if (self.reportFolder) {
            fileName = self.reportFolder  + fileName;
        }
        fs.writeFileSync(fileName, data, 'utf8');
        log(("Report Created: " + fileName).inverse);
    }

    function addProperty(name, val) {
        if (val) {
            strReport += "<property name='" + name + "' value='" + val + "' />";
        }
    }
    function addTest(time, className, name, failureMessage, log) {
        strReport += "<testcase time='" + (time / 1000).toFixed(2) + "' classname='" + className  + "' name='" + name + "'";
        if (failureMessage) {
            strReport += "><failure><![CDATA[" + failureMessage + "]]></failure>" + log + "</testcase>";
        } else {
            strReport += "/>";
        }
    }

    function parseYUIResults(testJson, dtName) {
        var l, m;

        yuiUserAgent = testJson.ua;
        yuiSuiteName = testJson.name;
        browser = UserAgent.parse(yuiUserAgent).toAgent();
        if (browser === "Other 0.0.0") {
            browser = "NodeJS";
        }
        descTestName = dtName;
        sessionId = testJson.sessionId;
        for (l in testJson) {
            if (testJson[l]) {
                if (testJson[l].type === "testcase") {
                    yuiTestCaseName = testJson[l].name;
                    timePerTest = testJson[l].duration / testJson[l].total;
                    passCount += testJson[l].passed;
                    failCount += testJson[l].failed;
                    skipCount += testJson[l].ignored;
                    timeCount += testJson[l].duration;
                    totalCount += testJson[l].total;
                    for (m in testJson[l]) {
                        if (testJson[l][m].type === "test") {
                            className = browser + "." + descTestName;
                            testName = yuiSuiteName + "::" + yuiTestCaseName + "::" + testJson[l][m].name;
                            if (testJson[l][m].result === "pass") {
                                addTest(timePerTest, className, testName);
                            } else {
                                addTest(timePerTest, className, testName, testJson[l][m].message);
                            }
                        }
                    }
                }
            }
        }
    }
    strReport = "<properties>";
    addProperty("descriptor", this.reportObj.descriptor);
    addProperty("parallel", this.reportObj.parallel);
    addProperty("driver", this.reportObj.driver);
    addProperty("browser", this.reportObj.browser);
    addProperty("reuseSession", this.reportObj.reuseSession);
    addProperty("activeSeleniumSessionCount", wdSessions.length);
    addProperty("seleniumSessionIds", wdSessions.join());
    addProperty("group", this.reportObj.group);
    addProperty("testName", this.reportObj.testName);
    addProperty("reportFolder", this.reportObj.reportFolder);
    strReport += "</properties>";

    for (i = 0; i < testSessions.length; i = i + 1) {
        rep = testSessions[i].driver.getReports();

        if (rep.scenario) {
            arrReport = rep.scenario;
        } else {
            arrReport = rep.results;
        }

        resultPresent = false;

        for (j = 0; j < arrReport.length; j = j + 1) {
            if (rep.scenario) {
                results = arrReport[j].results;
                for (k = 0; k < results.length; k = k + 1) {
                    testJson =  results[k];
                    if(testJson.type === "report") {
                        resultPresent = true;
                        parseYUIResults(testJson, testSessions[i].driver.testName);
                    }
                }

            } else {
                testJson = arrReport[j];
                if(testJson.type === "report") {
                    resultPresent = true;
                    parseYUIResults(testJson, testSessions[i].driver.testName);
                }
            }
        }

        if(!resultPresent) {
            errorCount = errorCount + 1;
           var errorRep = arrReport[arrReport.length-1];

           if(errorRep.results) {
               //console.log("Error :" + errorRep.results[0].error);
               addTest(0, "Error." +  testSessions[i].driver.testName,"Error" , errorRep.results[0].error);

           } else if (errorRep.error) {
              // console.log("Error : " +errorRep.error)
               addTest(0, "Error." +  testSessions[i].driver.testName,"Error" , errorRep.error);
           } else{
               console.log("Error : UNKOWN");
           }

            console.log("Test Session dint have any report");
        }
    }
    log();
    log("Test Report Summary".bold.magenta);
    log();
    log(("Total Number of Executed Tests: " + (totalCount + errorCount) ).blue);
    log(("Total Number of Passed Tests: " + passCount).green);
    log(("Total Number of Failed Tests: " + ( errorCount + failCount) ).red);
    log(("Total Number of Skipped Tests: " + skipCount).cyan);
    log();
    log(("Total Test Execution Time Inside Browser: " + (timeCount / 1000).toFixed(2) + " seconds").green.bold);
    totalTimeTaken = Date.now() - global.startTime;
    log(("Total Test Execution Time:" + (totalTimeTaken / 1000).toFixed(2) + " seconds").green.bold);
    log();

    errorCount = totalCount - passCount - failCount - skipCount;

    testSuiteName = "";
    if (this.reportObj.testSuiteName) {
        testSuiteName = this.reportObj.testSuiteName;
    } else {
        testSuiteName = "TestSuite";
    }

    //writing xml file
    strJunitReport = "<testsuite failures='" + failCount + "' time='" + (totalTimeTaken / 1000).toFixed(2) + "' errors='" + errorCount + "' skipped='" + skipCount + "' tests='" + totalCount + "' name='" + testSuiteName + "'>";
    strJunitReport += strReport;
    strJunitReport += "</testsuite>";
    if (this.reportObj.descriptor) {

        xmlReportName = this.reportObj.descriptor.split(".")[0] + "-report.xml";
        jsonReportName = this.reportObj.descriptor.split(".")[0] + "-report.json";
    } else {
        xmlReportName = "report.xml";
        jsonReportName = "report.json";
    }
    writeFile(xmlReportName, strJunitReport);

    //writing json file
    for (i = 0; i < testSessions.length; i = i + 1) {
        jsonReport[testSessions[i].driver.testName] = JSON.parse(JSON.stringify(testSessions[i].driver.getReports()));
    }
    jsonReport.testSuiteName =  testSuiteName;
    writeFile(jsonReportName, JSON.stringify(jsonReport));
};

module.exports = ReportManager;
<commit_msg>removing failure childNode for skipped tests in junit xml, instead now we show an attribute "executed" = "false"<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require('fs');
var colors = require("colors");
var UserAgent = require('useragent');

/**
 *
 * @param reportObj includes all information about testSessions, wsSessions and the test report itself
 * @constructor
 */
function ReportManager(reportObj) {
    var stats;
    try {
        if (reportObj.arrTestSessions) {
            this.testSessions = reportObj.arrTestSessions;
        } else {
            this.testSessions = [];
        }

        if (reportObj.arrWDSessions) {
            this.wdSessions = reportObj.arrWDSessions;
        } else {
            this.wdSessions = [];
        }
        this.reportObj = reportObj;
        if (reportObj.reportFolder) {
            stats = fs.lstatSync(reportObj.reportFolder);
            if (stats.isDirectory()) {
                this.reportFolder = reportObj.reportFolder;
            }
        }
    } catch (ex) {
        //console.log(ex);
    }
}

ReportManager.prototype.showReportOnConsole = function (result, verbose) {

//    console.log("Result: " + JSON.stringify(result));
//    console.log("Verbose " + verbose);

    var lastSuite, suite, k, k1, test, msg, m, browser,
        log = console.log;

    log("");
    browser = result.ua;
    if (result.failed) {
        log("Failed ".red +  result.name.blue + " on"  + browser);
    } else {
        log("Passed ".green + result.name.blue + " on"  + browser);
    }
    log((result.passed + " Passed").green + ", " + (result.failed + " Failed ").red + ", " + (result.ignored + " skipped ").grey);
    if (result.failed) {
        for (k in result) {
            suite = result[k];
            if ("object" === typeof suite) {
                if (suite.failed) {
                    for (k1 in suite) {
                        test = suite[k1];
                        if ("object" === typeof test) {
                            if ("fail" === test.result) {
                                if (!lastSuite || lastSuite !== suite.name) {
                                    log(" in " +  suite.name.bold);
                                    lastSuite = suite.name;
                                }
                                msg = test.message.split('\n');
                                log(" " +  test.name.bold.red + ":" +  msg[0]);
                                for (m = 1; m < msg.length; m = m + 1) {
                                    log(" " + msg[m]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    log("");
};

ReportManager.prototype.writeReports = function () {

    var i, j, k, strJunitReport, strReport, rep, results, testJson, yuiUserAgent, yuiSuiteName, browser, descTestName, sessionId, yuiTestCaseName, timePerTest,
        className, testName, totalTimeTaken, errorCount, testSuiteName, arrReport, xmlReportName, jsonReportName, errorRep,
        self = this,
        wdSessions = self.wdSessions,
        testSessions = self.testSessions,
        passCount = 0,
        failCount = 0,
        skipCount = 0,
        timeCount = 0,
        totalCount = 0,
        jsonReport = {},
        log = console.log;
        resultPresent = false;
        errorCount = 0;

    function writeFile(fileName, data) {

        if (self.reportFolder) {
            fileName = self.reportFolder  + fileName;
        }
        fs.writeFileSync(fileName, data, 'utf8');
        log(("Report Created: " + fileName).inverse);
    }

    function addProperty(name, val) {
        if (val) {
            strReport += "<property name='" + name + "' value='" + val + "' />";
        }
    }
    function addTest(time, className, name, failureMessage, log) {
        strReport += "<testcase time='" + (time / 1000).toFixed(2) + "' classname='" + className  + "' name='" + name + "'";
        if (failureMessage) {
            if (failureMessage === "skip") {
                strReport += " ' executed='false' />";
            } else {
                strReport += "><failure><![CDATA[" + failureMessage + "]]></failure>" + log + "</testcase>";
            }
        } else {
            strReport += "/>";
        }
    }

    function parseYUIResults(testJson, dtName) {
        var l, m;

        yuiUserAgent = testJson.ua;
        yuiSuiteName = testJson.name;
        browser = UserAgent.parse(yuiUserAgent).toAgent();
        if (browser === "Other 0.0.0") {
            browser = "NodeJS";
        }
        descTestName = dtName;
        sessionId = testJson.sessionId;
        for (l in testJson) {
            if (testJson[l]) {
                if (testJson[l].type === "testcase") {
                    yuiTestCaseName = testJson[l].name;
                    timePerTest = testJson[l].duration / testJson[l].total;
                    passCount += testJson[l].passed;
                    failCount += testJson[l].failed;
                    skipCount += testJson[l].ignored;
                    timeCount += testJson[l].duration;
                    totalCount += testJson[l].total;

                    for (m in testJson[l]) {
                        if (testJson[l][m].type === "test") {
                            className = browser + "." + descTestName;
                            testName = yuiSuiteName + "::" + yuiTestCaseName + "::" + testJson[l][m].name;
                            if (testJson[l][m].result === "fail") {
                                addTest(timePerTest, className, testName, testJson[l][m].message);
                            } else if (testJson[l][m].result === "pass") {
                                addTest(timePerTest, className, testName);
                            } else if (testJson[l][m].result === "ignore") {
                                addTest(timePerTest, className, testName,"skip");
                            }
                        }
                    }
                }
            }
        }
    }
    strReport = "<properties>";
    addProperty("descriptor", this.reportObj.descriptor);
    addProperty("parallel", this.reportObj.parallel);
    addProperty("driver", this.reportObj.driver);
    addProperty("browser", this.reportObj.browser);
    addProperty("reuseSession", this.reportObj.reuseSession);
    addProperty("activeSeleniumSessionCount", wdSessions.length);
    addProperty("seleniumSessionIds", wdSessions.join());
    addProperty("group", this.reportObj.group);
    addProperty("testName", this.reportObj.testName);
    addProperty("reportFolder", this.reportObj.reportFolder);
    strReport += "</properties>";

    for (i = 0; i < testSessions.length; i = i + 1) {
        rep = testSessions[i].driver.getReports();

        if (rep.scenario) {
            arrReport = rep.scenario;
        } else {
            arrReport = rep.results;
        }

        resultPresent = false;

        for (j = 0; j < arrReport.length; j = j + 1) {
            if (rep.scenario) {
                results = arrReport[j].results;
                for (k = 0; k < results.length; k = k + 1) {
                    testJson =  results[k];
                    if(testJson.type === "report") {
                        resultPresent = true;
                        parseYUIResults(testJson, testSessions[i].driver.testName);
                    }
                }

            } else {
                testJson = arrReport[j];
                if(testJson.type === "report") {
                    resultPresent = true;
                    parseYUIResults(testJson, testSessions[i].driver.testName);
                }
            }
        }

        if(!resultPresent) {
            errorCount = errorCount + 1;
           var errorRep = arrReport[arrReport.length-1];

           if(errorRep.results) {
               //console.log("Error :" + errorRep.results[0].error);
               addTest(0, "Error." +  testSessions[i].driver.testName,"Error" , errorRep.results[0].error);

           } else if (errorRep.error) {
              // console.log("Error : " +errorRep.error)
               addTest(0, "Error." +  testSessions[i].driver.testName,"Error" , errorRep.error);
           } else{
               console.log("Error : UNKOWN");
           }

            console.log("Test Session dint have any report");
        }
    }
    log();
    log("Test Report Summary".bold.magenta);
    log();
    log(("Total Number of Executed Tests: " + (totalCount + errorCount) ).blue);
    log(("Total Number of Passed Tests: " + passCount).green);
    log(("Total Number of Failed Tests: " + ( errorCount + failCount) ).red);
    log(("Total Number of Skipped Tests: " + skipCount).cyan);
    log();
    log(("Total Test Execution Time Inside Browser: " + (timeCount / 1000).toFixed(2) + " seconds").green.bold);
    totalTimeTaken = Date.now() - global.startTime;
    log(("Total Test Execution Time:" + (totalTimeTaken / 1000).toFixed(2) + " seconds").green.bold);
    log();

    errorCount = totalCount - passCount - failCount - skipCount;

    testSuiteName = "";
    if (this.reportObj.testSuiteName) {
        testSuiteName = this.reportObj.testSuiteName;
    } else {
        testSuiteName = "TestSuite";
    }

    //writing xml file
    strJunitReport = "<testsuite failures='" + failCount + "' time='" + (totalTimeTaken / 1000).toFixed(2) + "' errors='" + errorCount + "' skipped='" + skipCount + "' tests='" + totalCount + "' name='" + testSuiteName + "'>";
    strJunitReport += strReport;
    strJunitReport += "</testsuite>";
    if (this.reportObj.descriptor) {

        xmlReportName = this.reportObj.descriptor.split(".")[0] + "-report.xml";
        jsonReportName = this.reportObj.descriptor.split(".")[0] + "-report.json";
    } else {
        xmlReportName = "report.xml";
        jsonReportName = "report.json";
    }
    writeFile(xmlReportName, strJunitReport);

    //writing json file
    for (i = 0; i < testSessions.length; i = i + 1) {
        jsonReport[testSessions[i].driver.testName] = JSON.parse(JSON.stringify(testSessions[i].driver.getReports()));
    }
    jsonReport.testSuiteName =  testSuiteName;
    writeFile(jsonReportName, JSON.stringify(jsonReport));
};

module.exports = ReportManager;
<|endoftext|>


<commit_before>'use strict';

var Promise = require('rsvp').Promise;
var _       = require('lodash-node');

function Pipeline(hookNames) {
  hookNames = hookNames || [];

  this._pipelineHooks = hookNames.reduce(function(pipelineHooks, hookName) {
    pipelineHooks[hookName] = [];

    return pipelineHooks;
  }, {});
}

Pipeline.prototype.register = function(hookName, fn) {
  var pipelineHooks = this._pipelineHooks;

  if (pipelineHooks[hookName]) {
    pipelineHooks[hookName].push(fn);
  }
};

Pipeline.prototype.execute = function(context) {
  context = context || { };

  var pipelineHooks = this._pipelineHooks;
  var hookNames     = Object.keys(pipelineHooks);

  return hookNames.reduce(function(promise, hookName) {
    return promise.then(this._executeHook.bind(this, hookName));
  }.bind(this), Promise.resolve(context));
};

Pipeline.prototype._executeHook = function(hookName, context) {
  var hookFunctions = this._pipelineHooks[hookName];

  return hookFunctions.reduce(function(promise, fn) {
    return promise
      .then(function(context) {
        return fn(context);
      })
      .then(function(result) {
        return _.merge(result, context);
      })
  }, Promise.resolve(context));
}

module.exports = Pipeline;
<commit_msg>Had the order of objects around the wrong way when merging<commit_after>'use strict';

var Promise = require('rsvp').Promise;
var _       = require('lodash-node');

function Pipeline(hookNames) {
  hookNames = hookNames || [];

  this._pipelineHooks = hookNames.reduce(function(pipelineHooks, hookName) {
    pipelineHooks[hookName] = [];

    return pipelineHooks;
  }, {});
}

Pipeline.prototype.register = function(hookName, fn) {
  var pipelineHooks = this._pipelineHooks;

  if (pipelineHooks[hookName]) {
    pipelineHooks[hookName].push(fn);
  }
};

Pipeline.prototype.execute = function(context) {
  context = context || { };

  var pipelineHooks = this._pipelineHooks;
  var hookNames     = Object.keys(pipelineHooks);

  return hookNames.reduce(function(promise, hookName) {
    return promise.then(this._executeHook.bind(this, hookName));
  }.bind(this), Promise.resolve(context));
};

Pipeline.prototype._executeHook = function(hookName, context) {
  var hookFunctions = this._pipelineHooks[hookName];

  return hookFunctions.reduce(function(promise, fn) {
    return promise
      .then(function(context) {
        return fn(context);
      })
      .then(function(result) {
        return _.merge(context, result);
      })
  }, Promise.resolve(context));
}

module.exports = Pipeline;
<|endoftext|>


<commit_before>var _ = require("underscore");
var path = require("path");

module.exports = {

	wrappedRequire: function() {
		return require;
	},

	requireAndSetup: function(id, config) {
		var self = this;
		var exported_module;

		if (id.indexOf("./") === 0) {
			exported_module = self.wrappedRequire(path.join(process.cwd(), id));
		} else {
			// try to load the module from /node_modules relative to
			// current working directory.
			var parts = process.cwd().split(path.sep);
			var paths = [];

			for (var tip = parts.length - 1; tip >= 0; tip--) {
				// don't search in .../node_modules/node_modules
				if (parts[tip] === "node_modules") {
				 continue;
				}
				var dir = parts.slice(0, tip + 1).concat("node_modules").join(path.sep);
				paths.push(path.join(dir, id));
			}

			// if relative paths fail,
			// delegate module load to node's default procedure.
			paths.push(id);

			var load_module_from_paths = function() {
				try {
					exported_module = self.wrappedRequire(paths.shift());
				} catch (e) {
					if (paths.length) {
						return load_module_from_paths();
					} else {
						raise(e);
					}
				}
			};

			load_module_from_paths();
		}

		if (_.has(exported_module, "setup")) {
			exported_module.setup(config);
		}

		return exported_module;
	}

};
<commit_msg>Fixed argument error in wrapped require<commit_after>var _ = require("underscore");
var path = require("path");

module.exports = {

	wrappedRequire: function(path) {
		return require(path);
	},

	requireAndSetup: function(id, config) {
		var self = this;
		var exported_module;

		if (id.indexOf("./") === 0) {
			exported_module = self.wrappedRequire(path.join(process.cwd(), id));
		} else {
			// try to load the module from /node_modules relative to
			// current working directory.
			var parts = process.cwd().split(path.sep);
			var paths = [];

			for (var tip = parts.length - 1; tip >= 0; tip--) {
				// don't search in .../node_modules/node_modules
				if (parts[tip] === "node_modules") {
				 continue;
				}
				var dir = parts.slice(0, tip + 1).concat("node_modules").join(path.sep);
				paths.push(path.join(dir, id));
			}

			// if relative paths fail,
			// delegate module load to node's default procedure.
			paths.push(id);

			var load_module_from_paths = function() {
				try {
					exported_module = self.wrappedRequire(paths.shift());
				} catch (e) {
					if (paths.length) {
						return load_module_from_paths();
					} else {
						raise(e);
					}
				}
			};

			load_module_from_paths();
		}

		if (_.has(exported_module, "setup")) {
			exported_module.setup(config);
		}

		return exported_module;
	}

};
<|endoftext|>


<commit_before>"use strict";

var NDArray = require("../NDArray");
var DataType = require("../DataType");
var util = require("../util");
var fs = require("fs");

var shapeToLength = function(shape) {
	var length = 1;
	for (var i = 0; i < shape.length; i++) {
		length *= shape[i];
	}
	return length;
};

var isCompatibleShape = function(shape1, shape2) {
	if (shape1.length !== shape2.length) {
		return false;
	}
	for (var i = 0; i < shape1.length; i++) {
		if (shape1[i] !== shape2[i]) {
			return false;
		}
	}
	return true;
};

/* Not supported by Nokia-WebCL, buggy in Chromium-WebCL */
var useAsyncBufferRead = false;
/* Buggy in Chromium-WebCL */
var useBufferCreationWithInit = false;
/* Chromium-WebCL requires a list of devices. Nokia-WebCL, on the contrary, only works with no arguments to WebCLProgram.build */
var useDeviceForBuild = true;

var cl = (typeof window === "object") ? window.webcl : undefined;
var context = null;
var queue = null;
var messageCallbacks = {};

var binaryOpKernels = {
	add: {},
	sub: {},
	mul: {},
	div: {}
};
var binaryConstOpKernels = {
	add: {},
	sub: {},
	mul: {},
	div: {}
};
var unaryOpKernels = {
	neg: {},
	abs: {},
	exp: {},
	log: {},
	sqrt: {},
	square: {}
};

var setKernels = {};

function WebCLContext(callback) {
	if (typeof cl === "undefined") {
		cl = require("node-webcl");
	}
	if (context === null) {
		var source = fs.readFileSync(__dirname + "/kernels.cl", "utf8");

		var platforms = cl.getPlatforms();
		var platform = platforms[0];
		var devices = platform.getDevices(cl.DEVICE_TYPE_ALL);
		var device = devices[0];
		context = cl.createContext(device);
		queue = context.createCommandQueue();
		var program = context.createProgram(source);
		if (useDeviceForBuild) {
			program.build([device]);
		} else {
			program.build();
		}
		setKernels.f32 = program.createKernel("setF32");
		setKernels.f64 = program.createKernel("setF64");
		binaryOpKernels.add.f32 = program.createKernel("addF32");
		binaryOpKernels.add.f64 = program.createKernel("addF64");
		binaryOpKernels.sub.f32 = program.createKernel("subF32");
		binaryOpKernels.sub.f64 = program.createKernel("subF64");
		binaryOpKernels.mul.f32 = program.createKernel("mulF32");
		binaryOpKernels.mul.f64 = program.createKernel("mulF64");
		binaryOpKernels.div.f32 = program.createKernel("divF32");
		binaryOpKernels.div.f64 = program.createKernel("divF64");
		binaryConstOpKernels.add.f32 = program.createKernel("addConstF32");
		binaryConstOpKernels.add.f64 = program.createKernel("addConstF64");
		binaryConstOpKernels.sub.f32 = program.createKernel("subConstF32");
		binaryConstOpKernels.sub.f64 = program.createKernel("subConstF64");
		binaryConstOpKernels.mul.f32 = program.createKernel("mulConstF32");
		binaryConstOpKernels.mul.f64 = program.createKernel("mulConstF64");
		binaryConstOpKernels.div.f32 = program.createKernel("divConstF32");
		binaryConstOpKernels.div.f64 = program.createKernel("divConstF64");
		unaryOpKernels.neg.f32 = program.createKernel("negF32");
		unaryOpKernels.neg.f64 = program.createKernel("negF64");
		unaryOpKernels.abs.f32 = program.createKernel("absF32");
		unaryOpKernels.abs.f64 = program.createKernel("absF64");
		unaryOpKernels.exp.f32 = program.createKernel("expF32");
		unaryOpKernels.exp.f64 = program.createKernel("expF64");
		unaryOpKernels.log.f32 = program.createKernel("logF32");
		unaryOpKernels.log.f64 = program.createKernel("logF64");
		unaryOpKernels.sqrt.f32 = program.createKernel("sqrtF32");
		unaryOpKernels.sqrt.f64 = program.createKernel("sqrtF64");
		unaryOpKernels.square.f32 = program.createKernel("squareF32");
		unaryOpKernels.square.f64 = program.createKernel("squareF64");
	}
	callback(this);
}

WebCLContext.prototype.empty = function(shape, dataType) {
	shape = util.checkShape(shape);
	if (typeof dataType === "undefined") {
		dataType = new DataType("f64");
	} else if (!(dataType instanceof DataType)) {
		throw new TypeError(dataType + " is not an instance of DataType");
	}
	var array = new NDArray(shape, dataType, this);
	array._buffer = context.createBuffer(cl.MEM_READ_WRITE, array.length * dataType.size);
	return array;
};

WebCLContext.prototype.zeros = function(shape, dataType) {
	shape = util.checkShape(shape);
	if (typeof dataType === "undefined") {
		dataType = new DataType("f64");
	} else if (!(dataType instanceof DataType)) {
		throw new TypeError(dataType + " is not an instance of DataType");
	}
	var array = new NDArray(shape, dataType, this);
	array._buffer = context.createBuffer(cl.MEM_READ_WRITE, array.length * dataType.size);
	var kernel = setKernels[dataType.type];
	kernel.setArg(0, new Uint32Array([array.length]));
	kernel.setArg(1, array._buffer);
	kernel.setArg(2, new dataType.arrayType([0.0]));
	queue.enqueueNDRangeKernel(kernel, 1, null, [array.length]);
	return array;
};

WebCLContext.prototype.array = function(data, dataType) {
	if (typeof dataType === "undefined") {
		dataType = new DataType("f64");
	} else {
		dataType = util.checkDataType(dataType);
	}
	var shape = [];
	util.discoverArrayShapeRecursive(data, shape, 0);
	var array = new NDArray(shape, dataType, this);
	var buffer = new dataType.arrayType(array.length);
	util.copyArrayDataRecursive(buffer, data, shape, 0, 0);
	if (useBufferCreationWithInit) {
		array._buffer = context.createBuffer(cl.MEM_READ_WRITE, buffer.byteLength, buffer);
	} else {
		array._buffer = context.createBuffer(cl.MEM_READ_WRITE, buffer.byteLength);
		queue.enqueueWriteBuffer(array._buffer, false, 0, buffer.byteLength, buffer);
	}
	return array;
};

WebCLContext.prototype._invalidate = function(array) {
	if (array._buffer !== null) {
		/* Work-around for Chromium-WebCL that currently lacks WebCLMemObject.release method */
		if (typeof array._buffer.release !== "undefined") {
			array._buffer.release();
		}
		array._buffer = null;
	}
};

WebCLContext.prototype.get = function() {
	if (arguments.length === 0) {
		throw new Error("Callback argument missing");
	}
	var callback = arguments[arguments.length - 1];
	/* Validate arguments */
	if (arguments.length === 1) {
		throw new Error("At least one NDArray argument expected");
	}
	for (var i = 0; i < arguments.length - 1; i++) {
		if (!(arguments[i] instanceof NDArray)) {
			throw new TypeError("Argument " + i + " is not an NDArray");
		}
	}
	var callbackWaitArguments = arguments.length - 1;
	var callbackArguments = new Array(callbackWaitArguments);
	if (useAsyncBufferRead) {
		/* Async version: doesn't seem to be supported by WebCL implementations */
		for (var i = 0; i < callbackWaitArguments; i++) {
			var array = arguments[i];
			(function(i, shape, ArrayType) {
				var buffer = new ArrayType(length);
				var readFinishEvent = new WebCLEvent();
				queue.enqueueReadBuffer(array._buffer, false, 0, buffer.byteLength, buffer, null, readFinishEvent);
				if (shape.length === 0) {
					readFinishEvent.setCallback(cl.COMPLETE, function() {
						readFinishEvent.release();
						callbackArguments[i] = typedArray[0];
						if (--callbackWaitArguments === 0) {
							callback.apply(null, callbackArguments);
						}
					});
				} else {
					readFinishEvent.setCallback(cl.COMPLETE, function() {
						readFinishEvent.release();
						var jsarray = new Array(shape[0]);
						createArrayRecursive(new ArrayType(buffer), jsarray, shape, 0, 0);
						callbackArguments[i] = jsarray;
						if (--callbackWaitArguments === 0) {
							callback.apply(null, callbackArguments);
						}
					});
				}
			})(i, array.shape, array.dataType.arrayType);
		}
	} else {
		for (var i = 0; i < callbackWaitArguments; i++) {
			var array = arguments[i];
			var buffer = new array.dataType.arrayType(array.length);
			queue.enqueueReadBuffer(array._buffer, true, 0, buffer.byteLength, buffer);
			if (array.shape.length === 0) {
				callbackArguments[i] = typedArray[0];
			} else {
				var jsarray = new Array(array.shape[0]);
				util.createArrayRecursive(new array.dataType.arrayType(buffer), jsarray, array.shape, 0, 0);
				callbackArguments[i] = jsarray;
			}
		}
		callback.apply(null, callbackArguments);
	}
};

var binaryArithOp = function(a, b, out, context, operation) {
	var shape = null, dataType = null;
	if (a instanceof NDArray) {
		shape = a.shape;
		dataType = a.dataType;
		if (b instanceof NDArray) {
			if (!isCompatibleShape(shape, b.shape)) {
				throw new Error("The a and b arrays have incompatible shapes");
			}
		} else if (!util.isNumber(b)) {
			throw new TypeError("Unsupported type of b");
		}
	} else {
		throw new TypeError("Unsupported type of a");
	}
	if (typeof out === "undefined") {
		out = context.empty(shape, dataType);
	} else if (out instanceof NDArray) {
		if (!isCompatibleShape(shape, out.shape)) {
			throw new Error("The out array has incompatible shape");
		}
	} else {
		throw new TypeError("out is not an NDArray");
	}
	if (a instanceof NDArray) {
		if (b instanceof NDArray) {
			var kernel = binaryOpKernels[operation][dataType.type];
			kernel.setArg(0, new Uint32Array([out.length]));
			kernel.setArg(1, a._buffer);
			kernel.setArg(2, b._buffer);
			kernel.setArg(3, out._buffer);
			queue.enqueueNDRangeKernel(kernel, 1, null, [out.length]);
		} else {
			var kernel = binaryConstOpKernels[operation][dataType.type];
			kernel.setArg(0, new Uint32Array([out.length]));
			kernel.setArg(1, a._buffer);
			kernel.setArg(2, new a.dataType.arrayType([b]));
			kernel.setArg(3, out._buffer);
			queue.enqueueNDRangeKernel(kernel, 1, null, [out.length]);
		}
	}
	return out;
};

var unaryArithOp = function(a, out, context, operation) {
	var shape = null, dataType = null;
	if (a instanceof NDArray) {
		shape = a.shape;
		dataType = a.dataType;
	} else {
		throw new TypeError("Unsupported type of a");
	}
	if (typeof out === "undefined") {
		out = context.empty(shape, dataType);
	} else if (out instanceof NDArray) {
		if (!isCompatibleShape(shape, out.shape)) {
			throw new Error("The out array has incompatible shape");
		}
	} else {
		throw new TypeError("out is not an NDArray");
	}
	var kernel = unaryOpKernels[operation][dataType.type];
	kernel.setArg(0, new Uint32Array([out.length]));
	kernel.setArg(1, a._buffer);
	kernel.setArg(2, out._buffer);
	queue.enqueueNDRangeKernel(kernel, 1, null, [out.length]);
	return out;
};

WebCLContext.prototype.add = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "add");
};

WebCLContext.prototype.sub = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "sub");
};

WebCLContext.prototype.mul = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "mul");
};

WebCLContext.prototype.div = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "div");
};

WebCLContext.prototype.neg = function(a, out) {
	return unaryArithOp(a, out, this, "neg");
};

WebCLContext.prototype.abs = function(a, out) {
	return unaryArithOp(a, out, this, "abs");
};

WebCLContext.prototype.exp = function(a, out) {
	return unaryArithOp(a, out, this, "exp");
};

WebCLContext.prototype.log = function(a, out) {
	return unaryArithOp(a, out, this, "log");
};

WebCLContext.prototype.sqrt = function(a, out) {
	return unaryArithOp(a, out, this, "sqrt");
};

WebCLContext.prototype.square = function(a, out) {
	return unaryArithOp(a, out, this, "square");
};

module.exports = WebCLContext;
<commit_msg>WebCLContext: simultaneous workaround for Nokia-WebCL and Chromium-WebCL bugs in WebCLProgram.build<commit_after>"use strict";

var NDArray = require("../NDArray");
var DataType = require("../DataType");
var util = require("../util");
var fs = require("fs");

var shapeToLength = function(shape) {
	var length = 1;
	for (var i = 0; i < shape.length; i++) {
		length *= shape[i];
	}
	return length;
};

var isCompatibleShape = function(shape1, shape2) {
	if (shape1.length !== shape2.length) {
		return false;
	}
	for (var i = 0; i < shape1.length; i++) {
		if (shape1[i] !== shape2[i]) {
			return false;
		}
	}
	return true;
};

/* Not supported by Nokia-WebCL, buggy in Chromium-WebCL */
var useAsyncBufferRead = false;
/* Buggy in Chromium-WebCL */
var useBufferCreationWithInit = false;

var cl = (typeof window === "object") ? window.webcl : undefined;
var context = null;
var queue = null;
var messageCallbacks = {};

var binaryOpKernels = {
	add: {},
	sub: {},
	mul: {},
	div: {}
};
var binaryConstOpKernels = {
	add: {},
	sub: {},
	mul: {},
	div: {}
};
var unaryOpKernels = {
	neg: {},
	abs: {},
	exp: {},
	log: {},
	sqrt: {},
	square: {}
};

var setKernels = {};

function WebCLContext(callback) {
	if (typeof cl === "undefined") {
		cl = require("node-webcl");
	}
	if (context === null) {
		var source = fs.readFileSync(__dirname + "/kernels.cl", "utf8");

		var platforms = cl.getPlatforms();
		var platform = platforms[0];
		var devices = platform.getDevices(cl.DEVICE_TYPE_ALL);
		var device = devices[0];
		context = cl.createContext(device);
		queue = context.createCommandQueue();
		var program = context.createProgram(source);
		try {
			/* Chromium-WebCL requires a list of devices */
			program.build([device]);
		} catch (e) {
			if (e.name === "INVALID_DEVICE") {
				/* Nokia-WebCL only works with no arguments to WebCLProgram.build */
				program.build();
			} else {
				throw e;
			}
		}
		setKernels.f32 = program.createKernel("setF32");
		setKernels.f64 = program.createKernel("setF64");
		binaryOpKernels.add.f32 = program.createKernel("addF32");
		binaryOpKernels.add.f64 = program.createKernel("addF64");
		binaryOpKernels.sub.f32 = program.createKernel("subF32");
		binaryOpKernels.sub.f64 = program.createKernel("subF64");
		binaryOpKernels.mul.f32 = program.createKernel("mulF32");
		binaryOpKernels.mul.f64 = program.createKernel("mulF64");
		binaryOpKernels.div.f32 = program.createKernel("divF32");
		binaryOpKernels.div.f64 = program.createKernel("divF64");
		binaryConstOpKernels.add.f32 = program.createKernel("addConstF32");
		binaryConstOpKernels.add.f64 = program.createKernel("addConstF64");
		binaryConstOpKernels.sub.f32 = program.createKernel("subConstF32");
		binaryConstOpKernels.sub.f64 = program.createKernel("subConstF64");
		binaryConstOpKernels.mul.f32 = program.createKernel("mulConstF32");
		binaryConstOpKernels.mul.f64 = program.createKernel("mulConstF64");
		binaryConstOpKernels.div.f32 = program.createKernel("divConstF32");
		binaryConstOpKernels.div.f64 = program.createKernel("divConstF64");
		unaryOpKernels.neg.f32 = program.createKernel("negF32");
		unaryOpKernels.neg.f64 = program.createKernel("negF64");
		unaryOpKernels.abs.f32 = program.createKernel("absF32");
		unaryOpKernels.abs.f64 = program.createKernel("absF64");
		unaryOpKernels.exp.f32 = program.createKernel("expF32");
		unaryOpKernels.exp.f64 = program.createKernel("expF64");
		unaryOpKernels.log.f32 = program.createKernel("logF32");
		unaryOpKernels.log.f64 = program.createKernel("logF64");
		unaryOpKernels.sqrt.f32 = program.createKernel("sqrtF32");
		unaryOpKernels.sqrt.f64 = program.createKernel("sqrtF64");
		unaryOpKernels.square.f32 = program.createKernel("squareF32");
		unaryOpKernels.square.f64 = program.createKernel("squareF64");
	}
	callback(this);
}

WebCLContext.prototype.empty = function(shape, dataType) {
	shape = util.checkShape(shape);
	if (typeof dataType === "undefined") {
		dataType = new DataType("f64");
	} else if (!(dataType instanceof DataType)) {
		throw new TypeError(dataType + " is not an instance of DataType");
	}
	var array = new NDArray(shape, dataType, this);
	array._buffer = context.createBuffer(cl.MEM_READ_WRITE, array.length * dataType.size);
	return array;
};

WebCLContext.prototype.zeros = function(shape, dataType) {
	shape = util.checkShape(shape);
	if (typeof dataType === "undefined") {
		dataType = new DataType("f64");
	} else if (!(dataType instanceof DataType)) {
		throw new TypeError(dataType + " is not an instance of DataType");
	}
	var array = new NDArray(shape, dataType, this);
	array._buffer = context.createBuffer(cl.MEM_READ_WRITE, array.length * dataType.size);
	var kernel = setKernels[dataType.type];
	kernel.setArg(0, new Uint32Array([array.length]));
	kernel.setArg(1, array._buffer);
	kernel.setArg(2, new dataType.arrayType([0.0]));
	queue.enqueueNDRangeKernel(kernel, 1, null, [array.length]);
	return array;
};

WebCLContext.prototype.array = function(data, dataType) {
	if (typeof dataType === "undefined") {
		dataType = new DataType("f64");
	} else {
		dataType = util.checkDataType(dataType);
	}
	var shape = [];
	util.discoverArrayShapeRecursive(data, shape, 0);
	var array = new NDArray(shape, dataType, this);
	var buffer = new dataType.arrayType(array.length);
	util.copyArrayDataRecursive(buffer, data, shape, 0, 0);
	if (useBufferCreationWithInit) {
		array._buffer = context.createBuffer(cl.MEM_READ_WRITE, buffer.byteLength, buffer);
	} else {
		array._buffer = context.createBuffer(cl.MEM_READ_WRITE, buffer.byteLength);
		queue.enqueueWriteBuffer(array._buffer, false, 0, buffer.byteLength, buffer);
	}
	return array;
};

WebCLContext.prototype._invalidate = function(array) {
	if (array._buffer !== null) {
		/* Work-around for Chromium-WebCL that currently lacks WebCLMemObject.release method */
		if (typeof array._buffer.release !== "undefined") {
			array._buffer.release();
		}
		array._buffer = null;
	}
};

WebCLContext.prototype.get = function() {
	if (arguments.length === 0) {
		throw new Error("Callback argument missing");
	}
	var callback = arguments[arguments.length - 1];
	/* Validate arguments */
	if (arguments.length === 1) {
		throw new Error("At least one NDArray argument expected");
	}
	for (var i = 0; i < arguments.length - 1; i++) {
		if (!(arguments[i] instanceof NDArray)) {
			throw new TypeError("Argument " + i + " is not an NDArray");
		}
	}
	var callbackWaitArguments = arguments.length - 1;
	var callbackArguments = new Array(callbackWaitArguments);
	if (useAsyncBufferRead) {
		/* Async version: doesn't seem to be supported by WebCL implementations */
		for (var i = 0; i < callbackWaitArguments; i++) {
			var array = arguments[i];
			(function(i, shape, ArrayType) {
				var buffer = new ArrayType(length);
				var readFinishEvent = new WebCLEvent();
				queue.enqueueReadBuffer(array._buffer, false, 0, buffer.byteLength, buffer, null, readFinishEvent);
				if (shape.length === 0) {
					readFinishEvent.setCallback(cl.COMPLETE, function() {
						readFinishEvent.release();
						callbackArguments[i] = typedArray[0];
						if (--callbackWaitArguments === 0) {
							callback.apply(null, callbackArguments);
						}
					});
				} else {
					readFinishEvent.setCallback(cl.COMPLETE, function() {
						readFinishEvent.release();
						var jsarray = new Array(shape[0]);
						createArrayRecursive(new ArrayType(buffer), jsarray, shape, 0, 0);
						callbackArguments[i] = jsarray;
						if (--callbackWaitArguments === 0) {
							callback.apply(null, callbackArguments);
						}
					});
				}
			})(i, array.shape, array.dataType.arrayType);
		}
	} else {
		for (var i = 0; i < callbackWaitArguments; i++) {
			var array = arguments[i];
			var buffer = new array.dataType.arrayType(array.length);
			queue.enqueueReadBuffer(array._buffer, true, 0, buffer.byteLength, buffer);
			if (array.shape.length === 0) {
				callbackArguments[i] = typedArray[0];
			} else {
				var jsarray = new Array(array.shape[0]);
				util.createArrayRecursive(new array.dataType.arrayType(buffer), jsarray, array.shape, 0, 0);
				callbackArguments[i] = jsarray;
			}
		}
		callback.apply(null, callbackArguments);
	}
};

var binaryArithOp = function(a, b, out, context, operation) {
	var shape = null, dataType = null;
	if (a instanceof NDArray) {
		shape = a.shape;
		dataType = a.dataType;
		if (b instanceof NDArray) {
			if (!isCompatibleShape(shape, b.shape)) {
				throw new Error("The a and b arrays have incompatible shapes");
			}
		} else if (!util.isNumber(b)) {
			throw new TypeError("Unsupported type of b");
		}
	} else {
		throw new TypeError("Unsupported type of a");
	}
	if (typeof out === "undefined") {
		out = context.empty(shape, dataType);
	} else if (out instanceof NDArray) {
		if (!isCompatibleShape(shape, out.shape)) {
			throw new Error("The out array has incompatible shape");
		}
	} else {
		throw new TypeError("out is not an NDArray");
	}
	if (a instanceof NDArray) {
		if (b instanceof NDArray) {
			var kernel = binaryOpKernels[operation][dataType.type];
			kernel.setArg(0, new Uint32Array([out.length]));
			kernel.setArg(1, a._buffer);
			kernel.setArg(2, b._buffer);
			kernel.setArg(3, out._buffer);
			queue.enqueueNDRangeKernel(kernel, 1, null, [out.length]);
		} else {
			var kernel = binaryConstOpKernels[operation][dataType.type];
			kernel.setArg(0, new Uint32Array([out.length]));
			kernel.setArg(1, a._buffer);
			kernel.setArg(2, new a.dataType.arrayType([b]));
			kernel.setArg(3, out._buffer);
			queue.enqueueNDRangeKernel(kernel, 1, null, [out.length]);
		}
	}
	return out;
};

var unaryArithOp = function(a, out, context, operation) {
	var shape = null, dataType = null;
	if (a instanceof NDArray) {
		shape = a.shape;
		dataType = a.dataType;
	} else {
		throw new TypeError("Unsupported type of a");
	}
	if (typeof out === "undefined") {
		out = context.empty(shape, dataType);
	} else if (out instanceof NDArray) {
		if (!isCompatibleShape(shape, out.shape)) {
			throw new Error("The out array has incompatible shape");
		}
	} else {
		throw new TypeError("out is not an NDArray");
	}
	var kernel = unaryOpKernels[operation][dataType.type];
	kernel.setArg(0, new Uint32Array([out.length]));
	kernel.setArg(1, a._buffer);
	kernel.setArg(2, out._buffer);
	queue.enqueueNDRangeKernel(kernel, 1, null, [out.length]);
	return out;
};

WebCLContext.prototype.add = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "add");
};

WebCLContext.prototype.sub = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "sub");
};

WebCLContext.prototype.mul = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "mul");
};

WebCLContext.prototype.div = function(a, b, out) {
	return binaryArithOp(a, b, out, this, "div");
};

WebCLContext.prototype.neg = function(a, out) {
	return unaryArithOp(a, out, this, "neg");
};

WebCLContext.prototype.abs = function(a, out) {
	return unaryArithOp(a, out, this, "abs");
};

WebCLContext.prototype.exp = function(a, out) {
	return unaryArithOp(a, out, this, "exp");
};

WebCLContext.prototype.log = function(a, out) {
	return unaryArithOp(a, out, this, "log");
};

WebCLContext.prototype.sqrt = function(a, out) {
	return unaryArithOp(a, out, this, "sqrt");
};

WebCLContext.prototype.square = function(a, out) {
	return unaryArithOp(a, out, this, "square");
};

module.exports = WebCLContext;
<|endoftext|>


<commit_before>/**
 *  Mincer
 *
 *  This is a main entry point of the module (an object that you get by calling
 *  `require('mincer')`. You can get acces to some of the internal classes using
 *  this object.
 *
 *      var env = new (require('mincer').Environment)(__dirname);
 *
 *  `Mincer` depends on some 3rd-party modules. Most valueble (for understanding
 *  an API) are:
 *
 *  - [Hike](http://nodeca.github.com/hike-js/)
 *  - [Mimoza](http://nodeca.github.com/mimoza/)
 *  - [Types](http://nodeca.github.com/types/)
 *
 *
 *  ##### EXTENDED BY
 *
 *  - [[Engines]]
 *  - [[Mime]]
 *  - [[Processing]]
 *  - [[Paths]]
 **/

'use strict';

// Node < 0.8 shims
if (!require('fs').existsSync) {
  require('fs').existsSync = require('path').existsSync;
}

// 3rd-party
var Mimoza  = require('mimoza');
var Trail   = require('hike').Trail;
var Hash    = require('types').Hash;

// internal
var mixin = require('./mincer/common').mixin;
var prop  = require('./mincer/common').prop;

var Mincer = module.exports = {};

// Engines /////////////////////////////////////////////////////////////////////

/**
 *  Mincer.EjsEngine -> EjsEngine
 **/
Mincer.EjsEngine          = require('./mincer/engines/ejs_engine');

/**
 *  Mincer.LessEngine -> LessEngine
 **/
Mincer.LessEngine         = require('./mincer/engines/less_engine');

/**
 *  Mincer.StylusEngine -> StylusEngine
 **/
Mincer.StylusEngine       = require('./mincer/engines/stylus_engine');

/**
 *  Mincer.CoffeeEngine -> CoffeeEngine
 **/
Mincer.CoffeeEngine       = require('./mincer/engines/coffee_engine');

// Processors //////////////////////////////////////////////////////////////////

/**
 *  Mincer.DebugComments -> DebugComments
 **/
Mincer.DebugComments      = require('./mincer/processors/debug_comments');

/**
 *  Mincer.DirectiveProcessor -> DirectiveProcessor
 **/
Mincer.DirectiveProcessor = require('./mincer/processors/directive_processor');

/**
 *  Mincer.CharsetNormalizer -> CharsetNormalizer
 **/
Mincer.CharsetNormalizer  = require('./mincer/processors/charset_normalizer');

/**
 *  Mincer.SafetyColons -> SafetyColons
 **/
Mincer.SafetyColons       = require('./mincer/processors/safety_colons');

// Main exported classes ///////////////////////////////////////////////////////

/**
 *  Mincer.Environment -> Environment
 **/
Mincer.Environment        = require('./mincer/environment');

/**
 *  Mincer.Manifest -> Manifest
 **/
Mincer.Manifest           = require('./mincer/manifest');

/**
 *  Mincer.Template -> Template
 **/
Mincer.Template           = require('./mincer/template');

// Main exported functions /////////////////////////////////////////////////////

/** alias of: Server.createServer
 *  Mincer.createServer(environment[, manifest]) -> Function
 **/
Mincer.createServer       = require('./mincer/server').createServer;

// Main exported properties ////////////////////////////////////////////////////

/** read-only
 *  Mincer.VERSION -> String
 **/
prop(Mincer, 'VERSION', require('./mincer/version'));

/** read-only
 *  Mincer.logger -> Logger
 **/
prop(Mincer, 'logger',  require('./mincer/logger'));

// Spicy Sauce :)) /////////////////////////////////////////////////////////////

// main internal properties.
// each new environment clone these properties for initial states,
// so they can be used to set "defaults" for all environment instances.
prop(Mincer, '__trail__',             new Trail(__dirname));
prop(Mincer, '__engines__',           {});
prop(Mincer, '__mimeTypes__',         new Mimoza());
prop(Mincer, '__preProcessors__',     new Hash(function (h, k) { return h.set(k, []); }));
prop(Mincer, '__postProcessors__',    new Hash(function (h, k) { return h.set(k, []); }));
prop(Mincer, '__bundleProcessors__',  new Hash(function (h, k) { return h.set(k, []); }));

// mixin helpers
mixin(Mincer, require('./mincer/helpers/engines'));
mixin(Mincer, require('./mincer/helpers/mime'));
mixin(Mincer, require('./mincer/helpers/processing'));
mixin(Mincer, require('./mincer/helpers/paths'));

// register basic mimetypes
Mincer.registerMimeType('text/css',               '.css');
Mincer.registerMimeType('application/javascript', '.js');

// register default pre-processors
Mincer.registerPreProcessor('text/css',                 Mincer.DirectiveProcessor);
Mincer.registerPreProcessor('application/javascript',   Mincer.DirectiveProcessor);

// register default post-processors
Mincer.registerPostProcessor('application/javascript',  Mincer.SafetyColons);
Mincer.registerPostProcessor('application/javascript',  Mincer.DebugComments);
Mincer.registerPostProcessor('text/css',                Mincer.DebugComments);

// register default bundle-processors
Mincer.registerBundleProcessor('text/css',              Mincer.CharsetNormalizer);

// Register JS engines
Mincer.registerEngine('.coffee',    Mincer.CoffeeEngine);

// Register CSS engines
Mincer.registerEngine('.less',      Mincer.LessEngine);
Mincer.registerEngine('.styl',      Mincer.StylusEngine);

// Other engines
Mincer.registerEngine('.ejs',       Mincer.EjsEngine);
<commit_msg>Add fs.exists shim<commit_after>/**
 *  Mincer
 *
 *  This is a main entry point of the module (an object that you get by calling
 *  `require('mincer')`. You can get acces to some of the internal classes using
 *  this object.
 *
 *      var env = new (require('mincer').Environment)(__dirname);
 *
 *  `Mincer` depends on some 3rd-party modules. Most valueble (for understanding
 *  an API) are:
 *
 *  - [Hike](http://nodeca.github.com/hike-js/)
 *  - [Mimoza](http://nodeca.github.com/mimoza/)
 *  - [Types](http://nodeca.github.com/types/)
 *
 *
 *  ##### EXTENDED BY
 *
 *  - [[Engines]]
 *  - [[Mime]]
 *  - [[Processing]]
 *  - [[Paths]]
 **/

'use strict';

// Node < 0.8 shims
if (!require('fs').exists) {
  require('fs').exists = require('path').exists;
}
if (!require('fs').existsSync) {
  require('fs').existsSync = require('path').existsSync;
}

// 3rd-party
var Mimoza  = require('mimoza');
var Trail   = require('hike').Trail;
var Hash    = require('types').Hash;

// internal
var mixin = require('./mincer/common').mixin;
var prop  = require('./mincer/common').prop;

var Mincer = module.exports = {};

// Engines /////////////////////////////////////////////////////////////////////

/**
 *  Mincer.EjsEngine -> EjsEngine
 **/
Mincer.EjsEngine          = require('./mincer/engines/ejs_engine');

/**
 *  Mincer.LessEngine -> LessEngine
 **/
Mincer.LessEngine         = require('./mincer/engines/less_engine');

/**
 *  Mincer.StylusEngine -> StylusEngine
 **/
Mincer.StylusEngine       = require('./mincer/engines/stylus_engine');

/**
 *  Mincer.CoffeeEngine -> CoffeeEngine
 **/
Mincer.CoffeeEngine       = require('./mincer/engines/coffee_engine');

// Processors //////////////////////////////////////////////////////////////////

/**
 *  Mincer.DebugComments -> DebugComments
 **/
Mincer.DebugComments      = require('./mincer/processors/debug_comments');

/**
 *  Mincer.DirectiveProcessor -> DirectiveProcessor
 **/
Mincer.DirectiveProcessor = require('./mincer/processors/directive_processor');

/**
 *  Mincer.CharsetNormalizer -> CharsetNormalizer
 **/
Mincer.CharsetNormalizer  = require('./mincer/processors/charset_normalizer');

/**
 *  Mincer.SafetyColons -> SafetyColons
 **/
Mincer.SafetyColons       = require('./mincer/processors/safety_colons');

// Main exported classes ///////////////////////////////////////////////////////

/**
 *  Mincer.Environment -> Environment
 **/
Mincer.Environment        = require('./mincer/environment');

/**
 *  Mincer.Manifest -> Manifest
 **/
Mincer.Manifest           = require('./mincer/manifest');

/**
 *  Mincer.Template -> Template
 **/
Mincer.Template           = require('./mincer/template');

// Main exported functions /////////////////////////////////////////////////////

/** alias of: Server.createServer
 *  Mincer.createServer(environment[, manifest]) -> Function
 **/
Mincer.createServer       = require('./mincer/server').createServer;

// Main exported properties ////////////////////////////////////////////////////

/** read-only
 *  Mincer.VERSION -> String
 **/
prop(Mincer, 'VERSION', require('./mincer/version'));

/** read-only
 *  Mincer.logger -> Logger
 **/
prop(Mincer, 'logger',  require('./mincer/logger'));

// Spicy Sauce :)) /////////////////////////////////////////////////////////////

// main internal properties.
// each new environment clone these properties for initial states,
// so they can be used to set "defaults" for all environment instances.
prop(Mincer, '__trail__',             new Trail(__dirname));
prop(Mincer, '__engines__',           {});
prop(Mincer, '__mimeTypes__',         new Mimoza());
prop(Mincer, '__preProcessors__',     new Hash(function (h, k) { return h.set(k, []); }));
prop(Mincer, '__postProcessors__',    new Hash(function (h, k) { return h.set(k, []); }));
prop(Mincer, '__bundleProcessors__',  new Hash(function (h, k) { return h.set(k, []); }));

// mixin helpers
mixin(Mincer, require('./mincer/helpers/engines'));
mixin(Mincer, require('./mincer/helpers/mime'));
mixin(Mincer, require('./mincer/helpers/processing'));
mixin(Mincer, require('./mincer/helpers/paths'));

// register basic mimetypes
Mincer.registerMimeType('text/css',               '.css');
Mincer.registerMimeType('application/javascript', '.js');

// register default pre-processors
Mincer.registerPreProcessor('text/css',                 Mincer.DirectiveProcessor);
Mincer.registerPreProcessor('application/javascript',   Mincer.DirectiveProcessor);

// register default post-processors
Mincer.registerPostProcessor('application/javascript',  Mincer.SafetyColons);
Mincer.registerPostProcessor('application/javascript',  Mincer.DebugComments);
Mincer.registerPostProcessor('text/css',                Mincer.DebugComments);

// register default bundle-processors
Mincer.registerBundleProcessor('text/css',              Mincer.CharsetNormalizer);

// Register JS engines
Mincer.registerEngine('.coffee',    Mincer.CoffeeEngine);

// Register CSS engines
Mincer.registerEngine('.less',      Mincer.LessEngine);
Mincer.registerEngine('.styl',      Mincer.StylusEngine);

// Other engines
Mincer.registerEngine('.ejs',       Mincer.EjsEngine);
<|endoftext|>


<commit_before>function getMonzo() {
  return {
    // general
    name: "Monzo Account",
    provider: "monzo",

    // auth
    authType: "oauth2",
    accessToken: null,
    accessExpires: -1,
    // variables below used while auth is being negotiated
    clientId: null,
    clientSecret: null,
    state: null,
    redirectUri: null,

    // other variables
    accountId: null,
    cardId: null
  };
}

// auth functions
function monzoAuth(monzo) {
  if (monzo.clientId == null) {
    throw new Error("clientId isn't set and yet auth was called!");
  }
  if (monzo.clientSecret == null) {
    throw new Error("clientSecret isn't set and yet auth was called!");
  }
  if (monzo.state == null) {
    throw new Error("state isn't set and yet auth was called!");
  }
  if (monzo.redirectUri == null) {
    throw new Error("redirectUri isn't set and yet auth was called!");
  }
  window.location = "https://auth.getmondo.co.uk/?client_id=" + monzo.clientId + "&redirect_uri=" + monzo.redirectUri + "&response_type=code&state=" + monzo.state;
}

function monzoCallback(monzo, authCode) {
  if (monzo.clientId == null) {
    throw new Error("clientId isn't set and yet callback was called!");
  }
  if (monzo.clientSecret == null) {
    throw new Error("clientSecret isn't set and yet callback was called!");
  }
  if (monzo.state == null) {
    throw new Error("state isn't set and yet callback was called!");
  }
  if (monzo.redirectUri == null) {
    throw new Error("redirectUri isn't set and yet callback was called!");
  }

  var request = new XMLHttpRequest();
  request.open("POST", "https://api.monzo.com/oauth2/token", false);
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send("grant_type=authorization_code&client_id=" + monzo.clientId + "&client_secret=" + monzo.clientSecret + "&redirect_uri=" + monzo.redirectUri + "&code=" + authCode);
  if (request.status == 200) {
    monzo.accessToken = JSON.parse(request.responseText).access_token;
    monzo.accessExpires = Date.now() + JSON.parse(request.responseText).expires_in * 1000;
    // clear the variables we were using while getting an access token
    delete monzo["clientId"];
    delete monzo["clientSecret"];
    delete monzo["redirectUri"];
    delete monzo["state"];
    // get the account id
    var request = new XMLHttpRequest();
    request.open("GET", "https://api.monzo.com/accounts", false);
    request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
    request.send();
    monzo.accountId = JSON.parse(request.responseText).accounts[0].id;
    monzo.cardId = monzoGetCards(monzo).id;
  }
}

// HTML functions
function monzoTransactionHTML(monzo, id) {
  // alasql
  try {
    alasql("drop table transactions")
  } catch(err) {
    console.log(err.message);
  }
  try {
    alasql("drop table merchants")
  } catch(err) {
    console.log(err.message);
  }
  alasql('CREATE TABLE transactions (' +
    'id STRING PRIMARY KEY,' +
    'created Date,' +
    'settled Date,' +
    'is_load BOOLEAN,' +
    'merchant_id STRING,' +
    'description STRING,' +
    'currency STRING,' +
    'amount INT,' +
    'account_balance INT,' +
    'category STRING,' +
    'notes STRING);');
  alasql('CREATE TABLE merchants (' +
    'id STRING PRIMARY KEY,' +
    'name STRING,' +
    'address STRING,' +
    'city STRING,' +
    'region STRING,' +
    'country STRING,' +
    'postcode STRING,' +
    'latitude DOUBLE PRECISION,' +
    'longitude DOUBLE PRECISION,' +
    'zoom_level INT,' +
    'group_id STRING,' +
    'logo STRING,' +
    'emoji STRING,' +
    'category STRING);');
  // create a fake merchant for top-ups
  alasql('INSERT INTO merchants VALUES("merch_monzo", "Monzo", null, null, null, null, null, null, null, null, null, null, null, null);');

  transactions = monzoGetTransactions(monzo, true);
  for (var i = 0; i < transactions.length; i++) {
    var merchantId;
    if (transactions[i].merchant == null) {
      merchantId = null;
      if (transactions[i].is_load) {
        merchantId = "merch_monzo";
      }
    } else {
      merchantId = transactions[i].merchant.id;
      if (alasql('SELECT id from merchants where id="' + merchantId + '"').length == 0) {
        // add merchant to alasql
        alasql('INSERT INTO merchants VALUES(' +
          '"' + transactions[i].merchant.id + '"' + ',' +
          '"' + transactions[i].merchant.name + '"' + ',' +
          '"' + transactions[i].merchant.address.address + '"' + ',' +
          '"' + transactions[i].merchant.address.city + '"' + ',' +
          '"' + transactions[i].merchant.address.region + '"' + ',' +
          '"' + transactions[i].merchant.address.country + '"' + ',' +
          '"' + transactions[i].merchant.address.postcode + '"' + ',' +
          transactions[i].merchant.address.latitude + ',' +
          transactions[i].merchant.address.longitude + ',' +
          transactions[i].merchant.address.zoom_level + ',' +
          '"' + transactions[i].merchant.group_id + '"' + ',' +
          '"' + transactions[i].merchant.logo + '"' + ',' +
          '"' + transactions[i].merchant.emoji + '"' + ',' +
          '"' + transactions[i].merchant.category + '");');
      }
    }
    alasql('INSERT INTO transactions VALUES(' +
      '"' + transactions[i].id + '"' + ',' +
      '"' + transactions[i].created + '"' + ',' +
      '"' + transactions[i].settled + '"' + ',' +
      transactions[i].is_load + ',' +
      '"' + merchantId + '"' + ',' +
      '"' + transactions[i].description + '"' + ',' +
      '"' + transactions[i].currency + '"' + ',' +
      transactions[i].amount + ',' +
      transactions[i].account_balance + ',' +
      '"' + transactions[i].category + '"' + ',' +
      '"' + transactions[i].notes + '"' + ');');
  }

  var HTML = "";
  HTML += "
" + monzo.name + "
";
  HTML += '<textarea id="sql"></textarea>';
  HTML += '<button type="button" onclick="javascript:monzoSql(document.getElementById(\'sql\').value)" id="searchButton">Search!</button>';
  HTML += '<button type="button" onclick="javascript:monzoSaveQuery(document.getElementById(\'sql\').value)" id="searchButton">Save Query</button>';
  HTML += '

';
  return HTML;
}

function monzoDetailsHTML(monzo, id) {
  var HTML = "";
  var balance = monzoGetBalance(monzo);
  var card = monzoGetCards(monzo);
  HTML += "
Welcome, " + card.name + "!
";
  HTML += "
Balance: £" + (balance.balance*0.01).toFixed(2) + "
";
  HTML += "
You spent £" + (balance.spend_today*0.01).toFixed(2) + " today.
";
  if (card.status == "ACTIVE") {
    HTML += "
Your card (last 4 digits " + card.last_digits + ") is currently active.
";
    HTML += 'Freeze your card
';
  } else if (card.status == "INACTIVE") {
    HTML += "
Your card (last 4 digits " + card.last_digits + ") is currently frozen.
";
    HTML += 'Defrost your card
';
  } else {
    HTML += "
Your card (last 4 digits " + card.last_digits + ") has unknown status!
";
  }
  HTML += "
Saved Queries
";
  HTML += '

';
  return HTML;
}

// other functions
function monzoGetBalance(monzo) {
  var request = new XMLHttpRequest();
  request.open("GET", "https://api.monzo.com/balance?account_id=" + monzo.accountId, false);
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  return JSON.parse(request.responseText);
}

function monzoGetCards(monzo) {
  var request = new XMLHttpRequest();
  request.open("GET", "https://api.monzo.com/card/list?account_id=" + monzo.accountId, false);
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  return JSON.parse(request.responseText).cards[0];
}

function monzoGetTransactions(monzo, expand) {
  if (typeof expand === "undefined") { expand = false; }
  var request = new XMLHttpRequest();
  if (expand) {
    request.open("GET", "https://api.monzo.com/transactions?account_id=" + monzo.accountId + "&expand[]=merchant", false);
  } else {
    request.open("GET", "https://api.monzo.com/transactions?account_id=" + monzo.accountId, false);
  }
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  return JSON.parse(request.responseText).transactions;
}

function monzoFreezeCard(monzo, targetStatus, id) {
  var request = new XMLHttpRequest();
  request.open("PUT", "https://api.monzo.com/card/toggle?card_id=" + monzo.cardId + "&status=" + targetStatus, false);
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  document.getElementById("accountDetails").innerHTML = monzoDetailsHTML(monzo, id);
  // re-add saved queries
  for (var i = 0; i < monzoSavedQueries.length; i++) {
    document.getElementById("monzoSavedQueries").innerHTML += '
' + monzoSavedQueries[i].name + '
';
  }
}

function monzoSaveQuery(query, name) {
  if (typeof name === "undefined") {
    var name = prompt("What would you like to call this query?");
    if (name == null || name == "") {
      return;
    }
  }
  if (query == "") {
    for (var i = 0; i < monzoSavedQueries.length; i++) {
      if (monzoSavedQueries[i].name == name) {
        document.getElementById("monzoSavedQueries").innerHTML = document.getElementById("monzoSavedQueries").innerHTML.replace('
' + monzoSavedQueries[i].name + '
', '');
        monzoSavedQueries.splice(i, 1);
      }
    }
  } else {
    query = query.replace(";", ""); // remove semicolons because they break stuff...
    query = query.replace("'", "``"); // as do quotes...
    query = query.replace('"', "``");
    document.getElementById("monzoSavedQueries").innerHTML += '
' + name + '
';
    monzoSavedQueries.push({query: query, name: name});
  }
  var cookiePath = new RegExp("https://.+?(/.+?)(?:index.html)?$").exec(document.location.href)[1];
  setCookie("monzoSavedQueries", JSON.stringify(monzoSavedQueries), cookiePath, 28*24); // store queries for 28 days
}

function monzoSetQuery(query) {
  document.getElementById('sql').value = query;
  monzoSql(query);
}

function monzoSql(query) {
  alasql(query.replace(' from ', ' INTO HTML("#transactions", {headers:true}) from ').replace('``', '"'));
}<commit_msg>made global replaces _actually_ global<commit_after>function getMonzo() {
  return {
    // general
    name: "Monzo Account",
    provider: "monzo",

    // auth
    authType: "oauth2",
    accessToken: null,
    accessExpires: -1,
    // variables below used while auth is being negotiated
    clientId: null,
    clientSecret: null,
    state: null,
    redirectUri: null,

    // other variables
    accountId: null,
    cardId: null
  };
}

// auth functions
function monzoAuth(monzo) {
  if (monzo.clientId == null) {
    throw new Error("clientId isn't set and yet auth was called!");
  }
  if (monzo.clientSecret == null) {
    throw new Error("clientSecret isn't set and yet auth was called!");
  }
  if (monzo.state == null) {
    throw new Error("state isn't set and yet auth was called!");
  }
  if (monzo.redirectUri == null) {
    throw new Error("redirectUri isn't set and yet auth was called!");
  }
  window.location = "https://auth.getmondo.co.uk/?client_id=" + monzo.clientId + "&redirect_uri=" + monzo.redirectUri + "&response_type=code&state=" + monzo.state;
}

function monzoCallback(monzo, authCode) {
  if (monzo.clientId == null) {
    throw new Error("clientId isn't set and yet callback was called!");
  }
  if (monzo.clientSecret == null) {
    throw new Error("clientSecret isn't set and yet callback was called!");
  }
  if (monzo.state == null) {
    throw new Error("state isn't set and yet callback was called!");
  }
  if (monzo.redirectUri == null) {
    throw new Error("redirectUri isn't set and yet callback was called!");
  }

  var request = new XMLHttpRequest();
  request.open("POST", "https://api.monzo.com/oauth2/token", false);
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send("grant_type=authorization_code&client_id=" + monzo.clientId + "&client_secret=" + monzo.clientSecret + "&redirect_uri=" + monzo.redirectUri + "&code=" + authCode);
  if (request.status == 200) {
    monzo.accessToken = JSON.parse(request.responseText).access_token;
    monzo.accessExpires = Date.now() + JSON.parse(request.responseText).expires_in * 1000;
    // clear the variables we were using while getting an access token
    delete monzo["clientId"];
    delete monzo["clientSecret"];
    delete monzo["redirectUri"];
    delete monzo["state"];
    // get the account id
    var request = new XMLHttpRequest();
    request.open("GET", "https://api.monzo.com/accounts", false);
    request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
    request.send();
    monzo.accountId = JSON.parse(request.responseText).accounts[0].id;
    monzo.cardId = monzoGetCards(monzo).id;
  }
}

// HTML functions
function monzoTransactionHTML(monzo, id) {
  // alasql
  try {
    alasql("drop table transactions")
  } catch(err) {
    console.log(err.message);
  }
  try {
    alasql("drop table merchants")
  } catch(err) {
    console.log(err.message);
  }
  alasql('CREATE TABLE transactions (' +
    'id STRING PRIMARY KEY,' +
    'created Date,' +
    'settled Date,' +
    'is_load BOOLEAN,' +
    'merchant_id STRING,' +
    'description STRING,' +
    'currency STRING,' +
    'amount INT,' +
    'account_balance INT,' +
    'category STRING,' +
    'notes STRING);');
  alasql('CREATE TABLE merchants (' +
    'id STRING PRIMARY KEY,' +
    'name STRING,' +
    'address STRING,' +
    'city STRING,' +
    'region STRING,' +
    'country STRING,' +
    'postcode STRING,' +
    'latitude DOUBLE PRECISION,' +
    'longitude DOUBLE PRECISION,' +
    'zoom_level INT,' +
    'group_id STRING,' +
    'logo STRING,' +
    'emoji STRING,' +
    'category STRING);');
  // create a fake merchant for top-ups
  alasql('INSERT INTO merchants VALUES("merch_monzo", "Monzo", null, null, null, null, null, null, null, null, null, null, null, null);');

  transactions = monzoGetTransactions(monzo, true);
  for (var i = 0; i < transactions.length; i++) {
    var merchantId;
    if (transactions[i].merchant == null) {
      merchantId = null;
      if (transactions[i].is_load) {
        merchantId = "merch_monzo";
      }
    } else {
      merchantId = transactions[i].merchant.id;
      if (alasql('SELECT id from merchants where id="' + merchantId + '"').length == 0) {
        // add merchant to alasql
        alasql('INSERT INTO merchants VALUES(' +
          '"' + transactions[i].merchant.id + '"' + ',' +
          '"' + transactions[i].merchant.name + '"' + ',' +
          '"' + transactions[i].merchant.address.address + '"' + ',' +
          '"' + transactions[i].merchant.address.city + '"' + ',' +
          '"' + transactions[i].merchant.address.region + '"' + ',' +
          '"' + transactions[i].merchant.address.country + '"' + ',' +
          '"' + transactions[i].merchant.address.postcode + '"' + ',' +
          transactions[i].merchant.address.latitude + ',' +
          transactions[i].merchant.address.longitude + ',' +
          transactions[i].merchant.address.zoom_level + ',' +
          '"' + transactions[i].merchant.group_id + '"' + ',' +
          '"' + transactions[i].merchant.logo + '"' + ',' +
          '"' + transactions[i].merchant.emoji + '"' + ',' +
          '"' + transactions[i].merchant.category + '");');
      }
    }
    alasql('INSERT INTO transactions VALUES(' +
      '"' + transactions[i].id + '"' + ',' +
      '"' + transactions[i].created + '"' + ',' +
      '"' + transactions[i].settled + '"' + ',' +
      transactions[i].is_load + ',' +
      '"' + merchantId + '"' + ',' +
      '"' + transactions[i].description + '"' + ',' +
      '"' + transactions[i].currency + '"' + ',' +
      transactions[i].amount + ',' +
      transactions[i].account_balance + ',' +
      '"' + transactions[i].category + '"' + ',' +
      '"' + transactions[i].notes + '"' + ');');
  }

  var HTML = "";
  HTML += "
" + monzo.name + "
";
  HTML += '<textarea id="sql"></textarea>';
  HTML += '<button type="button" onclick="javascript:monzoSql(document.getElementById(\'sql\').value)" id="searchButton">Search!</button>';
  HTML += '<button type="button" onclick="javascript:monzoSaveQuery(document.getElementById(\'sql\').value)" id="searchButton">Save Query</button>';
  HTML += '

';
  return HTML;
}

function monzoDetailsHTML(monzo, id) {
  var HTML = "";
  var balance = monzoGetBalance(monzo);
  var card = monzoGetCards(monzo);
  HTML += "
Welcome, " + card.name + "!
";
  HTML += "
Balance: £" + (balance.balance*0.01).toFixed(2) + "
";
  HTML += "
You spent £" + (balance.spend_today*0.01).toFixed(2) + " today.
";
  if (card.status == "ACTIVE") {
    HTML += "
Your card (last 4 digits " + card.last_digits + ") is currently active.
";
    HTML += 'Freeze your card
';
  } else if (card.status == "INACTIVE") {
    HTML += "
Your card (last 4 digits " + card.last_digits + ") is currently frozen.
";
    HTML += 'Defrost your card
';
  } else {
    HTML += "
Your card (last 4 digits " + card.last_digits + ") has unknown status!
";
  }
  HTML += "
Saved Queries
";
  HTML += '

';
  return HTML;
}

// other functions
function monzoGetBalance(monzo) {
  var request = new XMLHttpRequest();
  request.open("GET", "https://api.monzo.com/balance?account_id=" + monzo.accountId, false);
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  return JSON.parse(request.responseText);
}

function monzoGetCards(monzo) {
  var request = new XMLHttpRequest();
  request.open("GET", "https://api.monzo.com/card/list?account_id=" + monzo.accountId, false);
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  return JSON.parse(request.responseText).cards[0];
}

function monzoGetTransactions(monzo, expand) {
  if (typeof expand === "undefined") { expand = false; }
  var request = new XMLHttpRequest();
  if (expand) {
    request.open("GET", "https://api.monzo.com/transactions?account_id=" + monzo.accountId + "&expand[]=merchant", false);
  } else {
    request.open("GET", "https://api.monzo.com/transactions?account_id=" + monzo.accountId, false);
  }
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  return JSON.parse(request.responseText).transactions;
}

function monzoFreezeCard(monzo, targetStatus, id) {
  var request = new XMLHttpRequest();
  request.open("PUT", "https://api.monzo.com/card/toggle?card_id=" + monzo.cardId + "&status=" + targetStatus, false);
  request.setRequestHeader("Authorization", "Bearer " + monzo.accessToken);
  request.send();
  document.getElementById("accountDetails").innerHTML = monzoDetailsHTML(monzo, id);
  // re-add saved queries
  for (var i = 0; i < monzoSavedQueries.length; i++) {
    document.getElementById("monzoSavedQueries").innerHTML += '
' + monzoSavedQueries[i].name + '
';
  }
}

function monzoSaveQuery(query, name) {
  if (typeof name === "undefined") {
    var name = prompt("What would you like to call this query?");
    if (name == null || name == "") {
      return;
    }
  }
  if (query == "") {
    for (var i = 0; i < monzoSavedQueries.length; i++) {
      if (monzoSavedQueries[i].name == name) {
        document.getElementById("monzoSavedQueries").innerHTML = document.getElementById("monzoSavedQueries").innerHTML.replace('
' + monzoSavedQueries[i].name + '
', '');
        monzoSavedQueries.splice(i, 1);
      }
    }
  } else {
    query = query.replace(";", ""); // remove semicolons because they break stuff...
    query = query.replace(/'/g, "``"); // as do quotes...
    query = query.replace(/"/g, "``");
    document.getElementById("monzoSavedQueries").innerHTML += '
' + name + '
';
    monzoSavedQueries.push({query: query, name: name});
  }
  var cookiePath = new RegExp("https://.+?(/.+?)(?:index.html)?$").exec(document.location.href)[1];
  setCookie("monzoSavedQueries", JSON.stringify(monzoSavedQueries), cookiePath, 28*24); // store queries for 28 days
}

function monzoSetQuery(query) {
  document.getElementById('sql').value = query.replace(/``/g, '"');
  monzoSql(query);
}

function monzoSql(query) {
  alasql(query.replace(' from ', ' INTO HTML("#transactions", {headers:true}) from '));
}<|endoftext|>


<commit_before>/* this file contains all grammatical productions in ECMA-262 edition 5.1 */
// most unicode and whitespace characters have been omitted

var $, _, \u0078, x$, x_, x\u0030, xa, x0, x0a, x0123456789,
  qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM;

null; true; false;

0; 00; 1234567890; 01234567;
0.; 0.00; 10.00; .0; .00
0e0; 0E0; 0.e0; 0.00e+0; .00e-0;
0x0; 0X0; 0x0123456789abcdefABCDEF;

""; "'"; "\'\"\\\b\f\n\r\t\v\0";
"\1\00\400\000";
"\x01\x23\x45\x67\x89\xAB\xCD\xEF";
"\u0123\u4567\u89AB\uCDEF";

''; '"'; '\'\"\\\b\f\n\r\t\v\0';
'\1\00\400\000';
'\x01\x23\x45\x67\x89\xAB\xCD\xEF';
'\u0123\u4567\u89AB\uCDEF';

/x/; /|/; /|||/;
/^$\b\B/; /(?=(?!(?:(.))))/;
/a.\f\n\r\t\v\0\[\-\/\\\x00\u0000/; /\d\D\s\S\w\W/;
/\ca\cb\cc\cd\ce\cf\cg\ch\ci\cj\ck\cl\cm\cn\co\cp\cq\cr\cs\ct\cu\cv\cw\cx\cy\cz/;
/\cA\cB\cC\cD\cE\cF\cG\cH\cI\cJ\cK\cL\cM\cN\cO\cP\cQ\cR\cS\cT\cU\cV\cW\cX\cY\cZ/;
/[a-z-]/; /[^\b\-^]/; /[/\]\\]/;
/./i; /./g; /./m; /./igm;
/.*/; /.*?/; /.+/; /.+?/; /.?/; /.??/;
/.{0}/; /.{0,}/; /.{0,0}/;

this;

x;

[]; [,]; [0]; [0,]; [0,0]; [0,0,]; [0,,0]; [,,];

({}); ({x:0}); ({x:0,y:0}); ({x:0,}); ({x:0,y:0,});
({0:0}); ({0.:0}); ({0.0:0}); ({.0:0}); ({0e0:0}); ({0x0:0});
({get x() {}, set x(y) {}});

0..a;

0[0];

// this function makes the NewExpression and CallExpression tests not throw at runtime
x = function f(){ return f; }; x[0] = x; x.a = x;

new x(); new new x()();
new x[0](); new x.a(); new x[0].a(); new x.a[0]();
new x; new new x; new new x();
new new x().a; new new x()[0];

x++; x--;

delete void typeof+-~!x; ++x; --x;

0*0; 0/0; 0%0;

0+0; 0-0;

0<<0; 0>>0; 0>>>0;

0<0; 0>0; 0<=0; 0>=0;
0 instanceof function(){};
0 in{};

0==0; 0!=0; 0===0; 0!==0;

0&0; 0^0; 0|0; 0&&0; 0||0;

0?0:0; 0?0?0:0:0; 0||0?x=0:x=0;

x=0; x*=0; x/=0; x%=0; x+=0; x-=0;
x<<=0; x>>=0; x>>>=0; x&=0; x^=0; x|=0;

0,0; 0,0,0; x=0,x=0;

{} {;} {0} {0;} {0;0} {0;0;}

var x; var x,y; var x,y,z;
var x=0; var x=0,y; var x,y=0; var x=0,y=0;

;

if(0); if(0);else;

do;while(0);
while(0);
for(;;)break; for(0;0;0); for((0 in[]);0;);
for(var a;;)break; for(var a,b;0;0);
for(var a=0;;)break; for(var a=(0 in[]);0;);
for(x in{}); for(var x in{});
for(var x=[]in{}); for(var x=(0 in[])in{});

for(;0;)continue; x:for(;0;)continue x;

for(;;)break; x:for(;;)break x;
switch(0){case 0:break;}

function f(){ return; }
function f(){ return 0; }

with(0);

switch(0){} switch(0){case 0:} switch(0){case 0:case 0:}
switch(0){default:} switch(0){case 0:default:case 0:}
switch(0){case 0:;} switch(0){case 0:;;}
switch(0){default:;} switch(0){default:;;}

x:; x:y:;

try { throw 0; }catch(x){}

try{}catch(x){}
try{}finally{}
try{}catch(x){}finally{}

debugger;

function f(){}
function f(x){}
function f(x,y){}
function f(){ function f(){} }

(function(){});
(function(x){});
(function(x,y){});
(function(){ function f(){} });
(function f(){});
(function f(x){});
(function f(x,y){});
(function f(){ function f(){} });
<commit_msg>add missing CallExpression coverage<commit_after>/* this file contains all grammatical productions in ECMA-262 edition 5.1 */
// most unicode and whitespace characters have been omitted

var $, _, \u0078, x$, x_, x\u0030, xa, x0, x0a, x0123456789,
  qwertyuiopasdfghjklzxcvbnm, QWERTYUIOPASDFGHJKLZXCVBNM;

null; true; false;

0; 00; 1234567890; 01234567;
0.; 0.00; 10.00; .0; .00
0e0; 0E0; 0.e0; 0.00e+0; .00e-0;
0x0; 0X0; 0x0123456789abcdefABCDEF;

""; "'"; "\'\"\\\b\f\n\r\t\v\0";
"\1\00\400\000";
"\x01\x23\x45\x67\x89\xAB\xCD\xEF";
"\u0123\u4567\u89AB\uCDEF";

''; '"'; '\'\"\\\b\f\n\r\t\v\0';
'\1\00\400\000';
'\x01\x23\x45\x67\x89\xAB\xCD\xEF';
'\u0123\u4567\u89AB\uCDEF';

/x/; /|/; /|||/;
/^$\b\B/; /(?=(?!(?:(.))))/;
/a.\f\n\r\t\v\0\[\-\/\\\x00\u0000/; /\d\D\s\S\w\W/;
/\ca\cb\cc\cd\ce\cf\cg\ch\ci\cj\ck\cl\cm\cn\co\cp\cq\cr\cs\ct\cu\cv\cw\cx\cy\cz/;
/\cA\cB\cC\cD\cE\cF\cG\cH\cI\cJ\cK\cL\cM\cN\cO\cP\cQ\cR\cS\cT\cU\cV\cW\cX\cY\cZ/;
/[a-z-]/; /[^\b\-^]/; /[/\]\\]/;
/./i; /./g; /./m; /./igm;
/.*/; /.*?/; /.+/; /.+?/; /.?/; /.??/;
/.{0}/; /.{0,}/; /.{0,0}/;

this;

x;

[]; [,]; [0]; [0,]; [0,0]; [0,0,]; [0,,0]; [,,];

({}); ({x:0}); ({x:0,y:0}); ({x:0,}); ({x:0,y:0,});
({0:0}); ({0.:0}); ({0.0:0}); ({.0:0}); ({0e0:0}); ({0x0:0});
({get x() {}, set x(y) {}});

0..a;

0[0];

// this function makes the NewExpression and CallExpression tests not throw at runtime
x = function f(){ return f; }; x[0] = x; x.a = x;

new x(); new new x()();
new x[0](); new x.a(); new x[0].a(); new x.a[0]();
new x; new new x; new new x();
new new x().a; new new x()[0];

x(); x()(); x(x); x(x, x);
x.a().a(); x[0]()[0](); x().a[0]();

x++; x--;

delete void typeof+-~!x; ++x; --x;

0*0; 0/0; 0%0;

0+0; 0-0;

0<<0; 0>>0; 0>>>0;

0<0; 0>0; 0<=0; 0>=0;
0 instanceof function(){};
0 in{};

0==0; 0!=0; 0===0; 0!==0;

0&0; 0^0; 0|0; 0&&0; 0||0;

0?0:0; 0?0?0:0:0; 0||0?x=0:x=0;

x=0; x*=0; x/=0; x%=0; x+=0; x-=0;
x<<=0; x>>=0; x>>>=0; x&=0; x^=0; x|=0;

0,0; 0,0,0; x=0,x=0;

{} {;} {0} {0;} {0;0} {0;0;}

var x; var x,y; var x,y,z;
var x=0; var x=0,y; var x,y=0; var x=0,y=0;

;

if(0); if(0);else;

do;while(0);
while(0);
for(;;)break; for(0;0;0); for((0 in[]);0;);
for(var a;;)break; for(var a,b;0;0);
for(var a=0;;)break; for(var a=(0 in[]);0;);
for(x in{}); for(var x in{});
for(var x=[]in{}); for(var x=(0 in[])in{});

for(;0;)continue; x:for(;0;)continue x;

for(;;)break; x:for(;;)break x;
switch(0){case 0:break;}

function f(){ return; }
function f(){ return 0; }

with(0);

switch(0){} switch(0){case 0:} switch(0){case 0:case 0:}
switch(0){default:} switch(0){case 0:default:case 0:}
switch(0){case 0:;} switch(0){case 0:;;}
switch(0){default:;} switch(0){default:;;}

x:; x:y:;

try { throw 0; }catch(x){}

try{}catch(x){}
try{}finally{}
try{}catch(x){}finally{}

debugger;

function f(){}
function f(x){}
function f(x,y){}
function f(){ function f(){} }

(function(){});
(function(x){});
(function(x,y){});
(function(){ function f(){} });
(function f(){});
(function f(x){});
(function f(x,y){});
(function f(){ function f(){} });
<|endoftext|>


<commit_before>/* globals popover isRtl */

this.popover = {
	renderedPopover: null,
	open(config) {
		this.renderedPopover = Blaze.renderWithData(Template.popover, config, document.body);
	},
	close() {
		Blaze.remove(this.renderedPopover);

		const activeElement = this.renderedPopover.dataVar.curValue.activeElement;
		if (activeElement) {
			$(activeElement).removeClass('active');
		}
	}
};

Template.popover.onRendered(function() {
	if (this.data.onRendered) {
		this.data.onRendered();
	}

	$('.rc-popover').click(function(e) {
		if (e.currentTarget === e.target) {
			popover.close();
		}
	});

	const activeElement = this.data.activeElement;
	const popoverContent = this.firstNode.children[0];
	const position = this.data.position;
	const customCSSProperties = this.data.customCSSProperties;

	if (position) {
		popoverContent.style.top = `${ position.top }px`;
		popoverContent.style.left = `${ position.left }px`;
	} else {
		const popoverWidth = popoverContent.offsetWidth;
		const popoverHeight = popoverContent.offsetHeight;
		const popoverHeightHalf = popoverHeight / 2;
		const windowWidth = window.innerWidth;
		const windowHeight = window.innerHeight;
		const mousePosition = this.data.mousePosition;

		let top;
		if (mousePosition.y <= popoverHeightHalf) {
			top = 10;
		} else if (mousePosition.y + popoverHeightHalf > windowHeight) {
			top = windowHeight - popoverHeight - 10;
		} else {
			top = mousePosition.y - popoverHeightHalf;
		}

		let left;
		if (mousePosition.x + popoverWidth >= windowWidth) {
			left = mousePosition.x - popoverWidth;
		} else if (mousePosition.x <= popoverWidth) {
			left = isRtl() ? mousePosition.x + 10 : 10;
		} else if (mousePosition.x <= windowWidth / 2) {
			left = mousePosition.x;
		} else {
			left = mousePosition.x - popoverWidth;
		}

		popoverContent.style.top = `${ top }px`;
		popoverContent.style.left = `${ left }px`;
	}

	if (customCSSProperties) {
		Object.keys(customCSSProperties).forEach(function(property) {
			popoverContent.style[property] = customCSSProperties[property];
		});
	}

	if (activeElement) {
		$(activeElement).addClass('active');
	}

	popoverContent.style.opacity = 1;
});

Template.popover.events({
	'click [data-type="messagebox-action"]'(event, t) {
		const action = RocketChat.messageBox.actions.getById(event.currentTarget.dataset.id);
		if ((action[0] != null ? action[0].action : undefined) != null) {
			action[0].action({rid: t.data.data.rid, messageBox: document.querySelector('.rc-message-box'), element: event.currentTarget, event});
			popover.close();
		}
	},
	'click [data-type="message-action"]'(e, t) {
		const button = RocketChat.MessageAction.getButtonById(e.currentTarget.dataset.id);
		if ((button != null ? button.action : undefined) != null) {
			button.action.call(t.data.data, e, t.data.instance);
			popover.close();
		}
	},
	'click [data-type="set-state"]'(e) {
		AccountBox.setStatus(e.currentTarget.dataset.id);
		RocketChat.callbacks.run('userStatusManuallySet', e.currentTarget.dataset.status);
		popover.close();
	},
	'click [data-type="open"]'(e) {
		const data = e.currentTarget.dataset;

		switch (data.id) {
			case 'account':
				SideNav.setFlex('accountFlex');
				SideNav.openFlex();
				FlowRouter.go('account');
				break;
			case 'logout':
				const user = Meteor.user();
				Meteor.logout(() => {
					RocketChat.callbacks.run('afterLogoutCleanUp', user);
					Meteor.call('logoutCleanUp', user);
					FlowRouter.go('home');
				});
				break;
			case 'administration':
				SideNav.setFlex('adminFlex');
				SideNav.openFlex();
				FlowRouter.go('admin-info');
				break;
		}

		if (data.href) {
			FlowRouter.go(data.href);
		}

		if (data.sideNav) {
			SideNav.setFlex(data.sideNav);
			SideNav.openFlex();
		}

		popover.close();
	},
	'click [data-type="sidebar-item"]'(e, instance) {
		popover.close();
		const { rid, name, template } = instance.data.data;

		if (e.currentTarget.dataset.id === 'hide') {
			let warnText;
			switch (template) {
				case 'c': warnText = 'Hide_Room_Warning'; break;
				case 'p': warnText = 'Hide_Group_Warning'; break;
				case 'd': warnText = 'Hide_Private_Warning'; break;
				case 'l': warnText = 'Hide_Livechat_Warning'; break;
			}

			return swal({
				title: t('Are_you_sure'),
				text: warnText ? t(warnText, name) : '',
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#DD6B55',
				confirmButtonText: t('Yes_hide_it'),
				cancelButtonText: t('Cancel'),
				closeOnConfirm: true,
				html: false
			}, function() {
				if (['channel', 'group', 'direct'].includes(FlowRouter.getRouteName()) && (Session.get('openedRoom') === rid)) {
					FlowRouter.go('home');
				}

				Meteor.call('hideRoom', rid, function(err) {
					if (err) {
						handleError(err);
					} else if (rid === Session.get('openedRoom')) {
						Session.delete('openedRoom');
					}
				});
			});
		} else {
			let warnText;
			switch (template) {
				case 'c': warnText = 'Leave_Room_Warning'; break;
				case 'p': warnText = 'Leave_Group_Warning'; break;
				case 'd': warnText = 'Leave_Private_Warning'; break;
				case 'l': warnText = 'Hide_Livechat_Warning'; break;
			}

			swal({
				title: t('Are_you_sure'),
				text: t(warnText, name),
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#DD6B55',
				confirmButtonText: t('Yes_leave_it'),
				cancelButtonText: t('Cancel'),
				closeOnConfirm: false,
				html: false
			}, function(isConfirm) {
				if (isConfirm) {
					Meteor.call('leaveRoom', rid, function(err) {
						if (err) {
							swal({
								title: t('Warning'),
								text: handleError(err, false),
								type: 'warning',
								html: false
							});
						} else {
							swal.close();
							if (['channel', 'group', 'direct'].includes(FlowRouter.getRouteName()) && (Session.get('openedRoom') === rid)) {
								FlowRouter.go('home');
							}

							RoomManager.close(rid);
						}
					});
				} else {
					swal.close();
				}
			});
		}
	}
});
<commit_msg>Adapt warning-text for leaving a room. Fixes #92<commit_after>/* globals popover isRtl */

this.popover = {
	renderedPopover: null,
	open(config) {
		this.renderedPopover = Blaze.renderWithData(Template.popover, config, document.body);
	},
	close() {
		Blaze.remove(this.renderedPopover);

		const activeElement = this.renderedPopover.dataVar.curValue.activeElement;
		if (activeElement) {
			$(activeElement).removeClass('active');
		}
	}
};

Template.popover.onRendered(function() {
	if (this.data.onRendered) {
		this.data.onRendered();
	}

	$('.rc-popover').click(function(e) {
		if (e.currentTarget === e.target) {
			popover.close();
		}
	});

	const activeElement = this.data.activeElement;
	const popoverContent = this.firstNode.children[0];
	const position = this.data.position;
	const customCSSProperties = this.data.customCSSProperties;

	if (position) {
		popoverContent.style.top = `${ position.top }px`;
		popoverContent.style.left = `${ position.left }px`;
	} else {
		const popoverWidth = popoverContent.offsetWidth;
		const popoverHeight = popoverContent.offsetHeight;
		const popoverHeightHalf = popoverHeight / 2;
		const windowWidth = window.innerWidth;
		const windowHeight = window.innerHeight;
		const mousePosition = this.data.mousePosition;

		let top;
		if (mousePosition.y <= popoverHeightHalf) {
			top = 10;
		} else if (mousePosition.y + popoverHeightHalf > windowHeight) {
			top = windowHeight - popoverHeight - 10;
		} else {
			top = mousePosition.y - popoverHeightHalf;
		}

		let left;
		if (mousePosition.x + popoverWidth >= windowWidth) {
			left = mousePosition.x - popoverWidth;
		} else if (mousePosition.x <= popoverWidth) {
			left = isRtl() ? mousePosition.x + 10 : 10;
		} else if (mousePosition.x <= windowWidth / 2) {
			left = mousePosition.x;
		} else {
			left = mousePosition.x - popoverWidth;
		}

		popoverContent.style.top = `${ top }px`;
		popoverContent.style.left = `${ left }px`;
	}

	if (customCSSProperties) {
		Object.keys(customCSSProperties).forEach(function(property) {
			popoverContent.style[property] = customCSSProperties[property];
		});
	}

	if (activeElement) {
		$(activeElement).addClass('active');
	}

	popoverContent.style.opacity = 1;
});

Template.popover.events({
	'click [data-type="messagebox-action"]'(event, t) {
		const action = RocketChat.messageBox.actions.getById(event.currentTarget.dataset.id);
		if ((action[0] != null ? action[0].action : undefined) != null) {
			action[0].action({rid: t.data.data.rid, messageBox: document.querySelector('.rc-message-box'), element: event.currentTarget, event});
			popover.close();
		}
	},
	'click [data-type="message-action"]'(e, t) {
		const button = RocketChat.MessageAction.getButtonById(e.currentTarget.dataset.id);
		if ((button != null ? button.action : undefined) != null) {
			button.action.call(t.data.data, e, t.data.instance);
			popover.close();
		}
	},
	'click [data-type="set-state"]'(e) {
		AccountBox.setStatus(e.currentTarget.dataset.id);
		RocketChat.callbacks.run('userStatusManuallySet', e.currentTarget.dataset.status);
		popover.close();
	},
	'click [data-type="open"]'(e) {
		const data = e.currentTarget.dataset;

		switch (data.id) {
			case 'account':
				SideNav.setFlex('accountFlex');
				SideNav.openFlex();
				FlowRouter.go('account');
				break;
			case 'logout':
				const user = Meteor.user();
				Meteor.logout(() => {
					RocketChat.callbacks.run('afterLogoutCleanUp', user);
					Meteor.call('logoutCleanUp', user);
					FlowRouter.go('home');
				});
				break;
			case 'administration':
				SideNav.setFlex('adminFlex');
				SideNav.openFlex();
				FlowRouter.go('admin-info');
				break;
		}

		if (data.href) {
			FlowRouter.go(data.href);
		}

		if (data.sideNav) {
			SideNav.setFlex(data.sideNav);
			SideNav.openFlex();
		}

		popover.close();
	},
	'click [data-type="sidebar-item"]'(e, instance) {
		popover.close();
		const { rid, name, template } = instance.data.data;

		if (e.currentTarget.dataset.id === 'hide') {
			let warnText;
			switch (template) {
				case 'c': warnText = 'Hide_Room_Warning'; break;
				case 'p': warnText = 'Hide_Group_Warning'; break;
				case 'd': warnText = 'Hide_Private_Warning'; break;
				case 'l': warnText = 'Hide_Livechat_Warning'; break;
			}

			return swal({
				title: t('Are_you_sure'),
				text: warnText ? t(warnText, name) : '',
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#DD6B55',
				confirmButtonText: t('Yes_hide_it'),
				cancelButtonText: t('Cancel'),
				closeOnConfirm: true,
				html: false
			}, function() {
				if (['channel', 'group', 'direct'].includes(FlowRouter.getRouteName()) && (Session.get('openedRoom') === rid)) {
					FlowRouter.go('home');
				}

				Meteor.call('hideRoom', rid, function(err) {
					if (err) {
						handleError(err);
					} else if (rid === Session.get('openedRoom')) {
						Session.delete('openedRoom');
					}
				});
			});
		} else {
			let warnText;
			switch (template) {
				case 'c': warnText = 'Leave_Room_Warning'; break;
				case 'p': warnText = 'Leave_Group_Warning'; break;
				case 'd': warnText = 'Leave_Private_Warning'; break;
				case 'l': warnText = 'Hide_Livechat_Warning'; break;
			}

			swal({
				title: t('Are_you_sure'),
				text: warnText ? t(warnText, name) : '',
				type: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#DD6B55',
				confirmButtonText: t('Yes_leave_it'),
				cancelButtonText: t('Cancel'),
				closeOnConfirm: false,
				html: false
			}, function(isConfirm) {
				if (isConfirm) {
					Meteor.call('leaveRoom', rid, function(err) {
						if (err) {
							swal({
								title: t('Warning'),
								text: handleError(err, false),
								type: 'warning',
								html: false
							});
						} else {
							swal.close();
							if (['channel', 'group', 'direct'].includes(FlowRouter.getRouteName()) && (Session.get('openedRoom') === rid)) {
								FlowRouter.go('home');
							}

							RoomManager.close(rid);
						}
					});
				} else {
					swal.close();
				}
			});
		}
	}
});
<|endoftext|>