<commit_before>/*
 * ajax.js
 * https://github.com/savetheinternet/Tinyboard/blob/master/js/ajax.js
 *
 * Released under the MIT license
 * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/ajax.js';
 *
 */

$(window).ready(function() {
	var setup_form = function($form) {
		$form.submit(function() {
			var form = this;
			var submit_txt = $(this).find('input[type="submit"]').val();
			if (typeof FormData == 'undefined')
				return true;

			var formData = new FormData(this);
			formData.append('json_response', '1');

			var updateProgress = function(e) {
				$(form).find('input[type="submit"]').val(_('Posting... (#%)').replace('#', Math.round(e.position / e.total * 100)));
			};

			$.ajax({
				url: this.action,
				type: 'POST',
				xhr: function() {
					var xhr = $.ajaxSettings.xhr();
					if(xhr.upload) {
						xhr.upload.addEventListener('progress', updateProgress, false);
					}
					return xhr;
				},
				success: function(post_response) {
					if (post_response.error) {
						alert(post_response.error);
						$(form).find('input[type="submit"]').val(submit_txt);
						$(form).find('input[type="submit"]').removeAttr('disabled');
					} else if (post_response.redirect && post_response.id) {
						if (!$(form).find('input[name="thread"]').length) {
							document.location = post_response.redirect;
						} else {
							$.ajax({
								url: post_response.redirect,
								success: function(data) {
									$(data).find('div.post.reply').each(function() {
										var id = $(this).attr('id');
										if($('#' + id).length == 0) {
											$(this).insertAfter($('div.post:last').next()).after('
');
											$(document).trigger('new_post', this);
										}
									});
									highlightReply(post_response.id);
									document.location = '#' + post_response.id;

									$(form).find('input[type="submit"]').val(submit_txt);
									$(form).find('input[type="submit"]').removeAttr('disabled');
									$(form).find('input[name="subject"],textarea[name="body"],input[type="file"]').val('');
								},
								cache: false,
								contentType: false,
								processData: false
							}, 'html');
						}
						$(form).find('input[type="submit"]').val('Posted...');
					} else {
						alert(_('An unknown error occured when posting!'));
						$(form).find('input[type="submit"]').val(submit_txt);
						$(form).find('input[type="submit"]').removeAttr('disabled');
					}
				},
				error: function(xhr, status, er) {
					// An error occured
					// TODO
					alert('Something went wrong!');
				},
				// Form data
				data: formData,
				cache: false,
				contentType: false,
				processData: false
			}, 'json');

			$(form).find('input[type="submit"]').val(_('Posting...'));
			$(form).find('input[type="submit"]').attr('disabled', true);

			return false;
		});
	};
	setup_form($('form[name="post"]'));
	$(window).on('quick-reply', function(e, quickForm) {
		setup_form($('form#quick-reply'));
	});
});
<commit_msg>some quick bugfixes<commit_after>/*
 * ajax.js
 * https://github.com/savetheinternet/Tinyboard/blob/master/js/ajax.js
 *
 * Released under the MIT license
 * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/ajax.js';
 *
 */

$(window).ready(function() {
	var setup_form = function($form) {
		$form.submit(function() {
			var form = this;
			var submit_txt = $(this).find('input[type="submit"]').val();
			if (typeof FormData == 'undefined')
				return true;

			var formData = new FormData(this);
			formData.append('json_response', '1');

			var updateProgress = function(e) {
				$(form).find('input[type="submit"]').val(_('Posting... (#%)').replace('#', Math.round(e.position / e.total * 100)));
			};

			$.ajax({
				url: this.action,
				type: 'POST',
				xhr: function() {
					var xhr = $.ajaxSettings.xhr();
					if(xhr.upload) {
						xhr.upload.addEventListener('progress', updateProgress, false);
					}
					return xhr;
				},
				success: function(post_response) {
					if (post_response.error) {
						alert(post_response.error);
						$(form).find('input[type="submit"]').val(submit_txt);
						$(form).find('input[type="submit"]').removeAttr('disabled');
					} else if (post_response.redirect && post_response.id) {
						if (!$(form).find('input[name="thread"]').length) {
							document.location = post_response.redirect;
						} else {
							$.ajax({
								url: post_response.redirect,
								success: function(data) {
									$(data).find('div.post.reply').each(function() {
										var id = $(this).attr('id');
										if($('#' + id).length == 0) {
											$(this).insertAfter($('div.post:last').next()).after('
');
											$(document).trigger('new_post', this);
										}
									});
									highlightReply(post_response.id);
									document.location = '#' + post_response.id;

									$(form).find('input[type="submit"]').val(submit_txt);
									$(form).find('input[type="submit"]').removeAttr('disabled');
									$(form).find('input[name="subject"],input[name="file_url"],\
										textarea[name="body"],input[type="file"]').val('').change();
								},
								cache: false,
								contentType: false,
								processData: false
							}, 'html');
						}
						$(form).find('input[type="submit"]').val('Posted...');
					} else {
						alert(_('An unknown error occured when posting!'));
						$(form).find('input[type="submit"]').val(submit_txt);
						$(form).find('input[type="submit"]').removeAttr('disabled');
					}
				},
				error: function(xhr, status, er) {
					// An error occured
					// TODO
					alert('Something went wrong!');
				},
				// Form data
				data: formData,
				cache: false,
				contentType: false,
				processData: false
			}, 'json');

			$(form).find('input[type="submit"]').val(_('Posting...'));
			$(form).find('input[type="submit"]').attr('disabled', true);

			return false;
		});
	};
	setup_form($('form[name="post"]'));
	$(window).on('quick-reply', function(e, quickForm) {
		setup_form($('form#quick-reply'));
	});
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'rocketchat:ldap',
  version: '0.0.1',
  summary: 'Accounts login handler for LDAP using ldapjs from npm',
  git: 'https://github.com/rocketchat/rocketchat-ldap'
});

Npm.depends({
  ldapjs: "0.7.1",
});

// Loads all i18n.json files into tapi18nFiles
var _ = Npm.require('underscore');
var fs = Npm.require('fs');
tapi18nFiles = _.compact(_.map(fs.readdirSync('packages/rocketchat-ldap/i18n'), function(filename) {
    if (fs.statSync('packages/rocketchat-ldap/i18n/' + filename).size > 16) {
        return 'i18n/' + filename;
    }
}));

Package.onUse(function(api) {
  api.versionsFrom('1.0.3.1');

  // Commom
  api.use('rocketchat:lib@0.0.1');
  api.use('tap:i18n@1.5.1');
  api.use('yasaricli:slugify');
  api.use('coffeescript');
  // Client
  api.use('templating', 'client');
  // Server
  api.use('accounts-base', 'server');
  api.use('accounts-password', 'server');

  // Common
  // TAP
  api.addFiles('package-tap.i18n');

  // Client
  api.addFiles('ldap_client.js', 'client');
  // Server
  api.addFiles('ldap_server.js', 'server');
  api.addFiles('config_server.coffee', 'server');

  api.addFiles(tapi18nFiles);

  api.export('LDAP', 'server');
  api.export('LDAP_DEFAULTS', 'server');
  api.export('MeteorWrapperLdapjs');
});
<commit_msg>update ldapjs for support node 0.12.x tls<commit_after>Package.describe({
  name: 'rocketchat:ldap',
  version: '0.0.1',
  summary: 'Accounts login handler for LDAP using ldapjs from npm',
  git: 'https://github.com/rocketchat/rocketchat-ldap'
});

Npm.depends({
  ldapjs: "1.0.0",
});

// Loads all i18n.json files into tapi18nFiles
var _ = Npm.require('underscore');
var fs = Npm.require('fs');
tapi18nFiles = _.compact(_.map(fs.readdirSync('packages/rocketchat-ldap/i18n'), function(filename) {
    if (fs.statSync('packages/rocketchat-ldap/i18n/' + filename).size > 16) {
        return 'i18n/' + filename;
    }
}));

Package.onUse(function(api) {
  api.versionsFrom('1.0.3.1');

  // Commom
  api.use('rocketchat:lib@0.0.1');
  api.use('tap:i18n@1.5.1');
  api.use('yasaricli:slugify');
  api.use('coffeescript');
  // Client
  api.use('templating', 'client');
  // Server
  api.use('accounts-base', 'server');
  api.use('accounts-password', 'server');

  // Common
  // TAP
  api.addFiles('package-tap.i18n');

  // Client
  api.addFiles('ldap_client.js', 'client');
  // Server
  api.addFiles('ldap_server.js', 'server');
  api.addFiles('config_server.coffee', 'server');

  api.addFiles(tapi18nFiles);

  api.export('LDAP', 'server');
  api.export('LDAP_DEFAULTS', 'server');
  api.export('MeteorWrapperLdapjs');
});
<|endoftext|>


<commit_before>(function(undefined) {
    'use strict';

    var ERROR_CONFIG_NOT_FOUND  = 2,
        ERROR_DEP_NOT_FOUND     = 3,
        JSON_SPACES             = 4,
        ENOENT                  = 'ENOENT',
        DEFAULT_BOWER_COMMAND   = 'help',
        DEFAULT_BOWER_DIR       = 'vendor',
        SRC_FILE                = '_source',
        GRUNT_FILE              = 'grunt.js',
        JETFUEL_FILE            = '.jetfuel.json',
        BOWER_LATEST            = '*';

    var util = require('util'),
        fs = require('fs'),
        path = require('path'),
        color = require('colors'),
        readJSON = require('./util').readJSON,
        //info = readJSON(__dirname + '/../package.json'),
        directories = [],
        die = curry(done, [1]),
        running = null,
        args,

        IndicatorsEnum = {
            SUCCESS:    '✓',
            FAILURE:    '✕'
        },

        LogEnum = {
            INFO:       'INFO',
            ERROR:      'ERROR',
            DEBUG:      'DEBUG',
            WARNING:    'WARNING'
        },

        components = {

            grunt: {
                name: 'Grunt',
                loaded: null,
                require: 'grunt',
                onLoad: grunt,
                onComplete: done,
                config: {
                    npmTasks: ['jetfuel-grunt-tasks']
                }
            },

            bower: {
                name: 'Bower',
                loaded: null,
                require: 'bower',
                onLoad: bower
            }

        },

        cli = {

            "--version": function() {
                util.puts('Version: ' + require('./version').call().bold);
                done();
            },

            init: function() {
                var init = require('./init');
                init.done = done;
                init.apply(init, args);
            },

            grunt:  curry(load, [components.grunt.require]),
            bower:  curry(load, [components.bower.require])

        },

        directives = {

            json: function(file) {
                var data = fs.existsSync(file) && readJSON(file) || {};
                data[SRC_FILE] = file;
                return data;
            }

        };

    function jetfuel() {
        load(components.grunt.require, { facade: true });
    }

    function curry(fn, args, ctx) {
       return function() {
         return fn.apply(ctx || this, args);
       }
    }

    function pushd(directory) {
        directories.push(process.cwd());
        process.chdir(directory);
    }

    function popd() {
        return directories.pop();
    }

    function directive(value) {
        var parts = typeof value === 'string' && value.match(/^<(.*)>$/),
            directive = parts && (parts = parts[1].split(':')) && directives[parts[0]];

        return directive && directive.apply(this, parts.shift() && parts) || value;
    }

    function msg(str, type) {
        return '[' + (LogEnum[type] || LogEnum.INFO) + '] ' + (running && running.name + ': ' || '') + str;
    }

    function errorMsg(str) {
        return msg(str, LogEnum.ERROR).red;
    }

    function bower(component, options) {
        var config = require(__dirname + '/../node_modules/bower/lib/core/config'),
            vendor = process.jetfuel.config.bower.vendor,
            dependencies = vendor.dependencies,
            commands = component.commands,
            command = args[0],
            subargs = args.splice(1),
            nowrite = false,
            hooks = {
                install:    curry(writeDependencies),
                uninstall:  curry(writeDependencies, [true])
            };

        function writeDependencies(uninstall) {
            if(nowrite) return;
            subargs.forEach(uninstall && removeDependency || addDependency);
            fs.writeFileSync(vendor[SRC_FILE], JSON.stringify(remove(SRC_FILE, require(components.grunt.require).utils._.extend({}, vendor)), null, JSON_SPACES));
        }

        function addDependency(dependency) {
            dependency = dependency.split('#');
            dependencies[dependency[0]] = dependency[1] || BOWER_LATEST;
        }

        function removeDependency(dependency) {
            remove(dependency.split('#')[0], dependencies);
        }

        function remove(k, o) {
            o[k] = undefined;
            delete o[k];
            return o;
        }

        function log(data, type) { data && util[type == LogEnum.ERROR ? 'error' : 'puts'](data); }

        config.directory = vendor.directory || DEFAULT_BOWER_DIR;

        if(command == 'uninstall') hooks[command] && hooks[command]();
        else if(command == 'install' && !subargs.length) {
            for(var dependency in vendor.dependencies) {
                subargs.push([dependency, vendor.dependencies[dependency] || BOWER_LATEST].join('#'));
                nowrite = true;
            }
        }

        try {
            (commands[command] || commands[DEFAULT_BOWER_COMMAND]).apply(component, [subargs, {}])
                .on('data',  log)
                .on('end', function(data) {
                    hooks[command] && hooks[command]();
                    log(data);
                    done();
                })
                .on('error', function(data) {
                    log(data, LogEnum.ERROR);
                    die();
                });
        } catch(e) {
            util.error(e);
            die();
        }
    }

    function begin(component) {
        running = component;
    }

    function done(code) {
        code = code || 0;
        running = null;
        if(code === 0) util.puts(IndicatorsEnum.SUCCESS.green + ' Done.');
        else util.error(IndicatorsEnum.FAILURE + ' Done.');
        process.exit(code);
    }

    function setLogging() {
        var write = process.stdout.write.bind(process.stdout),
            error = process.stderr.write.bind(process.stderr);

        process.stdout.write = function(str) { return write(msg(str)); };
        process.stderr.write = function(str) { return error(errorMsg(str)); };
    }

    function grunt(component, options) {
        !options.args.facade && component.cli.tasks.shift();

        pushd(__dirname + '/..');

        options.config.npmTasks.forEach(function(task) {
            component.loadNpmTasks(task);
        });

        popd();

        component.cli({ config: __dirname + '/' + GRUNT_FILE }, options.done);
    }

    function setup() {
        var jwd = path.resolve(path.dirname(require('./util').findup('.', JETFUEL_FILE))),
            jetfuel = process.jetfuel = process.jetfuel || {
                config: {},
                components: {},
                env: {
                    PATH: jwd,
                    FILE: JETFUEL_FILE
                }
            },

            jConfig, cmpConfig;

        process.chdir(jwd);

        if(!fs.existsSync(JETFUEL_FILE)) {
            util.error('Missing ' + JETFUEL_FILE + ' project configuration file.');
            done(ERROR_CONFIG_NOT_FOUND);
        }

        for(var cmp in (jConfig = jetfuel.config = readJSON(JETFUEL_FILE))) {
            if(typeof jConfig[cmp] === 'object') {
                for(var value in (cmpConfig = jConfig[cmp])) {
                    cmpConfig[value] = directive(cmpConfig[value]);
                }
            }
        }
    }

    function load(component, args) {
        component = components[component];

        setup();

        try {

            component.loaded = require(component.require);

        } catch(e) {

            util.error(e);
            process.exit(ERROR_DEP_NOT_FOUND);

        }

        util.puts('Running ' + component.name.bold + '...');

        begin(component);

        component.onLoad && component.onLoad(component.loaded, {
            done: component.onComplete,
            name: component.name,
            config: component.config || {},
            args: args || {}
        });
    }

    module.exports = function() {
        setLogging();
        return (cli[process.argv[2]] || jetfuel)(args = process.argv.slice(3));
    };

})(undefined);<commit_msg>Make jetfuel install/uninstall a facade for bower<commit_after>(function(undefined) {
    'use strict';

    var ERROR_CONFIG_NOT_FOUND  = 2,
        ERROR_DEP_NOT_FOUND     = 3,
        JSON_SPACES             = 4,
        ENOENT                  = 'ENOENT',
        DEFAULT_BOWER_COMMAND   = 'help',
        DEFAULT_BOWER_DIR       = 'vendor',
        SRC_FILE                = '_source',
        GRUNT_FILE              = 'grunt.js',
        JETFUEL_FILE            = '.jetfuel.json',
        BOWER_LATEST            = '*';

    var util = require('util'),
        fs = require('fs'),
        path = require('path'),
        color = require('colors'),
        readJSON = require('./util').readJSON,
        //info = readJSON(__dirname + '/../package.json'),
        directories = [],
        die = curry(done, [1]),
        running = null,
        args,

        IndicatorsEnum = {
            SUCCESS:    '✓',
            FAILURE:    '✕'
        },

        LogEnum = {
            INFO:       'INFO',
            ERROR:      'ERROR',
            DEBUG:      'DEBUG',
            WARNING:    'WARNING'
        },

        components = {

            grunt: {
                name: 'Grunt',
                loaded: null,
                require: 'grunt',
                onLoad: grunt,
                onComplete: done,
                config: {
                    npmTasks: ['jetfuel-grunt-tasks']
                }
            },

            bower: {
                name: 'Bower',
                loaded: null,
                require: 'bower',
                onLoad: bower
            }

        },

        cli = {

            "--version": function() {
                util.puts('Version: ' + require('./version').call().bold);
                done();
            },

            init: function() {
                var init = require('./init');
                init.done = done;
                init.apply(init, args);
            },

            grunt:      curry(load, [components.grunt.require]),
            bower:      curry(load, [components.bower.require]),
            install:    curry(load, [components.bower.require, { command: 'install' }]),
            uninstall:    curry(load, [components.bower.require, { command: 'uninstall' }])

        },

        directives = {

            json: function(file) {
                var data = fs.existsSync(file) && readJSON(file) || {};
                data[SRC_FILE] = file;
                return data;
            }

        };

    function jetfuel() {
        load(components.grunt.require, { facade: true });
    }

    function curry(fn, args, ctx) {
       return function() {
         return fn.apply(ctx || this, args);
       }
    }

    function pushd(directory) {
        directories.push(process.cwd());
        process.chdir(directory);
    }

    function popd() {
        return directories.pop();
    }

    function directive(value) {
        var parts = typeof value === 'string' && value.match(/^<(.*)>$/),
            directive = parts && (parts = parts[1].split(':')) && directives[parts[0]];

        return directive && directive.apply(this, parts.shift() && parts) || value;
    }

    function msg(str, type) {
        return '[' + (LogEnum[type] || LogEnum.INFO) + '] ' + (running && running.name + ': ' || '') + str;
    }

    function errorMsg(str) {
        return msg(str, LogEnum.ERROR).red;
    }

    function begin(component) {
        running = component;
    }

    function done(code) {
        code = code || 0;
        running = null;
        if(code === 0) util.puts(IndicatorsEnum.SUCCESS.green + ' Done.');
        else util.error(IndicatorsEnum.FAILURE + ' Done.');
        process.exit(code);
    }

    function setLogging() {
        var write = process.stdout.write.bind(process.stdout),
            error = process.stderr.write.bind(process.stderr);

        process.stdout.write = function(str) { return write(msg(str)); };
        process.stderr.write = function(str) { return error(errorMsg(str)); };
    }

    function bower(component, options) {
        options.args.command && args.unshift(options.args.command);

        var config = require(__dirname + '/../node_modules/bower/lib/core/config'),
            vendor = process.jetfuel.config.bower.vendor,
            dependencies = vendor.dependencies,
            commands = component.commands,
            command = args[0],
            subargs = args.splice(1),
            nowrite = false,
            hooks = {
                install:    curry(writeDependencies),
                uninstall:  curry(writeDependencies, [true])
            };

        function writeDependencies(uninstall) {
            if(nowrite) return;
            subargs.forEach(uninstall && removeDependency || addDependency);
            fs.writeFileSync(vendor[SRC_FILE], JSON.stringify(remove(SRC_FILE, require(components.grunt.require).utils._.extend({}, vendor)), null, JSON_SPACES));
        }

        function addDependency(dependency) {
            dependency = dependency.split('#');
            dependencies[dependency[0]] = dependency[1] || BOWER_LATEST;
        }

        function removeDependency(dependency) {
            remove(dependency.split('#')[0], dependencies);
        }

        function remove(k, o) {
            o[k] = undefined;
            delete o[k];
            return o;
        }

        function log(data, type) { data && util[type == LogEnum.ERROR ? 'error' : 'puts'](data); }

        config.directory = vendor.directory || DEFAULT_BOWER_DIR;

        if(command == 'uninstall') hooks[command] && hooks[command]();
        else if(command == 'install' && !subargs.length) {
            for(var dependency in vendor.dependencies) {
                subargs.push([dependency, vendor.dependencies[dependency] || BOWER_LATEST].join('#'));
                nowrite = true;
            }
        }

        try {
            (commands[command] || commands[DEFAULT_BOWER_COMMAND]).apply(component, [subargs, {}])
                .on('data',  log)
                .on('end', function(data) {
                    hooks[command] && hooks[command]();
                    log(data);
                    done();
                })
                .on('error', function(data) {
                    log(data, LogEnum.ERROR);
                    die();
                });
        } catch(e) {
            util.error(e);
            die();
        }
    }

    function grunt(component, options) {
        !options.args.facade && component.cli.tasks.shift();

        pushd(__dirname + '/..');

        options.config.npmTasks.forEach(function(task) {
            component.loadNpmTasks(task);
        });

        popd();

        component.cli({ config: __dirname + '/' + GRUNT_FILE }, options.done);
    }

    function setup() {
        var jwd = path.resolve(path.dirname(require('./util').findup('.', JETFUEL_FILE))),
            jetfuel = process.jetfuel = process.jetfuel || {
                config: {},
                components: {},
                env: {
                    PATH: jwd,
                    FILE: JETFUEL_FILE
                }
            },

            jConfig, cmpConfig;

        process.chdir(jwd);

        if(!fs.existsSync(JETFUEL_FILE)) {
            util.error('Missing ' + JETFUEL_FILE + ' project configuration file.');
            done(ERROR_CONFIG_NOT_FOUND);
        }

        for(var cmp in (jConfig = jetfuel.config = readJSON(JETFUEL_FILE))) {
            if(typeof jConfig[cmp] === 'object') {
                for(var value in (cmpConfig = jConfig[cmp])) {
                    cmpConfig[value] = directive(cmpConfig[value]);
                }
            }
        }
    }

    function load(component, args) {
        component = components[component];

        setup();

        try {

            component.loaded = require(component.require);

        } catch(e) {

            util.error(e);
            process.exit(ERROR_DEP_NOT_FOUND);

        }

        util.puts('Running ' + component.name.bold + '...');

        begin(component);

        component.onLoad && component.onLoad(component.loaded, {
            done: component.onComplete,
            name: component.name,
            config: component.config || {},
            args: args || {}
        });
    }

    module.exports = function() {
        setLogging();
        return (cli[process.argv[2]] || jetfuel)(args = process.argv.slice(3));
    };

})(undefined);<|endoftext|>


<commit_before>var program = require('commander');
var prompt = require('prompt');

var promptSchema = require('./promptSchema/config');
var pkg = require('../package.json');
var actions = require('./actions');
var logger = require('./logger');

program
  .version(pkg.version);

// program: init
program
  .command('init [dir]')
  .description('wp init [dir]')
  .action(function(dir) {
    // prompt for user inputs
    prompt.start();
    prompt.get(promptSchema, function (err, config) {
      if (err) {
        logger.error(`${err.name}: ${err.message}`);
        return;
      }
      actions.config.init(dir, config);
    });
  });

// program: config
program
  .command('config <opt> <key> <val>')
  .description('wp config update <key> <val>')
  .action(function(opt, key, val) {
    switch (opt) {
      case 'update':
        actions.config.update(key, val);
        break;
      default:
        logger.error('\r\n  error: missing option flag `update`\r\n');
        break;
    }
});

// program: plugin
program
  .command('plugin <opt> <pluginName>')
  .description('wp plugin <opt> <pluginName>@<pluginVersion>')
  .action(function(opt, pluginName) {
    switch (opt) {
      case 'add':
        actions.plugin.add(pluginName);
        break;
      case 'remove':
        actions.plugin.remove(pluginName);
        break;
      default:
        logger.error(`Invalid command input!: ${opt}`);
        break;
    }
});

// program: serve
program
  .command('serve')
  .description('wp serve')
  .action(function() {
    actions.server.start();
  });

// program: [anything else]
program
  .command('*')
  .action(function(env) {
    logger.error(`Invalid command input!: ${env}`);
  });

program.parse(process.argv);
<commit_msg>Add program: template init<commit_after>var program = require('commander');
var prompt = require('prompt');

var promptSchema = require('./promptSchema/config');
var pkg = require('../package.json');
var actions = require('./actions');
var logger = require('./logger');

program
  .version(pkg.version);

// program: init
program
  .command('init [dir]')
  .description('wp init [dir]')
  .action(function(dir) {
    // prompt for user inputs
    prompt.start();
    prompt.get(promptSchema, function (err, config) {
      if (err) {
        logger.error(`${err.name}: ${err.message}`);
        return;
      }
      actions.config.init(dir, config);
    });
  });

// program: config
program
  .command('config <opt> <key> <val>')
  .description('wp config update <key> <val>')
  .action(function(opt, key, val) {
    switch (opt) {
      case 'update':
        actions.config.update(key, val);
        break;
      default:
        logger.error('\r\n  error: missing option flag `update`\r\n');
        break;
    }
});

// program: plugin
program
  .command('plugin <opt> <pluginName>')
  .description('wp plugin <opt> <pluginName>@<pluginVersion>')
  .action(function(opt, pluginName) {
    switch (opt) {
      case 'add':
        actions.plugin.add(pluginName);
        break;
      case 'remove':
        actions.plugin.remove(pluginName);
        break;
      default:
        logger.error(`Invalid command input!: ${opt}`);
        break;
    }
});

// program: template
program
  .command('template <opt>')
  .description('wp template <opt>')
  .action(function(opt) {
    switch (opt) {
      case 'init':
        actions.template.init();
        break;
      default:
        logger.error(`Invalid command input!: ${opt}`);
        break;
    }
});

// program: serve
program
  .command('serve')
  .description('wp serve')
  .action(function() {
    actions.server.start();
  });

// program: [anything else]
program
  .command('*')
  .action(function(env) {
    logger.error(`Invalid command input!: ${env}`);
  });

program.parse(process.argv);
<|endoftext|>


<commit_before>/* eslint-disable no-console, no-sync */
import fs from "fs-extra";
import path from "path";
import spawn from "cross-spawn";
import yargs from "yargs";

process.on("unhandledRejection", err => {
  throw err;
});

const argv = yargs
  .version()
  .usage("Usage: $0 <project-directory>")
  .option("verbose", {
    type: "boolean",
    describe: "Show more details",
    default: false
  })
  .alias("help", "h")
  .alias("version", "v")
  .help()
  .example(
    "$0 todo-app",
    'Create "todo-app" project relative to current directory'
  )
  .strict().argv;
const projectDirectory = argv._[0];

const dependencies = [
  "apollo-client@2.3.8",
  "config@2.0.1",
  "express@4.16.3",
  "graphql@14.0.2",
  "next@7.0.0",
  "prop-types@15.6.2",
  "react@16.5.2",
  "react-apollo@2.2.1",
  "react-cookie@2.2.0",
  "react-dom@16.5.2",
  "react-redux@5.0.7",
  "redux@4.0.0",
  "soya-next@0.7.0",
  "soya-next-server@0.7.0"
];

const devDependencies = ["soya-next-scripts@0.7.0"];

const install = (cmd, dependencies, { dev = false, exact = true } = {}) => {
  const args = [];
  if (cmd === "yarn") {
    args.push("add");
  } else {
    args.push("install");
  }
  if (dev) args.push("-D"); // eslint-disable-line curly
  if (exact) args.push("-E"); // eslint-disable-line curly
  args.push(...dependencies);
  if (argv.verbose) {
    args.push("--verbose");
  }
  const { status } = spawn.sync(cmd, args, { stdio: "inherit" });
  if (status !== 0) {
    process.exit(status);
  }
};

if (projectDirectory) {
  const root = path.resolve(projectDirectory);
  const name = path.basename(root);
  const cwd = process.cwd();

  console.log(`Creating ${name} in ${root}.`);
  console.log();

  fs.ensureDirSync(projectDirectory);
  fs
    .copy(path.resolve(__dirname, "../templates"), root, { overwrite: false })
    .then(async () => {
      try {
        await fs.move(
          path.join(root, "gitignore"),
          path.join(root, ".gitignore")
        );
      } catch (err) {
        if (err.code === "EEXIST") {
          fs.unlink(path.join(root, "gitignore"));
        } else {
          throw err;
        }
      }
    });
  fs.writeJsonSync(
    path.join(root, "package.json"),
    {
      name,
      version: "1.0.0",
      license: "MIT",
      scripts: {
        analyze: "BUNDLE_ANALYZE=both soya-next-scripts build",
        "analyze:browser": "BUNDLE_ANALYZE=browser soya-next-scripts build",
        "analyze:server": "BUNDLE_ANALYZE=server soya-next-scripts build",
        build: "soya-next-scripts build",
        dev: "soya-next-scripts dev",
        eject: "soya-next-scripts eject",
        export: "soya-next-scripts export",
        start: "soya-next-server",
        test: "soya-next-scripts test"
      }
    },
    { spaces: 2 }
  );

  process.chdir(root);

  const { status } = spawn.sync("which", ["yarn"], { stdio: "ignore" });
  const cmd = status === 0 ? "yarn" : "npm";

  console.log("Installing dependencies.");
  console.log();

  install(cmd, dependencies);

  console.log();
  console.log("Installing dev dependencies.");
  console.log();

  install(cmd, devDependencies, { dev: true });

  console.log();
  console.log(`Successfully created ${name} in ${root}.`);
  console.log("Run the following commands to start the app:");
  console.log();
  let target;
  if (path.isAbsolute(projectDirectory)) {
    target = root;
  } else {
    target = path.relative(cwd, root);
  }
  if (target !== "") {
    console.log(`  cd ${target}`);
  }
  console.log(`  ${cmd} dev`);
  console.log();
} else {
  yargs.showHelp();
}
<commit_msg>fix(soya-next-cli): bump soya-next-scripts version<commit_after>/* eslint-disable no-console, no-sync */
import fs from "fs-extra";
import path from "path";
import spawn from "cross-spawn";
import yargs from "yargs";

process.on("unhandledRejection", err => {
  throw err;
});

const argv = yargs
  .version()
  .usage("Usage: $0 <project-directory>")
  .option("verbose", {
    type: "boolean",
    describe: "Show more details",
    default: false
  })
  .alias("help", "h")
  .alias("version", "v")
  .help()
  .example(
    "$0 todo-app",
    'Create "todo-app" project relative to current directory'
  )
  .strict().argv;
const projectDirectory = argv._[0];

const dependencies = [
  "apollo-client@2.3.8",
  "config@2.0.1",
  "express@4.16.3",
  "graphql@14.0.2",
  "next@7.0.0",
  "prop-types@15.6.2",
  "react@16.5.2",
  "react-apollo@2.2.1",
  "react-cookie@2.2.0",
  "react-dom@16.5.2",
  "react-redux@5.0.7",
  "redux@4.0.0",
  "soya-next@0.7.0",
  "soya-next-server@0.7.0"
];

const devDependencies = ["soya-next-scripts@0.7.1"];

const install = (cmd, dependencies, { dev = false, exact = true } = {}) => {
  const args = [];
  if (cmd === "yarn") {
    args.push("add");
  } else {
    args.push("install");
  }
  if (dev) args.push("-D"); // eslint-disable-line curly
  if (exact) args.push("-E"); // eslint-disable-line curly
  args.push(...dependencies);
  if (argv.verbose) {
    args.push("--verbose");
  }
  const { status } = spawn.sync(cmd, args, { stdio: "inherit" });
  if (status !== 0) {
    process.exit(status);
  }
};

if (projectDirectory) {
  const root = path.resolve(projectDirectory);
  const name = path.basename(root);
  const cwd = process.cwd();

  console.log(`Creating ${name} in ${root}.`);
  console.log();

  fs.ensureDirSync(projectDirectory);
  fs
    .copy(path.resolve(__dirname, "../templates"), root, { overwrite: false })
    .then(async () => {
      try {
        await fs.move(
          path.join(root, "gitignore"),
          path.join(root, ".gitignore")
        );
      } catch (err) {
        if (err.code === "EEXIST") {
          fs.unlink(path.join(root, "gitignore"));
        } else {
          throw err;
        }
      }
    });
  fs.writeJsonSync(
    path.join(root, "package.json"),
    {
      name,
      version: "1.0.0",
      license: "MIT",
      scripts: {
        analyze: "BUNDLE_ANALYZE=both soya-next-scripts build",
        "analyze:browser": "BUNDLE_ANALYZE=browser soya-next-scripts build",
        "analyze:server": "BUNDLE_ANALYZE=server soya-next-scripts build",
        build: "soya-next-scripts build",
        dev: "soya-next-scripts dev",
        eject: "soya-next-scripts eject",
        export: "soya-next-scripts export",
        start: "soya-next-server",
        test: "soya-next-scripts test"
      }
    },
    { spaces: 2 }
  );

  process.chdir(root);

  const { status } = spawn.sync("which", ["yarn"], { stdio: "ignore" });
  const cmd = status === 0 ? "yarn" : "npm";

  console.log("Installing dependencies.");
  console.log();

  install(cmd, dependencies);

  console.log();
  console.log("Installing dev dependencies.");
  console.log();

  install(cmd, devDependencies, { dev: true });

  console.log();
  console.log(`Successfully created ${name} in ${root}.`);
  console.log("Run the following commands to start the app:");
  console.log();
  let target;
  if (path.isAbsolute(projectDirectory)) {
    target = root;
  } else {
    target = path.relative(cwd, root);
  }
  if (target !== "") {
    console.log(`  cd ${target}`);
  }
  console.log(`  ${cmd} dev`);
  console.log();
} else {
  yargs.showHelp();
}
<|endoftext|>


<commit_before>
// var formInputs = form.childNodes
// console.log(formNodes)

function active_input(event) {
    // console.log(this.type, event.type);
    var input = this.name
    var v = this.value
    var labelElement = document.getElementById(input+'Label')
    switch(event.type) {
        // case 'keydown':
        //     break;
        // case 'keyup':
        //     break;
        case 'focus':
            labelElement.classList.add('active')
            break;
        case 'blur':
            if (this.value == '') {
                labelElement.classList.remove('active')
            }

            break;
    }
}

function addInputListeners() {
    var inputs = document.getElementsByTagName('input'), i=0;
    var textfields = document.getElementsByTagName('textarea'), i=0;
    var fields = []
    fields.push.apply(fields,inputs)
    fields.push.apply(fields,textfields)
    // console.log(fields)
    var events = ['blur', 'focus', 'keydown', 'keyup']

    do {
        switch(fields[i].type){
            case 'password':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'text':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'email':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'file':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'url':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'textarea':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
        }
    }
    while(fields[++i])

}

document.addEventListener("DOMContentLoaded", function(){
    addInputListeners();
});
<commit_msg>Js clean up<commit_after>
function active_input(event) {
    var input = this.name
    var v = this.value
    var labelElement = document.getElementById(input+'Label')
    switch(event.type) {
        // case 'keydown':
        //     break;
        // case 'keyup':
        //     break;
        case 'focus':
            labelElement.classList.add('active')
            break;
        case 'blur':
            if (this.value == '') {
                labelElement.classList.remove('active')
            }

            break;
    }
}

function addInputListeners() {
    var inputs = document.getElementsByTagName('input'), i=0;
    var textfields = document.getElementsByTagName('textarea'), i=0;
    var fields = []
    fields.push.apply(fields,inputs)
    fields.push.apply(fields,textfields)
    var events = ['blur', 'focus', 'keydown', 'keyup']

    do {
        switch(fields[i].type){
            case 'password':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'text':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'email':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'file':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'url':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
            case 'textarea':
                events.forEach(function(event){
                    fields[i].addEventListener(event, active_input, false);
                });
                break;
        }
    }
    while(fields[++i])

}

document.addEventListener("DOMContentLoaded", function(){
    addInputListeners();
});
<|endoftext|>


<commit_before>(function(){var n,e,t,r,o,a,u,i,c,l;e=require("fs-extra"),l=require("path"),n=require("commander-b"),c=require("moment"),t=function(){var t;return t=n("bbn"),t.version(require("../package.json").version),t.command("new","create a new post").option("-d, --date <date>").option("-w, --weekend").action(function(n){var t,u,i,l,s;return null==n&&(n={}),t=r(),n.directory=t.directory||"/home/bouzuya/blog.bouzuya.net",s=n.date?n.date+"T23:59:59+09:00":null,i=c.apply(null,null!=s?[s,"YYYY-MM-DDThh:mm:ssZ"]:[]),l=o(n.directory,i.format("YYYY-MM-DD")),e.existsSync(l)?(console.error("the post "+l+" already exists"),1):(u=a(i,n),console.log(l),console.log(u),e.outputFileSync(l,u,{encoding:"utf8"}),console.log("create a new post "+l),0)}),t},r=function(){var n;return n=l.join(process.env.HOME,".bbn.json"),e.existsSync(n)?require(n):{}},o=function(n,e){var t,r,o,a;return o=e.split("-"),a=o[0],r=o[1],t=o[2],l.join(n,"data",a,r,e+"-diary.md")},a=function(n,e){return'---\nlayout: post\npubdate: "'+n.format()+"\"\ntitle: ''\ntags: ['']\nminutes:\npagetype: posts\n---\n\n"+(e.weekend?u(n,e):"")},u=function(n,e){var t;return t=[1,2,3,4,5,6,7].map(function(e){return c(n).subtract(e,"days").format("YYYY-MM-DD")}).map(function(n){return{date:n,title:i(e.directory,n),url:"http://blog.bouzuya.net/"+n.replace(/-/g,"/")+"/"}}),t.map(function(n){return"- ["+n.date+" "+n.title+"]["+n.date+"]"}).join("\n")+"\n\n"+t.map(function(n){return"["+n.date+"]: "+n.url}).join("\n")},i=function(n,t){var r,a;return r=e.readFileSync(o(n,t),{encoding:"utf8"}),a=r.match(/^title: '?(.*)$/m)[1],"'"===a[a.length-1]?a.slice(0,-1):a},module.exports=function(){var n;return n=t(),n.execute()}}).call(this);<commit_msg>remove console.log<commit_after>(function(){var n,e,t,r,o,a,u,i,c,l;e=require("fs-extra"),l=require("path"),n=require("commander-b"),c=require("moment"),t=function(){var t;return t=n("bbn"),t.version(require("../package.json").version),t.command("new","create a new post").option("-d, --date <date>").option("-w, --weekend").action(function(n){var t,u,i,l,s;return null==n&&(n={}),t=r(),n.directory=t.directory||"/home/bouzuya/blog.bouzuya.net",s=n.date?n.date+"T23:59:59+09:00":null,i=c.apply(null,null!=s?[s,"YYYY-MM-DDThh:mm:ssZ"]:[]),l=o(n.directory,i.format("YYYY-MM-DD")),e.existsSync(l)?(console.error("the post "+l+" already exists"),1):(u=a(i,n),e.outputFileSync(l,u,{encoding:"utf8"}),console.log("create a new post "+l),0)}),t},r=function(){var n;return n=l.join(process.env.HOME,".bbn.json"),e.existsSync(n)?require(n):{}},o=function(n,e){var t,r,o,a;return o=e.split("-"),a=o[0],r=o[1],t=o[2],l.join(n,"data",a,r,e+"-diary.md")},a=function(n,e){return'---\nlayout: post\npubdate: "'+n.format()+"\"\ntitle: ''\ntags: ['']\nminutes:\npagetype: posts\n---\n\n"+(e.weekend?u(n,e):"")},u=function(n,e){var t;return t=[1,2,3,4,5,6,7].map(function(e){return c(n).subtract(e,"days").format("YYYY-MM-DD")}).map(function(n){return{date:n,title:i(e.directory,n),url:"http://blog.bouzuya.net/"+n.replace(/-/g,"/")+"/"}}),t.map(function(n){return"- ["+n.date+" "+n.title+"]["+n.date+"]"}).join("\n")+"\n\n"+t.map(function(n){return"["+n.date+"]: "+n.url}).join("\n")},i=function(n,t){var r,a;return r=e.readFileSync(o(n,t),{encoding:"utf8"}),a=r.match(/^title: '?(.*)$/m)[1],"'"===a[a.length-1]?a.slice(0,-1):a},module.exports=function(){var n;return n=t(),n.execute()}}).call(this);<|endoftext|>


<commit_before>import url from "url";
import Swagger from "swagger-client";
import _ from "underscore";
import IO from "socket.io-client";
import EE from "wolfy87-eventemitter";
import jwtDecode from "jwt-decode";
import request from "superagent";

// expose some stuff in our namespace
export * from "sp-utils";
import config from "sp-configuration";
export { config };

import Resource from "./Resource";

const API_SERVER_URL = config.optional("API_SERVER_URL");
const PUBLIC_API_SERVER_URL = config.optional("PUBLIC_API_SERVER_URL");
const DOMAIN = config.optional("DOMAIN");
const SCHEMA_URL = config.optional("SCHEMA_URL");
const PROTOCOL = config.optional("PROTOCOL") || "https";

const IMPORTANT_EVENTS = [
  "hello",
  "connect",
  "connect_error",
  "connect_timeout",
  "reconnect",
  "reconnect_attempt",
  "reconnecting",
  "reconnect_error",
  "reconnect_failed"
];

let isNode = true;
if (typeof window === "object") {
  isNode = false;
}

/**
 * We use HTTP error codes to know how to handle our errors usually, so here's a little helper for
 * that.
 */
const apiError = function(code, message) {
  const err = new Error(message);
  err.status = code;
  return err;
};

export class SPClient extends EE {
  constructor({ server, log, token, app } = {}) {
    super();
    this.app = app || "spclient";
    this.shouldLog = true;
    this.server = server;
    this.token = token;
  }

  connect({ server, log, token } = {}) {
    if (isNode) {
      // Someone teach me a better wneway to have node do something but not webpack.
      /*eslint-disable no-eval */
      const TokenGenerator = eval("require('./TokenGenerator')").default;
      this.tokenGenerator = new TokenGenerator({ app: this.app });
    }
    this.connected = false;
    this.shouldLog = true;
    this.token = token || this.token;
    if (!server) {
      server = this.server;
    }
    if (!server) {
      server = API_SERVER_URL;
    }
    if (!server) {
      server = PUBLIC_API_SERVER_URL;
    }
    if (!server && DOMAIN) {
      server = `${PROTOCOL}://${DOMAIN}`;
    }
    if (!server) {
      throw new Error(
        "Tried to instantate SPClient with no server provided explicitly. API_SERVER_URL and PUBLIC_API_SERVER_URL are also both unset."
      );
    }
    this.server = server;
    // Kill trailing slash if present
    if (this.server.slice(-1) === "/") {
      this.server = this.server.slice(0, this.server.length - 1);
    }
    const schemaUrl = SCHEMA_URL || this.server;
    return request(`${schemaUrl}/schema.json`)
      .then(res => {
        const schema = res.body;
        schema.schemes = [PROTOCOL];
        // If we have API_SERVER_URL, we're in a cluster, and should trust it over the schema
        if (API_SERVER_URL) {
          let { host, path } = url.parse(API_SERVER_URL);
          schema.host = host;
          schema.basePath = path;
        }
        this.schema = schema;

        // Generate a token if we can and we don't have one.
        if (!this.token && this.tokenGenerator) {
          this.token = this.tokenGenerator.generate();
        }
        if (!this.token) {
          return Promise.reject(apiError(401, "No token provided"));
        }

        this.client = new Swagger({
          spec: this.schema
        });
        this.client.buildFromSpec(this.schema);

        this.newToken(this.token);

        // Look at all the resources available in the freshly-parsed schema and build a Resource for
        // each one.
        this.client.apisArray.forEach(api => {
          this[api.name] = new Resource({
            SK: this,
            swaggerResource: this.client[api.name]
          });
        });

        this.client.usePromise = true;

        return this.getUser();
      })
      .then(user => {
        // Set up HTTP connection based on Swagger schema
        const serverURL = `${this.schema.schemes[0]}://${this.schema.host}`;
        this.log(`SPClient initalizing for server ${serverURL}`);

        this.user = user;
        let socketServer = `${serverURL}/`;
        if (this.token) {
          socketServer = `${socketServer}?token=${this.token}`;
        }

        let socketPath = this.schema.basePath + "/socket/socket.io";

        // Set up websocket connection
        this.socket = IO(socketServer, {
          path: socketPath,
          transports: ["websocket"]
        });
        this.socket.on("hello", () => {
          this.connected = true;
          _(this.activeSubscriptions).each(({ resource, query, cb }, subId) => {
            this.log("sub", resource, query);
            this.socket.emit("sub", { subId, resource, query });
          });
        });

        this.socket.on("data", ({ tableName, id, doc }) => {
          if (!this[tableName]) {
            throw new Error(
              `Got data event for ${tableName}, but I dunno what that is.`
            );
          }
          this[tableName]._data(id, doc);
        });

        this.socket.on("suback", ({ subId }) => {
          this.activeSubscriptions[subId] &&
            this.activeSubscriptions[subId].cb();
        });
        this.subscriptionIdx = 0;
        this.activeSubscriptions = {};

        const handler = this._handleMessage.bind(this);
        [
          "hello",
          "suback",
          "created",
          "updated",
          "deleted",
          "connect",
          "connect_error",
          "connect_timeout",
          "reconnect",
          "reconnect_attempt",
          "reconnecting",
          "reconnect_error",
          "reconnect_failed"
        ].forEach(msg => {
          this.socket.on(msg, this._handleMessage(msg));
        });

        this.socket.on("error", ::this._handleError);

        this.emit("ready");
        return this.user;
      })
      .catch(err => {
        this.log(err);
        throw err;
      });
  }

  disconnect() {
    this.socket.close();
  }

  newToken(token) {
    this.token = token;
    this.client.clientAuthorizations.add(
      "SP",
      new Swagger.ApiKeyAuthorization("sp-auth-token", token, "header")
    );
  }

  getUser() {
    const beforeToken = this.token;
    const decoded = jwtDecode(this.token);
    return this.users.find({ identity: decoded.sub }).then(([user]) => {
      // If we didn't find one and our token changed, the server gently let us know we're actually
      // someone else. Try again!
      if (!user) {
        if (this.token !== beforeToken) {
          return this.getUser();
        }
        throw new Error(`Cannot find user with identity="${decoded.sub}"`);
      }
      return user;
    });
  }

  _handleError(err) {
    try {
      err = JSON.parse(err);
    } catch (e) {
      err = new Error(err);
    }
    this.log(err);
    this.emit("error", err);
  }

  _handleMessage(eventName) {
    return (evt = {}) => {
      if (IMPORTANT_EVENTS.includes(eventName)) {
        this.log(`socket ${eventName} ${JSON.stringify({ subId: evt.subId })}`);
      }
      if (evt.subId && this.activeSubscriptions[evt.subId]) {
        this.activeSubscriptions[evt.subId].cb(eventName, evt);
      }
    };
  }

  log(...args) {
    /*eslint-disable no-console */
    if (this.shouldLog && console && console.info) {
      console.info(...args);
    }
  }

  // Couple of shortcuts. Might be complex client-side reporting in the future, who knows?
  info(...args) {
    console.info(...args);
  }

  error(...args) {
    console.info(...args);
  }

  _subscriptionId() {
    const subId = `${this.subscriptionIdx}`;
    this.subscriptionIdx += 1;
    return subId;
  }

  _subscribe(resource, query, cb) {
    const subId = this._subscriptionId();
    this.activeSubscriptions[subId] = { resource, query, cb };
    if (this.connected) {
      this.socket.emit("sub", { subId, resource, query });
    }
    return {
      stop: () => {
        this.socket.emit("unsub", { subId });
        delete this.activeSubscriptions[subId];
      }
    };
  }
}

const SP = new SPClient({});

if (!isNode) {
  window.SP = SP;
}

export default SP;
<commit_msg>only use TokenGenerator if no token<commit_after>import url from "url";
import Swagger from "swagger-client";
import _ from "underscore";
import IO from "socket.io-client";
import EE from "wolfy87-eventemitter";
import jwtDecode from "jwt-decode";
import request from "superagent";

// expose some stuff in our namespace
export * from "sp-utils";
import config from "sp-configuration";
export { config };

import Resource from "./Resource";

const API_SERVER_URL = config.optional("API_SERVER_URL");
const PUBLIC_API_SERVER_URL = config.optional("PUBLIC_API_SERVER_URL");
const DOMAIN = config.optional("DOMAIN");
const SCHEMA_URL = config.optional("SCHEMA_URL");
const PROTOCOL = config.optional("PROTOCOL") || "https";

const IMPORTANT_EVENTS = [
  "hello",
  "connect",
  "connect_error",
  "connect_timeout",
  "reconnect",
  "reconnect_attempt",
  "reconnecting",
  "reconnect_error",
  "reconnect_failed"
];

let isNode = true;
if (typeof window === "object") {
  isNode = false;
}

/**
 * We use HTTP error codes to know how to handle our errors usually, so here's a little helper for
 * that.
 */
const apiError = function(code, message) {
  const err = new Error(message);
  err.status = code;
  return err;
};

export class SPClient extends EE {
  constructor({ server, log, token, app } = {}) {
    super();
    this.app = app || "spclient";
    this.shouldLog = true;
    this.server = server;
    this.token = token;
  }

  connect({ server, log, token } = {}) {
    if (!token && isNode) {
      // Someone teach me a better wneway to have node do something but not webpack.
      /*eslint-disable no-eval */
      const TokenGenerator = eval("require('./TokenGenerator')").default;
      this.tokenGenerator = new TokenGenerator({ app: this.app });
    }
    this.connected = false;
    this.shouldLog = true;
    this.token = token || this.token;
    if (!server) {
      server = this.server;
    }
    if (!server) {
      server = API_SERVER_URL;
    }
    if (!server) {
      server = PUBLIC_API_SERVER_URL;
    }
    if (!server && DOMAIN) {
      server = `${PROTOCOL}://${DOMAIN}`;
    }
    if (!server) {
      throw new Error(
        "Tried to instantate SPClient with no server provided explicitly. API_SERVER_URL and PUBLIC_API_SERVER_URL are also both unset."
      );
    }
    this.server = server;
    // Kill trailing slash if present
    if (this.server.slice(-1) === "/") {
      this.server = this.server.slice(0, this.server.length - 1);
    }
    const schemaUrl = SCHEMA_URL || this.server;
    return request(`${schemaUrl}/schema.json`)
      .then(res => {
        const schema = res.body;
        schema.schemes = [PROTOCOL];
        // If we have API_SERVER_URL, we're in a cluster, and should trust it over the schema
        if (API_SERVER_URL) {
          let { host, path } = url.parse(API_SERVER_URL);
          schema.host = host;
          schema.basePath = path;
        }
        this.schema = schema;

        // Generate a token if we can and we don't have one.
        if (!this.token && this.tokenGenerator) {
          this.token = this.tokenGenerator.generate();
        }
        if (!this.token) {
          return Promise.reject(apiError(401, "No token provided"));
        }

        this.client = new Swagger({
          spec: this.schema
        });
        this.client.buildFromSpec(this.schema);

        this.newToken(this.token);

        // Look at all the resources available in the freshly-parsed schema and build a Resource for
        // each one.
        this.client.apisArray.forEach(api => {
          this[api.name] = new Resource({
            SK: this,
            swaggerResource: this.client[api.name]
          });
        });

        this.client.usePromise = true;

        return this.getUser();
      })
      .then(user => {
        // Set up HTTP connection based on Swagger schema
        const serverURL = `${this.schema.schemes[0]}://${this.schema.host}`;
        this.log(`SPClient initalizing for server ${serverURL}`);

        this.user = user;
        let socketServer = `${serverURL}/`;
        if (this.token) {
          socketServer = `${socketServer}?token=${this.token}`;
        }

        let socketPath = this.schema.basePath + "/socket/socket.io";

        // Set up websocket connection
        this.socket = IO(socketServer, {
          path: socketPath,
          transports: ["websocket"]
        });
        this.socket.on("hello", () => {
          this.connected = true;
          _(this.activeSubscriptions).each(({ resource, query, cb }, subId) => {
            this.log("sub", resource, query);
            this.socket.emit("sub", { subId, resource, query });
          });
        });

        this.socket.on("data", ({ tableName, id, doc }) => {
          if (!this[tableName]) {
            throw new Error(
              `Got data event for ${tableName}, but I dunno what that is.`
            );
          }
          this[tableName]._data(id, doc);
        });

        this.socket.on("suback", ({ subId }) => {
          this.activeSubscriptions[subId] &&
            this.activeSubscriptions[subId].cb();
        });
        this.subscriptionIdx = 0;
        this.activeSubscriptions = {};

        const handler = this._handleMessage.bind(this);
        [
          "hello",
          "suback",
          "created",
          "updated",
          "deleted",
          "connect",
          "connect_error",
          "connect_timeout",
          "reconnect",
          "reconnect_attempt",
          "reconnecting",
          "reconnect_error",
          "reconnect_failed"
        ].forEach(msg => {
          this.socket.on(msg, this._handleMessage(msg));
        });

        this.socket.on("error", ::this._handleError);

        this.emit("ready");
        return this.user;
      })
      .catch(err => {
        this.log(err);
        throw err;
      });
  }

  disconnect() {
    this.socket.close();
  }

  newToken(token) {
    this.token = token;
    this.client.clientAuthorizations.add(
      "SP",
      new Swagger.ApiKeyAuthorization("sp-auth-token", token, "header")
    );
  }

  getUser() {
    const beforeToken = this.token;
    const decoded = jwtDecode(this.token);
    return this.users.find({ identity: decoded.sub }).then(([user]) => {
      // If we didn't find one and our token changed, the server gently let us know we're actually
      // someone else. Try again!
      if (!user) {
        if (this.token !== beforeToken) {
          return this.getUser();
        }
        throw new Error(`Cannot find user with identity="${decoded.sub}"`);
      }
      return user;
    });
  }

  _handleError(err) {
    try {
      err = JSON.parse(err);
    } catch (e) {
      err = new Error(err);
    }
    this.log(err);
    this.emit("error", err);
  }

  _handleMessage(eventName) {
    return (evt = {}) => {
      if (IMPORTANT_EVENTS.includes(eventName)) {
        this.log(`socket ${eventName} ${JSON.stringify({ subId: evt.subId })}`);
      }
      if (evt.subId && this.activeSubscriptions[evt.subId]) {
        this.activeSubscriptions[evt.subId].cb(eventName, evt);
      }
    };
  }

  log(...args) {
    /*eslint-disable no-console */
    if (this.shouldLog && console && console.info) {
      console.info(...args);
    }
  }

  // Couple of shortcuts. Might be complex client-side reporting in the future, who knows?
  info(...args) {
    console.info(...args);
  }

  error(...args) {
    console.info(...args);
  }

  _subscriptionId() {
    const subId = `${this.subscriptionIdx}`;
    this.subscriptionIdx += 1;
    return subId;
  }

  _subscribe(resource, query, cb) {
    const subId = this._subscriptionId();
    this.activeSubscriptions[subId] = { resource, query, cb };
    if (this.connected) {
      this.socket.emit("sub", { subId, resource, query });
    }
    return {
      stop: () => {
        this.socket.emit("unsub", { subId });
        delete this.activeSubscriptions[subId];
      }
    };
  }
}

const SP = new SPClient({});

if (!isNode) {
  window.SP = SP;
}

export default SP;
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*globals $, FB, gapi, StackTrace, FacebookAppId, fbLogin, setSettings*/
"use strict";
function get(name) {
    var name2 = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search);
    if (name2) {
        return decodeURIComponent(name2[1]);
    }
    return "";
}

function sendLogError(msg) {
    $.ajax({url: '/logerror',
            data: { 'location': window.location.href, 'error': msg },
           });
}

function logError(error) {
    var message =
        "Error: " + error + "\r\n\r\n" +
        "Stack: ",
        callback,
        errback;

    callback = function (stackframes) {
        var stringifiedStack = stackframes.map(function (sf) {
            return sf.toString();
        }).join('\n');
        message = message + stringifiedStack;
        sendLogError(message);
    };
    errback = function (err) {
        message = message + err.message;
        sendLogError(message);
    };
    StackTrace.get().then(callback, errback);
}

function gGetEmail(resp) {
    if (resp.result.emails.length === 0) {
        console.log("gRentRollCallback - error no email!");
        return '';
    }
    return resp.result.emails[0].value;
}

function gGetName(resp) {
    if (resp.result.emails.length === 0) {
        console.log("gRentRollCallback - error no email!");
        logError("gRentRollCallback - error no email!");
        return '';
    }
    return resp.result.displayName;
}

function executeCallback(name, response, logerror) {
    var callback = document.getElementById(name),
        callbackAttr = null,
        callbackName = null,
        errorMsg = '';
    if (callback === null) {
        console.log('executeCallback - ERROR NO CALLBACK: ' + name);
        if (logerror === true) {
            logError('executeCallback - ERROR NO CALLBACK: ' + name);
        }
        return;
    }
    callbackAttr = callback.attributes.callback;
    if (callbackAttr === undefined) {
        console.log('executeCallback - ERROR NO CALLBACK: ' + name);
        if (logerror === true) {
            logError('executeCallback - ERROR NO CALLBACK: ' + name);
        }
        return;
    }
    callbackName = callbackAttr.value;
    if (callbackName === undefined || callbackName === null || callbackName === '') {
        return;
    }
    // call the callback.
    if (window[callbackName] === undefined || window[callbackName] === null) {
        errorMsg =
            'executeCallback - ERROR CALLBACK DOESNT EXIST,' +
            'id name: ' + name + ', ' +
            'callback name: ' + callbackName;
        console.log(errorMsg);
        logError(errorMsg);
        return;
    }
    return window[callbackName](response);
}

function startFBLogin() {
    window.fbAsyncInit = function () {
        FB.init({
            appId      : FacebookAppId,
            xfbml      : true,
            version    : 'v2.3'
        });
        FB.getLoginStatus(function (response) {
            fbLogin(response);
        });
    };
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}

var gSigninFailed = 0;

function gSignin(authResult) {
    if (authResult.status.signed_in) {
        var gSigninButton = document.getElementById('gSigninButton'),
            fbSigninButton = document.getElementById('fbSigninButton'),
            gsettings = document.getElementById('gsettings');
        /*client_id = authResult.client_id, code = authResult.code,access_token = authResult.access_token,*/
        if (gSigninButton !== null) {
            gSigninButton.setAttribute('style', 'display: none');
        }
        if (fbSigninButton !== null) {
            fbSigninButton.setAttribute('style', 'display: none');
        }
        if (gsettings !== null) {
            gsettings.setAttribute('style', 'display: inline');
        }
        gapi.client.load('plus', 'v1').then(function () {
            var request = gapi.client.plus.people.get({
                'userId': 'me'
            });
            request.then(function (resp) {
                var email = "",
                    gSignoutButton = document.getElementById('gSignoutButton');
                if (resp.result.emails.length === 0) {
                    console.log("Error no email!");
                    email = "dummy@dummy.com";
                } else {
                    email = resp.result.emails[0].value;
                }
                if (gSignoutButton !== null) {
                    gSignoutButton.innerHTML = email;
                }
                executeCallback('g-callback', resp, false);
            }, function (reason) {
                console.log('gSignin - Error: ' + reason.result.error.message);
                logError('Error: ' + reason.result.error.message);
            });
        });
    } else {
        // Update the app to reflect a signed out user
        // Possible error values:
        //   "user_signed_out" - User is signed-out
        //   "access_denied" - User denied access to your app
        //   "immediate_failed" - Could not automatically log in the user
        if (gSigninFailed === 0) {
            console.log('Sign-in state: ' + authResult.error);
            startFBLogin();
            gSigninFailed += 1;
        }
    }
}

function fbLogin(response) {
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        document.getElementById('gSigninButton').setAttribute('style', 'display: none');
        var fbsettings = document.getElementById('fbsettings');
        if (fbsettings !== null) {
            fbsettings.setAttribute('style', 'display: inline');
        }
        FB.api('/me', function (response) {
            document.getElementById('fbEmail').innerHTML = response.email;
        });
        executeCallback('fb-callback', response, false);
    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('fbstatus').innerHTML = 'Please log into this app.';
        executeCallback('notloggedin-callback', '', false);
    } else {
        // The person is not logged into Facebook
        executeCallback('notloggedin-callback', '', false);
    }
}

