<commit_before>// Rollup plugins.
import buble from 'rollup-plugin-buble'
import cjs from 'rollup-plugin-commonjs'
import globals from 'rollup-plugin-node-globals'
import replace from 'rollup-plugin-replace'
import resolve from 'rollup-plugin-node-resolve'

export default {
  dest: 'build/app.js',
  entry: 'src/index.js',
  format: 'iife',
  plugins: [
    buble(),
    cjs({
      exclude: 'node_modules/process-es6/**',
      include: [
        'node_modules/fbjs/**',
        'node_modules/object-assign/**',
        'node_modules/react/**',
        'node_modules/react-dom/**'
      ]
    }),
    globals(),
    replace({ 'process.env.NODE_ENV': JSON.stringify('development') }),
    resolve({
      browser: true,
      main: true
    })
  ],
  sourceMap: true
}
<commit_msg>Add prop-types module in config/dev.<commit_after>// Rollup plugins.
import buble from 'rollup-plugin-buble'
import cjs from 'rollup-plugin-commonjs'
import globals from 'rollup-plugin-node-globals'
import replace from 'rollup-plugin-replace'
import resolve from 'rollup-plugin-node-resolve'

export default {
  dest: 'build/app.js',
  entry: 'src/index.js',
  format: 'iife',
  plugins: [
    buble(),
    cjs({
      exclude: 'node_modules/process-es6/**',
      include: [
        'node_modules/fbjs/**',
        'node_modules/object-assign/**',
        'node_modules/react/**',
        'node_modules/react-dom/**',
        'node_modules/prop-types/**'
      ]
    }),
    globals(),
    replace({ 'process.env.NODE_ENV': JSON.stringify('development') }),
    resolve({
      browser: true,
      main: true
    })
  ],
  sourceMap: true
}
<|endoftext|>


<commit_before>/**
 * Load app configurations
 */

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

const devConfig = require('./config.default.dev');
const prodConfig = require('./config.default.prod');

//get custom config path from env
const customConfigPath = process.env.NODE_CONFIG_PATH;
const nodeBuildEnv = process.env.NODE_BUILD_ENV;

const DEFAULT_PREFIX_KEY = 'defaultPrefix';

let defaultConfigJS = '../app-config.js';
const defaultConfigJSAlt = './app-config.js';

try {
  fs.statSync(path.join(__dirname, defaultConfigJS));
} catch (e) {
  defaultConfigJS = defaultConfigJSAlt;
}

const configPath = customConfigPath
  ? path.resolve(customConfigPath)
  : path.join(__dirname, defaultConfigJS);
// console.log(configPath);
let configInfo = {};
let hasCustomConfig = true;
let checkMsg = '';

try {
  fs.statSync(configPath);
} catch (e) {
  console.error(e);
  hasCustomConfig = false;
}

// console.log('process.env.STATIC_PREFIX: ', process.env.STATIC_PREFIX);
// console.log('process.env.APP_PREFIX: ', process.env.APP_PREFIX);

if (hasCustomConfig) {
  configInfo = require(configPath);
  checkMsg += `Using [${chalk.green(configPath)}] as app configuration`;
} else {
  configInfo = !nodeBuildEnv ? prodConfig : devConfig;
  checkMsg += `Using [${chalk.green(
    !nodeBuildEnv ? 'config.default.dev' : 'config.default.prod'
  )}] as app configuration`;
}

console.log(checkMsg);

const config = {};
//cache non-empty config from env at init time instead of accessing from process.env at runtime to improve performance
for (let key in configInfo) {
  if (configInfo.hasOwnProperty(key)) {
    config[key] = process.env.hasOwnProperty(key)
      ? process.env[key]
      : configInfo[key];
  }
}

// console.log(config);

function getConfigProperty(key) {
  let value = undefined;
  if (config.hasOwnProperty(key)) {
    // console.log(`config[${key}] from cache`);
    value = config[key];
  } else {
    // console.log(`config[${key}] from process.env`);
    value = process.env[key];
  }
  return value;
}

// console.log('config: ', config);

module.exports = {
  getListeningPort: () => {
    return getConfigProperty('PORT') || getConfigProperty('NODE_PORT');
  },
  getNodeEnv: () => {
    return getConfigProperty('NODE_ENV');
  },
  isDevMode: () => {
    const env = getConfigProperty('NODE_ENV');
    return 'dev' === env || 'development' === env;
  },
  isProdMode: () => {
    const env = getConfigProperty('NODE_ENV');
    return 'prod' === env || 'production' === env;
  },
  isNodeProxyEnabled: () => {
    return !!getConfigProperty('NODE_PROXY');
  },
  getStaticAssetsEndpoint: () => {
    //AKA, get CDN domain
    return getConfigProperty('STATIC_ENDPOINT');
  },
  getAppPrefix: () => {
    return getConfigProperty('APP_PREFIX') || '';
  },
  getStaticPrefix: () => {
    return getConfigProperty('STATIC_PREFIX') || '';
  },
  isPrefixTailSlashEnabled: () => {
    return !!getConfigProperty('PREFIX_TRAILING_SLASH');
  },
  getApiEndPoints: () => {
    return getConfigProperty('API_ENDPOINTS');
  },
  getProxyDebugLevel: () => {
    return getConfigProperty('PROXY_DEBUG_LEVEL');
  },
  isHMREnabled: () => {
    const val = getConfigProperty('ENABLE_HMR');
    return module.exports.isDevMode() && isTrue(val);
  },
  isSSREnabled: () => {
    const val = getConfigProperty('ENABLE_SSR');
    return isTrue(val) && !module.exports.isHMREnabled();
  },
  isBundleAnalyzerEnabled: () => {
    const val = getConfigProperty('BUNDLE_ANALYZER');
    return isTrue(val);
  },
  isCustomAPIPrefix: () => {
    return !!getConfigProperty('CUSTOM_API_PREFIX');
  },
  getLogPath: () => {
    return getConfigProperty('LOG_PATH') || path.join(__dirname, '../logs');
  },
  getHttpProxy: () => {
    return getConfigProperty('HTTP_PROXY');
  },
  getDefaultApiEndPoint: () => {
    const obj = getConfigProperty('API_ENDPOINTS');
    return obj[obj[DEFAULT_PREFIX_KEY]];
  },
  getDefaultApiEndPointKey: () => {
    return DEFAULT_PREFIX_KEY;
  },
  isInlineStyles: () => {
    return getConfigProperty('INLINE_STYLES');
  },
  getEnv: key => {
    return getConfigProperty(key);
  },
};

function isTrue(val) {
  return !!(val && (val === true || val === 'true' || val === '1'));
}
<commit_msg>:wrench:Do not log error when no custom config file provided<commit_after>/**
 * Load app configurations
 */

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

const devConfig = require('./config.default.dev');
const prodConfig = require('./config.default.prod');

//get custom config path from env
const customConfigPath = process.env.NODE_CONFIG_PATH;
const nodeBuildEnv = process.env.NODE_BUILD_ENV;

const DEFAULT_PREFIX_KEY = 'defaultPrefix';

let defaultConfigJS = '../app-config.js';
const defaultConfigJSAlt = './app-config.js';

try {
  fs.statSync(path.join(__dirname, defaultConfigJS));
} catch (e) {
  defaultConfigJS = defaultConfigJSAlt;
}

const configPath = customConfigPath
  ? path.resolve(customConfigPath)
  : path.join(__dirname, defaultConfigJS);
// console.log(configPath);
let configInfo = {};
let hasCustomConfig = true;
let checkMsg = '';

try {
  fs.statSync(configPath);
} catch (e) {
  hasCustomConfig = false;
}

// console.log('process.env.STATIC_PREFIX: ', process.env.STATIC_PREFIX);
// console.log('process.env.APP_PREFIX: ', process.env.APP_PREFIX);

if (hasCustomConfig) {
  configInfo = require(configPath);
  checkMsg += `Using [${chalk.green(configPath)}] as app configuration`;
} else {
  configInfo = !nodeBuildEnv ? prodConfig : devConfig;
  checkMsg += `Using [${chalk.green(
    !nodeBuildEnv ? 'config.default.dev' : 'config.default.prod'
  )}] as app configuration`;
}

console.log(checkMsg);

const config = {};
//cache non-empty config from env at init time instead of accessing from process.env at runtime to improve performance
for (let key in configInfo) {
  if (configInfo.hasOwnProperty(key)) {
    config[key] = process.env.hasOwnProperty(key)
      ? process.env[key]
      : configInfo[key];
  }
}

// console.log(config);

function getConfigProperty(key) {
  let value = undefined;
  if (config.hasOwnProperty(key)) {
    // console.log(`config[${key}] from cache`);
    value = config[key];
  } else {
    // console.log(`config[${key}] from process.env`);
    value = process.env[key];
  }
  return value;
}

// console.log('config: ', config);

module.exports = {
  getListeningPort: () => {
    return getConfigProperty('PORT') || getConfigProperty('NODE_PORT');
  },
  getNodeEnv: () => {
    return getConfigProperty('NODE_ENV');
  },
  isDevMode: () => {
    const env = getConfigProperty('NODE_ENV');
    return 'dev' === env || 'development' === env;
  },
  isProdMode: () => {
    const env = getConfigProperty('NODE_ENV');
    return 'prod' === env || 'production' === env;
  },
  isNodeProxyEnabled: () => {
    return !!getConfigProperty('NODE_PROXY');
  },
  getStaticAssetsEndpoint: () => {
    //AKA, get CDN domain
    return getConfigProperty('STATIC_ENDPOINT');
  },
  getAppPrefix: () => {
    return getConfigProperty('APP_PREFIX') || '';
  },
  getStaticPrefix: () => {
    return getConfigProperty('STATIC_PREFIX') || '';
  },
  isPrefixTailSlashEnabled: () => {
    return !!getConfigProperty('PREFIX_TRAILING_SLASH');
  },
  getApiEndPoints: () => {
    return getConfigProperty('API_ENDPOINTS');
  },
  getProxyDebugLevel: () => {
    return getConfigProperty('PROXY_DEBUG_LEVEL');
  },
  isHMREnabled: () => {
    const val = getConfigProperty('ENABLE_HMR');
    return module.exports.isDevMode() && isTrue(val);
  },
  isSSREnabled: () => {
    const val = getConfigProperty('ENABLE_SSR');
    return isTrue(val) && !module.exports.isHMREnabled();
  },
  isBundleAnalyzerEnabled: () => {
    const val = getConfigProperty('BUNDLE_ANALYZER');
    return isTrue(val);
  },
  isCustomAPIPrefix: () => {
    return !!getConfigProperty('CUSTOM_API_PREFIX');
  },
  getLogPath: () => {
    return getConfigProperty('LOG_PATH') || path.join(__dirname, '../logs');
  },
  getHttpProxy: () => {
    return getConfigProperty('HTTP_PROXY');
  },
  getDefaultApiEndPoint: () => {
    const obj = getConfigProperty('API_ENDPOINTS');
    return obj[obj[DEFAULT_PREFIX_KEY]];
  },
  getDefaultApiEndPointKey: () => {
    return DEFAULT_PREFIX_KEY;
  },
  getEnv: key => {
    return getConfigProperty(key);
  },
};

