<commit_before>/*mish mash between different webpack examples
react hot boilerplate
https://github.com/shanewilson/react-webpack-example/blob/master/webpack.config.js
*/
var fs      = require('fs');
var path    = require('path');
var webpack = require('webpack');
var CompressionPlugin = require("compression-webpack-plugin");

var host    = "localhost";
var port    = 3000;
var srcPath = "src"
var xtraModulesWLoaders = ["js-csp/src","glView-helpers"]//add any module names that you want loaders to apply to

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

var getSymlinkedModules = function(){

  var rootPath = path.join(__dirname, "node_modules");
  var contents = fs.readdirSync(rootPath);
  var results = contents
  .map(function(entry){
    var fPath  = path.join(rootPath,entry);
    return fPath;
  })
  .filter(function(fPath){
    function check( entry ){
      var stats=fs.lstatSync(fPath);
      return stats.isSymbolicLink();
    }
    return check(fPath);
  })
  .map(function(fPath){
      return fs.realpathSync( fPath );
  });
  return results;
}

//add any extra folders we want to apply loaders to
var extraModulePaths = xtraModulesWLoaders.map(function(entry){ return path.join(__dirname, "node_modules",entry); });
var pathsToInclude = getSymlinkedModules().concat( path.join(__dirname, srcPath) ).concat( extraModulePaths );

//FIXME !! temporary hack: add any paths where loaders should be apllied
pathsToInclude.push( path.join(__dirname, "node_modules", "glView-helpers") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-kernel2") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-asset-manager") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-xhr-store") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-desktop-store") )

//ugh, also needed because of workers (ie worker loader)
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-stl-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ctm-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ply-parser")   )

//console.log("will user loaders on",pathsToInclude)

var config= {
  host:host,
  port:port,
  devtool: 'eval',
  entry: [
    './'+srcPath+'/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/' //'/'+'dist'+'/'
  },
  plugins: [
    //new webpack.NoErrorsPlugin(),
    //new webpack.optimize.DedupePlugin()
  ],
  module: {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },
      { test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      { test: /\.js?$/, loaders: ['react-hot', 'babel?optional[]=runtime&optional=es6.blockScoping'],include : pathsToInclude},
      { test: /\.css$/, loader: "style-loader!css-loader" }
    ],
    noParse: /\.min\.js/
  },
  resolve: {
    extensions: ['', '.js', '.jsx','json'],
    root: [
      path.join(__dirname, "node_modules"),
    ],
    /*alias: {
        "q$":path.join(__dirname, "node_modules","usco-kernel2/src/kernel.js"),//needed only FOR DEV
    }*/
    alias: {
      "three$":path.join(__dirname, "node_modules","three/three.min.js")
    }
  },
  resolveLoader:{
    root : path.join(__dirname, "node_modules")
  }
};

//console.log("production",production,"dev",dev)

if (production) {
  config.bail = true
  config.debug = false
  config.profile = false
  config.output.pathInfo = false
  config.output.publicPath = './dist/'//withouth this, issues with webworker paths

  //config.devtool = "#source-map";
  //config.output.filename = "[name].min.js"//"[name].[hash].min.js"
  //config.output.chunkFilename = '[id].js'
  config.plugins = config.plugins.concat([
    new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production') } }),
    new webpack.optimize.DedupePlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({minimize: true})
    /*
    new webpack.optimize.UglifyJsPlugin({
      mangle: {
        except: ['require', 'export', '$super', 'import']
      },
      compress: {
        warnings: false,
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true
      }
    })*/
    /*,
    new CompressionPlugin({
      asset: "{file}.gz",
      algorithm: "gzip",
      regExp: /\.js$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    })*/
  ]);
}
else{
  config.entry = config.entry.concat([
    'webpack-dev-server/client?',//http://'+host+":"+port,
    'webpack/hot/only-dev-server',
  ])
  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
  ])
}

module.exports = config;
<commit_msg>chore(build): modified webpack config, so it does not deal with (external)  "web workerified" modules anymore<commit_after>/*mish mash between different webpack examples
react hot boilerplate
https://github.com/shanewilson/react-webpack-example/blob/master/webpack.config.js
*/
var fs      = require('fs');
var path    = require('path');
var webpack = require('webpack');
var CompressionPlugin = require("compression-webpack-plugin");

var host    = "localhost";
var port    = 3000;
var srcPath = "src"
var xtraModulesWLoaders = ["js-csp/src","glView-helpers"]//add any module names that you want loaders to apply to

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

var getSymlinkedModules = function(){

  var rootPath = path.join(__dirname, "node_modules");
  var contents = fs.readdirSync(rootPath);
  var results = contents
  .map(function(entry){
    var fPath  = path.join(rootPath,entry);
    return fPath;
  })
  .filter(function(fPath){
    function check( entry ){
      var stats=fs.lstatSync(fPath);
      return stats.isSymbolicLink();
    }
    return check(fPath);
  })
  .map(function(fPath){
      return fs.realpathSync( fPath );
  });
  return results;
}

//add any extra folders we want to apply loaders to
var extraModulePaths = xtraModulesWLoaders.map(function(entry){ return path.join(__dirname, "node_modules",entry); });
var pathsToInclude = getSymlinkedModules().concat( path.join(__dirname, srcPath) ).concat( extraModulePaths );

//FIXME !! temporary hack: add any paths where loaders should be apllied
pathsToInclude.push( path.join(__dirname, "node_modules", "glView-helpers") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-kernel2") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-asset-manager") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-xhr-store") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-desktop-store") )

//ugh, also needed because of workers (ie worker loader)
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-stl-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ctm-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ply-parser")   )

//console.log("will user loaders on",pathsToInclude)

var config= {
  host:host,
  port:port,
  devtool: 'eval',
  entry: [
    './'+srcPath+'/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/' //'/'+'dist'+'/'
  },
  plugins: [
    //new webpack.NoErrorsPlugin(),
    //new webpack.optimize.DedupePlugin()
  ],
  module: {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },
      //{ test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      { test: /\.js?$/, loaders: ['react-hot', 'babel?optional[]=runtime&optional=es6.blockScoping'],include : pathsToInclude},
      { test: /\.css$/, loader: "style-loader!css-loader" }
    ],
    noParse: /\.min\.js/
  },
  resolve: {
    extensions: ['', '.js', '.jsx','json'],
    root: [
      path.join(__dirname, "node_modules"),
    ],
    /*alias: {
        "q$":path.join(__dirname, "node_modules","usco-kernel2/src/kernel.js"),//needed only FOR DEV
    }*/
    alias: {
      "three$":path.join(__dirname, "node_modules","three/three.min.js")
    }
  },
  resolveLoader:{
    root : path.join(__dirname, "node_modules")
  }
};

//console.log("production",production,"dev",dev)

if (production) {
  config.bail = true
  config.debug = false
  config.profile = false
  config.output.pathInfo = false
  config.output.publicPath = './dist/'//withouth this, issues with webworker paths

  //config.devtool = "#source-map";
  //config.output.filename = "[name].min.js"//"[name].[hash].min.js"
  //config.output.chunkFilename = '[id].js'
  config.plugins = config.plugins.concat([
    new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production') } })
    , new webpack.optimize.DedupePlugin()
    , new webpack.NoErrorsPlugin()
    , new webpack.optimize.UglifyJsPlugin({minimize: true})
    /*
    new webpack.optimize.UglifyJsPlugin({
      mangle: {
        except: ['require', 'export', '$super', 'import']
      },
      compress: {
        warnings: false,
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true
      }
    })
    , new CompressionPlugin({
      asset: "{file}.gz",
      algorithm: "gzip",
      regExp: /\.js$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    })*/
  ])
}
else{
  config.entry = config.entry.concat([
    'webpack-dev-server/client?',//http://'+host+":"+port,
    'webpack/hot/only-dev-server',
  ])
  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
  ])
}

module.exports = config;
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var globals = require('./globals');
var home = require('./home');

var Error = module.exports.Error = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

{context.title}

{context.description}

        );
    }
});

globals.content_views.register(Error, 'error');

var HTTPNotFound = module.exports.HTTPNotFound = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

Not found

The page could not be found. Please check the URL or enter a search term like "skin", "ChIP-seq", or "CTCF" in the toolbar above.

        );
    }
});

globals.content_views.register(HTTPNotFound, 'HTTPNotFound');

var HTTPForbidden = module.exports.HTTPForbidden = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

Not available

Please sign in to view this page.