function createAccount(email, loginMethod) {
    if (email === '') {
        console.log("populateRentRoll - empty email!");
        return;
    }
    $.ajax({url: '/createaccount',
            data: { 'email': email, 'loginmethod': loginMethod },
            success: function () {
            window.location.href = '/rentroll';
        }
           });
}

function gSignup(resp) {
    createAccount(gGetEmail(resp), 'Google');
}

function fbSignup() {
    FB.api('/me', function (response) {
        createAccount(response.email, 'Facebook');
    });
}

function gSettings(resp) {
    setSettings(gGetName(resp), gGetEmail(resp));
}

function fbSettings() {
    FB.api('/me', function (response) {
        setSettings(response.name, response.email);
    });

}

function setSettings(name, email) {
    var nameEle = document.getElementById("name"),
        emailEle = document.getElementById("email");
    nameEle.innerHTML = name;
    emailEle.innerHTML = email;
}

function gDummy(resp) {
}

function fbDummy() {
}
<commit_msg>Update facebook js sdk to v2.5<commit_after>/*jslint browser: true*/
/*globals $, FB, gapi, StackTrace, FacebookAppId, fbLogin, setSettings*/
"use strict";
function get(name) {
    var name2 = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search);
    if (name2) {
        return decodeURIComponent(name2[1]);
    }
    return "";
}

