/* Helper library to interpret commands as they flow in
Please invoke with a valid Webhook configuration
9141
function CommandInterpreter(config) {
    this.token = config.token;
    if (!this.token) {
        debug("token required, skipping interpreter initialization...");
        return;
    }
    
    // A bot should ignore its own messages by default
    // Only case when this would be set to true is for a developer to test a bot with its personal developer token
    if (typeof this.ignoreSelf != "boolean") {
        this.ignoreSelf = true;
    }

    // No prefix to commands by default
    this.prefix = config.commandPrefix ? config.commandPrefix : "";

    // Bot Mentions should be trimmed by default
    if (typeof this.trimMention != "boolean") {
        this.trimMention = true;
    }
    
    // Let's identify the account type and finalize configuration in there
    this.accountType = "unknown";
	this.person = null;
    var self = this;
	detectAccount(this.token, function(err, account, people) {
        if (err) {
            debug("could not retreive account type, err: " + err + ", continuing...");
            return;
        }

		self.accountType = account;
		self.person = people;

        // Decode account id identifier to better trim mentions (see trimMention)
        var temp = new Buffer(people.id, 'base64');
        self.person.rawId = temp.toString().substring(23);

        // Infer how Webex would generate a nickname for the bot,
        // which is approximate as the nick name would depend on the name of other room members...
        var splitted = people.displayName.split(' ');
	    self.nickName = splitted[0];
	});

}
215890
function cmdHelp(command) {
        let ext = '';
        if (command.args && command.args.length > 0) {
            ext = command.args.join(' ');
        }
        if (ext && helpTopics[ext]) {
            const txt = `Help topic for \`${ext}\`\n\n${helpTopics[ext]}` +
                '\n\nIssue the `help` command without any parameters to see all available commands';
            command.reply(txt);

        } else {
            const help = `${getCommandHelps()}\n\n\\* Help topic available.\n\nIssue the \`help\` command with an ` +
                'available help topic as a parameter to read additonal help';
            command.reply(help);
        }
        return Promise.resolve();
    }
188622
function captureEditorCommand(ed, captureCommandFunc, captureCallFunc) {
  var origCallKeyboardHandlers = ed.keyBinding.$callKeyboardHandlers,
      commandExecHandler = ed.commands.addEventListener('exec', function(e) {
        uninstall();
        e.stopPropagation(); e.preventDefault();
        captureCommandFunc && captureCommandFunc(e.command, e);
        return true;
      });

  var orig = ed.keyBinding.$callKeyboardHandlers;
  ed.keyBinding.$callKeyboardHandlers = function(hashId, keyString, keyCode, e) {
    captureCallFunc && captureCallFunc(hashId, keyString, keyCode, e);
    return orig.call(this, hashId, keyString, keyCode, e);
  };

  return uninstall;

  // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

  function uninstall() {
    commandExecHandler && ed.commands.removeEventListener('exec', commandExecHandler);
    ed.keyBinding.$callKeyboardHandlers = orig;
  }

}
307929
function updateProjectHooks(projectId, hooks, callback) {
        return self.projectCollection.findOne({_id: projectId})
            .then(function (projectData) {
                if (!projectData) {
                    throw new Error('no such project [' + projectId + ']');
                }

                // always update webhook information as a whole to allow remove and create and update as well
                projectData.hooks = hooks;

                return self.projectCollection.updateOne({_id: projectId}, projectData, {upsert: true});
            })
            .then(function () {
                return getProject(projectId);
            })
            .nodeify(callback);
    }
1014142
function RequestHooks_has(regex) {
        if (!Type.isRegExp(regex)) {
            throw new error.DataError({regex: regex}, "RequestHooks.has regex must be regex type");
        }
        return !!this.hooks.filter(function (item) {
            return item.key.source === regex.source;
        }).shift();
    }
551649
function httpOk(req, res, content, fileExt) {
    res.writeHead(200, {
        'Content-Type': Mine.getType(fileExt),
    });
    res.write(content, 'binary');
    res.end();
}
441393
function generateCodeHandlerJs (config) {

	// Read the handler script
	var handler_js = null;
	try {
		// Read from current script
		handler_js = fs.readFileSync(HANDLER_FILENAME).toString();
	} catch (e) {
		// Read from template script
		handler_js = fs.readFileSync(__dirname + '/../templates/' + HANDLER_FILENAME + '.tmpl').toString();
	}

	// Iterate the each commands
	for (var cmd_name in config.commands) {

		if (!cmd_name.match(/^[a-zA-Z][a-zA-Z0-9]+$/)) {
			throw new Error('Defined method name is invalid format: ' + cmd_name);
		}

		if (handler_js.indexOf(cmd_name) != -1) { // handler for this command was written
			continue; // skip
		}

		// Make a handler for this command
		var cmd = config.commands[cmd_name];
		var js_func = '\n\n\
/**\n\
* %cmdDescription%\n\
* @param  {Object} args         Arguments of the received command\n\
* @param  {Function} cb_runner  Callback runner for response\n\
* @return {Boolean} if returns true, handler indicates won\'t use the callback \n\
*/\n\
CommandsHandler.prototype.' + cmd_name + ' = function (args, cb_runner) {\n\
\t\n';

		// To align the line length of argument examples
		var cmd_args = cmd.arguments || cmd.args || [];
		var longest_length_of_arg_name = 0;
		for (var name_ in cmd_args) {
			if (longest_length_of_arg_name < name_.length) longest_length_of_arg_name = name_.length;
		}

		// Generate the argument examples
		for (var name in cmd_args) {

			// Generate an example
			var line = '\tthis.logger.log(args.' + name + ');';

			// Generate a comment
			var comment_spaces = new String(' ');
			for (var i = 0, l = longest_length_of_arg_name - name.length; i < l; i++) {
				comment_spaces += ' ';
			}
			var comment = '// ' + cmd_args[name];

			js_func += line + comment_spaces + comment + '\n';

		}

		if (0 < Object.keys(cmd_args).length) {
			js_func += '\t\n';
		}

		js_func += '\tcb_runner.send(null, \'OKAY\');\n\t\n\};\n';

		// Replace the command placeholders of the commands handler script
		js_func = js_func.replace(/\%cmdName\%/g, cmd_name);
		if (cmd.description) {
			js_func = js_func.replace(/\%cmdDescription\%/g, cmd.description);
		}

		// Done
		handler_js += js_func;

	}

	// Replace the placeholders (e.g. %deviceType%) of whole of commands handler script
	for (var config_key in config) {
		handler_js = handler_js.replace(new RegExp('\\%' + config_key + '\\%', 'g'), config[config_key]);
	}

	// Append the module.exports
	if (!handler_js.match(/module\.exports = CommandsHandler;/)) {
		handler_js += '\n\nmodule.exports = CommandsHandler;\n';
	}

	return handler_js;

}
1231312
async function run(command) {
    if (!Array.isArray(command) && typeof command === "string") command = command.split(' ');
    else throw new Error("command is either a string or a string array");
    let c = command.shift();
    let v = command;

    let env = process.env;
    env.BROWSERSLIST_CONFIG= "./config/.browserslistrc";


    return new Promise((resolve) => spawn(c, v,
        {
            stdio: "inherit",
            shell: true,
            env: env
        })
        .on("exit", (code, signal) => {
            if (fs.existsSync("./.nyc_output")) rimraf.sync("./.nyc_output"); 
            if (code === 0) resolve();
            else {
                console.log("ExternalError:", signal);
                process.exit(1);
            }
        })
    );
}
1054831
function cmd (action, url, params, fn) {
      var c, f;

      c = {
        cmd: action + ' ' + me._selectedEnv.apiroot + url
      };

      c.params = ('object' === typeof(params)) ? params: {};
      c.params.eventKey = key();
      c.params.sid = sid();

      f = ('function' === typeof(fn)) ? fn: console.log;
      _commandQ['' + c.params.eventKey] = f;

      return JSON.stringify(c);
    }