function isTrue(val) {
  return !!(val && (val === true || val === 'true' || val === '1'));
}
<|endoftext|>


<commit_before>'use strict';

var isProduction = process.env.NODE_ENV === 'production';

exports.version = '3.14.1';

exports.config = {
    combine: isProduction,
    filter : isProduction ? 'min' : 'raw',
    root   : exports.version + '/',

    groups: {
        'app': {
            combine  : isProduction,
            comboBase: '/combo/' + require('../package').version + '?',
            base     : '/',
            root     : '/',

            modules: {
                'css-mediaquery': {
                    path: 'vendor/css-mediaquery.js'
                },

                'handlebars-runtime': {
                    path: 'vendor/handlebars.runtime.js'
                },

                'rework': {
                    path: 'vendor/rework.js'
                },

                'rework-pure-grids': {
                    path: 'vendor/rework-pure-grids.js'
                }
            }
        }
    }
};
<commit_msg>add new modules to YUI config<commit_after>'use strict';

var isProduction = process.env.NODE_ENV === 'production';

exports.version = '3.14.1';

exports.config = {
    combine: isProduction,
    filter : isProduction ? 'min' : 'raw',
    root   : exports.version + '/',

    groups: {
        'app': {
            combine  : isProduction,
            comboBase: '/combo/' + require('../package').version + '?',
            base     : '/',
            root     : '/',

            modules: {
                'css-mediaquery': {
                    path: 'vendor/css-mediaquery.js'
                },

                'handlebars-runtime': {
                    path: 'vendor/handlebars.runtime.js'
                },

                'rework': {
                    path: 'vendor/rework.js'
                },

                'rework-pure-grids': {
                    path: 'vendor/rework-pure-grids.js'
                },

                'grid-router': {
                    path: 'js/grid-router.js'
                },

                'grid-model': {
                    path: 'js/models/grid-model.js'
                },

                'mq-model-list': {
                    path: 'js/models/mq-model-list.js'
                },

                'grid-input-view': {
                    path: 'js/views/grid-input-view.js'
                },

                'grid-output-view': {
                    path: 'js/views/grid-output-view.js'
                }
            }
        }
    }
};
<|endoftext|>


<commit_before>module.exports = {

	//---------------------------------------------------------------------
	// Action Name
	//
	// This is the name of the action displayed in the editor.
	//---------------------------------------------------------------------

	name: "Bot Typing",

	//---------------------------------------------------------------------
	// Action Section
	//
	// This is the section the action will fall into.
	//---------------------------------------------------------------------

	section: "Bot Client Control",

	//---------------------------------------------------------------------
	// Action Subtitle
	//
	// This function generates the subtitle displayed next to the name.
	//---------------------------------------------------------------------

	subtitle: function(data) {
		const names = ['Same Channel', 'Mentioned Channel', 'Default Channel', 'Temp Variable', 'Server Variable', 'Global Variable'];
		const names2 = ['Starts Typing', 'Stops Typing']
		const index2 = parseInt(data.EliteArtzIsPro);
		const index = parseInt(data.storage);
		return index < 3 ? `${names[index]} - ${names2[index2]}` : `${names[index]} - ${data.varName} - ${names2[index2]}`;
	},

	//---------------------------------------------------------------------
	// Action Fields
	//
	// These are the fields for the action. These fields are customized
	// by creating elements with corresponding IDs in the HTML. These
	// are also the names of the fields stored in the action's JSON data.
	//---------------------------------------------------------------------

	fields: ["storage", "varName", "EliteArtzIsPro"],

	//---------------------------------------------------------------------
	// Command HTML
	//
	// This function returns a string containing the HTML used for
	// editting actions.
	//
	// The "isEvent" parameter will be true if this action is being used
	// for an event. Due to their nature, events lack certain information,
	// so edit the HTML to reflect this.
	//
	// The "data" parameter stores constants for select elements to use.
	// Each is an array: index 0 for commands, index 1 for events.
	// The names are: sendTargets, members, roles, channels,
	//                messages, servers, variables
	//---------------------------------------------------------------------

	html: function(isEvent, data) {
		return `

				Mod Info:

				Created by Lasse! (Merged by EliteArtz)

			Typing Option:

			<select id="EliteArtzIsPro" class="round">
				<option value="0" selected>Start Typing</option>
				<option value="1">Stop Typing</option>
			</select>

			Channel to start typing in:

			<select id="storage" class="round" onchange="glob.channelChange(this, 'varNameContainer')">
				${data.channels[isEvent ? 1 : 0]}
			</select>

			Variable Name:

			<input id="varName" class="round" type="text" list="variableList">

			You can stop the typing with Stop Typing

`
	},

	//---------------------------------------------------------------------
	// Action Editor Init Code
	//
	// When the HTML is first applied to the action editor, this code
	// is also run. This helps add modifications or setup reactionary
	// functions for the DOM elements.
	//---------------------------------------------------------------------

	init: function() {
		const {glob, document} = this;

		glob.channelChange(document.getElementById('storage'), 'varNameContainer');
	},

	//---------------------------------------------------------------------
	// Action Bot Function
	//
	// This is the function for the action within the Bot's Action class.
	// Keep in mind event calls won't have access to the "msg" parameter,
	// so be sure to provide checks for variable existance.
	//---------------------------------------------------------------------

	action: function(cache) {
		const data = cache.actions[cache.index];
		const storage = parseInt(data.storage);
		const varName = this.evalMessage(data.VarName, cache);
		const time = parseInt(this.evalMessage(data.time, cache));
		const channel = this.getChannel(storage, varName, cache);

		try { //This "Try and Catch" Function is really useful for when it's coming up an error, it will log it in your logs.
			if (data.EliteArtzIsPro === "0") { //"If and else" Function is for looking if the result of them equals what you wan't.
				channel.startTyping(); //Starts the Typing
			} else {
				channel.stopTyping(true); //Stops the Typing
			}
		} catch (e) {
			console.error("ERROR!" + e + e.stack); // Here it's gonna log if an error occured.
		}

		this.callNextAction(cache);
	},

	//---------------------------------------------------------------------
	// Action Bot Mod
	//
	// Upon initialization of the bot, this code is run. Using the bot's
	// DBM namespace, one can add/modify existing functions if necessary.
	// In order to reduce conflictions between mods, be sure to alias
	// functions you wish to overwrite.
	//---------------------------------------------------------------------

	mod: function(DBM) {
	}

	}; // End of module
	<commit_msg>No need to Download! ~ Fixed Layout of Typing<commit_after>module.exports = {

	//---------------------------------------------------------------------
	// Action Name
	//
	// This is the name of the action displayed in the editor.
	//---------------------------------------------------------------------

	name: "Bot Typing",

	//---------------------------------------------------------------------
	// Action Section
	//
	// This is the section the action will fall into.
	//---------------------------------------------------------------------

	section: "Bot Client Control",

	//---------------------------------------------------------------------
	// Action Subtitle
	//
	// This function generates the subtitle displayed next to the name.
	//---------------------------------------------------------------------

	subtitle: function(data) {
		const names = ['Same Channel', 'Mentioned Channel', 'Default Channel', 'Temp Variable', 'Server Variable', 'Global Variable'];
		const names2 = ['Starts Typing', 'Stops Typing']
		const index2 = parseInt(data.EliteArtzIsPro);
		const index = parseInt(data.storage);
		return index < 3 ? `${names[index]} - ${names2[index2]}` : `${names[index]} - ${data.varName} - ${names2[index2]}`;
	},

	//---------------------------------------------------------------------
	// Action Fields
	//
	// These are the fields for the action. These fields are customized
	// by creating elements with corresponding IDs in the HTML. These
	// are also the names of the fields stored in the action's JSON data.
	//---------------------------------------------------------------------

	fields: ["storage", "varName", "EliteArtzIsPro"],

	//---------------------------------------------------------------------
	// Command HTML
	//
	// This function returns a string containing the HTML used for
	// editting actions.
	//
	// The "isEvent" parameter will be true if this action is being used
	// for an event. Due to their nature, events lack certain information,
	// so edit the HTML to reflect this.
	//
	// The "data" parameter stores constants for select elements to use.
	// Each is an array: index 0 for commands, index 1 for events.
	// The names are: sendTargets, members, roles, channels,
	//                messages, servers, variables
	//---------------------------------------------------------------------

	html: function(isEvent, data) {
		return `

				Mod Info:

				Created by Lasse! (Merged by EliteArtz)

			Typing Option:

			<select id="EliteArtzIsPro" class="round">
				<option value="0" selected>Start Typing</option>
				<option value="1">Stop Typing</option>
			</select>

			Channel to start typing in:

			<select id="storage" class="round" onchange="glob.channelChange(this, 'varNameContainer')">
				${data.channels[isEvent ? 1 : 0]}
			</select>

			Variable Name:

			<input id="varName" class="round" type="text" list="variableList">

			You can stop the typing with Stop Typing

`
	},

	//---------------------------------------------------------------------
	// Action Editor Init Code
	//
	// When the HTML is first applied to the action editor, this code
	// is also run. This helps add modifications or setup reactionary
	// functions for the DOM elements.
	//---------------------------------------------------------------------

	init: function() {
		const {glob, document} = this;

		glob.channelChange(document.getElementById('storage'), 'varNameContainer');
	},

	//---------------------------------------------------------------------
	// Action Bot Function
	//
	// This is the function for the action within the Bot's Action class.
	// Keep in mind event calls won't have access to the "msg" parameter,
	// so be sure to provide checks for variable existance.
	//---------------------------------------------------------------------

	action: function(cache) {
		const data = cache.actions[cache.index];
		const storage = parseInt(data.storage);
		const varName = this.evalMessage(data.VarName, cache);
		const time = parseInt(this.evalMessage(data.time, cache));
		const channel = this.getChannel(storage, varName, cache);

		try { //This "Try and Catch" Function is really useful for when it's coming up an error, it will log it in your logs.
			if (data.EliteArtzIsPro === "0") { //"If and else" Function is for looking if the result of them equals what you wan't.
				channel.startTyping(); //Starts the Typing
			} else {
				channel.stopTyping(true); //Stops the Typing
			}
		} catch (e) {
			console.error("ERROR!" + e + e.stack); // Here it's gonna log if an error occured.
		}

		this.callNextAction(cache);
	},

	//---------------------------------------------------------------------
	// Action Bot Mod
	//
	// Upon initialization of the bot, this code is run. Using the bot's
	// DBM namespace, one can add/modify existing functions if necessary.
	// In order to reduce conflictions between mods, be sure to alias
	// functions you wish to overwrite.
	//---------------------------------------------------------------------

	mod: function(DBM) {
	}

	}; // End of module
	<|endoftext|>


