<commit_before>/**
 * Copyright (C) 2018 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-parser/graphs/contributors
 * @url http://glayzzle.com
 */
"use strict";

const Location = require("./ast/location");
const Position = require("./ast/position");

/**
 * ## Class hierarchy
 *
 * - [Location](#location)
 * - [Position](#position)
 * - [Node](#node)
 *   - [Identifier](#identifier)
 *   - [TraitUse](#traituse)
 *   - [TraitAlias](#traitalias)
 *   - [TraitPrecedence](#traitprecedence)
 *   - [Entry](#entry)
 *   - [Case](#case)
 *   - [Label](#label)
 *   - [Comment](#comment)
 *     - [CommentLine](#commentline)
 *     - [CommentBlock](#commentblock)
 *   - [Error](#error)
 *   - [Expression](#expression)
 *     - [Array](#array)
 *     - [Variable](#variable)
 *     - [Variadic](#variadic)
 *     - [ConstRef](#constref)
 *     - [Yield](#yield)
 *     - [YieldFrom](#yieldfrom)
 *     - [Lookup](#lookup)
 *       - [PropertyLookup](#propertylookup)
 *       - [StaticLookup](#staticlookup)
 *       - [OffsetLookup](#offsetlookup)
 *     - [Operation](#operation)
 *       - [Pre](#pre)
 *       - [Post](#post)
 *       - [Bin](#bin)
 *       - [Parenthesis](#parenthesis)
 *       - [Unary](#unary)
 *       - [Cast](#cast)
 *     - [Literal](#literal)
 *       - [Boolean](#boolean)
 *       - [String](#string)
 *       - [Number](#number)
 *       - [Inline](#inline)
 *       - [Magic](#magic)
 *       - [Nowdoc](#nowdoc)
 *       - [Encapsed](#encapsed)
 *   - [Statement](#statement)
 *     - [Eval](#eval)
 *     - [Exit](#exit)
 *     - [Halt](#halt)
 *     - [Clone](#clone)
 *     - [Declare](#declare)
 *     - [Global](#global)
 *     - [Static](#static)
 *     - [Include](#include)
 *     - [Assign](#assign)
 *     - [RetIf](#retif)
 *     - [If](#if)
 *     - [Do](#do)
 *     - [While](#while)
 *     - [For](#for)
 *     - [Foreach](#foreach)
 *     - [Switch](#switch)
 *     - [Goto](#goto)
 *     - [Silent](#silent)
 *     - [Try](#try)
 *     - [Catch](#catch)
 *     - [Throw](#throw)
 *     - [Call](#call)
 *     - [Closure](#closure)
 *     - [New](#new)
 *     - [UseGroup](#usegroup)
 *     - [UseItem](#useitem)
 *     - [Block](#block)
 *       - [Program](#program)
 *       - [Namespace](#namespace)
 *     - [Sys](#sys)
 *       - [Echo](#echo)
 *       - [List](#list)
 *       - [Print](#print)
 *       - [Isset](#isset)
 *       - [Unset](#unset)
 *       - [Empty](#empty)
 *     - [Declaration](#declaration)
 *       - [Class](#class)
 *       - [Interface](#interface)
 *       - [Trait](#trait)
 *       - [Constant](#constant)
 *         - [ClassConstant](#classconstant)
 *       - [Function](#function)
 *         - [Method](#method)
 *       - [Parameter](#parameter)
 *       - [Property](#property)
 * ---
 */

/**
 * The AST builder class
 * @constructor AST
 * @property {Boolean} withPositions - Should locate any node (by default false)
 * @property {Boolean} withSource - Should extract the node original code (by default false)
 */
const AST = function(withPositions, withSource) {
  this.withPositions = withPositions;
  this.withSource = withSource;
};

/**
 * Create a position node from specified parser
 * including it's lexer current state
 * @param {Parser}
 * @return {Position}
 * @private
 */
AST.prototype.position = function(parser) {
  return new Position(
    parser.lexer.yylloc.first_line,
    parser.lexer.yylloc.first_column,
    parser.lexer.yylloc.first_offset
  );
};

// operators in ascending order of precedence
AST.precedence = {};
[
  ["or"],
  ["xor"],
  ["and"],
  ["="],
  ["?"],
  ["??"],
  ["||"],
  ["&&"],
  ["|"],
  ["^"],
  ["&"],
  ["==", "!=", "===", "!==", /* '<>', */ "<=>"],
  ["<", "<=", ">", ">="],
  ["<<", ">>"],
  ["+", "-", "."],
  ["*", "/", "%"],
  ["!"],
  ["instanceof"]
  // TODO: typecasts
  // TODO: [ (array)
  // TODO: clone, new
].forEach(function(list, index) {
  list.forEach(function(operator) {
    AST.precedence[operator] = index + 1;
  });
});

/**
 * Check and fix precence, by default using right
 */
AST.prototype.resolvePrecedence = function(result) {
  let buffer, lLevel, rLevel;
  // handling precendence
  if (result.kind === "bin") {
    if (result.right) {
      if (result.right.kind === "bin") {
        lLevel = AST.precedence[result.type];
        rLevel = AST.precedence[result.right.type];
        if (lLevel && rLevel && rLevel <= lLevel) {
          // https://github.com/glayzzle/php-parser/issues/79
          // shift precedence
          buffer = result.right;
          result.right = result.right.left;
          buffer.left = this.resolvePrecedence(result);
          result = buffer;
        }
      } else if (result.right.kind === "retif") {
        lLevel = AST.precedence[result.type];
        rLevel = AST.precedence["?"];
        if (lLevel && rLevel && rLevel <= lLevel) {
          buffer = result.right;
          result.right = result.right.test;
          buffer.test = this.resolvePrecedence(result);
          result = buffer;
        }
      }
    }
  } else if (result.kind === "unary") {
    // https://github.com/glayzzle/php-parser/issues/75
    if (result.what) {
      // unary precedence is allways lower
      if (result.what.kind === "bin") {
        buffer = result.what;
        result.what = result.what.left;
        buffer.left = this.resolvePrecedence(result);
        result = buffer;
      } else if (result.what.kind === "retif") {
        buffer = result.what;
        result.what = result.what.test;
        buffer.test = this.resolvePrecedence(result);
        result = buffer;
      }
    }
  } else if (result.kind === "retif") {
    // https://github.com/glayzzle/php-parser/issues/77
    if (result.falseExpr && result.falseExpr.kind === "retif") {
      buffer = result.falseExpr;
      result.falseExpr = buffer.test;
      buffer.test = this.resolvePrecedence(result);
      result = buffer;
    }
  } else if (result.kind === "assign") {
    // https://github.com/glayzzle/php-parser/issues/81
    if (result.right && result.right.kind === "bin") {
      lLevel = AST.precedence["="];
      rLevel = AST.precedence[result.right.type];
      // only shifts with and, xor, or
      if (lLevel && rLevel && rLevel < lLevel) {
        buffer = result.right;
        result.right = result.right.left;
        buffer.left = result;
        result = buffer;
      }
    }
  }
  return result;
};

/**
 * Prepares an AST node
 * @param {String|null} kind - Defines the node type
 * (if null, the kind must be passed at the function call)
 * @param {Parser} parser - The parser instance (use for extracting locations)
 * @return {Function}
 */
AST.prototype.prepare = function(kind, docs, parser) {
  let start = null;
  if (this.withPositions || this.withSource) {
    start = this.position(parser);
  }
  const self = this;
  // returns the node
  return function() {
    let location = null;
    const args = Array.prototype.slice.call(arguments);
    args.push(docs);
    if (self.withPositions || self.withSource) {
      let src = null;
      if (self.withSource) {
        src = parser.lexer._input.substring(start.offset, parser.prev[2]);
      }
      if (self.withPositions) {
        location = new Location(
          src,
          start,
          new Position(parser.prev[0], parser.prev[1], parser.prev[2])
        );
      } else {
        location = new Location(src, null, null);
      }
      // last argument is allways the location
      args.push(location);
    }
    // handle lazy kind definitions
    if (!kind) {
      kind = args.shift();
    }
    // build the object
    const node = self[kind];
    if (typeof node !== "function") {
      throw new Error('Undefined node "' + kind + '"');
    }
    const result = Object.create(node.prototype);
    node.apply(result, args);
    return self.resolvePrecedence(result);
  };
};

// Define all AST nodes
[
  require("./ast/array"),
  require("./ast/assign"),
  require("./ast/bin"),
  require("./ast/block"),
  require("./ast/boolean"),
  require("./ast/break"),
  require("./ast/call"),
  require("./ast/case"),
  require("./ast/cast"),
  require("./ast/catch"),
  require("./ast/class"),
  require("./ast/classconstant"),
  require("./ast/clone"),
  require("./ast/closure"),
  require("./ast/comment"),
  require("./ast/commentblock"),
  require("./ast/commentline"),
  require("./ast/constant"),
  require("./ast/constref"),
  require("./ast/continue"),
  require("./ast/declaration"),
  require("./ast/declare"),
  require("./ast/do"),
  require("./ast/echo"),
  require("./ast/empty"),
  require("./ast/encapsed"),
  require("./ast/entry"),
  require("./ast/error"),
  require("./ast/eval"),
  require("./ast/exit"),
  require("./ast/expression"),
  require("./ast/for"),
  require("./ast/foreach"),
  require("./ast/function"),
  require("./ast/global"),
  require("./ast/goto"),
  require("./ast/halt"),
  require("./ast/identifier"),
  require("./ast/if"),
  require("./ast/include"),
  require("./ast/inline"),
  require("./ast/interface"),
  require("./ast/isset"),
  require("./ast/label"),
  require("./ast/list"),
  require("./ast/literal"),
  require("./ast/lookup"),
  require("./ast/magic"),
  require("./ast/method"),
  require("./ast/namespace"),
  require("./ast/new"),
  require("./ast/node"),
  require("./ast/nowdoc"),
  require("./ast/number"),
  require("./ast/offsetlookup"),
  require("./ast/operation"),
  require("./ast/parameter"),
  require("./ast/parenthesis"),
  require("./ast/post"),
  require("./ast/pre"),
  require("./ast/print"),
  require("./ast/program"),
  require("./ast/property"),
  require("./ast/propertylookup"),
  require("./ast/retif"),
  require("./ast/return"),
  require("./ast/silent"),
  require("./ast/statement"),
  require("./ast/static"),
  require("./ast/staticlookup"),
  require("./ast/string"),
  require("./ast/switch"),
  require("./ast/sys"),
  require("./ast/throw"),
  require("./ast/trait"),
  require("./ast/traitalias"),
  require("./ast/traitprecedence"),
  require("./ast/traituse"),
  require("./ast/try"),
  require("./ast/unary"),
  require("./ast/unset"),
  require("./ast/usegroup"),
  require("./ast/useitem"),
  require("./ast/variable"),
  require("./ast/variadic"),
  require("./ast/while"),
  require("./ast/yield"),
  require("./ast/yieldfrom")
].forEach(function(ctor) {
  let kind = ctor.prototype.constructor.name.toLowerCase();
  if (kind[0] === "_") kind = kind.substring(1);
  AST.prototype[kind] = ctor;
});

module.exports = AST;
<commit_msg>add a new way to change the kind of the node<commit_after>/**
 * Copyright (C) 2018 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-parser/graphs/contributors
 * @url http://glayzzle.com
 */
"use strict";

const Location = require("./ast/location");
const Position = require("./ast/position");