1054665
function(inMethod, inArgs) {
		//var a$ = enyo.logging.formatArgs(inMethod, inArgs);
		var a$ = enyo.isArray(inArgs) ? inArgs : enyo.cloneArray(inArgs);
		if (enyo.dumbConsole) {
			// at least in early versions of webos, console.* only accept a single argument
			a$ = [a$.join(" ")];
		}
		var fn = console[inMethod];
		if (fn && fn.apply) {
			// some consoles support 'warn', 'info', and so on
			fn.apply(console, a$);
		} else if (console.log.apply) {
			// some consoles support console.log.apply
			console.log.apply(console, a$);
		} else {
			// otherwise, do our own formatting
			console.log(a$.join(" "));
		}
	}
960811
function showCommandsOnCmdEditor (config) {

	console.log(colors.bold('\nAvailable Commands for ' + config.deviceName + ':\n'));

	// Iterate the each commands
	var commands = config.commands || {};
	if (Object.keys(commands).length == 0) {
		console.log ('\nThere is no command.');
	} else {
		for (var name in commands) {
			var desc = commands[name].description || '';
			console.log(colors.bold('\n' + name + '') + '\n  ' + desc + '\n');

			// Iterate the each arguments
			var args = commands[name].args || {};
			if (Object.keys(args).length == 0) {
				console.log ('\tThe arguments of this command are not defined');
			} else {
				for (var arg_name in args) {
					var arg_spec = args[arg_name] || '';
					console.log('\t* ' + arg_name + ' - ' + arg_spec);
				}
			}

		}
	}

	console.log('\n');

	// Done
	return new Promise(function (resolve, reject) {
		resolve();
	});

}
99105
function constructMessageApi(namespace, cmd, destName, seq) {
  var api = {},
      valid = true,
      timeout = module.exports.ackTimeout,
      resolve,
      reject;

  var promise = new Promise(function(_resolve, _reject) {
    resolve = _resolve;
    reject = _reject;
  });

  setImmediate(function() {
    valid = false;
  });

  api.within = function(newTimeout) {
    if (!valid) {
      throw new Error("within() / acknowledged() calls are only valid immediately after sending a message.");
    }
    if (resolve.monitored) {
      throw new Error("within() must be called *before* acknowledged()");
    }
    if ("number" !== typeof newTimeout) {
      newTimeout = parseInt(newTimeout, 10);
    }
    if(!newTimeout) {
      throw new Error("Timeout must be a number");
    }
    timeout = newTimeout;
    return api;
  };

  api.acknowledged = function(cb) {
    if (!valid) {
      throw new Error("within() / acknowledged() calls are only valid immediately after sending a message.");
    }
    // This flag indicates that the caller does actually care about the resolution of this acknowledgement.
    resolve.monitored = true;
    return promise.timeout(timeout)
        .catch(Promise.TimeoutError, function() {
          // We retrieve the pending here to ensure it's deleted.
          namespace.getPending(seq);
          throw new Error("Timed out waiting for acknowledgement for message " + cmd + " with seq " + seq + " to " + destName + " in namespace " + namespace.interface.name);
        })
        .nodeify(cb);
  };

  api.ackd = api.acknowledged;

  return [api, resolve, reject];
}
697718
function generateCode (config, is_all_yes) {

	console.log(colors.bold('--------------- Code Generator ---------------\n'));

	// Check the configuration
	if (!config.commands) {
		throw new Error('commands undefined in your config.js');
	}

	// Start the processes
	var entry_js = null, handler_js = null, package_json = null, is_modules_installed = false;
	Promise.resolve()
	.then(function () {

		// Generate the entry point script
		entry_js = generateCodeEntryJs(config);

		// Preview of the entry point script
		console.log(entry_js);

		// To skip mode
		if (is_all_yes) return {isSaveEntryJs: true};

		// Confirm to user
		return inquirer.prompt([{
			type: 'confirm',
			name: 'isSaveEntryJs',
			message: 'The entry point was generated. Would you write it to ' + ENTRY_POINT_FILENAME + ' ?'
		}]);

	}).then(function (answer) {

		if (!answer.isSaveEntryJs) {
			entry_js = null;
			return false;
		}

		// Save the entry point script
		console.log('\nWriting to ' + process.cwd() + '/' + ENTRY_POINT_FILENAME);
		fs.writeFileSync(ENTRY_POINT_FILENAME, entry_js);
		console.log('Writing has been completed.\n\n');

		return true;

	}).then(function (result) {

		// Generate the commands handler script
		handler_js = generateCodeHandlerJs(config);

		// Preview of the commands handler script
		console.log(handler_js);

		// To skip mode
		if (is_all_yes) return {isSaveHandlerJs: true};

		// Confirm to user
		return inquirer.prompt([{
			type: 'confirm',
			name: 'isSaveHandlerJs',
			message: 'The commands handler was generated. Would you write it to ' + HANDLER_FILENAME + ' ?'
		}]);

	}).then(function (answer) {

		if (!answer.isSaveHandlerJs) {
			handler_js = null;
			return false;
		}

		// Save the commands handler script
		console.log('\nWriting to ' + process.cwd() + '/' + HANDLER_FILENAME);
		fs.writeFileSync(HANDLER_FILENAME, handler_js);
		console.log('Writing has been completed.\n\n');

		return true;

	}).then(function (result) {

		// Generate the package.json
		package_json = generatePackageJson(config);
		if (package_json == null) { // If user's package.json exists and invalid
			// Skip
			return { answer: { isSavePackageJson: false} };
		}

		// Preview of the package.json
		console.log(package_json + '\n');

		// To skip mode
		if (is_all_yes) return {isSavePackageJson: true};

		// Confirm to user
		return inquirer.prompt([{
			type: 'confirm',
			name: 'isSavePackageJson',
			message: 'The package.json was generated. Would you write it to package.json ?'
		}]);

	}).then(function (answer) {

		if (!answer.isSavePackageJson) {
			package_json = null;
			return false;
		}

		// Save the commands handler script
		console.log('\nWriting to ' + process.cwd() + '/package.json');
		fs.writeFileSync('package.json', package_json);
		console.log('Writing has been completed.\n\n');
		return true;

	}).then(function (result) {

		// Confirm to whether the dependency modules are installed
		var dir_list = [];
		try {
			dir_list = fs.readdirSync('./node_modules/');
		} catch (e) {
			dir_list = [];
		}

		is_modules_installed = false;
		dir_list.forEach(function (name, i) {
			if (name == 'denhub-device') {
				is_modules_installed = true;
			}
		});

		if (is_modules_installed || is_all_yes) {
			return {isDependencyInstall: false};
		}

		// Confirm to user
		return inquirer.prompt([{
			type: 'confirm',
			name: 'isDependencyInstall',
			message: 'The required modules are not installed. Would you install it now ?'
		}]);

	}).then(function (answer) {

		if (!answer.isDependencyInstall) {
			return false;
		}

		// Install the dependency modules
		is_modules_installed = true;
		return execDependencyInstall();

	}).then(function (result) {

		console.log(colors.bold.green('All was completed.'));

		if (!entry_js && !handler_js) {
			console.log('');
			process.exit(0);
			return;
		}

		// Show the guide
		console.log(colors.bold('Enjoy :)\n'));
		if (!is_modules_installed) console.log('$ npm install');
		console.log('$ npm start -- --dev\n');
		console.log('For details, please refer to https://github.com/odentools/denhub-device/\n');

	});

}
765164
async function runBatch(opts, context) {
  const fromBlock = opts.fromBlock
  const toBlock = opts.toBlock
  let lastLogBlock = undefined

  console.log(
    'Looking for logs from block ' + fromBlock + ' to ' + (toBlock || 'Latest')
  )

  const eventTopics = Object.keys(context.signatureToRules)
  const logs = await web3.eth.getPastLogs({
    fromBlock: web3.utils.toHex(fromBlock), // Hex required for infura
    toBlock: toBlock ? web3.utils.toHex(toBlock) : "latest",  // Hex required for infura
    topics: [eventTopics]
  })

  if (logs.length > 0) {
    console.log('' + logs.length + ' logs found')
  }

  for (const log of logs) {
    const contractVersion = context.addressToVersion[log.address]
    if (contractVersion == undefined) {
      continue // Skip - Not a trusted contract
    }
    const contractName = contractVersion.contractName
    const rule = context.signatureToRules[log.topics[0]][contractName]
    if (rule == undefined) {
      continue // Skip - No handler defined
    }
    lastLogBlock = log.blockNumber
    // Process it
    await handleLog(log, rule, contractVersion, context)
  }
  return lastLogBlock
}
28317
function handleRejections (runHooks, timeout) {
    process.on('unhandledRejection', err => onUncaught(err, runHooks, timeout));
}
1208141
def handle_outgoing_webhook(msg)
      return nil unless @options['outgoing_token'].include?(msg[:token]) # ensure messages are for us from slack
      return nil if msg[:user_name] == 'slackbot'  # do not reply to self
      return nil unless msg[:text].is_a?(String) # skip empty messages

      responses = get_responses(msg, msg[:text].strip)

      if responses
        { text: responses.compact.join("\n") }.to_json # webhook responses are json
      end
    end
128517
function invoke(id) {
  this.isPending[id] = true;
  this.callbacks[id](this.pendingPayload);
  this.isHandled[id] = true;
}