<commit_before>const CompositeDisposable = require('atom').CompositeDisposable;
const SemanticolorGrammarFactory = require('./semanticolor-grammar');
const semanticolorConfig = require('./config');

const _ = require('lodash');
const Sugar = require('sugar');
const debug = require('debug')('semanticolor');

const fs = require('fs');
const path = require('path');

let lessFile = path.join(__dirname, '..', 'styles', 'semanticolor.less');
let grammarListFile = path.join(__dirname, 'grammars.txt');
let ignoredFileTypes = ['md', 'sh', 'cmd', 'bat', 'diff', 'Dockerfile', 'json'];
let forceIncludeFileTypes = ['php', 'html', 'xml', 'vue'];

let grammars = {};
let config = {
	colorOptions: {
		description: 'Options that affect how colors are generated.',
		type: 'object',
		order: 0,
		properties: {
			hues: {
				type: 'integer',
				title: 'hues',
				description: 'Fewer colors may make them easier to distinguish, but they will be repeated more often.',
				minimum: 8,
				'default': 700,
				maximum: 700,
				order: 1,
			},
			saturation: {
				type: 'number',
				title: 'saturation',
				description: 'Color stauration (0 to 100%).',
				minimum: 0.1,
				'default': 90,
				maximum: 100,
				order: 2,
			},
			luminosity: {
				type: 'number',
				title: 'luminosity',
				description: 'Color luminosity (0 to 100%).',
				minimum: 0.1,
				'default': 50,
				maximum: 100,
				order: 3,
			},
			fade: {
				type: 'number',
				title: 'fade',
				description: 'Color fade (0 to 100%).',
				minimum: 0.1,
				'default': 40,
				maximum: 100,
				order: 4,
			},
		},
	},
	defaults: Object.assign({ order: 1 }, semanticolorConfig.base),
};

let grammarList = [];
try {
	grammarList = Sugar.Array.compact(fs.readFileSync(grammarListFile, { encoding: 'utf-8' })
		.split(/\r\n|\r|\n/), true);
} catch (e) {
	grammarList = [];
}

for (let i = 0; i < grammarList.length; i++) {
	addGrammarToConfig(grammarList[i]);
}

function getGrammarName(grammar) {
	let result = grammar.name + ' (' + grammar.packageName + ')';
	return result;
}

function getGrammarParamNameFromGrammarName(grammarName) {
	return Sugar.String.camelize(Sugar.String.parameterize(grammarName), false);
}

function addGrammarToConfig(grammarName) {
	let options = Sugar.Object.clone(semanticolorConfig.empty);
	options.title = grammarName;
	config[getGrammarParamNameFromGrammarName(grammarName)] = options;
}

function writeGrammarListFile() {
	let fileContents = '';
	for (let i = 0; i < grammarList.length; i++) {
		fileContents += grammarList[i] + '\n';
	}
	fs.writeFileSync(grammarListFile, fileContents, { encoding: 'utf-8' });
}

let defaults = {};

function getOptions(options) {
	let selector = {};
	for (let key in options) {
		let scope = key.replace(/_/g, '.');
		selector[scope] = options[key];
	}
	return selector;
}

function enable(editor) {
	let grammar = editor.getGrammar();
	let paramName = getGrammarParamNameFromGrammarName(getGrammarName(grammar));
	if (grammars[paramName]) {
		editor.setGrammar(grammars[paramName]);
	}
}

let Semanticolor = {
	config,
	disposables: new CompositeDisposable(),
	updateLessStylesheet: function () {
		let cfg = atom.config.get('semanticolor').colorOptions;
		let less = makeLess(cfg.hues, cfg.saturation, cfg.luminosity, cfg.fade);
		let written = false;
		try {
			let currentLess = fs.readFileSync(lessFile, { encoding: 'utf-8' });
			if (currentLess !== less) {
				fs.writeFileSync(lessFile, less, { encoding: 'utf-8' });
				written = true;
			}
			if (written) {
				atom.notifications.addSuccess('Rewrote new colors...', { detail: 'Reloading with stylesheet of ' + cfg.hues + ' possible colors.' });
			}
		} catch (e) {
			atom.notifications.addError('No initial colors configured...', {
				detail: 'Updating stylesheet with default of ' + this.config.colorOptions.hues.default +
					' possible colors.',
			});
			try {
				less = makeLess(this.config.colorOptions.hues.default, this.config.colorOptions.saturation.default,
					this.config.colorOptions.luminosity.default, this.config.colorOptions.fade.default);
				written = fs.writeFileSync(lessFile, less, { encoding: 'utf-8' });
			} catch (err) {
				debug(err);
				atom.notifications.addError(e.code + ' : ' + e.message, { detail: 'Something failed. Open an issue with me!' });
			}
		}

		return written;

		function makeLess(hues, saturation, luminosity, fade) {
			return '@hues: ' + hues + ';\n' +
				'@saturation: ' + saturation + '%;\n' +
				'@luminosity: ' + luminosity + '%;\n' +
				'@fade: ' + fade + '%;';
		}
	},
	activate: function () {
		this.updateLessStylesheet(true);
		this.deactivated = false;
		let cfg = atom.config.get('semanticolor');
		for (let key in cfg) {
			if (key === 'colorOptions') {
				continue;
			}
			for (let scope in cfg[key]) {
				if (!semanticolorConfig.empty.properties[scope]) {
					delete cfg[key][scope];
				}
			}
		}
		atom.config.set('semanticolor', cfg);

		let temp = atom.grammars.getGrammars();
		for (let i = 0; i < temp.length; i++) {
			createGrammar(temp[i]);
		}

		atom.grammars.onDidAddGrammar(function (grammar) {
			// Don't bother on unload
			if (!atom.workspace) {
				return;
			}

			createGrammar(grammar);
		});

		function createGrammar(grammar) {
			let paramName = tryAddGrammarToConfig(grammar);
			if (paramName) {
				setTimeout(() => {
					let cfg = atom.config.get('semanticolor');
					if (paramName && cfg[paramName].enabled) {
						let options = getOptions(cfg[paramName]);
						grammars[paramName] = SemanticolorGrammarFactory.create(grammar, defaults, options, cfg.colorOptions.hues);
					}
					// Activate grammar on existing text editors with matching grammar
					atom.workspace.getTextEditors()
						.filter(editor => editor.getGrammar().name == grammar.name)
						.map(enable);
				});
			}
		}

		function tryAddGrammarToConfig(grammar) {
			let grammarName = getGrammarName(grammar);
			let supported = isSupportedGrammar(grammar);
			let inGrammarList = grammarList.includes(grammarName);

			if (inGrammarList && supported) {
				return getGrammarParamNameFromGrammarName(grammarName);
			} else if (inGrammarList) {
				Sugar.Array.remove(grammarList, grammarName);
				writeGrammarListFile();
				debug('removed ' + grammarName, grammar);
				setTimeout(Semanticolor.reload);
				return null;
			}

			if (supported) {
				grammarList.push(grammarName);
				writeGrammarListFile();
				addGrammarToConfig(grammarName);
				debug('added ' + grammarName, grammar);
				setTimeout(Semanticolor.reload);
				return getGrammarParamNameFromGrammarName(grammarName);
			}
			return null;
		}

		function isSupportedGrammar(grammar) {
			let result = false;
			if (grammar.packageName !== SemanticolorGrammarFactory.packageName &&
				grammar.fileTypes.length > 0 &&
				((grammar.scopeName.includes('source') &&
						Sugar.Array.intersect(grammar.fileTypes, ignoredFileTypes).length == 0) ||
					Sugar.Array.intersect(grammar.fileTypes, forceIncludeFileTypes).length > 0)) {
				result = true;
			}
			return result;
		}

		this.disposables.add(atom.workspace.observeTextEditors(enable));

		this.disposables.add(atom.config.onDidChange('semanticolor', function (change) {
			if (Semanticolor.deactivated) {return;}
			_.debounce(function () {
				Semanticolor.updateLessStylesheet(change.newValue.colorOptions.hues === change.oldValue.colorOptions.hues);
				let reload = !Sugar.Object.isEqual(change.newValue.colorOptions.hues, change.oldValue.colorOptions.hues);
				for (let prop in change.newValue) {
					if (prop !== 'colorOptions' &&
						!Sugar.Object.isEqual(change.newValue[prop], change.oldValue[prop])) {
						reload = true;
						break;
					}
				}
				if (reload) {
					setTimeout(Semanticolor.reload);
				}
			}, 1000)();
		}));

		Semanticolor.reload();
	},
	//testing testing

	reload: function () {
		if (this.deactivated) {
			return;
		}
		let cfg = atom.config.get('semanticolor');
		defaults = getOptions(cfg.defaults);
		for (let prop in cfg) {
			if (prop !== 'colorOptions' && prop !== 'defaults' && grammars[prop]) {
				grammars[prop].defaults = defaults;
				grammars[prop].options = getOptions(cfg[prop]);
				grammars[prop].colorDiversity = cfg.colorOptions.hues;
				for (let editor of atom.workspace.getTextEditors()) {
					if (editor.getGrammar() === grammars[prop]) {
						editor.setGrammar(grammars[prop].__proto__);
					}
					if (!this.deactivated && cfg[prop].enabled) {
						enable(editor);
					}
				}
			}
		}
	},

	deactivate: function () {
		this.deactivated = true;
		let disposable = this.disposables;
		this.disposables = new CompositeDisposable();
		return disposable.dispose();
	},
};

module.exports = Semanticolor;
<commit_msg>fix error when first installing a new language<commit_after>const CompositeDisposable = require('atom').CompositeDisposable;
const SemanticolorGrammarFactory = require('./semanticolor-grammar');
const semanticolorConfig = require('./config');

const _ = require('lodash');
const Sugar = require('sugar');
const debug = require('debug')('semanticolor');

const fs = require('fs');
const path = require('path');

let lessFile = path.join(__dirname, '..', 'styles', 'semanticolor.less');
let grammarListFile = path.join(__dirname, 'grammars.txt');
let ignoredFileTypes = ['md', 'sh', 'cmd', 'bat', 'diff', 'Dockerfile', 'json'];
let forceIncludeFileTypes = ['php', 'html', 'xml', 'vue'];