function sendLogError(msg) {
    $.ajax({url: '/logerror',
            data: { 'location': window.location.href, 'error': msg },
           });
}

function logError(error) {
    var message =
        "Error: " + error + "\r\n\r\n" +
        "Stack: ",
        callback,
        errback;

    callback = function (stackframes) {
        var stringifiedStack = stackframes.map(function (sf) {
            return sf.toString();
        }).join('\n');
        message = message + stringifiedStack;
        sendLogError(message);
    };
    errback = function (err) {
        message = message + err.message;
        sendLogError(message);
    };
    StackTrace.get().then(callback, errback);
}

function gGetEmail(resp) {
    if (resp.result.emails.length === 0) {
        console.log("gRentRollCallback - error no email!");
        return '';
    }
    return resp.result.emails[0].value;
}

function gGetName(resp) {
    if (resp.result.emails.length === 0) {
        console.log("gRentRollCallback - error no email!");
        logError("gRentRollCallback - error no email!");
        return '';
    }
    return resp.result.displayName;
}

function executeCallback(name, response, logerror) {
    var callback = document.getElementById(name),
        callbackAttr = null,
        callbackName = null,
        errorMsg = '';
    if (callback === null) {
        console.log('executeCallback - ERROR NO CALLBACK: ' + name);
        if (logerror === true) {
            logError('executeCallback - ERROR NO CALLBACK: ' + name);
        }
        return;
    }
    callbackAttr = callback.attributes.callback;
    if (callbackAttr === undefined) {
        console.log('executeCallback - ERROR NO CALLBACK: ' + name);
        if (logerror === true) {
            logError('executeCallback - ERROR NO CALLBACK: ' + name);
        }
        return;
    }
    callbackName = callbackAttr.value;
    if (callbackName === undefined || callbackName === null || callbackName === '') {
        return;
    }
    // call the callback.
    if (window[callbackName] === undefined || window[callbackName] === null) {
        errorMsg =
            'executeCallback - ERROR CALLBACK DOESNT EXIST,' +
            'id name: ' + name + ', ' +
            'callback name: ' + callbackName;
        console.log(errorMsg);
        logError(errorMsg);
        return;
    }
    return window[callbackName](response);
}