Or Request an account.

        );
    }
});

globals.content_views.register(HTTPForbidden, 'HTTPForbidden');

var LoginDenied = module.exports.LoginDenied = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

Login failure

Access is restricted to ENCODE consortium members.

Request an account

        );
    }
});

globals.content_views.register(LoginDenied, 'LoginDenied');

var RenderingError = module.exports.RenderingError = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

{context.title}

{context.description}

{context.detail}

        );
    }
});

globals.content_views.register(RenderingError, 'RenderingError');
<commit_msg>Customize forbidden error message for logged in users.<commit_after>'use strict';
var React = require('react');
var globals = require('./globals');
var home = require('./home');

var Error = module.exports.Error = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

{context.title}

{context.description}

        );
    }
});

globals.content_views.register(Error, 'error');

var HTTPNotFound = module.exports.HTTPNotFound = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

Not found

The page could not be found. Please check the URL or enter a search term like "skin", "ChIP-seq", or "CTCF" in the toolbar above.

        );
    }
});

globals.content_views.register(HTTPNotFound, 'HTTPNotFound');

var HTTPForbidden = module.exports.HTTPForbidden = React.createClass({
    contextTypes: {
        session: React.PropTypes.object
    },

    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        var logged_in = this.context.session && this.context.session['auth.userid'];
        return (

Not available

                        {logged_in ?
Your account is not allowed to view this page.
 :
Please sign in to view this page.
}
                        {logged_in ? null :
Or Request an account.
}

        );
    }
});

globals.content_views.register(HTTPForbidden, 'HTTPForbidden');

var LoginDenied = module.exports.LoginDenied = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

Login failure

Access is restricted to ENCODE consortium members.

Request an account

        );
    }
});

globals.content_views.register(LoginDenied, 'LoginDenied');

var RenderingError = module.exports.RenderingError = React.createClass({
    render: function() {
        var context = this.props.context;
        var itemClass = globals.itemClass(context, 'panel-gray');
        return (

{context.title}

{context.description}

{context.detail}

        );
    }
});

globals.content_views.register(RenderingError, 'RenderingError');
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initLists();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsReady();
		this.initHoldsPending();

	} // initHolds()

, initHoldsReady: function() {

		var $cancel = $('.spl-field-cancel-hold-ready');

		$cancel.on('click', function(e) {
			var holdkey = $(this).data('holdkey');
			if ( holdkey ) {
				$cancel.button('loading');
				_self.cancelHold(holdkey);
			}
		});
}

, cancelHold: function(holdKey) {
		//console.log( holdKey );
		var $form = $('#spl-form-holds-ready');

		$.ajax({
	    url: this.config.endpoint.hzws+'cancel'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	holdKey: holdKey
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			//console.log(obj);
			//$submit.button('reset');
			//$form.data('process', 'http').submit();
			$form.submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

}

, initHoldsPending: function() {

		this.initHoldsPendingSuspend();

		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold requests(s).');
				}

			}

		});

	} // initHoldsPending()

, initHoldsPendingSuspend: function() {
		var $suspend = $('.spl-field-holds-pending-suspend');
		var $date = $('.spl-field-holds-pending-date');
		$date.on('change', function(e) {
			if ( $(this).val().length > 0 ) {
				$suspend.attr('disabled', false);
			} else {
				$suspend.attr('disabled', true);
			}
		});
		// disallow dates in the past
		$date.datepicker({startDate: new Date() });

} // initHoldsPendingSuspend()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $location = $('.spl-field-holds-pending-location');
		var $date = $('.spl-field-holds-pending-date');

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {sessionToken: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;

		switch ( action ) {
			case 'cancel':
				endpoint = 'cancel';
				break;
			case 'pickup':
				endpoint = 'pickup';
				data.params.newLocation = $location.val();
				break;
			case 'suspend':
				endpoint = 'suspend';
				data.params.suspendEndDate = $date.val();
				break;
			case 'resume':
				endpoint = 'resume';
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				//console.log(obj);
				//$submit.button('reset');
				$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initLists: function() {

		this.initListToggle();
		this.initListCreate();
		this.initListRemove();
		this.initListMove();

	} // initLists()

, initListToggle: function() {

		$('.spl-list-panel').on('show.bs.collapse', function() {

			console.log( '.spl-field-list-select-all, #'+$(this).attr('id') );

			/*
			_self.toggleCheckboxGroup('.spl-field-list-select-all, #'+$(this).attr('id')
															,'.spl-field-list-select-item, #'+$(this).attr('id')
															);
			*/
		});

} // initListToggle

, initListMove: function() {
		var $move = $('.spl-field-list-move-control');

		$move.on('click', function(e) {
			e.preventDefault();
			//$move.button('loading');

			var from =  $(this).data('list');
			if ( from ) {

				var titlekeys = new Array;
				$('.spl-field-list-select-item:checked', '#spl-form-list-control-'+from).each(function() {
					titlekeys.push( $(this).data('titlekey') );
				});

				if ( titlekeys.length > 0 ) {
					//_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					//$(this).data('action', '');
					var $to = $('#spl-field-list-move-to-'+from);
					var to = $to.val();
					_self.moveListItems(from, to, titlekeys);
				} else {
					alert('Please select list item(s).');
				}
			}

		});
} // initListMove()

, moveListItems: function(from, to, titleKeys) {

		$form = $('#spl-form-list-control-'+from);
		//$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'move'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	listKeyFrom: from
    									, listKeyTo: to
    									, titleKeys: titleKeys
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			console.log(obj);
			//$submit.button('reset');
			//$form.data('process', 'http').submit();
			//$form.submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} // moveList()

, initListRemove: function() {

		var $remove = $('.spl-field-list-remove-control');

		$remove.on('click', function(e) {
			e.preventDefault();
			$remove.button('loading');

			var list =  $(this).data('list');
			if ( list ) {
				_self.removeList(list);
			}

		});

	} // initListRemove()

, removeList: function(list) {
		//console.log( list );
		$form = $('#spl-form-list-control-'+list);
		//$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'remove'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	listKey: list
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			console.log(obj);
			//$submit.button('reset');
			//$form.data('process', 'http').submit();
			$form.submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} // removeList()

, initListCreate: function() {
		var $form = $('#spl-form-list-create');

		var $label = $('#spl-field-list-create-label');

		$form.on('submit', function(e) {

			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();
				var label = $label.val();
				if ( label.length > 0 ) {
					_self.createList(label);
				} else {
					alert('Please add a List Name');
				}
			}

		});

	} //initListCreate

, createList: function(label) {
		var $form = $('#spl-form-list-create');
		var $submit = $('.spl-submit-list-create');
		var $hidden = $('#spl-field-list-create');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'list'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	description: label
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			//console.log(obj);
			//$submit.button('reset');
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} //createList()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>list toggle<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initLists();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsReady();
		this.initHoldsPending();

	} // initHolds()

, initHoldsReady: function() {

		var $cancel = $('.spl-field-cancel-hold-ready');

		$cancel.on('click', function(e) {
			var holdkey = $(this).data('holdkey');
			if ( holdkey ) {
				$cancel.button('loading');
				_self.cancelHold(holdkey);
			}
		});
}

, cancelHold: function(holdKey) {
		//console.log( holdKey );
		var $form = $('#spl-form-holds-ready');

		$.ajax({
	    url: this.config.endpoint.hzws+'cancel'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	holdKey: holdKey
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			//console.log(obj);
			//$submit.button('reset');
			//$form.data('process', 'http').submit();
			$form.submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

}

, initHoldsPending: function() {

		this.initHoldsPendingSuspend();

		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold requests(s).');
				}

			}

		});

	} // initHoldsPending()