let grammars = {};
let config = {
	colorOptions: {
		description: 'Options that affect how colors are generated.',
		type: 'object',
		order: 0,
		properties: {
			hues: {
				type: 'integer',
				title: 'hues',
				description: 'Fewer colors may make them easier to distinguish, but they will be repeated more often.',
				minimum: 8,
				'default': 700,
				maximum: 700,
				order: 1,
			},
			saturation: {
				type: 'number',
				title: 'saturation',
				description: 'Color stauration (0 to 100%).',
				minimum: 0.1,
				'default': 90,
				maximum: 100,
				order: 2,
			},
			luminosity: {
				type: 'number',
				title: 'luminosity',
				description: 'Color luminosity (0 to 100%).',
				minimum: 0.1,
				'default': 50,
				maximum: 100,
				order: 3,
			},
			fade: {
				type: 'number',
				title: 'fade',
				description: 'Color fade (0 to 100%).',
				minimum: 0.1,
				'default': 40,
				maximum: 100,
				order: 4,
			},
		},
	},
	defaults: Object.assign({ order: 1 }, semanticolorConfig.base),
};

let grammarList = [];
try {
	grammarList = Sugar.Array.compact(fs.readFileSync(grammarListFile, { encoding: 'utf-8' })
		.split(/\r\n|\r|\n/), true);
} catch (e) {
	grammarList = [];
}

for (let i = 0; i < grammarList.length; i++) {
	addGrammarToConfig(grammarList[i]);
}

function getGrammarName(grammar) {
	let result = grammar.name + ' (' + grammar.packageName + ')';
	return result;
}

function getGrammarParamNameFromGrammarName(grammarName) {
	return Sugar.String.camelize(Sugar.String.parameterize(grammarName), false);
}

function addGrammarToConfig(grammarName) {
	let options = Sugar.Object.clone(semanticolorConfig.empty);
	options.title = grammarName;
	config[getGrammarParamNameFromGrammarName(grammarName)] = options;
}

function writeGrammarListFile() {
	let fileContents = '';
	for (let i = 0; i < grammarList.length; i++) {
		fileContents += grammarList[i] + '\n';
	}
	fs.writeFileSync(grammarListFile, fileContents, { encoding: 'utf-8' });
}

let defaults = {};

function getOptions(options) {
	let selector = {};
	for (let key in options) {
		let scope = key.replace(/_/g, '.');
		selector[scope] = options[key];
	}
	return selector;
}

function enable(editor) {
	let grammar = editor.getGrammar();
	let paramName = getGrammarParamNameFromGrammarName(getGrammarName(grammar));
	if (grammars[paramName]) {
		editor.setGrammar(grammars[paramName]);
	}
}

let Semanticolor = {
	config,
	disposables: new CompositeDisposable(),
	updateLessStylesheet: function () {
		let cfg = atom.config.get('semanticolor').colorOptions;
		let less = makeLess(cfg.hues, cfg.saturation, cfg.luminosity, cfg.fade);
		let written = false;
		try {
			let currentLess = fs.readFileSync(lessFile, { encoding: 'utf-8' });
			if (currentLess !== less) {
				fs.writeFileSync(lessFile, less, { encoding: 'utf-8' });
				written = true;
			}
			if (written) {
				atom.notifications.addSuccess('Rewrote new colors...', { detail: 'Reloading with stylesheet of ' + cfg.hues + ' possible colors.' });
			}
		} catch (e) {
			atom.notifications.addError('No initial colors configured...', {
				detail: 'Updating stylesheet with default of ' + this.config.colorOptions.hues.default +
					' possible colors.',
			});
			try {
				less = makeLess(this.config.colorOptions.hues.default, this.config.colorOptions.saturation.default,
					this.config.colorOptions.luminosity.default, this.config.colorOptions.fade.default);
				written = fs.writeFileSync(lessFile, less, { encoding: 'utf-8' });
			} catch (err) {
				debug(err);
				atom.notifications.addError(e.code + ' : ' + e.message, { detail: 'Something failed. Open an issue with me!' });
			}
		}

		return written;

		function makeLess(hues, saturation, luminosity, fade) {
			return '@hues: ' + hues + ';\n' +
				'@saturation: ' + saturation + '%;\n' +
				'@luminosity: ' + luminosity + '%;\n' +
				'@fade: ' + fade + '%;';
		}
	},
	activate: function () {
		this.updateLessStylesheet(true);
		this.deactivated = false;
		let cfg = atom.config.get('semanticolor');
		for (let key in cfg) {
			if (key === 'colorOptions') {
				continue;
			}
			for (let scope in cfg[key]) {
				if (!semanticolorConfig.empty.properties[scope]) {
					delete cfg[key][scope];
				}
			}
		}
		atom.config.set('semanticolor', cfg);

		let temp = atom.grammars.getGrammars();
		for (let i = 0; i < temp.length; i++) {
			createGrammar(temp[i]);
		}

		atom.grammars.onDidAddGrammar(function (grammar) {
			// Don't bother on unload
			if (!atom.workspace) {
				return;
			}

			createGrammar(grammar);
		});

		function createGrammar(grammar) {
			let paramName = tryAddGrammarToConfig(grammar);
			let cfg = atom.config.get('semanticolor');
			let options;
			if (paramName && cfg[paramName] && cfg[paramName].enabled) {
				options = getOptions(cfg[paramName]);
			} else if (paramName && !cfg[paramName]) {
				options = defaults;
			}
			if (options) {
				grammars[paramName] = SemanticolorGrammarFactory.create(grammar, defaults, options, cfg.colorOptions.hues);
			}
					// Activate grammar on existing text editors with matching grammar
			atom.workspace.getTextEditors()
				.filter(editor => editor.getGrammar().name == grammar.name)
				.map(enable);
		}

		function tryAddGrammarToConfig(grammar) {
			let grammarName = getGrammarName(grammar);
			let supported = isSupportedGrammar(grammar);
			let inGrammarList = grammarList.includes(grammarName);

			if (inGrammarList && supported) {
				return getGrammarParamNameFromGrammarName(grammarName);
			} else if (inGrammarList) {
				Sugar.Array.remove(grammarList, grammarName);
				writeGrammarListFile();
				debug('removed ' + grammarName, grammar);
				setTimeout(Semanticolor.reload);
				return null;
			}

			if (supported) {
				grammarList.push(grammarName);
				writeGrammarListFile();
				addGrammarToConfig(grammarName);
				debug('added ' + grammarName, grammar);
				setTimeout(Semanticolor.reload);
				return getGrammarParamNameFromGrammarName(grammarName);
			}
			return null;
		}

		function isSupportedGrammar(grammar) {
			let result = false;
			if (grammar.packageName !== SemanticolorGrammarFactory.packageName &&
				grammar.fileTypes.length > 0 &&
				((grammar.scopeName.includes('source') &&
						Sugar.Array.intersect(grammar.fileTypes, ignoredFileTypes).length == 0) ||
					Sugar.Array.intersect(grammar.fileTypes, forceIncludeFileTypes).length > 0)) {
				result = true;
			}
			return result;
		}

		this.disposables.add(atom.workspace.observeTextEditors(enable));

		this.disposables.add(atom.config.onDidChange('semanticolor', function (change) {
			if (Semanticolor.deactivated) {return;}
			_.debounce(function () {
				Semanticolor.updateLessStylesheet(change.newValue.colorOptions.hues === change.oldValue.colorOptions.hues);
				let reload = !Sugar.Object.isEqual(change.newValue.colorOptions.hues, change.oldValue.colorOptions.hues);
				for (let prop in change.newValue) {
					if (prop !== 'colorOptions' &&
						!Sugar.Object.isEqual(change.newValue[prop], change.oldValue[prop])) {
						reload = true;
						break;
					}
				}
				if (reload) {
					setTimeout(Semanticolor.reload);
				}
			}, 1000)();
		}));

		Semanticolor.reload();
	},
	//testing testing

	reload: function () {
		if (this.deactivated) {
			return;
		}
		let cfg = atom.config.get('semanticolor');
		defaults = getOptions(cfg.defaults);
		for (let prop in cfg) {
			if (prop !== 'colorOptions' && prop !== 'defaults' && grammars[prop]) {
				grammars[prop].defaults = defaults;
				grammars[prop].options = getOptions(cfg[prop]);
				grammars[prop].colorDiversity = cfg.colorOptions.hues;
				for (let editor of atom.workspace.getTextEditors()) {
					if (editor.getGrammar() === grammars[prop]) {
						editor.setGrammar(grammars[prop].__proto__);
					}
					if (!this.deactivated && cfg[prop].enabled) {
						enable(editor);
					}
				}
			}
		}
	},

	deactivate: function () {
		this.deactivated = true;
		let disposable = this.disposables;
		this.disposables = new CompositeDisposable();
		return disposable.dispose();
	},
};

module.exports = Semanticolor;
<|endoftext|>


<commit_before>Joshfire.define(['joshfire/class', 'joshfire/tree.data', 'joshfire/vendor/underscore'], function(Class, DataTree, _) {

  return Class(DataTree, {

    buildTree: function() {
      var self = this;

      // Joshfire datasources
      var datasources = Joshfire.factory.config.datasources;

      // transform these datasources in a Joshfire Framework friendly datasource type
      var datasourceArray = [];
      _.each(datasources, function(value, key) {
        if(_.isArray(value)) {
          _.each(value, function(val, index) {
            datasourceArray.push( _.extend(Joshfire.factory.getDataSource(key).children[index], { id: key + index, name: val.name }) );
          });
        } else {
          datasourceArray.push( _.extend(Joshfire.factory.getDataSource(key), { id: key }) );
        }
      });

      // add a last fake datasource for the About page
      if(Joshfire.factory.config.template.options && Joshfire.factory.config.template.options.abouthtml) {
        datasourceArray.splice(datasourceArray.length, 0, {
                id: "about",
                config : {
                  col : "about"
                },
                name : "About"
              });
      }

      // Loop trough all datasources to create data tree branches
      var datachildren = [];
      _.each(datasourceArray, function(datasource, index) {
        datachildren.push(
          {
            'id': datasource.id,
            'col': datasource.config.col,
            'database': datasource.config.db,
            children: function(query, cb) {
              datasource.find({}, function (err, data) {
                // The framework requires an 'id', but datasources
                // use 'url' (or nothing). Make sure we have an id.
                // NB: the framework does not like URL as ids!
                var items = _.map(data.entries, function (item, idx) {
                  return _.extend(item, { id: "#" + idx });
                });

                cb(null, items);
              });
            }
          });
      });

      // return the data tree
      return [
        {
          id: 'datasourcelist',
          children: function(query, callback) {
            callback(null, datasourceArray);
          }
        },
        {
          id: 'datasource',
          children: datachildren
        }
      ];

    }
  });

});<commit_msg>about in second position<commit_after>Joshfire.define(['joshfire/class', 'joshfire/tree.data', 'joshfire/vendor/underscore'], function(Class, DataTree, _) {

  return Class(DataTree, {

    buildTree: function() {
      var self = this;

      // Joshfire datasources
      var datasources = Joshfire.factory.config.datasources;

      // transform these datasources in a Joshfire Framework friendly datasource type
      var datasourceArray = [];
      _.each(datasources, function(value, key) {
        if(_.isArray(value)) {
          _.each(value, function(val, index) {
            datasourceArray.push( _.extend(Joshfire.factory.getDataSource(key).children[index], { id: key + index, name: val.name }) );
          });
        } else {
          datasourceArray.push( _.extend(Joshfire.factory.getDataSource(key), { id: key }) );
        }
      });

      // add a last fake datasource for the About page
      if(Joshfire.factory.config.template.options && Joshfire.factory.config.template.options.abouthtml) {
        datasourceArray.splice(1, 0, {
                id: "about",
                config : {
                  col : "about"
                },
                name : "About"
              });
      }

      // Loop trough all datasources to create data tree branches
      var datachildren = [];
      _.each(datasourceArray, function(datasource, index) {
        datachildren.push(
          {
            'id': datasource.id,
            'col': datasource.config.col,
            'database': datasource.config.db,
            children: function(query, cb) {
              datasource.find({}, function (err, data) {
                // The framework requires an 'id', but datasources
                // use 'url' (or nothing). Make sure we have an id.
                // NB: the framework does not like URL as ids!
                var items = _.map(data.entries, function (item, idx) {
                  return _.extend(item, { id: "#" + idx });
                });

                cb(null, items);
              });
            }
          });
      });

      // return the data tree
      return [
        {
          id: 'datasourcelist',
          children: function(query, callback) {
            callback(null, datasourceArray);
          }
        },
        {
          id: 'datasource',
          children: datachildren
        }
      ];

    }
  });

});<|endoftext|>