function startFBLogin() {
    window.fbAsyncInit = function () {
        FB.init({
            appId      : FacebookAppId,
            xfbml      : true,
            version    : 'v2.5'
        });
        FB.getLoginStatus(function (response) {
            fbLogin(response);
        });
    };
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement(s);
        js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}

var gSigninFailed = 0;

function gSignin(authResult) {
    if (authResult.status.signed_in) {
        var gSigninButton = document.getElementById('gSigninButton'),
            fbSigninButton = document.getElementById('fbSigninButton'),
            gsettings = document.getElementById('gsettings');
        /*client_id = authResult.client_id, code = authResult.code,access_token = authResult.access_token,*/
        if (gSigninButton !== null) {
            gSigninButton.setAttribute('style', 'display: none');
        }
        if (fbSigninButton !== null) {
            fbSigninButton.setAttribute('style', 'display: none');
        }
        if (gsettings !== null) {
            gsettings.setAttribute('style', 'display: inline');
        }
        gapi.client.load('plus', 'v1').then(function () {
            var request = gapi.client.plus.people.get({
                'userId': 'me'
            });
            request.then(function (resp) {
                var email = "",
                    gSignoutButton = document.getElementById('gSignoutButton');
                if (resp.result.emails.length === 0) {
                    console.log("Error no email!");
                    email = "dummy@dummy.com";
                } else {
                    email = resp.result.emails[0].value;
                }
                if (gSignoutButton !== null) {
                    gSignoutButton.innerHTML = email;
                }
                executeCallback('g-callback', resp, false);
            }, function (reason) {
                console.log('gSignin - Error: ' + reason.result.error.message);
                logError('Error: ' + reason.result.error.message);
            });
        });
    } else {
        // Update the app to reflect a signed out user
        // Possible error values:
        //   "user_signed_out" - User is signed-out
        //   "access_denied" - User denied access to your app
        //   "immediate_failed" - Could not automatically log in the user
        if (gSigninFailed === 0) {
            console.log('Sign-in state: ' + authResult.error);
            startFBLogin();
            gSigninFailed += 1;
        }
    }
}