, initHoldsPendingSuspend: function() {
		var $suspend = $('.spl-field-holds-pending-suspend');
		var $date = $('.spl-field-holds-pending-date');
		$date.on('change', function(e) {
			if ( $(this).val().length > 0 ) {
				$suspend.attr('disabled', false);
			} else {
				$suspend.attr('disabled', true);
			}
		});
		// disallow dates in the past
		$date.datepicker({startDate: new Date() });

} // initHoldsPendingSuspend()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $location = $('.spl-field-holds-pending-location');
		var $date = $('.spl-field-holds-pending-date');

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {sessionToken: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;

		switch ( action ) {
			case 'cancel':
				endpoint = 'cancel';
				break;
			case 'pickup':
				endpoint = 'pickup';
				data.params.newLocation = $location.val();
				break;
			case 'suspend':
				endpoint = 'suspend';
				data.params.suspendEndDate = $date.val();
				break;
			case 'resume':
				endpoint = 'resume';
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				//console.log(obj);
				//$submit.button('reset');
				$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initLists: function() {

		this.initListToggle();
		this.initListCreate();
		this.initListRemove();
		this.initListMove();

	} // initLists()

, initListToggle: function() {

		$('.spl-list-panel').on('show.bs.collapse', function() {

			console.log( '.spl-field-list-select-all, #'+$(this).attr('id') );

			_self.toggleCheckboxGroup('.spl-field-list-select-all'
															,'.spl-field-list-select-item'
															,'#'+$(this).attr('id')
															);

		});

} // initListToggle

, initListMove: function() {
		var $move = $('.spl-field-list-move-control');

		$move.on('click', function(e) {
			e.preventDefault();
			//$move.button('loading');

			var from =  $(this).data('list');
			if ( from ) {

				var titlekeys = new Array;
				$('.spl-field-list-select-item:checked', '#spl-form-list-control-'+from).each(function() {
					titlekeys.push( $(this).data('titlekey') );
				});

				if ( titlekeys.length > 0 ) {
					//_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					//$(this).data('action', '');
					var $to = $('#spl-field-list-move-to-'+from);
					var to = $to.val();
					_self.moveListItems(from, to, titlekeys);
				} else {
					alert('Please select list item(s).');
				}
			}

		});
} // initListMove()

, moveListItems: function(from, to, titleKeys) {

		$form = $('#spl-form-list-control-'+from);
		//$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'move'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	listKeyFrom: from
    									, listKeyTo: to
    									, titleKeys: titleKeys
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			console.log(obj);
			//$submit.button('reset');
			//$form.data('process', 'http').submit();
			//$form.submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} // moveList()

, initListRemove: function() {

		var $remove = $('.spl-field-list-remove-control');

		$remove.on('click', function(e) {
			e.preventDefault();
			$remove.button('loading');

			var list =  $(this).data('list');
			if ( list ) {
				_self.removeList(list);
			}

		});

	} // initListRemove()

, removeList: function(list) {
		//console.log( list );
		$form = $('#spl-form-list-control-'+list);
		//$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'remove'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	listKey: list
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			console.log(obj);
			//$submit.button('reset');
			//$form.data('process', 'http').submit();
			$form.submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} // removeList()

, initListCreate: function() {
		var $form = $('#spl-form-list-create');

		var $label = $('#spl-field-list-create-label');

		$form.on('submit', function(e) {

			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();
				var label = $label.val();
				if ( label.length > 0 ) {
					_self.createList(label);
				} else {
					alert('Please add a List Name');
				}
			}

		});

	} //initListCreate

, createList: function(label) {
		var $form = $('#spl-form-list-create');
		var $submit = $('.spl-submit-list-create');
		var $hidden = $('#spl-field-list-create');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'list'
    , data: { params: { sessionToken: this.user.sessionToken
    									,	description: label
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			//$hidden.val(JSON.stringify(obj));
			//console.log(obj);
			//$submit.button('reset');
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

} //createList()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>
const ActorClass = {};
const RG = require('./rg');
RG.Component = require('./component');
RG.Spell = require('./spell');

/* Factory function for actor classes. */
ActorClass.create = function(name, entity) {
    if (ActorClass.hasOwnProperty(name)) {
        const actorClass = new ActorClass[name](entity);
        return actorClass;
    }
    else {
        RG.diag('Called with entity:');
        RG.diag(entity);
        RG.err('ActorClass', 'create',
            `No class ${name} in ActorClass`);
    }
    return null;
};

/* Used by different in-game classes for actors. Provides basic getters and
 * progress functions to increase stats etc on level up. */
class ActorClassBase {

    constructor(actor, name) {
        this._actor = actor;
        actor.setActorClass(this);
        this._className = name;
    }

    getClassName() {
        return this._className;
    }

    /* Called when a level is advanced by the actor. Checks for messages, and if
     * the next ability is triggered. */
    advanceLevel() {
        const newLevel = this._actor.get('Experience').getExpLevel();
        if (this._messages.hasOwnProperty(newLevel)) {
            const cell = this._actor.getCell();
            RG.gameMsg({cell, msg: this._messages[newLevel]});
        }
        if (this._advances.hasOwnProperty(newLevel)) {
            this._advances[newLevel]();
        }
        this.incrStats(newLevel);
    }

    incrStats(newLevel) {
        const actor = this._actor;

        const hComp = actor.get('Health');
        const incr = Math.ceil(actor.getStrength() / 2);
        hComp.setMaxHP(hComp.getMaxHP() + incr);
        hComp.setHP(hComp.getHP() + incr);

        if (actor.has('SpellPower')) {
            const ppIncr = Math.ceil(actor.getMagic() / 2);
            const ppComp = actor.get('SpellPower');
            ppComp.setMaxPP(ppComp.getMaxPP() + ppIncr);
            ppComp.addPP(ppIncr);
        }

        RG.levelUpCombatStats(actor, newLevel);
    }
}

//-------------------------------------------------------------------------
/* Adventurer actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Adventurer extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Adventurer');
        this._messages = {};
        this._advances = {
            1: () => {
                const book = new RG.Spell.SpellBook(this._actor);
                this._actor.setBook(book);
            },
            4: () => {
                this._actor.add(new RG.Component.NourishedOne());
            }
        };
    }

    /* Called when a level is advanced by the actor. Checks for messages, and if
     * the next ability is triggered. */
    advanceLevel() {
        super.advanceLevel();
        const newLevel = this._actor.get('Experience').getExpLevel();
        if (newLevel % 4 === 0) {
            // Get other random actor class
            // Use it to add new abilities to the actor
        }
    }

    /* Called at the creation of the actor. Gives certain set of starting items.
     */
    getStartingItems() {
        return [
            {name: 'Ration', count: 2}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Short sword', count: 1},
            {name: 'Leather armour', count: 1}
        ];
    }

    setStartingStats() {
        // const stats = this._actor.get('Stats');
    }
}

ActorClass.Adventurer = Adventurer;

//-------------------------------------------------------------------------
/* Blademaster actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Blademaster extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Blademaster');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} knows now how to defend more skillfully`,
            8: `${_name} knows now how to hit enemies more accurately`,
            12: `${_name} knows now how to handle equipment better`,
            16: `${_name} can now strike in two directions`,
            20: `${_name} can now keep the weapons sharp`,
            24: `${_name} can now wield two blades at once`,
            28: `${_name} can now strike back immediately when attacked`,
            32: `${_name} has become a True Blademaster`
        };

        this._advances = {
            1: () => {

            },
            4: () => {
                this._actor.add(new RG.Component.Defender());
            },
            8: () => {
                this._actor.add(new RG.Component.Attacker());
            },
            12: () => {
                this._actor.add(new RG.Component.MasterEquipper());
            },
            16: () => {
                this._actor.add(new RG.Component.BiDirStrike());
            },
            20: () => {
                this._actor.add(new RG.Component.Sharpener());
            },
            24: () => {
                this._actor.add(new RG.Component.Ambidexterity());
            },
            28: () => {
                this._actor.add(new RG.Component.CounterAttack());
            },
            32: () => {
                actor.get('Combat').setRange(2);
                this._actor.add(new RG.Component.LongReach());
            }
        };
    }

    /* Called at the creation of the actor. Gives certain set of starting items.
     */
    getStartingItems() {
        return [
            {name: 'Ration', count: 1}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Longsword', count: 1},
            {name: 'Chain armour', count: 1}
        ];
    }

    setStartingStats() {
        const stats = this._actor.get('Stats');
        stats.incrStat('strength', 3);
        stats.incrStat('magic', -3);
    }

}

ActorClass.Blademaster = Blademaster;

//-------------------------------------------------------------------------
/* Cryomancer actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Cryomancer extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Cryomancer');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} learns a protection spell`,
            8: `${_name} learns to attack enemies from distance`,
            12: `${_name} can freeze enemies on their tracks`,
            16: `${_name} can summon an ice companion now`,
            20: `${_name} can drain power from other spellcasters`,
            24: `${_name} can fire ice arrows towards enemies`,
            28: `${_name} can control their enemies now`,
            32: `${_name} has become a True Cryomancer, Bringer of Blizzard`
        };

        this._advances = {
            1: () => {
                // Create the spellbook
                const book = new RG.Spell.SpellBook(this._actor);
                const grasp = new RG.Spell.GraspOfWinter();
                book.addSpell(grasp);
                this._actor.setBook(book);
            },
            4: () => {
                this._actor.getBook().addSpell(new RG.Spell.IceShield());
            },
            8: () => {
                this._actor.getBook().addSpell(new RG.Spell.FrostBolt());
            },
            12: () => {
                this._actor.getBook().addSpell(new RG.Spell.IcyPrison());
            },
            16: () => {
                this._actor.getBook().addSpell(new RG.Spell.SummonIceMinion());
            },
            20: () => {
                this._actor.getBook().addSpell(new RG.Spell.PowerDrain());
            },
            24: () => {
                this._actor.getBook().addSpell(new RG.Spell.IceArrow());
            },
            28: () => {
                this._actor.getBook().addSpell(new RG.Spell.MindControl());
            },
            32: () => {
                this._actor.getBook().addSpell(new RG.Spell.Blizzard());
            }
        };
    }

    getStartingItems() {
        return [
            {name: 'Ration', count: 1},
            {name: 'Potion of power', count: 1}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Robe', count: 1},
            {name: 'Wooden staff', count: 1}
        ];

    }

    setStartingStats() {
        const stats = this._actor.get('Stats');
        stats.incrStat('strength', -2);
        stats.incrStat('magic', 3);
    }

}

ActorClass.Cryomancer = Cryomancer;

//-------------------------------------------------------------------------
/* Marksman actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Marksman extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Marksman');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} can now see and shoot further`,
            8: `${_name} deals now more damage with shots`,
            12: `${_name} can bypass enemies with ranged attacks`,
            16: `${_name} can use arrows/bolts interchangeably`,
            20: `${_name} can shoot even further`,
            24: `${_name} can evade ranged attacks`,
            28: `${_name} can shoot enemies critically`,
            32: `${_name} has become a True Marksman`
        };

        this._advances = {
            1: () => {

            },
            4: () => {
                this._actor.add(new RG.Component.EagleEye());
            },
            8: () => {
                this._actor.add(new RG.Component.StrongShot());
            },
            12: () => {
                this._actor.add(new RG.Component.ThroughShot());
            },
            16: () => {
                this._actor.add(new RG.Component.MixedShot());
            },
            20: () => {
                this._actor.add(new RG.Component.LongRangeShot());
            },
            24: () => {
                this._actor.add(new RG.Component.RangedEvasion());
            },
            28: () => {
                this._actor.add(new RG.Component.CriticalShot());
            },
            32: () => {
                this._actor.add(new RG.Component.DoubleShot());
            }
        };
    }

    getStartingItems() {
        return [
            {name: 'Ration', count: 1}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Leather armour', count: 1},
            {name: 'Wooden bow', count: 1},
            {name: 'Wooden arrow', count: 15}
        ];

    }

    setStartingStats() {
        const stats = this._actor.get('Stats');
        stats.incrStat('accuracy', 3);
        stats.incrStat('perception', 2);
        stats.incrStat('magic', -3);
    }

}
ActorClass.Marksman = Marksman;

//-------------------------------------------------------------------------
/* Spellsinger actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Spellsinger extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Spellsinger');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} gains new skill`,
            8: `${_name} gains new skill`,
            12: `${_name} gains new skill`,
            16: `${_name} gains new skill`,
            20: `${_name} gains new skill`,
            24: `${_name} gains new skill`,
            28: `${_name} gains new skill`,
            32: `${_name} has become a Mighty Spellsinger`
        };

        this._advances = {
            1: () => {
                const book = new RG.Spell.SpellBook(this._actor);
                this._actor.setBook(book);
            },
            4: () => {

            },
            8: () => {

            },
            12: () => {

            },
            16: () => {

            },
            20: () => {

            },
            24: () => {

            },
            28: () => {

            },
            32: () => {

            }
        };
    }

    getStartingItems() {
        // Starting instrument

    }

    getStartingEquipment() {

    }

    setStartingStats() {

    }

}
ActorClass.Spellsinger = Spellsinger;

//-------------------------------------------------------------------------
/* Spiritcrafter actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Spiritcrafter extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Spiritcrafter');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} can now equip 2 spirit gems`,
            8: `${_name} gains new skill`,
            12: `${_name} gains new skill`,
            16: `${_name} gains new skill`,
            20: `${_name} gains new skill`,
            24: `${_name} gains new skill`,
            28: `${_name} gains new skill`,
            32: `${_name} has become a Mighty Spiritcrafter`
        };

        this._advances = {
            1: () => {
                const book = new RG.Spell.SpellBook(this._actor);
                this._actor.setBook(book);
            },
            4: () => {

            },
            8: () => {

            },
            12: () => {

            },
            16: () => {

            },
            20: () => {
                this._actor.add(new RG.Component.SpiritItemCrafter());
            },
            24: () => {

            },
            28: () => {

            },
            32: () => {

            }
        };
    }

    getStartingItems() {
        // Starting instrument

    }

    getStartingEquipment() {

    }

    setStartingStats() {

    }

}
ActorClass.Spiritcrafter = Spiritcrafter;

RG.ACTOR_CLASSES = Object.keys(ActorClass);

module.exports = ActorClass;
<commit_msg>Specifies explicitly the classes in ACTOR_CLASSES.<commit_after>
const ActorClass = {};
const RG = require('./rg');
RG.Component = require('./component');
RG.Spell = require('./spell');

/* Factory function for actor classes. */
ActorClass.create = function(name, entity) {
    if (ActorClass.hasOwnProperty(name)) {
        const actorClass = new ActorClass[name](entity);
        return actorClass;
    }
    else {
        RG.diag('Called with entity:');
        RG.diag(entity);
        RG.err('ActorClass', 'create',
            `No class ${name} in ActorClass`);
    }
    return null;
};

/* Used by different in-game classes for actors. Provides basic getters and
 * progress functions to increase stats etc on level up. */
class ActorClassBase {

    constructor(actor, name) {
        this._actor = actor;
        actor.setActorClass(this);
        this._className = name;
    }

    getClassName() {
        return this._className;
    }

    /* Called when a level is advanced by the actor. Checks for messages, and if
     * the next ability is triggered. */
    advanceLevel() {
        const newLevel = this._actor.get('Experience').getExpLevel();
        if (this._messages.hasOwnProperty(newLevel)) {
            const cell = this._actor.getCell();
            RG.gameMsg({cell, msg: this._messages[newLevel]});
        }
        if (this._advances.hasOwnProperty(newLevel)) {
            this._advances[newLevel]();
        }
        this.incrStats(newLevel);
    }

    incrStats(newLevel) {
        const actor = this._actor;

        const hComp = actor.get('Health');
        const incr = Math.ceil(actor.getStrength() / 2);
        hComp.setMaxHP(hComp.getMaxHP() + incr);
        hComp.setHP(hComp.getHP() + incr);

        if (actor.has('SpellPower')) {
            const ppIncr = Math.ceil(actor.getMagic() / 2);
            const ppComp = actor.get('SpellPower');
            ppComp.setMaxPP(ppComp.getMaxPP() + ppIncr);
            ppComp.addPP(ppIncr);
        }

        RG.levelUpCombatStats(actor, newLevel);
    }
}

//-------------------------------------------------------------------------
/* Adventurer actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Adventurer extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Adventurer');
        this._messages = {};
        this._advances = {
            1: () => {
                const book = new RG.Spell.SpellBook(this._actor);
                this._actor.setBook(book);
            },
            4: () => {
                this._actor.add(new RG.Component.NourishedOne());
            }
        };
    }

    /* Called when a level is advanced by the actor. Checks for messages, and if
     * the next ability is triggered. */
    advanceLevel() {
        super.advanceLevel();
        const newLevel = this._actor.get('Experience').getExpLevel();
        if (newLevel % 4 === 0) {
            // Get other random actor class
            // Use it to add new abilities to the actor
        }
    }

    /* Called at the creation of the actor. Gives certain set of starting items.
     */
    getStartingItems() {
        return [
            {name: 'Ration', count: 2}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Short sword', count: 1},
            {name: 'Leather armour', count: 1}
        ];
    }

    setStartingStats() {
        // const stats = this._actor.get('Stats');
    }
}

ActorClass.Adventurer = Adventurer;

//-------------------------------------------------------------------------
/* Blademaster actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Blademaster extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Blademaster');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} knows now how to defend more skillfully`,
            8: `${_name} knows now how to hit enemies more accurately`,
            12: `${_name} knows now how to handle equipment better`,
            16: `${_name} can now strike in two directions`,
            20: `${_name} can now keep the weapons sharp`,
            24: `${_name} can now wield two blades at once`,
            28: `${_name} can now strike back immediately when attacked`,
            32: `${_name} has become a True Blademaster`
        };

        this._advances = {
            1: () => {

            },
            4: () => {
                this._actor.add(new RG.Component.Defender());
            },
            8: () => {
                this._actor.add(new RG.Component.Attacker());
            },
            12: () => {
                this._actor.add(new RG.Component.MasterEquipper());
            },
            16: () => {
                this._actor.add(new RG.Component.BiDirStrike());
            },
            20: () => {
                this._actor.add(new RG.Component.Sharpener());
            },
            24: () => {
                this._actor.add(new RG.Component.Ambidexterity());
            },
            28: () => {
                this._actor.add(new RG.Component.CounterAttack());
            },
            32: () => {
                actor.get('Combat').setRange(2);
                this._actor.add(new RG.Component.LongReach());
            }
        };
    }

    /* Called at the creation of the actor. Gives certain set of starting items.
     */
    getStartingItems() {
        return [
            {name: 'Ration', count: 1}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Longsword', count: 1},
            {name: 'Chain armour', count: 1}
        ];
    }

    setStartingStats() {
        const stats = this._actor.get('Stats');
        stats.incrStat('strength', 3);
        stats.incrStat('magic', -3);
    }

}