<commit_before>/*global $, WebSocket, console, window, document*/
"use strict";

/**
 * Connects to Pi server and receives video data.
 */
var client = {

    // Connects to Pi via websocket
    connect: function (port) {
        var self = this, video = document.getElementById("video");

        this.socket = new WebSocket("//" + window.location.hostname + ":" + port + "/websocket");

        // Request the video stream once connected
        this.socket.onopen = function () {
            console.log("Connected!");
            self.readCamera();
        };

        // Currently, all returned messages are video data. However, this is
        // extensible with full-spec JSON-RPC.
        this.socket.onmessage = function (messageEvent) {
            video.src = "data:image/jpeg;base64," + messageEvent.data;
        };
    },

    // Requests video stream
    readCamera: function () {
        this.socket.send("read_camera");
    }
};
<commit_msg>Debugging SSL<commit_after>/*global $, WebSocket, console, window, document*/
"use strict";

/**
 * Connects to Pi server and receives video data.
 */
var client = {

    // Connects to Pi via websocket
    connect: function (port) {
        var self = this, video = document.getElementById("video");

        var protocol = "ws";
        if (location.protocol === 'https:') protocol = "wss";
        this.socket = new WebSocket(protocol + "//" + window.location.hostname + ":" + port + "/websocket");

        // Request the video stream once connected
        this.socket.onopen = function () {
            console.log("Connected!");
            self.readCamera();
        };

        // Currently, all returned messages are video data. However, this is
        // extensible with full-spec JSON-RPC.
        this.socket.onmessage = function (messageEvent) {
            video.src = "data:image/jpeg;base64," + messageEvent.data;
        };
    },

    // Requests video stream
    readCamera: function () {
        this.socket.send("read_camera");
    }
};
<|endoftext|>


<commit_before>import router from 'router'
import http from 'http'
import mapSeries from '../helpers/map-series'
import asynchronous from './middleware/asynchronous'
import finalhandler from './finalhandler'
import middleware from './middleware'
import route from './route'
import logger from '../helpers/logger'
import Emitter from './emitter'

export default () => {
  // Prepare internals
  const internals = {
    // Prepare router
    router: router(),

    // Prepare server
    server: http.createServer((req, res) => {
      internals.router(req, res, finalhandler(req, res))
    }),

    // Prepare event emitter
    emitter: new Emitter(),

    // Prepare store
    store: {},

    // Prepare routes array
    routes: []
  }

  // Apply middleware
  middleware(internals.router)

  // Pleasant...
  class Pleasant {
    constructor() {
      this.listener = internals.server
    }

    // Register plugins
    async register(...args) {
      // Get arguments
      const prefix = typeof args[0] === 'string' ? args.shift() : null
      const plugins = !Array.isArray(args[0]) ? [args[0]] : args[0]
      const config = args[1] || {}

      // Save reference to application router
      const app = internals.router

      // Prefix enabled?
      if (prefix) {
        // Attach temporary router
        internals.router = router()

        // State that router is prefixed
        internals.router.prefix = prefix
      }

      // Register plugins
      const results = mapSeries(plugins, plugin => {
        const fn = plugin.default || plugin

        return Promise.resolve(fn(this, config)).catch(err => {
          logger.error(err)
          process.exit()
        })
      })

      // Prefix enabled?
      if (prefix) {
        // Add temporary router as prefixed middleware to application router
        app.use(prefix, internals.router)

        // Change back to application router
        internals.router = app
      }

      return results
    }

    // Events
    on(...args) {
      return internals.emitter.on(...args)
    }
    off(...args) {
      return internals.emitter.off(...args)
    }
    emit(...args) {
      return internals.emitter.emit(...args)
    }

    // Server
    async listen(...args) {
      await this.emit('ready')
      return internals.server.listen(...args)
    }
    close(...args) {
      return internals.server.close(...args)
    }

    // Routes
    route(config) {
      return route(internals.router, config, () => {
        if (internals.router.prefix) {
          config.url = `${internals.router.prefix}${config.url}`
        }

        internals.routes.push(config)
      })
    }
    routes() {
      return internals.routes
    }

    // Middleware
    use(...args) {
      args = args.map(
        arg => (typeof arg === 'function' ? asynchronous(arg) : arg)
      )
      return internals.router.use(...args)
    }

    // Store
    set(key, value) {
      internals.store[key] = value
    }
    get(key) {
      return key ? internals.store[key] : internals.store
    }
  }

  return new Pleasant()
}
<commit_msg>Added await<commit_after>import router from 'router'
import http from 'http'
import mapSeries from '../helpers/map-series'
import asynchronous from './middleware/asynchronous'
import finalhandler from './finalhandler'
import middleware from './middleware'
import route from './route'
import logger from '../helpers/logger'
import Emitter from './emitter'

export default () => {
  // Prepare internals
  const internals = {
    // Prepare router
    router: router(),

    // Prepare server
    server: http.createServer((req, res) => {
      internals.router(req, res, finalhandler(req, res))
    }),

    // Prepare event emitter
    emitter: new Emitter(),

    // Prepare store
    store: {},

    // Prepare routes array
    routes: []
  }

  // Apply middleware
  middleware(internals.router)

  // Pleasant...
  class Pleasant {
    constructor() {
      this.listener = internals.server
    }

    // Register plugins
    async register(...args) {
      // Get arguments
      const prefix = typeof args[0] === 'string' ? args.shift() : null
      const plugins = !Array.isArray(args[0]) ? [args[0]] : args[0]
      const config = args[1] || {}

      // Save reference to application router
      const app = internals.router

      // Prefix enabled?
      if (prefix) {
        // Attach temporary router
        internals.router = router()

        // State that router is prefixed
        internals.router.prefix = prefix
      }

      // Register plugins
      const results = await mapSeries(plugins, plugin => {
        const fn = plugin.default || plugin

        return Promise.resolve(fn(this, config)).catch(err => {
          logger.error(err)
          process.exit()
        })
      })

      // Prefix enabled?
      if (prefix) {
        // Add temporary router as prefixed middleware to application router
        app.use(prefix, internals.router)

        // Change back to application router
        internals.router = app
      }

      return results
    }

    // Events
    on(...args) {
      return internals.emitter.on(...args)
    }
    off(...args) {
      return internals.emitter.off(...args)
    }
    emit(...args) {
      return internals.emitter.emit(...args)
    }

    // Server
    async listen(...args) {
      await this.emit('ready')
      return internals.server.listen(...args)
    }
    close(...args) {
      return internals.server.close(...args)
    }

    // Routes
    route(config) {
      return route(internals.router, config, () => {
        if (internals.router.prefix) {
          config.url = `${internals.router.prefix}${config.url}`
        }

        internals.routes.push(config)
      })
    }
    routes() {
      return internals.routes
    }

    // Middleware
    use(...args) {
      args = args.map(
        arg => (typeof arg === 'function' ? asynchronous(arg) : arg)
      )
      return internals.router.use(...args)
    }

    // Store
    set(key, value) {
      internals.store[key] = value
    }
    get(key) {
      return key ? internals.store[key] : internals.store
    }
  }

  return new Pleasant()
}
<|endoftext|>


<commit_before><commit_msg>Adding base64 variable length quantities<commit_after>/* -*- Mode: js; js-indent-level: 2; -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Source Map.
 *
 * The Initial Developer of the Original Code is Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Nick Fitzgerald <nfitzgerald@mozilla.com> (original author)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * The contents of this file is a derivative work of
 * http://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java, its license follows:
 *
 * Copyright 2011 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ***** END LICENSE BLOCK ***** */
define(function (require, exports, module) {

  var base64 = require('source-map/base64');

  // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  // length quantities we use in the source map spec, the first bit is the sign,
  // the next four bits are the actual value, and the 6th bit is the
  // continuation bit. The continuation bit tells us whether there are more
  // digits in this value following this digit.

  var VLQ_BASE_SHIFT = 5;

  // binary: 100000
  var VLQ_BASE = 1 << VLQ_BASE_SHIFT;

  // binary: 011111
  var VLQ_BASE_MASK = VLQ_BASE - 1;

  // binary: 100000
  var VLQ_CONTINUATION_BIT = VLQ_BASE;

  /**
   * Converts from a two-complement value to a value where the sign bit is
   * is placed in the least significant bit.  For example, as decimals:
   *   1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
   *   2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
   */
  function toVLQSigned (value) {
    return value < 0
      ? ((-value) << 1) + 1
      : (value << 1) + 0;
  }

  /**
   * Converts to a two-complement value from a value where the sign bit is
   * is placed in the least significant bit.  For example, as decimals:
   *   2 (10 binary) becomes 1, 3 (11 binary) becomes -1
   *   4 (100 binary) becomes 2, 5 (101 binary) becomes -2
   */
  function fromVLQSigned (value) {
    var isNegative = (value & 1) === 1;
    value = value >> 1;
    return isNegative
      ? -value
      : value;
  }

  /**
   * Returns the base 64 VLQ encoded value.
   */
  exports.encode = function base64VLQ_encode (value) {
    var encoded = "";
    var digit;

    value = toVLQSigned(value);

    do {
      digit = value & VLQ_BASE_SHIFT;
      value >>>= VLQ_BASE_SHIFT;
      if ( value > 0 ) {
        // There are still more digits in this value, so we must make sure the
        // continuation bit is marked.
        digit |= VLQ_CONTINUATION_BIT;
      }
      encoded += digit;
    } while ( value > 0 );

    return encoded;
  };

  /**
   * Decodes the next base 64 VLQ value from the given string and returns the
   * value and the rest of the string.
   */
  exports.decode = function base64VLQ_decode (str) {
    var i = 0;
    var strLen = str.length;
    var result = 0;
    var shift = 0;
    var continuation, digit;

    do {
      if ( i >= strLen ) {
        throw new Error("Expected more digits in base 64 VLQ value.");
      }
      digit = base64.decode(str.charAt(i++));
      continuation = (digit & VLQ_CONTINUATION_BIT) !== 0;
      digit &= VLQ_BASE_MASK;
      result = result + (digit << shift);
      shift = shift + VLQ_BASE_SHIFT;
    } while ( continuation );

    return {
      value: fromVLQSigned(result),
      rest: str.slice(i)
    };
  };

});<|endoftext|>


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