/**
 * ## Class hierarchy
 *
 * - [Location](#location)
 * - [Position](#position)
 * - [Node](#node)
 *   - [Identifier](#identifier)
 *   - [TraitUse](#traituse)
 *   - [TraitAlias](#traitalias)
 *   - [TraitPrecedence](#traitprecedence)
 *   - [Entry](#entry)
 *   - [Case](#case)
 *   - [Label](#label)
 *   - [Comment](#comment)
 *     - [CommentLine](#commentline)
 *     - [CommentBlock](#commentblock)
 *   - [Error](#error)
 *   - [Expression](#expression)
 *     - [Array](#array)
 *     - [Variable](#variable)
 *     - [Variadic](#variadic)
 *     - [ConstRef](#constref)
 *     - [Yield](#yield)
 *     - [YieldFrom](#yieldfrom)
 *     - [Lookup](#lookup)
 *       - [PropertyLookup](#propertylookup)
 *       - [StaticLookup](#staticlookup)
 *       - [OffsetLookup](#offsetlookup)
 *     - [Operation](#operation)
 *       - [Pre](#pre)
 *       - [Post](#post)
 *       - [Bin](#bin)
 *       - [Parenthesis](#parenthesis)
 *       - [Unary](#unary)
 *       - [Cast](#cast)
 *     - [Literal](#literal)
 *       - [Boolean](#boolean)
 *       - [String](#string)
 *       - [Number](#number)
 *       - [Inline](#inline)
 *       - [Magic](#magic)
 *       - [Nowdoc](#nowdoc)
 *       - [Encapsed](#encapsed)
 *   - [Statement](#statement)
 *     - [Eval](#eval)
 *     - [Exit](#exit)
 *     - [Halt](#halt)
 *     - [Clone](#clone)
 *     - [Declare](#declare)
 *     - [Global](#global)
 *     - [Static](#static)
 *     - [Include](#include)
 *     - [Assign](#assign)
 *     - [RetIf](#retif)
 *     - [If](#if)
 *     - [Do](#do)
 *     - [While](#while)
 *     - [For](#for)
 *     - [Foreach](#foreach)
 *     - [Switch](#switch)
 *     - [Goto](#goto)
 *     - [Silent](#silent)
 *     - [Try](#try)
 *     - [Catch](#catch)
 *     - [Throw](#throw)
 *     - [Call](#call)
 *     - [Closure](#closure)
 *     - [New](#new)
 *     - [UseGroup](#usegroup)
 *     - [UseItem](#useitem)
 *     - [Block](#block)
 *       - [Program](#program)
 *       - [Namespace](#namespace)
 *     - [Sys](#sys)
 *       - [Echo](#echo)
 *       - [List](#list)
 *       - [Print](#print)
 *       - [Isset](#isset)
 *       - [Unset](#unset)
 *       - [Empty](#empty)
 *     - [Declaration](#declaration)
 *       - [Class](#class)
 *       - [Interface](#interface)
 *       - [Trait](#trait)
 *       - [Constant](#constant)
 *         - [ClassConstant](#classconstant)
 *       - [Function](#function)
 *         - [Method](#method)
 *       - [Parameter](#parameter)
 *       - [Property](#property)
 * ---
 */

/**
 * The AST builder class
 * @constructor AST
 * @property {Boolean} withPositions - Should locate any node (by default false)
 * @property {Boolean} withSource - Should extract the node original code (by default false)
 */
const AST = function(withPositions, withSource) {
  this.withPositions = withPositions;
  this.withSource = withSource;
};

/**
 * Create a position node from specified parser
 * including it's lexer current state
 * @param {Parser}
 * @return {Position}
 * @private
 */
AST.prototype.position = function(parser) {
  return new Position(
    parser.lexer.yylloc.first_line,
    parser.lexer.yylloc.first_column,
    parser.lexer.yylloc.first_offset
  );
};

// operators in ascending order of precedence
AST.precedence = {};
[
  ["or"],
  ["xor"],
  ["and"],
  ["="],
  ["?"],
  ["??"],
  ["||"],
  ["&&"],
  ["|"],
  ["^"],
  ["&"],
  ["==", "!=", "===", "!==", /* '<>', */ "<=>"],
  ["<", "<=", ">", ">="],
  ["<<", ">>"],
  ["+", "-", "."],
  ["*", "/", "%"],
  ["!"],
  ["instanceof"]
  // TODO: typecasts
  // TODO: [ (array)
  // TODO: clone, new
].forEach(function(list, index) {
  list.forEach(function(operator) {
    AST.precedence[operator] = index + 1;
  });
});

/**
 * Check and fix precence, by default using right
 */
AST.prototype.resolvePrecedence = function(result) {
  let buffer, lLevel, rLevel;
  // handling precendence
  if (result.kind === "bin") {
    if (result.right) {
      if (result.right.kind === "bin") {
        lLevel = AST.precedence[result.type];
        rLevel = AST.precedence[result.right.type];
        if (lLevel && rLevel && rLevel <= lLevel) {
          // https://github.com/glayzzle/php-parser/issues/79
          // shift precedence
          buffer = result.right;
          result.right = result.right.left;
          buffer.left = this.resolvePrecedence(result);
          result = buffer;
        }
      } else if (result.right.kind === "retif") {
        lLevel = AST.precedence[result.type];
        rLevel = AST.precedence["?"];
        if (lLevel && rLevel && rLevel <= lLevel) {
          buffer = result.right;
          result.right = result.right.test;
          buffer.test = this.resolvePrecedence(result);
          result = buffer;
        }
      }
    }
  } else if (result.kind === "unary") {
    // https://github.com/glayzzle/php-parser/issues/75
    if (result.what) {
      // unary precedence is allways lower
      if (result.what.kind === "bin") {
        buffer = result.what;
        result.what = result.what.left;
        buffer.left = this.resolvePrecedence(result);
        result = buffer;
      } else if (result.what.kind === "retif") {
        buffer = result.what;
        result.what = result.what.test;
        buffer.test = this.resolvePrecedence(result);
        result = buffer;
      }
    }
  } else if (result.kind === "retif") {
    // https://github.com/glayzzle/php-parser/issues/77
    if (result.falseExpr && result.falseExpr.kind === "retif") {
      buffer = result.falseExpr;
      result.falseExpr = buffer.test;
      buffer.test = this.resolvePrecedence(result);
      result = buffer;
    }
  } else if (result.kind === "assign") {
    // https://github.com/glayzzle/php-parser/issues/81
    if (result.right && result.right.kind === "bin") {
      lLevel = AST.precedence["="];
      rLevel = AST.precedence[result.right.type];
      // only shifts with and, xor, or
      if (lLevel && rLevel && rLevel < lLevel) {
        buffer = result.right;
        result.right = result.right.left;
        buffer.left = result;
        result = buffer;
      }
    }
  }
  return result;
};

/**
 * Prepares an AST node
 * @param {String|null} kind - Defines the node type
 * (if null, the kind must be passed at the function call)
 * @param {Parser} parser - The parser instance (use for extracting locations)
 * @return {Function}
 */
AST.prototype.prepare = function(kind, docs, parser) {
  let start = null;
  if (this.withPositions || this.withSource) {
    start = this.position(parser);
  }
  const self = this;
  // returns the node
  const result = function() {
    let location = null;
    const args = Array.prototype.slice.call(arguments);
    args.push(docs);
    if (self.withPositions || self.withSource) {
      let src = null;
      if (self.withSource) {
        src = parser.lexer._input.substring(start.offset, parser.prev[2]);
      }
      if (self.withPositions) {
        location = new Location(
          src,
          start,
          new Position(parser.prev[0], parser.prev[1], parser.prev[2])
        );
      } else {
        location = new Location(src, null, null);
      }
      // last argument is allways the location
      args.push(location);
    }
    // handle lazy kind definitions
    if (!kind) {
      kind = args.shift();
    }
    // build the object
    const node = self[kind];
    if (typeof node !== "function") {
      throw new Error('Undefined node "' + kind + '"');
    }
    const result = Object.create(node.prototype);
    node.apply(result, args);
    return self.resolvePrecedence(result);
  };
  /**
   * Helper to change a node kind
   * @param {String} newKind
   */
  result.setKind = function(newKind) {
    kind =  newKind;
  };
  return result;
};

// Define all AST nodes
[
  require("./ast/array"),
  require("./ast/assign"),
  require("./ast/bin"),
  require("./ast/block"),
  require("./ast/boolean"),
  require("./ast/break"),
  require("./ast/call"),
  require("./ast/case"),
  require("./ast/cast"),
  require("./ast/catch"),
  require("./ast/class"),
  require("./ast/classconstant"),
  require("./ast/clone"),
  require("./ast/closure"),
  require("./ast/comment"),
  require("./ast/commentblock"),
  require("./ast/commentline"),
  require("./ast/constant"),
  require("./ast/constref"),
  require("./ast/continue"),
  require("./ast/declaration"),
  require("./ast/declare"),
  require("./ast/do"),
  require("./ast/echo"),
  require("./ast/empty"),
  require("./ast/encapsed"),
  require("./ast/entry"),
  require("./ast/error"),
  require("./ast/eval"),
  require("./ast/exit"),
  require("./ast/expression"),
  require("./ast/for"),
  require("./ast/foreach"),
  require("./ast/function"),
  require("./ast/global"),
  require("./ast/goto"),
  require("./ast/halt"),
  require("./ast/identifier"),
  require("./ast/if"),
  require("./ast/include"),
  require("./ast/inline"),
  require("./ast/interface"),
  require("./ast/isset"),
  require("./ast/label"),
  require("./ast/list"),
  require("./ast/literal"),
  require("./ast/lookup"),
  require("./ast/magic"),
  require("./ast/method"),
  require("./ast/namespace"),
  require("./ast/new"),
  require("./ast/node"),
  require("./ast/nowdoc"),
  require("./ast/number"),
  require("./ast/offsetlookup"),
  require("./ast/operation"),
  require("./ast/parameter"),
  require("./ast/parenthesis"),
  require("./ast/post"),
  require("./ast/pre"),
  require("./ast/print"),
  require("./ast/program"),
  require("./ast/property"),
  require("./ast/propertylookup"),
  require("./ast/retif"),
  require("./ast/return"),
  require("./ast/silent"),
  require("./ast/statement"),
  require("./ast/static"),
  require("./ast/staticlookup"),
  require("./ast/string"),
  require("./ast/switch"),
  require("./ast/sys"),
  require("./ast/throw"),
  require("./ast/trait"),
  require("./ast/traitalias"),
  require("./ast/traitprecedence"),
  require("./ast/traituse"),
  require("./ast/try"),
  require("./ast/unary"),
  require("./ast/unset"),
  require("./ast/usegroup"),
  require("./ast/useitem"),
  require("./ast/variable"),
  require("./ast/variadic"),
  require("./ast/while"),
  require("./ast/yield"),
  require("./ast/yieldfrom")
].forEach(function(ctor) {
  let kind = ctor.prototype.constructor.name.toLowerCase();
  if (kind[0] === "_") kind = kind.substring(1);
  AST.prototype[kind] = ctor;
});

module.exports = AST;
<|endoftext|>


<commit_before>/**
 * @fileOverview Wrapper for node-rdkafka Producer Ctor, a mixin.
 */
var Promise = require('bluebird');
var cip = require('cip');
var kafka = require('node-rdkafka');

var magicByte = require('./magic-byte');