ActorClass.Blademaster = Blademaster;

//-------------------------------------------------------------------------
/* Cryomancer actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Cryomancer extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Cryomancer');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} learns a protection spell`,
            8: `${_name} learns to attack enemies from distance`,
            12: `${_name} can freeze enemies on their tracks`,
            16: `${_name} can summon an ice companion now`,
            20: `${_name} can drain power from other spellcasters`,
            24: `${_name} can fire ice arrows towards enemies`,
            28: `${_name} can control their enemies now`,
            32: `${_name} has become a True Cryomancer, Bringer of Blizzard`
        };

        this._advances = {
            1: () => {
                // Create the spellbook
                const book = new RG.Spell.SpellBook(this._actor);
                const grasp = new RG.Spell.GraspOfWinter();
                book.addSpell(grasp);
                this._actor.setBook(book);
            },
            4: () => {
                this._actor.getBook().addSpell(new RG.Spell.IceShield());
            },
            8: () => {
                this._actor.getBook().addSpell(new RG.Spell.FrostBolt());
            },
            12: () => {
                this._actor.getBook().addSpell(new RG.Spell.IcyPrison());
            },
            16: () => {
                this._actor.getBook().addSpell(new RG.Spell.SummonIceMinion());
            },
            20: () => {
                this._actor.getBook().addSpell(new RG.Spell.PowerDrain());
            },
            24: () => {
                this._actor.getBook().addSpell(new RG.Spell.IceArrow());
            },
            28: () => {
                this._actor.getBook().addSpell(new RG.Spell.MindControl());
            },
            32: () => {
                this._actor.getBook().addSpell(new RG.Spell.Blizzard());
            }
        };
    }

    getStartingItems() {
        return [
            {name: 'Ration', count: 1},
            {name: 'Potion of power', count: 1}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Robe', count: 1},
            {name: 'Wooden staff', count: 1}
        ];

    }

    setStartingStats() {
        const stats = this._actor.get('Stats');
        stats.incrStat('strength', -2);
        stats.incrStat('magic', 3);
    }

}

ActorClass.Cryomancer = Cryomancer;

//-------------------------------------------------------------------------
/* Marksman actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Marksman extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Marksman');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} can now see and shoot further`,
            8: `${_name} deals now more damage with shots`,
            12: `${_name} can bypass enemies with ranged attacks`,
            16: `${_name} can use arrows/bolts interchangeably`,
            20: `${_name} can shoot even further`,
            24: `${_name} can evade ranged attacks`,
            28: `${_name} can shoot enemies critically`,
            32: `${_name} has become a True Marksman`
        };

        this._advances = {
            1: () => {

            },
            4: () => {
                this._actor.add(new RG.Component.EagleEye());
            },
            8: () => {
                this._actor.add(new RG.Component.StrongShot());
            },
            12: () => {
                this._actor.add(new RG.Component.ThroughShot());
            },
            16: () => {
                this._actor.add(new RG.Component.MixedShot());
            },
            20: () => {
                this._actor.add(new RG.Component.LongRangeShot());
            },
            24: () => {
                this._actor.add(new RG.Component.RangedEvasion());
            },
            28: () => {
                this._actor.add(new RG.Component.CriticalShot());
            },
            32: () => {
                this._actor.add(new RG.Component.DoubleShot());
            }
        };
    }

    getStartingItems() {
        return [
            {name: 'Ration', count: 1}
        ];
    }

    getStartingEquipment() {
        return [
            {name: 'Leather armour', count: 1},
            {name: 'Wooden bow', count: 1},
            {name: 'Wooden arrow', count: 15}
        ];

    }

    setStartingStats() {
        const stats = this._actor.get('Stats');
        stats.incrStat('accuracy', 3);
        stats.incrStat('perception', 2);
        stats.incrStat('magic', -3);
    }

}
ActorClass.Marksman = Marksman;

//-------------------------------------------------------------------------
/* Spellsinger actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Spellsinger extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Spellsinger');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} gains new skill`,
            8: `${_name} gains new skill`,
            12: `${_name} gains new skill`,
            16: `${_name} gains new skill`,
            20: `${_name} gains new skill`,
            24: `${_name} gains new skill`,
            28: `${_name} gains new skill`,
            32: `${_name} has become a Mighty Spellsinger`
        };

        this._advances = {
            1: () => {
                const book = new RG.Spell.SpellBook(this._actor);
                this._actor.setBook(book);
            },
            4: () => {

            },
            8: () => {

            },
            12: () => {

            },
            16: () => {

            },
            20: () => {

            },
            24: () => {

            },
            28: () => {

            },
            32: () => {

            }
        };
    }

    getStartingItems() {
        // Starting instrument

    }

    getStartingEquipment() {

    }

    setStartingStats() {

    }

}
ActorClass.Spellsinger = Spellsinger;

//-------------------------------------------------------------------------
/* Spiritcrafter actor class and its experience level-specific features. */
//-------------------------------------------------------------------------
class Spiritcrafter extends ActorClassBase {