<commit_before>import Ember from 'ember';

const {
  RSVP,
  merge,
  computed,
  getOwner
} = Ember;

const DEFAULT_SOURCE = 'application';

export default Ember.Service.extend({

  config: computed(function() {
    return getOwner(this).resolveRegistration('config:environment') || {};
  }),

  isFastBoot : computed.reads('fastBoot.isFastBoot'),
  fastBoot   : computed(function() {
    return getOwner(this).lookup('service:fastboot');
  }),

  tml:null,

  initialize(config){
    if(config) {
      this.set('config.tml', config);
    }
    return new RSVP.Promise((resolve, reject) => {
      if(this.get('config.tml.key')) {
        try {
          if(this.get('isFastBoot')){
            this.initServer(resolve)
          } else {
            this.initClient(resolve)
          }
        } catch(e) {
          reject(e)
        }
      } else {
        resolve() // tml is disabled
      }
    });
  },

  initServer(callback) {
    let config  = this.get('config.tml');
    /* eslint-disable */
    let tml     = FastBoot.require('tml-server');
    /* eslint-enable */
    let cookie  = this.get(`fastBoot.request.cookies.trex_${config.key}`) || '';
    let server  = config.server || {};
    let app     = new tml.Application({ key: config.key });

    cookie = tml.utils ? (tml.utils.decode(cookie)||{}) : {};

    let locale     = (server.locale || config.locale || cookie.locale);
    let translator = (server.translator || cookie.translator || cookie.translator);

    let opts = merge({
      current_locale      : locale,
      current_source      : config.source || DEFAULT_SOURCE,
      current_translator  : translator || null,
      cache               : server.cache
    }, server);

    tml.config.initCache(config.key);

    app.init(opts, () => {
      tml.app = app;
      this.set('tml', tml);
      callback(tml)
    });
  },

  initClient(callback) {
    let tml = window.tml;
    let opts = merge({ source: DEFAULT_SOURCE }, this.get('config.tml'));

    tml.init(opts, () => {
      this.set('tml', tml);
      callback(tml);
    });
  },

  agent: computed(function(){
    return window.Trex;
  }),

  app: computed.readOnly('tml.app'),

  currentApplication: computed.readOnly('app'),
  currentSource     : computed.readOnly('app.current_source'),
  currentTranslator : computed.readOnly('app.current_translator'),

  currentLanguage: computed(function(){
    return this.get('app').getCurrentLanguage();
  }).readOnly(),

  translationModeEnabled: computed(function(){
    return this.get('app').isInlineModeEnabled();
  }).readOnly(),

  availableLanguages: computed.readOnly('app.languages'),

  translate(label, description, tokens, options={}) {
    let language = this.get('currentLanguage');
    return language ?
      language.translate(label, description, tokens, merge({
        current_translator  : this.get('currentTranslator')
      }, options)) :
      label;
  },

  translateLabel(label, description, tokens, options={}) {
    let language = this.get('currentLanguage');
    return language ?
      language.translateLabel(label, description, tokens, merge({
        current_translator  : this.get('currentTranslator')
      }, options)) :
      label;
  },

  tr()  { return this.translate.apply(this, arguments); },
  trl() { return this.translateLabel.apply(this, arguments); },

  beginBlock(opts={}) {
    if(this.get('tml.block_options')) {
      this.get('tml.block_options').unshift(opts);
    }
  },

  endBlock() {
    if(this.get('tml.block_options')) {
      this.get('tml.block_options').pop();
    }
  },

  setSource(name) {
    return new RSVP.Promise((res) => {
      if(this.get('tml').setSource) {
        this.get('tml').setSource(name, res);
      }
      else { res(); }
    })
  },

  changeLanguage(locale) {
    this.get('tml.app').changeLanguage(locale, () => {
      this.get('tml').changeLanguage(locale);
      window.location.reload();
    });
  },

  toggleTranslationMode() {
    if(this.get('agent')){
      this.get('agent').toggleTranslationMode();
    }
  }

});
<commit_msg>fix for translateLabel<commit_after>import Ember from 'ember';

const {
  RSVP,
  merge,
  computed,
  getOwner
} = Ember;

const DEFAULT_SOURCE = 'application';

export default Ember.Service.extend({

  config: computed(function() {
    return getOwner(this).resolveRegistration('config:environment') || {};
  }),

  isFastBoot : computed.reads('fastBoot.isFastBoot'),
  fastBoot   : computed(function() {
    return getOwner(this).lookup('service:fastboot');
  }),

  tml:null,

  initialize(config){
    if(config) {
      this.set('config.tml', config);
    }
    return new RSVP.Promise((resolve, reject) => {
      if(this.get('config.tml.key')) {
        try {
          if(this.get('isFastBoot')){
            this.initServer(resolve)
          } else {
            this.initClient(resolve)
          }
        } catch(e) {
          reject(e)
        }
      } else {
        resolve() // tml is disabled
      }
    });
  },

  initServer(callback) {
    let config  = this.get('config.tml');
    /* eslint-disable */
    let tml     = FastBoot.require('tml-server');
    /* eslint-enable */
    let cookie  = this.get(`fastBoot.request.cookies.trex_${config.key}`) || '';
    let server  = config.server || {};
    let app     = new tml.Application({ key: config.key });

    cookie = tml.utils ? (tml.utils.decode(cookie)||{}) : {};

    let locale     = (server.locale || config.locale || cookie.locale);
    let translator = (server.translator || cookie.translator || cookie.translator);

    let opts = merge({
      current_locale      : locale,
      current_source      : config.source || DEFAULT_SOURCE,
      current_translator  : translator || null,
      cache               : server.cache
    }, server);

    tml.config.initCache(config.key);

    app.init(opts, () => {
      tml.app = app;
      this.set('tml', tml);
      callback(tml)
    });
  },

  initClient(callback) {
    let tml = window.tml;
    let opts = merge({ source: DEFAULT_SOURCE }, this.get('config.tml'));

    tml.init(opts, () => {
      this.set('tml', tml);
      callback(tml);
    });
  },

  agent: computed(function(){
    return window.Trex;
  }),

  app: computed.readOnly('tml.app'),

  currentApplication: computed.readOnly('app'),
  currentSource     : computed.readOnly('app.current_source'),
  currentTranslator : computed.readOnly('app.current_translator'),

  currentLanguage: computed(function(){
    return this.get('app').getCurrentLanguage();
  }).readOnly(),

  translationModeEnabled: computed(function(){
    return this.get('app').isInlineModeEnabled();
  }).readOnly(),

  availableLanguages: computed.readOnly('app.languages'),

  translate(label, description, tokens, options={}) {
    let language = this.get('currentLanguage');
    return language ?
      language.translate(label, description, tokens, merge({
        current_translator  : this.get('currentTranslator')
      }, options)) :
      label;
  },

  translateLabel(label, description, tokens, options={}) {
    let language = this.get('currentLanguage');
    return language ?
      language.translate(label, description, tokens, merge({
        current_translator  : this.get('currentTranslator'),
        skip_decorations    : true
      }, options)) :
      label;
  },

  tr()  { return this.translate.apply(this, arguments); },
  trl() { return this.translateLabel.apply(this, arguments); },

  beginBlock(opts={}) {
    if(this.get('tml.block_options')) {
      this.get('tml.block_options').unshift(opts);
    }
  },

  endBlock() {
    if(this.get('tml.block_options')) {
      this.get('tml.block_options').pop();
    }
  },

  setSource(name) {
    return new RSVP.Promise((res) => {
      if(this.get('tml').setSource) {
        this.get('tml').setSource(name, res);
      }
      else { res(); }
    })
  },

  changeLanguage(locale) {
    this.get('tml.app').changeLanguage(locale, () => {
      this.get('tml').changeLanguage(locale);
      window.location.reload();
    });
  },

  toggleTranslationMode() {
    if(this.get('agent')){
      this.get('agent').toggleTranslationMode();
    }
  }

});
<|endoftext|>


<commit_before>import generatorRows from '../src/formatters/rows/generatorRows';
import zipcelx, { generateXMLWorksheet } from '../src/zipcelx';
import { ERROR_INVALID_CONFIG } from '../src/commons/constants';

console.error = jest.genMockFn();

const baseConfig = {
  filename: 'report',
  sheet: {
    data: [
      [{
        value: 'Monkey',
        type: 'string'
      }, {
        value: 1000,
        type: 'number'
      }]
    ]
  }
};

describe('XML Formatter', () => {
  const rowsXML = `<row r="1"><c r="A1" t="inlineStr"><is><t>Monkey</t></is></c><c r="B1"><v>1000</v></c></row>`;

  it('Should console log error if validator fails', () => {
    let config = Object.assign({}, baseConfig, { sheet: { data: [{test: 'demo'}] } });
    zipcelx(config);
    expect(console.error).toBeCalled();
  });

  it('Should map row arrays to XML markup', () => {
    expect(generatorRows(baseConfig.sheet.data)).toBe(rowsXML);
  });

  it('Should generate and XML Worksheet from template', () => {
    const expectedXML = [
      '<?xml version="1.0" ?>',
      `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><sheetData>${rowsXML}</sheetData></worksheet>`
    ].join('\n');
    expect(generateXMLWorksheet(baseConfig.sheet.data)).toBe(expectedXML);
  });
});
<commit_msg>Changed test copy<commit_after>import generatorRows from '../src/formatters/rows/generatorRows';
import zipcelx, { generateXMLWorksheet } from '../src/zipcelx';
import { ERROR_INVALID_CONFIG } from '../src/commons/constants';

console.error = jest.genMockFn();

const baseConfig = {
  filename: 'report',
  sheet: {
    data: [
      [{
        value: 'Monkey',
        type: 'string'
      }, {
        value: 1000,
        type: 'number'
      }]
    ]
  }
};

describe('Zipcelx', () => {
  const rowsXML = `<row r="1"><c r="A1" t="inlineStr"><is><t>Monkey</t></is></c><c r="B1"><v>1000</v></c></row>`;

  it('Should console log error if validator fails', () => {
    let config = Object.assign({}, baseConfig, { sheet: { data: [{test: 'demo'}] } });
    zipcelx(config);
    expect(console.error).toBeCalled();
  });

  it('Should map row arrays to XML markup', () => {
    expect(generatorRows(baseConfig.sheet.data)).toBe(rowsXML);
  });

  it('Should generate and XML Worksheet from template', () => {
    const expectedXML = [
      '<?xml version="1.0" ?>',
      `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"><sheetData>${rowsXML}</sheetData></worksheet>`
    ].join('\n');
    expect(generateXMLWorksheet(baseConfig.sheet.data)).toBe(expectedXML);
  });
});
<|endoftext|>


<commit_before>jest.dontMock('../lib/monkey.js');
jest.dontMock('underscore');
jest.dontMock('async');

//jest.dontMock('loglevel'); require('loglevel').setLevel('TRACE');