function fbLogin(response) {
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        document.getElementById('gSigninButton').setAttribute('style', 'display: none');
        var fbsettings = document.getElementById('fbsettings');
        if (fbsettings !== null) {
            fbsettings.setAttribute('style', 'display: inline');
        }
        FB.api('/me', function (response) {
            document.getElementById('fbEmail').innerHTML = response.email;
        });
        executeCallback('fb-callback', response, false);
    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('fbstatus').innerHTML = 'Please log into this app.';
        executeCallback('notloggedin-callback', '', false);
    } else {
        // The person is not logged into Facebook
        executeCallback('notloggedin-callback', '', false);
    }
}

function createAccount(email, loginMethod) {
    if (email === '') {
        console.log("populateRentRoll - empty email!");
        return;
    }
    $.ajax({url: '/createaccount',
            data: { 'email': email, 'loginmethod': loginMethod },
            success: function () {
            window.location.href = '/rentroll';
        }
           });
}

function gSignup(resp) {
    createAccount(gGetEmail(resp), 'Google');
}

function fbSignup() {
    FB.api('/me', function (response) {
        createAccount(response.email, 'Facebook');
    });
}

function gSettings(resp) {
    setSettings(gGetName(resp), gGetEmail(resp));
}

function fbSettings() {
    FB.api('/me', function (response) {
        setSettings(response.name, response.email);
    });

}