    constructor(actor) {
        super(actor, 'Spiritcrafter');
        const _name = actor.getName();

        this._messages = {
            4: `${_name} can now equip 2 spirit gems`,
            8: `${_name} gains new skill`,
            12: `${_name} gains new skill`,
            16: `${_name} gains new skill`,
            20: `${_name} gains new skill`,
            24: `${_name} gains new skill`,
            28: `${_name} gains new skill`,
            32: `${_name} has become a Mighty Spiritcrafter`
        };

        this._advances = {
            1: () => {
                const book = new RG.Spell.SpellBook(this._actor);
                this._actor.setBook(book);
            },
            4: () => {

            },
            8: () => {

            },
            12: () => {

            },
            16: () => {

            },
            20: () => {
                this._actor.add(new RG.Component.SpiritItemCrafter());
            },
            24: () => {

            },
            28: () => {

            },
            32: () => {

            }
        };
    }

    getStartingItems() {
        // Starting instrument

    }

    getStartingEquipment() {

    }

    setStartingStats() {

    }

}
ActorClass.Spiritcrafter = Spiritcrafter;

RG.ACTOR_CLASSES = ['Cryomancer', 'Blademaster'];

module.exports = ActorClass;
<|endoftext|>


<commit_before>module.exports = {
  entry: './src/main.tsx',
  output: {
    filename: './build/main.js'
  },
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },
  devServer: {
    inline: true,
    port: 1337
  },
  module: {
    loaders: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ]
  }
}
<commit_msg>Updgrade webpack config<commit_after>const { join } = require('path');

module.exports = {
  entry: './src/main.tsx',
  output: {
    path: join(__dirname, 'build'),
    filename: 'main.js',
  },
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json'],
  },
  devServer: {
    inline: true,
    port: 1337
  },
  module: {
    rules: [
      { test: /\.tsx?$/, use: 'ts-loader' }
    ]
  }
}
<|endoftext|>