describe('Monkey', function () {

  var Monkey = require('../lib/monkey');

  describe('constructor', function () {

    it('creates the processes array', function () {
      expect(new Monkey().processes).toEqual(jasmine.any(Array));
    });

    it('created an options object if non are passed', function () {
      var monkey = new Monkey();
      expect(monkey.options).toBeDefined();
    });

    it('stores the options object', function () {
      var myOptions = {};
      var monkey = new Monkey(myOptions);
      expect(monkey.options).toBe(myOptions);
    });

    it('puts all the options on the environment hash prefixed with [monkey.]', function () {

      var myOptions = {
        a: 1,
        b: "aString"
      };
      var monkey = new Monkey(myOptions);

      expect(process.env['monkey.a']).toBe(myOptions.a.toString());
      expect(process.env['monkey.b']).toBe(myOptions.b);

    });

  });

  describe('bin path', function () {

    it('sets the bin path to the location of cuke-monkey', function () {
      expect(Monkey.bin.match(/cuke-monkey\/bin\/cuke-monkey$/)).not.toBe(null);
    });

  });

  describe('init', function () {

    it('runs in single mode when no mode option is passed', function () {

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      monkey.start = jest.genMockFunction();
      monkey.watch = jest.genMockFunction();
      var callback = function () {};

      monkey.init(callback);

      expect(monkey.run).toBeCalledWith(callback);
      expect(monkey.run.mock.calls.length).toBe(1);

      expect(monkey.start.mock.calls.length).toBe(0);
      expect(monkey.watch.mock.calls.length).toBe(0);

    });

    it('runs in watch mode)', function () {

      var monkey = new Monkey({watch: true});

      monkey.run = jest.genMockFunction();
      monkey.start = jest.genMockFunction();
      monkey.watch = jest.genMockFunction();

      monkey.init();

      expect(monkey.watch).toBeCalledWith();
      expect(monkey.watch.mock.calls.length).toBe(1);

      expect(monkey.run.mock.calls.length).toBe(0);
      expect(monkey.start.mock.calls.length).toBe(0);
    });

    it('kicks-off the right run [default] / server / watch )', function () {

      var monkey = new Monkey({server: true});

      monkey.run = jest.genMockFunction();
      monkey.start = jest.genMockFunction();
      monkey.watch = jest.genMockFunction();

      monkey.init();

      expect(monkey.start).toBeCalledWith();
      expect(monkey.start.mock.calls.length).toBe(1);

      expect(monkey.run.mock.calls.length).toBe(0);
      expect(monkey.watch.mock.calls.length).toBe(0);
    });

  });

  describe('watch', function () {

    it('initializes chokidar', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var options = {path: 'abc'};
      var monkey = new Monkey(options);
      monkey.run = jest.genMockFunction();

      monkey.watch();

      expect(chokidar.watch.mock.calls[0][0]).toBe(options.path);

    });

    it('all listener is registered after watcher is ready', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var options = {path: 'abc'};
      var monkey = new Monkey(options);

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();
      expect(chokidar.watcher.on.mock.calls[0][0]).toBe('ready');

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];

      readyCallback();
      expect(chokidar.watcher.on.mock.calls[1][0]).toBe('all');

    });

    it('an non-unlink event triggers the interrupt and run sequence', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      var allCallback = chokidar.watcher.on.mock.calls[1][1];

      monkey.rerun = jest.genMockFunction();

      allCallback('not-unlink');

      expect(monkey.rerun.mock.calls.length).toBe(1);

    });

    it('a deleted feature does not trigger the interrupt and run sequence', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      var allCallback = chokidar.watcher.on.mock.calls[1][1];

      monkey.rerun = jest.genMockFunction();

      allCallback('unlink', '/path/some.feature');

      expect(monkey.rerun.mock.calls.length).toBe(0);

    });

    it('a deleted non-feature triggers the interrupt and run sequence', function () {

      var chokidar = require('chokidar');
      var async = require('async');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      var allCallback = chokidar.watcher.on.mock.calls[1][1];

      monkey.rerun = jest.genMockFunction();

      allCallback('unlink', '/path/some.feature.js');

      expect(monkey.rerun.mock.calls.length).toBe(1);

    });

    it('runs on startup', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      expect(monkey.run.mock.calls.length).toBe(1);

    });

  });

  describe('run', function () {

    it('interrupts any existing processes, starts processes and calls callback', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });
      monkey._startProcesses = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });

      var callback = jest.genMockFn();
      monkey.run(callback);

      expect(monkey.interrupt.mock.calls.length).toBe(2);
      expect(monkey._startProcesses.mock.calls.length).toBe(1);
      expect(callback.mock.calls.length).toBe(1);

    });

    it('detects errors in interrupt and calls callback with an error', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFunction().mockImplementation(function (callback) {
        return callback('error');
      });

      var callback = jest.genMockFn();
      monkey.run(callback);

      expect(callback.mock.calls.length).toBe(1);
      expect(callback.mock.calls[0][0]).toEqual('error');

    });

    it('stops all processes on successful runs', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });
      monkey._startProcesses = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });

      monkey.stop = jest.genMockFunction();

      var callback = jest.genMockFn();
      monkey.run(callback);

      expect(monkey.interrupt.mock.calls.length).toBe(2);

    });

  });

  describe('interrupt', function () {

    it('calls interrupt on all processes in the reverse order that they were started', function () {

      jest.dontMock('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      var orderCounter = 0;

      function Process () {
        this.orderRun = -1;
      }

      Process.prototype.interrupt = function (callback) {
        this.orderRun = orderCounter++;
        callback();
      };

      var process1 = new Process('1');
      var process2 = new Process('2');
      monkey.processes = [process1, process2];

      var callback = jest.genMockFunction();

      monkey.interrupt(callback);

      expect(process2.orderRun).toBe(0);
      expect(process1.orderRun).toBe(1);

    });

    it('bubbles callback without modifying the arguments', function () {

      var async = require('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();
      monkey.processes = [{interrupt: jest.genMockFn()}];
      var someArgs = ['some', 'args'];

      async.series = jest.genMockFunction().mockImplementation(function (processes, callback) {
        callback.apply(this, someArgs);
      });

      var callback = jest.genMockFn();
      monkey.interrupt(callback);

      expect(callback.mock.calls.length).toBe(1);
      expect(callback.mock.calls[0]).toEqual(['some', 'args']);

    });

    it('calls the callback when no processes have been started', function () {

      var async = require('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      async.series = jest.genMockFn();

      var callback = jest.genMockFn();
      monkey.interrupt(callback);

      expect(callback.mock.calls.length).toBe(1);
      expect(async.series.mock.calls.length).toBe(0);

    });

  });

  describe('rerun', function () {

    it('calls run if interrupt is successful', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFn().mockImplementation = function (callback) {
        callback(null);
      };

      monkey.run = jest.genMockFn();

      monkey.rerun();

      expect(monkey.run.mock.calls.length).toBe(1);

    });

    it('does not call run if interrupt fails', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFn().mockImplementation = function (callback) {
        callback('Error');
      };

      monkey.run = jest.genMockFn();

      monkey.rerun();

      expect(monkey.run.mock.calls.length).toBe(0);

    });

    it('does not rerun if an rerun is in progress', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFn();
      monkey.run = jest.genMockFn();

      monkey.rerun();
      monkey.rerun();

      expect(monkey.interrupt.mock.calls.length).toBe(1);
      expect(monkey.run.mock.calls.length).toBe(0);
    });

    it('reruns once it has finished rerunning', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFn().mockImplementation = function (callback) {
        callback(null);
        // after the first run, replace this mockImplementation with a standard mock so we
        // can assert on that the rerun interrupts after a successful run
        monkey.interrupt = jest.genMockFn();
      };

      monkey.run = jest.genMockFn().mockImplementation = function (callback) {
        callback(null);
      };

      monkey.rerun();
      expect(monkey.isRerunning).toBe(false);

      monkey.rerun();
      expect(monkey.interrupt.mock.calls.length).toBe(1);

    });

  });

  describe('_startProcesses', function () {

    it('creates an array of series of processes and starts them', function () {

      var async = require('async');

      var Monkey = require('../lib/monkey.js');

      async.series = jest.genMockFn();

      var monkey = new Monkey();
      var processes = [];
      monkey._createProcesses = jest.genMockFunction().mockReturnValue(processes);

      monkey._startProcesses();

      expect(monkey._createProcesses.mock.calls.length).toBe(1);
      expect(monkey.processes).toBe(processes);

    });

    it('start each process in its own context and calls callback once', function () {

      jest.dontMock('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      function Process () {
        this.state = 'constructed';
      }

      Process.prototype.start = function (callback) {
        this.state = 'started';
        callback();
      };

      var processes = [new Process(), new Process()];
      monkey._createProcesses = jest.genMockFunction().mockReturnValue(processes);

      var callback = jest.genMockFunction();

      monkey._startProcesses(callback);

      expect(typeof callback.mock.calls[0][0]).toBe('undefined');
      expect(callback.mock.calls.length).toBe(1);
      expect(processes[0].state).toBe('started');
      expect(processes[1].state).toBe('started');

    });

    it('bubbles up errors in callback if an processes callback with an error', function () {

      jest.dontMock('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      function Process () {
        this.state = 'constructed';
      }

      Process.prototype.start = function (callback) {
        this.state = 'started';
        callback('error!');
      };

      var processes = [new Process('1'), new Process('2')];
      monkey._createProcesses = jest.genMockFunction().mockReturnValue(processes);

      var callback = jest.genMockFunction();

      monkey._startProcesses(callback);

      expect(callback.mock.calls[0][0]).toBe('error!');
      expect(callback.mock.calls.length).toBe(1);
      expect(processes[0].state).toBe('started');
      expect(processes[1].state).toBe('constructed');

    });

  });

  describe('_createProcesses', function () {

    it('adds a phantom', function () {
      var Phantom = require('../lib/phantom.js');
      var Monkey = require('../lib/monkey.js');

      var options = {browser: 'phantomjs'};
      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(Phantom.mock.calls[0][0]).toBe(options);
      expect(processes.length).toBe(2);

    });

    it('adds a selenium when no browser is passed', function () {
      var Selenium = require('../lib/selenium.js');
      var Monkey = require('../lib/monkey.js');

      var options = {browser: 'some-browser', host: ''};
      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(Selenium.mock.calls[0][0]).toBe(options);
      expect(processes.length).toBe(2);
    });

    it('does not add selenium when SauceLabs is the host', function () {
      var Selenium = require('../lib/selenium.js');
      var Monkey = require('../lib/monkey.js');

      var options = {host: 'saucelabs'};
      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(Selenium.mock.calls.length).toBe(0);
      expect(processes.length).toBe(1);
    });

    it('adds cucumber last', function () {
      jest.dontMock('../lib/cucumber.js');

      var Monkey = require('../lib/monkey.js');
      var options = {browser: 'phantomjs'};

      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(typeof processes[0].cucumberChild).toBe('undefined');
      expect(typeof processes[1].cucumberChild).not.toBe('undefined');
    });

    it('should add at least one process', function () {

      var monkey = new Monkey({browser: 'phantomjs'});

      var processes = monkey._createProcesses();

      expect(processes.length).not.toBe(0);
    });

  });

});
<commit_msg>revised testing of rerun method<commit_after>jest.dontMock('../lib/monkey.js');
jest.dontMock('underscore');
jest.dontMock('async');