/**
 * Wrapper for node-rdkafka Produce Ctor, a mixin.
 *
 * @constructor
 */
var Producer = module.exports = cip.extend();

/**
 * The wrapper of the node-rdkafka package Producer Ctor.
 *
 * @param {Object} opts Producer general options.
 * @see https://github.com/edenhill/librdkafka/blob/2213fb29f98a7a73f22da21ef85e0783f6fd67c4/CONFIGURATION.md
 * @return {Promise(kafka.Producer)} A Promise.
 */
Producer.prototype.getProducer = Promise.method(function (opts) {
  if (!opts) {
    opts = {};
  }

  if (!opts['metadata.broker.list']) {
    opts['metadata.broker.list'] = this.kafkaBrokerUrl;
  }
  console.log('KafkaAvro :: Starting producer with options:', opts);
  var producer = new kafka.Producer(opts);

  this._producers.push(producer);

  // hack node-rdkafka
  producer.__kafkaAvro_produce = producer.produce;
  producer.produce = this._produceWrapper.bind(this, producer);

  producer.connect();

  return new Promise(function(resolve) {
    producer.on('ready', resolve);
  })
    .return(producer);
});

/**
 * The node-rdkafka produce method wrapper, will validate and serialize
 * the message against the existing schemas.
 *
 * @param {kafka.Producer} producerInstance node-rdkafka instance.
 * @param {kafka.Producer.Topic} kafkaTopic node-rdkafka Topic instance.
 * @param {number} partition The partition to produce on.
 * @param {Object} value The message.
 * @param {string|number} key The partioning key.
 * @param {*=} optOpaque Pass vars to receipt handler.
 */
Producer.prototype._produceWrapper = function (producerInstance, kafkaTopic,
  partition, value, key, optOpaque) {

  var topicName = kafkaTopic.name();

  if (!this.valueSchemas[topicName]) {
    // topic not found in schemas, bail early
    console.log('KafkaAvro :: Warning, did not find topic on SR:', topicName);
    var bufVal = new Buffer(JSON.stringify(value));
    return producerInstance.__kafkaAvro_produce(kafkaTopic, partition, bufVal,
      key, optOpaque);
  }

  var type = this.valueSchemas[topicName];
  var schemaId = this.schemaMeta[topicName].id;

  var bufValue = this.serialize(type, schemaId, value);

  return producerInstance.__kafkaAvro_produce(kafkaTopic, partition, bufValue,
    key, optOpaque);
};

/**
 * Serialize the message using avro.
 *
 * @param {avsc.Type} type The avro type instance.
 * @param {number} schemaId The schema id.
 * @param {*} value The value to serialize.
 * @return {Buffer} Serialized buffer.
 * @private
 */
Producer.prototype.serialize = function (type, schemaId, value) {
  var bufValue = magicByte.toMessageBuffer(value, type, schemaId);

  return bufValue;
};
<commit_msg>tweak logging names<commit_after>/**
 * @fileOverview Wrapper for node-rdkafka Producer Ctor, a mixin.
 */
var Promise = require('bluebird');
var cip = require('cip');
var kafka = require('node-rdkafka');

var magicByte = require('./magic-byte');

/**
 * Wrapper for node-rdkafka Produce Ctor, a mixin.
 *
 * @constructor
 */
var Producer = module.exports = cip.extend();

/**
 * The wrapper of the node-rdkafka package Producer Ctor.
 *
 * @param {Object} opts Producer general options.
 * @see https://github.com/edenhill/librdkafka/blob/2213fb29f98a7a73f22da21ef85e0783f6fd67c4/CONFIGURATION.md
 * @return {Promise(kafka.Producer)} A Promise.
 */
Producer.prototype.getProducer = Promise.method(function (opts) {
  if (!opts) {
    opts = {};
  }

  if (!opts['metadata.broker.list']) {
    opts['metadata.broker.list'] = this.kafkaBrokerUrl;
  }
  console.log('KafkaAvro.Producer.getProducer() :: Starting producer with',
    'options:', opts);

  var producer = new kafka.Producer(opts);

  this._producers.push(producer);

  // hack node-rdkafka
  producer.__kafkaAvro_produce = producer.produce;
  producer.produce = this._produceWrapper.bind(this, producer);

  producer.connect();

  return new Promise(function(resolve) {
    producer.on('ready', resolve);
  })
    .return(producer);
});

/**
 * The node-rdkafka produce method wrapper, will validate and serialize
 * the message against the existing schemas.
 *
 * @param {kafka.Producer} producerInstance node-rdkafka instance.
 * @param {kafka.Producer.Topic} kafkaTopic node-rdkafka Topic instance.
 * @param {number} partition The partition to produce on.
 * @param {Object} value The message.
 * @param {string|number} key The partioning key.
 * @param {*=} optOpaque Pass vars to receipt handler.
 */
Producer.prototype._produceWrapper = function (producerInstance, kafkaTopic,
  partition, value, key, optOpaque) {

  var topicName = kafkaTopic.name();

  if (!this.valueSchemas[topicName]) {
    // topic not found in schemas, bail early
    console.warn('KafkaAvro.Producer._produceWrapper() :: Warning, did not find',
      'topic on SR:', topicName);
    var bufVal = new Buffer(JSON.stringify(value));
    return producerInstance.__kafkaAvro_produce(kafkaTopic, partition, bufVal,
      key, optOpaque);
  }

  var type = this.valueSchemas[topicName];
  var schemaId = this.schemaMeta[topicName].id;

  var bufValue = this.serialize(type, schemaId, value);

  return producerInstance.__kafkaAvro_produce(kafkaTopic, partition, bufValue,
    key, optOpaque);
};

/**
 * Serialize the message using avro.
 *
 * @param {avsc.Type} type The avro type instance.
 * @param {number} schemaId The schema id.
 * @param {*} value The value to serialize.
 * @return {Buffer} Serialized buffer.
 * @private
 */
Producer.prototype.serialize = function (type, schemaId, value) {
  var bufValue = magicByte.toMessageBuffer(value, type, schemaId);

  return bufValue;
};
<|endoftext|>


<commit_before>/**
 * This module provides BEM (Block Element Modifier) related methods
 * These methods can be used as an abstraction to talk to the DOM
 * BEM is a CSS methodology separating blocks (block) from elements (__element) and modifiers (--modifier)
 * BEM examples: alert, alert--warning, form__button, form__button--disabled
 * @see https://en.bem.info/methodology/key-concepts/
 * @module
 */

/**
 * BEM class
 * Contains static methods with BEM abstraction to DOM manipulation
 * @class
 */
class BEM {
    /**
     * Get a node by BEM (Block Element Modifier) description
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {HTMLElement}
     */
    static getBEMNode(block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return document.querySelector(selector);
    }

    /**
     * Get multiple nodes by BEM (Block Element Modifier) description
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {NodeList}
     */
    static getBEMNodes(block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return document.querySelectorAll(selector);
    }

    /**
     * Get a child node by BEM (Block Element Modifier) description
     * @param {HTMLElement} node The parent node
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {HTMLElement}
     */
    static getChildBEMNode(node, block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return node.querySelector(selector);
    }

    /**
     * Get a child node by BEM (Block Element Modifier) description
     * @param {HTMLElement} node The parent node
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {HTMLElement}
     */
    static getChildBEMNodes(node, block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return node.querySelectorAll(selector);
    }

    /**
     * Get a BEM (Block Element Modifier) class name
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {String}
     */
    static getBEMClassName(block, element, modifier) {
        let className = block;

        if (element) {
            className += `__${element}`;
        }

        if (modifier) {
            className += `--${modifier}`;
        }

        return className;
    }

    /**
     * Add an additional class name with a specific modifier (--modifier) to a BEM (Block Element Modifier) element
     * A modifier class is created for each of the existing class names
     * Class names containing "--" (modifier pattern) are discarded
     * Double class names are prevented
     * @param {HTMLElement} node The block/element to append the class name to (block, block__element)
     * @param {String} modifier The name of the modifier (--name)
     */
    static addModifier(node, modifier) {
        let classNames = node.className.split(' '),
            modifierClassNames = '';

        for (let i in classNames) {  // jshint ignore:line
            let className = classNames[i], modifierClassName = `${className}--${modifier}`;

            // Discard class names containing "--" (modifier pattern)
            if (className.match('--')) {
                continue;
            }

            // Prevent double class names
            if (node.className.match(modifierClassName)) {
                continue;
            }

            modifierClassNames += `${className}--${modifier} `;
        }

        node.className = `${node.className.trim()} ${modifierClassNames}`.trim();
    }

    /**
     * Remove all class names with a specific modifier (--modifier) from a BEM (Block Element Modifier) element
     * @param {HTMLElement} node The block/element to remove the class names from (block, block__element)
     * @param {String} modifier The name of the modifier (--name)
     */
    static removeModifier(node, modifier) {
        let regex = new RegExp(`[^^\\s]+?--${modifier}\\s?`, 'g');  // Regex matching all class names containing "--" + modifier
        node.className = node.className.replace(regex, '').trim();
    }

    /**
     * Toggles between addModifier() and removeModifier() based on the presence of modifier (--modifier)
     * Block/element names are NOT taken into account while matching
     * @param {HTMLElement} node The block/element to remove the class names from (block, block__element)
     * @param {String} modifier The name of the modifier (--name)
     */
    static toggleModifier(node, modifier) {
        if (BEM.hasModifier(node, modifier)) {
            BEM.removeModifier(node, modifier);
            return;
        }
        BEM.addModifier(node, modifier);
    }

    /**
     * Returns whether node has modifier (--modifier)
     * Block/element names are NOT taken into account while matching
     * @param {HTMLElement} node The block/element to check
     * @param {String} modifier The name of the modifier (--name)
     * @returns {Boolean}
     */
    static hasModifier(node, modifier) {
        let regex = new RegExp(`--${modifier}(?=\\s|$)`, 'g');  // Regex matching specific modifier
        return node.className.match(regex);
    }
}

export default BEM;
export { BEM };
<commit_msg>Fix a bug that could cause BEN,addModifier() to fail on Internet Explorer 11.<commit_after>/**
 * This module provides BEM (Block Element Modifier) related methods
 * These methods can be used as an abstraction to talk to the DOM
 * BEM is a CSS methodology separating blocks (block) from elements (__element) and modifiers (--modifier)
 * BEM examples: alert, alert--warning, form__button, form__button--disabled
 * @see https://en.bem.info/methodology/key-concepts/
 * @module
 */

/**
 * BEM class
 * Contains static methods with BEM abstraction to DOM manipulation
 * @class
 */
class BEM {
    /**
     * Get a node by BEM (Block Element Modifier) description
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {HTMLElement}
     */
    static getBEMNode(block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return document.querySelector(selector);
    }

    /**
     * Get multiple nodes by BEM (Block Element Modifier) description
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {NodeList}
     */
    static getBEMNodes(block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return document.querySelectorAll(selector);
    }

    /**
     * Get a child node by BEM (Block Element Modifier) description
     * @param {HTMLElement} node The parent node
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {HTMLElement}
     */
    static getChildBEMNode(node, block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return node.querySelector(selector);
    }

    /**
     * Get a child node by BEM (Block Element Modifier) description
     * @param {HTMLElement} node The parent node
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {HTMLElement}
     */
    static getChildBEMNodes(node, block, element, modifier) {
        let selector = `.${BEM.getBEMClassName(block, element, modifier)}`;
        return node.querySelectorAll(selector);
    }