<commit_before>#!/bin/node
/*
 * initial screen script, to be used by other scripts
 * (Except preinstall)
 */
let vermon = require('../main')
const menu = require('inquirer-menu')
let entities = require('../Entities')
let filters = require('../Filters')
let meta = require('../Metadata') // Imported to trigger metadata functions, but not explicitely used
let extensions = require('../Extensions')
let utils = require('../utils')
let log = utils.log
const screen = [
  ' __      __                             ',
  ' \\ \\    / /                             ',
  '  \\ \\  / /__ _ __ _ __ ___   ___  _ __  ',
  "   \\ \\/ / _ \\ '__| '_ ` _ \\ / _ \\| '_ \\ ",
  '    \\  /  __/ |  | | | | | | (_) | | | |',
  '     \\/ \\___|_|  |_| |_| |_|\\___/|_| |_|'
]
const C = {
  Reset: '\x1b[0m',
  Bright: '\x1b[1m',
  Dim: '\x1b[2m',
  Underscore: '\x1b[4m',
  Blink: '\x1b[5m',
  Reverse: '\x1b[7m',
  Hidden: '\x1b[8m',

  FgBlack: '\x1b[30m',
  FgRed: '\x1b[31m',
  FgGreen: '\x1b[32m',
  FgYellow: '\x1b[33m',
  FgBlue: '\x1b[34m',
  FgMagenta: '\x1b[35m',
  FgCyan: '\x1b[36m',
  FgWhite: '\x1b[37m',

  BgBlack: '\x1b[40m',
  BgRed: '\x1b[41m',
  BgGreen: '\x1b[42m',
  BgYellow: '\x1b[43m',
  BgBlue: '\x1b[44m',
  BgMagenta: '\x1b[45m',
  BgCyan: '\x1b[46m',
  BgWhite: '\x1b[47m'
}

var count

startScreen()
increaseCount()

function startScreen () {
  for (line in screen) {
    console.log(C.FgBlue, screen[line])
  }
  console.log('                                                         (Fonts by https://patorsk.com)')
  console.log(C.Reset, '_____________________________________________________________')
  console.log(C.Reset, 'Welcome to the setup screen')
  console.log(C.Reset, '')
}

function increaseCount () {
  if (!count) count = 1
  else count++
}

function getCount () {
  return count
}

const saveChanges = (className, bag) => {
  return {
    'Save changes': () => {
      log.info(`Saving object ${className}...`)
      let choices = bag[className]
      let saveOption = choices['Save changes']
      delete choices['Save changes']
      // Expect to receive the actual entry which needs to be instantiated
      log.debug(choices)
      let factory = new entities.EntitiesFactory()
      let args = {}
      for (var c in choices) {
        args[c] = choices[c].answer
      }
      log.debug(`Instanciating with args ${JSON.stringify(args)}...`)
      try {
        vermon.addInstance(factory, className, args)
      } catch (e) {
        log.error(e.message)
        //Need to reinstate save changes
        choices['Save changes'] = saveOption
      }
      //TODO: This should actually only be done at the end, in the
      //vermon.save('test_config.js', (status, message) => {

      //})
    }
  }
}

const chooseEnvironment = {
  message: 'Select my Environment',
  choices: entities.GetExtensionsMetadata(entities.Environment, saveChanges)
}

const addDetectors = {
  message: 'Add a Detector',
  choices: entities.GetExtensionsMetadata(entities.MotionDetector, saveChanges)
}

const addNotifiers = {
  message: 'Add a Notifier',
  choices: entities.GetExtensionsMetadata(entities.BaseNotifier, saveChanges)
}

const addFilters = {
  message: 'Add a Filter',
  choices: entities.GetExtensionsMetadata(filters.BaseFilter, saveChanges)
}

const runWithoutSaving = {
  message: 'Run current configuration without Saving.',
  choices: {
    callApi: function () {
      console.log('red-api called')
    }
  }
}

const saveConfig = {
  message: 'Save to Local Config file.',
  choices: {
    'Confirm saving to local': function () {
      vermon.save('test_config.js', (status, message) => {

      }, true)
    }
  }
}

let level = 0

function createMenu () {
  utils.setLevel('info');
  return {
    message: 'Choose your option(s) below',
    choices: {
      'Choose your Environment': chooseEnvironment,
      'Add a Detector': addDetectors,
      'Add a Notifier': addNotifiers,
      'Add a Filter': addFilters,
      'Run without saving': runWithoutSaving,
      'Save to local Config file': saveConfig
    }
  }
};

menu(createMenu)
  .then(function () {
    console.log('bye')
  })
  .catch(function (err) {
    console.log(err.stack)
  })

exports.count = getCount()
exports.C = C
<commit_msg>Changed log level of init script to show errors only<commit_after>#!/bin/node
/*
 * initial screen script, to be used by other scripts
 * (Except preinstall)
 */
let vermon = require('../main')
const menu = require('inquirer-menu')
let entities = require('../Entities')
let filters = require('../Filters')
let meta = require('../Metadata') // Imported to trigger metadata functions, but not explicitely used
let extensions = require('../Extensions')
let utils = require('../utils')
let log = utils.log
const screen = [
  ' __      __                             ',
  ' \\ \\    / /                             ',
  '  \\ \\  / /__ _ __ _ __ ___   ___  _ __  ',
  "   \\ \\/ / _ \\ '__| '_ ` _ \\ / _ \\| '_ \\ ",
  '    \\  /  __/ |  | | | | | | (_) | | | |',
  '     \\/ \\___|_|  |_| |_| |_|\\___/|_| |_|'
]
const C = {
  Reset: '\x1b[0m',
  Bright: '\x1b[1m',
  Dim: '\x1b[2m',
  Underscore: '\x1b[4m',
  Blink: '\x1b[5m',
  Reverse: '\x1b[7m',
  Hidden: '\x1b[8m',

  FgBlack: '\x1b[30m',
  FgRed: '\x1b[31m',
  FgGreen: '\x1b[32m',
  FgYellow: '\x1b[33m',
  FgBlue: '\x1b[34m',
  FgMagenta: '\x1b[35m',
  FgCyan: '\x1b[36m',
  FgWhite: '\x1b[37m',

  BgBlack: '\x1b[40m',
  BgRed: '\x1b[41m',
  BgGreen: '\x1b[42m',
  BgYellow: '\x1b[43m',
  BgBlue: '\x1b[44m',
  BgMagenta: '\x1b[45m',
  BgCyan: '\x1b[46m',
  BgWhite: '\x1b[47m'
}

var count

startScreen()
increaseCount()

function startScreen () {
  for (line in screen) {
    console.log(C.FgBlue, screen[line])
  }
  console.log('                                                         (Fonts by https://patorsk.com)')
  console.log(C.Reset, '_____________________________________________________________')
  console.log(C.Reset, 'Welcome to the setup screen')
  console.log(C.Reset, '')
}

function increaseCount () {
  if (!count) count = 1
  else count++
}

function getCount () {
  return count
}

const saveChanges = (className, bag) => {
  return {
    'Save changes': () => {
      log.info(`Saving object ${className}...`)
      let choices = bag[className]
      let saveOption = choices['Save changes']
      delete choices['Save changes']
      // Expect to receive the actual entry which needs to be instantiated
      log.debug(choices)
      let factory = new entities.EntitiesFactory()
      let args = {}
      for (var c in choices) {
        args[c] = choices[c].answer
      }
      log.debug(`Instanciating with args ${JSON.stringify(args)}...`)
      try {
        vermon.addInstance(factory, className, args)
      } catch (e) {
        log.error(e.message)
        //Need to reinstate save changes
        choices['Save changes'] = saveOption
      }
      //TODO: This should actually only be done at the end, in the
      //vermon.save('test_config.js', (status, message) => {

      //})
    }
  }
}

const chooseEnvironment = {
  message: 'Select my Environment',
  choices: entities.GetExtensionsMetadata(entities.Environment, saveChanges)
}

const addDetectors = {
  message: 'Add a Detector',
  choices: entities.GetExtensionsMetadata(entities.MotionDetector, saveChanges)
}

const addNotifiers = {
  message: 'Add a Notifier',
  choices: entities.GetExtensionsMetadata(entities.BaseNotifier, saveChanges)
}

const addFilters = {
  message: 'Add a Filter',
  choices: entities.GetExtensionsMetadata(filters.BaseFilter, saveChanges)
}

const runWithoutSaving = {
  message: 'Run current configuration without Saving.',
  choices: {
    callApi: function () {
      console.log('red-api called')
    }
  }
}