//jest.dontMock('loglevel'); require('loglevel').setLevel('TRACE');

describe('Monkey', function () {

  var Monkey = require('../lib/monkey');

  describe('constructor', function () {

    it('creates the processes array', function () {
      expect(new Monkey().processes).toEqual(jasmine.any(Array));
    });

    it('created an options object if non are passed', function () {
      var monkey = new Monkey();
      expect(monkey.options).toBeDefined();
    });

    it('stores the options object', function () {
      var myOptions = {};
      var monkey = new Monkey(myOptions);
      expect(monkey.options).toBe(myOptions);
    });

    it('puts all the options on the environment hash prefixed with [monkey.]', function () {

      var myOptions = {
        a: 1,
        b: "aString"
      };
      var monkey = new Monkey(myOptions);

      expect(process.env['monkey.a']).toBe(myOptions.a.toString());
      expect(process.env['monkey.b']).toBe(myOptions.b);

    });

  });

  describe('bin path', function () {

    it('sets the bin path to the location of cuke-monkey', function () {
      expect(Monkey.bin.match(/cuke-monkey\/bin\/cuke-monkey$/)).not.toBe(null);
    });

  });

  describe('init', function () {

    it('runs in single mode when no mode option is passed', function () {

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      monkey.start = jest.genMockFunction();
      monkey.watch = jest.genMockFunction();
      var callback = function () {};

      monkey.init(callback);

      expect(monkey.run).toBeCalledWith(callback);
      expect(monkey.run.mock.calls.length).toBe(1);

      expect(monkey.start.mock.calls.length).toBe(0);
      expect(monkey.watch.mock.calls.length).toBe(0);

    });

    it('runs in watch mode)', function () {

      var monkey = new Monkey({watch: true});

      monkey.run = jest.genMockFunction();
      monkey.start = jest.genMockFunction();
      monkey.watch = jest.genMockFunction();

      monkey.init();

      expect(monkey.watch).toBeCalledWith();
      expect(monkey.watch.mock.calls.length).toBe(1);

      expect(monkey.run.mock.calls.length).toBe(0);
      expect(monkey.start.mock.calls.length).toBe(0);
    });

    it('kicks-off the right run [default] / server / watch )', function () {

      var monkey = new Monkey({server: true});

      monkey.run = jest.genMockFunction();
      monkey.start = jest.genMockFunction();
      monkey.watch = jest.genMockFunction();

      monkey.init();

      expect(monkey.start).toBeCalledWith();
      expect(monkey.start.mock.calls.length).toBe(1);

      expect(monkey.run.mock.calls.length).toBe(0);
      expect(monkey.watch.mock.calls.length).toBe(0);
    });

  });

  describe('watch', function () {

    it('initializes chokidar', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var options = {path: 'abc'};
      var monkey = new Monkey(options);
      monkey.run = jest.genMockFunction();

      monkey.watch();

      expect(chokidar.watch.mock.calls[0][0]).toBe(options.path);

    });

    it('all listener is registered after watcher is ready', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var options = {path: 'abc'};
      var monkey = new Monkey(options);

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();
      expect(chokidar.watcher.on.mock.calls[0][0]).toBe('ready');

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];

      readyCallback();
      expect(chokidar.watcher.on.mock.calls[1][0]).toBe('all');

    });

    it('an non-unlink event triggers the interrupt and run sequence', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      var allCallback = chokidar.watcher.on.mock.calls[1][1];

      monkey.rerun = jest.genMockFunction();

      allCallback('not-unlink');

      expect(monkey.rerun.mock.calls.length).toBe(1);

    });

    it('a deleted feature does not trigger the interrupt and run sequence', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      var allCallback = chokidar.watcher.on.mock.calls[1][1];

      monkey.rerun = jest.genMockFunction();

      allCallback('unlink', '/path/some.feature');

      expect(monkey.rerun.mock.calls.length).toBe(0);

    });

    it('a deleted non-feature triggers the interrupt and run sequence', function () {

      var chokidar = require('chokidar');
      var async = require('async');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      var allCallback = chokidar.watcher.on.mock.calls[1][1];

      monkey.rerun = jest.genMockFunction();

      allCallback('unlink', '/path/some.feature.js');

      expect(monkey.rerun.mock.calls.length).toBe(1);

    });

    it('runs on startup', function () {

      var chokidar = require('chokidar');
      var Monkey = require('../lib/monkey.js');

      var monkey = new Monkey();

      monkey.run = jest.genMockFunction();
      chokidar.watcher.on = jest.genMockFunction();

      monkey.watch();

      var readyCallback = chokidar.watcher.on.mock.calls[0][1];
      readyCallback();

      expect(monkey.run.mock.calls.length).toBe(1);

    });

  });

  describe('run', function () {

    it('interrupts any existing processes, starts processes and calls callback', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });
      monkey._startProcesses = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });

      var callback = jest.genMockFn();
      monkey.run(callback);

      expect(monkey.interrupt.mock.calls.length).toBe(2);
      expect(monkey._startProcesses.mock.calls.length).toBe(1);
      expect(callback.mock.calls.length).toBe(1);

    });

    it('detects errors in interrupt and calls callback with an error', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFunction().mockImplementation(function (callback) {
        return callback('error');
      });

      var callback = jest.genMockFn();
      monkey.run(callback);

      expect(callback.mock.calls.length).toBe(1);
      expect(callback.mock.calls[0][0]).toEqual('error');

    });

    it('stops all processes on successful runs', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });
      monkey._startProcesses = jest.genMockFunction().mockImplementation(function (callback) {
        return callback();
      });

      monkey.stop = jest.genMockFunction();

      var callback = jest.genMockFn();
      monkey.run(callback);

      expect(monkey.interrupt.mock.calls.length).toBe(2);

    });

  });

  describe('interrupt', function () {

    it('calls interrupt on all processes in the reverse order that they were started', function () {

      jest.dontMock('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      var orderCounter = 0;

      function Process () {
        this.orderRun = -1;
      }

      Process.prototype.interrupt = function (callback) {
        this.orderRun = orderCounter++;
        callback();
      };

      var process1 = new Process('1');
      var process2 = new Process('2');
      monkey.processes = [process1, process2];

      var callback = jest.genMockFunction();

      monkey.interrupt(callback);

      expect(process2.orderRun).toBe(0);
      expect(process1.orderRun).toBe(1);

    });

    it('bubbles callback without modifying the arguments', function () {

      var async = require('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();
      monkey.processes = [{interrupt: jest.genMockFn()}];
      var someArgs = ['some', 'args'];

      async.series = jest.genMockFunction().mockImplementation(function (processes, callback) {
        callback.apply(this, someArgs);
      });

      var callback = jest.genMockFn();
      monkey.interrupt(callback);

      expect(callback.mock.calls.length).toBe(1);
      expect(callback.mock.calls[0]).toEqual(['some', 'args']);

    });

    it('calls the callback when no processes have been started', function () {

      var async = require('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      async.series = jest.genMockFn();

      var callback = jest.genMockFn();
      monkey.interrupt(callback);

      expect(callback.mock.calls.length).toBe(1);
      expect(async.series.mock.calls.length).toBe(0);

    });

  });

  describe('rerun', function () {

    it('calls run if interrupt is successful', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFn().mockImplementation (function (callback) {
        callback(null);
      });

      monkey.run = jest.genMockFn();

      monkey.rerun();

      expect(monkey.run.mock.calls.length).toBe(1);

    });

    it('does not rerun if an rerun is in progress', function () {

      var monkey = new Monkey();

      monkey.interrupt = jest.genMockFn();
      monkey.run = jest.genMockFn();

      monkey.rerun();
      monkey.rerun();

      expect(monkey.run.mock.calls.length).toBe(1);
    });

    it('reruns once it has finished rerunning', function () {

      var monkey = new Monkey();

      monkey.run = jest.genMockFn().mockImplementation(function (callback) {
        callback(null);
        // after the first run, replace this mockImplementation with a standard mock so we
        // can assert on that the rerun interrupts after a successful run
        monkey.run = jest.genMockFn();
      });

      monkey.rerun();
      monkey.rerun();

      expect(monkey.run.mock.calls.length).toBe(1);

    });

  });

  describe('_startProcesses', function () {

    it('creates an array of series of processes and starts them', function () {

      var async = require('async');

      var Monkey = require('../lib/monkey.js');

      async.series = jest.genMockFn();

      var monkey = new Monkey();
      var processes = [];
      monkey._createProcesses = jest.genMockFunction().mockReturnValue(processes);

      monkey._startProcesses();

      expect(monkey._createProcesses.mock.calls.length).toBe(1);
      expect(monkey.processes).toBe(processes);

    });

    it('start each process in its own context and calls callback once', function () {

      jest.dontMock('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      function Process () {
        this.state = 'constructed';
      }

      Process.prototype.start = function (callback) {
        this.state = 'started';
        callback();
      };

      var processes = [new Process(), new Process()];
      monkey._createProcesses = jest.genMockFunction().mockReturnValue(processes);

      var callback = jest.genMockFunction();

      monkey._startProcesses(callback);

      expect(typeof callback.mock.calls[0][0]).toBe('undefined');
      expect(callback.mock.calls.length).toBe(1);
      expect(processes[0].state).toBe('started');
      expect(processes[1].state).toBe('started');

    });

    it('bubbles up errors in callback if an processes callback with an error', function () {

      jest.dontMock('async');
      var Monkey = require('../lib/monkey');

      var monkey = new Monkey();

      function Process () {
        this.state = 'constructed';
      }

      Process.prototype.start = function (callback) {
        this.state = 'started';
        callback('error!');
      };

      var processes = [new Process('1'), new Process('2')];
      monkey._createProcesses = jest.genMockFunction().mockReturnValue(processes);

      var callback = jest.genMockFunction();

      monkey._startProcesses(callback);

      expect(callback.mock.calls[0][0]).toBe('error!');
      expect(callback.mock.calls.length).toBe(1);
      expect(processes[0].state).toBe('started');
      expect(processes[1].state).toBe('constructed');

    });

  });

  describe('_createProcesses', function () {

    it('adds a phantom', function () {
      var Phantom = require('../lib/phantom.js');
      var Monkey = require('../lib/monkey.js');

      var options = {browser: 'phantomjs'};
      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(Phantom.mock.calls[0][0]).toBe(options);
      expect(processes.length).toBe(2);

    });

    it('adds a selenium when no browser is passed', function () {
      var Selenium = require('../lib/selenium.js');
      var Monkey = require('../lib/monkey.js');

      var options = {browser: 'some-browser', host: ''};
      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(Selenium.mock.calls[0][0]).toBe(options);
      expect(processes.length).toBe(2);
    });

    it('does not add selenium when SauceLabs is the host', function () {
      var Selenium = require('../lib/selenium.js');
      var Monkey = require('../lib/monkey.js');

      var options = {host: 'saucelabs'};
      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(Selenium.mock.calls.length).toBe(0);
      expect(processes.length).toBe(1);
    });

    it('adds cucumber last', function () {
      jest.dontMock('../lib/cucumber.js');

      var Monkey = require('../lib/monkey.js');
      var options = {browser: 'phantomjs'};

      var monkey = new Monkey(options);

      var processes = monkey._createProcesses();

      expect(typeof processes[0].cucumberChild).toBe('undefined');
      expect(typeof processes[1].cucumberChild).not.toBe('undefined');
    });

    it('should add at least one process', function () {

      var monkey = new Monkey({browser: 'phantomjs'});

      var processes = monkey._createProcesses();

      expect(processes.length).not.toBe(0);
    });

  });

});
<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux';
import 'whatwg-fetch';
import fetchMock from 'fetch-mock';
import { reducerlessMiddleware, reducerlessEnhancer } from '../src';
import im from 'object-path-immutable';