function setSettings(name, email) {
    var nameEle = document.getElementById("name"),
        emailEle = document.getElementById("email");
    nameEle.innerHTML = name;
    emailEle.innerHTML = email;
}

function gDummy(resp) {
}

function fbDummy() {
}
<|endoftext|>


<commit_before>/**
 * Execute user php function.
 * @package exec-php
 * @version 1.0
 */

var exec = require('child_process').exec,
    fs   = require('fs'),
    path = require('path'),
    tmp  = require('tmp');

/**
 * Execute the script and get the result.
 * @param {string} file, User php file.
 * @param {string} bin, Path to php bin file.
 * @param {string} func, User php function name to call.
 * @param {array} args, List of function array, with the last arg is callback function.
 */
exports.execute = function(file, bin, func, args){
    if(!args || !args.length)
        args = [function(){}];

    if(typeof args[args.length-1] !== 'function')
        args.push(function(){});

    var user_fn_args = args.slice(0, -1),
        user_fn_cb   = args[args.length-1];

    tmp.file(function(error, tmpParam, fd){
        var tmpParamData = {
                'arguments': user_fn_args,
                'file'     : file,
                'function' : func
            };

        tmpParamData = JSON.stringify(tmpParamData);

        fs.writeFileSync(tmpParam, tmpParamData);

        tmp.file(function(error, tmpResult, fds){

            var cli = path.join(__dirname, 'php', 'cli.php'),
                cmd = [bin, cli, '-p' + tmpParam, '-r' + tmpResult].join(' ');

            var opt = {cwd: path.dirname(file)};

            exec(cmd, opt, function(error, stdout, stderr){
                if(error || stderr)
                    return user_fn_cb((error||stderr));

                var data = JSON.parse(fs.readFileSync(tmpResult));

                fs.unlink(tmpParam);
                fs.unlink(tmpResult);

                user_fn_cb(false, data.result, data.output, data.printed);
            });
        });
    });
};<commit_msg>Fixing issue #6<commit_after>/**
 * Execute user php function.
 * @package exec-php
 * @version 1.0
 */