const saveConfig = {
  message: 'Save to Local Config file.',
  choices: {
    'Confirm saving to local': function () {
      vermon.save('test_config.js', (status, message) => {

      }, true)
    }
  }
}

let level = 0

function createMenu () {
  utils.setLevel('error');
  return {
    message: 'Choose your option(s) below',
    choices: {
      'Choose your Environment': chooseEnvironment,
      'Add a Detector': addDetectors,
      'Add a Notifier': addNotifiers,
      'Add a Filter': addFilters,
      'Run without saving': runWithoutSaving,
      'Save to local Config file': saveConfig
    }
  }
};

menu(createMenu)
  .then(function () {
    console.log('bye')
  })
  .catch(function (err) {
    console.log(err.stack)
  })

exports.count = getCount()
exports.C = C
<|endoftext|>


<commit_before>"use strict";

/// Required Core Modules

///
/// External Modules
const Deque = require('double-ended-queue');
///
/// Internal Modules
const SuperTaskInternal = require('./lib/SuperTask');
const ContextPermissions = require('./lib/ContextPermissions');
const TaskObject = require('./lib/TaskObject');
///
/// Predefined Types
// TYPES
const ST_LOCAL_TYPE = 0, ST_SHARED_TYPE = 1, ST_FOREIGN_TYPE = 2;
// PERMISSIONS
const ST_NONE = 0, ST_RESTRICTED = 1, ST_MINIMAL = 2, ST_UNRESTRICTED = 3;
///
// No Operation function
function noop() { return null; }

class SuperTask extends SuperTaskInternal {
    /**
     * Creates new instance.
     * @class SuperTask
     *
     * @example
     * var SuperTask = require('supertask');
     * var TaskManager = new SuperTask();
     *
     * @returns {Instance} Returns a new instance of the module.
     */
    constructor(size) {
        super(size);
    }
    /**
    * Creates a new local Task. A local task is a task that is not
    * shared by any outside entity and usually performs slightly
    * faster than shared or foreign tasks as there is no compilation
    * or try/catch involved.
    *
    * @param {String} name - A unique name for this Task.
    * @param {Function} taskFunction - The JS function of the Task.
    * @returns {@link Task}
    */
    addLocal(name, func) {
        return this._addTask(name, func, null, ST_LOCAL_TYPE);
    }

    /**
     * Creates a new foreign Task. A local task is a task that is not
     * shared by any outside entity and usually performs slightly
     * faster than shared or foreign tasks as there is no compilation
     * or try/catch involved.
     *
     * @param {String} name - A unique name for this Task.
     * @param {Function} taskFunction - The JS function or source with
     * module.exports to be used as the function. Note that sources are compiled
     * to a function before use with about a 30ms overhead on the first call unless
     * precompile method of task is called beforehand.
     * @returns {@link Task}
     */
    addForeign(name, source) {
        // VM requires a String source to compile
        // If given source is a function convert it to source (context is lost)
        if (typeof source === 'function') {
            source = 'module.exports = ' + source.toString();
        }
        return this._addTask(name, source, null, ST_FOREIGN_TYPE);
    }

    /**
     * Run a task with the given arguments
     *
     * @param {String} taskName - Unique name of the task
     * @param {...*} arguments - Arguments that are passed to the Task.
     * You can call this function with any number of arguments so long
     * as the last argument is the callback.
     * @param {Function} callback - The callback that handles the response.
     * Note that the callback parameters are based on what the function calls
     * the callback with but will include `error` as the first parameter as
     * per usual NodeJS async calls.
     */
    do() {
        let args = Array.prototype.slice.call(arguments);
        let name = args.shift();
        let callback = noop;

        // Check for callback
        if (typeof args[args.length - 1] === 'function') {
            callback = args.pop();
        }

        this.apply(name, null, args, callback);
    }

    apply(name, context, args, callback) {

        // Check for mapped task
        if (!this.map.has(name)) {
            callback(new Error('Task not found!'));
            return;
        }

        let task = this.map.get(name);

        // Check for mapped task
        if (!task) {
            return callback(new Error('Task not found!'));
        }

        // Set Globals to task's default
        let globals = task.globals;
        // Combine Permissions Context (SLOWS DOWN EXECUTION)
        if ((task.access) && (task.access !== ST_NONE)) {
            globals = ContextPermissions(globals || {}, task.access);
        }

        // Sanitize args
        args = (Array.isArray(args)) ? args : [];

        // Compile task if it is in source form
        if (typeof task.func !== 'function') {
            try {
                let result = this._compile(task, globals);
                if (typeof result === 'function') task.func = result;
                else return callback(new Error("Unknown error occurred. Failed to compile and execution was halted."));
            } catch (e) {
                return callback(e);
            }
        }
        // Push to Queue
        this._push({
            name: name,
            globals: globals,
            context: context,
            args: args,
            task: task,
            callback: callback
        });
    }

    /**
     * Remove a task.
     *
     * @param {String} name - Name of the task.
     * @returns {Boolean} - Returns true if task
     * existed and was removed or false if task did not exist
     */
    remove(name) {
        return this.map.delete(name);
    }

    /**
     * Check if task exists.
     *
     * @param {String} name - Name of the task.
     * @returns {Boolean} exists
     */
    has(name) {
        return !!this.map.has(name);
    }

    /**
     * Get a wrapped version of the task.
     *
     * @param {String} name - Name of the task.
     * @returns {Object} task
     */
    get(name) {
        if (!this.has(name)) return null;
        return TaskObject.wrap(this, this.map.get(name));
    }
}

/// EXTEND PREDEFINED VARS
SuperTask.ST_LOCAL_TYPE = ST_LOCAL_TYPE;
SuperTask.ST_SHARED_TYPE = ST_SHARED_TYPE;
SuperTask.ST_FOREIGN_TYPE = ST_FOREIGN_TYPE;

/** No permissions. Code runs JS only. */
SuperTask.ST_NONE = ST_NONE;
/** Some permissions. Allows streams, Buffer, setTimeout, setInterval only */
SuperTask.ST_RESTRICTED = ST_RESTRICTED;
/** Minimal permissions. Allows all restricted permissions and __dirname, __filename, console globals.
 * Includes a limited require('*') function with access to 'http', 'https', 'util', 'os', 'path', 'events', 'stream', 'string_decoder', 'url', 'zlib'
 */
SuperTask.ST_MINIMAL = ST_MINIMAL;
/** UNSAFE, All permissions. Copies global scope. */
SuperTask.ST_UNRESTRICTED = ST_UNRESTRICTED;

module.exports = SuperTask;<commit_msg>Improved argument parsing for V8<commit_after>"use strict";

/// Required Core Modules

///
/// External Modules
const Deque = require('double-ended-queue');
///
/// Internal Modules
const SuperTaskInternal = require('./lib/SuperTask');
const ContextPermissions = require('./lib/ContextPermissions');
const TaskObject = require('./lib/TaskObject');
///
/// Predefined Types
// TYPES
const ST_LOCAL_TYPE = 0, ST_SHARED_TYPE = 1, ST_FOREIGN_TYPE = 2;
// PERMISSIONS
const ST_NONE = 0, ST_RESTRICTED = 1, ST_MINIMAL = 2, ST_UNRESTRICTED = 3;
///
// No Operation function
function noop() { return null; }

class SuperTask extends SuperTaskInternal {
    /**
     * Creates new instance.
     * @class SuperTask
     *
     * @example
     * var SuperTask = require('supertask');
     * var TaskManager = new SuperTask();
     *
     * @returns {Instance} Returns a new instance of the module.
     */
    constructor(size) {
        super(size);
    }
    /**
    * Creates a new local Task. A local task is a task that is not
    * shared by any outside entity and usually performs slightly
    * faster than shared or foreign tasks as there is no compilation
    * or try/catch involved.
    *
    * @param {String} name - A unique name for this Task.
    * @param {Function} taskFunction - The JS function of the Task.
    * @returns {@link Task}
    */
    addLocal(name, func) {
        return this._addTask(name, func, null, ST_LOCAL_TYPE);
    }