function start () {
    forever.list('array', function (err, processes) {

        // stop all forever
        if (config === 'stop') {

            if (!processes) {
                return console.log('no process to stop');
            }

            forever.stopAll();
            console.log('server stoped');

            return;
        }

        // stop on config errors
        if (typeof config === 'string') {
            return console.log(config);
        }

        if (processes) {
            return console.log('server already running');
        }

        // start the server directly
        if (config.dev) {
            return require(config.paths.PROXY_SERVER);
        }

        // start proxy as a deamon
        forever.startDaemon(config.paths.PROXY_SERVER, {
            "max"           : config.attempts,
            "minUptime"     : config.minUptime,
            "spinSleepTime" : config.spinSleepTime,
            "silent"        : config.silent,
            "verbose"       : config.verbose,
            "logFile"       : config.log
        });

        console.log('server is running in the background');
    });
}

exports.start = start;
<commit_msg>show host and port of started proxy<commit_after>var config = require('./config');
var forever = require('forever');

exports.start = start;

function start () {
    forever.list('array', function (err, processes) {

        // stop all forever
        if (config === 'stop') {

            if (!processes) {
                return console.log('no proxy processes found to stop');
            }

            forever.stopAll();
            console.log('proxy stoped');

            return;
        }

        // stop on config errors
        if (typeof config === 'string') {
            return console.log(config);
        }

        if (processes) {
            return console.log('proxy already listening');
        }

        // start the server directly
        if (config.dev) {
            return require(config.paths.PROXY_SERVER);
        }

        // start proxy as a deamon
        forever.startDaemon(config.paths.PROXY_SERVER, {
            'max'           : config.attempts,
            'minUptime'     : config.minUptime,
            'spinSleepTime' : config.spinSleepTime,
            'silent'        : config.silent,
            'verbose'       : config.verbose,
            'logFile'       : config.log
        });

        console.log('proxy is listening to:', config.host + ':' + config.port);
    });
}
<|endoftext|>


<commit_before>// Load in our dependencies
var assert = require('assert');
var fs = require('fs');
var _ = require('underscore');
var _s = require('underscore.string');
var handlebars = require('handlebars');
var handlebarsLayouts = require('handlebars-layouts');
var jsonContentDemux = require('json-content-demux');

// Allow for layouts to occur on `handlebars` templates
handlebarsLayouts.register(handlebars);

/**
 * @param {Object} params Container for parameters
 * @param {Object[]} params.items Array of objects with coordinate data about each sprite on the spritesheet
 * @param {String} params.items.*.name Name to use for the image
 * @param {Number} params.items.*.x Horizontal coordinate of top-left corner of image
 * @param {Number} params.items.*.y Vertical coordinate of top-left corner of image
 * @param {Number} params.items.*.width Horizontal length of image in pixels
 * @param {Number} params.items.*.height Vertical length of image in pixels
 * @param {Object} params.spritesheet Information about spritesheet
 * @param {Number} params.spritesheet.width Horizontal length of image in pixels
 * @param {Number} params.spritesheet.height Vertical length of image in pixels
 * @param {Number} params.spritesheet.image URL to use for spritesheet
 * @param {Object} [options] Optional settings
 * @param {String} [options.spritesheetName="spritesheet"] Prefix to use for spritesheet related variables
 * @param {String} [options.format="css"] Format to generate output in
 * @param {Mixed} [options.formatOpts={}] Options to pass through to the formatter
 */
function templater(params, options) {
  // Assert we were given items and spritesheet
  assert(params, '`spritesheet-templates` expected to receive "params" but did not. Please provide it.');
  assert(params.items, '`spritesheet-templates` expected to receive "params.items" but did not. ' +
    'Please provide it.');
  assert(params.spritesheet, '`spritesheet-templates` expected to receive "params.spritesheet" but did not. ' +
    'Please provide it.');

  // Fallback and localize options
  options = options || {};
  var format = options.format || 'css';
  var template = templater.templates[format];

  // Assert that the template exists
  assert(template, 'The templater format "' + format + '" could not be found. Please make sure to either add ' +
    'it via addTemplate or the spelling is correct.');

  // Deep clone the items and spritesheet
  var items = JSON.parse(JSON.stringify(params.items));
  var spritesheet = JSON.parse(JSON.stringify(params.spritesheet));
  spritesheet.name = options.spritesheetName || 'spritesheet';

  // Add on extra data to spritesheet and each item
  templater.escapeImage(spritesheet);
  templater.ensureTemplateVariables(spritesheet);
  items.forEach(function addExtraData (item) {
    templater.addSpritesheetProperties(item, spritesheet);
    templater.ensureTemplateVariables(item);
  });

  // If we have retina items, enhance them as well well
  var retinaItems;
  var retinaSpritesheet;
  if (params.retinaItems || params.retinaSpritesheet) {
    retinaItems = JSON.parse(JSON.stringify(params.retinaItems));
    retinaSpritesheet = JSON.parse(JSON.stringify(params.retinaSpritesheet));

    templater.escapeImage(retinaSpritesheet);
    templater.ensureTemplateVariables(retinaSpritesheet);
    retinaItems.forEach(function addExtraData (retinaItem) {
      templater.addSpritesheetProperties(retinaItem, retinaSpritesheet);
      templater.ensureTemplateVariables(retinaItem);
    });
  }

  // Process the params via the template
  var retVal = template({
    items: items,
    retina_items: retinaItems,
    spritesheet: spritesheet,
    spritesheet_name: spritesheet.name,
    options: options.formatOpts || {}
  });

  // Return the output
  return retVal;
}

// Helper function to escape image path
templater.escapeImage = function (spritesheet) {
  // Escape the quotes, parentheses, and whitespace
  // http://www.w3.org/TR/CSS21/syndata.html#uri
  var img = spritesheet.image;
  var escapedImg = img.replace(/['"\(\)\s]/g, function encodeCssUri (chr) {
    return '%' + chr.charCodeAt(0).toString(16);
  });
  spritesheet.escaped_image = escapedImg;
};

// Helper function to add spritesheet info
templater.addSpritesheetProperties = function (item, spritesheet) {
  // Save spritesheet info
  item.image = spritesheet.image;
  item.escaped_image = spritesheet.escaped_image;
  item.total_width = spritesheet.width;
  item.total_height = spritesheet.height;
};

// Helper function to ensure offset values exist as well as values with pixels in the name
templater.ensureTemplateVariables = function (item) {
  // Guarantee offsets exist
  if (item.x !== undefined) {
    item.offset_x = -item.x;
  }
  if (item.y !== undefined) {
    item.offset_y = -item.y;
  }

  // Create a px namespace
  var px = {};
  item.px = px;

  // For each of the x, y, offset_x, offset_y, height, width, add a px after that
  ['x', 'y', 'offset_x', 'offset_y', 'height', 'width', 'total_height', 'total_width'].forEach(function (key) {
    if (item[key] !== undefined) {
      px[key] = item[key] + 'px';
    }
  });
};

templater.ensureMustacheVariables = function (item, transformFn) {
  // Define strings in the appropriate case
  item.strings = {};

  // If we have a name, add on name keys
  if (item.name) {
    _.extend(item.strings, {
      // icon-home
      name: transformFn(item.name),
      // icon-home-name
      name_name: transformFn(item.name + '-name'),
      // icon-home-x
      name_x: transformFn(item.name + '-x'),
      // icon-home-y
      name_y: transformFn(item.name + '-y'),
      // icon-home-offset-x
      name_offset_x: transformFn(item.name + '-offset-x'),
      // icon-home-offset-y
      name_offset_y: transformFn(item.name + '-offset-y'),
      // icon-home-width
      name_width: transformFn(item.name + '-width'),
      // icon-home-height
      name_height: transformFn(item.name + '-height'),
      // icon-home-total-width
      name_total_width: transformFn(item.name + '-total-width'),
      // icon-home-total-height
      name_total_height: transformFn(item.name + '-total-height'),
      // icon-home-image
      name_image: transformFn(item.name + '-image'),
      // icon-home-sprites
      name_sprites: transformFn(item.name + '-sprites')
    });
  }

  // Bare strings for maps
  _.extend(item.strings, {
    bare_name: transformFn('name'),
    bare_x: transformFn('x'),
    bare_y: transformFn('y'),
    bare_offset_x: transformFn('offset-x'),
    bare_offset_y: transformFn('offset-y'),
    bare_width: transformFn('width'),
    bare_height: transformFn('height'),
    bare_total_width: transformFn('total-width'),
    bare_total_height: transformFn('total-height'),
    bare_image: transformFn('image'),
    bare_sprites: transformFn('sprites')
  });
};