var exec = require('child_process').exec,
    fs   = require('fs'),
    path = require('path'),
    tmp  = require('tmp');

/**
 * Execute the script and get the result.
 * @param {string} file, User php file.
 * @param {string} bin, Path to php bin file.
 * @param {string} func, User php function name to call.
 * @param {array} args, List of function array, with the last arg is callback function.
 */
exports.execute = function(file, bin, func, args){
    if(!args || !args.length)
        args = [function(){}];

    if(typeof args[args.length-1] !== 'function')
        args.push(function(){});

    var user_fn_args = args.slice(0, -1),
        user_fn_cb   = args[args.length-1];

    tmp.file(function(error, tmpParam, fd){
        var tmpParamData = {
                'arguments': user_fn_args,
                'file'     : file,
                'function' : func
            };

        tmpParamData = JSON.stringify(tmpParamData);

        fs.writeFileSync(tmpParam, tmpParamData);

        tmp.file(function(error, tmpResult, fds){

          if (process.platform == "win32")
            var cli = '"' + path.join(__dirname, 'php', 'cli.php') + '"',
                cmd = [bin, cli, '-p' + '"' + tmpParam + '"', '-r' + '"' + tmpResult + '"'].join(' ');
          else
            var cli = path.join(__dirname, 'php', 'cli.php'),
                cmd = [bin, cli.replace(" ", "\\ "), '-p' + tmpParam.replace(" ", "\\ "), '-r' + tmpResult.replace(" ", "\\ ")].join(' ');

            var opt = {cwd: path.dirname(file)};

            exec(cmd, opt, function(error, stdout, stderr){
                if(error || stderr)
                    return user_fn_cb((error||stderr));

                var data = JSON.parse(fs.readFileSync(tmpResult));

                fs.unlink(tmpParam);
                fs.unlink(tmpResult);

                user_fn_cb(false, data.result, data.output, data.printed);
            });
        });
    });
};
<|endoftext|>