    /**
     * Get a BEM (Block Element Modifier) class name
     * @param {String} block The outer block or component
     * @param {String} [element] An optional element within the outer block
     * @param {String} [modifier] An optional modifier or (e.g. state or theme) for a block/element
     * @returns {String}
     */
    static getBEMClassName(block, element, modifier) {
        let className = block;

        if (element) {
            className += `__${element}`;
        }

        if (modifier) {
            className += `--${modifier}`;
        }

        return className;
    }

    /**
     * Add an additional class name with a specific modifier (--modifier) to a BEM (Block Element Modifier) element
     * A modifier class is created for each of the existing class names
     * Class names containing "--" (modifier pattern) are discarded
     * Double class names are prevented
     * @param {HTMLElement} node The block/element to append the class name to (block, block__element)
     * @param {String} modifier The name of the modifier (--name)
     */
    static addModifier(node, modifier) {
        let classNames = node.className.split(' '),
            modifierClassNames = '';

        for (let i in classNames) {
            if (!classNames.hasOwnProperty(i)) {
                continue;
            }

            let className = classNames[i];
            let modifierClassName = `${className}--${modifier}`;

            // Discard class names containing "--" (modifier pattern)
            if (className.match('--')) {
                continue;
            }

            // Prevent double class names
            if (node.className.match(modifierClassName)) {
                continue;
            }

            modifierClassNames += `${className}--${modifier} `;
        }

        node.className = `${node.className.trim()} ${modifierClassNames}`.trim();
    }

    /**
     * Remove all class names with a specific modifier (--modifier) from a BEM (Block Element Modifier) element
     * @param {HTMLElement} node The block/element to remove the class names from (block, block__element)
     * @param {String} modifier The name of the modifier (--name)
     */
    static removeModifier(node, modifier) {
        let regex = new RegExp(`[^^\\s]+?--${modifier}\\s?`, 'g');  // Regex matching all class names containing "--" + modifier
        node.className = node.className.replace(regex, '').trim();
    }

    /**
     * Toggles between addModifier() and removeModifier() based on the presence of modifier (--modifier)
     * Block/element names are NOT taken into account while matching
     * @param {HTMLElement} node The block/element to remove the class names from (block, block__element)
     * @param {String} modifier The name of the modifier (--name)
     */
    static toggleModifier(node, modifier) {
        if (BEM.hasModifier(node, modifier)) {
            BEM.removeModifier(node, modifier);
            return;
        }
        BEM.addModifier(node, modifier);
    }

    /**
     * Returns whether node has modifier (--modifier)
     * Block/element names are NOT taken into account while matching
     * @param {HTMLElement} node The block/element to check
     * @param {String} modifier The name of the modifier (--name)
     * @returns {Boolean}
     */
    static hasModifier(node, modifier) {
        let regex = new RegExp(`--${modifier}(?=\\s|$)`, 'g');  // Regex matching specific modifier
        return node.className.match(regex);
    }
}

export default BEM;
export { BEM };
<|endoftext|>


<commit_before>module.exports = LdpMiddleware

var express = require('express')
var header = require('./header')
var acl = require('./acl')
var authentication = require('./handlers/authentication')
var get = require('./handlers/get')
var post = require('./handlers/post')
var put = require('./handlers/put')
var del = require('./handlers/delete')
var patch = require('./handlers/patch')
var index = require('./handlers/index')
var errorPages = require('./handlers/error-pages')

function LdpMiddleware (corsSettings) {
  var router = express.Router('/')

  // Add Link headers
  router.use(header.linksHandler)
  if (corsSettings) {
    router.use(corsSettings)
  }

  router.use('/*', authentication)
  router.get('/*', acl.allow('Read'), index, get)
  router.post('/*', acl.allow('Append'), post)
  router.patch('/*', acl.allow('Append'), patch)
  router.put('/*', acl.allow('Append'), put)
  router.delete('/*', acl.allow('Write'), del)

  // Errors
  router.use(errorPages)

  // TODO: in the process of being deprecated
  // Convert json-ld and nquads to turtle
  // router.use('/*', parse.parseHandler)

  return router
}
<commit_msg>put needs write<commit_after>module.exports = LdpMiddleware

var express = require('express')
var header = require('./header')
var acl = require('./acl')
var authentication = require('./handlers/authentication')
var get = require('./handlers/get')
var post = require('./handlers/post')
var put = require('./handlers/put')
var del = require('./handlers/delete')
var patch = require('./handlers/patch')
var index = require('./handlers/index')
var errorPages = require('./handlers/error-pages')