// Add template store and helper methods to add new templates
templater.templates = {};
templater.addTemplate = function (name, fn) {
  templater.templates[name] = fn;
};
templater.addHandlebarsTemplate = function (name, tmplStr) {
  // Break up the template and default options
  var tmplObj = jsonContentDemux(tmplStr);
  var defaults = tmplObj.json || {};
  var tmpl = tmplObj.content;

  // Generate a function which processes objects through the mustache template
  function templateFn(itemObj) {
    // Set up the defaults for the item object
    _.defaults(itemObj.options, defaults);

    // If we want to transform our variables, then transform them
    var transformFn = _.identity;
    var variableNameTransforms = itemObj.options.variableNameTransforms;
    if (variableNameTransforms) {
      assert(Array.isArray(variableNameTransforms),
        '`options.variableNameTransforms` was expected to be an array but it was not');
      transformFn = function (str) {
        var strObj = _s(str);
        variableNameTransforms.forEach(function runTransform (transformKey) {
          strObj = strObj[transformKey]();
        });
        return strObj.value();
      };
    }

    // Generate strings for our variables
    templater.ensureMustacheVariables(itemObj, transformFn);
    templater.ensureMustacheVariables(itemObj.spritesheet, transformFn);
    itemObj.items.forEach(function addMustacheVariables (item) {
      templater.ensureMustacheVariables(item, transformFn);
    });

    // Render the items via the template
    var retStr = handlebars.compile(tmpl)(itemObj);
    return retStr;
  }

  // Save the template to our collection as well as handlebars for inheritance
  handlebars.registerPartial(name, tmpl);
  templater.addTemplate(name, templateFn);
};
templater.addMustacheTemplate = templater.addHandlebarsTemplate;

// Add in the templates from templates
var templatesDir = __dirname + '/templates';

templater.addTemplate('json', require(templatesDir + '/json.template.js'));
templater.addTemplate('jsonArray', require(templatesDir + '/json_array.template.js'));
templater.addTemplate('css', require(templatesDir + '/css.template.js'));