let store;
let numRetryCalled;
beforeEach(() => {
  fetchMock.reset();
  store = createStore(
    null,
    null,
    compose(
      applyMiddleware(
        reducerlessMiddleware({
          setKey: (state, key, value) => im.set(state, key, value),
          getOpts: opts => {
            opts.headers = { 'X-Api-Token': 'token' };
            return opts;
          },
        })
      ),
      reducerlessEnhancer(),
    ),
  );
  numRetryCalled = 0;
});

afterAll(fetchMock.restore);

fetchMock.get('/api/foos', [
  { name: 'foo1' },
  { name: 'foo2' }
]);
fetchMock.get('/api/foo/1', {
  name: 'foo1', details: 'my details'
});
fetchMock.post('/api/foo', (url, opts) => {
  return opts.body;
});
fetchMock.post('/api/opts', (url, opts) => {
  return { body: { headers: opts.headers } };
});
fetchMock.get('/api/err', { status: 500 });
fetchMock.get('/api/test', { foo: 'bar' });
fetchMock.get('/api/retry', (url, opts) => {
  if (numRetryCalled < 2) {
    numRetryCalled += 1;
    return { status: 500 };
  }
  return { foo: 'bar' };
});
fetchMock.get('/api/bars', []);

test('fetch data and store in simple key', () => {
  const prom = store.dispatch({
    key: 'foos',
    url: '/api/foos',
  });
  expect(store.getState().foos.pending).toBe(true);
  return prom.then(result => {
    expect(store.getState().foos.value).toBe(result);
  });
});

test('fetch data and store in complex key', () => {
  const prom = store.dispatch({
    key: ['results', 'foos'],
    url: '/api/foos',
  });
  expect(store.getState().results.foos.pending).toBe(true);
  return prom.then(result => {
    expect(store.getState().results.foos.value).toBe(result);
  })
});

test('can specify update function that returns updated state', () => {
  store.dispatch({
    update: state => im.set(state, ['hello'], 'kitty'),
  });
  expect(store.getState().hello).toBe('kitty');
});

test('can specify a transform on the action', () => {
  return store.dispatch({
    key: 'foo',
    url: '/api/foo/1',
    transform: data => {
      data.details = 'no details';
      return data;
    }
  })
  .then(result => {
    expect(store.getState().foo.value).toEqual({ name: 'foo1', details: 'no details' });
  })
});

test('can supply http method on action', () => {
  return store.dispatch({
    key: 'addFooResp',
    url: '/api/foo',
    method: 'POST',
    body: { name: 'newFoo' },
  })
  .then(_ => {
    expect(store.getState().addFooResp.value).toEqual({ name: 'newFoo' });
  });
});

test('call onFulfilled with response and dipatch', (done) => {
  store.dispatch({
    key: 'addFooResp',
    url: '/api/foo',
    method: 'POST',
    body: { name: 'newFoo' },
    onFulfilled: (data, dispatch) => {
      //expect(data).toEqual({ name: 'newFoo' });
      //expect(dispatch).toBe(store.dispatch);
      dispatch({
        update: state => im.set(state, 'hello', 'kitty'),
      });
      expect(store.getState().hello).toBe('kitty');
      expect(store.getState().addFooResp.value).toEqual({ name: 'newFoo' });
      done();
    }
  });
});

test('customize request options with getOptions()', () => {
  return store.dispatch({
    key: 'postResp',
    url: '/api/opts',
    method: 'POST',
  })
  .then(result => {
    expect(store.getState().postResp.value.headers).toEqual({ 'X-Api-Token': 'token' });
  });
});

test('handles http errors', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/err',
  })
  .catch(err => {
    expect(err.reason.response.status).toBe(500);
    done();
  })
});

test('can override default response handling on a per action level', () => {
  return store.dispatch({
    key: 'foos',
    url: '/api/test',
    handleResponse: response => {
      return response.text();
    }
  })
  .then(result => {
    expect(store.getState().foos.value).toEqual(JSON.stringify({ foo: 'bar' }));
  })
});

test('can repeat an action on a predefined interval', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
    refreshInterval: 1,
  });
  setTimeout(() => {
    const calls = fetchMock.calls('/api/foos').length;
    expect(calls).toBeGreaterThan(5);
    done();
  }, 200);

});

test('can retry an action based on action.maxRetry', () => {
  return store.dispatch({
    key: 'foos',
    url: '/api/retry',
    maxRetry: 3,
    retryBackoff: 1
  })
  .then(result => {
    const expected = store.getState().foos.value;
    expect(expected).toEqual({ foo: 'bar' });
  });
});

test('multiple dispatches of a repeating action will not fetch the url again', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
    refreshInterval: 1,
  });
  setTimeout(() => {
    store.dispatch({
      key: 'foos',
      url: '/api/foos',
    })
    .then(result => {
      expect(result).toEqual({ refreshing: true });
      done();
    })
  }, 100);
});

test('do not fetch (GET) a url that is pending fetch', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
  });
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
  })
  .then(result => {
    expect(result).toEqual({ pending: true });
    done();
  });
});

test('can clear auto refreshing actions', (done) => {
  const url = '/api/bars';
  console.log('calls', fetchMock.calls(url).length);
  store.dispatch({
    key: 'foos',
    url: url,
    refreshInterval: 1,
  });
  setTimeout(() => {
    store.dispatch({
      clearRefresh: true,
    });
    const callsNow = fetchMock.calls(url).length;
    setTimeout(() => {
      const callsLater = fetchMock.calls(url).length;
      expect(callsNow).toBe(callsLater);
      done();
    }, 100);

  }, 100)
});<commit_msg>formatting<commit_after>import { createStore, applyMiddleware, compose } from 'redux';
import 'whatwg-fetch';
import fetchMock from 'fetch-mock';
import { reducerlessMiddleware, reducerlessEnhancer } from '../src';
import im from 'object-path-immutable';

let store;
let numRetryCalled;
beforeEach(() => {
  fetchMock.reset();
  store = createStore(
    null,
    null,
    compose(
      applyMiddleware(
        reducerlessMiddleware({
          setKey: (state, key, value) => im.set(state, key, value),
          getOpts: opts => {
            opts.headers = { 'X-Api-Token': 'token' };
            return opts;
          },
        })
      ),
      reducerlessEnhancer(),
    ),
  );
  numRetryCalled = 0;
});

afterAll(fetchMock.restore);

fetchMock.get('/api/foos', [
  { name: 'foo1' },
  { name: 'foo2' }
]);
fetchMock.get('/api/foo/1', {
  name: 'foo1', details: 'my details'
});
fetchMock.post('/api/foo', (url, opts) => {
  return opts.body;
});
fetchMock.post('/api/opts', (url, opts) => {
  return { body: { headers: opts.headers } };
});
fetchMock.get('/api/err', { status: 500 });
fetchMock.get('/api/test', { foo: 'bar' });
fetchMock.get('/api/retry', (url, opts) => {
  if (numRetryCalled < 2) {
    numRetryCalled += 1;
    return { status: 500 };
  }
  return { foo: 'bar' };
});
fetchMock.get('/api/bars', []);

test('fetch data and store in simple key', () => {
  const prom = store.dispatch({
    key: 'foos',
    url: '/api/foos',
  });
  expect(store.getState().foos.pending).toBe(true);
  return prom.then(result => {
    expect(store.getState().foos.value).toBe(result);
  });
});

test('fetch data and store in complex key', () => {
  const prom = store.dispatch({
    key: ['results', 'foos'],
    url: '/api/foos',
  });
  expect(store.getState().results.foos.pending).toBe(true);
  return prom.then(result => {
    expect(store.getState().results.foos.value).toBe(result);
  })
});

test('can specify update function that returns updated state', () => {
  store.dispatch({
    update: state => im.set(state, ['hello'], 'kitty'),
  });
  expect(store.getState().hello).toBe('kitty');
});

test('can specify a transform on the action', () => {
  return store.dispatch({
    key: 'foo',
    url: '/api/foo/1',
    transform: data => {
      data.details = 'no details';
      return data;
    }
  })
  .then(result => {
    expect(store.getState().foo.value).toEqual({ name: 'foo1', details: 'no details' });
  })
});

test('can supply http method on action', () => {
  return store.dispatch({
    key: 'addFooResp',
    url: '/api/foo',
    method: 'POST',
    body: { name: 'newFoo' },
  })
  .then(_ => {
    expect(store.getState().addFooResp.value).toEqual({ name: 'newFoo' });
  });
});

test('call onFulfilled with response and dipatch', (done) => {
  store.dispatch({
    key: 'addFooResp',
    url: '/api/foo',
    method: 'POST',
    body: { name: 'newFoo' },
    onFulfilled: (data, dispatch) => {
      //expect(data).toEqual({ name: 'newFoo' });
      //expect(dispatch).toBe(store.dispatch);
      dispatch({
        update: state => im.set(state, 'hello', 'kitty'),
      });
      expect(store.getState().hello).toBe('kitty');
      expect(store.getState().addFooResp.value).toEqual({ name: 'newFoo' });
      done();
    }
  });
});

test('customize request options with getOptions()', () => {
  return store.dispatch({
    key: 'postResp',
    url: '/api/opts',
    method: 'POST',
  })
  .then(result => {
    expect(store.getState().postResp.value.headers).toEqual({ 'X-Api-Token': 'token' });
  });
});

test('handles http errors', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/err',
  })
  .catch(err => {
    expect(err.reason.response.status).toBe(500);
    done();
  })
});