function LdpMiddleware (corsSettings) {
  var router = express.Router('/')

  // Add Link headers
  router.use(header.linksHandler)
  if (corsSettings) {
    router.use(corsSettings)
  }

  router.use('/*', authentication)
  router.get('/*', acl.allow('Read'), index, get)
  router.post('/*', acl.allow('Append'), post)
  router.patch('/*', acl.allow('Append'), patch)
  router.put('/*', acl.allow('Write'), put)
  router.delete('/*', acl.allow('Write'), del)

  // Errors
  router.use(errorPages)

  // TODO: in the process of being deprecated
  // Convert json-ld and nquads to turtle
  // router.use('/*', parse.parseHandler)

  return router
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

module.exports = function(components) {

  return function(id) {
    var def = components[id];
    if (!def) { return; }

    if (def.package && def.class) {
      var mod = require(def.package);
      var constructor = mod[def.class];
      return constructor;
    }

    return;
  }
}
<commit_msg>Auto-register all specs for configured components.<commit_after>/**
 * Module dependencies.
 */

module.exports = function(components) {

  function source(id) {
    var def = components[id];
    if (!def) { return; }

    if (def.module && def.ctor) {
      var mod = require(def.module);
      var constructor = mod[def.ctor];
      return constructor;
    }

    return;
  }

  source.used = function(container) {
    // Auto-register all configured specs, allowing for introspection.
    // Introspection is used, for example, when loading plugins such as Passport
    // strategies.
    var ids = Object.keys(components)
      , i, len;
    for (i = 0, len = ids.length; i < len; ++i) {
      container.register(ids[i]);
    }
  }

  return source;
}
<|endoftext|>


<commit_before>var fs = require('fs');
var ursa = require('ursa');
var dgram = require('dgram');
var tls = require('tls');
var net = require('net');
var mongoose = require('mongoose');

var message_parser = function(){

	/************************************************************************/
	//Webサーバーから送られてきた子機への命令
	var command = {};
	var receive_command = function(str){
		var obj = JSON.parse(str);
		command.type = obj["type"];
		command.functionName = obj["value"]["functionName"];
		command.id = obj["value"]["id"];
		command.args = JSON.stringify(obj["value"]["args"]);
	};

	var send_command = function(str){
		receive_command(str);
		var obj = {
			"id" : command.id,
			"message" : {
				"type" : command.type,
				"value" : {
					"functionName" : command.functionName,
					"args" : JSON.parse(command.args)
				}
			}
		};
		console.log("receive command to -  id: " + command.id + " ,functionName: " + command.functionName);
		var str = JSON.stringify(obj);
		return str;
	};
	/************************************************************************/
	//子機から送られてきたWebサーバーへの機能の通知
	var functions = {};
	var receive_functions = function(str){
		var obj = JSON.parse(str);
		functions.name = obj["name"];
		functions.id = obj["id"];
		functions.dest = obj["dest"];
		functions.type = obj["type"];
		functions.value = [];
		for(var i=0;i<obj["value"].length;i++){
			functions.value[i] = JSON.stringify(obj["value"][i]);
		}
	};

	var send_functions = function(str){
		receive_functions(str);
		var obj = {
			"type" : "notice",
			"value" : {
				"id" : functions.id,
				"name" : functions.name,
				"functions" : []
			}
		};
		for(var i=0;i<functions.value.length;i++){
			obj["value"]["functions"][i] = JSON.parse(functions.value[i]);
		}
		var str = JSON.stringify(obj);
		return str;
	};
	/************************************************************************/
	//子機から命令の結果
	var result = {};
	var receive_result = function(str){
		var obj = JSON.parse(str);
		result.name = obj["name"];
		result.id = obj["id"];
		result.dest = obj["dest"];
		result.type = obj["type"];
		result.value = obj["value"];
	};

	var send_result = function(str){
		receive_result(str);
		if(result.value.result == undefined || result.value.result == null){
			result.value.result = {};
		}
		var obj = {
			"type" : "result",
			"value" : {
				"id" : result.id,
				"name" : result.name,
				"functionName" : result.value.functionName,
				"hasError": result.value.hasError,
				"error": result.value.error,
				"result" : result.value.result
			}
		};
		var str = JSON.stringify(obj);
		return str;
	};
	/*******************************************************************************/
	//子機からのメッセージ
	var send_message = function(str){
		receive_result(str); //resultと同じやつで使える
		var obj = {
			"type" : "message",
			"value" : {
				"id" : result.id,
				"name" : result.name,
				"functionName" : result.value.functionName,
				"value" : result.value.value
			}
		};
		var str = JSON.stringify(obj);
		return str;
	};
	/*******************************************************************************/
	var system_command = function(str){
		obj = JSON.parse(str);
		if(obj.value.to == "childrenclient"){
			children_sender.write(str);
		}else if(obj.value.to == "webclient"){
			webclient_sender.write(str);
		}
	};
	//サーバー&クライアント
	var th = this;
	var message_finish = true;

	var classify_message = function(obj){
		message_finish = true;
		var str = JSON.stringify(obj);
		switch(obj["type"]){
			case 'system_command':
				system_command(str);
				break;
			//子機から機能の通知
			case 'function':
				var send_json = send_functions(str);
				webclient_sender.write(send_json);
				break;
				//子機からの命令結果
			case 'result':
				var send_json = send_result(str);
				webclient_sender.write(send_json);
				break;
			case 'message':
				var send_json = send_message(str);
				webclient_sender.write(send_json);
				break;
				//Webサーバーからの命令
			case 'call':
				var send_json = send_command(str);
				children_sender.write(send_json);
				break;
			case 'child':
				webclient_sender.write(str);
				break;
			default:
				break;
		}
	};

	var check_message = function(str){
		var string = str.toString();
		if(message_finish){
			try{
				var obj = JSON.parse(string);
				classify_message(obj);
			}catch(ex){
				if(string[0] == "{"){
					join_long_message(string);
				}else{
					console.log("[JSON MESSAGE PARSE ERROR]: " + ex.message);
				}
			}
		}else{
			join_long_message(string);
		}
	};

	var part_of_text = "";
	var join_long_message = function(str){
		var complete_text = "";
		if(message_finish){
			part_of_text = str;
			message_finish = false;
		}else{
			var complete_text = part_of_text + str;
			part_of_text = complete_text;
			if(complete_text.slice(-1) == "}"){
				message_finish = true;
				try{
					obj = JSON.parse(complete_text);
					classify_message(obj);
				}catch(ex){
					console.log(ex);
				}
				complete_text = "";
				part_of_text = "";
			}
		}
	};

	var message_server = new net.Server(function(socket){
		socket.on('data',function(str){
			check_message(str);
		});
	});

	var webclient_server_port = 10000;
	var webclient_sender = new net.Socket();
	webclient_sender.on('error',function(error){});
	webclient_sender.on('close',function(){
		webclient_sender.setTimeout(500,function(){
			webclient_sender.connect(webclient_server_port);
		});
	});

	var children_server_port = 20000;
	var children_sender = new net.Socket();
	children_sender.on('error',function(error){});
	children_sender.on('close',function(error){
		children_sender.setTimeout(500,function(){
			children_sender.connect(children_server_port);
		});
	});

	this.start = function(){
		message_server.listen(12000);
		webclient_sender.connect(webclient_server_port);
		children_sender.connect(children_server_port);
	};
}

module.exports = message_parser;
<commit_msg>add comment for messsage_parser<commit_after>var fs = require('fs');
var ursa = require('ursa');
var dgram = require('dgram');
var tls = require('tls');
var net = require('net');
var mongoose = require('mongoose');
/**
 * インスタンスを初期化します。
 * @constructor
 * @classdec メッセージを整えるためのクラス
 */
var message_parser = function(){

	/************************************************************************/
	//Webサーバーから送られてきた子機への命令
	var command = {};
	/**
	 * commandに子機への命令を保存する
	 * @param  {String} str - Webサーバーから送られてきた子機への命令のJson文字列
	 */
	var receive_command = function(str){
		var obj = JSON.parse(str);
		command.type = obj["type"];
		command.functionName = obj["value"]["functionName"];
		command.id = obj["value"]["id"];
		command.args = JSON.stringify(obj["value"]["args"]);
	};

	/**
	 * Webサーバーからの命令を親機へ送信します。
	 * @param  {String} str - Webサーバーから送られてきた子機への命令のJson文字列
	 * @return {String} str - 子機に送信する命令Jsonの文字列
	 */
	var send_command = function(str){
		receive_command(str);
		var obj = {
			"id" : command.id,
			"message" : {
				"type" : command.type,
				"value" : {
					"functionName" : command.functionName,
					"args" : JSON.parse(command.args)
				}
			}
		};
		console.log("receive command to -  id: " + command.id + " ,functionName: " + command.functionName);
		var str = JSON.stringify(obj);
		return str;
	};
	/************************************************************************/
	//子機から送られてきたWebサーバーへの機能の通知
	var functions = {};

	/**
	 * 子機から送らてきた通知文字列Jsonをfunctionsに保存する
	 * @param  {String} str - 子機から送られてきたWebサーバーへの機能通知Json文字列
	 */
	var receive_functions = function(str){
		var obj = JSON.parse(str);
		functions.name = obj["name"];
		functions.id = obj["id"];
		functions.dest = obj["dest"];
		functions.type = obj["type"];
		functions.value = [];
		for(var i=0;i<obj["value"].length;i++){
			functions.value[i] = JSON.stringify(obj["value"][i]);
		}
	};

	/**
	 * Webサーバーに送信するための子機機能通知Jsonを作成する。
	 * @param  {String} str - 子機から送られてきたWebサーバーへの機能通知Json文字列
	 * @return {String} str - Webサーバーに送信する子機からの機能通知Json文字列
	 */
	var send_functions = function(str){
		receive_functions(str);
		var obj = {
			"type" : "notice",
			"value" : {
				"id" : functions.id,
				"name" : functions.name,
				"functions" : []
			}
		};
		for(var i=0;i<functions.value.length;i++){
			obj["value"]["functions"][i] = JSON.parse(functions.value[i]);
		}
		var str = JSON.stringify(obj);
		return str;
	};

	/************************************************************************/
	//子機から命令の結果

	var result = {};

	/**
	 * 子機から送られてきた命令結果Jsonを一時保存する
	 * @param  {String} str - 子機から送られてきた命令結果Json文字列
	 */
	var receive_result = function(str){
		var obj = JSON.parse(str);
		result.name = obj["name"];
		result.id = obj["id"];
		result.dest = obj["dest"];
		result.type = obj["type"];
		result.value = obj["value"];
	};

	/**
	 * Webサーバーに送る子機からの命令結果Jsonを作成します。
	 * @param  {String} str - 子機から送られてきた命令結果Json文字列
	 * @return {String} str - Webサーバーに送る命令結果Json文字列
	 */
	var send_result = function(str){
		receive_result(str);
		if(result.value.result == undefined || result.value.result == null){
			result.value.result = {};
		}
		var obj = {
			"type" : "result",
			"value" : {
				"id" : result.id,
				"name" : result.name,
				"functionName" : result.value.functionName,
				"hasError": result.value.hasError,
				"error": result.value.error,
				"result" : result.value.result
			}
		};
		var str = JSON.stringify(obj);
		return str;
	};

	/*******************************************************************************/
	//子機からのメッセージ
	/**
	 * 子機から送られてきたtype:messageのJson文字列をWebサーバーへ送信する用に変換する
	 * @param  {String} str - 子機から送られてきたmessageJson文字列
	 * @return {String} str - Webサーバーに送るmessageJsom文字列
	 */
	var send_message = function(str){
		receive_result(str); //resultと同じやつで使える
		var obj = {
			"type" : "message",
			"value" : {
				"id" : result.id,
				"name" : result.name,
				"functionName" : result.value.functionName,
				"value" : result.value.value
			}
		};
		var str = JSON.stringify(obj);
		return str;
	};

	/*******************************************************************************/

	/**
	 * システムコマンドを送信します。
	 * @param  {String} str - システムコマンド文字列
	 */
	var system_command = function(str){
		obj = JSON.parse(str);
		if(obj.value.to == "childrenclient"){
			children_sender.write(str);
		}else if(obj.value.to == "webclient"){
			webclient_sender.write(str);
		}
	};
	//サーバー&クライアント
	var th = this;
	var message_finish = true;

	/**
	 * 送られてきたJsonオブジェクトを分類して処理します。
	 * @param  {Object} Webサーバークライアントまたは子機クライアントから送られてきたJsonオブジェクト
	 */
	var classify_message = function(obj){
		message_finish = true;
		var str = JSON.stringify(obj);
		switch(obj["type"]){
			case 'system_command':
				system_command(str);
				break;
			//子機から機能の通知
			case 'function':
				var send_json = send_functions(str);
				webclient_sender.write(send_json);
				break;
				//子機からの命令結果
			case 'result':
				var send_json = send_result(str);
				webclient_sender.write(send_json);
				break;
			case 'message':
				var send_json = send_message(str);
				webclient_sender.write(send_json);
				break;
				//Webサーバーからの命令
			case 'call':
				var send_json = send_command(str);
				children_sender.write(send_json);
				break;
			case 'child':
				webclient_sender.write(str);
				break;
			default:
				break;
		}
	};

	/**
	 * 送られきた文字列を適切なJsonの形に変換します
	 * @param  {Object} str - 送られてきたメッセージ
	 */
	var check_message = function(str){
		var string = str.toString();
		if(message_finish){
			try{
				var obj = JSON.parse(string);
				classify_message(obj);
			}catch(ex){
				if(string[0] == "{"){
					join_long_message(string);
				}else{
					console.log("[JSON MESSAGE PARSE ERROR]: " + ex.message);
				}
			}
		}else{
			join_long_message(string);
		}
	};

	var part_of_text = "";
	/**
	 * 文字列を適正なjsonの形にします。
	 * @param  {String} str - 繋げたい文字列
	 */
	var join_long_message = function(str){
		var complete_text = "";
		if(message_finish){
			part_of_text = str;
			message_finish = false;
		}else{
			var complete_text = part_of_text + str;
			part_of_text = complete_text;
			if(complete_text.slice(-1) == "}"){
				message_finish = true;
				try{
					obj = JSON.parse(complete_text);
					classify_message(obj);
				}catch(ex){
					console.log(ex);
				}
				complete_text = "";
				part_of_text = "";
			}
		}
	};

	var message_server = new net.Server(function(socket){
		socket.on('data',function(str){
			check_message(str);
		});
	});

	var webclient_server_port = 10000;
	var webclient_sender = new net.Socket();
	webclient_sender.on('error',function(error){});
	webclient_sender.on('close',function(){
		webclient_sender.setTimeout(500,function(){
			webclient_sender.connect(webclient_server_port);
		});
	});

	var children_server_port = 20000;
	var children_sender = new net.Socket();
	children_sender.on('error',function(error){});
	children_sender.on('close',function(error){
		children_sender.setTimeout(500,function(){
			children_sender.connect(children_server_port);
		});
	});

	/**
	 * システムをスタートさせます。
	 */
	this.start = function(){
		message_server.listen(12000);
		webclient_sender.connect(webclient_server_port);
		children_sender.connect(children_server_port);
	};
}

module.exports = message_parser;
<|endoftext|>


<commit_before>var cli = {
    fullscreen: false,
    width: 60,
    height: 35,
    bg_color: '#000000',
    fg_color: '#FFFFFF',
    prompt_color: '#00FF00',
    cursor_color: '#FFFFFF',
    command_buffer: 'help',

    prompt: 'rivalware/home> ',

    init: function(fullscreen) {
	this.fullscreen = fullscreen

	this.screen = document.getElementById('cli');

	if (this.fullscreen) {
	    this.screen.classList.add('full-screen')
	}
	else {
	    this.screen.style.width = '' + this.width + 'em';
	    this.screen.style.height = '' + this.height + 'em';
	}
	this.screen.style['background-color'] = this.bg_color;
	this.screen.style.color = this.fg_color;
	this.screen.style.padding = '1em';
	this.screen.style['font-family'] = 'monospace';

	this.render();
	window.onkeypress = this.handle_key;
    },

    handle_key: function(key) {
	var k = key.keyCode;
	if (key.shiftKey) {
	    key -= 48;
	}
	cli.command_buffer += String.fromCharCode(k);
	cli.render();
    },

    render: function() {
	var self = this;

	while (this.screen.lastChild) {
	    this.screen.removeChild(this.screen.lastChild);
	}

	var input = document.createElement('div');
	input.className = 'input';

	var prompt = document.createElement('span');
	prompt.innerHTML = this.prompt;
	prompt.style.color = this.prompt_color;
	prompt.style['font-weight'] = 'bold';

	var command = document.createElement('span');
	command.innerHTML = this.command_buffer;
	command.style.color = this.fg_color;
	command.style['font-weight'] = 'bold';

	var cursor = document.createElement('span');
	cursor.innerHTML = '&nbsp';
	cursor.style['background-color'] = this.cursor_color;
	cursor.on = true;
	this.cursor = cursor;

	input.appendChild(prompt);
	input.appendChild(command);
	input.appendChild(cursor);

	if (this.cursor_interval) {
	    clearInterval(this.cursor_interval);
	}
	this.cursor_interval = setInterval(function() {
	    if (self.cursor.on) {
		self.cursor.on = false;
		self.cursor.style['background-color'] = self.bg_color;
	    }
	    else {
		self.cursor.on = true;
		self.cursor.style['background-color'] = self.cursor_color;
	    }
	}, 750);

	this.screen.appendChild(input);
    }
};<commit_msg>Added ability to enter multiple spaces<commit_after>var cli = {
    fullscreen: false,
    width: 60,
    height: 35,
    bg_color: '#000000',
    fg_color: '#FFFFFF',
    prompt_color: '#00FF00',
    cursor_color: '#FFFFFF',
    command_buffer: 'help',

    prompt: 'rivalware/home> ',

    init: function(fullscreen) {
	this.fullscreen = fullscreen

	this.screen = document.getElementById('cli');

	if (this.fullscreen) {
	    this.screen.classList.add('full-screen')
	}
	else {
	    this.screen.style.width = '' + this.width + 'em';
	    this.screen.style.height = '' + this.height + 'em';
	}
	this.screen.style['background-color'] = this.bg_color;
	this.screen.style.color = this.fg_color;
	this.screen.style.padding = '1em';
	this.screen.style['font-family'] = 'monospace';

	this.render();
	window.onkeypress = this.handle_key;
    },

    handle_key: function(key) {
	var k = key.keyCode;
	var ch;
	if (k == 32) {
	    ch = ' '
	}
	else if (key.shiftKey) {
	    key -= 48;
	    ch = String.fromCharCode(k);
	}
	else {
	    ch = String.fromCharCode(k);
	}
	cli.command_buffer += ch;
	cli.render();
    },

    render: function() {
	var self = this;

	while (this.screen.lastChild) {
	    this.screen.removeChild(this.screen.lastChild);
	}

	var input = document.createElement('div');
	input.className = 'input';

	var prompt = document.createElement('span');
	prompt.innerHTML = this.prompt;
	prompt.style.color = this.prompt_color;
	prompt.style['font-weight'] = 'bold';

	var command = document.createElement('span');
	command.innerHTML = this.command_buffer;
	command.style.color = this.fg_color;
	command.style['font-weight'] = 'bold';

	var cursor = document.createElement('span');
	cursor.innerHTML = '&nbsp';
	cursor.style['background-color'] = this.cursor_color;
	cursor.on = true;
	this.cursor = cursor;

	input.appendChild(prompt);
	input.appendChild(command);
	input.appendChild(cursor);

	if (this.cursor_interval) {
	    clearInterval(this.cursor_interval);
	}
	this.cursor_interval = setInterval(function() {
	    if (self.cursor.on) {
		self.cursor.on = false;
		self.cursor.style['background-color'] = self.bg_color;
	    }
	    else {
		self.cursor.on = true;
		self.cursor.style['background-color'] = self.cursor_color;
	    }
	}, 750);

	this.screen.appendChild(input);
    }
};
<|endoftext|>


<commit_before>const rp = require('request-promise')

module.exports = function () {
  const { commands, hears, on: reservedCallback } = this.actions

  if (!this.longPollParams) {
    return this.api('messages.getLongPollServer', {
      need_pts: 1,
      lp_version: 2,
      access_token: this.token,
      v: 5.65
    })
      .then((body) => {
        if (!body.response || !body.response.server) {
          throw new Error(JSON.stringify(body))
        }

        this.longPollParams = body.response
        this.listen()
      })
      .catch((err) => {
        this.longPollParams = null
        return this.listen()
      })
  }

  return rp({
    url: `https://${this.longPollParams.server}`,
    qs: {
      ...this.longPollParams,
      act: 'a_check',
      wait: 25,
      mode: 2,
      version: 2
    },
    json: true
  })
    .then((body) => {
      if (body.failed) {
        if (body.failed && body.ts) {
          this.longPollParams.ts = body.ts
        } else {
          this.longPollParams = null
        }

        return this.listen()
      }

      if (body.ts) {
        this.longPollParams.ts = body.ts
      }

      this.listen()

      if (body.updates && body.updates.length) {
        body.updates.forEach((update) => {
          if (update[0] === 4 && (update[2] & 2) === 0) {
            const ctx = {
              user_id: update[3],
              body: update[5],
              attachments: update[6],
              date: update[4],
              message_id: update[1],
            }

            if (update[6].from) {
              ctx.from = +update[6].from
            }

            const getForward = (ctx) => {
              return new Promise((resolve) => {
                if (!ctx.attachments || !ctx.attachments.fwd) {
                  resolve(null)
                }

                this.execute('messages.getById', {
                  message_ids: ctx.message_id,
                  v: 5.67
                }, this.token, (data) => {
                  resolve(this.getLastMessage(data.items[0]))
                })
              })
            }

            getForward(ctx)
              .then((forward) => {
                if (forward) {
                  ctx.forward = forward
                  ctx.body = forward.body
                }

                const attachmentsKeys = Object.keys(ctx.attachments).filter(key => key.search('attach') > -1 && key.search('type') === -1 && key.search('kind') === -1)
                const attachments = []

                attachmentsKeys.forEach((key) => {
                  const file = {}

                  file['type'] = ctx.attachments[`${key}_type`]
                  file[file.type] = ctx.attachments[key]

                  attachments.push(file)
                })

                ctx.attachments = attachments
                ctx.body = ctx.body.replace(/
/g, '\n')

                ctx.reply = (message, attachment) => this.reply(ctx.user_id, message, attachment)
                ctx.sendMessage = (userId, message, attachment) => this.reply(ctx.user_id, message, attachment)

                const message = ctx.body.toLowerCase()
                const commandKey = Object.keys(commands).filter(item => item.indexOf(message) > -1)[0]
                const commandCallback = commands[commandKey]
                const hearsKey = Object.keys(hears).filter((item) => {
                  const index = item.split(';')
                    .filter((item) => {
                      if (/\/[\S]{1,}\/[a-z]{1,2}/.test(item)) {
                        const string = item.substr(1).replace(/\/[a-z]{1,2}/i, '')
                        const type = item.substr(1).match(/\/[a-z]{1,2}/i)[0].substr(1)

                        return new RegExp(string, type).test(message)
                      } else {
                        return new RegExp(item, 'i').test(message)
                      }
                    })
                  return index.length
                })[0]
                const hearsCallback = hears[hearsKey]

                if (commandCallback !== undefined) {
                  return commandCallback(ctx)
                } else if (hearsCallback !== undefined) {
                  return hearsCallback(ctx)
                } else if (reservedCallback !== undefined) {
                  return reservedCallback(ctx)
                }
              })
              .catch((err) => {
                this.longPollParams = null
                return this.listen()
              })
          }
        })
      }
    })
    .catch((err) => {
      this.longPollParams = null
      return this.listen()
    })
}
<commit_msg>Bugfix (#5)<commit_after>const rp = require('request-promise')

module.exports = function () {
  const { commands, hears, on: reservedCallback } = this.actions

  if (!this.longPollParams) {
    return this.api('messages.getLongPollServer', {
      need_pts: 1,
      lp_version: 2,
      access_token: this.token,
      v: 5.65
    })
      .then((body) => {
        if (!body.response || !body.response.server) {
          throw new Error(JSON.stringify(body))
        }

        this.longPollParams = body.response
        this.listen()
      })
      .catch((err) => {
        this.longPollParams = null
        return this.listen()
      })
  }

  return rp({
    url: `https://${this.longPollParams.server}`,
    qs: {
      ...this.longPollParams,
      act: 'a_check',
      wait: 25,
      mode: 2,
      version: 2
    },
    json: true
  })
    .then((body) => {
      if (body.failed) {
        if (body.failed && body.ts) {
          this.longPollParams.ts = body.ts
        } else {
          this.longPollParams = null
        }

        return this.listen()
      }

      if (body.ts) {
        this.longPollParams.ts = body.ts
      }

      this.listen()

      if (body.updates && body.updates.length) {
        body.updates.forEach((update) => {
          if (update[0] === 4 && (update[2] & 2) === 0) {
            const ctx = {
              user_id: update[3],
              body: update[5],
              attachments: update[6],
              date: update[4],
              message_id: update[1],
            }

            if (update[6].from) {
              ctx.from = +update[6].from
            }

            const getForward = (ctx) => {
              return new Promise((resolve) => {
                if (!ctx.attachments || !ctx.attachments.fwd) {
                  resolve(null)
                }

                this.execute('messages.getById', {
                  message_ids: ctx.message_id,
                  v: 5.67
                }, this.token, (data) => {
                  resolve(this.getLastMessage(data.items[0]))
                })
              })
            }

            getForward(ctx)
              .then((forward) => {
                if (forward) {
                  ctx.forward = forward
                  ctx.body = forward.body
                }

                const attachmentsKeys = Object.keys(ctx.attachments).filter(key => key.search('attach') > -1 && key.search('type') === -1 && key.search('kind') === -1)
                const attachments = []

                attachmentsKeys.forEach((key) => {
                  const file = {}

                  file['type'] = ctx.attachments[`${key}_type`]
                  file[file.type] = ctx.attachments[key]

                  attachments.push(file)
                })

                ctx.attachments = attachments
                ctx.body = ctx.body.replace(/
/g, '\n')

                ctx.reply = (message, attachment) => this.reply(ctx.user_id, message, attachment)
                ctx.sendMessage = (userId, message, attachment) => this.reply(userId, message, attachment)

                const message = ctx.body.toLowerCase()
                const commandKey = Object.keys(commands).filter(item => item.indexOf(message) > -1)[0]
                const commandCallback = commands[commandKey]
                const hearsKey = Object.keys(hears).filter((item) => {
                  const index = item.split(';')
                    .filter((item) => {
                      if (/\/[\S]{1,}\/[a-z]{1,2}/.test(item)) {
                        const string = item.substr(1).replace(/\/[a-z]{1,2}/i, '')
                        const type = item.substr(1).match(/\/[a-z]{1,2}/i)[0].substr(1)

                        return new RegExp(string, type).test(message)
                      } else {
                        return new RegExp(item, 'i').test(message)
                      }
                    })
                  return index.length
                })[0]
                const hearsCallback = hears[hearsKey]

                if (commandCallback !== undefined) {
                  return commandCallback(ctx)
                } else if (hearsCallback !== undefined) {
                  return hearsCallback(ctx)
                } else if (reservedCallback !== undefined) {
                  return reservedCallback(ctx)
                }
              })
              .catch((err) => {
                this.longPollParams = null
                return this.listen()
              })
          }
        })
      }
    })
    .catch((err) => {
      this.longPollParams = null
      return this.listen()
    })
}
<|endoftext|>


<commit_before>/**
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const AutoWebPerf = require('./awp-core');
const argv = require('minimist')(process.argv.slice(2));

function printUsage() {
  let usage = `
Usage: ./awp [ACTION] [OPTIONS...]

Available Actions:
  run\t\tExecute audits from the test list.
  recurringActivate\tUpdate test frequency and timestamps.
  recurring\t\tExecute recurring audits from the test list.
  retrieve\tRetrieve test results from the results list.

Options (*denotes default value if not passed in):
  tests\t\tThe JSON file with the URL list for audit.
  results\t\tThe output JSON file for writing test results.
  dataSources\t\ttComma-separated list of data sources. Default: webpagetest.
  extensions\t\tComma-separated list of extensions.
  selectedOnly\t\tOnly execute with tests or results with selected=true.
  verbose\t\tPrint out verbose logs.
  debug\t\tPrint out debug console logs.

Examples:
  # List CLI options
  ./awp --help

  # Run tests
  ./awp run --tests=examples/tests.json --results=output/results.json

  # Run recurring tests
  ./awp recurring --tests=examples/tests.json --results=output/results.json

  # Activate recurring tests without running actual tests.
  ./awp recurringActivate --tests=examples/tests.json --results=output/results.json

  # Retrieve pending results
  ./awp retrieve --tests=examples/tests.json --results=output/results.json
  `;
  console.log(usage);
}

/**
 * Main CLI function.
 */
async function begin() {
  let action = argv['_'][0], output = argv['output'];
  let dataSources = argv['dataSources'] ? argv['dataSources'].split(',') : null;
  let extensions = argv['extensions'] ? argv['extensions'].split(',') : [];
  let runByBatch = argv['runByBatch'] ?  true : false;
  let debug = argv['debug'];
  let verbose = argv['verbose'];

  let filters = [];
  if (argv['selectedOnly']) filters.push('selected');

  if (!action) {
    printUsage();
    return;
  }

  let awp = new AutoWebPerf({
    connector: 'JSON',
    helper: 'Node',
    dataSources: dataSources || ['webpagetest', 'psi', 'chromeuxreport'],
    extensions: extensions,
    json: { // Config for JSON connector.
      testsJsonPath: argv['tests'],
      resultsJsonPath: argv['results'],
    },
    verbose: verbose,
    debug: debug,
  });

  let options = {
    filters: filters,
    runByBatch: runByBatch,
    debug: debug,
  };

  switch(action) {
    case 'run':
      await awp.run(options);
      break;

    case 'recurringActivate':
      options.activateOnly = true;
      await awp.recurring(options);
      break;

    case 'recurring':
      await awp.recurring(options);
      break;

    case 'retrieve':
      await awp.retrieve(options);
      break;

    default:
      printUsage();
      break;
  }
}

module.exports = {
  begin,
};
<commit_msg>crux Run example<commit_after>/**
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const AutoWebPerf = require('./awp-core');
const argv = require('minimist')(process.argv.slice(2));

function printUsage() {
  let usage = `
Usage: ./awp [ACTION] [OPTIONS...]

Available Actions:
  run\t\tExecute audits from the test list.
  recurringActivate\tUpdate test frequency and timestamps.
  recurring\t\tExecute recurring audits from the test list.
  retrieve\tRetrieve test results from the results list.

Options (*denotes default value if not passed in):
  tests\t\tThe JSON file with the URL list for audit.
  results\t\tThe output JSON file for writing test results.
  dataSources\t\ttComma-separated list of data sources. Default: webpagetest.
  extensions\t\tComma-separated list of extensions.
  selectedOnly\t\tOnly execute with tests or results with selected=true.
  verbose\t\tPrint out verbose logs.
  debug\t\tPrint out debug console logs.

Examples:
  # List CLI options
  ./awp --help

  # Run tests
  ./awp run --tests=examples/tests.json --results=output/results.json

  # Run recurring tests
  ./awp recurring --tests=examples/tests.json --results=output/results.json

  # Activate recurring tests without running actual tests.
  ./awp recurringActivate --tests=examples/tests.json --results=output/results.json

  # Retrieve pending results
  ./awp retrieve --tests=examples/tests.json --results=output/results.json

  # CrUX Test runByBatch
  ./awp run --tests=examples/tests-crux.json --results=output/results.json --runByBatch
  `;
  console.log(usage);
}

/**
 * Main CLI function.
 */
async function begin() {
  let action = argv['_'][0], output = argv['output'];
  let dataSources = argv['dataSources'] ? argv['dataSources'].split(',') : null;
  let extensions = argv['extensions'] ? argv['extensions'].split(',') : [];
  let runByBatch = argv['runByBatch'] ?  true : false;
  let debug = argv['debug'];
  let verbose = argv['verbose'];

  let filters = [];
  if (argv['selectedOnly']) filters.push('selected');

  if (!action) {
    printUsage();
    return;
  }

  let awp = new AutoWebPerf({
    connector: 'JSON',
    helper: 'Node',
    dataSources: dataSources || ['webpagetest', 'psi', 'chromeuxreport'],
    extensions: extensions,
    json: { // Config for JSON connector.
      testsJsonPath: argv['tests'],
      resultsJsonPath: argv['results'],
    },
    verbose: verbose,
    debug: debug,
  });

  let options = {
    filters: filters,
    runByBatch: runByBatch,
    debug: debug,
  };

  switch(action) {
    case 'run':
      await awp.run(options);
      break;

    case 'recurringActivate':
      options.activateOnly = true;
      await awp.recurring(options);
      break;

    case 'recurring':
      await awp.recurring(options);
      break;

    case 'retrieve':
      await awp.retrieve(options);
      break;

    default:
      printUsage();
      break;
  }
}

module.exports = {
  begin,
};
<|endoftext|>


<commit_before>// @flow

import type {Command} from 'cli-engine-command'
import {color} from 'cli-engine-command/lib/color'
import {buildConfig, type Config, type ConfigOptions} from 'cli-engine-config'
import {default as cli} from 'cli-ux'
import path from 'path'
import type {Hooks, PreRunOptions} from './hooks'
import semver from 'semver'

const debug = require('debug')('cli')
const handleEPIPE = err => { if (err.code !== 'EPIPE') throw err }

if (!global.testing) {
  process.once('SIGINT', () => {
    if (cli.action.task) cli.action.stop(color.red('ctrl-c'))
    cli.exit(1)
  })
  let handleErr = err => {
    cli.error(err)
  }
  process.once('uncaughtException', handleErr)
  process.once('unhandledRejection', handleErr)
  process.stdout.on('error', handleEPIPE)
  process.stderr.on('error', handleEPIPE)
}

process.env.CLI_ENGINE_VERSION = require('../package.json').version

export default class CLI {
  config: Config
  cmd: Command<*>
  hooks: Hooks

  constructor ({config}: {|config?: ConfigOptions|} = {}) {
    if (!config) config = {}
    if (!config.initPath) {
      config.initPath = module.parent.filename
    }
    if (!config.root) {
      const findUp = require('find-up')
      config.root = path.dirname(findUp.sync('package.json', {
        cwd: module.parent.filename
      }))
    }
    this.config = buildConfig(config)
    global.config = this.config
    global['cli-ux'] = {
      debug: this.config.debug,
      mock: this.config.mock
    }
  }

  async run () {
    debug('starting run')

    require('./fs')
    const {Updater} = require('./updater')
    const updater = new Updater(this.config)
    debug('checking autoupdater')
    await updater.autoupdate()

    const {Hooks} = require('./hooks')
    this.hooks = new Hooks({config: this.config})
    await this.hooks.run('init')

    if (this.cmdAskingForHelp) {
      debug('running help command')
      this.cmd = await this.Help.run(this.config)
    } else {
      debug('dispatcher')
      const id = this.config.argv[1]
      const {Dispatcher} = require('./dispatcher')
      const dispatcher = new Dispatcher(this.config)
      let Command = await dispatcher.findCommand(id || this.config.defaultCommand || 'help')

      if (Command) {
        let {default: Lock} = require('./lock')
        let lock = new Lock(this.config)
        await lock.unread()
        let opts: PreRunOptions = {
          Command: (Command: any),
          argv: this.config.argv.slice(2)
        }
        await this.hooks.run('prerun', opts)
        if (!Command._version) {
          // old style command
          // flow$ignore
          debug('running old style command')
          this.cmd = await Command.run({
            argv: this.config.argv.slice(2),
            config: this.config,
            mock: this.config.mock
          })
        } else {
          if (semver.satisfies((Command._version: any), '>=10.0.0-ts')) {
            debug('running ts command', {_version: Command._version})
            this.config.argv.shift()
            this.cmd = await Command.run(this.config)
          } else {
            debug('running flow command', {_version: Command._version})
            this.cmd = await Command.run(this.config)
          }
        }
      } else {
        let topic = await dispatcher.findTopic(id)
        if (topic) {
          await this.Help.run(this.config)
        } else {
          const {NotFound} = require('./not_found')
          return new NotFound(this.config, this.config.argv).run()
        }
      }
    }

    debug('flushing stdout')
    const {timeout} = require('./util')
    await timeout(this.flush(), 10000)
    debug('exiting')
    cli.exit(0)
  }

  flush (): Promise<void> {
    if (global.testing) return Promise.resolve()
    let p = new Promise(resolve => process.stdout.once('drain', resolve))
    process.stdout.write('')
    return p
  }

  get cmdAskingForHelp (): boolean {
    for (let arg of this.config.argv) {
      if (['--help', '-h'].includes(arg)) return true
      if (arg === '--') return false
    }
    return false
  }

  get Help () {
    const {default: Help} = this.config.userPlugins ? require('./commands/help') : require('./commands/newhelp')
    return Help
  }
}

export function run ({config}: {config?: ConfigOptions} = {}) {
  if (!config) config = {}
  const cli = new CLI({config})
  return cli.run()
}
<commit_msg>better arg slicing<commit_after>// @flow

import type {Command} from 'cli-engine-command'
import {color} from 'cli-engine-command/lib/color'
import {buildConfig, type Config, type ConfigOptions} from 'cli-engine-config'
import {default as cli} from 'cli-ux'
import path from 'path'
import type {Hooks, PreRunOptions} from './hooks'
import semver from 'semver'

const debug = require('debug')('cli')
const handleEPIPE = err => { if (err.code !== 'EPIPE') throw err }

if (!global.testing) {
  process.once('SIGINT', () => {
    if (cli.action.task) cli.action.stop(color.red('ctrl-c'))
    cli.exit(1)
  })
  let handleErr = err => {
    cli.error(err)
  }
  process.once('uncaughtException', handleErr)
  process.once('unhandledRejection', handleErr)
  process.stdout.on('error', handleEPIPE)
  process.stderr.on('error', handleEPIPE)
}

process.env.CLI_ENGINE_VERSION = require('../package.json').version

export default class CLI {
  config: Config
  cmd: Command<*>
  hooks: Hooks

  constructor ({config}: {|config?: ConfigOptions|} = {}) {
    if (!config) config = {}
    if (!config.initPath) {
      config.initPath = module.parent.filename
    }
    if (!config.root) {
      const findUp = require('find-up')
      config.root = path.dirname(findUp.sync('package.json', {
        cwd: module.parent.filename
      }))
    }
    this.config = buildConfig(config)
    global.config = this.config
    global['cli-ux'] = {
      debug: this.config.debug,
      mock: this.config.mock
    }
  }

  async run () {
    debug('starting run')

    require('./fs')
    const {Updater} = require('./updater')
    const updater = new Updater(this.config)
    debug('checking autoupdater')
    await updater.autoupdate()

    const {Hooks} = require('./hooks')
    this.hooks = new Hooks({config: this.config})
    await this.hooks.run('init')

    if (this.cmdAskingForHelp) {
      debug('running help command')
      this.cmd = await this.Help.run(this.config)
    } else {
      debug('dispatcher')
      const id = this.config.argv[1]
      const {Dispatcher} = require('./dispatcher')
      const dispatcher = new Dispatcher(this.config)
      let Command = await dispatcher.findCommand(id || this.config.defaultCommand || 'help')

      if (Command) {
        let {default: Lock} = require('./lock')
        let lock = new Lock(this.config)
        await lock.unread()
        let opts: PreRunOptions = {
          Command: (Command: any),
          argv: this.config.argv.slice(2)
        }
        await this.hooks.run('prerun', opts)
        if (!Command._version) {
          // old style command
          // flow$ignore
          debug('running old style command')
          this.cmd = await Command.run({
            argv: this.config.argv.slice(2),
            config: this.config,
            mock: this.config.mock
          })
        } else {
          if (semver.satisfies((Command._version: any), '>=10.0.0-ts')) {
            debug('running ts command', {_version: Command._version})
            this.cmd = await Command.run({...this.config, argv: this.config.argv.slice(1)})
          } else {
            debug('running flow command', {_version: Command._version})
            this.cmd = await Command.run(this.config)
          }
        }
      } else {
        let topic = await dispatcher.findTopic(id)
        if (topic) {
          await this.Help.run(this.config)
        } else {
          const {NotFound} = require('./not_found')
          return new NotFound(this.config, this.config.argv).run()
        }
      }
    }

    debug('flushing stdout')
    const {timeout} = require('./util')
    await timeout(this.flush(), 10000)
    debug('exiting')
    cli.exit(0)
  }

  flush (): Promise<void> {
    if (global.testing) return Promise.resolve()
    let p = new Promise(resolve => process.stdout.once('drain', resolve))
    process.stdout.write('')
    return p
  }

  get cmdAskingForHelp (): boolean {
    for (let arg of this.config.argv) {
      if (['--help', '-h'].includes(arg)) return true
      if (arg === '--') return false
    }
    return false
  }

  get Help () {
    const {default: Help} = this.config.userPlugins ? require('./commands/help') : require('./commands/newhelp')
    return Help
  }
}

export function run ({config}: {config?: ConfigOptions} = {}) {
  if (!config) config = {}
  const cli = new CLI({config})
  return cli.run()
}
<|endoftext|>


<commit_before>'use babel'
/* global atom */
import fs from 'fs-plus'
import isArray from 'lodash/isArray'
import each from 'lodash/each'

export default function(relativePath, destinationPath) {
  if (relativePath.split('../').length > 2) {
    try {
      const projectPath = atom.project.getPaths()[0]
      const content = fs.readFileSync(`${projectPath}/.babelrc`).toString()
      const config = JSON.parse(content)
      if (!config || !config.plugins || !isArray(config.plugins)) {
        return relativePath
      }
      const pluginConfig =
        config.plugins.find(p => p[0] === 'module-alias' || p[0] === 'babel-plugin-module-alias') ||
        config.plugins.find(
          p => p[0] === 'module-resolver' || p[0] === 'babel-plugin-module-resolver'
        )
      if (!pluginConfig[1].alias) {
        return relativePath
      }

      let aliasPath = ''
      each(pluginConfig[1].alias, function(src, alias) {
        if (src[0] === '.') {
          src = src.substring(1, src.length)
        }
        let dest = destinationPath.split(src)[1]
        if (dest[0] === '/') {
          dest = dest.substring(1, dest.length)
        }
        if (destinationPath.split(alias).length > 1) {
          aliasPath = `${alias}/${dest}`
        }
      })
      console.log('return 3')
      return aliasPath || relativePath
    } catch (error) {
      console.log('Error:', error)
      return relativePath
    }
  }
  return relativePath
}
<commit_msg>no more ../<commit_after>'use babel'
/* global atom */
import fs from 'fs-plus'
import isArray from 'lodash/isArray'
import each from 'lodash/each'

export default function(relativePath, destinationPath) {
  if (relativePath.includes('../')) {
    try {
      const projectPath = atom.project.getPaths()[0]
      const content = fs.readFileSync(`${projectPath}/.babelrc`).toString()
      const config = JSON.parse(content)
      if (!config || !config.plugins || !isArray(config.plugins)) {
        return relativePath
      }
      const pluginConfig =
        config.plugins.find(p => p[0] === 'module-alias' || p[0] === 'babel-plugin-module-alias') ||
        config.plugins.find(
          p => p[0] === 'module-resolver' || p[0] === 'babel-plugin-module-resolver'
        )
      if (!pluginConfig[1].alias) {
        return relativePath
      }

      let aliasPath = ''
      each(pluginConfig[1].alias, function(src, alias) {
        if (src[0] === '.') {
          src = src.substring(1, src.length)
        }
        let dest = destinationPath.split(src)[1]
        if (dest[0] === '/') {
          dest = dest.substring(1, dest.length)
        }
        if (destinationPath.split(alias).length > 1) {
          aliasPath = `${alias}/${dest}`
        }
      })
      console.log('return 3')
      return aliasPath || relativePath
    } catch (error) {
      console.log('Error:', error)
      return relativePath
    }
  }
  return relativePath
}
<|endoftext|>


<commit_before>"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.listCategories = exports.toSlack = exports.getRandomPost = exports.loadNews = undefined;

var _feedparserPromised = require('feedparser-promised');

var _feedparserPromised2 = _interopRequireDefault(_feedparserPromised);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _striptags = require('striptags');

var _striptags2 = _interopRequireDefault(_striptags);

var _helptos = require('helptos');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * get rss url form array of categories by category name
 *
 * @param categories
 * @param category
 * @returns {*}
 */
var getRssUrl = function getRssUrl(categories, category) {

    var el = (0, _helptos.getFirstByName)(categories, category),
        output = false;

    if (el && el.url) {
        output = el.url;
    }

    return output;
};

var configFile = '../config/news.json';
var categories = (0, _helptos.getConfig)(configFile, __dirname).categories.filter(function (category) {
    return (0, _helptos.hasAllPropsSet)(['name', 'url'])(category);
});
_moment2.default.locale('de');

/**
 *
 *
 * @param category
 * @param callback
 * @returns {Promise}
 */
var loadNews = exports.loadNews = function loadNews() {
    var category = arguments.length <= 0 || arguments[0] === undefined ? 'alles' : arguments[0];
    var callback = arguments[1];

    return new Promise(function (resolve, reject) {

        var rssURL = getRssUrl(categories, category);

        if (!rssURL) {
            reject('Category "' + category + '" not found.\nAvailable categories:\n' + getNameList(categories));
        }

        _feedparserPromised2.default.parse(rssURL).then(function (items) {

            resolve(items.map(function (item) {
                return {
                    date: (0, _moment2.default)(item.pubDate).fromNow(),
                    title: item.title,
                    url: item.link,
                    description: (0, _striptags2.default)(item.description).replace(/(\r\n|\n|\r)/gm, "")
                };
            }));
        }).catch(function (error) {
            reject('error: ' + error);
        });
    });
};

/**
 * get a random post
 *
 * @param items
 */
var getRandomPost = exports.getRandomPost = function getRandomPost(items) {
    return (0, _helptos.getRandomEntry)(items);
};

/**
 * converts news item to a slack message
 *
 * @param item
 * @returns {Promise}
 */
var toSlack = exports.toSlack = function toSlack(item) {

    return new Promise(function (resolve, reject) {

        (0, _helptos.shortenUrl)(item.url).then(function (url) {
            return resolve('>>>_' + item.date + '_:\n*' + item.title + '*\n\n' + item.description + '\n\n<' + url + '>');
        }).catch(function () {
            return resolve('>>>_' + item.date + '_:\n*' + item.title + '*\n\n' + item.description + '\n\n<' + item.url + '>');
        });
    });
};

/**
 * creates a list of all available categories
 *
 * @returns {string}
 */
var listCategories = exports.listCategories = function listCategories() {
    return 'Available categories:\n' + getNameList(categories);
};<commit_msg>recompiled<commit_after>"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.listCategories = exports.toSlack = exports.getRandomPost = exports.loadNews = undefined;

var _feedparserPromised = require('feedparser-promised');

var _feedparserPromised2 = _interopRequireDefault(_feedparserPromised);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _striptags = require('striptags');

var _striptags2 = _interopRequireDefault(_striptags);

var _helptos = require('helptos');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * get rss url form array of categories by category name
 *
 * @param categories
 * @param category
 * @returns {*}
 */
var getRssUrl = function getRssUrl(categories, category) {

    var el = (0, _helptos.getFirstByName)(categories, category),
        output = false;

    if (el && el.url) {
        output = el.url;
    }

    return output;
};

var configFile = '../config/news.json';
var categories = (0, _helptos.getConfig)(configFile, __dirname).categories.filter(function (category) {
    return (0, _helptos.hasAllPropsSet)(['name', 'url'])(category);
});
_moment2.default.locale('de');

/**
 *
 *
 * @param category
 * @param callback
 * @returns {Promise}
 */
var loadNews = exports.loadNews = function loadNews() {
    var category = arguments.length <= 0 || arguments[0] === undefined ? 'alles' : arguments[0];
    var callback = arguments[1];

    return new Promise(function (resolve, reject) {

        var rssURL = getRssUrl(categories, category);

        if (!rssURL) {
            reject('Category "' + category + '" not found.\nAvailable categories:\n' + (0, _helptos.getNameList)(categories));
        }

        _feedparserPromised2.default.parse(rssURL).then(function (items) {

            resolve(items.map(function (item) {
                return {
                    date: (0, _moment2.default)(item.pubDate).fromNow(),
                    title: item.title,
                    url: item.link,
                    description: (0, _striptags2.default)(item.description).replace(/(\r\n|\n|\r)/gm, "")
                };
            }));
        }).catch(function (error) {
            reject('error: ' + error);
        });
    });
};

/**
 * get a random post
 *
 * @param items
 */
var getRandomPost = exports.getRandomPost = function getRandomPost(items) {
    return (0, _helptos.getRandomEntry)(items);
};

/**
 * converts news item to a slack message
 *
 * @param item
 * @returns {Promise}
 */
var toSlack = exports.toSlack = function toSlack(item) {

    return new Promise(function (resolve, reject) {

        (0, _helptos.shortenUrl)(item.url).then(function (url) {
            return resolve('>>>_' + item.date + '_:\n*' + item.title + '*\n\n' + item.description + '\n\n<' + url + '>');
        }).catch(function () {
            return resolve('>>>_' + item.date + '_:\n*' + item.title + '*\n\n' + item.description + '\n\n<' + item.url + '>');
        });
    });
};

/**
 * creates a list of all available categories
 *
 * @returns {string}
 */
var listCategories = exports.listCategories = function listCategories() {
    return 'Available categories:\n' + (0, _helptos.getNameList)(categories);
};<|endoftext|>


<commit_before>var _ = require('lodash');
var kramed = require('kramed');

// Get all the pairs of header + paragraph in a list of nodes
function groups(nodes) {
    // A list of next nodes
    var next = nodes.slice(1).concat(null);

    return _.reduce(nodes, function(accu, node, idx) {
        // Skip
        if(!(
            node.type === 'heading' &&
            (next[idx] && next[idx].type === 'paragraph')
        )) {
            return accu;
        }

        // Add group
        accu.push([
            node,
            next[idx]
        ]);

        return accu;
    }, []);
}

function parseGlossary(src) {
    var nodes = kramed.lexer(src);

    return groups(nodes)
    .map(function(pair) {
        // Simplify each group to a simple object with name/description
        return {
            name: pair[0].text,
            id: entryId(pair[0].text),
            description: pair[1].text,
        };
    });
}

// Normalizes a glossary entry's name to create an ID
function entryId(name) {
    return name.toLowercase();
}

module.exports = parseGlossary;
<commit_msg>Fix dump typo in glossary's entryId func<commit_after>var _ = require('lodash');
var kramed = require('kramed');

// Get all the pairs of header + paragraph in a list of nodes
function groups(nodes) {
    // A list of next nodes
    var next = nodes.slice(1).concat(null);

    return _.reduce(nodes, function(accu, node, idx) {
        // Skip
        if(!(
            node.type === 'heading' &&
            (next[idx] && next[idx].type === 'paragraph')
        )) {
            return accu;
        }

        // Add group
        accu.push([
            node,
            next[idx]
        ]);

        return accu;
    }, []);
}

function parseGlossary(src) {
    var nodes = kramed.lexer(src);

    return groups(nodes)
    .map(function(pair) {
        // Simplify each group to a simple object with name/description
        return {
            name: pair[0].text,
            id: entryId(pair[0].text),
            description: pair[1].text,
        };
    });
}

// Normalizes a glossary entry's name to create an ID
function entryId(name) {
    return name.toLowerCase();
}

module.exports = parseGlossary;
<|endoftext|>