var stylusHandlebars = fs.readFileSync(templatesDir + '/stylus.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('stylus', stylusHandlebars);
var stylusRetinaHandlebars = fs.readFileSync(templatesDir + '/stylus-retina.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('stylus-retina', stylusRetinaHandlebars);

var lessHandlebars = fs.readFileSync(templatesDir + '/less.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('less', lessHandlebars);

var sassHandlebars = fs.readFileSync(templatesDir + '/sass.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('sass', sassHandlebars);

var scssHandlebars = fs.readFileSync(templatesDir + '/scss.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('scss', scssHandlebars);

var scssMapsHandlebars = fs.readFileSync(templatesDir + '/scss_maps.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('scss_maps', scssMapsHandlebars);

// Expose templater
module.exports = templater;
<commit_msg>Added more variables for us<commit_after>// Load in our dependencies
var assert = require('assert');
var fs = require('fs');
var _ = require('underscore');
var _s = require('underscore.string');
var handlebars = require('handlebars');
var handlebarsLayouts = require('handlebars-layouts');
var jsonContentDemux = require('json-content-demux');

// Allow for layouts to occur on `handlebars` templates
handlebarsLayouts.register(handlebars);

/**
 * @param {Object} params Container for parameters
 * @param {Object[]} params.items Array of objects with coordinate data about each sprite on the spritesheet
 * @param {String} params.items.*.name Name to use for the image
 * @param {Number} params.items.*.x Horizontal coordinate of top-left corner of image
 * @param {Number} params.items.*.y Vertical coordinate of top-left corner of image
 * @param {Number} params.items.*.width Horizontal length of image in pixels
 * @param {Number} params.items.*.height Vertical length of image in pixels
 * @param {Object} params.spritesheet Information about spritesheet
 * @param {Number} params.spritesheet.width Horizontal length of image in pixels
 * @param {Number} params.spritesheet.height Vertical length of image in pixels
 * @param {Number} params.spritesheet.image URL to use for spritesheet
 * @param {Object} [options] Optional settings
 * @param {String} [options.spritesheetName="spritesheet"] Prefix to use for spritesheet related variables
 * @param {String} [options.format="css"] Format to generate output in
 * @param {Mixed} [options.formatOpts={}] Options to pass through to the formatter
 */
function templater(params, options) {
  // Assert we were given items and spritesheet
  assert(params, '`spritesheet-templates` expected to receive "params" but did not. Please provide it.');
  assert(params.items, '`spritesheet-templates` expected to receive "params.items" but did not. ' +
    'Please provide it.');
  assert(params.spritesheet, '`spritesheet-templates` expected to receive "params.spritesheet" but did not. ' +
    'Please provide it.');

  // Fallback and localize options
  options = options || {};
  var format = options.format || 'css';
  var template = templater.templates[format];

  // Assert that the template exists
  assert(template, 'The templater format "' + format + '" could not be found. Please make sure to either add ' +
    'it via addTemplate or the spelling is correct.');

  // Deep clone the items and spritesheet
  var items = JSON.parse(JSON.stringify(params.items));
  var spritesheet = JSON.parse(JSON.stringify(params.spritesheet));
  spritesheet.name = options.spritesheetName || 'spritesheet';

  // Add on extra data to spritesheet and each item
  templater.escapeImage(spritesheet);
  templater.ensureTemplateVariables(spritesheet);
  items.forEach(function addExtraData (item) {
    templater.addSpritesheetProperties(item, spritesheet);
    templater.ensureTemplateVariables(item);
  });

  // If we have retina items, enhance them as well well
  var retinaItems;
  var retinaSpritesheet;
  if (params.retinaItems || params.retinaSpritesheet) {
    assert(params.retinaItems && params.retinaSpritesheet, 'Expected both "params.retinaItems" and ' +
      '"params.retinaSpritesheet" to be provided but one of them was missing');
    retinaItems = JSON.parse(JSON.stringify(params.retinaItems));
    retinaSpritesheet = JSON.parse(JSON.stringify(params.retinaSpritesheet));
    retinaSpritesheet.name = options.retinaSpritesheetName || 'spritesheet-retina';

    templater.escapeImage(retinaSpritesheet);
    templater.ensureTemplateVariables(retinaSpritesheet);
    retinaItems.forEach(function addExtraData (retinaItem) {
      templater.addSpritesheetProperties(retinaItem, retinaSpritesheet);
      templater.ensureTemplateVariables(retinaItem);
    });
  }

  // Process the params via the template
  var retVal = template({
    items: items,
    retina_items: retinaItems,
    spritesheet: spritesheet,
    spritesheet_name: spritesheet.name,
    retina_spritesheet: retinaSpritesheet,
    retina_spritesheet_name: retinaSpritesheet.name,
    options: options.formatOpts || {}
  });

  // Return the output
  return retVal;
}

// Helper function to escape image path
templater.escapeImage = function (spritesheet) {
  // Escape the quotes, parentheses, and whitespace
  // http://www.w3.org/TR/CSS21/syndata.html#uri
  var img = spritesheet.image;
  var escapedImg = img.replace(/['"\(\)\s]/g, function encodeCssUri (chr) {
    return '%' + chr.charCodeAt(0).toString(16);
  });
  spritesheet.escaped_image = escapedImg;
};

// Helper function to add spritesheet info
templater.addSpritesheetProperties = function (item, spritesheet) {
  // Save spritesheet info
  item.image = spritesheet.image;
  item.escaped_image = spritesheet.escaped_image;
  item.total_width = spritesheet.width;
  item.total_height = spritesheet.height;
};

// Helper function to ensure offset values exist as well as values with pixels in the name
templater.ensureTemplateVariables = function (item) {
  // Guarantee offsets exist
  if (item.x !== undefined) {
    item.offset_x = -item.x;
  }
  if (item.y !== undefined) {
    item.offset_y = -item.y;
  }

  // Create a px namespace
  var px = {};
  item.px = px;

  // For each of the x, y, offset_x, offset_y, height, width, add a px after that
  ['x', 'y', 'offset_x', 'offset_y', 'height', 'width', 'total_height', 'total_width'].forEach(function (key) {
    if (item[key] !== undefined) {
      px[key] = item[key] + 'px';
    }
  });
};

templater.ensureMustacheVariables = function (item, transformFn) {
  // Define strings in the appropriate case
  item.strings = {};

  // If we have a name, add on name keys
  if (item.name) {
    _.extend(item.strings, {
      // icon-home
      name: transformFn(item.name),
      // icon-home-name
      name_name: transformFn(item.name + '-name'),
      // icon-home-x
      name_x: transformFn(item.name + '-x'),
      // icon-home-y
      name_y: transformFn(item.name + '-y'),
      // icon-home-offset-x
      name_offset_x: transformFn(item.name + '-offset-x'),
      // icon-home-offset-y
      name_offset_y: transformFn(item.name + '-offset-y'),
      // icon-home-width
      name_width: transformFn(item.name + '-width'),
      // icon-home-height
      name_height: transformFn(item.name + '-height'),
      // icon-home-total-width
      name_total_width: transformFn(item.name + '-total-width'),
      // icon-home-total-height
      name_total_height: transformFn(item.name + '-total-height'),
      // icon-home-image
      name_image: transformFn(item.name + '-image'),
      // icon-home-sprites
      name_sprites: transformFn(item.name + '-sprites')
    });
  }

  // Bare strings for maps
  _.extend(item.strings, {
    bare_name: transformFn('name'),
    bare_x: transformFn('x'),
    bare_y: transformFn('y'),
    bare_offset_x: transformFn('offset-x'),
    bare_offset_y: transformFn('offset-y'),
    bare_width: transformFn('width'),
    bare_height: transformFn('height'),
    bare_total_width: transformFn('total-width'),
    bare_total_height: transformFn('total-height'),
    bare_image: transformFn('image'),
    bare_sprites: transformFn('sprites')
  });
};

// Add template store and helper methods to add new templates
templater.templates = {};
templater.addTemplate = function (name, fn) {
  templater.templates[name] = fn;
};
templater.addHandlebarsTemplate = function (name, tmplStr) {
  // Break up the template and default options
  var tmplObj = jsonContentDemux(tmplStr);
  var defaults = tmplObj.json || {};
  var tmpl = tmplObj.content;

  // Generate a function which processes objects through the mustache template
  function templateFn(itemObj) {
    // Set up the defaults for the item object
    _.defaults(itemObj.options, defaults);

    // If we want to transform our variables, then transform them
    var transformFn = _.identity;
    var variableNameTransforms = itemObj.options.variableNameTransforms;
    if (variableNameTransforms) {
      assert(Array.isArray(variableNameTransforms),
        '`options.variableNameTransforms` was expected to be an array but it was not');
      transformFn = function (str) {
        var strObj = _s(str);
        variableNameTransforms.forEach(function runTransform (transformKey) {
          strObj = strObj[transformKey]();
        });
        return strObj.value();
      };
    }

    // Generate strings for our variables
    templater.ensureMustacheVariables(itemObj, transformFn);
    templater.ensureMustacheVariables(itemObj.spritesheet, transformFn);
    itemObj.items.forEach(function addMustacheVariables (item) {
      templater.ensureMustacheVariables(item, transformFn);
    });

    // Render the items via the template
    var retStr = handlebars.compile(tmpl)(itemObj);
    return retStr;
  }

  // Save the template to our collection as well as handlebars for inheritance
  handlebars.registerPartial(name, tmpl);
  templater.addTemplate(name, templateFn);
};
templater.addMustacheTemplate = templater.addHandlebarsTemplate;

// Add in the templates from templates
var templatesDir = __dirname + '/templates';

templater.addTemplate('json', require(templatesDir + '/json.template.js'));
templater.addTemplate('jsonArray', require(templatesDir + '/json_array.template.js'));
templater.addTemplate('css', require(templatesDir + '/css.template.js'));

var stylusHandlebars = fs.readFileSync(templatesDir + '/stylus.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('stylus', stylusHandlebars);
var stylusRetinaHandlebars = fs.readFileSync(templatesDir + '/stylus-retina.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('stylus-retina', stylusRetinaHandlebars);

var lessHandlebars = fs.readFileSync(templatesDir + '/less.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('less', lessHandlebars);

var sassHandlebars = fs.readFileSync(templatesDir + '/sass.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('sass', sassHandlebars);

var scssHandlebars = fs.readFileSync(templatesDir + '/scss.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('scss', scssHandlebars);

var scssMapsHandlebars = fs.readFileSync(templatesDir + '/scss_maps.template.handlebars', 'utf8');
templater.addHandlebarsTemplate('scss_maps', scssMapsHandlebars);

// Expose templater
module.exports = templater;
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

app.sv = cs.clazz({
    mixin: [ cs.marker.service ],
    protos: {
        create: function () {
            /*  converts a string containing multiple traces into an array of trace objects  */
            cs(this).register('parseLogfile', function (lines) {
                var pattern = /^[^<]*< ([^,]*), ([^,]*), ([^,]*), ([^,]*), ([^,]*), ([^,]*), ([^,]*), (.*) >/
                var traces = []
                for (var i = 0; i < lines.length; i++) {
                    var line = lines[i]
                    var matches = line.match(pattern)
                    var param = JSON.parse(matches[8])
                    var newTrace = {
                        id: parseInt(matches[1], 10),
                        time: parseInt(matches[2], 10),
                        source: matches[3],
                        sourceType: matches[4],
                        origin: matches[5],
                        originType: matches[6],
                        operation: matches[7],
                        parameters: param
                    }
                    newTrace = app.lib.richTrace.enrich(newTrace)
                    traces.push(newTrace)
                }
                return traces
            })

            cs(this).register('getState', function (path) {
                var cmps = cs('//componentTree').call('getComponent', path)
                if (cmps.length > 0)
                    return cmps[0].state
                return
            })

            /*  parses a given string using the PEG parser for the constraint grammar  */
            cs(this).register('parsePeepholeConstraintset', function (content) {
                try {
                    var constraintSet = app.lib.peephole_constraint_parser.parse(content)
                    return { success: true, constraints: constraintSet }
                }
                catch (err) {
                    return { success: false, error: err }
                }
            })

            /*  parses a given string using the PEG parser for the temporal constraint grammar  */
            cs(this).register('parseTemporalConstraintset', function (content) {
                try {
                    var constraintSet = app.lib.temporal_constraint_parser.parse(content)
                    return { success: true, constraints: constraintSet }
                }
                catch (err) {
                    return { success: false, error: err }
                }
            })

            /*  validates the given constraints semantically  */
            cs(this).register('validateTemporalConstraints', function (constraintSet) {
                var result = []
                var noDups = _.uniq(constraintSet, function (constraint) { return constraint.id })
                if (noDups.length !== constraintSet.length) {
                    var diff = _.difference(constraintSet, noDups)
                    _.each(diff, function (constraint) {
                        result.push({
                            constraint: constraint,
                            column: 0,
                            type: 'error',
                            message: 'Found another constraint with the id "' + constraint.id + '", the id of a constraint has to be unique'
                        })
                    })
                }
                _.map(constraintSet, function (constraint) {
                    var participants = constraint.constraintBody.sequence
                    var terminateIdx = _.indexOf(participants, 'terminate')
                    if (terminateIdx !== -1 && terminateIdx !== participants.length - 1)
                        result.push({
                            constraint: constraint,
                            column: 0,
                            type: 'error',
                            message: 'Terminate has to be the last participant in the sequence, if present'
                        })
                    if (participants.length < 2)
                        result.push({
                            constraint: constraint,
                            column: 0,
                            type: 'error',
                            message: 'The number of participating traces of a temporal constraint must be at least two'
                        })
                    var noDups = _.uniq(participants)
                    if (noDups.length !== participants.length)
                        result.push({
                            constraint: constraint,
                            column: 0,
                            type: 'error',
                            message: 'The members in the sequence of a temporal constraint have to be diversely named'
                        })
                    _.map(_.without(participants, 'terminate'), function (participant) {
                        var filterIds = _.map(constraint.constraintBody.filters, function (filter) { return filter.id })
                        if (_.indexOf(filterIds, participant) === -1)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'warning',
                                message: 'There is no filter expression specified for ' + participant
                            })
                    })
                    _.map(constraint.constraintBody.filters, function (filter) {
                        if (_.indexOf(participants, filter.id) === -1)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: filter.id + ' is not defined in the sequence section but used in a filter expression'
                            })
                    })
                    _.map(constraint.constraintBody.links, function (link) {
                        if (_.indexOf(participants, link.id) === -1)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: link.id + ' is not defined in the sequence section but used in a link expression'
                            })
                    })
                })

                return result
            })

            /*  validates the given constraints semantically  */
            cs(this).register('validatePeepholeConstraints', function (constraintSet) {
                var result = []
                var containsDup = function (constraint) {
                    if (constraint.constraintBody.constraints) {
                        var dups = {}
                        _.each(constraint.constraintBody.constraints, function (constraint) {
                            if (dups[constraint.id])
                                dups[constraint.id] = dups[constraint.id] + 1
                            else
                                dups[constraint.id] = 1
                        })
                        dups = _.omit(dups, function (value) { return value <= 1 })
                        var keys = _.keys(dups)
                        if (keys.length > 0)
                            return keys

                        /*  for loop is necessary here!  */
                        for (var i = 0; i < constraint.constraintBody.constraints.length; i++)
                            return containsDup(constraint.constraintBody.constraints[i])
                    }
                    return false
                }
                _.each(constraintSet, function (constraint) {
                    var res = containsDup(constraint)
                    if (res)
                        result.push({
                            constraint: constraint,
                            column: 0,
                            type: 'error',
                            message: 'The name for the nested constraint' + (res.length > 1 ? 's' : '') + ' "' + res.join('", "') + '" is ambiguous'
                        })
                })
                var noDups = _.uniq(constraintSet, function (constraint) { return constraint.id })
                if (noDups.length !== constraintSet.length) {
                    var diff = _.difference(constraintSet, noDups)
                    _.each(diff, function (constraint) {
                        result.push({
                            constraint: constraint,
                            column: 0,
                            type: 'error',
                            message: 'Found another constraint with the id "' + constraint.id + '", the id of a constraint has to be unique'
                        })
                    })
                }

                return result
            })

            /*  checks an array of traces against a given set of constraints  */
            cs(this).register('checkTraces', function (traces, constraintSet) {
                var resTraces = []
                _.map(traces, function (trace) {
                    var mTrace = app.lib.constraintChecker.checkTrace(constraintSet, trace)
                    if (mTrace.result === 'UNCLASSIFIED' || mTrace.result === 'FAIL')
                        resTraces.push(mTrace)
                })
                return resTraces
            })
        }
    }
})<commit_msg>Added spooling to service component<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

app.sv = cs.clazz({
    mixin: [ cs.marker.service ],
    protos: {
        create: function () {
            /*  converts a string containing multiple traces into an array of trace objects  */
            cs(this).register({
                name: 'parseLogfile', spool: 'created',
                func: function (lines) {
                    var pattern = /^[^<]*< ([^,]*), ([^,]*), ([^,]*), ([^,]*), ([^,]*), ([^,]*), ([^,]*), (.*) >/
                    var traces = []
                    for (var i = 0; i < lines.length; i++) {
                        var line = lines[i]
                        var matches = line.match(pattern)
                        var param = JSON.parse(matches[8])
                        var newTrace = {
                            id: parseInt(matches[1], 10),
                            time: parseInt(matches[2], 10),
                            source: matches[3],
                            sourceType: matches[4],
                            origin: matches[5],
                            originType: matches[6],
                            operation: matches[7],
                            parameters: param
                        }
                        newTrace = app.lib.richTrace.enrich(newTrace)
                        traces.push(newTrace)
                    }
                    return traces
                }
            })

            cs(this).register({
                name: 'getState', spool: 'created',
                func: function (path) {
                    var cmps = cs('//componentTree').call('getComponent', path)
                    if (cmps.length > 0)
                        return cmps[0].state
                    return
                }
            })

            /*  parses a given string using the PEG parser for the constraint grammar  */
            cs(this).register({
                name: 'parsePeepholeConstraintset', spool: 'created',
                func: function (content) {
                    try {
                        var constraintSet = app.lib.peephole_constraint_parser.parse(content)
                        return { success: true, constraints: constraintSet }
                    }
                    catch (err) {
                        return { success: false, error: err }
                    }
                }
            })

            /*  parses a given string using the PEG parser for the temporal constraint grammar  */
            cs(this).register({
                name: 'parseTemporalConstraintset', spool: 'created',
                func: function (content) {
                    try {
                        var constraintSet = app.lib.temporal_constraint_parser.parse(content)
                        return { success: true, constraints: constraintSet }
                    }
                    catch (err) {
                        return { success: false, error: err }
                    }
                }
            })

            /*  validates the given constraints semantically  */
            cs(this).register({
                name: 'validateTemporalConstraints', spool: 'created',
                func: function (constraintSet) {
                    var result = []
                    var noDups = _.uniq(constraintSet, function (constraint) { return constraint.id })
                    if (noDups.length !== constraintSet.length) {
                        var diff = _.difference(constraintSet, noDups)
                        _.each(diff, function (constraint) {
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: 'Found another constraint with the id "' + constraint.id + '", the id of a constraint has to be unique'
                            })
                        })
                    }
                    _.map(constraintSet, function (constraint) {
                        var participants = constraint.constraintBody.sequence
                        var terminateIdx = _.indexOf(participants, 'terminate')
                        if (terminateIdx !== -1 && terminateIdx !== participants.length - 1)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: 'Terminate has to be the last participant in the sequence, if present'
                            })
                        if (participants.length < 2)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: 'The number of participating traces of a temporal constraint must be at least two'
                            })
                        var noDups = _.uniq(participants)
                        if (noDups.length !== participants.length)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: 'The members in the sequence of a temporal constraint have to be diversely named'
                            })
                        _.map(_.without(participants, 'terminate'), function (participant) {
                            var filterIds = _.map(constraint.constraintBody.filters, function (filter) { return filter.id })
                            if (_.indexOf(filterIds, participant) === -1)
                                result.push({
                                    constraint: constraint,
                                    column: 0,
                                    type: 'warning',
                                    message: 'There is no filter expression specified for ' + participant
                                })
                        })
                        _.map(constraint.constraintBody.filters, function (filter) {
                            if (_.indexOf(participants, filter.id) === -1)
                                result.push({
                                    constraint: constraint,
                                    column: 0,
                                    type: 'error',
                                    message: filter.id + ' is not defined in the sequence section but used in a filter expression'
                                })
                        })
                        _.map(constraint.constraintBody.links, function (link) {
                            if (_.indexOf(participants, link.id) === -1)
                                result.push({
                                    constraint: constraint,
                                    column: 0,
                                    type: 'error',
                                    message: link.id + ' is not defined in the sequence section but used in a link expression'
                                })
                        })
                    })

                    return result
                }
            })

            /*  validates the given constraints semantically  */
            cs(this).register({
                name: 'validatePeepholeConstraints', spool: 'created',
                func: function (constraintSet) {
                    var result = []
                    var containsDup = function (constraint) {
                        if (constraint.constraintBody.constraints) {
                            var dups = {}
                            _.each(constraint.constraintBody.constraints, function (constraint) {
                                if (dups[constraint.id])
                                    dups[constraint.id] = dups[constraint.id] + 1
                                else
                                    dups[constraint.id] = 1
                            })
                            dups = _.omit(dups, function (value) { return value <= 1 })
                            var keys = _.keys(dups)
                            if (keys.length > 0)
                                return keys

                            /*  for loop is necessary here!  */
                            for (var i = 0; i < constraint.constraintBody.constraints.length; i++)
                                return containsDup(constraint.constraintBody.constraints[i])
                        }
                        return false
                    }
                    _.each(constraintSet, function (constraint) {
                        var res = containsDup(constraint)
                        if (res)
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: 'The name for the nested constraint' + (res.length > 1 ? 's' : '') + ' "' + res.join('", "') + '" is ambiguous'
                            })
                    })
                    var noDups = _.uniq(constraintSet, function (constraint) { return constraint.id })
                    if (noDups.length !== constraintSet.length) {
                        var diff = _.difference(constraintSet, noDups)
                        _.each(diff, function (constraint) {
                            result.push({
                                constraint: constraint,
                                column: 0,
                                type: 'error',
                                message: 'Found another constraint with the id "' + constraint.id + '", the id of a constraint has to be unique'
                            })
                        })
                    }
                    return result
                }
            })

            /*  checks an array of traces against a given set of constraints  */
            cs(this).register({
                name: 'checkTraces', spool: 'created',
                func: function (traces, constraintSet) {
                    var resTraces = []
                    _.map(traces, function (trace) {
                        var mTrace = app.lib.constraintChecker.checkTrace(constraintSet, trace)
                        if (mTrace.result === 'UNCLASSIFIED' || mTrace.result === 'FAIL')
                            resTraces.push(mTrace)
                    })
                    return resTraces
                }
            })
        }
    }
})<|endoftext|>