test('can override default response handling on a per action level', () => {
  return store.dispatch({
    key: 'foos',
    url: '/api/test',
    handleResponse: response => {
      return response.text();
    }
  })
  .then(result => {
    expect(store.getState().foos.value).toEqual(JSON.stringify({ foo: 'bar' }));
  })
});

test('can repeat an action on a predefined interval', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
    refreshInterval: 1,
  });
  setTimeout(() => {
    const calls = fetchMock.calls('/api/foos').length;
    expect(calls).toBeGreaterThan(5);
    done();
  }, 200);

});

test('can retry an action based on action.maxRetry', () => {
  return store.dispatch({
    key: 'foos',
    url: '/api/retry',
    maxRetry: 3,
    retryBackoff: 1
  })
  .then(result => {
    const expected = store.getState().foos.value;
    expect(expected).toEqual({ foo: 'bar' });
  });
});

test('multiple dispatches of a repeating action will not fetch the url again', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
    refreshInterval: 1,
  });
  setTimeout(() => {
    store.dispatch({
      key: 'foos',
      url: '/api/foos',
    })
    .then(result => {
      expect(result).toEqual({ refreshing: true });
      done();
    })
  }, 100);
});

test('do not fetch (GET) a url that is pending fetch', (done) => {
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
  });
  store.dispatch({
    key: 'foos',
    url: '/api/foos',
  })
  .then(result => {
    expect(result).toEqual({ pending: true });
    done();
  });
});

test('can clear auto refreshing actions', (done) => {
  const url = '/api/bars';
  console.log('calls', fetchMock.calls(url).length);
  store.dispatch({
    key: 'foos',
    url: url,
    refreshInterval: 1,
  });
  setTimeout(() => {
    store.dispatch({
      clearRefresh: true,
    });
    const callsNow = fetchMock.calls(url).length;
    setTimeout(() => {
      const callsLater = fetchMock.calls(url).length;
      expect(callsNow).toBe(callsLater);
      done();
    }, 100);
  }, 100)
});<|endoftext|>


<commit_before>import { forEachMessage, setEncoding, attachHandlers, writeMessage } from '../src/socket';
import MockSocket from '../__mocks__/socket';

const mockMessage = '{"name": "msg1", "data": "data1"}\n{"name": "msg2", "data": "data2"}';
const mockBadMessage = '{"name" "msg1", "data": "data1"}\n{"name": "msg2", "data": "data2"}';
const mockData = {
  name: 'msg1',
  data: 'hello\nworld'
};

describe('forEachMessage function', () => {
  test('should call callback for each message line', () => {
    const func = jest.fn();
    forEachMessage(mockMessage, func);
    expect(func).toHaveBeenCalledTimes(2);
  });

  test('should trigger errorCallback on error', () => {
    const func = jest.fn();
    const errorFunc = jest.fn();
    forEachMessage(mockBadMessage, func, errorFunc);

    expect(func).toHaveBeenCalledTimes(1);
    expect(errorFunc).toHaveBeenCalledTimes(1);
  });
});

describe('setEncoding function', () => {
  test('sets encoding properly', () => {
    const mockSocket = new MockSocket();
    setEncoding(mockSocket);
    expect(mockSocket.encoding).toBe('utf8');
  });
});

describe('attachHandlers function', () => {
  const mockSocket = new MockSocket();

  test('should not throw', () => {
    const attach = () => attachHandlers(mockSocket);
    expect(attach).not.toThrow();
  });

  test('set data handler should not throw', () => {
    const emitData = () => mockSocket.emit('data', mockMessage);
    expect(emitData).not.toThrow();
  });

  test('set close handler should not throw', () => {
    const emitClose = () => mockSocket.emit('close', null);
    expect(emitClose).not.toThrow();
  });
});

describe('writeMessage function', () => {
  test('properly write data to socket', () => {
    const result = writeMessage(MockSocket, mockData);
    expect(result.message).toBe(`${JSON.stringify(mockData)}\n`);
    expect(result.encoding).toBe('utf8');
  });
});
<commit_msg>Added remaining socket tests<commit_after>import { forEachMessage, setEncoding, attachHandlers, writeMessage } from '../src/socket';
import workerList from '../src/worker_list';
import MockWorker from '../__mocks__/worker';
import MockSocket from '../__mocks__/socket';

const mockMessage = '{"name": "msg1", "data": "data1"}\n{"name": "msg2", "data": "data2"}\n';
const mockBadMessage = '{"name" "msg1", "data": "data1"}\n{"name": "msg2", "data": "data2"}\n';
const mockIdentification = '{"name": "identification", "data": "mockUID"}\n';
const mockBadIdentification = '{"name": "identification", "data": "asd"}\n';
const mockData = {
  name: 'msg1',
  data: 'hello\nworld'
};

describe('forEachMessage function', () => {
  test('should call callback for each message line', () => {
    const func = jest.fn();
    forEachMessage(mockMessage, func);
    expect(func).toHaveBeenCalledTimes(2);
  });

  test('should trigger errorCallback on error', () => {
    const func = jest.fn();
    const errorFunc = jest.fn();
    forEachMessage(mockBadMessage, func, errorFunc);

    expect(func).toHaveBeenCalledTimes(1);
    expect(errorFunc).toHaveBeenCalledTimes(1);
  });

  test('should not throw if no errorCallback is given', () => {
    const func = jest.fn();
    const parseMessage = () => forEachMessage(mockBadMessage, func);

    expect(parseMessage).not.toThrow();
    expect(func).toHaveBeenCalledTimes(1);
  });
});

describe('setEncoding function', () => {
  test('sets encoding properly', () => {
    const mockSocket = new MockSocket();
    setEncoding(mockSocket);
    expect(mockSocket.encoding).toBe('utf8');
  });
});

describe('attachHandlers function', () => {
  test('should not throw', () => {
    const mockSocket = new MockSocket();
    const attach = () => attachHandlers(mockSocket);
    expect(attach).not.toThrow();
  });

  test('should destroy unknown sockets', () => {
    const mockSocket = new MockSocket();
    attachHandlers(mockSocket);
    mockSocket.emit('data', mockMessage);
    expect(mockSocket.dead).toBe(true);
  });

  test('should destroy sockets trying to identify with unknown workers', () => {
    const mockSocket = new MockSocket();
    attachHandlers(mockSocket);

    mockSocket.emit('data', mockBadIdentification);
    expect(mockSocket.dead).toBe(true);
  });

  test('should attach a socket to it\'s worker', () => {
    const mockWorker = new MockWorker('mockUID');
    workerList.add(mockWorker);

    const mockSocket = new MockSocket();
    attachHandlers(mockSocket);

    mockSocket.emit('data', mockIdentification);
    expect(mockWorker.socket).toBe(mockSocket);

    workerList.remove(mockWorker);
  });

  test('should emit messages on it\'s worker', () => {
    const func = jest.fn();

    const mockWorker = new MockWorker('mockUID');
    mockWorker.on('msg1', func);
    workerList.add(mockWorker);

    const mockSocket = new MockSocket();
    attachHandlers(mockSocket);

    mockSocket.emit('data', mockIdentification);
    expect(mockWorker.socket).toBe(mockSocket);

    mockSocket.emit('data', mockMessage);
    expect(func).toHaveBeenCalledTimes(1);

    workerList.remove(mockWorker);
  });

  test('should detach socket from it\'s worker on close', () => {
    const mockWorker = new MockWorker('mockUID');
    workerList.add(mockWorker);

    const mockSocket = new MockSocket();
    attachHandlers(mockSocket);

    mockSocket.emit('data', mockIdentification);
    expect(mockWorker.socket).toBe(mockSocket);

    mockSocket.emit('close');
    expect(mockWorker.socket).toBe(null);
    expect(mockSocket.dead).toBe(true);

    workerList.remove(mockWorker);
  });

  test('should destroy a socket on close even if it has no worker', () => {
    const mockSocket = new MockSocket();
    attachHandlers(mockSocket);

    mockSocket.emit('close');
    expect(mockSocket.dead).toBe(true);
  });
});

describe('writeMessage function', () => {
  test('properly write data to socket', () => {
    const result = writeMessage(MockSocket, mockData);
    expect(result.message).toBe(`${JSON.stringify(mockData)}\n`);
    expect(result.encoding).toBe('utf8');
  });
});
<|endoftext|>