    /**
     * Creates a new foreign Task. A local task is a task that is not
     * shared by any outside entity and usually performs slightly
     * faster than shared or foreign tasks as there is no compilation
     * or try/catch involved.
     *
     * @param {String} name - A unique name for this Task.
     * @param {Function} taskFunction - The JS function or source with
     * module.exports to be used as the function. Note that sources are compiled
     * to a function before use with about a 30ms overhead on the first call unless
     * precompile method of task is called beforehand.
     * @returns {@link Task}
     */
    addForeign(name, source) {
        // VM requires a String source to compile
        // If given source is a function convert it to source (context is lost)
        if (typeof source === 'function') {
            source = 'module.exports = ' + source.toString();
        }
        return this._addTask(name, source, null, ST_FOREIGN_TYPE);
    }

    /**
     * Run a task with the given arguments
     *
     * @param {String} taskName - Unique name of the task
     * @param {...*} arguments - Arguments that are passed to the Task.
     * You can call this function with any number of arguments so long
     * as the last argument is the callback.
     * @param {Function} callback - The callback that handles the response.
     * Note that the callback parameters are based on what the function calls
     * the callback with but will include `error` as the first parameter as
     * per usual NodeJS async calls.
     */
    do() {
        let args = new Array(arguments.length);
        for(let i = 0; i < args.length; ++i) {
            args[i] = arguments[i];
        }
        let name = args.shift();
        let callback = noop;

        // Check for callback
        if (typeof args[args.length - 1] === 'function') {
            callback = args.pop();
        }

        this.apply(name, null, args, callback);
    }

    apply(name, context, args, callback) {

        // Check for mapped task
        if (!this.map.has(name)) {
            callback(new Error('Task not found!'));
            return;
        }

        let task = this.map.get(name);

        // Check for mapped task
        if (!task) {
            return callback(new Error('Task not found!'));
        }

        // Set Globals to task's default
        let globals = task.globals;
        // Combine Permissions Context (SLOWS DOWN EXECUTION)
        if ((task.access) && (task.access !== ST_NONE)) {
            globals = ContextPermissions(globals || {}, task.access);
        }

        // Sanitize args
        args = (Array.isArray(args)) ? args : [];

        // Compile task if it is in source form
        if (typeof task.func !== 'function') {
            try {
                let result = this._compile(task, globals);
                if (typeof result === 'function') task.func = result;
                else return callback(new Error("Unknown error occurred. Failed to compile and execution was halted."));
            } catch (e) {
                return callback(e);
            }
        }
        // Push to Queue
        this._push({
            name: name,
            globals: globals,
            context: context,
            args: args,
            task: task,
            callback: callback
        });
    }

    /**
     * Remove a task.
     *
     * @param {String} name - Name of the task.
     * @returns {Boolean} - Returns true if task
     * existed and was removed or false if task did not exist
     */
    remove(name) {
        return this.map.delete(name);
    }

    /**
     * Check if task exists.
     *
     * @param {String} name - Name of the task.
     * @returns {Boolean} exists
     */
    has(name) {
        return !!this.map.has(name);
    }

    /**
     * Get a wrapped version of the task.
     *
     * @param {String} name - Name of the task.
     * @returns {Object} task
     */
    get(name) {
        if (!this.has(name)) return null;
        return TaskObject.wrap(this, this.map.get(name));
    }
}

/// EXTEND PREDEFINED VARS
SuperTask.ST_LOCAL_TYPE = ST_LOCAL_TYPE;
SuperTask.ST_SHARED_TYPE = ST_SHARED_TYPE;
SuperTask.ST_FOREIGN_TYPE = ST_FOREIGN_TYPE;

/** No permissions. Code runs JS only. */
SuperTask.ST_NONE = ST_NONE;
/** Some permissions. Allows streams, Buffer, setTimeout, setInterval only */
SuperTask.ST_RESTRICTED = ST_RESTRICTED;
/** Minimal permissions. Allows all restricted permissions and __dirname, __filename, console globals.
 * Includes a limited require('*') function with access to 'http', 'https', 'util', 'os', 'path', 'events', 'stream', 'string_decoder', 'url', 'zlib'
 */
SuperTask.ST_MINIMAL = ST_MINIMAL;
/** UNSAFE, All permissions. Copies global scope. */
SuperTask.ST_UNRESTRICTED = ST_UNRESTRICTED;

module.exports = SuperTask;<|endoftext|>


<commit_before>/**
 * jQuery.deferredEach() -- a non-blocking, async implementation of $.each()
 * using jQuery's deferred/promise features.
 *
 * Copyright (c) 2015 Adam Messinger, http://zenscope.com/
 * Released under the MIT license, see LICENSE.txt for details.
 *
 * Based on "yieldingEach" by Colin Marc (http://colinmarc.com/) and the source
 * for jQuery.each()
 */

(function($, undefined) {
  'use strict';

  $.deferredEach = function(collection, callback) {
    var i = 0;
    var length = collection.length;
    var is_array = _isArraylike(collection);
    var parent_deferred = new $.Deferred();
    var child_deferreds;
    var keys = [];
    var next, key;

    if (is_array) {
      child_deferreds = _makeChildDeferredsArray(length);

      next = function() {
        if (i < length && callback.call(collection[i], i, collection[i++]) !== false) {
          setTimeout(next, 1);
        }
        child_deferreds[i - 1].resolve();
        parent_deferred.notify(i / length);
      };
      next();
    } else {
      for (key in collection) {
        keys.push(key);
      }
      child_deferreds = _makeChildDeferredsArray(keys.length);

      next = function() {
        if (i < keys.length && callback.call(collection[keys[i]], keys[i], collection[keys[i++]]) !== false) {
          setTimeout(next, 1);
        }
        child_deferreds[i - 1].resolve();
        parent_deferred.notify(i / keys.length);
      };
      next();
    }

    $.when.apply(undefined, child_deferreds).then(function() {
      parent_deferred.notify(1);
      parent_deferred.resolve(collection);
    });
    return parent_deferred.promise();
  };

  function _makeChildDeferredsArray(length) {
    var i = 0;
    var array = [];

    for (; i < length; i++) {
      array.push(new $.Deferred());
    }
    return array;
  }

  function _isArraylike(obj) {
    var length = obj.length;
    var type = $.type(obj);

    if (type === "function" || $.isWindow(obj)) {
      return false;
    }
    if (obj.nodeType === 1 && length) {
      return true;
    }
    return type === "array" || length === 0 ||
           (typeof length === "number" && length > 0 && (length - 1) in obj);
  }
})(jQuery);
<commit_msg>Added leading semicolon for safer script concatenation.<commit_after>/**
 * jQuery.deferredEach() -- a non-blocking, async implementation of $.each()
 * using jQuery's deferred/promise features.
 *
 * Copyright (c) 2015 Adam Messinger, http://zenscope.com/
 * Released under the MIT license, see LICENSE.txt for details.
 *
 * Based on "yieldingEach" by Colin Marc (http://colinmarc.com/) and the source
 * for jQuery.each()
 */

;(function($, undefined) {
  'use strict';

  $.deferredEach = function(collection, callback) {
    var i = 0;
    var length = collection.length;
    var is_array = _isArraylike(collection);
    var parent_deferred = new $.Deferred();
    var child_deferreds;
    var keys = [];
    var next, key;

    if (is_array) {
      child_deferreds = _makeChildDeferredsArray(length);

      next = function() {
        if (i < length && callback.call(collection[i], i, collection[i++]) !== false) {
          setTimeout(next, 1);
        }
        child_deferreds[i - 1].resolve();
        parent_deferred.notify(i / length);
      };
      next();
    } else {
      for (key in collection) {
        keys.push(key);
      }
      child_deferreds = _makeChildDeferredsArray(keys.length);

      next = function() {
        if (i < keys.length && callback.call(collection[keys[i]], keys[i], collection[keys[i++]]) !== false) {
          setTimeout(next, 1);
        }
        child_deferreds[i - 1].resolve();
        parent_deferred.notify(i / keys.length);
      };
      next();
    }

    $.when.apply(undefined, child_deferreds).then(function() {
      parent_deferred.notify(1);
      parent_deferred.resolve(collection);
    });
    return parent_deferred.promise();
  };

  function _makeChildDeferredsArray(length) {
    var i = 0;
    var array = [];

    for (; i < length; i++) {
      array.push(new $.Deferred());
    }
    return array;
  }

  function _isArraylike(obj) {
    var length = obj.length;
    var type = $.type(obj);

    if (type === "function" || $.isWindow(obj)) {
      return false;
    }
    if (obj.nodeType === 1 && length) {
      return true;
    }
    return type === "array" || length === 0 ||
           (typeof length === "number" && length > 0 && (length - 1) in obj);
  }
})(jQuery);<|endoftext|>