<commit_before>/**
 * @flow
 */

import wcjs from 'wcjs-prebuilt';
import render from 'wcjs-renderer';
import supportedEvents from './supportedEvents';

class Player {
  player: Function;
  options: Object;

  constructor(options: Object = {}) {
    this.options = options;
    this.player = wcjs.createPlayer();
    if (this.options.debug) {
      window.vlc = this.player;
      console.log(this.player.vlcVersion); //eslint-disable-line
    }
  }

  renderVideo(element: HTMLElement, options: Object = {}) {
    render.bind(element, this.player, options);
  }

  play(file: string) {
    this.player.play(file);
  }

  addToPlaylist(item: string) {
    this.player.playlist.add(item);
  }

  getPlayListItems(): Array<Object> {
    const count = this.player.playlist.items.count;
    const items = [];
    for (let i = 0; i < count; i += 1) {
      items.push(this.player.playlist.items[i]);
    }
    return items;
  }

  playOrPause(): boolean {
    this.player.togglePause();
    return this.isPlaying();
  }

  isPlaying(): boolean {
    return this.player.playing;
  }

  isMute(): boolean {
    return this.player.mute;
  }

  getPosition(): number {
    return this.player.position * 100;
  }

  setPosition(value: number): number {
    this.player.position = (value / 100);
    return this.getPosition();
  }

  addEventListener(eventName: string, callback: Function) {
    if (supportedEvents.includes(eventName)) {
      this.player[eventName] = callback;
    } else {
      throw Error(`${eventName} is a not a valid player event`);
    }
  }

}

export default Player;
<commit_msg>removed<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
var url = require('url')
var http = require('http')
var https = require('https')
var level = require('level')
var asyncMap = require('slide').asyncMap
var multiLevel = require('multilevel')
var livestream = require('level-live-stream')
var browserify = require('browserify')
var engineServer = require('engine.io-stream')
var fileserver = require('node-static').Server
var newhmac = require('crypto').createhmac
var formidable = require('formidable')

!(process.argv[2])
  ? boot(require('./config.json'))
  : boot(process.argv[2])

function startServer (conf, cb) { // WRITE INDEX!
  fs.writeFileSync('./static/index.html', '<!doctype html>'+
  ''+
  '<meta charset="utf-8">'+
  ''+
  '<title>Untitiled</title>'+
  '<link rel="stylesheet" href="/style.css">'+
  ''+
  ''+
  '
'+
  '
'+
  ''+
  ''+
  '')

  if (!conf.ssl) {
    var file = new fileserver('./static')
    var server = http.createServer(handleHttp)
  } else {
    var hsts = {'Strict-Transport-Security':'max-age=31536000'}
    var file = new fileServer('./static', hsts)
    var server = https.createServer({
      honorCipherOrder : true,
      key : fs.readFileSync(conf.ssl.key),
      cert : fs.readFileSync(conf.ssl.cert),
      cipher : 'ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:'+
               'ecdh+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:'+
               'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'
    }, handleHttp)
  }

  function handleHttp (req, res) {
    if (req.url === '/upload' && req.method === 'post') fileUpload(req, res)
    file.serve(req, res, function noFile (e) {
      if (e) {
        var path = url.parse(req.url).pathname.slice(1)
        file.serveFile('/index.html', 200, {}, req, res)
      }
    })
  }

  var engine = engineServer(function (wss) {
    wss.pipe(multiLevel.server(db, {
      auth: function (user, cb) {
        getHmac({token:user.pass,user:user.user}, function handleHmac (d) {
          if (modes[user.user] === pass) cb(null, { name: user.user, token: d.val })
          if (modes[user.user] !== pass) cb(new Error('wrong pass!'), null)
          if (e) cb(e, null)
        })
      },
      access: function (user, db, method, args) {}
    })).pipe(wss)
    wss.on('error', console.error)
  }, {cookie:false})
    .attach(server, '/ws')

  server.listen(conf.port, conf.host, cb)
}

function boot (conf) {
  if (!conf) throw new Error('Nimoy needs a config to run!')
  if (!fs.existsSync('./static')) fs.mkdir('./static')

  var db = level('./' + conf.host)
  livestream.install(db)
  multiLevel.writeManifest(db, './static/manifest.json')

  compileModules(conf.bundle, function (library) {
    db.put('library', JSON.stringify(library))
    startServer(conf.server)
  })

  if (conf.brico) {
    var conf = conf.brico
    for (m in conf.modes) {
      if (conf.modes[m].pass) {
        var token = conf.modes[m].pass
        delete conf.modes[m].pass
        gethmac({token:token,user:m}, function (d) { modes[d.key] = d.val })
      }
    }
    db.put('config', JSON.stringify(conf))
  }
}

function getHmac (algo, key, d, next) {
  var hmac = newHmac(algo, key)
  hmac.setEncoding('hex')
  hmac.write(d.token)
  hmac.end()
  next({key:'users:'+d.user, val:hmac.read().toString()})
}

function compileModules (config, cb) {
  var library  = {}
  var inBun = config.pathBundleEntry
  var outBun = config.pathBundleOut
  var b = browserify(inBun)
  var modulesFolder = fs.readdirSync(config.pathModules)

  asyncMap(modulesFolder, function (moduleFolder, next) {
    var pkgPath = config.pathModules + moduleFolder + '/package.json'
    if (!fs.existsSync(pkgPath)) { next(); return null }

    var pkg = JSON.parse(fs.readFileSync(pkgPath, {encoding:'utf8'}))
    if (!pkg.nimoy) { next(); return null }

    var key = 'modules:'+pkg.name
    library[key] = pkg.nimoy
    b.require(config.pathModules+moduleFolder+'/'+pkg.main, {expose: moduleFolder})

    next()

  }, function end () {
    var bun = fs.createWriteStream(outBun)
    bun.on('finish',function () {console.log('compiled '+inBun+' to '+outBun)})
    b.bundle().pipe(bun)
    cb(library)
  })
}

function fileUpload (req, res) {
  var form = new formidable.IncomingForm()
  form.parse(req, function(err, fields, files) {
    // this may need changing!
    res.writeHead(200, {'content-type': 'text/plain'})
    res.write('received upload:\n\n')
    res.end()
    var blob = fields.blob.split(',')[1]
    fs.writeFileSync(config.files.uploads+fields.file, blob, {encoding:'base64'})
  })
}
<commit_msg>fixed server callback and callback when compileModules is complete<commit_after>var fs = require('fs')
var url = require('url')
var http = require('http')
var https = require('https')
var level = require('level')
var asyncMap = require('slide').asyncMap
var multiLevel = require('multilevel')
var livestream = require('level-live-stream')
var browserify = require('browserify')
var engineServer = require('engine.io-stream')
var fileserver = require('node-static').Server
var newhmac = require('crypto').createhmac
var formidable = require('formidable')

!(process.argv[2])
  ? boot(require('./config.json'))
  : boot(process.argv[2])