<commit_before>/*
hook system

*/
export default class Hooks {
    constructor() {
        // ...

        this.hooks = {
            /*
            table-scroll1:[
                function(){},
                function(){}
            ],
            table-scroll2:[
                function(){},
                function(){}
            ]

            */
        };
    }

    /**
     * Add listener to plugin hooks system.
     *
     * @param {string} hookName The hook name.
     * @param {Function} callback The listener function to add.
     */
    addHook(hookName, callback) {
        let hooks;

        if (!this.hooks[hookName]) {
            this.hooks[hookName] = [];
        }

        hooks = this.hooks[hookName];

        // exclude repeat hook
        let isRepeat = false;
        for (let i = 0; i < hooks.length; i++) {
            if (hooks[i] === callback) {
                isRepeat = true;
                break;
            }
        }

        if (isRepeat) {
            console.warn(`Repeat hook name:${hookName}`);
        } else {
            hooks.push(callback);
        }
    }

    /**
     * Trigger hook.
     *
     * @param {string} hookName The hook name.
     * @param {Argument} args
     */
    triggerHook(hookName) {
        const hooks = this.hooks[hookName];

        const args = Array.prototype.slice.call(arguments);

        if (hooks && hooks.length) {
            hooks.forEach((hook) => {
                //hook(arguments);
                hook.apply(null, args.slice(1));
            });
        } else {
            console.warn(`Can't find hook name:${hookName}`);
        }
    }
}
<commit_msg>Update hooks.js<commit_after>/*
hook system

*/
export default class Hooks {
    constructor() {
        // ...

        this.hooks = {
            /*
            table-scroll1:[
                function(){},
                function(){}
            ],
            table-scroll2:[
                function(){},
                function(){}
            ]

            */
        };
    }

    /**
     * Add listener to plugin hooks system.
     *
     * @param {string} hookName The hook name.
     * @param {Function} callback The listener function to add.
     */
    addHook(hookName, callback) {
        let hooks;

        if (!this.hooks[hookName]) {
            this.hooks[hookName] = [];
        }

        hooks = this.hooks[hookName];

        // exclude repeat hook
        let isRepeat = false;
        for (let i = 0; i < hooks.length; i++) {
            if (hooks[i] === callback) {
                isRepeat = true;
                break;
            }
        }

        if (isRepeat) {
            console.warn(`Repeat hook name:${hookName}`);
        } else {
            hooks.push(callback);
        }
    }

    /**
     * Trigger hook.
     *
     * @param {string} hookName The hook name.
     * @param {Argument} args
     */
    triggerHook(hookName) {
        const hooks = this.hooks[hookName];

        if (hooks && hooks.length) {
            const args = Array.prototype.slice.call(arguments);

            hooks.forEach((hook) => {
                //hook(arguments);
                hook.apply(null, args.slice(1));
            });
        } else {
            console.warn(`Can't find hook name:${hookName}`);
        }
    }
}
<|endoftext|>