<commit_before>$(document).ready(function(){
	$db="relax-o-notes";

	$("#upload_file_btn").live("click", function(){
		console.log("http://api.twitter.com/1/users/profile_image/"+$("#uploaded_by").val());
		var d=new Date();
		d=d.toLocaleString();
		var doc={
			"uploaded_by": $("#uploaded_by").val(),
			"gravatar_url": "http://api.twitter.com/1/users/profile_image/"+$("#uploaded_by").val(),
			"uploader_msg": $("#upload_message").val(),
			"created_at": d
		};
		$.couch.db($db).saveDoc(doc,{
			success: function(data){
				var id=data.id;
				var stat=data.ok;
				if(stat){
					$("#uploadModal").modal('hide');

				}
			},
			error: function(data){
				console.log(data);
			}
		});
		return false;
	});

	$.couch.db($db).view("app/notes/",{
		success: function(data){
			$("#all_notes").html('');
			var val;
			for(var i=0;i<data.total_rows;i++){
				val=data.rows[i].value;
				$("#all_notes").append("
"+val.user+"
"+val.uploader_msg+"
"+val.created_at+"

");
			}
			$("#all_notes").hide().fadeIn(500);
		},
		error: function(data){
			console.log(data);
		}
	});

	$.couch.db($db).changes().onChange(function(data){
		var id=data.results[0].id;
		if(id=="_design/app"){

		}
		else{
		$.couch.db($db).openDoc(id,{
			success: function(obj){
				$("#all_notes").first().append("
"+obj.uploaded_by+"
"+obj.uploader_msg+"
"+obj.created_at+"

").hide().fadeIn(500);
			},
			error: function(data2){
				if(data2==404){
					$("#"+id).fadeOut(500);
				}
			}
		});
	 }
	});

});
<commit_msg>adding tags support<commit_after>$(document).ready(function(){
	$db="relax-o-notes";

	$("#upload_file_btn").live("click", function(){
		console.log("http://api.twitter.com/1/users/profile_image/"+$("#uploaded_by").val());
		var d=new Date();
		d=d.toLocaleString();
		var tags=$("#upload_message").val().split(" ");
		var act_tags="", k=0;
		for(var j=0;j<tags.length;j++){
			if(tags[j].indexOf('#') == 0){
				act_tags=act_tags+" "+tags[j];
				act_tags=act_tags.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
				k++;
			}
		}
		console.log(act_tags);
		act_tags=act_tags.substring(1,act_tags.length);
		var doc={
			"uploaded_by": $("#uploaded_by").val(),
			"gravatar_url": "http://api.twitter.com/1/users/profile_image/"+$("#uploaded_by").val(),
			"uploader_msg": $("#upload_message").val(),
			"created_at": d,
			"tags": act_tags.split(" ")
		};
		$.couch.db($db).saveDoc(doc,{
			success: function(data){
				var id=data.id;
				var stat=data.ok;
				if(stat){
					$("#uploadModal").modal('hide');

				}
			},
			error: function(data){
				console.log(data);
			}
		});
		return false;
	});

	$.couch.db($db).view("app/notes/",{
		success: function(data){
			console.log(data);
			$("#all_notes").html('');
			var val;
			for(var i=0;i<data.total_rows;i++){
				val=data.rows[i].value;
				$("#all_notes").append("
"+val.user+"
"+val.uploader_msg+"
"+val.created_at+"

");
			}
			$("#all_notes").hide().fadeIn(500);
		},
		error: function(data){
			console.log(data);
		}
	});

	$.couch.db($db).changes().onChange(function(data){
		var id=data.results[0].id;
		if(id=="_design/app"){

		}
		else{
		$.couch.db($db).openDoc(id,{
			success: function(obj){
				$("#all_notes").first().append("
"+obj.uploaded_by+"
"+obj.uploader_msg+"
"+obj.created_at+"

").hide().fadeIn(500);
			},
			error: function(data2){
				if(data2==404){
					$("#"+id).fadeOut(500);
				}
			}
		});
	 }
	});

});
<|endoftext|>


<commit_before>$(document).ready(function(){
	$db="relax-o-notes";
});
<commit_msg>function for uplaod file button click to create a doc with email field<commit_after>$(document).ready(function(){
	$db="relax-o-notes";

	$("#upload_file_btn").live("click", function(){
		var doc={
			"uploaded_by": $("#uploaded_by").val(),
		};
		$.couch.db($db).saveDoc(doc,{
			success: function(data){
				var id=data.id;
				var stat=data.ok;
				if(stat){
					$("#uploadModal").modal('hide');

				}
				console.log(data);
			},
			error: function(data){
				console.log(data);
			}
		});
		console.log($db);
		return false;
	});

});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Vola IP Tools
// @version      24
// @description  Hides ip addresses for mods.
// @namespace    https://volafile.org
// @icon         https://volafile.org/favicon.ico
// @author       topkuk productions
// @match        https://volafile.org/r/*
// @require      https://cdn.rawgit.com/RealDolos/volascripts/1dd689f72763c0e59f567fdf93865837e35964d6/dry.js
// @run-at       document-start
// ==/UserScript==

dry.once("dom", () => {
    "use strict";
    console.log("running", GM_info.script.name, GM_info.script.version, dry.version);

    const style = document.createElement("style");
    style.textContent = `
body[noipspls] a.username > span:not([class]),
body[noipspls] a.username > span[class=""],
body[noipspls] .tag_key_ip {
  display: none;
}
.username.ban {
  display: inline-block;
}
@-moz-document url-prefix() {
.username.ban {
  display: inline;
}
}
.username.ban {
  vertical-align: top;
  color: white !important;
  font-size: 50%;
  padding: 0;
  opacity: 0.4;
}
.username.ban:hover {
  opacity: 1;
}
.username.ban icon-hammer {
  padding: 0;
}
#room_tools {
  display: inline-block;
  position: absolute;
  right: 0;
  bottom: 0;
}
`;
    document.body.appendChild(style);
    let state = localStorage.getItem("noipspls") !== "false";
    if (state !== false) {
        state = true;
    }
    const update = () => {
        if (state) {
            document.body.setAttribute("noipspls", "true");
        }
        else {
            document.body.removeAttribute("noipspls");
        }
        localStorage.setItem("noipspls", state.toString());
        if (dry.exts) {
            dry.exts.chat.scrollState.bottom();
        }
    };
    const toggle = () => {
        state = !state;
        update();
    };
    update();

    let btn = document.createElement("a");
    btn.textContent = "IP";
    btn.style.padding = "0 1ex";
    let uc = document.querySelector("#user_count_icon");
    uc.parentElement.insertBefore(btn, uc.nextSibling);
    btn.addEventListener("click", toggle);

    dry.replaceEarly("chat", "showMessage", function(orig, nick, message, options, data, ...args) {
        try {
            if (nick === "Log" && options.staff) {
                if (typeof(message) == "string") {
                    message = {type: "text", value: message};
                }
                if (!message.forEach) {
                    message = [message];
                }
                let newmsg = new dry.unsafeWindow.Array();
                message.forEach(m => {
                    try {
                        if (m && m.type === "text") {
                            const pieces = m.value.match(/^(.+?)( \(([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\))(.+)$/);
                            if (!pieces) {
                                newmsg.push(m);
                                return;
                            }
                            newmsg.push({type: "text", value: pieces[1] + pieces[4]});
                            if (!data) {
                                data = new dry.unsafeWindow.Object();
                                data.ip = pieces[3];
                            }
                            return;
                        }
                    }
                    catch (ex) {
                        console.error(ex);
                    }
                    newmsg.push(m);
                });
                message = newmsg;
            }
        }
        catch (ex) {
            console.error(ex);
        }
        const msg = orig(...[nick, message, options, data].concat(args));
        try {
            if (msg && msg.ip_elem) {
                msg.ban_elem = document.createElement("span");
                const hammer = document.createElement("i");
                hammer.setAttribute("class", "chat_message_icon icon-hammer");
                msg.ban_elem.appendChild(hammer);
                msg.ban_elem.setAttribute("class", "username clickable ban");
                msg.ban_elem.addEventListener("click", msg.showBanWindow.bind(msg));
                msg.nick_elem.appendChild(msg.ban_elem);
            }
        }
        catch (ex) {
            console.error(ex);
        }
        return msg;
    });

    new class extends dry.Commands {
        ip(e) {
            toggle();
            return true;
        }
    }();

    {
        let settings = document.querySelector("#room_settings");
        let disable = document.createElement("a");
        disable.id = "disable_room";
        disable.className = "button light";
        disable.textContent = "Nuke";

        settings.parentElement.appendChild(disable);
        disable.addEventListener("click", function() {
            dry.exts.ui.showQuestion({
                title: "Disable this room",
                text: "Are you sure you want to disable this room?",
                positive: "Disable",
                negative: "Abort"
            }, (res) => {
                if (!res) {
                    return;
                }
                dry.exts.connection.call("editInfo", {
                    "name": "closed",
                    "motd": "",
                    "disabled": true
                });
            });
        });
    }
});
<commit_msg>more ips<commit_after>// ==UserScript==
// @name         Vola IP Tools
// @version      25
// @description  Hides ip addresses for mods.
// @namespace    https://volafile.org
// @icon         https://volafile.org/favicon.ico
// @author       topkuk productions
// @match        https://volafile.org/r/*
// @require      https://cdn.rawgit.com/RealDolos/volascripts/1dd689f72763c0e59f567fdf93865837e35964d6/dry.js
// @run-at       document-start
// ==/UserScript==

dry.once("dom", () => {
    "use strict";
    console.log("running", GM_info.script.name, GM_info.script.version, dry.version);

    const style = document.createElement("style");
    style.textContent = `
body[noipspls] a.username > span:not([class]),
body[noipspls] a.username > span[class=""],
body[noipspls] .tag_key_ip {
  display: none;
}
.username.ban {
  display: inline-block;
}
@-moz-document url-prefix() {
.username.ban {
  display: inline;
}
}
.username.ban {
  vertical-align: top;
  color: white !important;
  font-size: 50%;
  padding: 0;
  opacity: 0.4;
}
.username.ban:hover {
  opacity: 1;
}
.username.ban icon-hammer {
  padding: 0;
}
#room_tools {
  display: inline-block;
  position: absolute;
  right: 0;
  bottom: 0;
}
`;
    document.body.appendChild(style);
    let state = localStorage.getItem("noipspls") !== "false";
    if (state !== false) {
        state = true;
    }
    const update = () => {
        if (state) {
            document.body.setAttribute("noipspls", "true");
        }
        else {
            document.body.removeAttribute("noipspls");
        }
        localStorage.setItem("noipspls", state.toString());
        if (dry.exts) {
            dry.exts.chat.scrollState.bottom();
        }
    };
    const toggle = () => {
        state = !state;
        update();
    };
    update();

    let btn = document.createElement("a");
    btn.textContent = "IP";
    btn.style.padding = "0 1ex";
    let uc = document.querySelector("#user_count_icon");
    uc.parentElement.insertBefore(btn, uc.nextSibling);
    btn.addEventListener("click", toggle);

    dry.replaceEarly("chat", "showMessage", function(orig, nick, message, options, data, ...args) {
        try {
            if (nick === "Log" && options.staff) {
                if (typeof(message) == "string") {
                    message = {type: "text", value: message};
                }
                if (!message.forEach) {
                    message = [message];
                }
                let newmsg = new dry.unsafeWindow.Array();
                message.forEach(m => {
                    try {
                        if (m && m.type === "text") {
                            let pieces = m.value.match(/^(.+?)( to ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(.+)$/);
                            if (!pieces) {
                                pieces = m.value.match(/^(.+?)( \(([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\))(.+)$/);
                            }
                            if (!pieces) {
                                newmsg.push(m);
                                return;
                            }
                            newmsg.push({type: "text", value: pieces[1] + pieces[4]});
                            if (!data) {
                                data = new dry.unsafeWindow.Object();
                                data.ip = pieces[3];
                            }
                            return;
                        }
                    }
                    catch (ex) {
                        console.error(ex);
                    }
                    newmsg.push(m);
                });
                message = newmsg;
            }
        }
        catch (ex) {
            console.error(ex);
        }
        const msg = orig(...[nick, message, options, data].concat(args));
        try {
            if (msg && msg.ip_elem) {
                msg.ban_elem = document.createElement("span");
                const hammer = document.createElement("i");
                hammer.setAttribute("class", "chat_message_icon icon-hammer");
                msg.ban_elem.appendChild(hammer);
                msg.ban_elem.setAttribute("class", "username clickable ban");
                msg.ban_elem.addEventListener("click", msg.showBanWindow.bind(msg));
                msg.nick_elem.appendChild(msg.ban_elem);
            }
        }
        catch (ex) {
            console.error(ex);
        }
        return msg;
    });

    new class extends dry.Commands {
        ip(e) {
            toggle();
            return true;
        }
    }();

    {
        let settings = document.querySelector("#room_settings");
        let disable = document.createElement("a");
        disable.id = "disable_room";
        disable.className = "button light";
        disable.textContent = "Nuke";

        settings.parentElement.appendChild(disable);
        disable.addEventListener("click", function() {
            dry.exts.ui.showQuestion({
                title: "Disable this room",
                text: "Are you sure you want to disable this room?",
                positive: "Disable",
                negative: "Abort"
            }, (res) => {
                if (!res) {
                    return;
                }
                dry.exts.connection.call("editInfo", {
                    "name": "closed",
                    "motd": "",
                    "disabled": true
                });
            });
        });
    }
});
<|endoftext|>