function startServer (conf, cb) { // WRITE INDEX!
  fs.writeFileSync('./static/index.html', '<!doctype html>'+
  ''+
  '<meta charset="utf-8">'+
  ''+
  '<title>Untitiled</title>'+
  '<link rel="stylesheet" href="/style.css">'+
  ''+
  ''+
  '
'+
  '
'+
  ''+
  ''+
  '')

  if (!conf.ssl) {
    var file = new fileserver('./static')
    var server = http.createServer(handleHttp)
  } else {
    var hsts = {'Strict-Transport-Security':'max-age=31536000'}
    var file = new fileServer('./static', hsts)
    var server = https.createServer({
      honorCipherOrder : true,
      key : fs.readFileSync(conf.ssl.key),
      cert : fs.readFileSync(conf.ssl.cert),
      cipher : 'ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:'+
               'ecdh+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:'+
               'RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'
    }, handleHttp)
  }

  function handleHttp (req, res) {
    if (req.url === '/upload' && req.method === 'post') fileUpload(req, res)
    file.serve(req, res, function noFile (e) {
      if (e) {
        var path = url.parse(req.url).pathname.slice(1)
        file.serveFile('/index.html', 200, {}, req, res)
      }
    })
  }

  var engine = engineServer(function (wss) {
    wss.pipe(multiLevel.server(db, {
      auth: function (user, cb) {
        getHmac({token:user.pass,user:user.user}, function handleHmac (d) {
          if (modes[user.user] === pass) cb(null, { name: user.user, token: d.val })
          if (modes[user.user] !== pass) cb(new Error('wrong pass!'), null)
          if (e) cb(e, null)
        })
      },
      access: function (user, db, method, args) {}
    })).pipe(wss)
    wss.on('error', console.error)
  }, {cookie:false})
    .attach(server, '/ws')

  server.listen(conf.port, conf.host, cb)
}

function boot (conf) {
  if (!conf) throw new Error('Nimoy needs a config to run!')
  if (!fs.existsSync('./static')) fs.mkdir('./static')

  var db = level('./' + conf.host)
  livestream.install(db)
  multiLevel.writeManifest(db, './static/manifest.json')

  compileModules(conf.bundle, function (library) {
    db.put('library', JSON.stringify(library))
    startServer(conf.server, function () {
      console.log('server running')
    })
  })

  // setup bricoleur

  if (conf.brico) {
    var conf = conf.brico
    for (m in conf.modes) {
      if (conf.modes[m].pass) {
        var token = conf.modes[m].pass
        delete conf.modes[m].pass
        gethmac({token:token,user:m}, function (d) { modes[d.key] = d.val })
      }
    }
    db.put('config', JSON.stringify(conf))
  }
}

function getHmac (algo, key, d, next) {
  var algo = 'sha256'
  var hmac = newHmac(algo, key)
  hmac.setEncoding('hex')
  hmac.write(d.token)
  hmac.end()
  next({key:'users:'+d.user, val:hmac.read().toString()})
}

function compileModules (config, cb) {
  var library  = {}
  var inBun = config.pathBundleEntry
  var outBun = config.pathBundleOut
  var b = browserify(inBun)
  var modulesFolder = fs.readdirSync(config.pathModules)

  asyncMap(modulesFolder, function (moduleFolder, next) {
    var pkgPath = config.pathModules + moduleFolder + '/package.json'
    if (!fs.existsSync(pkgPath)) { next(); return null }

    var pkg = JSON.parse(fs.readFileSync(pkgPath, {encoding:'utf8'}))
    if (!pkg.nimoy) { next(); return null }

    var key = 'modules:'+pkg.name
    library[key] = pkg.nimoy
    b.require(config.pathModules+moduleFolder+'/'+pkg.main, {expose: moduleFolder})

    next()

  }, function end () {
    var bun = fs.createWriteStream(outBun)
    b.bundle().pipe(bun)
    bun.on('finish',function () {
      console.log('compiled '+inBun+' to '+outBun)
      cb(library)
    })
  })
}

function fileUpload (req, res) {
  var form = new formidable.IncomingForm()
  form.parse(req, function(err, fields, files) {
    // this may need changing!
    res.writeHead(200, {'content-type': 'text/plain'})
    res.write('received upload:\n\n')
    res.end()
    var blob = fields.blob.split(',')[1]
    fs.writeFileSync(config.files.uploads+fields.file, blob, {encoding:'base64'})
  })
}
<|endoftext|>


<commit_before>define(['rpn/main'], function (rpn) {
    'use strict';

    describe('Infix to RPN', function () {
        it("should ignore empty expressions", function () {
            expect(rpn.getFromInfix('')).toEqual('');
        });

        it("should NOT transform single-number non-negative expressions", function () {
            expect(rpn.getFromInfix('2')).toEqual('2');
        });

        it("should transform simple use of unary operators", function () {
            expect(rpn.getFromInfix('_ 2')).toEqual('2 _');
        });

        it("should treat minus as unary when in the beginning", function () {
            expect(rpn.getFromInfix('-2')).toEqual('2 _');
        });

        it("should treat minus as unary when used after another operator", function () {
            expect(rpn.getFromInfix('2 - -3')).toEqual('2 3 _ -');
        });

        it("should treat minus as unary when used after left parentheses", function () {
            expect(rpn.getFromInfix('2 - (-3)')).toEqual('2 3 _ -');
        });

        it("should NOT treat minus as unary when used after right parentheses", function () {
            expect(rpn.getFromInfix('2 - (-3) - 4')).toEqual('2 3 _ - 4 -');
        });

        it("should transform simple use of binary operators", function () {
            expect(rpn.getFromInfix('2 + 3')).toEqual('2 3 +');
            expect(rpn.getFromInfix('2 - 3')).toEqual('2 3 -');
            expect(rpn.getFromInfix('2 * 3')).toEqual('2 3 *');
            expect(rpn.getFromInfix('2 x 3')).toEqual('2 3 x');
            expect(rpn.getFromInfix('2 % 3')).toEqual('2 3 %');
            expect(rpn.getFromInfix('2 pow 3')).toEqual('2 3 pow');
        });

        it("should respect precedence/associativity of binary operators", function () {
            expect(rpn.getFromInfix('2 + 3 * 4')).toEqual('2 3 4 * +');
            expect(rpn.getFromInfix('2 / 3 pow 4')).toEqual('2 3 4 pow /');
        });

        it("should respect precedence/associativity of binary and unary operators", function () {
            expect(rpn.getFromInfix('-2 - -3 * -(-4)')).toEqual('2 _ 3 _ 4 _ _ * -');
        });

        it("should forece precedence depending on parentheses", function () {
            expect(rpn.getFromInfix('(2 + 3) * 4')).toEqual('2 3 + 4 *');
            expect(rpn.getFromInfix('(2 / 3) pow 4')).toEqual('2 3 / 4 pow');
            expect(rpn.getFromInfix('-(2 + 3) * -(4 - -5)')).toEqual('2 3 + _ 4 5 _ - _ *');
        });

        it("should throw on mismatched parentheses - missing right", function () {
            function testThrow() {
                return rpn.getFromInfix('((2 + 3) * 1');
            }

            expect(testThrow).toThrowError(/Mismatched parentheses/);
        });

        it("should throw on mismatched parentheses - missing left", function () {
            function testThrow() {
                return rpn.getFromInfix('(2 + 3) * 1)');
            }

            expect(testThrow).toThrowError(/Mismatched parentheses/);
        });
    });
});<commit_msg>Improve infix to RPN tests<commit_after>define(['rpn/main'], function (rpn) {
    'use strict';

    describe('Infix to RPN', function () {
        it("should ignore empty expressions", function () {
            expect(rpn.getFromInfix('')).toEqual('');
        });

        it("should NOT transform single-number non-negative expressions", function () {
            expect(rpn.getFromInfix('2')).toEqual('2');
        });

        it("should transform simple use of unary operators", function () {
            expect(rpn.getFromInfix('_ 2')).toEqual('2 _');
        });

        it("should treat minus as unary when in the beginning", function () {
            expect(rpn.getFromInfix('-2')).toEqual('2 _');
        });

        it("should treat minus as unary when used after another operator", function () {
            expect(rpn.getFromInfix('2 - -3')).toEqual('2 3 _ -');
        });

        it("should treat minus as unary when used after left parentheses", function () {
            expect(rpn.getFromInfix('2 - (-3)')).toEqual('2 3 _ -');
        });

        it("should NOT treat minus as unary when used after right parentheses", function () {
            expect(rpn.getFromInfix('2 - (-3) - 4')).toEqual('2 3 _ - 4 -');
        });

        it("should transform simple use of binary operators", function () {
            expect(rpn.getFromInfix('2 + 3')).toEqual('2 3 +');
            expect(rpn.getFromInfix('2 - 3')).toEqual('2 3 -');
            expect(rpn.getFromInfix('2 * 3')).toEqual('2 3 *');
            expect(rpn.getFromInfix('2 x 3')).toEqual('2 3 x');
            expect(rpn.getFromInfix('2 % 3')).toEqual('2 3 %');
            expect(rpn.getFromInfix('2 pow 3')).toEqual('2 3 pow');
        });

        it("should respect precedence operators with right associativity", function () {
            expect(rpn.getFromInfix('2 pow -2 pow -2')).toEqual('2 2 _ 2 _ pow pow');
        });

        it("should respect precedence/associativity of binary operators", function () {
            expect(rpn.getFromInfix('0 + 1 - 2 + 3 * 4 x 5 / 6 % 7')).toEqual('0 1 + 2 - 3 4 * 5 x 6 / 7 % +');
            expect(rpn.getFromInfix('2 - 3 - 4')).toEqual('2 3 - 4 -');
            expect(rpn.getFromInfix('2 + 3 + 4')).toEqual('2 3 + 4 +');
            expect(rpn.getFromInfix('2 x 3 x 4')).toEqual('2 3 x 4 x');
            expect(rpn.getFromInfix('2 / 3 / 4')).toEqual('2 3 / 4 /');
            expect(rpn.getFromInfix('2 % 3 % 4')).toEqual('2 3 % 4 %');
            expect(rpn.getFromInfix('1 / 2 pow 3 pow -4')).toEqual('1 2 3 4 _ pow pow /');
        });

        it("should respect precedence/associativity of binary and unary operators", function () {
            expect(rpn.getFromInfix('-2 - -3 * -(-4)')).toEqual('2 _ 3 _ 4 _ _ * -');
        });

        it("should forece precedence depending on parentheses", function () {
            expect(rpn.getFromInfix('(2 + 3) * 4')).toEqual('2 3 + 4 *');
            expect(rpn.getFromInfix('(2 / 3) pow 4')).toEqual('2 3 / 4 pow');
            expect(rpn.getFromInfix('-(2 + 3) * -(4 - -5) + 1')).toEqual('2 3 + _ 4 5 _ - _ * 1 +');
        });

        it("should throw on mismatched parentheses - missing right", function () {
            function testThrow() {
                return rpn.getFromInfix('((2 + 3) * 1');
            }

            expect(testThrow).toThrowError(/Mismatched parentheses/);
        });

        it("should throw on mismatched parentheses - missing left", function () {
            function testThrow() {
                return rpn.getFromInfix('(2 + 3) * 1)');
            }

            expect(testThrow).toThrowError(/Mismatched parentheses/);
        });
    });
});<|endoftext|>